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): draft announcements for open, lock, odds shift and result into an admin review queue; posting stays off until approved
nirholas1e447069ea31
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 3658c1bc0..f7bc4c5b1 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -17,6 +17,7 @@ bottom.| Web renderer / viewer | [avatar-sdk/](avatar-sdk) `→ /viewer` | Published as `@three-ws/avatar` | `<agent-3d>` web component || Entity studio (one detail page for agents AND avatars) | [pages/avatar-page.html](pages/avatar-page.html) + [src/avatar-page.js](src/avatar-page.js) `→ /avatars/:id` and `→ /agents/:id`, view switcher [src/view-switcher.js](src/view-switcher.js), AR lane [src/ar-page.js](src/ar-page.js) `→ /avatars/:id/ar` + `/agents/:id/ar`, long-form agent profile [pages/agent-detail.html](pages/agent-detail.html) + [src/agent-detail.js](src/agent-detail.js) `→ /agents/:id/profile` | Live | The canonical page every entity link on the platform lands on: search, `/agents`, `/gallery`, the marketplace, galaxy, launches and profiles all point here. One controller renders both kinds from one shell (3D stage + wallet-reactive aura, identity, tabs for Overview / Chat / Pose / Skills / Plugins / Embed, related grid). Agent mode projects the agent record onto the avatar shape (`agentStudioRecord`): the agent's name, description, tags and custodial wallet win, its bound body supplies geometry and fork lineage, and chat posts the real `agentId` so replies come from that agent's brain and memory. Agents and avatars are separate tables with separate UUIDs, so an id that lands on the wrong route is probed against the other store and redirected to its canonical path instead of 404ing. An agent with no body yet renders a designed stage state ("create a body" / "pick one from the marketplace") rather than an empty viewer, and every body-scoped surface (AR, Pose, forks, coin launch, GLB stats) stays hidden. Docs: [docs/agents-vs-avatars.md](docs/agents-vs-avatars.md) || Agent shell (companion identity + agentic ⌘K + persistent navigation) | [src/agents/guest-agent.js](src/agents/guest-agent.js), [src/shared/agent-names.js](src/shared/agent-names.js), [src/walk-companion-identity.js](src/walk-companion-identity.js), [public/search.js](public/search.js), [src/view-transitions.js](src/view-transitions.js), [src/shell/page-lifecycle.js](src/shell/page-lifecycle.js) | Live | The agent IS the interface: every visitor gets a named ephemeral agent in the first five seconds (auto-summoned corner companion with an identity chip; “Claim →” prefills /create-agent and POST /api/agents makes it real); the ⌘K palette executes real commands in place (forge → free text→3D lane, digest → clustered news, price → live market data, ask → streamed /api/chat) and announces completions so the companion reacts; pages marked data-shell (`/markets`, `/coins`) navigate by swapping only the main element so the agent and shell never unload (page modules re-init via onPageReady). Docs: [docs/agent-shell.md](docs/agent-shell.md). Tests: [tests/search-commands.test.js](tests/search-commands.test.js), [tests/guest-agent.test.js](tests/guest-agent.test.js), [tests/agent-names.test.js](tests/agent-names.test.js) |+| Event Market announcements | [api/_lib/event-markets/announce.js](api/_lib/event-markets/announce.js), [review.js](api/_lib/event-markets/review.js), [poster.js](api/_lib/event-markets/poster.js), [api/event-markets/announcements.js](api/event-markets/announcements.js), [api/cron/event-market-announce.js](api/cron/event-market-announce.js), [pages/event-market-announcements.html](pages/event-market-announcements.html) `→ /admin/event-market-announcements` | Live, posting off until the owner enables it | Cron writes drafts per market lifecycle change; admin queue approves, edits, rejects; poster is the only sender and refuses anything not approved (flag `EVENT_MARKET_ANNOUNCE_POST`, daily cap). Entrants tagged only with self-linked X handles. Docs: [docs/event-markets.md](docs/event-markets.md). Tests: [tests/event-market-announcements.test.js](tests/event-market-announcements.test.js) || Walk companion + playground | [walk-sdk/](walk-sdk) `→ /walk-companion.js` | Published as `@three-ws/walk` | Corner mascot + full-page stroll/platformer playground + diverse avatar picker. App entries: [src/walk-companion.js](src/walk-companion.js), [src/walk-playground.js](src/walk-playground.js) || The walkaround world (`/temporary`) | [pages/temporary.html](pages/temporary.html) `→ /temporary`, app [src/walk.js](src/walk.js), environments [src/walk-environments.js](src/walk-environments.js) + [public/environments/](public/environments), multiplayer [src/walk-net.js](src/walk-net.js) → `walk_world`, day/night [src/walk-day-night.js](src/walk-day-night.js), radar [src/game/hud/minimap.js](src/game/hud/minimap.js), companions [src/walk-npcs.js](src/walk-npcs.js), agent desks [src/walk-agent-desk.js](src/walk-agent-desk.js) | Live | Walk your avatar through six real staged environments (park, cyberpunk street, beach, gallery, void, office) with physics-driven locomotion on a heightfield, four camera modes, gestures, voice chat, trails, capture, and live peers. **Time of day is real and shared:** the same deterministic world clock `/play` runs on ([src/shared/world-clock.js](src/shared/world-clock.js)) drives the sun arc, sky gradient, light levels, and IBL strength, so two people in the same world always agree on whether it is night. The sky crossfades on a wider curve than the light levels, so dawn and dusk linger instead of flipping. Armed for outdoor stages only (indoor/void keep their authored manifest lighting) and paused while AR passthrough owns the rig. **The radar is `/play`'s:** `/temporary` mounts the same rotating GTA-style minimap the world HUD uses, with a compass, the walkable-disc boundary ring, and live blips for peers (their nameplate colours), NPC companions, live agent desks, the guide's named landmarks, and scenery. Click or tap it to set a walk-to waypoint (`Minimap.worldFromScreen()` inverts the rotating projection); `M` or the dock button toggles it and the choice persists. **Frame pacing is shared too:** the loop runs through [src/shared/frame-governor.js](src/shared/frame-governor.js) (60fps focused, 30 unfocused, 30 under power saver) and the controls overlay carries the cross-surface Power-saver switch. Tests: [tests/walk-day-night.test.js](tests/walk-day-night.test.js), [tests/minimap-projection.test.js](tests/minimap-projection.test.js) || Walk landing + one-tag embed (`/walk`) | [pages/walk-landing.html](pages/walk-landing.html) `→ /walk`, embed app [pages/walk-embed.html](pages/walk-embed.html) `→ /walk/app` and `→ /walk-embed` ([src/walk-embed.js](src/walk-embed.js)), board [pages/walk-leaderboard.html](pages/walk-leaderboard.html) `→ /walk-leaderboard`, ranking API [api/walk/leaderboard.js](api/walk/leaderboard.js), curated quotes [data/walk-social.json](data/walk-social.json) | Live | The marketing entry for Walk and the surface the `→ /walk` route actually serves (the walkaround world above is at `/temporary`). Live demo embeds across six environments, the copyable one-tag iframe snippet, the Chrome extension pitch, and a top-three teaser off the real all-time distance ranking, which reads `rows` straight from the leaderboard endpoint and falls back to designed empty and retryable error states. All nine demo iframes stay keyboard-reachable, which axe's `frame-focusable-content` rule requires of any frame whose document has focusable content, and each gets a scripted focus ring because an iframe whose document holds focus matches no focus pseudo-class. Page copy is mirrored in the `walk_landing` namespace of [public/locales/en.json](public/locales/en.json), which the i18n runtime applies over the served HTML, so the two must be edited together. |diff --git a/api/_lib/event-markets/announce.js b/api/_lib/event-markets/announce.jsnew file mode 100644index 000000000..644327ff9--- /dev/null+++ b/api/_lib/event-markets/announce.js@@ -0,0 +1,243 @@+// Announcement drafter for Event Markets. Reads live market data and writes+// DRAFTS into event_market_announcements. It never posts: the only sender is+// poster.js, and it refuses anything not approved. Guide: docs/event-markets.md.+//+// Rules the text obeys (enforced by `lint`, not by hope):+// - positive framing, no price promises, no other-coin mentions+// - an entrant is tagged only with an X handle the entrant linked to their own+// profile (agent_x_connections, or the owner's social_connections for a+// wallet entrant). A handle is never scraped, guessed or typed in by us.+// An entrant with no linked handle is named, not tagged.+// - one announcement per kind per market (a table-level unique key)++import { sql } from '../db.js';+import { env } from '../env.js';+import { readFileSync } from 'node:fs';+import { languageProblems } from '../x-content/editorial.js';+import { weightedLength } from '../x-content/quality.js';+import { getMarket } from './index.js';+import { taggableEntrants } from './entrants.js';++export const CONFIG = JSON.parse(readFileSync(new URL('../../../data/event-markets-announcements.json', import.meta.url), 'utf8'));++/** The outcome ahead (by crowd share), or null on a dead heat, including no picks at all. */+export function leaderOf(market) {+ const sorted = [...market.outcomes].sort((x, y) => y.share - x.share);+ if (!sorted.length) return null;+ if (sorted.length > 1 && Math.abs(sorted[0].share - sorted[1].share) < 1e-9) return null;+ return sorted[0];+}++const HANDLE = /^[A-Za-z0-9_]{1,15}$/;+const MAX_TAGS = 3;+const MAX_LEN = 280;++const origin = () => (env.PUBLIC_APP_ORIGIN || 'https://three.ws').replace(/\/$/, '');+export const marketUrl = (slug) => `${origin()}/event-markets/${slug}`;+export const cardUrl = (slug) => `${origin()}/api/event-market-og?slug=${encodeURIComponent(slug)}`;++const pct = (share) => `${Math.round(share * 100)}%`;+const hoursUntil = (iso, now) => Math.max(0, Math.round((new Date(iso) - now) / 3_600_000));++/**+ * Linked X handles for a market's outcomes, keyed by outcome id. Only a handle+ * the entrant connected to their own account through X OAuth qualifies: an+ * agent's own connection first, else its owner's. Entrants who opted out of+ * being tagged (event_market_entrant_prefs) are excluded by taggableEntrants.+ */+export async function linkedHandles(market) {+ const entrants = await taggableEntrants(market);+ const handles = new Map();+ for (const { outcome, accountId } of entrants) {+ let row;+ if (outcome.ref_kind === 'agent') {+ [row] = await sql`+ select username from agent_x_connections+ where agent_id::text = ${outcome.ref_id} and user_id = ${accountId} and disconnected_at is null limit 1+ `;+ }+ if (!row) {+ [row] = await sql`+ select username from social_connections+ where user_id = ${accountId} and provider = 'x' and disconnected_at is null limit 1+ `;+ }+ const handle = row?.username?.replace(/^@/, '');+ if (handle && HANDLE.test(handle)) handles.set(outcome.id, handle);+ }+ return handles;+}++const nameOf = (outcome, handles) => (handles.get(outcome.id) ? `@${handles.get(outcome.id)}` : outcome.label);++function entrantList(outcomes, handles, { limit = MAX_TAGS } = {}) {+ const tagged = outcomes.filter((o) => handles.has(o.id)).slice(0, limit);+ const taggedIds = new Set(tagged.map((o) => o.id));+ const untagged = outcomes.filter((o) => !taggedIds.has(o.id));+ return { tagged, untagged };+}++function join(names) {+ if (names.length <= 1) return names.join('');+ return `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;+}++/**+ * Pure: build the text for one kind from already-loaded data. Tags are dropped+ * one at a time (last first) until the post fits, and the entrants named without+ * a tag fall back to a count, so a long field never overflows.+ *+ * ctx: { market (the getMarket view), handles:Map, now, baseline?, forecasters?:[] }+ */+export function buildDraft(kind, ctx) {+ const { market, handles, now = new Date() } = ctx;+ const outcomes = market.outcomes;+ const url = marketUrl(market.slug);+ const byId = new Map(outcomes.map((o) => [o.id, o]));+ const shareOf = (id) => byId.get(id)?.share ?? 0;++ const compose = (tagLimit) => {+ let text;+ let tags = [];+ if (kind === 'opened') {+ const { tagged, untagged } = entrantList(outcomes, handles, { limit: tagLimit });+ tags = tagged.map((o) => handles.get(o.id));+ const names = [...tagged.map((o) => nameOf(o, handles)), ...untagged.slice(0, 2).map((o) => o.label)];+ const more = outcomes.length - names.length;+ const field = more > 0 ? `${join(names)} and ${more} more` : join(names);+ text = `Picks are open on ${market.title}. ${field} ${outcomes.length === 2 ? 'are' : 'are all in the field'}. Free to play: back your call with points before it locks.\n${url}`;+ } else if (kind === 'locking_soon') {+ const lead = leaderOf(market);+ const hours = market.locks_at ? hoursUntil(market.locks_at, now) : null;+ const when = hours === null ? 'soon' : hours <= 1 ? 'within the hour' : `in ${hours} hours`;+ const leadTag = lead && handles.has(lead.id) && tagLimit > 0;+ if (leadTag) tags = [handles.get(lead.id)];+ const state = market.odds.even_prior+ ? 'No picks have landed yet, so the field is an even split.'+ : lead+ ? `${nameOf(byId.get(lead.id), leadTag ? handles : new Map())} leads at ${pct(lead.share)} of the crowd's points.`+ : 'The crowd is split evenly across the front of the field.';+ text = `Picks on ${market.title} lock ${when}. ${state} Make or change yours while it is open.\n${url}`;+ } else if (kind === 'odds_shift') {+ const lead = leaderOf(market);+ const leadO = lead && byId.get(lead.id);+ const leadTag = leadO && handles.has(leadO.id) && tagLimit > 0;+ if (leadTag) tags = [handles.get(leadO.id)];+ const from = ctx.baseline?.leader_id && ctx.baseline.leader_id !== lead?.id+ ? ` after ${byId.get(ctx.baseline.leader_id)?.label ?? 'the previous favourite'} held the top spot`+ : '';+ text = `The crowd moved on ${market.title}. ${leadO ? `${nameOf(leadO, leadTag ? handles : new Map())} now leads at ${pct(lead.share)}` : 'The field is level'}${from}, from ${market.pick_count} picks so far. Still open.\n${url}`;+ } else if (kind === 'resolved') {+ const winner = byId.get(market.winner?.outcome_id);+ if (!winner) return null;+ const win = handles.has(winner.id) && tagLimit > 0;+ if (win) tags = [handles.get(winner.id)];+ const called = ctx.forecasters?.length ? ` First to call it: ${join(ctx.forecasters)}.` : '';+ text = `${win ? `@${handles.get(winner.id)}` : winner.label} won ${market.title}, ${pct(shareOf(winner.id))} of the crowd's points had it.${called} The result and its evidence are on the market page.\n${url}`;+ } else {+ throw new Error(`unknown announcement kind: ${kind}`);+ }+ return { text, tags };+ };++ for (let limit = MAX_TAGS; limit >= 0; limit--) {+ const out = compose(limit);+ if (!out) return null;+ if (weightedLength(out.text) <= MAX_LEN) return { ...out, card_url: cardUrl(market.slug) };+ if (limit === 0) {+ const short = out.text.replace(/ Free to play: back your call with points before it locks\./, '');+ if (weightedLength(short) <= MAX_LEN) return { text: short, tags: [], card_url: cardUrl(market.slug) };+ return null;+ }+ }+ return null;+}++/** House voice and compliance gate. Mention-count is waived: tagging is the point and a person approves it. */+export function lint(text) {+ return languageProblems(text).filter((p) => p.severity === 'blocking' && p.rule !== 'mentions');+}++/** Has the crowd moved enough since the market opened to be worth a post? */+export function oddsShifted(market, baseline, cfg = CONFIG) {+ if (market.pick_count < cfg.minPicksForOddsShift) return false;+ const lead = leaderOf(market);+ if (!lead) return false;+ if (baseline?.leader_id && baseline.leader_id !== lead.id) return true;+ const before = baseline?.shares?.[lead.id] ?? 1 / market.outcomes.length;+ return (lead.share - before) * 100 >= cfg.oddsShiftPoints;+}++async function loadMarketCtx(row) {+ const market = await getMarket(row.id);+ return { market, handles: await linkedHandles(market) };+}++const snapshot = (market) => ({+ leader_id: leaderOf(market)?.id ?? null,+ shares: Object.fromEntries(market.outcomes.map((o) => [o.id, o.share])),+});++async function topForecasters(market, n) {+ if (!market.winner?.outcome_id) return [];+ const rows = await sql`+ select coalesce(u.display_name, u.username) as name+ from event_market_picks p join users u on u.id = p.account_id+ where p.market_id = ${market.id} and p.outcome_id = ${market.winner?.outcome_id} and p.agent_id is null+ order by p.created_at asc, p.points desc limit ${n}+ `;+ return rows.map((r) => r.name).filter(Boolean);+}++/**+ * Scan lifecycle state and write a draft for every kind that is due and has no+ * announcement yet. Idempotent: the (market_id, kind) unique key makes a second+ * run a no-op. Returns what it wrote and what it skipped, with reasons.+ */+export async function draftPending({ now = new Date() } = {}) {+ const cfg = CONFIG;+ const markets = await sql`+ select m.* from event_markets m+ where m.status in ('open','locked','resolved')+ and not (select count(*) = 4 from event_market_announcements a where a.market_id = m.id)+ order by m.created_at desc limit 200+ `;+ const written = [];+ const skipped = [];+ for (const m of markets) {+ const have = new Map((await sql`select kind, baseline from event_market_announcements where market_id = ${m.id}`).map((r) => [r.kind, r]));+ const due = [];+ if (m.status === 'open' || m.status === 'locked') if (!have.has('opened')) due.push('opened');+ if (m.status === 'open' && m.locks_at && !have.has('locking_soon')) {+ const ms = new Date(m.locks_at) - now;+ if (ms > 0 && ms <= cfg.lockingSoonHours * 3_600_000) due.push('locking_soon');+ }+ if (m.status === 'open' && have.has('opened') && !have.has('odds_shift')) due.push('odds_shift');+ if (m.status === 'resolved' && m.winner_outcome_id && !have.has('resolved')) due.push('resolved');+ if (!due.length) continue;++ const ctx = await loadMarketCtx(m);+ if (due.includes('resolved')) ctx.forecasters = await topForecasters(ctx.market, cfg.topForecasters);+ for (const kind of due) {+ ctx.baseline = have.get('opened')?.baseline;+ if (kind === 'odds_shift' && !oddsShifted(ctx.market, ctx.baseline, cfg)) continue;+ const draft = buildDraft(kind, { ...ctx, now });+ if (!draft) {+ skipped.push({ slug: m.slug, kind, reason: 'does not fit in one post' });+ continue;+ }+ const problems = lint(draft.text);+ if (problems.length) {+ skipped.push({ slug: m.slug, kind, reason: problems.map((p) => p.message).join('; ') });+ continue;+ }+ const rows = await sql`+ insert into event_market_announcements (market_id, kind, draft_text, card_url, tags, baseline)+ values (${m.id}, ${kind}, ${draft.text}, ${draft.card_url}, ${draft.tags}, ${JSON.stringify(snapshot(ctx.market))}::jsonb)+ on conflict (market_id, kind) do nothing returning id+ `;+ if (rows.length) written.push({ slug: m.slug, kind, id: rows[0].id, tags: draft.tags });+ }+ }+ return { written, skipped };+}diff --git a/api/_lib/event-markets/poster.js b/api/_lib/event-markets/poster.jsnew file mode 100644index 000000000..7aa802ba8--- /dev/null+++ b/api/_lib/event-markets/poster.js@@ -0,0 +1,69 @@+// The single place an Event Market announcement is sent to X. It refuses+// anything that is not `approved`, re-checks the text, enforces the daily cap,+// and sends nothing unless EVENT_MARKET_ANNOUNCE_POST=on and dryRun is false.+//+// Sends through @trythreews with the same OAuth 1.0a client as the x-content+// publisher (api/_lib/x-content/publisher.js), so the account's own cadence and+// credentials apply. Dry run uses that module's previewClient and prints the+// exact call a live send would make.++import { sql } from '../db.js';+import { CONFIG } from './announce.js';+import { textProblems } from './review.js';+import { previewClient, xClientFromEnv } from '../x-content/publisher.js';++export class PosterError extends Error {+ constructor(code, message, status = 409) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++export const postingEnabled = (env = process.env) => String(env.EVENT_MARKET_ANNOUNCE_POST || '').toLowerCase() === 'on';++export async function sendAnnouncement(id, { dryRun = true, client = null, env = process.env } = {}) {+ const [row] = await sql`select * from event_market_announcements where id = ${id}`;+ if (!row) throw new PosterError('not_found', 'announcement not found', 404);+ if (row.status !== 'approved') throw new PosterError('not_approved', `refusing to send: status is ${row.status}, only approved announcements are sent`);+ const problems = textProblems(row.draft_text, row.tags);+ if (problems.length) throw new PosterError('unsendable', `refusing to send: ${problems.join('; ')}`);++ const [{ n }] = await sql`+ select count(*)::int as n from event_market_announcements+ where status = 'posted' and posted_at > now() - interval '24 hours'+ `;+ const cap = CONFIG.dailyCap;+ if (n >= cap) throw new PosterError('daily_cap', `daily cap of ${cap} announcements reached; try again after the oldest ages out of the 24 hour window`, 429);++ const payload = { text: row.draft_text };+ if (dryRun) {+ const preview = previewClient();+ await preview.tweet(payload);+ return { dry_run: true, would_send: payload, calls: preview.calls, flag_on: postingEnabled(env) };+ }+ if (!postingEnabled(env)) throw new PosterError('posting_disabled', 'posting is off: set EVENT_MARKET_ANNOUNCE_POST=on to send approved announcements', 403);++ const x = client || (await xClientFromEnv(env));+ if (!x) throw new PosterError('not_configured', 'X credentials are not configured (X_API_KEY, X_API_SECRET, X_ACCESS_TOKEN, X_ACCESS_SECRET)', 501);++ const [claimed] = await sql`+ update event_market_announcements set status = 'posting', updated_at = now()+ where id = ${id} and status = 'approved' returning id+ `;+ if (!claimed) throw new PosterError('conflict', 'another send already claimed this announcement');+ let res;+ try {+ res = await x.tweet(payload);+ } catch (err) {+ await sql`update event_market_announcements set status = 'approved', updated_at = now() where id = ${id} and status = 'posting'`;+ throw new PosterError('send_failed', `X rejected the post: ${String(err?.message || err).slice(0, 200)}`, 502);+ }+ const postId = res?.data?.id;+ const url = postId ? `https://x.com/i/status/${postId}` : null;+ const [out] = await sql`+ update event_market_announcements set status = 'posted', posted_at = now(), post_url = ${url}, updated_at = now()+ where id = ${id} returning *+ `;+ return { dry_run: false, sent: payload, announcement: out };+}diff --git a/api/_lib/event-markets/review.js b/api/_lib/event-markets/review.jsnew file mode 100644index 000000000..bac18dd4a--- /dev/null+++ b/api/_lib/event-markets/review.js@@ -0,0 +1,80 @@+// Review queue actions for announcement drafts: edit, approve (one or a batch),+// reject. Approval is the only way a draft becomes sendable, and an edit sends a+// draft back to `draft` so the text that goes out is always the text approved.++import { sql } from '../db.js';+import { weightedLength } from '../x-content/quality.js';+import { lint } from './announce.js';++export class ReviewError extends Error {+ constructor(code, message, status = 400) {+ super(message);+ this.code = code;+ this.status = status;+ }+}++const MENTION = /(?<![\w@])@(\w{1,15})/g;++/** Problems that make a text unsendable. Mentions must come from the row's linked-handle tags. */+export function textProblems(text, tags) {+ const problems = [];+ if (!String(text || '').trim()) problems.push('text is empty');+ if (weightedLength(text) > 280) problems.push('text is longer than 280 characters');+ const allowed = new Set((tags || []).map((t) => t.toLowerCase()));+ for (const [, handle] of String(text).matchAll(MENTION)) {+ if (!allowed.has(handle.toLowerCase())) problems.push(`@${handle} is not a handle this entrant linked to their profile`);+ }+ for (const p of lint(text)) problems.push(p.message);+ return problems;+}++export async function listAnnouncements({ status = null, limit = 100 } = {}) {+ const q = status+ ? sql`select a.*, m.slug, m.title from event_market_announcements a join event_markets m on m.id = a.market_id where a.status = ${status} order by a.created_at desc limit ${limit}`+ : sql`select a.*, m.slug, m.title from event_market_announcements a join event_markets m on m.id = a.market_id order by a.created_at desc limit ${limit}`;+ return q;+}++export async function editAnnouncement(id, text) {+ const [row] = await sql`select * from event_market_announcements where id = ${id}`;+ if (!row) throw new ReviewError('not_found', 'announcement not found', 404);+ if (['posting', 'posted'].includes(row.status)) throw new ReviewError('conflict', `a ${row.status} announcement cannot be edited`, 409);+ const problems = textProblems(text, row.tags);+ if (problems.length) throw new ReviewError('validation_error', problems.join('; '));+ const [out] = await sql`+ update event_market_announcements+ set draft_text = ${text}, status = 'draft', approved_by = null, approved_at = null, updated_at = now()+ where id = ${id} returning *+ `;+ return out;+}++/** Approve one or many drafts in a single action. Each is re-checked; failures are reported, not hidden. */+export async function approveAnnouncements(ids, approverId) {+ const approved = [];+ const failed = [];+ for (const id of ids) {+ const [row] = await sql`select * from event_market_announcements where id = ${id}`;+ if (!row) { failed.push({ id, reason: 'not found' }); continue; }+ if (row.status !== 'draft') { failed.push({ id, reason: `status is ${row.status}, only drafts can be approved` }); continue; }+ const problems = textProblems(row.draft_text, row.tags);+ if (problems.length) { failed.push({ id, reason: problems.join('; ') }); continue; }+ const [out] = await sql`+ update event_market_announcements+ set status = 'approved', approved_by = ${approverId}, approved_at = now(), updated_at = now()+ where id = ${id} and status = 'draft' returning *+ `;+ if (out) approved.push(out); else failed.push({ id, reason: 'changed while approving' });+ }+ return { approved, failed };+}++export async function rejectAnnouncement(id) {+ const [out] = await sql`+ update event_market_announcements set status = 'rejected', approved_by = null, approved_at = null, updated_at = now()+ where id = ${id} and status in ('draft','approved') returning *+ `;+ if (!out) throw new ReviewError('conflict', 'only a draft or approved announcement can be rejected', 409);+ return out;+}diff --git a/api/_lib/migrations/20261012020000_event_market_announcements.sql b/api/_lib/migrations/20261012020000_event_market_announcements.sqlnew file mode 100644index 000000000..df7e5ea6f--- /dev/null+++ b/api/_lib/migrations/20261012020000_event_market_announcements.sql@@ -0,0 +1,26 @@+-- Event Market announcement outbox: drafts the cron writes when a market's+-- lifecycle changes, held for owner review and sent only by+-- api/_lib/event-markets/poster.js once approved. Idempotent.+-- One announcement per kind per market, whatever its status: a rejected draft is+-- a decision, not a slot for the next cron tick to refill.++create table if not exists event_market_announcements (+ id uuid primary key default gen_random_uuid(),+ market_id uuid not null references event_markets(id) on delete cascade,+ kind text not null check (kind in ('opened','locking_soon','odds_shift','resolved')),+ draft_text text not null,+ card_url text,+ tags text[] not null default '{}',+ -- 'posting' is the poster's claim while a send is in flight, so two ticks never send one draft twice.+ status text not null default 'draft' check (status in ('draft','approved','posting','posted','rejected')),+ baseline jsonb not null default '{}'::jsonb,+ approved_by uuid references users(id) on delete set null,+ approved_at timestamptz,+ posted_at timestamptz,+ post_url text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ unique (market_id, kind)+);++create index if not exists event_market_announcements_status on event_market_announcements (status, created_at);diff --git a/api/cron/event-market-announce.js b/api/cron/event-market-announce.jsnew file mode 100644index 000000000..af7c38c0c--- /dev/null+++ b/api/cron/event-market-announce.js@@ -0,0 +1,16 @@+// GET /api/cron/event-market-announce: writes announcement DRAFTS for Event+// Markets whose lifecycle changed (opened, locking soon, odds shifted, resolved).+// It never posts and never approves: drafts wait in the admin review queue.+// Idempotent, a second tick writes nothing new. Library:+// api/_lib/event-markets/announce.js. Guide: docs/event-markets.md.++import { json, method, wrapCron } from '../_lib/http.js';+import { requireCron } from '../_lib/cron-auth.js';+import { draftPending } from '../_lib/event-markets/announce.js';++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;+ const { written, skipped } = await draftPending();+ return json(res, 200, { ok: true, drafted: written.length, written, skipped }, { 'cache-control': 'no-store' });+});diff --git a/api/event-markets/announcements.js b/api/event-markets/announcements.jsnew file mode 100644index 000000000..e7ac47967--- /dev/null+++ b/api/event-markets/announcements.js@@ -0,0 +1,58 @@+// /api/event-markets/announcements: the admin review queue for Event Market+// announcement drafts. Admin only.+// GET ?status=draft|approved|posted|rejected the queue+// POST { action: 'approve', ids: [uuid] } approve one or a whole batch+// POST { action: 'edit', id, text } edit (sends the draft back to review)+// POST { action: 'reject', id }+// POST { action: 'send', id, dry_run? } dry run by default; a live send+// needs dry_run:false AND the flag+// The sender is api/_lib/event-markets/poster.js. Guide: docs/event-markets.md.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { requireAdmin } from '../_lib/admin.js';+import { requireCsrf } from '../_lib/csrf.js';+import { isUuid } from '../_lib/validate.js';+import { approveAnnouncements, editAnnouncement, listAnnouncements, rejectAnnouncement, ReviewError } from '../_lib/event-markets/review.js';+import { PosterError, postingEnabled, sendAnnouncement } from '../_lib/event-markets/poster.js';++const STATUSES = ['draft', 'approved', 'posting', 'posted', 'rejected'];++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;+ const admin = await requireAdmin(req, res);+ if (!admin) return;++ if (req.method === 'GET') {+ const status = new URL(req.url, 'http://x').searchParams.get('status');+ if (status && !STATUSES.includes(status)) return error(res, 400, 'validation_error', `status must be one of ${STATUSES.join(', ')}`);+ const announcements = await listAnnouncements({ status });+ return json(res, 200, { announcements, posting_enabled: postingEnabled() }, { 'cache-control': 'no-store' });+ }++ if (!(await requireCsrf(req, res, admin.id))) return;+ const body = (await readJson(req)) || {};+ try {+ switch (body.action) {+ case 'approve': {+ const ids = Array.isArray(body.ids) ? body.ids : [];+ if (!ids.length || ids.length > 50 || !ids.every(isUuid)) return error(res, 400, 'validation_error', 'ids must be 1 to 50 uuids');+ return json(res, 200, await approveAnnouncements(ids, admin.id));+ }+ case 'edit':+ if (!isUuid(body.id) || typeof body.text !== 'string') return error(res, 400, 'validation_error', 'id (uuid) and text required');+ return json(res, 200, { announcement: await editAnnouncement(body.id, body.text.trim()) });+ case 'reject':+ if (!isUuid(body.id)) return error(res, 400, 'validation_error', 'id must be a uuid');+ return json(res, 200, { announcement: await rejectAnnouncement(body.id) });+ case 'send':+ if (!isUuid(body.id)) return error(res, 400, 'validation_error', 'id must be a uuid');+ return json(res, 200, await sendAnnouncement(body.id, { dryRun: body.dry_run !== false }));+ default:+ return error(res, 400, 'validation_error', 'action must be approve, edit, reject or send');+ }+ } catch (err) {+ if (err instanceof ReviewError || err instanceof PosterError) return error(res, err.status, err.code, err.message);+ throw err;+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex 9cf7f5ea2..a5649d231 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-10",+ "title": "Event Market announcements draft themselves, and nothing posts until you approve it",+ "summary": "When an Event Market opens, nears its lock, shifts, or resolves, a draft announcement now appears in a review queue with the market link and card. Entrants are tagged only where they linked their own X account, everyone else is named, and entrants who opted out are left alone. Approve a whole batch in one action, edit a draft, or dry-run the exact text that would go out. Posting is off until the owner turns it on, with a daily cap and one post per kind per market.",+ "tags": [+ "feature"+ ],+ "link": "/admin/event-market-announcements"+ },{"date": "2026-10-10","title": "Launch a coin from a quote the agent wallet pays, with a creator-fee picker and a live status",diff --git a/data/event-markets-announcements.json b/data/event-markets-announcements.jsonnew file mode 100644index 000000000..46b1b5195--- /dev/null+++ b/data/event-markets-announcements.json@@ -0,0 +1,8 @@+{+ "$comment": "Announcement lane numbers for Event Markets. Drafts only: posting is a separate, owner-approved step. oddsShiftPoints is how many points of the crowd's share the leader must gain since the market opened (or any change of leader) before a shift is worth a post, and only once minPicksForOddsShift picks exist.",+ "lockingSoonHours": 24,+ "oddsShiftPoints": 15,+ "minPicksForOddsShift": 5,+ "dailyCap": 4,+ "topForecasters": 3+}diff --git a/docs/event-markets.md b/docs/event-markets.mdnew file mode 100644index 000000000..103fe5248--- /dev/null+++ b/docs/event-markets.md@@ -0,0 +1,58 @@+# Event Markets++A free-to-play "who wins this?" market for every three.ws event, with the entrants as outcomes. Picks carry points, never funds. Build briefs: [docs/prompts/event-markets/](prompts/event-markets/README.md). Core module: `api/_lib/event-markets/`.++## Announcements++A market that is not announced does not get picks, and the announcement is what tags the entrants so they show their own audiences. The announcement lane writes the drafts, holds them for review, and sends only what the owner approved.++### The flow++1. **Cron drafts.** `/api/cron/event-market-announce` (every 15 minutes) scans open, locked and resolved markets and writes a draft per kind that is due. It never posts and never approves. It reads market state directly (status, lock time, picks), so a missed tick catches up on the next one.+2. **Review.** `/admin/event-market-announcements` lists drafts. Edit, reject, approve one, or approve a batch in one action. Editing sends an approved draft back to review, so the text that goes out is always the text that was approved.+3. **Send.** `api/_lib/event-markets/poster.js` is the only sender. It refuses anything not `approved`, re-checks the text, enforces the daily cap, and sends nothing unless the flag is on and the call is not a dry run.++### Kinds++| Kind | When | Content |+| --- | --- | --- |+| `opened` | the market is open | the question, the entrants (tagged where linked), the link |+| `locking_soon` | within `lockingSoonHours` of the lock | time left, the current leader and its share, or an honest "no picks yet" |+| `odds_shift` | the leader changed, or gained `oddsShiftPoints` since the market opened, with at least `minPicksForOddsShift` picks | the new leader and pick count |+| `resolved` | a winner is set | the winner, the crowd's share, the first forecasters to call it, the market page as evidence |++One announcement per kind per market, enforced by a unique key on `(market_id, kind)`. A rejected draft is a decision and is not refilled. Numbers live in `data/event-markets-announcements.json`.++### Tagging rules++- A handle is tagged only when the entrant linked it to their own account through X OAuth: an agent's own connection (`agent_x_connections`), else its owner's (`social_connections`). Handles are never scraped, guessed or typed in by an admin: an edit may not add an `@` mention that is not in the draft's `tags`.+- An entrant with no linked handle is named, not tagged.+- An entrant who opted out (`event_market_entrant_prefs`) is neither tagged nor featured. The drafter reads `taggableEntrants`, the same source the entrant notifications use.+- At most three tags per post, dropped last-first until the post fits 280 characters.++### Voice++Every draft passes the house editorial lint (`api/_lib/x-content/editorial.js`: brand spelling, no price promises, no slang, no engagement asks). Copy is positive and states only what the market's own data says. No other coin is named.++### Enabling posting (owner steps)++Posting is off by default. Dry run is always safe:++```+POST /api/event-markets/announcements { "action": "send", "id": "<uuid>" }+```++It returns `would_send.text`, the exact text and the call a live send would make, and changes nothing. To send for real, the owner approves the drafts in the queue, then enables the flag and sends with `dry_run: false`:++```+gcloud run services update three-ws-api --region us-central1 --update-env-vars EVENT_MARKET_ANNOUNCE_POST=on+POST /api/event-markets/announcements { "action": "send", "id": "<uuid>", "dry_run": false }+```++What the owner must approve: (1) the posts themselves, one by one or as a batch in the queue, and (2) turning the flag on. Posts go out from @trythreews through the same `X_API_KEY`, `X_API_SECRET`, `X_ACCESS_TOKEN`, `X_ACCESS_SECRET` credentials as the x-content publisher. A daily cap (`dailyCap`, default 4 posts per rolling 24 hours) applies on top.++### Table++`event_market_announcements`: `market_id`, `kind`, `draft_text`, `card_url`, `tags`, `status` (`draft`, `approved`, `posting`, `posted`, `rejected`), `approved_by`, `posted_at`, `post_url`, `baseline` (odds snapshot at draft time). `posting` is the poster's in-flight claim, so two ticks never send one draft twice.++Tests: [tests/event-market-announcements.test.js](../tests/event-market-announcements.test.js).diff --git a/pages/event-market-announcements.html b/pages/event-market-announcements.htmlnew file mode 100644index 000000000..f7322e162--- /dev/null+++ b/pages/event-market-announcements.html@@ -0,0 +1,241 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <script>/* three.ws theme boot: no-flash */(function(){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, viewport-fit=cover" />+ <meta name="robots" content="noindex" />+ <title>Announcement queue · Event Markets · three.ws</title>+ <meta name="description" content="Admin review queue for Event Market announcement drafts: edit, approve a batch, reject, and dry-run the exact post before anything is sent." />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <style>+ * { box-sizing: border-box; }+ html, body { margin: 0; background: var(--bg-0); color: var(--ink); }+ body { font-family: var(--font-body, 'Inter', system-ui, sans-serif); min-height: 100vh; }+ .emq { max-width: 880px; margin: 0 auto; padding: 44px 18px 96px; }+ .emq h1 { font-size: clamp(1.6rem, 4.5vw, 2.3rem); margin: 0 0 8px; letter-spacing: -0.03em; color: var(--ink-bright, var(--ink)); }+ .emq-lede { margin: 0 0 20px; color: var(--ink-dim); line-height: 1.55; max-width: 62ch; }+ .emq-flag { border: 1px solid var(--stroke-strong); border-radius: 10px; padding: 10px 14px; margin: 0 0 18px; font-size: 0.9rem; color: var(--ink-dim); }+ .emq-flag[data-on="true"] { border-color: var(--accent); color: var(--ink); }+ .emq-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 0 0 16px; }+ .emq-tab, .emq-btn { font: inherit; font-size: 0.88rem; font-weight: 600; padding: 8px 14px; border-radius: 10px; border: 1px solid var(--stroke-strong); background: transparent; color: var(--ink); cursor: pointer; transition: background 140ms ease, border-color 140ms ease; }+ .emq-tab:hover, .emq-btn:hover { background: var(--surface-2, rgba(255,255,255,0.06)); }+ .emq-tab:active, .emq-btn:active { transform: translateY(1px); }+ .emq-tab:focus-visible, .emq-btn:focus-visible, .emq textarea:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .emq-tab[aria-selected="true"] { border-color: var(--accent); color: var(--accent); }+ .emq-btn[data-primary] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink, #000); }+ .emq-btn[disabled] { opacity: 0.45; cursor: not-allowed; }+ .emq-spacer { flex: 1; }+ .emq-card { border: 1px solid var(--stroke-strong); border-radius: 14px; background: var(--surface-2, rgba(255,255,255,0.04)); padding: 16px; margin: 0 0 12px; }+ .emq-head { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin: 0 0 10px; font-size: 0.82rem; color: var(--ink-dim); }+ .emq-head a { color: var(--accent); text-decoration: none; font-weight: 600; }+ .emq-head a:hover { text-decoration: underline; }+ .emq-kind { text-transform: uppercase; letter-spacing: 0.07em; font-weight: 650; font-size: 0.72rem; }+ .emq-text { white-space: pre-wrap; word-break: break-word; line-height: 1.5; margin: 0 0 10px; }+ .emq textarea { width: 100%; min-height: 120px; font: inherit; color: var(--ink); background: var(--bg-0); border: 1px solid var(--stroke-strong); border-radius: 10px; padding: 10px; resize: vertical; }+ .emq-meta { font-size: 0.8rem; color: var(--ink-dim); margin: 0 0 10px; }+ .emq-actions { display: flex; flex-wrap: wrap; gap: 8px; }+ .emq-note { margin: 10px 0 0; padding: 10px 12px; border-radius: 10px; border: 1px dashed var(--stroke-strong); font-size: 0.85rem; white-space: pre-wrap; word-break: break-word; }+ .emq-note[data-error] { border-color: #d9534f; }+ .emq-empty { border: 1px dashed var(--stroke-strong); border-radius: 14px; padding: 28px; text-align: center; color: var(--ink-dim); line-height: 1.6; }+ .emq-skel { height: 118px; border-radius: 14px; margin: 0 0 12px; background: linear-gradient(90deg, var(--surface-2, rgba(255,255,255,0.04)), var(--stroke-strong), var(--surface-2, rgba(255,255,255,0.04))); background-size: 200% 100%; animation: emq-shimmer 1.4s linear infinite; }+ @keyframes emq-shimmer { to { background-position: -200% 0; } }+ @media (prefers-reduced-motion: reduce) { .emq-skel { animation: none; } }+ </style>+</head>+<body>+ <script src="/nav.js"></script>+ <main class="emq">+ <h1>Announcement queue</h1>+ <p class="emq-lede">Drafts the cron wrote when an Event Market opened, neared its lock, shifted or resolved. Nothing is posted until you approve it, and the dry run shows the exact text that would go out.</p>+ <div class="emq-flag" id="flag" role="status"></div>+ <div class="emq-bar" role="tablist" aria-label="Announcement status" id="tabs"></div>+ <div class="emq-bar" id="batch" hidden>+ <label><input type="checkbox" id="all" /> Select all drafts</label>+ <span class="emq-spacer"></span>+ <button class="emq-btn" data-primary id="approve-batch" type="button">Approve selected</button>+ </div>+ <div id="list" aria-live="polite"></div>+ </main>+ <script type="module">+ const STATUSES = ['draft', 'approved', 'posted', 'rejected'];+ const state = { status: 'draft', rows: [], selected: new Set(), csrf: null };+ const $ = (id) => document.getElementById(id);++ const el = (tag, props = {}, ...kids) => {+ const n = Object.assign(document.createElement(tag), props);+ for (const k of kids) n.append(k);+ return n;+ };++ async function csrf() {+ if (state.csrf) return state.csrf;+ const r = await fetch('/api/csrf-token', { credentials: 'include' });+ const j = await r.json().catch(() => ({}));+ state.csrf = j.data?.token || j.token || null;+ return state.csrf;+ }++ async function call(body) {+ const token = await csrf();+ const r = await fetch('/api/event-markets/announcements', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json', ...(token ? { 'x-csrf-token': token } : {}) },+ body: JSON.stringify(body),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || j.message || `request failed (${r.status})`);+ return j.data || j;+ }++ function renderTabs() {+ const tabs = $('tabs');+ tabs.replaceChildren(...STATUSES.map((s) => {+ const b = el('button', { className: 'emq-tab', type: 'button', textContent: s[0].toUpperCase() + s.slice(1) });+ b.setAttribute('role', 'tab');+ b.setAttribute('aria-selected', String(s === state.status));+ b.onclick = () => { state.status = s; state.selected.clear(); load(); };+ return b;+ }));+ }++ function note(card, text, isError) {+ card.querySelector('.emq-note')?.remove();+ const n = el('p', { className: 'emq-note', textContent: text });+ n.setAttribute('role', isError ? 'alert' : 'status');+ if (isError) n.setAttribute('data-error', '');+ card.append(n);+ }++ function card(row) {+ const c = el('article', { className: 'emq-card' });+ const head = el('div', { className: 'emq-head' });+ if (row.status === 'draft') {+ const cb = el('input', { type: 'checkbox', checked: state.selected.has(row.id) });+ cb.setAttribute('aria-label', `Select ${row.kind} draft for ${row.title}`);+ cb.onchange = () => { cb.checked ? state.selected.add(row.id) : state.selected.delete(row.id); syncBatch(); };+ head.append(cb);+ }+ head.append(el('span', { className: 'emq-kind', textContent: row.kind.replace('_', ' ') }));+ head.append(el('a', { href: `/event-markets/${encodeURIComponent(row.slug)}`, textContent: row.title }));+ head.append(el('span', { textContent: new Date(row.created_at).toLocaleString() }));+ c.append(head);++ const text = el('p', { className: 'emq-text', textContent: row.draft_text });+ c.append(text);+ const tags = row.tags?.length ? `Tags: ${row.tags.map((t) => '@' + t).join(', ')} (linked handles only)` : 'No tags: no entrant here has a linked handle.';+ c.append(el('p', { className: 'emq-meta', textContent: tags }));+ if (row.post_url) c.append(el('a', { href: row.post_url, textContent: 'View post', target: '_blank', rel: 'noopener' }));++ const actions = el('div', { className: 'emq-actions' });+ const btn = (label, fn, primary) => {+ const b = el('button', { className: 'emq-btn', type: 'button', textContent: label });+ if (primary) b.setAttribute('data-primary', '');+ b.onclick = async () => {+ b.disabled = true;+ try { await fn(b); } catch (e) { note(c, e.message, true); } finally { b.disabled = false; }+ };+ return b;+ };+ if (row.status === 'draft' || row.status === 'approved') {+ actions.append(btn('Edit', () => edit(c, row)));+ actions.append(btn('Reject', async () => { await call({ action: 'reject', id: row.id }); await load(); }));+ }+ if (row.status === 'draft') actions.append(btn('Approve', async () => { await approve([row.id], c); }, true));+ if (row.status === 'approved') actions.append(btn('Dry run send', async () => {+ const out = await call({ action: 'send', id: row.id, dry_run: true });+ note(c, `Dry run. This exact text would be sent, nothing was:\n\n${out.would_send.text}\n\nPosting flag is ${out.flag_on ? 'ON' : 'OFF'}.`, false);+ }, true));+ c.append(actions);+ return c;+ }++ function edit(c, row) {+ const ta = el('textarea', { value: row.draft_text });+ ta.setAttribute('aria-label', 'Draft text');+ const count = el('p', { className: 'emq-meta' });+ const upd = () => { count.textContent = `${ta.value.length} characters (links count as 23 on X). Editing sends an approved draft back to review.`; };+ ta.oninput = upd; upd();+ const save = el('button', { className: 'emq-btn', type: 'button', textContent: 'Save draft' });+ save.setAttribute('data-primary', '');+ save.onclick = async () => {+ save.disabled = true;+ try { await call({ action: 'edit', id: row.id, text: ta.value.trim() }); await load(); }+ catch (e) { note(c, e.message, true); save.disabled = false; }+ };+ c.querySelector('.emq-text').replaceWith(ta);+ c.append(count, save);+ ta.focus();+ }++ async function approve(ids, anchor) {+ const out = await call({ action: 'approve', ids });+ state.selected.clear();+ await load();+ if (out.failed?.length) {+ const msg = out.failed.map((f) => `${f.id.slice(0, 8)}: ${f.reason}`).join('\n');+ $('list').prepend(el('p', { className: 'emq-note', textContent: `Approved ${out.approved.length}. Not approved:\n${msg}` }));+ }+ }++ function syncBatch() {+ const drafts = state.rows.filter((r) => r.status === 'draft');+ $('batch').hidden = state.status !== 'draft' || !drafts.length;+ $('approve-batch').disabled = !state.selected.size;+ $('approve-batch').textContent = state.selected.size ? `Approve ${state.selected.size} selected` : 'Approve selected';+ $('all').checked = drafts.length > 0 && state.selected.size === drafts.length;+ }++ function renderList() {+ const list = $('list');+ if (!state.rows.length) {+ list.replaceChildren(el('div', { className: 'emq-empty', textContent: state.status === 'draft'+ ? 'No drafts waiting. The cron writes one when a market opens, nears its lock, shifts, or resolves. Open a market and check back within 15 minutes.'+ : `Nothing is ${state.status} yet.` }));+ } else {+ list.replaceChildren(...state.rows.map(card));+ }+ syncBatch();+ }++ async function load() {+ renderTabs();+ $('list').replaceChildren(el('div', { className: 'emq-skel' }), el('div', { className: 'emq-skel' }));+ try {+ const r = await fetch(`/api/event-markets/announcements?status=${state.status}`, { credentials: 'include' });+ const j = await r.json().catch(() => ({}));+ if (r.status === 401 || r.status === 403) throw new Error('Admin sign-in required. Sign in with an admin account, then reload.');+ if (!r.ok) throw new Error(j.error_description || j.message || `could not load the queue (${r.status})`);+ const data = j.data || j;+ state.rows = data.announcements;+ $('flag').dataset.on = String(data.posting_enabled);+ $('flag').textContent = data.posting_enabled+ ? 'Posting is ON. Approved announcements can be sent live.'+ : 'Posting is OFF (EVENT_MARKET_ANNOUNCE_POST is not "on"). Approving and dry runs work; nothing can be sent live.';+ renderList();+ } catch (e) {+ const retry = el('button', { className: 'emq-btn', type: 'button', textContent: 'Try again' });+ retry.onclick = load;+ const box = el('div', { className: 'emq-empty', textContent: e.message });+ box.setAttribute('role', 'alert');+ $('list').replaceChildren(box, retry);+ }+ }++ $('all').onchange = (e) => {+ state.selected = new Set(e.target.checked ? state.rows.filter((r) => r.status === 'draft').map((r) => r.id) : []);+ renderList();+ };+ $('approve-batch').onclick = async (e) => {+ e.target.disabled = true;+ try { await approve([...state.selected]); } catch (err) { $('list').prepend(el('p', { className: 'emq-note', textContent: err.message })); }+ };+ load();+ </script>+</body>+</html>diff --git a/tests/event-market-announcements.test.js b/tests/event-market-announcements.test.jsnew file mode 100644index 000000000..d6919fe33--- /dev/null+++ b/tests/event-market-announcements.test.js@@ -0,0 +1,263 @@+// Event Market announcement lane: each draft kind, handle tagging, the one-per-kind+// dedupe, and the poster's refusal to send anything not approved. The database is+// an in-memory fake that answers exactly the queries the lane issues.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const db = { optOut: new Set(), markets: [], outcomes: [], picks: [], ann: [], agentX: new Map(), users: [], nextId: 1 };+const id = () => `00000000-0000-4000-8000-${String(db.nextId++).padStart(12, '0')}`;++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...v) => {+ const q = strings.join('?').replace(/\s+/g, ' ').trim().toLowerCase();+ if (q.includes('from agent_x_connections')) return db.agentX.has(v[0]) ? [{ username: db.agentX.get(v[0]) }] : [];+ if (q.includes('from social_connections')) return [];+ if (q.includes('from event_markets m where m.status')) return db.markets.filter((m) => ['open', 'locked', 'resolved'].includes(m.status) && db.ann.filter((a) => a.market_id === m.id).length < 4);+ if (q.includes('select kind, baseline from event_market_announcements')) return db.ann.filter((a) => a.market_id === v[0]);+ if (q.includes('from event_market_picks p join users')) return db.users;+ if (q.startsWith('insert into event_market_announcements')) {+ const [market_id, kind, draft_text, card_url, tags, baseline] = v;+ if (db.ann.some((a) => a.market_id === market_id && a.kind === kind)) return [];+ const row = { id: id(), market_id, kind, draft_text, card_url, tags, status: 'draft', baseline: JSON.parse(baseline), posted_at: null };+ db.ann.push(row);+ return [row];+ }+ if (q.includes('select * from event_market_announcements where id')) return db.ann.filter((a) => a.id === v[0]);+ if (q.includes("count(*)::int as n from event_market_announcements")) return [{ n: db.ann.filter((a) => a.status === 'posted').length }];+ if (q.includes("set status = 'posting'")) {+ const a = db.ann.find((x) => x.id === v[0] && x.status === 'approved');+ if (!a) return [];+ a.status = 'posting';+ return [{ id: a.id }];+ }+ if (q.includes("set status = 'posted'")) {+ const a = db.ann.find((x) => x.id === v[1]);+ Object.assign(a, { status: 'posted', post_url: v[0], posted_at: new Date() });+ return [a];+ }+ if (q.includes("set status = 'approved', updated_at")) {+ const a = db.ann.find((x) => x.id === v[0] && x.status === 'posting');+ if (a) a.status = 'approved';+ return [];+ }+ if (q.includes("set status = 'approved', approved_by")) {+ const a = db.ann.find((x) => x.id === v[1] && x.status === 'draft');+ if (!a) return [];+ Object.assign(a, { status: 'approved', approved_by: v[0] });+ return [a];+ }+ if (q.includes('set draft_text')) {+ const a = db.ann.find((x) => x.id === v[1]);+ Object.assign(a, { draft_text: v[0], status: 'draft' });+ return [a];+ }+ throw new Error(`unhandled query: ${q}`);+ }),+}));++// The getMarket view as the core module serves it: outcomes carry crowd share,+// the winner is an object, odds say whether the split is only the even prior.+const PRIOR = 50;+function view(mid) {+ const m = db.markets.find((x) => x.id === mid);+ if (!m) return null;+ const outs = db.outcomes.filter((o) => o.market_id === mid);+ const picks = db.picks.filter((p) => p.market_id === mid);+ const total = picks.reduce((n, p) => n + p.points, 0);+ return {+ ...m,+ pick_count: picks.length,+ odds: { even_prior: picks.length === 0 },+ winner: m.winner_outcome_id ? { outcome_id: m.winner_outcome_id } : null,+ outcomes: outs.map((o) => {+ const points = picks.filter((p) => p.outcome_id === o.id).reduce((n, p) => n + p.points, 0);+ return { ...o, points, share: (points + PRIOR) / (total + PRIOR * outs.length) };+ }),+ };+}+vi.mock('../api/_lib/event-markets/index.js', () => ({ getMarket: async (mid) => globalThis.__view(mid) }));+globalThis.__view = view;+vi.mock('../api/_lib/event-markets/entrants.js', () => ({+ taggableEntrants: async (market) => market.outcomes.filter((o) => !db.optOut.has(o.id)).map((outcome) => ({ outcome, accountId: `acct-${outcome.ref_id}` })),+}));++const { buildDraft, draftPending, oddsShifted, lint } = await import('../api/_lib/event-markets/announce.js');+const { approveAnnouncements, editAnnouncement } = await import('../api/_lib/event-markets/review.js');+const { sendAnnouncement, PosterError } = await import('../api/_lib/event-markets/poster.js');++const NOW = new Date('2026-10-12T12:00:00Z');+const M = id();+const A = id(), B = id(), C = id();++function seed({ status = 'open', locks = '2026-10-13T06:00:00Z', winner = null } = {}) {+ Object.assign(db, { optOut: new Set(), markets: [], outcomes: [], picks: [], ann: [], agentX: new Map(), users: [] });+ db.markets.push({ id: M, slug: 'spring-build-round', title: 'the Spring Build Round', status, locks_at: locks, winner_outcome_id: winner, created_at: NOW });+ db.outcomes.push(+ { id: A, market_id: M, label: 'Atlas', ref_kind: 'agent', ref_id: 'agent-a', position: 0 },+ { id: B, market_id: M, label: 'Borealis', ref_kind: 'agent', ref_id: 'agent-b', position: 1 },+ { id: C, market_id: M, label: 'Cinder', ref_kind: 'agent', ref_id: 'agent-c', position: 2 },+ );+ db.agentX.set('agent-a', 'atlas_agent');+ db.agentX.set('agent-b', 'borealis');+}+const ctx = async (extra = {}) => ({ market: view(M), handles: new Map([[A, 'atlas_agent'], [B, 'borealis']]), now: NOW, ...extra });++beforeEach(() => seed());++describe('draft kinds', () => {+ it('opened: tags only entrants with a linked handle, names the rest, carries link and card', async () => {+ const d = buildDraft('opened', await ctx());+ expect(d.tags).toEqual(['atlas_agent', 'borealis']);+ expect(d.text).toContain('@atlas_agent');+ expect(d.text).toContain('Cinder');+ expect(d.text).not.toContain('@Cinder');+ expect(d.text).toContain('https://three.ws/event-markets/spring-build-round');+ expect(d.card_url).toContain('slug=spring-build-round');+ expect(lint(d.text)).toEqual([]);+ });++ it('opened: an entrant with no linked handle is never tagged', async () => {+ const d = buildDraft('opened', await ctx({ handles: new Map() }));+ expect(d.tags).toEqual([]);+ expect(d.text).not.toMatch(/@\w/);+ });++ it('locking_soon: says the hours left and the leader once picks exist', async () => {+ db.picks.push({ market_id: M, outcome_id: A, points: 80 }, { market_id: M, outcome_id: B, points: 20 });+ const d = buildDraft('locking_soon', await ctx());+ expect(d.text).toContain('in 18 hours');+ expect(d.text).toContain('@atlas_agent leads');+ expect(d.tags).toEqual(['atlas_agent']);+ });++ it('locking_soon: an empty market says so instead of inventing a favourite', async () => {+ const d = buildDraft('locking_soon', await ctx());+ expect(d.text).toContain('No picks have landed yet');+ expect(d.tags).toEqual([]);+ });++ it('odds_shift: names the new leader and the pick count', async () => {+ db.picks.push({ market_id: M, outcome_id: B, points: 90 }, { market_id: M, outcome_id: A, points: 10 });+ const d = buildDraft('odds_shift', await ctx({ baseline: { leader_id: A } }));+ expect(d.text).toContain('@borealis now leads');+ expect(d.text).toContain('after Atlas held the top spot');+ });++ it('resolved: names the winner and the first forecasters, and only when a winner exists', async () => {+ seed({ status: 'resolved', winner: B });+ db.picks.push({ market_id: M, outcome_id: B, points: 60 }, { market_id: M, outcome_id: A, points: 40 });+ const d = buildDraft('resolved', await ctx({ forecasters: ['Mira', 'Jo'] }));+ expect(d.text).toContain('@borealis won');+ expect(d.text).toContain('First to call it: Mira and Jo.');+ db.markets[0].winner_outcome_id = null;+ expect(buildDraft('resolved', await ctx())).toBeNull();+ });++ it('every draft fits in 280 weighted characters even with a long field', async () => {+ const many = Array.from({ length: 40 }, (_, i) => ({ id: id(), market_id: M, label: `Entrant number ${i} with a long name`, ref_kind: 'agent' }));+ const d = buildDraft('opened', { market: { ...db.markets[0], pick_count: 0, odds: { even_prior: true }, outcomes: many.map((o) => ({ ...o, share: 1 / 40 })) }, handles: new Map(many.map((o, i) => [o.id, `h${i}`])), now: NOW });+ expect(d.text.length).toBeLessThanOrEqual(280);+ });++ it('house voice: no price promises or em dashes', () => {+ expect(lint('Atlas will moon, a guaranteed 10x.').length).toBeGreaterThan(0);+ });+});++describe('odds shift threshold', () => {+ const withPicks = (picks) => { db.picks.push(...picks.map((p) => ({ market_id: M, ...p }))); return view(M); };+ it('stays quiet below the minimum picks', () => {+ expect(oddsShifted(withPicks([{ outcome_id: B, points: 100 }]), { leader_id: A })).toBe(false);+ });+ it('fires when the leader changes with enough picks', () => {+ expect(oddsShifted(withPicks(Array.from({ length: 5 }, () => ({ outcome_id: B, points: 20 }))), { leader_id: A })).toBe(true);+ });+ it('fires when the leader gains the configured points, not before', () => {+ const base = { leader_id: A, shares: { [A]: 0.34 } };+ const mk = (n) => withPicks([...Array.from({ length: 5 }, () => ({ outcome_id: A, points: n })), { outcome_id: B, points: 40 }, { outcome_id: C, points: 40 }]);+ expect(oddsShifted(mk(60), base)).toBe(true);+ db.picks.length = 0;+ expect(oddsShifted(mk(4), base)).toBe(false);+ });+});++describe('draftPending', () => {+ it('writes an opened draft once and dedupes on the next tick', async () => {+ const first = await draftPending({ now: NOW });+ expect(first.written.map((w) => w.kind).sort()).toEqual(['locking_soon', 'opened']);+ const second = await draftPending({ now: NOW });+ expect(second.written).toEqual([]);+ expect(db.ann.filter((a) => a.kind === 'opened')).toHaveLength(1);+ });++ it('does not announce locking_soon outside the window', async () => {+ db.markets[0].locks_at = '2026-10-20T00:00:00Z';+ const r = await draftPending({ now: NOW });+ expect(r.written.map((w) => w.kind)).toEqual(['opened']);+ });++ it('a rejected draft is not refilled', async () => {+ await draftPending({ now: NOW });+ db.ann.find((a) => a.kind === 'opened').status = 'rejected';+ const r = await draftPending({ now: NOW });+ expect(r.written.find((w) => w.kind === 'opened')).toBeUndefined();+ });+});++describe('review and poster', () => {+ const draftOpened = async () => {+ await draftPending({ now: NOW });+ return db.ann.find((a) => a.kind === 'opened');+ };++ it('refuses to send a draft that is not approved', async () => {+ const a = await draftOpened();+ await expect(sendAnnouncement(a.id)).rejects.toMatchObject({ code: 'not_approved' });+ await expect(sendAnnouncement(a.id, { dryRun: false, env: { EVENT_MARKET_ANNOUNCE_POST: 'on' }, client: { tweet: vi.fn() } })).rejects.toMatchObject({ code: 'not_approved' });+ });++ it('dry run after approval shows exactly the approved text and sends nothing', async () => {+ const a = await draftOpened();+ await approveAnnouncements([a.id], 'admin-1');+ const out = await sendAnnouncement(a.id);+ expect(out.dry_run).toBe(true);+ expect(out.would_send.text).toBe(a.draft_text);+ expect(out.calls).toEqual([expect.objectContaining({ call: 'tweets.create', text: a.draft_text })]);+ expect(db.ann.find((x) => x.id === a.id).status).toBe('approved');+ });++ it('a live send stays off until the flag is on, then sends the approved text once', async () => {+ const a = await draftOpened();+ await approveAnnouncements([a.id], 'admin-1');+ const client = { tweet: vi.fn(async (p) => ({ data: { id: '123', text: p.text } })) };+ await expect(sendAnnouncement(a.id, { dryRun: false, env: {}, client })).rejects.toMatchObject({ code: 'posting_disabled' });+ expect(client.tweet).not.toHaveBeenCalled();+ const out = await sendAnnouncement(a.id, { dryRun: false, env: { EVENT_MARKET_ANNOUNCE_POST: 'on' }, client });+ expect(client.tweet).toHaveBeenCalledWith({ text: a.draft_text });+ expect(out.announcement.status).toBe('posted');+ await expect(sendAnnouncement(a.id, { dryRun: false, env: { EVENT_MARKET_ANNOUNCE_POST: 'on' }, client })).rejects.toBeInstanceOf(PosterError);+ expect(client.tweet).toHaveBeenCalledTimes(1);+ });++ it('enforces the daily cap', async () => {+ const a = await draftOpened();+ await approveAnnouncements([a.id], 'admin-1');+ for (let i = 0; i < 4; i++) db.ann.push({ id: id(), market_id: id(), kind: 'opened', status: 'posted', posted_at: new Date(), tags: [] });+ await expect(sendAnnouncement(a.id)).rejects.toMatchObject({ code: 'daily_cap' });+ });++ it('an edit may not add a handle the entrant never linked, and re-opens review', async () => {+ const a = await draftOpened();+ await expect(editAnnouncement(a.id, 'Picks are open, cc @someone_else\nhttps://three.ws/event-markets/x')).rejects.toMatchObject({ code: 'validation_error' });+ await approveAnnouncements([a.id], 'admin-1');+ const edited = await editAnnouncement(a.id, `Picks are open and free to play. ${'@atlas_agent'} is in.\nhttps://three.ws/event-markets/spring-build-round`);+ expect(edited.status).toBe('draft');+ });++ it('batch approval reports each failure instead of hiding it', async () => {+ const a = await draftOpened();+ const r = await approveAnnouncements([a.id, id()], 'admin-1');+ expect(r.approved).toHaveLength(1);+ expect(r.failed).toEqual([expect.objectContaining({ reason: 'not found' })]);+ });+});diff --git a/vercel.json b/vercel.jsonindex 73a83a90b..dee82a3ee 100644--- a/vercel.json+++ b/vercel.json@@ -2578,6 +2578,10 @@"src": "/home-next/?","status": 301,"headers": {+ {+ "src": "/admin/event-market-announcements/?",+ "dest": "/event-market-announcements.html"+ },"Location": "/"}},@@ -7347,3 +7351,7 @@}]}+ },+ {+ "path": "/api/cron/event-market-announce",+ "schedule": "*/15 * * * *"diff --git a/vite.config.js b/vite.config.jsindex eb3170ee9..325664b1f 100644--- a/vite.config.js+++ b/vite.config.js@@ -705,6 +705,7 @@ const appConfig = {connect: resolve(__dirname, 'pages/connect.html'),grok: resolve(__dirname, 'pages/grok.html'),'x-claim': resolve(__dirname, 'pages/x-claim.html'),+ 'event-market-announcements': resolve(__dirname, 'pages/event-market-announcements.html'),awesome: resolve(__dirname, 'pages/awesome.html'),prompts: resolve(__dirname, 'pages/prompts.html'),'render-lab': resolve(__dirname, 'pages/render-lab.html'),@@ -1908,6 +1909,7 @@ const appConfig = {'/ar': resolve(root, 'public/ar-forge.html'),'/ar/': resolve(root, 'public/ar-forge.html'),'/x/claim': resolve(root, 'pages/x-claim.html'),+ '/admin/event-market-announcements': resolve(root, 'pages/event-market-announcements.html'),'/x/claim/': resolve(root, 'pages/x-claim.html'),'/daily': resolve(root, 'pages/daily.html'),'/daily/': resolve(root, 'pages/daily.html'),