Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(event-markets): auto-open a Who wins market for every Arena tournament, platform event, build round and bounty, with late entrants, a skip log, an outbox row and an admin view
nirholas458ea0f18c4f
diff --git a/api/_lib/event-markets/auto-open.js b/api/_lib/event-markets/auto-open.jsnew file mode 100644index 000000000..24dfd6ed8--- /dev/null+++ b/api/_lib/event-markets/auto-open.js@@ -0,0 +1,193 @@+// Auto-open: turn "an event exists" into "a market exists", with no human in the loop.+//+// For every event an adapter lists (sources/), this opens one market whose outcomes+// are the entrants, then keeps it in step with the event until picks lock:+//+// no market yet open one when the event has a defined winner, at least+// minEntrants entrants, and a lock time still in the future.+// Otherwise record why in event_market_skips.+// open, pre-lock add any entrant that joined since; existing outcomes and the+// picks on them are never touched.+// locked or later never change outcomes.+//+// Idempotent on (source_kind, source_ref): the unique index is the guarantee, the+// lookup is the fast path. Opening writes an `event_market.opened` row to+// event_market_outbox in the same pass so announcements read it, never get called.++import { createHash } from 'node:crypto';+import { sql } from '../db.js';+import { eventMarketsAutoOpen } from './config-auto-open.js';+import { SOURCES } from './sources/index.js';+import { createMarket, EventMarketError, slugify } from './index.js';++export const OPENED_KIND = 'event_market.opened';++/** "Who wins X?" capped to the 140-character title limit. */+export function questionTitle(eventTitle) {+ const name = String(eventTitle || '').replace(/\s+/g, ' ').trim();+ const room = 140 - 'Who wins ?'.length;+ return `Who wins ${name.length > room ? `${name.slice(0, room - 3).trimEnd()}...` : name}?`;+}++/** Deterministic slug: readable title plus a hash of the event identity. */+export function marketSlug(event) {+ const tag = createHash('sha1').update(`${event.sourceKind}:${event.sourceRef}`).digest('hex').slice(0, 6);+ return `${slugify(`who wins ${event.title}`).slice(0, 56).replace(/-+$/, '')}-${tag}`;+}++/**+ * Decide what the cron does with one event that has no market yet.+ * Pure: returns { action: 'open' } or { action: 'skip', reason, detail }.+ */+export function planOpen(event, now, { force = false, cfg = eventMarketsAutoOpen } = {}) {+ if (!event.winnerDefined) {+ return { action: 'skip', reason: 'no_defined_winner', detail: event.noWinnerReason || 'the event has no defined winner' };+ }+ if (event.entrants.length < cfg.minEntrants) {+ return {+ action: 'skip',+ reason: 'too_few_entrants',+ detail: `${event.entrants.length} of ${cfg.minEntrants} entrants needed`,+ };+ }+ if (!force && event.lockAt <= now) {+ return { action: 'skip', reason: 'lock_passed', detail: `picks would have closed ${event.lockAt.toISOString()}` };+ }+ return { action: 'open' };+}++async function recordSkip(event, plan) {+ await sql`+ insert into event_market_skips (source_kind, source_ref, title, reason, detail)+ values (${event.sourceKind}, ${event.sourceRef}, ${event.title}, ${plan.reason}, ${plan.detail})+ on conflict (source_kind, source_ref) do update+ set title = excluded.title, reason = excluded.reason, detail = excluded.detail,+ last_seen = now(), seen_count = event_market_skips.seen_count + 1`;+}++async function clearSkip(event) {+ await sql`delete from event_market_skips where source_kind = ${event.sourceKind} and source_ref = ${event.sourceRef}`;+}++async function findBySource(event) {+ const [row] = await sql`+ select id, slug, status, locks_at from event_markets+ where source_kind = ${event.sourceKind} and source_ref = ${event.sourceRef}`;+ return row || null;+}++/** Add entrants a pre-lock market does not have yet. Returns how many were added. */+async function addLateEntrants(marketId, event) {+ const have = await sql`select ref_kind, ref_id from event_market_outcomes where market_id = ${marketId}`;+ const known = new Set(have.map((o) => `${o.ref_kind}:${o.ref_id}`));+ const room = eventMarketsAutoOpen.maxOutcomes - have.length;+ const fresh = event.entrants.filter((e) => !known.has(`${e.refKind}:${e.refId}`)).slice(0, Math.max(room, 0));+ let added = 0;+ for (const e of fresh) {+ const rows = await sql`+ insert into event_market_outcomes (market_id, label, ref_kind, ref_id, image_url, position)+ values (${marketId}, ${String(e.label).slice(0, 80)}, ${e.refKind}, ${String(e.refId)}, ${e.imageUrl ?? null},+ (select coalesce(max(position), -1) + 1 from event_market_outcomes where market_id = ${marketId}))+ on conflict (market_id, ref_kind, ref_id) where ref_id is not null do nothing+ returning id`;+ added += rows.length;+ }+ return added;+}++function toOutcome(e) {+ return { label: String(e.label).trim().slice(0, 80), ref_kind: e.refKind, ref_id: e.refId, image_url: e.imageUrl ?? null };+}++async function emitOpened(market, event) {+ await sql`+ insert into event_market_outbox (kind, market_id, payload)+ values (${OPENED_KIND}, ${market.id}, ${JSON.stringify({+ slug: market.slug,+ title: market.title,+ source_kind: event.sourceKind,+ source_ref: event.sourceRef,+ locks_at: market.locks_at,+ resolves_at: market.resolves_at,+ outcome_count: market.outcomes.length,+ })}::jsonb)+ on conflict (kind, market_id) do nothing`;+}++/**+ * Open the market for one event, or sync an existing one.+ * @returns {Promise<{ result: 'opened'|'synced'|'unchanged'|'skipped', slug?: string, added?: number, reason?: string }>}+ */+export async function openForEvent(event, { now = new Date(), force = false, locksAt = null } = {}) {+ const existing = await findBySource(event);+ if (existing) {+ await clearSkip(event);+ if (existing.status === 'open' && new Date(existing.locks_at) > now) {+ const added = await addLateEntrants(existing.id, event);+ return { result: added ? 'synced' : 'unchanged', slug: existing.slug, added };+ }+ return { result: 'unchanged', slug: existing.slug, added: 0 };+ }++ const plan = planOpen(event, now, { force });+ if (plan.action === 'skip') {+ await recordSkip(event, plan);+ return { result: 'skipped', reason: plan.reason, detail: plan.detail };+ }++ const lockTime = locksAt+ || (event.lockAt > now ? event.lockAt : new Date(now.getTime() + eventMarketsAutoOpen.manualLockMinutes * 60_000));+ const resolvesAt = event.resolvesAt >= lockTime ? event.resolvesAt : lockTime;+ let market;+ try {+ market = await createMarket({+ title: questionTitle(event.title),+ slug: marketSlug(event),+ source_kind: event.sourceKind,+ source_ref: event.sourceRef,+ status: 'open',+ opens_at: now.toISOString(),+ locks_at: lockTime.toISOString(),+ resolves_at: resolvesAt.toISOString(),+ resolution_rule: { ...event.rule, starts_at: event.startsAt.toISOString(), ends_at: event.endsAt.toISOString() },+ outcomes: event.entrants.slice(0, eventMarketsAutoOpen.maxOutcomes).map(toOutcome),+ });+ } catch (err) {+ if (err instanceof EventMarketError && err.code === 'market_exists_for_source') {+ // A concurrent tick opened it between our lookup and our insert.+ const raced = await findBySource(event);+ if (raced) return { result: 'unchanged', slug: raced.slug, added: 0 };+ }+ throw err;+ }+ await emitOpened(market, event);+ await clearSkip(event);+ return { result: 'opened', slug: market.slug };+}++/** One pass over every source. A failing source is reported, never fatal to the rest. */+export async function runAutoOpen({ now = new Date(), sources = SOURCES } = {}) {+ const report = { opened: [], synced: [], skipped: [], errors: [], seen: 0 };+ for (const source of sources) {+ let events;+ try {+ events = await source.listEvents(now);+ } catch (err) {+ report.errors.push({ source_kind: source.sourceKind, message: err?.message || String(err) });+ continue;+ }+ for (const event of events) {+ report.seen += 1;+ try {+ const r = await openForEvent(event, { now });+ const row = { source_kind: event.sourceKind, source_ref: event.sourceRef, title: event.title, ...r };+ if (r.result === 'opened') report.opened.push(row);+ else if (r.result === 'synced') report.synced.push(row);+ else if (r.result === 'skipped') report.skipped.push(row);+ } catch (err) {+ report.errors.push({ source_kind: event.sourceKind, source_ref: event.sourceRef, message: err?.message || String(err) });+ }+ }+ }+ return report;+}diff --git a/api/_lib/event-markets/config-auto-open.js b/api/_lib/event-markets/config-auto-open.jsnew file mode 100644index 000000000..2ea7cab4c--- /dev/null+++ b/api/_lib/event-markets/config-auto-open.js@@ -0,0 +1,13 @@+// Auto-open tunables. One source of truth: data/event-market-autoopen.json.++import { readFileSync } from 'node:fs';++const raw = JSON.parse(readFileSync(new URL('../../../data/event-market-autoopen.json', import.meta.url), 'utf8'));++export const eventMarketsAutoOpen = Object.freeze({+ minEntrants: Number(raw.minEntrants),+ maxOutcomes: Number(raw.maxOutcomes),+ lockFractions: Object.freeze({ ...raw.lockFractions }),+ bountyResolveGraceDays: Number(raw.bountyResolveGraceDays),+ manualLockMinutes: Number(raw.manualLockMinutes),+});diff --git a/api/_lib/event-markets/sources/arena-tournaments.js b/api/_lib/event-markets/sources/arena-tournaments.jsnew file mode 100644index 000000000..69672ae81--- /dev/null+++ b/api/_lib/event-markets/sources/arena-tournaments.js@@ -0,0 +1,56 @@+// Arena tournaments (api/_lib/migrations/20260623120000_tournaments.sql): upcoming and+// live trading tournaments. Entrants are the active, public agents in+// tournament_entries. The winner is the entry ranked first at settlement.++import { sql } from '../../db.js';+import { eventMarketsAutoOpen } from '../config-auto-open.js';+import { agentImage, fractionOf } from './shared.js';++export const sourceKind = 'arena_tournament';++export async function listEvents() {+ const tournaments = await sql`+ select id, name, starts_at, ends_at from tournaments+ where status in ('upcoming', 'live') and ends_at > now()+ order by starts_at`;+ if (!tournaments.length) return [];+ const entries = await sql`+ select e.tournament_id, i.id as agent_id, i.name,+ a.thumbnail_key as avatar_thumbnail_key, a.visibility as avatar_visibility+ from tournament_entries e+ join agent_identities i on i.id = e.agent_id and i.deleted_at is null and i.is_public = true+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null+ where e.status = 'active' and e.tournament_id = any(${tournaments.map((t) => t.id)}::uuid[])+ order by e.joined_at`;+ const by = new Map();+ for (const r of entries) {+ if (!by.has(r.tournament_id)) by.set(r.tournament_id, []);+ by.get(r.tournament_id).push({+ label: r.name,+ refKind: 'agent',+ refId: r.agent_id,+ imageUrl: agentImage(r),+ });+ }+ const fraction = eventMarketsAutoOpen.lockFractions.arena_tournament;+ return tournaments.map((t) => {+ const startsAt = new Date(t.starts_at);+ const endsAt = new Date(t.ends_at);+ return {+ sourceKind,+ sourceRef: t.id,+ title: t.name,+ startsAt,+ endsAt,+ lockAt: fractionOf(startsAt, endsAt, fraction),+ resolvesAt: endsAt,+ entrants: by.get(t.id) || [],+ rule: {+ type: 'tournament_final_rank',+ tournament_id: t.id,+ description: 'Resolves to the agent ranked first on the tournament standings when the tournament closes.',+ },+ winnerDefined: true,+ };+ });+}diff --git a/api/_lib/event-markets/sources/bounties.js b/api/_lib/event-markets/sources/bounties.jsnew file mode 100644index 000000000..fefc2f393--- /dev/null+++ b/api/_lib/event-markets/sources/bounties.js@@ -0,0 +1,51 @@+// Bounty board (bounties / bounty_submissions). Entrants are one submission per+// submitter. The owner picks the winning submission, so the market resolves to+// bounties.winner_submission_id. Picks stay open until the bounty expires.++import { sql } from '../../db.js';+import { eventMarketsAutoOpen } from '../config-auto-open.js';++export const sourceKind = 'bounty';++export async function listEvents() {+ const bounties = await sql`+ select id, title, created_at, expires_at from bounties+ where status = 'open' and deleted_at is null and expires_at > now()+ order by expires_at`;+ if (!bounties.length) return [];+ const subs = await sql`+ select distinct on (bounty_id, user_id) id, bounty_id, username, media_url, media_type+ from bounty_submissions+ where status <> 'rejected' and bounty_id = any(${bounties.map((b) => b.id)}::uuid[])+ order by bounty_id, user_id, created_at`;+ const by = new Map();+ for (const s of subs) {+ if (!by.has(s.bounty_id)) by.set(s.bounty_id, []);+ by.get(s.bounty_id).push({+ label: s.username || `Entry ${by.get(s.bounty_id).length + 1}`,+ refKind: 'project',+ refId: s.id,+ imageUrl: s.media_type === 'image' ? s.media_url : null,+ });+ }+ const graceMs = eventMarketsAutoOpen.bountyResolveGraceDays * 86_400_000;+ return bounties.map((b) => {+ const expiresAt = new Date(b.expires_at);+ return {+ sourceKind,+ sourceRef: b.id,+ title: b.title,+ startsAt: new Date(b.created_at),+ endsAt: expiresAt,+ lockAt: expiresAt,+ resolvesAt: new Date(expiresAt.getTime() + graceMs),+ entrants: by.get(b.id) || [],+ rule: {+ type: 'bounty_winner_submission',+ bounty_id: b.id,+ description: 'Resolves to the entrant whose submission the bounty owner marks as the winner.',+ },+ winnerDefined: true,+ };+ });+}diff --git a/api/_lib/event-markets/sources/build-rounds.js b/api/_lib/event-markets/sources/build-rounds.jsnew file mode 100644index 000000000..7026b34cc--- /dev/null+++ b/api/_lib/event-markets/sources/build-rounds.js@@ -0,0 +1,56 @@+// Build program rounds (program_rounds / program_submissions). Entrants are the+// distinct agents with a live submission. Submissions arrive through the round, so+// picks stay open until submissions close (ends_at) and resolve once judging ends.+// A round with no published judging criteria has no defined winner and is skipped.++import { sql } from '../../db.js';+import { agentImage } from './shared.js';++export const sourceKind = 'build_round';++export async function listEvents() {+ const rounds = await sql`+ select id, slug, title, starts_at, ends_at, judging_ends_at, criteria+ from program_rounds+ where status = 'open' and ends_at > now()+ order by starts_at`;+ if (!rounds.length) return [];+ const subs = await sql`+ select distinct on (s.round_id, s.agent_id)+ s.round_id, i.id as agent_id, i.name,+ a.thumbnail_key as avatar_thumbnail_key, a.visibility as avatar_visibility+ from program_submissions s+ join agent_identities i on i.id = s.agent_id and i.deleted_at is null and i.is_public = true+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null+ where s.status in ('submitted', 'shortlisted', 'winner')+ and s.round_id = any(${rounds.map((r) => r.id)}::uuid[])+ order by s.round_id, s.agent_id, s.created_at`;+ const by = new Map();+ for (const r of subs) {+ if (!by.has(r.round_id)) by.set(r.round_id, []);+ by.get(r.round_id).push({ label: r.name, refKind: 'agent', refId: r.agent_id, imageUrl: agentImage(r) });+ }+ return rounds.map((r) => {+ const startsAt = new Date(r.starts_at);+ const endsAt = new Date(r.ends_at);+ const judged = Array.isArray(r.criteria) && r.criteria.length > 0;+ return {+ sourceKind,+ sourceRef: r.id,+ title: r.title,+ startsAt,+ endsAt,+ lockAt: endsAt,+ resolvesAt: r.judging_ends_at ? new Date(r.judging_ends_at) : endsAt,+ entrants: by.get(r.id) || [],+ rule: {+ type: 'build_round_top_score',+ round_id: r.id,+ slug: r.slug,+ description: 'Resolves to the agent whose submission the judges score highest when judging closes.',+ },+ winnerDefined: judged,+ noWinnerReason: judged ? undefined : 'the round publishes no judging criteria, so no winner can be read from it',+ };+ });+}diff --git a/api/_lib/event-markets/sources/index.js b/api/_lib/event-markets/sources/index.jsnew file mode 100644index 000000000..da5dd2d33--- /dev/null+++ b/api/_lib/event-markets/sources/index.js@@ -0,0 +1,13 @@+// Registry of event sources the auto-open cron reads. Adding a source is one file+// exporting { sourceKind, listEvents } plus one line here.+//+// Not listed on purpose: `launch_cohort` and seasons. No table in this codebase+// records a cohort or season with entrants and a defined winner yet; the day one+// does, its adapter goes here and the cron picks it up with no other change.++import * as arenaTournaments from './arena-tournaments.js';+import * as platformEvent from './platform-event.js';+import * as buildRounds from './build-rounds.js';+import * as bounties from './bounties.js';++export const SOURCES = Object.freeze([arenaTournaments, platformEvent, buildRounds, bounties]);diff --git a/api/_lib/event-markets/sources/platform-event.js b/api/_lib/event-markets/sources/platform-event.jsnew file mode 100644index 000000000..7f97c6561--- /dev/null+++ b/api/_lib/event-markets/sources/platform-event.js@@ -0,0 +1,44 @@+// The live platform event (public/event.json, the `/play` quest line and `/event`+// page). Entrants are the wallets that have completed at least one event quest;+// the winner is the top of the event leaderboard when the event ends.++import { eventConfig } from '../../event-config.js';+import { readEventRecords } from '../../event-leaderboard-store.js';+import { eventMarketsAutoOpen } from '../config-auto-open.js';+import { fractionOf, shortAddress } from './shared.js';++export const sourceKind = 'event_leaderboard';++export async function listEvents(now = new Date()) {+ const event = eventConfig(now.getTime());+ if (!event) return [];+ const endsAt = new Date(event.endsAt);+ if (endsAt <= now) return [];+ const startsAt = new Date(event.startsAt);+ const { records } = await readEventRecords(event.id);+ const entrants = records+ .filter((r) => r.runs > 0)+ .sort((a, b) => a.lastAt - b.lastAt)+ .map((r) => ({+ label: r.name || shortAddress(r.account),+ refKind: 'wallet',+ refId: r.account,+ imageUrl: null,+ }));+ return [{+ sourceKind,+ sourceRef: event.id,+ title: event.name,+ startsAt,+ endsAt,+ lockAt: fractionOf(startsAt, endsAt, eventMarketsAutoOpen.lockFractions.event_leaderboard),+ resolvesAt: endsAt,+ entrants,+ rule: {+ type: 'event_leaderboard_top',+ event_id: event.id,+ description: 'Resolves to the entrant ranked first on the event leaderboard when the event ends.',+ },+ winnerDefined: true,+ }];+}diff --git a/api/_lib/event-markets/sources/shared.js b/api/_lib/event-markets/sources/shared.jsnew file mode 100644index 000000000..93504d5a8--- /dev/null+++ b/api/_lib/event-markets/sources/shared.js@@ -0,0 +1,29 @@+// Helpers every event-source adapter shares. An adapter lists upcoming and live+// events from our own tables and returns them in one normalized shape:+//+// { sourceKind, sourceRef, title, startsAt, endsAt, lockAt, resolvesAt,+// entrants: [{ label, refKind, refId, imageUrl }],+// rule: { type, description, ... },+// winnerDefined, noWinnerReason }+//+// Times are Date objects. `lockAt` is when picks close (documented per adapter in+// docs/event-markets.md); `resolvesAt` is when the winner can be read.++import { thumbnailUrl } from '../../r2.js';++/** Date at `fraction` of the way from `startsAt` to `endsAt`. */+export function fractionOf(startsAt, endsAt, fraction) {+ return new Date(startsAt.getTime() + (endsAt.getTime() - startsAt.getTime()) * fraction);+}++/** Public thumbnail for an agent row joined to its avatar, or null when not public. */+export function agentImage(row) {+ const pub = row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted';+ return row.avatar_thumbnail_key && pub ? thumbnailUrl(row.avatar_thumbnail_key) : null;+}++/** Short stable label for a wallet-shaped id. */+export function shortAddress(id) {+ const s = String(id || '');+ return s.length > 12 ? `${s.slice(0, 4)}...${s.slice(-4)}` : s;+}diff --git a/api/_lib/migrations/20261012000000_event_markets_core.sql b/api/_lib/migrations/20261012000000_event_markets_core.sqlnew file mode 100644index 000000000..d3896006a--- /dev/null+++ b/api/_lib/migrations/20261012000000_event_markets_core.sql@@ -0,0 +1,81 @@+-- Event Markets core: free-to-play prediction markets over our own events.+-- Points only. Nothing here signs, escrows or moves funds.+--+-- event_markets one market per event, a state machine over `status`+-- event_market_outcomes the entrants a pick can back (agent, wallet, project, team)+-- event_market_picks one live pick per account per market+-- event_market_pick_log append-only record of every place/change/withdraw/void+--+-- Later event_market_* migrations add columns and indexes with if not exists, so+-- re-running this file is safe. Logic: api/_lib/event-markets/index.js.++begin;++create table if not exists event_markets (+ id uuid primary key default gen_random_uuid(),+ slug text not null unique,+ title text not null,+ description text,+ source_kind text not null,+ source_ref text,+ status text not null default 'open',+ opens_at timestamptz not null default now(),+ locks_at timestamptz not null,+ resolves_at timestamptz,+ resolution_rule jsonb not null default '{}'::jsonb,+ winner_outcome_id uuid,+ void_reason text,+ created_by uuid references users(id) on delete set null,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint event_markets_status_chk check (status in ('draft','open','locked','resolved','void')),+ constraint event_markets_source_kind_chk check (source_kind in ('arena_tournament','event_leaderboard','launch_cohort','build_round','bounty','custom'))+);+create index if not exists event_markets_status_locks on event_markets (status, locks_at);++create table if not exists event_market_outcomes (+ id uuid primary key default gen_random_uuid(),+ market_id uuid not null references event_markets(id) on delete cascade,+ label text not null,+ ref_kind text,+ ref_id text,+ image_url text,+ position integer not null default 0,+ created_at timestamptz not null default now(),+ constraint event_market_outcomes_ref_kind_chk check (ref_kind is null or ref_kind in ('agent','wallet','project','team'))+);+create index if not exists event_market_outcomes_market on event_market_outcomes (market_id, position);++do $$ begin+ alter table event_markets add constraint event_markets_winner_fk+ foreign key (winner_outcome_id) references event_market_outcomes(id) on delete set null;+exception when duplicate_object then null;+end $$;++create table if not exists event_market_picks (+ id uuid primary key default gen_random_uuid(),+ market_id uuid not null references event_markets(id) on delete cascade,+ outcome_id uuid not null references event_market_outcomes(id) on delete cascade,+ account_id uuid not null references users(id) on delete cascade,+ points integer not null check (points > 0),+ status text not null default 'live',+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint event_market_picks_status_chk check (status in ('live','won','lost','refunded')),+ unique (market_id, account_id)+);+create index if not exists event_market_picks_outcome on event_market_picks (outcome_id);+create index if not exists event_market_picks_account on event_market_picks (account_id, created_at desc);++create table if not exists event_market_pick_log (+ id bigserial primary key,+ market_id uuid not null references event_markets(id) on delete cascade,+ outcome_id uuid not null references event_market_outcomes(id) on delete cascade,+ account_id uuid not null references users(id) on delete cascade,+ points integer not null,+ action text not null check (action in ('place','change','withdraw','void')),+ created_at timestamptz not null default now()+);+create index if not exists event_market_pick_log_market on event_market_pick_log (market_id, id);++commit;diff --git a/api/_lib/migrations/20261012010000_event_market_auto_open.sql b/api/_lib/migrations/20261012010000_event_market_auto_open.sqlnew file mode 100644index 000000000..2d99515e2--- /dev/null+++ b/api/_lib/migrations/20261012010000_event_market_auto_open.sql@@ -0,0 +1,38 @@+-- Event Markets auto-open (brief 04): idempotency guarantees, the skip log and the outbox.+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261012010000_event_market_auto_open.sql+-- Idempotent. Docs: docs/event-markets.md ("Which events get a market").++-- One market per event, one outcome per entrant. Repeated here so the guarantee holds+-- whichever of the core migrations created the tables first.+CREATE UNIQUE INDEX IF NOT EXISTS event_markets_source_uidx+ ON event_markets (source_kind, source_ref) WHERE source_ref IS NOT NULL;+CREATE UNIQUE INDEX IF NOT EXISTS event_market_outcomes_ref_uidx+ ON event_market_outcomes (market_id, ref_kind, ref_id) WHERE ref_id IS NOT NULL;++-- Events the cron looked at and declined, and why, so the owner can see every event+-- that has no market. One row per event; opening a market for it deletes the row.+CREATE TABLE IF NOT EXISTS event_market_skips (+ source_kind text NOT NULL,+ source_ref text NOT NULL,+ title text NOT NULL,+ reason text NOT NULL CHECK (reason IN ('too_few_entrants', 'no_defined_winner', 'lock_passed')),+ detail text,+ first_seen timestamptz NOT NULL DEFAULT now(),+ last_seen timestamptz NOT NULL DEFAULT now(),+ seen_count int NOT NULL DEFAULT 1,+ PRIMARY KEY (source_kind, source_ref)+);++-- Outbox. Features that react to a market (announcement drafts, notifications) read+-- rows from here instead of being called in-process, so they stay independent of+-- this one. `processed_at` belongs to the consumer.+CREATE TABLE IF NOT EXISTS event_market_outbox (+ id bigserial PRIMARY KEY,+ kind text NOT NULL,+ market_id uuid NOT NULL REFERENCES event_markets(id) ON DELETE CASCADE,+ payload jsonb NOT NULL DEFAULT '{}'::jsonb,+ created_at timestamptz NOT NULL DEFAULT now(),+ processed_at timestamptz+);+CREATE UNIQUE INDEX IF NOT EXISTS event_market_outbox_once_uidx ON event_market_outbox (kind, market_id);+CREATE INDEX IF NOT EXISTS event_market_outbox_pending_idx ON event_market_outbox (created_at) WHERE processed_at IS NULL;diff --git a/api/cron/event-markets-open.js b/api/cron/event-markets-open.jsnew file mode 100644index 000000000..23b0b7469--- /dev/null+++ b/api/cron/event-markets-open.js@@ -0,0 +1,18 @@+// GET /api/cron/event-markets-open: opens a market for every event that has none.+//+// Reads the event sources (api/_lib/event-markets/sources/), opens "Who wins X?" with+// the entrants as outcomes, tops up pre-lock markets with late entrants, and logs+// every event it declined to market in event_market_skips. Idempotent: a second tick+// changes nothing. Points only: nothing here can move a token or touch a wallet.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { runAutoOpen } from '../_lib/event-markets/auto-open.js';++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const report = await runAutoOpen();+ return json(res, 200, { ok: report.errors.length === 0, ...report });+});diff --git a/api/ops/event-markets.js b/api/ops/event-markets.jsnew file mode 100644index 000000000..7241d895b--- /dev/null+++ b/api/ops/event-markets.js@@ -0,0 +1,116 @@+// /api/ops/event-markets: the owner's view of Event Markets auto-open.+//+// GET every event the sources list now, with its market (or the reason it has+// none), plus the skip log and the latest markets. Admin session required.+// POST { action: 'open', source_kind, source_ref, locks_in_minutes? }+// open a market for one event by hand: bypasses the lock-time and+// entrant-count skips only when the event still has two entrants and a+// defined winner. A past lock gets a fresh lock window.+// { action: 'void', market_id }+// void a market. Points are a per-market allowance, so nothing is owed back.+//+// Read-only except the two POST actions; points only, nothing here moves funds.++import { cors, json, method, wrap, error, rateLimited, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { requireAdmin } from '../_lib/admin.js';+import { isSameSiteOrigin } from '../_lib/auth.js';+import { SOURCES } from '../_lib/event-markets/sources/index.js';+import { openForEvent, planOpen } from '../_lib/event-markets/auto-open.js';+import { voidMarket, EventMarketError } from '../_lib/event-markets/index.js';+import { sql } from '../_lib/db.js';++export const maxDuration = 30;++async function gatherEvents(now) {+ const events = [];+ const errors = [];+ for (const source of SOURCES) {+ try {+ events.push(...(await source.listEvents(now)));+ } catch (err) {+ errors.push({ source_kind: source.sourceKind, message: err?.message || String(err) });+ }+ }+ return { events, errors };+}++async function report(now) {+ const { events, errors } = await gatherEvents(now);+ const [markets, skips] = await Promise.all([+ sql`select m.id, m.slug, m.title, m.source_kind, m.source_ref, m.status, m.locks_at, m.resolves_at,+ (select count(*)::int from event_market_outcomes o where o.market_id = m.id) as outcome_count,+ (select count(*)::int from event_market_picks p where p.market_id = m.id) as pick_count+ from event_markets m order by m.created_at desc limit 100`,+ sql`select source_kind, source_ref, title, reason, detail, first_seen, last_seen, seen_count+ from event_market_skips order by last_seen desc limit 100`,+ ]);+ const bySource = new Map(markets.map((m) => [`${m.source_kind}:${m.source_ref}`, m]));+ const skipBy = new Map(skips.map((s) => [`${s.source_kind}:${s.source_ref}`, s]));+ return {+ generated_at: now.toISOString(),+ events: events.map((e) => {+ const key = `${e.sourceKind}:${e.sourceRef}`;+ const plan = planOpen(e, now);+ return {+ source_kind: e.sourceKind,+ source_ref: e.sourceRef,+ title: e.title,+ starts_at: e.startsAt,+ ends_at: e.endsAt,+ lock_at: e.lockAt,+ entrant_count: e.entrants.length,+ market: bySource.get(key) || null,+ skip: skipBy.get(key) || null,+ blocker: plan.action === 'skip' ? { reason: plan.reason, detail: plan.detail } : null,+ };+ }),+ markets,+ skips,+ source_errors: errors,+ };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const rl = await limits.authedReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const admin = await requireAdmin(req, res);+ if (!admin) return;++ const now = new Date();+ try {+ if (req.method === 'GET') {+ return json(res, 200, await report(now), { 'cache-control': 'private, no-store' });+ }+ if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site requests are not allowed');+ const body = await readJson(req);++ if (body.action === 'open') {+ const { events } = await gatherEvents(now);+ const event = events.find((e) => e.sourceKind === body.source_kind && e.sourceRef === body.source_ref);+ if (!event) return error(res, 404, 'not_found', 'that event is not listed by any source right now');+ const mins = Number(body.locks_in_minutes);+ const locksAt = Number.isFinite(mins) && mins >= 5 && mins <= 7 * 1440 ? new Date(now.getTime() + mins * 60_000) : null;+ const result = await openForEvent(event, { now, force: true, locksAt });+ if (result.result === 'skipped') return error(res, 409, result.reason, result.detail);+ return json(res, 200, { ok: true, ...result });+ }++ if (body.action === 'void') {+ const voided = await voidMarket(String(body.market_id || ''), 'Voided by an admin');+ return json(res, 200, { ok: true, slug: voided.market.slug, status: voided.market.status, refunded_picks: voided.refunded_picks });+ }++ return error(res, 400, 'validation_error', "action must be 'open' or 'void'");+ } catch (err) {+ if (err instanceof EventMarketError) return error(res, err.status, err.code, err.message);+ if (err?.code === '42P01') {+ return error(res, 503, 'migration_pending', 'Event Markets tables are missing: apply the pending event market migrations (npm run db:status)');+ }+ throw err;+ }+});diff --git a/data/event-market-autoopen.json b/data/event-market-autoopen.jsonnew file mode 100644index 000000000..51c1aeb8a--- /dev/null+++ b/data/event-market-autoopen.json@@ -0,0 +1,10 @@+{+ "minEntrants": 2,+ "maxOutcomes": 64,+ "lockFractions": {+ "arena_tournament": 0.1,+ "event_leaderboard": 0.2+ },+ "bountyResolveGraceDays": 7,+ "manualLockMinutes": 60+}diff --git a/pages/event-markets-admin.html b/pages/event-markets-admin.htmlnew file mode 100644index 000000000..4ca50eb05--- /dev/null+++ b/pages/event-markets-admin.html@@ -0,0 +1,76 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Event Markets Admin · three.ws</title>+ <meta name="robots" content="noindex, nofollow" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <style>+ body { background: #0a0a0f; color: #e2e8f0; min-height: 100vh; }+ .em-wrap { width: 100%; min-width: 0; box-sizing: border-box; max-width: 1200px; margin: 0 auto; padding: clamp(1.5rem, 4vw, 3rem) 1.25rem 5rem; }+ .em-title { font-size: clamp(1.4rem, 3vw, 1.85rem); font-weight: 800; letter-spacing: -0.025em; margin: 0 0 0.5rem; }+ .em-sub { color: rgba(255,255,255,0.45); font-size: 13.5px; margin: 0 0 1.75rem; max-width: 74ch; line-height: 1.65; }+ .em-controls { display: flex; gap: 0.75rem; margin-bottom: 1.75rem; align-items: center; flex-wrap: wrap; }+ .em-stamp { font-size: 11.5px; color: rgba(255,255,255,0.3); margin-left: auto; font-variant-numeric: tabular-nums; }+ .em-btn { font: inherit; font-size: 13px; padding: 7px 12px; border-radius: 8px; border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.05); color: #e2e8f0; cursor: pointer; transition: border-color .15s ease, background .15s ease, transform .15s ease; }+ .em-btn:hover { border-color: rgba(255,255,255,0.28); background: rgba(255,255,255,0.1); }+ .em-btn:active { transform: translateY(1px); }+ .em-btn:focus-visible { outline: 2px solid rgba(124,92,255,0.75); outline-offset: 2px; }+ .em-btn[disabled] { opacity: 0.5; cursor: progress; }+ .em-btn.danger:hover { border-color: rgba(248,113,113,0.6); background: rgba(248,113,113,0.12); }+ .em-note { padding: 2.5rem 1.5rem; text-align: center; border-radius: 14px; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); color: rgba(255,255,255,0.55); line-height: 1.75; }+ .em-note.bad { background: rgba(248,113,113,0.05); border-color: rgba(248,113,113,0.18); }+ .em-note h2 { font-size: 15px; margin: 0 0 0.6rem; color: #e2e8f0; font-weight: 700; }+ .em-note a { color: var(--accent-violet-strong, #a78bfa); }+ .em-note code { background: rgba(255,255,255,0.08); padding: 2px 6px; border-radius: 4px; font-size: 12.5px; }+ .em-section { margin-bottom: 2.5rem; }+ .em-section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: rgba(255,255,255,0.35); margin: 0 0 0.85rem; display: flex; gap: 0.6rem; align-items: baseline; flex-wrap: wrap; }+ .em-section-title span { text-transform: none; letter-spacing: 0; font-weight: 500; color: rgba(255,255,255,0.25); }+ .em-table-wrap { overflow-x: auto; border: 1px solid rgba(255,255,255,0.07); border-radius: 12px; }+ .em-table { width: 100%; border-collapse: collapse; font-size: 13px; min-width: 720px; }+ .em-table th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: rgba(255,255,255,0.4); font-weight: 600; padding: 10px 14px; background: rgba(255,255,255,0.02); }+ .em-table td { padding: 11px 14px; border-top: 1px solid rgba(255,255,255,0.06); vertical-align: top; }+ .em-table tr:hover td { background: rgba(255,255,255,0.025); }+ .em-ev-title { font-weight: 600; overflow-wrap: anywhere; }+ .em-muted { color: rgba(255,255,255,0.45); font-size: 12px; margin-top: 2px; }+ .em-pill { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: 11.5px; font-weight: 600; background: rgba(255,255,255,0.08); }+ .em-pill.open { background: rgba(45,212,191,0.15); color: #5eead4; }+ .em-pill.locked { background: rgba(240,169,59,0.15); color: #f6c26b; }+ .em-pill.resolved { background: rgba(124,92,255,0.18); color: #c4b5fd; }+ .em-pill.void, .em-pill.skip { background: rgba(248,113,113,0.14); color: #fca5a5; }+ .em-pill.none { background: rgba(255,255,255,0.06); color: rgba(255,255,255,0.55); }+ .em-actions { display: flex; gap: 6px; flex-wrap: wrap; }+ .em-skeleton { height: 46px; border-radius: 10px; margin-bottom: 8px; background: linear-gradient(90deg, rgba(255,255,255,0.04) 25%, rgba(255,255,255,0.09) 50%, rgba(255,255,255,0.04) 75%); background-size: 200% 100%; animation: em-shimmer 1.4s linear infinite; }+ @keyframes em-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ .em-toast { position: fixed; right: 1rem; bottom: 1rem; max-width: min(420px, calc(100vw - 2rem)); padding: 12px 16px; border-radius: 10px; background: #1a1a24; border: 1px solid rgba(255,255,255,0.16); font-size: 13px; line-height: 1.5; }+ .em-toast.bad { border-color: rgba(248,113,113,0.5); }+ @media (prefers-reduced-motion: reduce) { .em-skeleton { animation: none; } .em-btn { transition: none; } }+ </style>+</head>+<body>+ <div class="em-wrap">+ <h1 class="em-title">Event Markets</h1>+ <p class="em-sub">+ Every event on the platform and whether it has a "Who wins?" market. The cron opens one as soon as an+ event has a defined winner and two entrants, adds late entrants until picks lock, and logs every event+ it declines with the reason. Open or void one by hand here. Points only, nothing on this page moves funds.+ Internal tooling, not a public surface.+ </p>+ <div class="em-controls">+ <button class="em-btn" id="em-refresh" type="button">Refresh</button>+ <span class="em-stamp" id="em-stamp"></span>+ </div>+ <div id="em-content" aria-live="polite" aria-busy="true"></div>+ </div>+ <div id="em-toast-host" role="status" aria-live="polite"></div>++ <script src="/nav.js"></script>+ <script type="module" src="/src/event-markets-admin.js"></script>+ <script type="module" src="/i18n.js"></script>+</body>+</html>diff --git a/src/event-markets-admin.js b/src/event-markets-admin.jsnew file mode 100644index 000000000..add747d5c--- /dev/null+++ b/src/event-markets-admin.js@@ -0,0 +1,166 @@+// /admin/event-markets: events with and without markets, why the cron skipped some,+// and manual open / void. A client of /api/ops/event-markets, never a gate in front of+// it: the endpoint authorizes on the server (platform admin session).++const el = document.getElementById('em-content');+const refreshBtn = document.getElementById('em-refresh');+const stamp = document.getElementById('em-stamp');+const toastHost = document.getElementById('em-toast-host');++const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+const when = (iso) => (iso ? new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : 'n/a');+const KIND = {+ arena_tournament: 'Arena tournament',+ event_leaderboard: 'Platform event',+ launch_cohort: 'Launch cohort',+ build_round: 'Build round',+ bounty: 'Bounty',+ custom: 'Custom',+};+const REASON = {+ too_few_entrants: 'Too few entrants',+ no_defined_winner: 'No defined winner',+ lock_passed: 'Pick window already closed',+};++function toast(message, bad = false) {+ const t = document.createElement('div');+ t.className = `em-toast${bad ? ' bad' : ''}`;+ t.textContent = message;+ toastHost.replaceChildren(t);+ setTimeout(() => t.remove(), 6000);+}++function skeleton() {+ el.innerHTML = '<div class="em-skeleton"></div>'.repeat(5);+}++function note(title, body, bad = false) {+ el.innerHTML = `<div class="em-note${bad ? ' bad' : ''}"><h2>${esc(title)}</h2><p>${body}</p></div>`;+}++function marketCell(e) {+ if (e.market) {+ const m = e.market;+ return `<span class="em-pill ${esc(m.status)}">${esc(m.status)}</span>+ <div class="em-muted"><a href="/event-markets/${encodeURIComponent(m.slug)}">${esc(m.slug)}</a> · ${m.outcome_count} outcomes · ${m.pick_count} picks</div>`;+ }+ const why = e.skip || e.blocker;+ if (why) {+ return `<span class="em-pill skip">${esc(REASON[why.reason] || why.reason)}</span><div class="em-muted">${esc(why.detail || '')}</div>`;+ }+ return '<span class="em-pill none">Opens next tick</span>';+}++function actionsCell(e) {+ const kind = esc(e.source_kind);+ const ref = esc(e.source_ref);+ if (e.market) {+ const open = ['open', 'locked'].includes(e.market.status);+ return open ? `<button class="em-btn danger" data-act="void" data-market="${esc(e.market.id)}" type="button">Void</button>` : '';+ }+ return `<button class="em-btn" data-act="open" data-kind="${kind}" data-ref="${ref}" type="button">Open now</button>`;+}++function eventsSection(d) {+ if (!d.events.length) {+ return `<div class="em-note"><h2>No upcoming or live events</h2><p>When a tournament, build round, bounty or platform event is announced it appears here and gets a market on the next tick.</p></div>`;+ }+ const rows = d.events+ .map(+ (e) => `<tr>+ <td><div class="em-ev-title">${esc(e.title)}</div><div class="em-muted">${esc(KIND[e.source_kind] || e.source_kind)}</div></td>+ <td>${esc(when(e.starts_at))}<div class="em-muted">to ${esc(when(e.ends_at))}</div></td>+ <td>${e.entrant_count}<div class="em-muted">locks ${esc(when(e.lock_at))}</div></td>+ <td>${marketCell(e)}</td>+ <td><div class="em-actions">${actionsCell(e)}</div></td>+ </tr>`,+ )+ .join('');+ return `<section class="em-section"><div class="em-section-title">Events <span>${d.events.length} listed by the sources right now</span></div>+ <div class="em-table-wrap"><table class="em-table"><thead><tr><th>Event</th><th>Window</th><th>Entrants</th><th>Market</th><th></th></tr></thead><tbody>${rows}</tbody></table></div></section>`;+}++function skipsSection(d) {+ if (!d.skips.length) return '';+ const rows = d.skips+ .map(+ (s) => `<tr><td><div class="em-ev-title">${esc(s.title)}</div><div class="em-muted">${esc(KIND[s.source_kind] || s.source_kind)}</div></td>+ <td><span class="em-pill skip">${esc(REASON[s.reason] || s.reason)}</span><div class="em-muted">${esc(s.detail || '')}</div></td>+ <td>${esc(when(s.first_seen))}</td><td>${esc(when(s.last_seen))}<div class="em-muted">seen ${s.seen_count}x</div></td></tr>`,+ )+ .join('');+ return `<section class="em-section"><div class="em-section-title">Skipped <span>events the cron declined, with the reason</span></div>+ <div class="em-table-wrap"><table class="em-table"><thead><tr><th>Event</th><th>Reason</th><th>First seen</th><th>Last seen</th></tr></thead><tbody>${rows}</tbody></table></div></section>`;+}++function errorsSection(d) {+ if (!d.source_errors.length) return '';+ return `<div class="em-note bad"><h2>A source failed to list events</h2><p>${d.source_errors.map((x) => `<code>${esc(x.source_kind)}</code> ${esc(x.message)}`).join('<br>')}</p></div>`;+}++function render(d) {+ el.innerHTML = errorsSection(d) + eventsSection(d) + skipsSection(d);+ stamp.textContent = `Read ${when(d.generated_at)}`;+}++let inFlight = null;++async function load() {+ if (inFlight) return;+ refreshBtn.disabled = true;+ el.setAttribute('aria-busy', 'true');+ skeleton();+ inFlight = (async () => {+ try {+ const res = await fetch('/api/ops/event-markets', { credentials: 'include', headers: { accept: 'application/json' } });+ if (res.status === 401) return note('Sign in required', 'This page takes a platform admin session. <a href="/login?next=/admin/event-markets">Sign in</a>, then come back.');+ if (res.status === 403) return note('Admins only', 'This account is not a platform admin. <a href="/login?next=/admin/event-markets">Switch account</a>.');+ if (res.status === 429) return note('Rate limited', `Retry in ${esc(res.headers.get('retry-after') || 'a moment')} seconds.`, true);+ if (res.status === 503) {+ const body = await res.json().catch(() => ({}));+ return note('Migration pending', esc(body.error_description || 'Event Markets tables are missing. Run npm run db:status.'), true);+ }+ if (!res.ok) throw new Error(`status ${res.status}`);+ render(await res.json());+ } catch (err) {+ note('Could not load events', `${esc(err?.message || err)}. Check your connection and refresh.`, true);+ } finally {+ refreshBtn.disabled = false;+ el.setAttribute('aria-busy', 'false');+ inFlight = null;+ }+ })();+ await inFlight;+}++async function act(btn) {+ const act = btn.dataset.act;+ if (act === 'void' && !confirm('Void this market? Picks on it stop counting.')) return;+ btn.disabled = true;+ try {+ const payload = act === 'open'+ ? { action: 'open', source_kind: btn.dataset.kind, source_ref: btn.dataset.ref }+ : { action: 'void', market_id: btn.dataset.market };+ const res = await fetch('/api/ops/event-markets', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: JSON.stringify(payload),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.error_description || `status ${res.status}`);+ toast(act === 'open' ? `Opened ${body.slug}` : `Voided ${body.slug}`);+ await load();+ } catch (err) {+ toast(err?.message || String(err), true);+ btn.disabled = false;+ }+}++el.addEventListener('click', (ev) => {+ const btn = ev.target.closest('button[data-act]');+ if (btn) act(btn);+});+refreshBtn.addEventListener('click', load);+load();diff --git a/tests/event-markets-auto-open.test.js b/tests/event-markets-auto-open.test.jsnew file mode 100644index 000000000..6f99256bb--- /dev/null+++ b/tests/event-markets-auto-open.test.js@@ -0,0 +1,206 @@+/**+ * Event Markets auto-open (api/_lib/event-markets/auto-open.js): which events get a+ * market, how it is phrased and timed, and the guarantees around it: idempotent on+ * the event, late entrants added before lock and never after, every declined event+ * logged with a reason, and the outbox row written on open.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const queries = [];+let route = () => [];+vi.mock('../api/_lib/db.js', () => ({+ sql: (strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join('?') : String(strings);+ queries.push({ q, values });+ return Promise.resolve().then(() => route(q, values));+ },+}));++const created = [];+let createError = null;+vi.mock('../api/_lib/event-markets/index.js', async () => {+ class EventMarketError extends Error {+ constructor(status, code, message) {+ super(message);+ this.status = status;+ this.code = code;+ }+ }+ return {+ EventMarketError,+ slugify: (t) => String(t).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''),+ createMarket: async (input) => {+ if (createError) throw createError;+ created.push(input);+ return { id: 'm1', slug: input.slug, title: input.title, locks_at: input.locks_at, resolves_at: input.resolves_at, outcomes: input.outcomes };+ },+ };+});++const A = await import('../api/_lib/event-markets/auto-open.js');++const NOW = new Date('2026-10-12T12:00:00Z');+const hour = 3_600_000;+const entrant = (n) => ({ label: `Agent ${n}`, refKind: 'agent', refId: `agent-${n}`, imageUrl: null });+function event(over = {}) {+ return {+ sourceKind: 'arena_tournament',+ sourceRef: 't-1',+ title: 'Spring Cup',+ startsAt: new Date(NOW.getTime() + 2 * hour),+ endsAt: new Date(NOW.getTime() + 10 * hour),+ lockAt: new Date(NOW.getTime() + 2 * hour),+ resolvesAt: new Date(NOW.getTime() + 10 * hour),+ entrants: [entrant(1), entrant(2), entrant(3)],+ rule: { type: 'tournament_final_rank', description: 'Top of the standings.' },+ winnerDefined: true,+ ...over,+ };+}++beforeEach(() => {+ queries.length = 0;+ created.length = 0;+ createError = null;+ route = () => [];+});++describe('question phrasing and slugs', () => {+ it('phrases the title as a question and caps its length', () => {+ expect(A.questionTitle('Spring Cup')).toBe('Who wins Spring Cup?');+ const long = A.questionTitle('x'.repeat(400));+ expect(long.length).toBeLessThanOrEqual(160);+ expect(long.endsWith('...?')).toBe(true);+ });++ it('derives a deterministic slug from the event identity', () => {+ const a = A.marketSlug(event());+ expect(a).toBe(A.marketSlug(event()));+ expect(a).not.toBe(A.marketSlug(event({ sourceRef: 't-2' })));+ expect(a).toMatch(/^[a-z0-9][a-z0-9-]{1,78}$/);+ });+});++describe('planOpen', () => {+ it('opens an event with a winner, enough entrants and a future lock', () => {+ expect(A.planOpen(event(), NOW)).toEqual({ action: 'open' });+ });++ it('skips fewer than two entrants', () => {+ const p = A.planOpen(event({ entrants: [entrant(1)] }), NOW);+ expect(p).toMatchObject({ action: 'skip', reason: 'too_few_entrants' });+ });++ it('skips an event with no defined winner, whatever its entrants', () => {+ const p = A.planOpen(event({ winnerDefined: false, noWinnerReason: 'no judging criteria' }), NOW);+ expect(p).toMatchObject({ action: 'skip', reason: 'no_defined_winner', detail: 'no judging criteria' });+ });++ it('skips when picks would already have closed, unless forced', () => {+ const late = event({ lockAt: new Date(NOW.getTime() - hour) });+ expect(A.planOpen(late, NOW)).toMatchObject({ action: 'skip', reason: 'lock_passed' });+ expect(A.planOpen(late, NOW, { force: true })).toEqual({ action: 'open' });+ });+});++describe('openForEvent', () => {+ it('opens a market with the entrants as outcomes and writes the outbox row', async () => {+ const r = await A.openForEvent(event(), { now: NOW });+ expect(r.result).toBe('opened');+ expect(created).toHaveLength(1);+ const c = created[0];+ expect(c.title).toBe('Who wins Spring Cup?');+ expect(c.status).toBe('open');+ expect(c.source_kind).toBe('arena_tournament');+ expect(c.source_ref).toBe('t-1');+ expect(c.locks_at).toBe(event().lockAt.toISOString());+ expect(c.resolves_at).toBe(event().resolvesAt.toISOString());+ expect(c.outcomes.map((o) => o.ref_id)).toEqual(['agent-1', 'agent-2', 'agent-3']);+ expect(c.resolution_rule.type).toBe('tournament_final_rank');+ const outbox = queries.find((q) => q.q.includes('event_market_outbox'));+ expect(outbox.values[0]).toBe('event_market.opened');+ expect(queries.some((q) => q.q.includes('delete from event_market_skips'))).toBe(true);+ });++ it('records a skip with its reason instead of opening', async () => {+ const r = await A.openForEvent(event({ entrants: [entrant(1)] }), { now: NOW });+ expect(r).toMatchObject({ result: 'skipped', reason: 'too_few_entrants' });+ expect(created).toHaveLength(0);+ const skip = queries.find((q) => q.q.includes('insert into event_market_skips'));+ expect(skip.values).toEqual(expect.arrayContaining(['arena_tournament', 't-1', 'too_few_entrants']));+ });++ it('is idempotent: an event that already has a market is not created again', async () => {+ route = (q) => (q.includes('from event_markets') ? [{ id: 'm1', slug: 's', status: 'open', locks_at: event().lockAt }]+ : q.includes('from event_market_outcomes')+ ? ['agent-1', 'agent-2', 'agent-3'].map((id) => ({ ref_kind: 'agent', ref_id: id }))+ : []);+ const r = await A.openForEvent(event(), { now: NOW });+ expect(r.result).toBe('unchanged');+ expect(created).toHaveLength(0);+ expect(queries.some((q) => q.q.includes('insert into event_market_outcomes'))).toBe(false);+ });++ it('treats a lost creation race as the existing market', async () => {+ const { EventMarketError } = await import('../api/_lib/event-markets/index.js');+ createError = new EventMarketError(409, 'market_exists_for_source', 'exists');+ let lookups = 0;+ route = (q) => (q.includes('from event_markets') ? (lookups++ === 0 ? [] : [{ id: 'm1', slug: 'raced', status: 'open', locks_at: event().lockAt }]) : []);+ const r = await A.openForEvent(event(), { now: NOW });+ expect(r).toMatchObject({ result: 'unchanged', slug: 'raced' });+ });++ it('adds an entrant that joined before lock and leaves existing outcomes alone', async () => {+ route = (q) => {+ if (q.includes('from event_markets')) return [{ id: 'm1', slug: 's', status: 'open', locks_at: event().lockAt }];+ if (q.includes('select ref_kind, ref_id')) return ['agent-1', 'agent-2'].map((id) => ({ ref_kind: 'agent', ref_id: id }));+ if (q.includes('insert into event_market_outcomes')) return [{ id: 'new' }];+ return [];+ };+ const r = await A.openForEvent(event(), { now: NOW });+ expect(r).toMatchObject({ result: 'synced', added: 1 });+ const inserts = queries.filter((q) => q.q.includes('insert into event_market_outcomes'));+ expect(inserts).toHaveLength(1);+ expect(inserts[0].values).toContain('agent-3');+ expect(queries.some((q) => /delete from event_market_outcomes|update event_market_outcomes/.test(q.q))).toBe(false);+ });++ it('never changes outcomes after lock', async () => {+ const locked = new Date(NOW.getTime() - hour);+ route = (q) => (q.includes('from event_markets') ? [{ id: 'm1', slug: 's', status: 'open', locks_at: locked }] : []);+ const r = await A.openForEvent(event(), { now: NOW });+ expect(r.result).toBe('unchanged');+ expect(queries.some((q) => q.q.includes('event_market_outcomes'))).toBe(false);+ });++ it('never changes outcomes of a locked, resolved or void market', async () => {+ for (const status of ['locked', 'resolved', 'void']) {+ queries.length = 0;+ route = (q) => (q.includes('from event_markets') ? [{ id: 'm1', slug: 's', status, locks_at: event().lockAt }] : []);+ const r = await A.openForEvent(event(), { now: NOW });+ expect(r.result).toBe('unchanged');+ expect(queries.some((q) => q.q.includes('event_market_outcomes'))).toBe(false);+ }+ });++ it('forced open of a past-lock event gets a manual lock window', async () => {+ const late = event({ lockAt: new Date(NOW.getTime() - hour) });+ const r = await A.openForEvent(late, { now: NOW, force: true });+ expect(r.result).toBe('opened');+ expect(new Date(created[0].locks_at).getTime()).toBeGreaterThan(NOW.getTime());+ });+});++describe('runAutoOpen', () => {+ it('reports a failing source without stopping the others', async () => {+ const sources = [+ { sourceKind: 'bounty', listEvents: async () => { throw new Error('db down'); } },+ { sourceKind: 'arena_tournament', listEvents: async () => [event()] },+ ];+ const rep = await A.runAutoOpen({ now: NOW, sources });+ expect(rep.errors).toEqual([{ source_kind: 'bounty', message: 'db down' }]);+ expect(rep.opened).toHaveLength(1);+ expect(rep.seen).toBe(1);+ });+});