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(crons): report the rows that actually landed instead of the rows that were attempted

nirholas106456815f2b
diff --git a/api/cron/db-retention.js b/api/cron/db-retention.js
index c4713f3c4..aa5e20133 100644
--- a/api/cron/db-retention.js
+++ b/api/cron/db-retention.js
@@ -61,8 +61,7 @@
// runtime and hardcodes no specific mint — generic retention plumbing, not an
// endorsement of any coin.
-import { error, json, method, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { sql, isDbCapacityError } from '../_lib/db.js';
import { sendOpsAlert } from '../_lib/alerts.js';
import { requireCron } from '../_lib/cron-auth.js';
@@ -125,6 +124,20 @@ const COMPACT_MAX_TABLES = 3; // per tick; the cron re-runs on its schedule
// pressure valve, because shortening it is exactly what re-opens the replay
// hole the table exists to close. The rows are tiny (a hash, a route, an
// amount), so it cannot be the reason the branch is under pressure.
+//
+// DELIBERATELY UNMANAGED, and the single biggest table this cron does NOT prune:
+// x402_self_facilitator_log (632 MB as of 2026-08-10, third largest in the
+// branch). Every other big grower above is churn; this one is the settle book.
+// It is excluded because /api/x402-ring aggregates it with NO time filter for
+// its `lifetime` period (api/x402-ring.js, sinceFor() returns null), so any
+// retention window silently shrinks published lifetime settlement and fee
+// totals. Every other reader is short-window (healthz 24h, fee-audit and
+// wallet-fee-meter current-day, ring-reconciliation LOOKBACK_HOURS,
+// sponsor-runway X402_SPONSOR_BURN_WINDOW_DAYS), so a window is technically
+// safe for them. Pruning it is therefore a product decision about the public
+// revenue figures, not a mechanical retention one: get owner sign-off on what
+// `lifetime` should mean (and roll the pruned totals into a summary row first)
+// before adding it here.
const TIME_SERIES_TABLES = [
{ table: 'pump_launch_snapshots', tsColumn: 'ts', windowKind: 'firehose' },
{ table: 'x402_autonomous_log', tsColumn: 'ts', windowKind: 'audit' },
diff --git a/api/cron/forge-off-crown.js b/api/cron/forge-off-crown.js
index 76f35939a..72c4aa843 100644
--- a/api/cron/forge-off-crown.js
+++ b/api/cron/forge-off-crown.js
@@ -24,19 +24,30 @@
//
// Runs Monday 00:07 UTC (just after the week rolls over). Auth: CRON_SECRET.
-import { json, method, wrapCron } from '../_lib/http.js';
+import { error, json, method, wrapCron } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { forgeOffWeekStart, forgeStoreEnabled } from '../_lib/forge-store.js';
import { requireCron } from '../_lib/cron-auth.js';
// The Monday that starts the week we are crowning. Default: the week that just
// completed (the previous Monday relative to now). `weekParam` (YYYY-MM-DD)
-// overrides for backfills — it is snapped to its own week's Monday so a mid-week
+// overrides for backfills: it is snapped to its own week's Monday so a mid-week
// date still resolves to a valid week boundary.
-function resolveWeekStart(weekParam) {
+//
+// An unparseable `weekParam` returns null rather than falling back to the
+// default week. A crowning is permanent (ON CONFLICT DO NOTHING below), so an
+// owner backfilling `?week=2026-13-99` used to silently and irreversibly crown
+// the CURRENT default week instead of erroring: a typo with no undo. The caller
+// turns null into a 400.
+export function resolveWeekStart(weekParam) {
if (weekParam) {
+ // Strict YYYY-MM-DD. Date.parse alone is not a validator here: V8 falls back
+ // to a lenient parser that happily reads `2026-07T00:00:00Z` as 1 July, so a
+ // truncated backfill date would resolve to a real (wrong) week rather than
+ // erroring, which is the same silent-misread this guard exists to stop.
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(weekParam)) return null;
const t = Date.parse(`${weekParam}T00:00:00Z`);
- if (Number.isFinite(t)) return forgeOffWeekStart(new Date(t));
+ return Number.isFinite(t) ? forgeOffWeekStart(new Date(t)) : null;
}
const thisWeek = forgeOffWeekStart();
const prev = new Date(thisWeek);
@@ -59,7 +70,11 @@ export default wrapCron(async (req, res) => {
const url = new URL(req.url || '/', 'https://three.ws');
const dryRun = url.searchParams.get('dry_run') === '1';
- const weekStart = resolveWeekStart(url.searchParams.get('week'));
+ const weekParam = url.searchParams.get('week');
+ const weekStart = resolveWeekStart(weekParam);
+ if (!weekStart) {
+ return error(res, 400, 'invalid_week', `week must be a YYYY-MM-DD date; got "${String(weekParam).slice(0, 40)}"`);
+ }
const weekKey = toDateKey(weekStart);
const weekEnd = new Date(weekStart);
weekEnd.setUTCDate(weekEnd.getUTCDate() + 7);
diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.js
index 231138db4..7ed7480ac 100644
--- a/api/cron/forge-seed-cron.js
+++ b/api/cron/forge-seed-cron.js
@@ -411,7 +411,12 @@ async function advanceGates(origin) {
}
const avatarId = await publishSeedAvatar({ job, verdict, rigged: false });
- results.push({ job_id: job.id, status: 'published', avatar_id: avatarId, prompt: job.prompt });
+ results.push({
+ job_id: job.id,
+ status: avatarId ? 'published' : 'already_published',
+ avatar_id: avatarId,
+ prompt: job.prompt,
+ });
} catch (err) {
// The gate itself broke (storage read, renderer, judge transport). That is
@@ -432,7 +437,26 @@ async function advanceGates(origin) {
// Publish a gated keeper and close the job out. Shared by the direct path and
// the post-rig path so the avatar row is written in exactly one place.
+//
+// The close-out is a compare-and-set, and it runs BEFORE the avatar insert: the
+// gate and rig phases select their rows by status with no lock, so two ticks
+// overlapping (a Cloud Scheduler retry, a manual run alongside the schedule) can
+// both hand the same row here. The avatar insert cannot dedupe on its own since
+// every call mints a fresh random slug, so the loser would publish a second
+// public avatar for one creation. Only the tick that wins the transition writes.
+// Returns null when this tick lost, so the caller reports that instead of
+// claiming a publish it did not do.
async function publishSeedAvatar({ job, verdict, rigged, rigCreationId = null }) {
+ const [won] = await sql`
+ update forge_seed_jobs
+ set status = 'done',
+ finished_at = now()
+ where id = ${job.id}
+ and status <> 'done'
+ returning id
+ `;
+ if (!won) return null;
+
const avatarId = await insertSeedAvatar({
userId: job.user_id,
prompt: job.prompt,
@@ -442,13 +466,7 @@ async function publishSeedAvatar({ job, verdict, rigged, rigCreationId = null })
gate: gateSummary(verdict),
rigged,
});
- await sql`
- update forge_seed_jobs
- set status = 'done',
- avatar_id = ${avatarId},
- finished_at = now()
- where id = ${job.id}
- `;
+ await sql`update forge_seed_jobs set avatar_id = ${avatarId} where id = ${job.id}`;
return avatarId;
}
@@ -533,18 +551,30 @@ async function advanceRigs(origin) {
rigged: true,
rigCreationId,
});
- results.push({ job_id: job.id, status: 'published', rigged: true, avatar_id: avatarId });
+ results.push({
+ job_id: job.id,
+ status: avatarId ? 'published' : 'already_published',
+ rigged: true,
+ avatar_id: avatarId,
+ });
} else if (poll.body?.status === 'failed' || poll.status >= 400) {
// The mesh already passed the gate. A rig fault must not cost the
// catalog the asset: publish it static and say so on the row.
const avatarId = await publishSeedAvatar({ job, verdict: job.gate, rigged: false });
- await sql`
- update forge_seed_jobs
- set error = ${('rig failed: ' + (poll.body?.error || poll.status)).slice(0, 500)}
- where id = ${job.id}
- `;
- results.push({ job_id: job.id, status: 'published', rigged: false, avatar_id: avatarId });
+ if (avatarId) {
+ await sql`
+ update forge_seed_jobs
+ set error = ${('rig failed: ' + (poll.body?.error || poll.status)).slice(0, 500)}
+ where id = ${job.id}
+ `;
+ }
+ results.push({
+ job_id: job.id,
+ status: avatarId ? 'published' : 'already_published',
+ rigged: false,
+ avatar_id: avatarId,
+ });
} else {
results.push({ job_id: job.id, status: 'rigging' });
}
@@ -612,33 +642,15 @@ async function startNextJob(origin, claimed = new Set()) {
const chosen = pool[Math.floor(Math.random() * pool.length)];
claimed.add(chosen.prompt);
- // Claim an OG username. Try the bare word first; if taken, try word + 2,
- // word + 3 … up to word + 99 before falling back to word + short uuid hex.
+ // Claim an OG username and mint the account that owns it.
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 — will retry next tick' };
+ const claim = await claimSeedUser(baseWord);
+ if (!claim) {
+ return { skipped: true, reason: `could not mint a seed account for "${baseWord}"; will retry next tick` };
}
+ const { user, username } = claim;
const rawClientId = randomUUID();
- // Display name is the word, capitalised — looks like a real account. Drop
- // claimUsername's collision suffixes (`_xxxx` uuid fallback, numbered slot)
- // first; stripping digits alone turned "fog_1a2b" into "Fog_".
- const displayName = username
- .replace(/_[0-9a-f]{4}$/, '')
- .replace(/\d+$/, '')
- .replace(/\b\w/g, c => c.toUpperCase());
- const email = `${username}@forge.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 — will retry next tick' };
- }
const cronSecret = process.env.CRON_SECRET || env.CRON_SECRET || '';
const submit = await fetchJson(`${origin}/api/forge`, {
@@ -741,24 +753,68 @@ async function startNextJob(origin, claimed = new Set()) {
};
}
-// Try to claim `word` as a username. Returns the claimed username string or null.
-async function claimUsername(word) {
- // Check which variants already exist so we skip to the next free slot.
+// Mint the seed account for an OG word, letting the users unique index arbitrate
+// the username. Returns { user: { id }, username } or null when every candidate
+// collided.
+//
+// This used to read a bounded slice of the existing names (`limit 100`) and trust
+// it as the complete picture. Once a word's numbered slots filled up, the slice
+// hid the exhaustion and handed back a name that already existed; the insert's
+// `on conflict do nothing` then returned no row and the tick skipped with "user
+// insert conflict". By 2026-07-25 all 171 OG words were saturated (word plus
+// word2..word99), so every tick skipped and seeding stopped dead for weeks while
+// the cron kept answering 200 OK. The index is the only honest arbiter: propose
+// candidates, INSERT, and move to the next one on a conflict.
+const CLAIM_ATTEMPTS = 6;
+
+/**
+ * The usernames to try for `word`, best first, given the ones already taken.
+ * Always returns CLAIM_ATTEMPTS names: a word whose numbered slots are all gone
+ * falls through to random hex slots, which are unbounded, so a saturated word
+ * can never come back empty and stall the tick.
+ * @param {string} word
+ * @param {Set<string>} taken
+ * @returns {string[]}
+ */
+export function seedUsernameCandidates(word, taken) {
+ const candidates = [];
+ if (!taken.has(word)) candidates.push(word);
+ for (let n = 2; n <= 99 && candidates.length < CLAIM_ATTEMPTS; n++) {
+ if (!taken.has(`${word}${n}`)) candidates.push(`${word}${n}`);
+ }
+ while (candidates.length < CLAIM_ATTEMPTS) {
+ candidates.push(`${word}_${randomUUID().slice(0, 4)}`);
+ }
+ return candidates;
+}
+
+async function claimSeedUser(word) {
+ // Exactly the numbered candidate space (word, word2..word99), so the row set
+ // is complete by construction and can never be truncated into a wrong answer.
const existing = await sql`
select username from users
where username = ${word}
- or username like ${word + '%'}
- limit 100
+ or username ~ ${`^${word}[0-9]{1,2}$`}
`;
- 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;
+ const taken = new Set(existing.map((r) => r.username));
+
+ for (const username of seedUsernameCandidates(word, taken)) {
+ // Display name is the word, capitalised, so it reads like a real account.
+ // Drop the collision suffixes (`_xxxx` hex fallback, numbered slot) first;
+ // stripping digits alone turned "fog_1a2b" into "Fog_".
+ const displayName = username
+ .replace(/_[0-9a-f]{4}$/, '')
+ .replace(/\d+$/, '')
+ .replace(/\b\w/g, (c) => c.toUpperCase());
+ const [user] = await sql`
+ insert into users (email, display_name, username, plan, email_verified, service_account, created_at, updated_at)
+ values (${`${username}@forge.three.ws`}, ${displayName}, ${username}, 'free', false, true, now(), now())
+ on conflict do nothing
+ returning id
+ `;
+ if (user?.id) return { user, username };
}
- // All numbered variants taken — fall back to word + short hex (rare).
- return `${word}_${randomUUID().slice(0, 4)}`;
+ return null;
}
// ── Helpers ───────────────────────────────────────────────────────────────────
diff --git a/api/cron/gmgn-seed.js b/api/cron/gmgn-seed.js
index 72719a3bf..16d9b9d56 100644
--- a/api/cron/gmgn-seed.js
+++ b/api/cron/gmgn-seed.js
@@ -121,9 +121,11 @@ function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
* Upsert a batch of seeded wallets into wallet_reputation.
* Only touches label + smart_money_score if the wallet has < 5 judged coins
* in our own system — once we've observed them ourselves we trust our own data.
+ * @returns {Promise<{ written: number, failed: number }>} rows actually written
+ * vs rejected, so the response reports what landed rather than what was tried.
*/
async function upsertSeeded(batch) {
- if (!batch.length) return 0;
+ if (!batch.length) return { written: 0, failed: 0 };
// Build values for a single multi-row upsert.
const values = batch.map((w) => ({
wallet: w.wallet,
@@ -133,12 +135,16 @@ async function upsertSeeded(batch) {
}));
// Postgres doesn't support VALUES with json arrays easily via tagged sql;
- // process in chunks of 50 with individual upserts.
- let count = 0;
+ // process in chunks of 50 with individual upserts. allSettled keeps one bad
+ // row from sinking the chunk, so the count has to come from the fulfilled
+ // results: counting chunk.length reported a clean run while every write was
+ // rejecting, which is exactly the failure this cron would need to surface.
+ let written = 0;
+ let failed = 0;
const CHUNK = 50;
for (let i = 0; i < values.length; i += CHUNK) {
const chunk = values.slice(i, i + CHUNK);
- await Promise.allSettled(chunk.map((v) =>
+ const settled = await Promise.allSettled(chunk.map((v) =>
sql`
insert into wallet_reputation (wallet, network, label, smart_money_score, first_seen_at, updated_at)
values (${v.wallet}, ${v.network}, ${v.label}, ${v.score}, now(), now())
@@ -154,9 +160,19 @@ async function upsertSeeded(batch) {
updated_at = now()
`,
));
- count += chunk.length;
+ for (const r of settled) {
+ if (r.status === 'fulfilled') written++;
+ else {
+ failed++;
+ // The first fault message plus a total, not one line per row: a chunk
+ // that fails wholesale (schema drift, permissions, a dead connection)
+ // would otherwise print the same line fifty times.
+ if (failed === 1) console.warn(`[gmgn-seed] wallet_reputation upsert failed: ${r.reason?.message || r.reason}`);
+ }
+ }
}
- return count;
+ if (failed) console.warn(`[gmgn-seed] ${failed} of ${values.length} upserts failed`);
+ return { written, failed };
}
export default wrapCron(async (req, res) => {
@@ -199,12 +215,13 @@ export default wrapCron(async (req, res) => {
}
const batch = [...collected.values()];
- const upserted = await upsertSeeded(batch);
+ const { written, failed } = await upsertSeeded(batch);
return json(res, 200, {
- ok: true,
+ ok: failed === 0,
fetched: collected.size,
- upserted,
+ upserted: written,
+ upsert_failed: failed,
tags_tried: tags.length,
fallback_used: fallbackUsed,
ms: Date.now() - started,
diff --git a/api/cron/kol-tracker-refresh.js b/api/cron/kol-tracker-refresh.js
index c446b8583..254f079a0 100644
--- a/api/cron/kol-tracker-refresh.js
+++ b/api/cron/kol-tracker-refresh.js
@@ -9,12 +9,13 @@
// Idempotent and cheap: getKolTracker's own cache checks make a warm run mostly
// no-ops.
-import { json, wrapCron } from '../_lib/http.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { requireCron } from '../_lib/cron-auth.js';
const WINDOWS = ['24h', '7d', '30d'];
export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
if (!requireCron(req, res)) return;
const started = Date.now();
@@ -23,10 +24,28 @@ export default wrapCron(async (req, res) => {
WINDOWS.map((window) => getKolTracker({ window, limit: 100 })),
);
+ // A prewarm that silently returned nulls for every window still read as a
+ // healthy 200, so a tracker broken for hours looked identical to a warm
+ // cache. Report the failed windows and their reason instead.
const byWindow = {};
+ const failures = {};
results.forEach((r, i) => {
- byWindow[WINDOWS[i]] = r.status === 'fulfilled' ? r.value.length : null;
+ const window = WINDOWS[i];
+ if (r.status === 'fulfilled') {
+ byWindow[window] = r.value.length;
+ } else {
+ byWindow[window] = null;
+ failures[window] = String(r.reason?.message || r.reason).slice(0, 160);
+ }
});
+ const failed = Object.keys(failures).length;
+ if (failed) console.warn('[kol-tracker-refresh] prewarm failed for', failures);
- return json(res, 200, { ok: true, rows: byWindow, ms: Date.now() - started });
+ return json(res, 200, {
+ ok: failed < WINDOWS.length,
+ rows: byWindow,
+ failed,
+ ...(failed ? { failures } : {}),
+ ms: Date.now() - started,
+ });
});
diff --git a/api/cron/mirror-fanout.js b/api/cron/mirror-fanout.js
index 5d1348231..f1a6aa929 100644
--- a/api/cron/mirror-fanout.js
+++ b/api/cron/mirror-fanout.js
@@ -10,7 +10,7 @@
// Bounded so a 2-minute cron can never run away: only edges with a leader trade
// in the recent window are scanned, and each edge processes at most N events.
-import { error, json, method, wrapCron } from '../_lib/http.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { syncFollow } from '../_lib/agent-mirror.js';
import { requireCron } from '../_lib/cron-auth.js';
@@ -42,8 +42,8 @@ async function fanout(network, stats) {
ORDER BY f.updated_at ASC
LIMIT ${MAX_FOLLOWS_PER_RUN}
`;
- if (!follows.length) return;
stats.edges = (stats.edges || 0) + follows.length;
+ if (!follows.length) return;
for (const f of follows) {
try {
@@ -62,7 +62,10 @@ export default wrapCron(async (req, res) => {
if (!method(req, res, ['GET', 'POST'])) return;
if (!requireCron(req, res)) return;
- const stats = {};
+ // Seeded so an idle run answers {edges:0} rather than a bare {ok:true}: a
+ // scan that found nothing has to be distinguishable from a scan that never
+ // reached the query.
+ const stats = { edges: 0 };
for (const network of NETWORKS) {
try { await fanout(network, stats); }
catch (err) { stats[`error_${network}`] = (err?.message || 'error').slice(0, 160); }
diff --git a/api/cron/news-archive-append.js b/api/cron/news-archive-append.js
index b43e90a72..394bc1981 100644
--- a/api/cron/news-archive-append.js
+++ b/api/cron/news-archive-append.js
@@ -16,7 +16,7 @@
//
// ?dry_run=1 computes and reports without writing.
-import { error, json, method, wrapCron } from '../_lib/http.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { getGcpAccessToken } from '../_lib/gcp-auth.js';
import { getNews } from '../_lib/news.js';
import { geckoFetch } from '../_lib/coingecko.js';
@@ -212,6 +212,10 @@ export default wrapCron(async (req, res) => {
const marketContext = await currentMarketContext();
const appendedByMonth = {};
+ const racedMonths = [];
+ // Only the articles this run actually landed. The stats rollup below must
+ // not count a month whose write lost the generation guard.
+ const written = [];
if (!dryRun) {
for (const [m, { existing, fresh }] of Object.entries(months)) {
@@ -220,25 +224,38 @@ export default wrapCron(async (req, res) => {
const body = existing.text
? `${existing.text.replace(/\n$/, '')}\n${lines.join('\n')}\n`
: `${lines.join('\n')}\n`;
- await gcsPutObject(token, `articles/${m}.jsonl`, body, existing.generation, 'application/x-ndjson');
+ try {
+ await gcsPutObject(token, `articles/${m}.jsonl`, body, existing.generation, 'application/x-ndjson');
+ } catch (err) {
+ // The header promises the loser of an overlapping run just retries
+ // next hour, but an uncaught 412 threw out of the handler instead:
+ // wrap() turns that into a 5xx and pages ops for a race the design
+ // already tolerates. Records are content-addressed, so the winner
+ // wrote the same ids and nothing is lost.
+ if (err?.code !== 'race') throw err;
+ racedMonths.push(m);
+ console.warn(`news-archive-append: ${m} lost the generation guard to an overlapping run; retrying next hour`);
+ continue;
+ }
appendedByMonth[m] = fresh.length;
+ written.push(...fresh);
}
// Keep corpus stats truthful for /markets/archive and the API's
// stats mode. Best-effort: a stats race loses to next hour's run.
try {
- const stats = await gcsGetObject(token, 'meta/stats.json');
+ const stats = written.length ? await gcsGetObject(token, 'meta/stats.json') : { exists: false };
if (stats.exists) {
const parsed = JSON.parse(stats.text);
- parsed.total_articles += allFresh.length;
- parsed.total_with_url += allFresh.length;
- parsed.total_with_date += allFresh.filter((a) => a.pub_date).length;
- parsed.total_with_description += allFresh.filter((a) => a.description).length;
- const newest = allFresh.map((a) => a.pub_date).filter(Boolean).sort().pop();
+ parsed.total_articles += written.length;
+ parsed.total_with_url += written.length;
+ parsed.total_with_date += written.filter((a) => a.pub_date).length;
+ parsed.total_with_description += written.filter((a) => a.description).length;
+ const newest = written.map((a) => a.pub_date).filter(Boolean).sort().pop();
if (newest && (!parsed.last_article_date || newest > parsed.last_article_date)) {
parsed.last_article_date = newest;
}
- for (const a of allFresh) {
+ for (const a of written) {
parsed.sources[a.source_key] = (parsed.sources[a.source_key] || 0) + 1;
}
await gcsPutObject(token, 'meta/stats.json', JSON.stringify(parsed, null, 2), stats.generation, 'application/json');
@@ -255,8 +272,9 @@ export default wrapCron(async (req, res) => {
return json(res, 200, {
ok: true,
month,
- appended: allFresh.length,
+ appended: dryRun ? allFresh.length : written.length,
appended_by_month: appendedByMonth,
+ ...(racedMonths.length ? { raced_months: racedMonths } : {}),
live_considered: live.articles.length,
already_archived: alreadyArchived,
skipped_backlog: skippedBacklog,
diff --git a/api/cron/vanity-inventory-replenish.js b/api/cron/vanity-inventory-replenish.js
index 302280107..a906df808 100644
--- a/api/cron/vanity-inventory-replenish.js
+++ b/api/cron/vanity-inventory-replenish.js
@@ -25,8 +25,7 @@
// this pages ops with the exact manual command instead of pretending to have
// replenished anything.
-import { error, json, method, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { sendOpsAlert } from '../_lib/alerts.js';
import { inventoryStats, sweepExpiredSecrets, isDbUnavailableError } from '../_lib/vanity-inventory-store.js';
import { getGcpAccessToken, gcpAuthConfigured } from '../_lib/gcp-auth.js';
@@ -35,6 +34,27 @@ import { requireCron } from '../_lib/cron-auth.js';
// Below this many available items platform-wide, fire a replenishment run.
// Overridable so ops can tune the shelf depth without a redeploy.
const LOW_WATERMARK = Number(process.env.VANITY_INVENTORY_LOW_WATERMARK || 25);
+// …and below this many DISTINCT rarity tiers in stock, fire one too. Raw depth
+// alone is a misleading signal: the premium tiers sell at very different prices
+// (api/_lib/vanity-inventory-pricing.js), so a shelf holding 300 items that are
+// all one tier cannot serve a buyer asking for any other, while `available`
+// reads comfortably above the watermark and the grinder never runs. Five tiers
+// exist today (uncommon → mythic); three is "the shelf still has a spread".
+const MIN_TIERS = Number(process.env.VANITY_INVENTORY_MIN_TIERS || 3);
+
+/**
+ * Does the shelf need a grind? Depth OR spread failing is enough. See the
+ * watermarks above for why spread is not derivable from depth. Exported so the
+ * trigger is testable without a DB or a Cloud Run job.
+ * @param {{available:number, tiers:number}} stats
+ * @returns {{low:boolean, reasons:string[]}}
+ */
+export function replenishTrigger(stats) {
+ const reasons = [];
+ if (Number(stats?.available || 0) < LOW_WATERMARK) reasons.push(`available ${Number(stats?.available || 0)} < ${LOW_WATERMARK}`);
+ if (Number(stats?.tiers || 0) < MIN_TIERS) reasons.push(`tiers ${Number(stats?.tiers || 0)} < ${MIN_TIERS}`);
+ return { low: reasons.length > 0, reasons };
+}
const PROJECT = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCP_PROJECT_ID || '';
const REGION = process.env.VANITY_GRIND_REGION || 'us-central1';
@@ -88,33 +108,34 @@ export default wrapCron(async (req, res) => {
console.error('[vanity-inventory-replenish] sweep failed', err?.message || err);
}
- const low = stats.available < LOW_WATERMARK;
+ const { low, reasons } = replenishTrigger(stats);
if (!low) {
return json(res, 200, { ok: true, low_stock: false, stats, swept });
}
+ const why = reasons.join('; ');
if (!jobConfigured()) {
await sendOpsAlert(
'Vanity inventory low — replenishment job not configured',
- `Available: ${stats.available} (watermark ${LOW_WATERMARK}). Run manually: ` +
+ `Low on ${why}. Run manually: ` +
`PROJECT_ID=<gcp-project> ./scripts/gcp/vanity-grind-deploy.sh --run — or set ` +
`GOOGLE_CLOUD_PROJECT (+ GCP auth) so this cron can trigger the Cloud Run Job itself.`,
{ signature: 'vanity-replenish-not-configured' },
);
- return json(res, 200, { ok: true, low_stock: true, configured: false, stats, swept });
+ return json(res, 200, { ok: true, low_stock: true, configured: false, reasons, stats, swept });
}
try {
const execution = await triggerGrindJob();
await sendOpsAlert(
'🟡 Vanity inventory low — replenishment grind triggered',
- `Available: ${stats.available} (watermark ${LOW_WATERMARK}). Fired Cloud Run Job ` +
+ `Low on ${why}. Fired Cloud Run Job ` +
`${JOB} in ${REGION}. Execution: ${execution || '(unnamed)'}.`,
{ signature: `vanity-replenish-fired:${new Date().toISOString().slice(0, 13)}` },
);
- return json(res, 200, { ok: true, low_stock: true, configured: true, triggered: true, execution, stats, swept });
+ return json(res, 200, { ok: true, low_stock: true, configured: true, triggered: true, execution, reasons, stats, swept });
} catch (err) {
await sendOpsAlert('Vanity inventory low — replenishment trigger failed', err.message, { signature: 'vanity-replenish-trigger-failed' });
- return json(res, 200, { ok: false, low_stock: true, error: err.message, stats, swept });
+ return json(res, 200, { ok: false, low_stock: true, error: err.message, reasons, stats, swept });
}
});
diff --git a/api/cron/x402-directory-registrar.js b/api/cron/x402-directory-registrar.js
index 119cab75a..2d9eb5b4e 100644
--- a/api/cron/x402-directory-registrar.js
+++ b/api/cron/x402-directory-registrar.js
@@ -61,6 +61,29 @@ async function upsertAt402Index(entry) {
return { ok: r.ok, status: r.status, body: body.slice(0, 200) };
}
+/**
+ * Which slice of the live paid catalog this hour re-upserts.
+ *
+ * The cursor is derived from the hour number rather than persisted, so the
+ * rotation survives a cold start, a redeploy, and a skipped tick without any
+ * state of its own: hour N always maps to the same window. Callers pass `nowMs`
+ * so the mapping is testable without a clock.
+ *
+ * @param {Array<object>} candidates live x402 catalog entries
+ * @param {number} nowMs epoch milliseconds
+ * @param {number} [windowSize] entries per tick (402index rate-limits to 10/h/IP)
+ * @returns {{ windows: number, cursor: number, batch: Array<object> }}
+ */
+export function registrarWindow(candidates, nowMs, windowSize = WINDOW) {
+ // An empty catalog would make `% windows` a modulo by zero (NaN), which slices
+ // to nothing and reports "window NaN/0". The handler refuses an empty catalog
+ // outright; this keeps the pure function total regardless.
+ const windows = Math.max(1, Math.ceil(candidates.length / windowSize));
+ const cursor = Math.floor(nowMs / HOUR_MS) % windows;
+ const start = cursor * windowSize;
+ return { windows, cursor, batch: candidates.slice(start, start + windowSize) };
+}
+
export default wrapCron(async (req, res) => {
if (!method(req, res, ['GET', 'POST'])) return;
if (!requireCron(req, res)) return;
@@ -71,9 +94,7 @@ export default wrapCron(async (req, res) => {
return error(res, 500, 'empty_catalog', 'paid catalog rendered empty — refusing to run');
}
- const windows = Math.ceil(candidates.length / WINDOW);
- const cursor = Math.floor(Date.now() / HOUR_MS) % windows;
- const batch = candidates.slice(cursor * WINDOW, cursor * WINDOW + WINDOW);
+ const { windows, cursor, batch } = registrarWindow(candidates, Date.now());
const results = [];
for (const entry of batch) {
diff --git a/tests/api/kol-tracker-refresh-cron.test.js b/tests/api/kol-tracker-refresh-cron.test.js
new file mode 100644
index 000000000..40031b2c1
--- /dev/null
+++ b/tests/api/kol-tracker-refresh-cron.test.js
@@ -0,0 +1,104 @@
+// api/cron/kol-tracker-refresh.js: the KOL Tracker cache prewarm.
+//
+// Two regressions this pins down:
+// 1. It was the only cron in api/cron/ with NO method gate. Its own header
+// documents GET/POST, but a DELETE (or PUT, or PATCH) fell straight
+// through to the cron-secret check and, with a valid secret, ran the
+// sweep. Every neighbouring cron answers 405 first.
+// 2. A window whose prewarm threw was reported as `null` inside an `ok:true`
+// body, so a tracker broken for hours looked exactly like a warm cache.
+// Failures are named now, and a run where every window failed is not ok.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const getKolTracker = vi.fn();
+vi.mock('../../src/kol/tracker.js', () => ({ getKolTracker }));
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));
+
+const { default: handler } = await import('../../api/cron/kol-tracker-refresh.js');
+
+function call(method = 'GET', auth = 'Bearer test-cron-secret') {
+ const res = {
+ statusCode: 0,
+ body: null,
+ headers: {},
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b ? JSON.parse(b) : null; },
+ get headersSent() { return this.body !== null; },
+ get writableEnded() { return this.body !== null; },
+ };
+ const req = { method, url: '/api/cron/kol-tracker-refresh', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ getKolTracker.mockReset();
+ getKolTracker.mockResolvedValue([{ handle: 'a' }, { handle: 'b' }]);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ vi.restoreAllMocks();
+});
+
+describe('GET/POST /api/cron/kol-tracker-refresh', () => {
+ it('rejects a method it does not serve, before touching the tracker', async () => {
+ const res = await call('DELETE');
+ expect(res.statusCode).toBe(405);
+ expect(res.body.error).toBe('method_not_allowed');
+ expect(getKolTracker).not.toHaveBeenCalled();
+ });
+
+ it('serves GET and POST', async () => {
+ expect((await call('GET')).statusCode).toBe(200);
+ expect((await call('POST')).statusCode).toBe(200);
+ });
+
+ it('rejects a bad cron secret', async () => {
+ const res = await call('GET', 'Bearer wrong');
+ expect(res.statusCode).toBe(401);
+ expect(getKolTracker).not.toHaveBeenCalled();
+ });
+
+ it('prewarms every window and reports the row counts', async () => {
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.ok).toBe(true);
+ expect(res.body.rows).toEqual({ '24h': 2, '7d': 2, '30d': 2 });
+ expect(res.body.failed).toBe(0);
+ expect(res.body.failures).toBeUndefined();
+ expect(getKolTracker.mock.calls.map((c) => c[0].window)).toEqual(['24h', '7d', '30d']);
+ });
+
+ it('names a failed window instead of reporting a silent null', async () => {
+ getKolTracker.mockImplementation(async ({ window }) => {
+ if (window === '7d') throw new Error('X API rate limit');
+ return [{ handle: 'a' }];
+ });
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.ok).toBe(true); // a partial prewarm is still useful
+ expect(res.body.rows).toEqual({ '24h': 1, '7d': null, '30d': 1 });
+ expect(res.body.failed).toBe(1);
+ expect(res.body.failures['7d']).toContain('X API rate limit');
+ });
+
+ it('is not ok when every window failed', async () => {
+ getKolTracker.mockRejectedValue(new Error('tracker down'));
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.ok).toBe(false);
+ expect(res.body.failed).toBe(3);
+ });
+});
diff --git a/tests/api/mirror-fanout-cron.test.js b/tests/api/mirror-fanout-cron.test.js
new file mode 100644
index 000000000..766ad4dd9
--- /dev/null
+++ b/tests/api/mirror-fanout-cron.test.js
@@ -0,0 +1,91 @@
+// api/cron/mirror-fanout.js: the custodial copy-trade fanout.
+//
+// The handler answers with whatever counters the sweep accumulated, and an idle
+// run used to accumulate none: the early `return` on an empty candidate set
+// fired before `stats.edges` was ever assigned, so the response was a bare
+// {ok:true}. That is indistinguishable from a run that never reached the query,
+// which matters because this cron is the only thing standing between a leader's
+// trade and a follower's mirror of it. An idle run now says so: {edges: 0}.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+const syncFollow = vi.fn();
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+vi.mock('../../api/_lib/agent-mirror.js', () => ({ syncFollow }));
+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));
+
+const { default: handler } = await import('../../api/cron/mirror-fanout.js');
+
+function call(method = 'GET', auth = 'Bearer test-cron-secret') {
+ const res = {
+ statusCode: 0,
+ body: null,
+ headers: {},
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b ? JSON.parse(b) : null; },
+ get headersSent() { return this.body !== null; },
+ get writableEnded() { return this.body !== null; },
+ };
+ const req = { method, url: '/api/cron/mirror-fanout', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+ syncFollow.mockReset();
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ vi.restoreAllMocks();
+});
+
+describe('GET/POST /api/cron/mirror-fanout', () => {
+ it('rejects a method it does not serve', async () => {
+ expect((await call('DELETE')).statusCode).toBe(405);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a bad cron secret', async () => {
+ expect((await call('GET', 'Bearer wrong')).statusCode).toBe(401);
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('an idle run reports edges: 0 rather than a bare ok', async () => {
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({ ok: true, edges: 0 });
+ expect(syncFollow).not.toHaveBeenCalled();
+ });
+
+ it('counts edges across both networks and rolls up per-fill statuses', async () => {
+ sqlMock.mockResolvedValue([{ id: 'f1', follower_agent_id: 'a', leader_agent_id: 'b', leader_name: 'Leader' }]);
+ syncFollow.mockResolvedValue({ results: [{ status: 'filled' }, { status: 'skipped' }] });
+ const res = await call();
+ expect(res.body.edges).toBe(2); // one candidate on each of mainnet + devnet
+ expect(res.body.filled).toBe(2);
+ expect(res.body.skipped).toBe(2);
+ expect(syncFollow).toHaveBeenCalledTimes(2);
+ });
+
+ it('a failing edge is counted, never fatal to the sweep', async () => {
+ sqlMock.mockResolvedValue([{ id: 'f1' }]);
+ syncFollow.mockRejectedValue(new Error('custody refused'));
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.error).toBe(2);
+ expect(res.body.last_error).toContain('custody refused');
+ });
+});
diff --git a/tests/api/oracle-digest-cron.test.js b/tests/api/oracle-digest-cron.test.js
new file mode 100644
index 000000000..91be1b234
--- /dev/null
+++ b/tests/api/oracle-digest-cron.test.js
@@ -0,0 +1,150 @@
+// api/cron/oracle-digest.js: the daily Oracle conviction digest.
+//
+// platformDayStats and buildChannelDigest are exported "for tests" but had
+// none, so nothing pinned the one property that matters for a message posted
+// to a public channel: it renders from real DB rows, degrades to honest
+// "nothing today" copy when the query returns nothing, and escapes the
+// attacker-controlled strings it interpolates (a coin symbol is on-chain
+// metadata, so it is untrusted input, and the digest is parse_mode HTML).
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+vi.mock('../../api/_lib/env.js', () => ({ env: {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: vi.fn() }));
+vi.mock('../../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn() }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: vi.fn() }));
+
+const { default: handler, platformDayStats, buildChannelDigest } =
+ await import('../../api/cron/oracle-digest.js');
+
+function call(method = 'GET', auth = 'Bearer test-cron-secret') {
+ const res = {
+ statusCode: 0,
+ body: null,
+ headers: {},
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b ? JSON.parse(b) : null; },
+ get headersSent() { return this.body !== null; },
+ get writableEnded() { return this.body !== null; },
+ };
+ const req = { method, url: '/api/cron/oracle-digest', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+const originalFetch = global.fetch;
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ delete process.env.TELEGRAM_BOT_TOKEN;
+ delete process.env.TELEGRAM_ORACLE_CHAT_ID;
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+ global.fetch = vi.fn(async () => ({ ok: true, json: async () => ({ ok: true }) }));
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ global.fetch = originalFetch;
+ vi.restoreAllMocks();
+});
+
+describe('the digest handler gates', () => {
+ it('rejects a method it does not serve', async () => {
+ expect((await call('DELETE')).statusCode).toBe(405);
+ });
+
+ it('rejects a bad cron secret', async () => {
+ expect((await call('GET', 'Bearer wrong')).statusCode).toBe(401);
+ });
+
+ it('reports the missing credential instead of failing, and sends nothing', async () => {
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({ ok: true, sent: 0, reason: 'TELEGRAM_BOT_TOKEN not set' });
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('posts the channel anchor even with zero personal subscribers', async () => {
+ process.env.TELEGRAM_BOT_TOKEN = 'bot-token';
+ process.env.TELEGRAM_ORACLE_CHAT_ID = '-100123';
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.channel).toBe(true);
+ expect(res.body.subscribers).toBe(0);
+ expect(res.body.sent).toBe(1);
+ const [url, opts] = global.fetch.mock.calls[0];
+ expect(String(url)).toContain('/botbot-token/sendMessage');
+ expect(JSON.parse(opts.body).chat_id).toBe('-100123');
+ expect(JSON.parse(opts.body).parse_mode).toBe('HTML');
+ });
+});
+
+describe('platformDayStats', () => {
+ it('reads the scored count, action rollup and top coins for the window', async () => {
+ sqlMock
+ .mockResolvedValueOnce([{ n: 412 }])
+ .mockResolvedValueOnce([{ total: 9, wins: 5, losses: 4, pnl: '1.25' }])
+ .mockResolvedValueOnce([{ mint: 'Mint1', symbol: 'ABC', score: 91, tier: 'prime', category: 'meme' }]);
+ const day = await platformDayStats('mainnet');
+ expect(day.scored).toBe(412);
+ expect(day.actions).toMatchObject({ total: 9, wins: 5, losses: 4 });
+ expect(day.top).toHaveLength(1);
+ });
+
+ it('degrades to zeroes when the tables are not there yet', async () => {
+ sqlMock.mockRejectedValue(new Error('relation "oracle_conviction" does not exist'));
+ const day = await platformDayStats('mainnet');
+ expect(day.scored).toBe(0);
+ expect(day.actions).toMatchObject({ total: 0, wins: 0, losses: 0 });
+ expect(day.top).toEqual([]);
+ });
+});
+
+describe('buildChannelDigest', () => {
+ const base = { scored: 1234, actions: { total: 0, wins: 0, losses: 0, pnl: 0 }, top: [] };
+
+ it('renders the scored count and the referral offers', () => {
+ const msg = buildChannelDigest(base);
+ expect(msg).toContain('1,234');
+ expect(msg).toContain('https://three.ws/oracle');
+ expect(msg).toContain('Trade with a fee discount');
+ });
+
+ it('says nothing cleared the floor rather than rendering an empty list', () => {
+ expect(buildChannelDigest(base)).toContain('No launches cleared the scoring floor today');
+ });
+
+ it('renders the agent line only when there were actions, with a signed PnL', () => {
+ expect(buildChannelDigest(base)).not.toContain('<b>Agents</b>');
+ const msg = buildChannelDigest({ ...base, actions: { total: 3, wins: 2, losses: 1, pnl: 0.5 } });
+ expect(msg).toContain('3 actions');
+ expect(msg).toContain('2W / 1L');
+ expect(msg).toContain('+0.5000 SOL');
+ });
+
+ it('escapes a hostile coin symbol instead of injecting markup into the channel post', () => {
+ const msg = buildChannelDigest({
+ ...base,
+ top: [{ mint: 'Mint1', symbol: '<b>PWN</b>', score: 88, tier: 'strong', category: 'unknown' }],
+ });
+ expect(msg).toContain('&lt;b&gt;PWN&lt;/b&gt;');
+ expect(msg).not.toContain('$<b>PWN</b>');
+ // an "unknown" category is omitted, not printed as the literal word
+ expect(msg).not.toContain('· unknown');
+ });
+
+ it('falls back to a mint prefix when a coin has no symbol', () => {
+ const msg = buildChannelDigest({
+ ...base,
+ top: [{ mint: 'AbCdEfGhIjKl', symbol: null, score: 70, tier: 'lean', category: 'meme' }],
+ });
+ expect(msg).toContain('$AbCdEf');
+ });
+});
diff --git a/tests/cron-seed-username-claim.test.js b/tests/cron-seed-username-claim.test.js
new file mode 100644
index 000000000..b739912a9
--- /dev/null
+++ b/tests/cron-seed-username-claim.test.js
@@ -0,0 +1,70 @@
+// The forge seed cron's username claim (api/cron/forge-seed-cron.js) and the
+// free-model liveness audit (api/cron/free-model-audit.js).
+//
+// Both encode the same lesson: a cron that answers 200 OK while doing nothing is
+// worse than one that fails, because nothing pages. The seed cron used to read a
+// bounded slice of the existing usernames (`limit 100`) and trust it as complete.
+// Once a word's numbered slots filled up the slice hid the exhaustion, the claim
+// handed back a name that already existed, the insert's `on conflict do nothing`
+// returned no row, and the tick skipped. By 2026-07-25 every one of the 171 OG
+// words was saturated, so seeding stopped entirely for weeks with a green cron.
+// These lock the saturated case in: candidate generation must always yield names
+// to try, and must never propose one it was told is taken.
+import { test, expect } from 'vitest';
+import { seedUsernameCandidates } from '../api/cron/forge-seed-cron.js';
+import { diffFreeModels } from '../api/cron/free-model-audit.js';
+
+test('a fresh word claims the bare word first', () => {
+ const candidates = seedUsernameCandidates('wolf', new Set());
+ expect(candidates[0]).toBe('wolf');
+ expect(candidates.slice(1, 3)).toEqual(['wolf2', 'wolf3']);
+});
+
+test('a partly used word skips to the free numbered slots', () => {
+ const taken = new Set(['wolf', 'wolf2', 'wolf3']);
+ const candidates = seedUsernameCandidates('wolf', taken);
+ expect(candidates[0]).toBe('wolf4');
+ expect(candidates.some((c) => taken.has(c))).toBe(false);
+});
+
+// The regression: word + word2..word99 all gone. The old claim returned a taken
+// name here and the tick skipped forever.
+test('a fully saturated word still yields usable candidates', () => {
+ const taken = new Set(['wolf', ...Array.from({ length: 98 }, (_, i) => `wolf${i + 2}`)]);
+ const candidates = seedUsernameCandidates('wolf', taken);
+
+ expect(candidates.length).toBeGreaterThan(0);
+ expect(candidates.some((c) => taken.has(c))).toBe(false);
+ // Every fallback is a random hex slot off the same word, so the display name
+ // still reads as the OG word.
+ for (const c of candidates) expect(c).toMatch(/^wolf_[0-9a-f]{4}$/);
+ // Distinct, so retrying after a conflict actually tries something new.
+ expect(new Set(candidates).size).toBe(candidates.length);
+});
+
+test('candidates never repeat a name the caller reported as taken', () => {
+ const taken = new Set(['ash', 'ash2', 'ash5', 'ash6', 'ash7', 'ash9']);
+ const candidates = seedUsernameCandidates('ash', taken);
+ for (const c of candidates) expect(taken.has(c)).toBe(false);
+});
+
+// free-model-audit: the verdict that pages ops, and the one that must not.
+test('a hardcoded id missing from the live list is reported dead', () => {
+ const result = diffFreeModels(
+ ['openai/gpt-oss-20b:free', 'inclusionai/ling-3.0-flash:free'],
+ ['openai/gpt-oss-20b:free', 'google/gemma-4-31b-it:free'],
+ );
+ expect(result.status).toBe('dead_rungs');
+ expect(result.dead).toEqual(['inclusionai/ling-3.0-flash:free']);
+ expect(result.live).toBe(1);
+});
+
+// The failure path that matters: OpenRouter being unreachable returns an empty
+// live list, and calling every model dead on our own outage would page ops with
+// a false alarm and invite a pointless catalog rewrite.
+test('an empty live list is unknown, never a dead verdict', () => {
+ const result = diffFreeModels(['openai/gpt-oss-20b:free'], []);
+ expect(result.status).toBe('unknown');
+ expect(result.dead).toEqual([]);
+ expect(result.checked).toBe(1);
+});
diff --git a/tests/cron-vanity-replenish-trigger.test.js b/tests/cron-vanity-replenish-trigger.test.js
new file mode 100644
index 000000000..27fda2eb2
--- /dev/null
+++ b/tests/cron-vanity-replenish-trigger.test.js
@@ -0,0 +1,41 @@
+// The vanity shelf's replenishment trigger (api/cron/vanity-inventory-replenish.js).
+//
+// The cron's contract was always "fire the grinder when stock OR the distinct-tier
+// count drops below a watermark", but only the stock half was implemented: a shelf
+// holding hundreds of items that had collapsed to a single rarity tier read as
+// healthy forever, so the premium tiers (api/x402/vanity-premium.js sells per tier)
+// could go permanently unservable while the grinder never ran. These lock both
+// halves in, including the case that regressed.
+import { test, expect } from 'vitest';
+import { replenishTrigger } from '../api/cron/vanity-inventory-replenish.js';
+
+test('a deep, well-spread shelf does not fire a grind', () => {
+ const { low, reasons } = replenishTrigger({ available: 385, tiers: 5 });
+ expect(low).toBe(false);
+ expect(reasons).toEqual([]);
+});
+
+test('shallow stock fires a grind and says so', () => {
+ const { low, reasons } = replenishTrigger({ available: 4, tiers: 5 });
+ expect(low).toBe(true);
+ expect(reasons.join(' ')).toMatch(/available 4/);
+});
+
+test('a deep shelf collapsed to one tier still fires a grind', () => {
+ // The regression: depth alone reads healthy, spread does not.
+ const { low, reasons } = replenishTrigger({ available: 300, tiers: 1 });
+ expect(low).toBe(true);
+ expect(reasons.join(' ')).toMatch(/tiers 1/);
+ expect(reasons.join(' ')).not.toMatch(/available/);
+});
+
+test('both watermarks failing are both reported', () => {
+ const { low, reasons } = replenishTrigger({ available: 2, tiers: 1 });
+ expect(low).toBe(true);
+ expect(reasons).toHaveLength(2);
+});
+
+test('an empty shelf is low, and a missing stat is treated as zero', () => {
+ expect(replenishTrigger({}).low).toBe(true);
+ expect(replenishTrigger({ available: 0, tiers: 0 }).low).toBe(true);
+});
diff --git a/tests/forge-off-crown-week.test.js b/tests/forge-off-crown-week.test.js
new file mode 100644
index 000000000..397a955da
--- /dev/null
+++ b/tests/forge-off-crown-week.test.js
@@ -0,0 +1,51 @@
+// resolveWeekStart: which Monday the Forge-Off crowning applies to.
+//
+// This is the input guard on an IRREVERSIBLE write. A crowning is permanent by
+// design (forge_board_winners has ON CONFLICT (week_start) DO NOTHING, so the
+// first crowning for a week wins forever), and `?week=` is the owner's backfill
+// override. Before 2026-08-10 an unparseable date silently fell through to the
+// default week, so `?week=2026-13-99` did not error: it permanently crowned the
+// CURRENT week instead of the one the owner typed, with no way to undo it.
+// Unparseable input must therefore be rejected, never guessed.
+
+import { describe, it, expect } from 'vitest';
+import { resolveWeekStart } from '../api/cron/forge-off-crown.js';
+
+const key = (d) => d.toISOString().slice(0, 10);
+
+describe('resolveWeekStart', () => {
+ it('defaults to the Monday of the week that just completed', () => {
+ const resolved = resolveWeekStart(null);
+ expect(resolved).toBeInstanceOf(Date);
+ // Always a Monday (UTC day 1), and strictly in the past.
+ expect(resolved.getUTCDay()).toBe(1);
+ expect(resolved.getTime()).toBeLessThan(Date.now());
+ });
+
+ it('accepts an explicit Monday and returns exactly that week', () => {
+ expect(key(resolveWeekStart('2026-07-27'))).toBe('2026-07-27');
+ });
+
+ it('snaps a mid-week backfill date to its own week Monday', () => {
+ // Thu 2026-07-30 and Sun 2026-08-02 both belong to the 2026-07-27 week.
+ expect(key(resolveWeekStart('2026-07-30'))).toBe('2026-07-27');
+ expect(key(resolveWeekStart('2026-08-02'))).toBe('2026-07-27');
+ });
+
+ it('rejects an unparseable week instead of crowning the default one', () => {
+ // The whole point: each of these used to resolve to the default week and
+ // perform a permanent write against it.
+ expect(resolveWeekStart('2026-13-99')).toBeNull();
+ expect(resolveWeekStart('not-a-date')).toBeNull();
+ expect(resolveWeekStart('2026-07')).toBeNull();
+ expect(resolveWeekStart('last monday please')).toBeNull();
+ expect(resolveWeekStart("2026-08-03'; DROP TABLE forge_board_winners;--")).toBeNull();
+ });
+
+ it('treats an empty week param as absent, not as invalid', () => {
+ // `?week=` with no value is the same as omitting it; the cron's own
+ // schedule hits this path, and it must not start 400ing.
+ expect(resolveWeekStart('')).toBeInstanceOf(Date);
+ expect(resolveWeekStart(undefined)).toBeInstanceOf(Date);
+ });
+});
diff --git a/tests/news-archive-append.test.js b/tests/news-archive-append.test.js
index 5f551c1e4..5d7c820cc 100644
--- a/tests/news-archive-append.test.js
+++ b/tests/news-archive-append.test.js
@@ -186,3 +186,50 @@ describe('GET /api/cron/news-archive-append', () => {
expect(stats.last_article_date).toBe(`${NOW_MONTH}-05T10:00:00.000Z`);
});
});
+
+describe('an overlapping run losing the GCS generation guard', () => {
+ // The header promises the loser of a race just retries next hour, but the
+ // 412 threw straight out of the handler, so wrap() turned a benign,
+ // designed-for race into a 5xx that pages ops. Records are content
+ // addressed, so the winner wrote the same ids and nothing was lost.
+ it('is tolerated per month: the run still 200s and the other month still lands', async () => {
+ const base = global.fetch;
+ global.fetch = vi.fn(async (url, opts = {}) => {
+ if (opts.method === 'POST' && String(url).includes(`articles%2F${NOW_MONTH}.jsonl`)) {
+ return { ok: false, status: 412, json: async () => ({}), text: async () => 'precondition failed' };
+ }
+ return base(url, opts);
+ });
+ const res = await call('/api/cron/news-archive-append');
+ expect(res._json.status).toBe(200);
+ expect(res._json.body.raced_months).toEqual([NOW_MONTH]);
+ expect(res._json.body.appended_by_month).toEqual({ [PREV_MONTH]: 1 });
+ expect(res._json.body.appended).toBe(1);
+ });
+
+ it('does not credit the raced month to the corpus stats', async () => {
+ const base = global.fetch;
+ global.fetch = vi.fn(async (url, opts = {}) => {
+ if (opts.method === 'POST' && String(url).includes(`articles%2F${NOW_MONTH}.jsonl`)) {
+ return { ok: false, status: 412, json: async () => ({}), text: async () => 'precondition failed' };
+ }
+ return base(url, opts);
+ });
+ await call('/api/cron/news-archive-append');
+ const statsWrite = writes.find((w) => w.url.includes('meta%2Fstats.json'));
+ // 662047 + only the one article that actually landed
+ expect(JSON.parse(statsWrite.body).total_articles).toBe(662048);
+ expect(JSON.parse(statsWrite.body).sources.coindesk).toBe(2108);
+ });
+
+ it('a real GCS write failure still fails the run', async () => {
+ const base = global.fetch;
+ global.fetch = vi.fn(async (url, opts = {}) => {
+ if (opts.method === 'POST') {
+ return { ok: false, status: 503, json: async () => ({}), text: async () => 'backend error' };
+ }
+ return base(url, opts);
+ });
+ await expect(call('/api/cron/news-archive-append')).rejects.toThrow(/GCS write/);
+ });
+});