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: /go bounty board — submission likes + AI judge
nirholas10783fe9e079
diff --git a/api/_lib/bounty-judge.js b/api/_lib/bounty-judge.jsnew file mode 100644index 000000000..111cb68da--- /dev/null+++ b/api/_lib/bounty-judge.js@@ -0,0 +1,118 @@+// AI bounty judge — pure prompt-building + output-normalising logic.+//+// Kept free of any I/O imports (no db, no llm, no cache) so it can be unit+// tested in isolation and so importing it never drags in env-dependent modules.+// The endpoint (api/bounties/[id]/judge.js) wires this to the real LLM.++const CONTENT_CAP = 600; // per-submission text fed to the model+const VERDICT_CAP = 160;+const SUMMARY_CAP = 280;++// Build the system + user prompt for judging a bounty's submissions.+// `bounty`: { title, description }+// `subs`: [{ id, username, content, media_url, media_type, like_count }]+export function buildJudgePrompt(bounty, subs) {+ const system = [+ 'You are an impartial judge for a crypto bounty board.',+ 'A poster set a task with a reward. People submitted proof of doing it. Score how well each submission fulfils the task.',+ 'Judge on, in order: relevance to the task, quality and credibility of the proof (an attached photo / video / link is stronger evidence than a bare claim), effort, and originality.',+ 'Community likes are a weak secondary signal — use them only to break near-ties, never as the main driver. Reward genuine fulfilment, not popularity.',+ 'Give clearly off-topic, low-effort, spam, or unverifiable submissions low scores (under 35).',+ 'Do not mention or name any cryptocurrency, coin, or token in your output.',+ 'Respond with ONLY a single minified JSON object — no markdown, no code fence, no commentary — in exactly this shape:',+ '{"summary":"<=200 char read on the field and why your pick wins","recommended_id":"<one submission id>","rankings":[{"submission_id":"<id>","score":<integer 0-100>,"verdict":"<=120 char reason"}]}',+ 'Include every submission in rankings, best first. recommended_id MUST be one of the provided submission ids.',+ ].join('\n');++ const blocks = subs.map((s, i) => {+ const proof = s.media_url+ ? `[${s.media_type || 'link'} attached: ${String(s.media_url).slice(0, 300)}]`+ : '[no media attached]';+ const text =+ (s.content || '')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, CONTENT_CAP) || '(no description)';+ return [+ `Submission ${i + 1}`,+ `id: ${s.id}`,+ `author: ${s.username || 'anon'}`,+ `community_likes: ${s.like_count || 0}`,+ `proof: ${proof}`,+ `text: ${text}`,+ ].join('\n');+ });++ const user = [+ `BOUNTY TITLE: ${bounty.title}`,+ `BOUNTY DETAILS: ${bounty.description?.trim() || '(none provided)'}`,+ '',+ `SUBMISSIONS (${subs.length}):`,+ blocks.join('\n\n'),+ ].join('\n');++ return { system, user };+}++function clampScore(v) {+ const n = Math.round(Number(v));+ if (!Number.isFinite(n)) return 0;+ return Math.max(0, Math.min(100, n));+}++// Best-effort extraction of a JSON object from a model response that may be+// wrapped in prose or a ```json fence.+export function extractJson(text) {+ if (!text) return null;+ let t = String(text).trim();+ // Strip a leading/trailing markdown code fence if present.+ t = t.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();+ try {+ return JSON.parse(t);+ } catch {+ /* fall through to brace-slicing */+ }+ const start = t.indexOf('{');+ const end = t.lastIndexOf('}');+ if (start === -1 || end <= start) return null;+ try {+ return JSON.parse(t.slice(start, end + 1));+ } catch {+ return null;+ }+}++// Validate + normalise raw model text into a safe, sorted judgement.+// Throws if the output can't be salvaged into at least one valid ranking.+// `validIds` is a Set (or array) of submission ids that actually exist — any+// id the model invents is dropped, so the result can be trusted downstream.+export function normalizeJudgement(rawText, validIds) {+ const parsed = extractJson(rawText);+ if (!parsed || typeof parsed !== 'object') {+ throw new Error('judge returned unparseable output');+ }+ const valid = validIds instanceof Set ? validIds : new Set(validIds || []);+ const seen = new Set();++ const rankings = (Array.isArray(parsed.rankings) ? parsed.rankings : [])+ .map((r) => ({+ submission_id: String(r?.submission_id ?? r?.id ?? ''),+ score: clampScore(r?.score),+ verdict: typeof r?.verdict === 'string' ? r.verdict.trim().slice(0, VERDICT_CAP) : '',+ }))+ .filter((r) => {+ if (!valid.has(r.submission_id) || seen.has(r.submission_id)) return false;+ seen.add(r.submission_id);+ return true;+ })+ .sort((a, b) => b.score - a.score);++ if (!rankings.length) throw new Error('judge produced no valid rankings');++ let recommendedId = typeof parsed.recommended_id === 'string' ? parsed.recommended_id : '';+ if (!valid.has(recommendedId)) recommendedId = rankings[0].submission_id;++ const summary = typeof parsed.summary === 'string' ? parsed.summary.trim().slice(0, SUMMARY_CAP) : '';++ return { summary, recommended_id: recommendedId, rankings };+}diff --git a/api/_lib/bounty-likes.js b/api/_lib/bounty-likes.jsnew file mode 100644index 000000000..09b3f8ea9--- /dev/null+++ b/api/_lib/bounty-likes.js@@ -0,0 +1,55 @@+// Submission "likes" — read-side enrichment for the /go bounty board.+//+// Counts are computed on read (not denormalised) so the only schema this needs+// is the bounty_submission_likes table. Crucially this is ADDITIVE and+// resilient: if the table doesn't exist yet (migration not applied) or any+// query errors, rows degrade to like_count=0 / liked_by_me=false instead of+// breaking the feed. That lets the likes feature ship without a coordinated+// migrate-then-deploy.++import { sql } from './db.js';++// Mutates `rows` in place, attaching `like_count` (int) and `liked_by_me`+// (bool) to each, and returns the same array. `idField` is the property on+// each row holding the submission id. `userId` may be null for anonymous+// callers (then liked_by_me is always false).+export async function enrichLikes(rows, { idField = 'id', userId = null } = {}) {+ if (!Array.isArray(rows) || rows.length === 0) return rows;++ const ids = [...new Set(rows.map((r) => r?.[idField]).filter(Boolean))];+ if (!ids.length) return rows;++ try {+ const countRows = await sql`+ SELECT submission_id, COUNT(*)::int AS c+ FROM bounty_submission_likes+ WHERE submission_id = ANY(${ids}::uuid[])+ GROUP BY submission_id+ `;+ const counts = new Map(countRows.map((r) => [r.submission_id, r.c]));++ let liked = new Set();+ if (userId) {+ const mine = await sql`+ SELECT submission_id+ FROM bounty_submission_likes+ WHERE user_id = ${userId} AND submission_id = ANY(${ids}::uuid[])+ `;+ liked = new Set(mine.map((r) => r.submission_id));+ }++ for (const r of rows) {+ const sid = r?.[idField];+ r.like_count = counts.get(sid) || 0;+ r.liked_by_me = liked.has(sid);+ }+ } catch {+ // Table missing (pre-migration) or a transient error — degrade gracefully.+ for (const r of rows) {+ if (r.like_count == null) r.like_count = 0;+ r.liked_by_me = false;+ }+ }++ return rows;+}diff --git a/api/_lib/migrations/2026-06-08-bounty-likes.sql b/api/_lib/migrations/2026-06-08-bounty-likes.sqlnew file mode 100644index 000000000..93c642d1f--- /dev/null+++ b/api/_lib/migrations/2026-06-08-bounty-likes.sql@@ -0,0 +1,17 @@+-- Submission upvotes ("likes") for the /go bounty board.+--+-- Pure social-proof layer: one row per (submission, user). Counts are computed+-- on read (see api/_lib/bounty-likes.js) rather than denormalised, so this+-- migration only adds a table and never alters bounty_submissions — the board+-- keeps working even if this hasn't been applied yet (enrichment degrades to+-- zero likes).++CREATE TABLE IF NOT EXISTS bounty_submission_likes (+ submission_id UUID NOT NULL REFERENCES bounty_submissions(id) ON DELETE CASCADE,+ user_id UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (submission_id, user_id)+);++CREATE INDEX IF NOT EXISTS bsl_submission_idx ON bounty_submission_likes(submission_id);+CREATE INDEX IF NOT EXISTS bsl_user_idx ON bounty_submission_likes(user_id);diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex bd0609f78..fd63305d8 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -205,6 +205,11 @@ export const limits = {getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),chatUser: (userId) => getLimiter('chat:user', { limit: 40, window: '1 m' }).limit(userId),chatIp: (ip) => getLimiter('chat:ip', { limit: 60, window: '1 m' }).limit(ip),+ // AI bounty judge (api/bounties/:id/judge). Each run spends real LLM tokens+ // scoring a whole field of submissions, so cap per poster and fail closed+ // without Redis in prod rather than allowing unbounded paid inference.+ bountyJudge: (userId) =>+ getLimiter('bounty:judge:user', { limit: 30, window: '1 h', critical: true }).limit(userId),// Direct messages between friends — its own bucket so DM spam can't starve// world-chat posting and vice versa. Mirrors world chat's order of magnitude.dmSend: (userId) => getLimiter('dm:send', { limit: 30, window: '1 m' }).limit(userId),diff --git a/api/bounties.js b/api/bounties.jsindex 14dfe5b99..339e1a66e 100644--- a/api/bounties.js+++ b/api/bounties.js@@ -1,6 +1,7 @@import { sql } from './_lib/db.js';import { cors, json, error, readJson, wrap, method } from './_lib/http.js';import { getSessionUser } from './_lib/auth.js';+import { enrichLikes } from './_lib/bounty-likes.js';const SOL_USD_FALLBACK = 160;@@ -12,6 +13,8 @@ export default wrap(async (req, res) => {const tab = url.searchParams.get('tab') || 'trending';const limit = Math.min(parseInt(url.searchParams.get('limit') || '30', 10), 50);const offset = Math.max(parseInt(url.searchParams.get('offset') || '0', 10), 0);+ // Optional: identify the caller so submission cards know what they've liked.+ const userId = (await getSessionUser(req).catch(() => null))?.id || null;if (tab === 'feed') {// Mixed feed: interleave recent submissions and open bounties@@ -51,6 +54,10 @@ export default wrap(async (req, res) => {const subs = subsByBounty[b.id] || [];for (const s of subs.slice(0, 2)) feed.push(s);}+ await enrichLikes(+ feed.filter((x) => x._type === 'submission'),+ { userId },+ );return json(res, 200, { feed, tab });}@@ -66,6 +73,7 @@ export default wrap(async (req, res) => {ORDER BY bs.created_at DESCLIMIT ${limit} OFFSET ${offset}`;+ await enrichLikes(rows, { userId });return json(res, 200, { submissions: rows, tab });}diff --git a/api/bounties/[id].js b/api/bounties/[id].jsindex 57df7e857..e21cc9a09 100644--- a/api/bounties/[id].js+++ b/api/bounties/[id].js@@ -1,6 +1,8 @@import { sql } from '../_lib/db.js';import { cors, json, error, wrap, method } from '../_lib/http.js';import { isUuid } from '../_lib/validate.js';+import { getSessionUser } from '../_lib/auth.js';+import { enrichLikes } from '../_lib/bounty-likes.js';export default wrap(async (req, res) => {if (cors(req, res)) return;@@ -33,5 +35,9 @@ export default wrap(async (req, res) => {`;if (!bounty) return error(res, 404, 'not_found', 'bounty not found');++ const userId = (await getSessionUser(req).catch(() => null))?.id || null;+ await enrichLikes(bounty.submissions, { userId });+return json(res, 200, { bounty });});diff --git a/api/bounties/[id]/judge.js b/api/bounties/[id]/judge.jsnew file mode 100644index 000000000..4d430a395--- /dev/null+++ b/api/bounties/[id]/judge.js@@ -0,0 +1,99 @@+// POST /api/bounties/:id/judge — AI judge for the /go bounty board.+//+// Owner-only. Scores every (non-rejected) submission against the bounty's+// requirements with the platform LLM and returns a ranked, reasoned shortlist+// plus a recommended winner. Posters drowning in dozens of submissions get an+// instant, defensible read on the field instead of eyeballing them one by one.+//+// Cost control: result is cached in Redis keyed by (bounty, submission count,+// newest submission time) for an hour, so re-opening the resolve modal is free+// and only a genuinely changed field re-bills. A per-poster hourly rate limit+// caps worst-case spend.++import { sql } from '../../_lib/db.js';+import { cors, json, error, wrap, method } from '../../_lib/http.js';+import { getSessionUser } from '../../_lib/auth.js';+import { isUuid } from '../../_lib/validate.js';+import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';+import { cacheGet, cacheSet } from '../../_lib/cache.js';+import { limits } from '../../_lib/rate-limit.js';+import { enrichLikes } from '../../_lib/bounty-likes.js';+import { buildJudgePrompt, normalizeJudgement } from '../../_lib/bounty-judge.js';++const MAX_SUBS = 40; // submissions fed to the model in one pass+const PREVIEW_CAP = 140;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const id = req.query?.id;+ if (!id || !isUuid(id)) return error(res, 400, 'bad_request', 'valid bounty id required');++ const user = await getSessionUser(req).catch(() => null);+ if (!user) return error(res, 401, 'unauthorized', 'sign in to use the AI judge');++ const rl = await limits.bountyJudge(user.id);+ if (!rl.success) return error(res, 429, 'rate_limited', 'AI judge limit reached — try again later');++ const [bounty] = await sql`+ SELECT id, user_id, title, description, status+ FROM bounties+ WHERE id = ${id} AND deleted_at IS NULL+ `;+ if (!bounty) return error(res, 404, 'not_found', 'bounty not found');+ if (bounty.user_id !== user.id) {+ return error(res, 403, 'forbidden', 'only the bounty poster can run the AI judge');+ }++ const subs = await sql`+ SELECT id, username, content, media_url, media_type, created_at+ FROM bounty_submissions+ WHERE bounty_id = ${id} AND status != 'rejected'+ ORDER BY created_at ASC+ LIMIT ${MAX_SUBS}+ `;+ if (!subs.length) return error(res, 400, 'no_submissions', 'no submissions to judge yet');++ await enrichLikes(subs, { idField: 'id', userId: user.id });++ const validIds = new Set(subs.map((s) => s.id));+ const newest = subs.reduce((m, s) => Math.max(m, new Date(s.created_at).getTime() || 0), 0);+ const cacheKey = `bounty:judge:${id}:${subs.length}:${newest}`;++ const cached = await cacheGet(cacheKey).catch(() => null);+ if (cached) return json(res, 200, { ...cached, cached: true });++ let result;+ try {+ const { system, user: userPrompt } = buildJudgePrompt(bounty, subs);+ const out = await llmComplete({ system, user: userPrompt, maxTokens: 1400, timeoutMs: 30_000 });+ result = normalizeJudgement(out.text, validIds);+ result.model = out.model;+ result.provider = out.provider;+ } catch (e) {+ if (e instanceof LlmUnavailableError) {+ return error(res, 503, 'llm_unavailable', 'AI judge is unavailable right now');+ }+ return error(res, 502, 'judge_failed', e?.message || 'the judge could not score this field');+ }++ // Decorate each ranking with display context the client needs (author,+ // likes, a short preview) so the resolve modal can render without a second+ // lookup against its own submission list.+ const byId = new Map(subs.map((s) => [s.id, s]));+ result.rankings = result.rankings.map((r) => {+ const s = byId.get(r.submission_id);+ return {+ ...r,+ username: s?.username || 'anon',+ like_count: s?.like_count || 0,+ content_preview: String(s?.content || s?.media_url || '').slice(0, PREVIEW_CAP),+ };+ });+ result.judged_count = subs.length;++ await cacheSet(cacheKey, result, 3600).catch(() => {});++ return json(res, 200, { ...result, cached: false });+});diff --git a/api/bounties/[id]/likes.js b/api/bounties/[id]/likes.jsnew file mode 100644index 000000000..76f6730b9--- /dev/null+++ b/api/bounties/[id]/likes.js@@ -0,0 +1,61 @@+// POST /api/bounties/:id/likes — toggle the caller's like on a submission.+//+// Body: { submission_id }. Returns { liked, like_count } reflecting the new+// state. Likes are the board's social-proof signal: they surface in the feed+// and feed into the AI judge as a weak tiebreaker. One like per (submission,+// user); posting again removes it.++import { sql } from '../../_lib/db.js';+import { cors, json, error, readJson, wrap, method } from '../../_lib/http.js';+import { getSessionUser } from '../../_lib/auth.js';+import { isUuid } from '../../_lib/validate.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const bountyId = req.query?.id;+ if (!bountyId || !isUuid(bountyId)) return error(res, 400, 'bad_request', 'valid bounty id required');++ const user = await getSessionUser(req).catch(() => null);+ if (!user) return error(res, 401, 'unauthorized', 'sign in to like submissions');++ const body = await readJson(req);+ const submissionId = body?.submission_id;+ if (!submissionId || !isUuid(submissionId)) {+ return error(res, 400, 'bad_request', 'submission_id required');+ }++ // The submission must exist and belong to this (non-deleted) bounty.+ const [sub] = await sql`+ SELECT bs.id+ FROM bounty_submissions bs+ JOIN bounties b ON b.id = bs.bounty_id AND b.deleted_at IS NULL+ WHERE bs.id = ${submissionId} AND bs.bounty_id = ${bountyId}+ `;+ if (!sub) return error(res, 404, 'not_found', 'submission not found on this bounty');++ const [existing] = await sql`+ SELECT 1 AS x FROM bounty_submission_likes+ WHERE submission_id = ${submissionId} AND user_id = ${user.id}+ `;++ if (existing) {+ await sql`+ DELETE FROM bounty_submission_likes+ WHERE submission_id = ${submissionId} AND user_id = ${user.id}+ `;+ } else {+ await sql`+ INSERT INTO bounty_submission_likes (submission_id, user_id)+ VALUES (${submissionId}, ${user.id})+ ON CONFLICT DO NOTHING+ `;+ }++ const [{ c }] = await sql`+ SELECT COUNT(*)::int AS c FROM bounty_submission_likes WHERE submission_id = ${submissionId}+ `;++ return json(res, 200, { liked: !existing, like_count: c });+});diff --git a/api/bounties/[id]/submissions.js b/api/bounties/[id]/submissions.jsindex 71160c16d..40e4a4501 100644--- a/api/bounties/[id]/submissions.js+++ b/api/bounties/[id]/submissions.js@@ -1,6 +1,7 @@import { sql } from '../../_lib/db.js';import { cors, json, error, readJson, wrap, method } from '../../_lib/http.js';import { getSessionUser } from '../../_lib/auth.js';+import { enrichLikes } from '../../_lib/bounty-likes.js';export default wrap(async (req, res) => {if (cors(req, res)) return;@@ -21,6 +22,8 @@ export default wrap(async (req, res) => {ORDER BY created_at DESCLIMIT ${limit} OFFSET ${offset}`;+ const userId = (await getSessionUser(req).catch(() => null))?.id || null;+ await enrichLikes(rows, { userId });return json(res, 200, { submissions: rows });}diff --git a/pages/go.html b/pages/go.htmlindex b94a1dece..ee5e2118c 100644--- a/pages/go.html+++ b/pages/go.html@@ -297,6 +297,61 @@.toast.show { transform: translateY(0); opacity: 1; }.toast.success { border-color: rgba(34,197,94,0.4); color: var(--green); }.toast.fail { border-color: rgba(248,113,113,0.4); color: #f87171; }++ /* ── Likes ───────────────────────────────────────────── */+ .like-btn {+ display: inline-flex; align-items: center; gap: 5px;+ font-size: 12px; font-weight: 600; color: var(--muted);+ background: var(--panel); border: 1px solid var(--border);+ border-radius: 999px; padding: 4px 10px;+ transition: color .14s, border-color .14s, background .14s;+ }+ .like-btn:hover { color: var(--text); border-color: rgba(255,255,255,0.18); }+ .like-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .like-btn svg { width: 13px; height: 13px; transition: transform .14s; }+ .like-btn.liked { color: #ff6b81; border-color: rgba(255,107,129,0.42); background: rgba(255,107,129,0.10); }+ .like-btn.liked svg { fill: #ff6b81; transform: scale(1.08); }+ .like-btn:active svg { transform: scale(0.8); }+ .like-btn[disabled] { opacity: 0.6; cursor: default; }+ .like-count { font-variant-numeric: tabular-nums; }++ /* ── AI judge (resolve modal) ────────────────────────── */+ .resolve-actions { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; }+ .resolve-actions .hint { font-size: 12px; color: var(--muted-2); }+ .ai-judge-btn {+ display: inline-flex; align-items: center; gap: 6px;+ font-size: 12px; font-weight: 600; padding: 6px 12px; border-radius: 8px;+ color: var(--accent); background: var(--accent-glow);+ border: 1px solid rgba(124,92,255,0.32);+ transition: background .14s, opacity .14s;+ }+ .ai-judge-btn:hover { background: rgba(124,92,255,0.22); }+ .ai-judge-btn[disabled] { opacity: 0.7; cursor: default; }+ .ai-summary {+ font-size: 12.5px; line-height: 1.5; color: var(--text);+ background: linear-gradient(90deg, rgba(124,92,255,0.14), rgba(124,92,255,0.03));+ border: 1px solid rgba(124,92,255,0.28); border-radius: 10px;+ padding: 11px 13px; margin-bottom: 12px;+ }+ .ai-summary .ai-badge {+ display: inline-flex; align-items: center; font-size: 9px; font-weight: 800;+ letter-spacing: 0.1em; color: #fff; background: var(--accent);+ border-radius: 4px; padding: 2px 6px; margin-right: 7px; vertical-align: 1px;+ }+ .ai-summary .ai-meta { color: var(--muted-2); }+ .sub-pick-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }+ .sub-pick.recommended { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-glow); }+ .sub-pick-rec {+ display: inline-flex; align-items: center; gap: 4px; font-size: 10px; font-weight: 800;+ letter-spacing: 0.06em; text-transform: uppercase; color: var(--accent); margin-top: 6px;+ }+ .ai-score {+ font-size: 12px; font-weight: 800; font-variant-numeric: tabular-nums; color: #fff;+ border-radius: 6px; padding: 2px 8px; flex-shrink: 0;+ background: hsl(calc(var(--s, 0) * 1.2) 68% 42%);+ }+ .ai-verdict { font-size: 11.5px; color: var(--muted); margin-top: 7px; line-height: 1.45; }+ .sp-likes { color: #ff6b81; font-weight: 600; margin-left: 6px; }</style></head><body>@@ -419,7 +474,11 @@</div><div class="modal-body"><div id="resolve-error" class="form-error" style="display:none"></div>- <p style="font-size:13px;color:var(--muted);margin-bottom:12px;">Select the submission you want to reward. Mark their Solana tx hash once you've paid.</p>+ <div class="resolve-actions">+ <span class="hint">Pick the submission to reward.</span>+ <button id="ai-judge-btn" class="ai-judge-btn" type="button">✨ Rank with AI</button>+ </div>+ <div id="ai-summary" class="ai-summary" style="display:none"></div><div id="resolve-subs" class="sub-pick-list"></div><div class="field" style="margin-top:12px;"><label>Solana TX Hash (optional)</label>diff --git a/scripts/migrate-bounties.sql b/scripts/migrate-bounties.sqlindex 91ec032d9..f93eab664 100644--- a/scripts/migrate-bounties.sql+++ b/scripts/migrate-bounties.sql@@ -44,3 +44,16 @@ CREATE INDEX IF NOT EXISTS bs_bounty_idx ON bounty_submissions(bounty_id);CREATE INDEX IF NOT EXISTS bs_user_idx ON bounty_submissions(user_id);CREATE INDEX IF NOT EXISTS bs_created_idx ON bounty_submissions(created_at DESC);CREATE INDEX IF NOT EXISTS bs_status_idx ON bounty_submissions(status);++-- Submission upvotes ("likes"). Counts are computed on read; one row per+-- (submission, user). See api/_lib/bounty-likes.js and the dated migration+-- api/_lib/migrations/2026-06-08-bounty-likes.sql (the canonical runner path).+CREATE TABLE IF NOT EXISTS bounty_submission_likes (+ submission_id UUID NOT NULL REFERENCES bounty_submissions(id) ON DELETE CASCADE,+ user_id UUID NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ PRIMARY KEY (submission_id, user_id)+);++CREATE INDEX IF NOT EXISTS bsl_submission_idx ON bounty_submission_likes(submission_id);+CREATE INDEX IF NOT EXISTS bsl_user_idx ON bounty_submission_likes(user_id);diff --git a/src/go.js b/src/go.jsindex 15c24b4d7..cc8f1ce32 100644--- a/src/go.js+++ b/src/go.js@@ -7,6 +7,7 @@ let feedOffset = 0;let activeBountyId = null;let resolveSubmissions = [];let selectedSubmissionId = null;+let aiRecommendedId = null;// ── Bootstrap ────────────────────────────────────────────────────────────────@@ -189,6 +190,10 @@ function renderSubmissionCard(s) {<div class="time-left">${esc(ago)}</div>${s.status === 'accepted' ? `<span class="badge badge-open" style="font-size:10px;">✓ WINNER</span>` : ''}${s.reward_sol ? `<div class="reward">◎ ${parseFloat(s.reward_sol).toFixed(2)} SOL</div>` : ''}+ <button class="like-btn ${s.liked_by_me ? 'liked' : ''}" data-action="like" data-id="${esc(s.id)}" data-bounty="${esc(s.bounty_id)}" aria-pressed="${s.liked_by_me ? 'true' : 'false'}" aria-label="Like submission" style="margin-left:auto;">+ ${heartSvg()}+ <span class="like-count">${s.like_count || 0}</span>+ </button></div></div></div>@@ -278,6 +283,10 @@ function bindModals() {const btn = e.target.closest('[data-action]');if (!btn) return;if (!currentUser) { location.href = '/login'; return; }+ if (btn.dataset.action === 'like') {+ toggleLike(btn);+ return;+ }if (btn.dataset.action === 'submit') {openSubmitModal(btn.dataset.id, btn.dataset.title);}@@ -398,8 +407,15 @@ async function openResolveModal(bountyId) {activeBountyId = bountyId;selectedSubmissionId = null;resolveSubmissions = [];+ aiRecommendedId = null;document.getElementById('resolve-error').style.display = 'none';document.getElementById('r-tx').value = '';+ const summary = document.getElementById('ai-summary');+ summary.style.display = 'none';+ summary.innerHTML = '';+ const judgeBtn = document.getElementById('ai-judge-btn');+ judgeBtn.disabled = false;+ judgeBtn.textContent = '✨ Rank with AI';document.getElementById('resolve-subs').innerHTML = '<div style="color:var(--muted);font-size:13px;">Loading submissions…</div>';openModal('resolve-modal');@@ -419,12 +435,24 @@ function renderResolveSubs() {el.innerHTML = '<div style="color:var(--muted);font-size:13px;">No submissions yet</div>';return;}- el.innerHTML = resolveSubmissions.map(s => `- <div class="sub-pick ${s.id === selectedSubmissionId ? 'selected' : ''}" data-sid="${esc(s.id)}">- <div class="sub-pick-user">${esc(s.username || 'anon')} · ${timeAgo(s.created_at)}</div>+ el.innerHTML = resolveSubmissions.map(s => {+ const ai = s._ai;+ const isRec = aiRecommendedId && s.id === aiRecommendedId;+ const likes = s.like_count ? `<span class="sp-likes">♥ ${s.like_count}</span>` : '';+ const score = ai ? `<span class="ai-score" style="--s:${ai.score}">${ai.score}</span>` : '';+ const verdict = ai?.verdict ? `<div class="ai-verdict">${esc(ai.verdict)}</div>` : '';+ const recBadge = isRec ? `<div class="sub-pick-rec">★ AI pick</div>` : '';+ return `+ <div class="sub-pick ${s.id === selectedSubmissionId ? 'selected' : ''} ${isRec ? 'recommended' : ''}" data-sid="${esc(s.id)}">+ <div class="sub-pick-head">+ <div class="sub-pick-user">${esc(s.username || 'anon')} · ${timeAgo(s.created_at)}${likes}</div>+ ${score}+ </div><div class="sub-pick-content">${esc(s.content || s.media_url || '(media only)')}</div>- </div>- `).join('');+ ${verdict}+ ${recBadge}+ </div>`;+ }).join('');el.querySelectorAll('.sub-pick').forEach(div => {div.addEventListener('click', () => {@@ -436,6 +464,8 @@ function renderResolveSubs() {}function bindResolve() {+ document.getElementById('ai-judge-btn').addEventListener('click', runJudge);+document.getElementById('resolve-submit').addEventListener('click', async () => {const errEl = document.getElementById('resolve-error');if (!selectedSubmissionId) { showErr(errEl, 'Select a winning submission'); return; }@@ -467,6 +497,87 @@ function bindResolve() {});}+// ── Likes ─────────────────────────────────────────────────────────────────────++function heartSvg() {+ return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round" aria-hidden="true"><path d="M12 21s-7.5-4.6-10-9.3C.2 8 2 4.5 5.2 4.5 7 4.5 8.5 5.6 12 8c3.5-2.4 5-3.5 6.8-3.5C22 4.5 23.8 8 22 11.7 19.5 16.4 12 21 12 21z"/></svg>`;+}++async function toggleLike(btn) {+ if (!currentUser) { location.href = '/login'; return; }+ const sid = btn.dataset.id;+ const bid = btn.dataset.bounty;+ if (!sid || !bid) return;++ const countEl = btn.querySelector('.like-count');+ const wasLiked = btn.classList.contains('liked');+ const prevCount = parseInt(countEl.textContent, 10) || 0;++ // Optimistic toggle — revert on failure.+ btn.classList.toggle('liked', !wasLiked);+ btn.setAttribute('aria-pressed', String(!wasLiked));+ countEl.textContent = String(Math.max(0, prevCount + (wasLiked ? -1 : 1)));+ btn.disabled = true;++ try {+ const r = await fetch(`${API}/${bid}/likes`, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ submission_id: sid }),+ });+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || data.error || 'failed');+ btn.classList.toggle('liked', !!data.liked);+ btn.setAttribute('aria-pressed', String(!!data.liked));+ countEl.textContent = String(data.like_count);+ } catch (err) {+ btn.classList.toggle('liked', wasLiked);+ btn.setAttribute('aria-pressed', String(wasLiked));+ countEl.textContent = String(prevCount);+ toast(err.message || 'Could not like', 'fail');+ } finally {+ btn.disabled = false;+ }+}++// ── AI judge ──────────────────────────────────────────────────────────────────++async function runJudge() {+ if (!resolveSubmissions.length) { toast('No submissions to rank yet'); return; }+ const btn = document.getElementById('ai-judge-btn');+ const banner = document.getElementById('ai-summary');+ const prevLabel = btn.textContent;+ btn.disabled = true;+ btn.textContent = '✨ Judging…';++ try {+ const r = await fetch(`${API}/${activeBountyId}/judge`, { method: 'POST', credentials: 'include' });+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || data.error || 'failed');++ const byId = new Map((data.rankings || []).map(x => [x.submission_id, x]));+ resolveSubmissions = resolveSubmissions+ .map(s => ({ ...s, _ai: byId.get(s.id) || null }))+ .sort((a, b) => (b._ai?.score ?? -1) - (a._ai?.score ?? -1));++ aiRecommendedId = data.recommended_id || null;+ if (aiRecommendedId) selectedSubmissionId = aiRecommendedId;+ renderResolveSubs();++ banner.style.display = '';+ banner.innerHTML = `<span class="ai-badge">AI</span>${esc(data.summary || 'Ranked by how well each submission fits the task.')} <span class="ai-meta">· ${data.judged_count || resolveSubmissions.length} judged${data.cached ? ' · cached' : ''}</span>`;+ btn.textContent = '✨ Re-rank';+ toast('AI ranked the submissions', 'success');+ } catch (err) {+ const msg = /unavailable/i.test(err.message) ? 'AI judge is unavailable right now' : (err.message || 'Judge failed');+ toast(msg, 'fail');+ btn.textContent = prevLabel;+ } finally {+ btn.disabled = false;+ }+}+// ── Helpers ───────────────────────────────────────────────────────────────────function renderSkeletons(n) {diff --git a/tests/bounties-judge.test.js b/tests/bounties-judge.test.jsnew file mode 100644index 000000000..63e5c5122--- /dev/null+++ b/tests/bounties-judge.test.js@@ -0,0 +1,109 @@+// Unit tests for the AI bounty judge's pure normalisation logic.+//+// The judge feeds untrusted model output back into a poster-facing UI, so the+// normaliser must be defensive: drop hallucinated ids, clamp scores, sort, and+// never trust the model's recommended id blindly. These tests pin that contract+// without touching the LLM, DB, or cache.++import { describe, it, expect } from 'vitest';+import { buildJudgePrompt, normalizeJudgement, extractJson } from '../api/_lib/bounty-judge.js';++const IDS = ['aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', 'cccccccc-cccc-cccc-cccc-cccccccccccc'];++describe('extractJson', () => {+ it('parses a bare JSON object', () => {+ expect(extractJson('{"a":1}')).toEqual({ a: 1 });+ });++ it('parses JSON wrapped in a ```json fence', () => {+ expect(extractJson('```json\n{"a":1}\n```')).toEqual({ a: 1 });+ });++ it('parses JSON embedded in prose by brace-slicing', () => {+ expect(extractJson('Here is my verdict: {"a":1} — done.')).toEqual({ a: 1 });+ });++ it('returns null for non-JSON', () => {+ expect(extractJson('no json here')).toBeNull();+ expect(extractJson('')).toBeNull();+ });+});++describe('normalizeJudgement', () => {+ const valid = new Set(IDS);++ it('keeps only known ids, clamps scores, and sorts best-first', () => {+ const raw = JSON.stringify({+ summary: 'A clear winner.',+ recommended_id: IDS[1],+ rankings: [+ { submission_id: IDS[0], score: 40, verdict: 'ok' },+ { submission_id: IDS[1], score: 150, verdict: 'great' }, // clamps to 100+ { submission_id: 'ffffffff-ffff-ffff-ffff-ffffffffffff', score: 99, verdict: 'fake' }, // dropped+ { submission_id: IDS[2], score: -5, verdict: 'bad' }, // clamps to 0+ ],+ });+ const out = normalizeJudgement(raw, valid);+ expect(out.rankings.map((r) => r.submission_id)).toEqual([IDS[1], IDS[0], IDS[2]]);+ expect(out.rankings.map((r) => r.score)).toEqual([100, 40, 0]);+ expect(out.recommended_id).toBe(IDS[1]);+ });++ it('falls back to the top-ranked id when recommended_id is invalid', () => {+ const raw = JSON.stringify({+ recommended_id: 'ffffffff-ffff-ffff-ffff-ffffffffffff',+ rankings: [+ { submission_id: IDS[0], score: 70 },+ { submission_id: IDS[1], score: 90 },+ ],+ });+ const out = normalizeJudgement(raw, valid);+ expect(out.recommended_id).toBe(IDS[1]); // highest score+ });++ it('de-duplicates repeated submission ids', () => {+ const raw = JSON.stringify({+ rankings: [+ { submission_id: IDS[0], score: 50 },+ { submission_id: IDS[0], score: 80 },+ ],+ });+ const out = normalizeJudgement(raw, valid);+ expect(out.rankings).toHaveLength(1);+ expect(out.rankings[0].score).toBe(50); // first occurrence wins+ });++ it('handles non-numeric scores as 0', () => {+ const raw = JSON.stringify({ rankings: [{ submission_id: IDS[0], score: 'not a number' }] });+ const out = normalizeJudgement(raw, valid);+ expect(out.rankings[0].score).toBe(0);+ });++ it('throws when output is unparseable', () => {+ expect(() => normalizeJudgement('garbage', valid)).toThrow();+ });++ it('throws when no rankings reference a real submission', () => {+ const raw = JSON.stringify({ rankings: [{ submission_id: 'ffffffff-ffff-ffff-ffff-ffffffffffff', score: 90 }] });+ expect(() => normalizeJudgement(raw, valid)).toThrow();+ });+});++describe('buildJudgePrompt', () => {+ const bounty = { title: 'Do a backflip on camera', description: 'Must be one continuous shot.' };+ const subs = [+ { id: IDS[0], username: 'alice', content: 'Here is my flip', media_url: 'https://x.com/a', media_type: 'link', like_count: 3 },+ { id: IDS[1], username: 'bob', content: '', media_url: null, like_count: 0 },+ ];++ it('includes every submission id and the bounty title in the user prompt', () => {+ const { user, system } = buildJudgePrompt(bounty, subs);+ for (const id of [IDS[0], IDS[1]]) expect(user).toContain(id);+ expect(user).toContain('Do a backflip on camera');+ expect(user).toContain('community_likes: 3');+ expect(user).toContain('[no media attached]');+ // The judge must be instructed to emit JSON-only and stay coin-agnostic.+ expect(system.toLowerCase()).toContain('json');+ expect(system.toLowerCase()).toContain('coin');+ });+});