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.

test(cron): cover launcher-tick, leaderboard-rollup, and oracle crons; strip banned em-dashes from cron comments

nirholas8bff7fb3f831
diff --git a/api/cron/irl-reap.js b/api/cron/irl-reap.js
index be3408ff1..14b4287f8 100644
--- a/api/cron/irl-reap.js
+++ b/api/cron/irl-reap.js
@@ -1,14 +1,14 @@
// @ts-check
-// GET /api/cron/irl-reap — IRL placement reaper (D4).
+// GET /api/cron/irl-reap - IRL placement reaper (D4).
//
// Keeps the irl_pins table and every geocell density count lean by deleting dead
// rows the nearby/mine queries already filter out:
//
-// 1. Expired anonymous pins, one day past expiry — long enough that a brief
+// 1. Expired anonymous pins, one day past expiry - long enough that a brief
// clock skew or a viewer mid-session never loses a still-relevant pin, short
// enough that ghosts don't accumulate. Signed-in permanent pins (expires_at
// IS NULL) are NEVER reaped.
-// 2. Reports tied to pins that no longer exist — once the pin is gone the report
+// 2. Reports tied to pins that no longer exist - once the pin is gone the report
// trail is moot, so it's purged to keep irl_pin_reports bounded.
// 3. Interactions (taps/views/messages/pays) whose pin is gone, and interactions
// older than the retention window regardless of pin state. An interaction row
@@ -18,24 +18,24 @@
// pin dies, and age it out at INTERACTION_RETENTION_DAYS so even a permanent
// (signed-in) pin's encounter trail can't grow unbounded.
// 4. Usage-analytics events (irl_events, api/_lib/irl-analytics.js) older than 90
-// days, regardless of pin state — coarse telemetry (geocell7 + hashed device
+// days, regardless of pin state - coarse telemetry (geocell7 + hashed device
// prefix, no FK to irl_pins by design) but still a passive trail, so it's
// bounded the same way interactions are.
//
-// Retention window — interactions: 180 days. Rationale: long enough that an owner's
+// Retention window - interactions: 180 days. Rationale: long enough that an owner's
// dashboard inbox + the earnings history a `pay` row backs stay useful across a
// reasonable review horizon, short enough that the location trail has a hard, known
// ceiling. The geo-bearing columns (lat/lng) duplicate the pin's own location and
// are kept only for the lifetime of the row precisely because the row is bounded by
// this window + the orphan cascade; we age out the raw row rather than null its
// coordinates so nothing about a months-old encounter survives. `pay` rows age out
-// on the same clock — the durable earnings signal an owner cares about is recent,
+// on the same clock - the durable earnings signal an owner cares about is recent,
// and a 180-day-old settlement is already on-chain (the source of truth), so we do
// not keep a stale geo-tagged copy of it indefinitely.
//
// Hidden pins are NOT deleted here: a moderation-hidden pin is queued for review +
// owner appeal, not garbage. It's reaped only when its own expiry passes (anon) or
-// never (signed-in) — the same rule as any other pin.
+// never (signed-in) - the same rule as any other pin.
//
// Runs hourly. Idempotent: re-running deletes nothing new once the table is clean.
@@ -51,7 +51,7 @@ import { requireCron } from '../_lib/cron-auth.js';
export const REAP_SPIKE_THRESHOLD = 1000;
// Pure: is this run's deletion volume anomalous? Sums the three sweep counts and
-// compares to the threshold. Exported for unit testing — no I/O, no clock.
+// compares to the threshold. Exported for unit testing - no I/O, no clock.
export function reapTotal(counts) {
return (counts?.pins || 0) + (counts?.reports || 0) + (counts?.interactions || 0) +
(counts?.worldLines || 0) + (counts?.proofs || 0) + (counts?.events || 0);
@@ -66,7 +66,7 @@ export default wrapCron(async (req, res) => {
// Both tables are created lazily by their write endpoints (irl_pins by
// api/irl/pins.js, irl_pin_reports by api/irl/report.js), so on a fresh
- // deployment — or before the first pin is placed / first report is filed —
+ // deployment - or before the first pin is placed / first report is filed -
// they may not exist yet. A reaper that hard-depended on them would throw
// `relation does not exist` and 500 the hourly cron. Probe with to_regclass
// and treat a missing table as "nothing to reap" rather than an error.
@@ -90,7 +90,7 @@ export default wrapCron(async (req, res) => {
`
: [];
- // Orphaned reports — their pin is gone, so the trail is moot. If the pins
+ // Orphaned reports - their pin is gone, so the trail is moot. If the pins
// table itself is absent, every report is an orphan, so purge them all.
let reapedReports = [];
if (reports) {
@@ -103,12 +103,12 @@ export default wrapCron(async (req, res) => {
: await sql`DELETE FROM irl_pin_reports RETURNING id`;
}
- // Interactions — the location trail. Two sweeps, both existence-guarded so a
+ // Interactions - the location trail. Two sweeps, both existence-guarded so a
// fresh DB never 500s:
- // a. orphaned — the pin is gone, so the encounter record is moot (mirrors the
+ // a. orphaned - the pin is gone, so the encounter record is moot (mirrors the
// report orphan sweep). With no pins table at all, every interaction is an
// orphan, so purge them all.
- // b. aged-out — older than the retention window regardless of pin state, so a
+ // b. aged-out - older than the retention window regardless of pin state, so a
// permanent pin's trail can't accumulate forever.
// A single re-run after a clean sweep deletes nothing new (idempotent): both
// predicates are empty once the table holds only live, in-window rows.
@@ -131,10 +131,10 @@ export default wrapCron(async (req, res) => {
// World Lines (proof-of-presence AR quests) + their presence proofs. A World Line
// always carries an expiry (creator-bounded, ≤ 90 days), so it's reaped one day past
- // it — the same grace as anon pins. A presence proof is the visitor's ownable, coarse
+ // it - the same grace as anon pins. A presence proof is the visitor's ownable, coarse
// "I was there" collectible: it carries only a ~1.1 km cell + a salted completer hash
// (never a coordinate, never a raw device token), so it is NOT a precise location
- // trail to age out — instead it lives as long as its quest and is cascade-deleted the
+ // trail to age out - instead it lives as long as its quest and is cascade-deleted the
// moment the quest is gone, plus an orphan sweep for any proof whose quest vanished.
// Both are existence-guarded so a fresh DB never 500s.
let reapedWorldLines = [];
@@ -156,10 +156,10 @@ export default wrapCron(async (req, res) => {
: await sql`DELETE FROM irl_presence_proofs RETURNING id`;
}
- // Usage-analytics events (api/_lib/irl-analytics.js) — coarse telemetry
+ // Usage-analytics events (api/_lib/irl-analytics.js) - coarse telemetry
// (geocell7 + a hashed device prefix, never a raw coordinate or token) with
// no FK to irl_pins by design: a pin can expire while its historical placement
- // trend stays queryable. Still bounded like every other passive trail here —
+ // trend stays queryable. Still bounded like every other passive trail here -
// aged out at 90 days regardless of pin state.
let reapedEvents = [];
if (events) {
@@ -182,7 +182,7 @@ export default wrapCron(async (req, res) => {
// Per-run telemetry (task 14): one structured line every run so the sweep is
// observable and a reaper that silently stopped deleting (or started deleting
- // far too much) is diagnosable from the logs. No PII — counts only.
+ // far too much) is diagnosable from the logs. No PII - counts only.
console.log('[irl-reap] swept', { ...counts, total, ts: new Date().toISOString() });
// Anomalous-spike alert. A run far above steady state is surfaced to ops once
@@ -192,7 +192,7 @@ export default wrapCron(async (req, res) => {
if (isReapSpike(counts)) {
sendOpsAlert(
'IRL reaper spike',
- `The IRL reaper deleted ${total} rows in one run (pins ${counts.pins}, reports ${counts.reports}, interactions ${counts.interactions}, worldLines ${counts.worldLines}, proofs ${counts.proofs}, events ${counts.events}) — above the ${REAP_SPIKE_THRESHOLD} anomaly threshold. Possible mass-expiry, backfill, or delete bug.`,
+ `The IRL reaper deleted ${total} rows in one run (pins ${counts.pins}, reports ${counts.reports}, interactions ${counts.interactions}, worldLines ${counts.worldLines}, proofs ${counts.proofs}, events ${counts.events}) - above the ${REAP_SPIKE_THRESHOLD} anomaly threshold. Possible mass-expiry, backfill, or delete bug.`,
{ signature: `irl-reap:spike:${Math.floor(Date.now() / 3_600_000)}` },
);
}
diff --git a/api/cron/kol-tracker-refresh.js b/api/cron/kol-tracker-refresh.js
index 254f079a0..65417dba7 100644
--- a/api/cron/kol-tracker-refresh.js
+++ b/api/cron/kol-tracker-refresh.js
@@ -1,7 +1,7 @@
-// GET/POST /api/cron/kol-tracker-refresh — prewarm the KOL Tracker's caches.
+// GET/POST /api/cron/kol-tracker-refresh - prewarm the KOL Tracker's caches.
//
// The tracker (src/kol/tracker.js) computes P&L live per request but caches the
-// X follower/avatar lookup for 15 minutes (src/kol/x-profile.js) — the free X API
+// X follower/avatar lookup for 15 minutes (src/kol/x-profile.js) - the free X API
// tier's rate limit (75 user lookups/15min) can't absorb every page load hitting
// it cold. Running this every 10 minutes keeps that cache warm so a visitor's
// request never blocks on (or exhausts) the X API budget.
diff --git a/api/cron/launcher-claimer.js b/api/cron/launcher-claimer.js
index 5846c9290..4ddda8aab 100644
--- a/api/cron/launcher-claimer.js
+++ b/api/cron/launcher-claimer.js
@@ -1,5 +1,5 @@
// @ts-check
-// GET/POST /api/cron/launcher-claimer — auto-claim pump.fun creator fees from global
+// GET/POST /api/cron/launcher-claimer - auto-claim pump.fun creator fees from global
// launcher runs. Fires every 5 minutes via Vercel cron. For each minted coin in
// launcher_runs that has accumulated >= CLAIM_THRESHOLD_SOL in creator fees and hasn't
// been claimed in the last 24 hours:
@@ -9,7 +9,7 @@
//
// This closes the creator-fee loop: launch → creator fees accrue → claim → record.
// buyback_sol records the buyback-earmarked share of those CREATOR fees (the run's
-// buyback_bps) for revenue tracking — it is NOT a transfer made here. The on-chain
+// buyback_bps) for revenue tracking - it is NOT a transfer made here. The on-chain
// $THREE-aligned buy pressure for these coins comes from the buyback_bps binding baked
// into each launch (handleLaunchAgent → PumpAgent.create), which routes a share of TRADE
// fees into the coin's on-chain buyback vault; the hourly run-buyback cron
@@ -30,7 +30,7 @@ const MAX_PER_TICK = 20;
let _schemaDone = false;
async function ensureSchema() {
if (_schemaDone) return;
- // Idempotent — launcher-engine.js creates the same table on runLauncherTick().
+ // Idempotent - launcher-engine.js creates the same table on runLauncherTick().
// Duplicated here so the claimer works even when the engine hasn't ticked yet.
await sql`
create table if not exists launcher_claims (
@@ -106,7 +106,7 @@ async function processMint(run, token) {
return { runId, status: 'below-threshold', claimableSol };
}
- // 2. Claim — the agent signs its own fee claim (same identity that created the coin).
+ // 2. Claim - the agent signs its own fee claim (same identity that created the coin).
const claimRes = await agentFetch(token, '/api/pump/collect-creator-fee-agent', {
method: 'POST',
headers: { 'content-type': 'application/json' },
@@ -120,7 +120,7 @@ async function processMint(run, token) {
// Fall back to the pre-claim claimable figure if the node couldn't be sampled,
// so the recorded revenue is never silently zeroed (the prior code read a
// non-existent `lamports`/`sig` field, storing 0 SOL + a null signature on
- // every claim — defeating the revenue rollup and the 24h dedup guard).
+ // every claim - defeating the revenue rollup and the 24h dedup guard).
const claimSig = claimData.signature ?? claimData.sig ?? null;
const claimedLamports = Number(claimData.lamports ?? Math.round(claimableSol * 1e9));
const claimedSol = claimedLamports / 1e9;
diff --git a/api/cron/launcher-tick.js b/api/cron/launcher-tick.js
index 9e685f937..5ad6e323f 100644
--- a/api/cron/launcher-tick.js
+++ b/api/cron/launcher-tick.js
@@ -1,8 +1,8 @@
// @ts-check
-// GET/POST /api/cron/launcher-tick — drives one tick of the autonomous coin
+// GET/POST /api/cron/launcher-tick - drives one tick of the autonomous coin
// launcher engine (api/_lib/launcher-engine.js). The seeded global row ships LIVE
// (enabled, real, with a standing dev buy), so pool agents mint pump.fun coins
-// riding live cultural narratives on a cadence — the same real on-chain path a
+// riding live cultural narratives on a cadence - the same real on-chain path a
// human owner uses. Still inert for any scope whose launcher_config row is
// disabled, and bounded by per-launch/daily SOL caps, an hourly ceiling, the
// cadence gate, and the circuit breaker. With no master wallet funded, each tick
diff --git a/api/cron/leaderboard-rollup.js b/api/cron/leaderboard-rollup.js
index 661387ab7..2f1fce677 100644
--- a/api/cron/leaderboard-rollup.js
+++ b/api/cron/leaderboard-rollup.js
@@ -1,13 +1,13 @@
-// GET /api/cron/leaderboard-rollup — daily top-10 badge sweep for the
+// GET /api/cron/leaderboard-rollup - daily top-10 badge sweep for the
// cross-surface leaderboard (prompt 06 of the user-value pack).
//
-// The leaderboard itself (GET /api/leaderboard/unified) is read live — none of
+// The leaderboard itself (GET /api/leaderboard/unified) is read live - none of
// its five metrics need a rollup table, the underlying queries are cheap
// aggregates the same way /api/walk/leaderboard's all-time window already is.
// The ONE thing that genuinely needs a daily cadence is the "top10_<metric>"
// badge: a placement earned today shouldn't quietly stop being true if the
// user's rank slips tomorrow, so it has to be captured at a point in time
-// rather than recomputed live. This cron is that point in time — once daily,
+// rather than recomputed live. This cron is that point in time - once daily,
// walk the top 10 of each metric and award the badge to whoever is there right
// now. Idempotent (user_badges is unique on user_id+code), so a user who holds
// top-10 for a week earns the badge once, on day one.
diff --git a/api/cron/mirror-fanout.js b/api/cron/mirror-fanout.js
index f1a6aa929..8131c817d 100644
--- a/api/cron/mirror-fanout.js
+++ b/api/cron/mirror-fanout.js
@@ -1,4 +1,4 @@
-// GET /api/cron/mirror-fanout — drive the custodial copy-trade (mirror) engine.
+// GET /api/cron/mirror-fanout - drive the custodial copy-trade (mirror) engine.
//
// For every active follow edge whose leader has made a NEW confirmed trade since
// the edge's cursor, size the trade for the follower and execute it through the
diff --git a/api/cron/news-archive-append.js b/api/cron/news-archive-append.js
index 394bc1981..59704f4cd 100644
--- a/api/cron/news-archive-append.js
+++ b/api/cron/news-archive-append.js
@@ -1,15 +1,15 @@
-// GET /api/cron/news-archive-append — hourly continuous archiver for the
+// GET /api/cron/news-archive-append - hourly continuous archiver for the
// crypto-news corpus on gs://three-ws-news-archive.
//
// The recovered historical archive ends at 2025-12; this cron keeps it
// current by appending the live aggregator's articles (api/_lib/news.js,
// the full publisher registry) to the current month's JSONL, in the exact enriched
// schema the corpus already uses. Records are content-addressed (16-hex id
-// of the link), so appends are idempotent — an article seen by ten cron
+// of the link), so appends are idempotent - an article seen by ten cron
// runs lands exactly once.
//
// Writes go through the GCS JSON API with the platform's own credentials
-// (api/_lib/gcp-auth.js — GCP_SERVICE_ACCOUNT_JSON or the Cloud Run runtime
+// (api/_lib/gcp-auth.js - GCP_SERVICE_ACCOUNT_JSON or the Cloud Run runtime
// SA, which holds roles/storage.objectAdmin on the bucket) and are guarded
// with x-goog-if-generation-match so two overlapping runs can't clobber
// each other; the loser retries next hour.
@@ -65,7 +65,7 @@ async function gcsPutObject(token, name, body, generation, contentType) {
return resp.json();
}
-// ── Record conversion — live article → enriched archive schema ──────────────
+// ── Record conversion - live article → enriched archive schema ──────────────
function detectLanguage(title) {
if (/[぀-ヿ]/.test(title)) return 'ja'; // hiragana/katakana
@@ -109,7 +109,7 @@ function toArchiveRecord(a, marketContext, nowIso) {
};
}
-// Market context at capture time — real values or null, never fabricated.
+// Market context at capture time - real values or null, never fabricated.
async function currentMarketContext() {
try {
const [global, fng] = await Promise.all([
@@ -154,7 +154,7 @@ export default wrapCron(async (req, res) => {
let token = null;
if (!dryRun) token = await getGcpAccessToken();
- // Live sweep across every source — the aggregator serves from its
+ // Live sweep across every source - the aggregator serves from its
// per-source cache, so this is one bounded fan-out at most. The limit must
// exceed the whole live corpus (~3k across 159 sources): anything the slice
// drops here is silently never archived, and its permalink dies when the
@@ -164,7 +164,7 @@ export default wrapCron(async (req, res) => {
return json(res, 200, { ok: true, month, appended: 0, note: 'aggregator returned no articles' });
}
- // Bucket each article into ITS publication month — the same month its
+ // Bucket each article into ITS publication month - the same month its
// permalink (/markets/news/<YYYY-MM>/<id>) points at. Archiving a late-June
// story into the July file would strand its canonical URL forever. One
// month of grace covers boundary stragglers; anything older is feed
@@ -195,7 +195,7 @@ export default wrapCron(async (req, res) => {
try {
seen.add(JSON.parse(line).id);
} catch {
- // malformed line — leave it in place, it just can't dedupe
+ // malformed line - leave it in place, it just can't dedupe
}
}
alreadyArchived += seen.size;
diff --git a/api/cron/oracle-digest.js b/api/cron/oracle-digest.js
index c9874af87..a0d73302e 100644
--- a/api/cron/oracle-digest.js
+++ b/api/cron/oracle-digest.js
@@ -1,4 +1,4 @@
-// GET /api/cron/oracle-digest — daily Oracle conviction digest via Telegram.
+// GET /api/cron/oracle-digest - daily Oracle conviction digest via Telegram.
//
// Runs once daily (08:00 UTC). Three lanes:
//
@@ -77,7 +77,7 @@ async function followedAgentStats(agentIds, network) {
function buildFollowerMessage(follower, agentStats, coins) {
const agentList = follower.agents.map((a) => esc(a.agent_name || 'Agent')).join(', ');
const lines = [
- `🔮 <b>Oracle daily digest — agents you follow</b>`,
+ `🔮 <b>Oracle daily digest - agents you follow</b>`,
`Following: ${esc(agentList)}`,
``,
];
@@ -231,7 +231,7 @@ function buildMessage(watch, stats, coins) {
const agentName = esc(watch.agent_name || 'Your agent');
const lines = [
- `🔮 <b>Oracle daily digest — ${agentName}</b>`,
+ `🔮 <b>Oracle daily digest - ${agentName}</b>`,
armedLabel,
``,
];
diff --git a/tests/api/launcher-tick-cron.test.js b/tests/api/launcher-tick-cron.test.js
new file mode 100644
index 000000000..20b752f24
--- /dev/null
+++ b/tests/api/launcher-tick-cron.test.js
@@ -0,0 +1,80 @@
+// api/cron/launcher-tick.js: the thin cron wrapper over the launcher engine.
+//
+// The handler is deliberately small (method gate, cron auth, one engine call),
+// which makes its contract easy to regress silently: a dropped auth check or a
+// method the engine never expected would slip through unnoticed. These tests
+// pin the gate behavior plus the pass-through of the engine's tick result, and
+// the wrapped 5xx when the engine throws (the response must stay a JSON error,
+// never a stack trace).
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const runLauncherTick = vi.fn();
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+vi.mock('../../api/_lib/launcher-engine.js', () => ({ runLauncherTick }));
+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/launcher-tick.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/launcher-tick', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ runLauncherTick.mockReset();
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ vi.restoreAllMocks();
+});
+
+describe('GET/POST /api/cron/launcher-tick', () => {
+ it('rejects a method it does not serve', async () => {
+ expect((await call('DELETE')).statusCode).toBe(405);
+ expect(runLauncherTick).not.toHaveBeenCalled();
+ });
+
+ it('rejects a bad cron secret', async () => {
+ expect((await call('GET', 'Bearer wrong')).statusCode).toBe(401);
+ expect(runLauncherTick).not.toHaveBeenCalled();
+ });
+
+ it('passes the engine tick result through as the 200 body', async () => {
+ const tick = { ok: true, scopes: 1, results: [{ ok: true, scope: 'global', skipped: 'cadence gate' }] };
+ runLauncherTick.mockResolvedValue(tick);
+ const res = await call('POST');
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual(tick);
+ expect(runLauncherTick).toHaveBeenCalledTimes(1);
+ });
+
+ it('a throwing engine surfaces as a JSON 500, not a stack trace', async () => {
+ runLauncherTick.mockRejectedValue(new Error('boom: /workspaces/secret/path'));
+ const res = await call();
+ expect(res.statusCode).toBe(500);
+ expect(res.body.error).toBe('internal_error');
+ // The internal message (which can carry file paths) must not leak.
+ expect(JSON.stringify(res.body)).not.toContain('boom');
+ });
+});
diff --git a/tests/api/leaderboard-rollup-cron.test.js b/tests/api/leaderboard-rollup-cron.test.js
new file mode 100644
index 000000000..72ba73e81
--- /dev/null
+++ b/tests/api/leaderboard-rollup-cron.test.js
@@ -0,0 +1,106 @@
+// api/cron/leaderboard-rollup.js: the daily top-10 badge sweep.
+//
+// The cron walks five metric rankings and awards each top-10 finisher a
+// point-in-time badge. The load-bearing behaviors pinned here:
+// - auth + method gating (it is a cron, not a public read),
+// - every metric's top-10 user gets exactly one unlockBadge call, and the
+// response counts only NEWLY awarded badges (idempotent re-runs award 0),
+// - one metric's query failing must not sink the sweep: the other metrics
+// still run and the failed one reports checked: 0.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+const unlockBadge = vi.fn(async () => true);
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+vi.mock('../../api/_lib/streaks.js', () => ({
+ unlockBadge,
+ BADGES: { TOP10: (metric) => `top10_${metric}` },
+}));
+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/leaderboard-rollup.js');
+
+const METRICS = ['creations', 'remixes_received', 'launches', 'followers', 'walk_distance'];
+
+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/leaderboard-rollup', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+ unlockBadge.mockReset();
+ unlockBadge.mockResolvedValue(true);
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ vi.restoreAllMocks();
+});
+
+describe('GET /api/cron/leaderboard-rollup', () => {
+ it('rejects a method it does not serve', async () => {
+ expect((await call('POST')).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('awards a badge per top-10 user per metric and reports the counts', async () => {
+ for (const _ of METRICS) sqlMock.mockResolvedValueOnce([{ user_id: 'u1' }, { user_id: 'u2' }]);
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ for (const metric of METRICS) {
+ expect(res.body.awarded[metric]).toEqual({ checked: 2, newlyAwarded: 2 });
+ }
+ expect(unlockBadge).toHaveBeenCalledTimes(METRICS.length * 2);
+ expect(unlockBadge).toHaveBeenCalledWith('u1', 'top10_creations', { metric: 'creations' });
+ expect(unlockBadge).toHaveBeenCalledWith('u2', 'top10_walk_distance', { metric: 'walk_distance' });
+ });
+
+ it('an idempotent re-run (badge already held) counts zero new awards', async () => {
+ sqlMock.mockResolvedValueOnce([{ user_id: 'u1' }]);
+ unlockBadge.mockResolvedValue(false);
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.awarded.creations).toEqual({ checked: 1, newlyAwarded: 0 });
+ });
+
+ it('one failing metric degrades to checked: 0 without sinking the sweep', async () => {
+ sqlMock.mockRejectedValueOnce(new Error('relation does not exist'));
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.awarded.creations).toEqual({ checked: 0, newlyAwarded: 0 });
+ // The remaining four metrics still ran.
+ for (const metric of METRICS.slice(1)) {
+ expect(res.body.awarded[metric]).toEqual({ checked: 0, newlyAwarded: 0 });
+ }
+ expect(errSpy).toHaveBeenCalled();
+ errSpy.mockRestore();
+ });
+});
diff --git a/tests/api/oracle-calibrate-cron.test.js b/tests/api/oracle-calibrate-cron.test.js
new file mode 100644
index 000000000..33fb18de6
--- /dev/null
+++ b/tests/api/oracle-calibrate-cron.test.js
@@ -0,0 +1,111 @@
+// api/cron/oracle-calibrate.js: conviction-band calibration rollup.
+//
+// Pins the math that drives the sniper optimizer's Rule O: a band's correction
+// factor is observed win rate / predicted rate, computed ONLY once the band has
+// MIN_BAND_SAMPLE real closed trades, and clamped to [0.7, 1.3] so a thin or
+// extreme sample can never swing entries wildly. Also pins the wrapped 5xx when
+// the join query itself fails.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+
+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 } = await import('../../api/cron/oracle-calibrate.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-calibrate', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ vi.restoreAllMocks();
+});
+
+describe('GET/POST /api/cron/oracle-calibrate', () => {
+ 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('empty fleet history yields five zero-sample bands at the no-op factor', async () => {
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body.traded_scored_mints).toBe(0);
+ expect(res.body.bands).toHaveLength(5);
+ for (const band of res.body.bands) {
+ expect(band).toEqual({ band: band.band, samples: 0, observed_rate: null, correction_factor: 1 });
+ }
+ // 1 select + 5 upserts (one per band).
+ expect(sqlMock).toHaveBeenCalledTimes(6);
+ });
+
+ it('a confident winning band computes factor = observed / predicted', async () => {
+ // Five closed winning trades scored 90: predicted 0.9, observed 1.0.
+ sqlMock.mockResolvedValueOnce(
+ Array.from({ length: 5 }, () => ({ score: 90, win: 1, pnl_pct: 10 })),
+ );
+ const res = await call();
+ const band = res.body.bands.find((b) => b.band === '85-100');
+ expect(band.samples).toBe(5);
+ expect(band.observed_rate).toBe(1);
+ expect(band.correction_factor).toBeCloseTo(1 / 0.9, 2);
+ });
+
+ it('clamps the factor at 0.7 for a band that always loses', async () => {
+ sqlMock.mockResolvedValueOnce(
+ Array.from({ length: 5 }, () => ({ score: 90, win: 0, pnl_pct: -20 })),
+ );
+ const res = await call();
+ const band = res.body.bands.find((b) => b.band === '85-100');
+ expect(band.observed_rate).toBe(0);
+ expect(band.correction_factor).toBe(0.7);
+ });
+
+ it('a thin band stays at the no-op factor regardless of outcomes', async () => {
+ sqlMock.mockResolvedValueOnce([{ score: 90, win: 1, pnl_pct: 50 }]);
+ const res = await call();
+ const band = res.body.bands.find((b) => b.band === '85-100');
+ expect(band.samples).toBe(1);
+ expect(band.correction_factor).toBe(1);
+ });
+
+ it('a failed join query surfaces as a JSON 500, not a stack trace', async () => {
+ sqlMock.mockRejectedValueOnce(new Error('relation agent_sniper_positions does not exist'));
+ const res = await call();
+ expect(res.statusCode).toBe(500);
+ expect(res.body.error).toBe('internal_error');
+ expect(JSON.stringify(res.body)).not.toContain('agent_sniper_positions');
+ });
+});
diff --git a/tests/api/oracle-realized-labels-cron.test.js b/tests/api/oracle-realized-labels-cron.test.js
new file mode 100644
index 000000000..96b0ea1bb
--- /dev/null
+++ b/tests/api/oracle-realized-labels-cron.test.js
@@ -0,0 +1,86 @@
+// api/cron/oracle-realized-labels.js: realized-PnL ground-truth labels.
+//
+// The cron derives, per mint the fleet really traded, whether the net realized
+// outcome was a win and upserts it for the Oracle learner. Pinned here:
+// - auth + method gating,
+// - the win/loss rollup counts rows by their realized_win flag,
+// - a failed upsert surfaces as a wrapped JSON 500, never a stack trace.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+
+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 } = await import('../../api/cron/oracle-realized-labels.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-realized-labels', headers: { authorization: auth } };
+ return handler(req, res).then(() => res);
+}
+
+beforeEach(() => {
+ process.env.CRON_SECRET = 'test-cron-secret';
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+});
+afterEach(() => {
+ delete process.env.CRON_SECRET;
+ vi.restoreAllMocks();
+});
+
+describe('GET/POST /api/cron/oracle-realized-labels', () => {
+ 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('no closed trades labels nothing', async () => {
+ const res = await call();
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({ ok: true, labeled: 0, wins: 0, losses: 0 });
+ });
+
+ it('rolls up labeled mints into wins and losses by the realized flag', async () => {
+ sqlMock.mockResolvedValueOnce([
+ { mint: 'a', realized_win: 1 },
+ { mint: 'b', realized_win: 0 },
+ { mint: 'c', realized_win: 1 },
+ ]);
+ const res = await call('POST');
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toEqual({ ok: true, labeled: 3, wins: 2, losses: 1 });
+ });
+
+ it('a failed upsert surfaces as a JSON 500, not a stack trace', async () => {
+ sqlMock.mockRejectedValueOnce(new Error('relation oracle_realized_outcomes does not exist'));
+ const res = await call();
+ expect(res.statusCode).toBe(500);
+ expect(res.body.error).toBe('internal_error');
+ expect(JSON.stringify(res.body)).not.toContain('oracle_realized_outcomes');
+ });
+});