import type { Hono } from 'hono'; import type { AppEnv, Ctx, User } from '../env'; import { runAiReview, type AiReport } from '../lib/ai'; import { approveRepo, getImport, importItems, rejectRepo, settleImportOfVersion, type ImportItemView } from '../lib/imports'; import type { Finding } from '../lib/scan'; import { setFlash } from '../lib/session'; import { banUser, CATEGORIES, categoryName, cleanCategory, decideVersion, getSkillCardById, getVersion, listSkills, PLATFORMS, readVersionFiles, savePick, setSkillState, splitPlatforms, type ManifestEntry, type SkillCard } from '../lib/skills'; import { TIERS, tierFor } from '../lib/tiers'; import { getUserById } from '../lib/users'; import { HttpError, likeEscape, newId, now, plural, safeNext, timeAgo } from '../lib/util'; import { Avatar, Empty, stateLabel, TierBadge } from '../views/components'; import { render } from '../views/layout'; import { FindingsList } from './skills'; function admin(c: Ctx): User { const u = c.get('user'); if (!u || !u.is_admin) throw new HttpError(404, 'Not found.'); return u; } const REC_LABEL: Record = { approve: 'Approve', deny: 'Deny', needs_review: 'Needs a close look' }; const RecPill = ({ status, rec }: { status: string; rec: string | null }) => { if (status === 'done' && rec) return AI: {REC_LABEL[rec] ?? rec}; if (status === 'queued' || status === 'running') return AI review running; if (status === 'unavailable') return AI review not configured; return AI review failed; }; /** Ready-made reasons for a denial. The text is emailed to the member as the reviewer's note. */ export const DENY_REASONS: Record = { quality: { label: 'Not strong enough yet', text: 'Thanks for sharing this. Skillfarm is a curated list and we are looking for higher-quality skills: clear steps an agent can follow, tried on real work, and specific enough to beat a plain prompt. Take it back to the drawing board and share it again when it is stronger.', }, duplicate: { label: 'Too close to one we list', text: 'Thanks for sharing this. Skillfarm already lists a skill that does the same job, and this one does not add enough beyond it. If yours does something the listed one cannot, make that clear in the description and share it again.', }, personal: { label: 'Only works on your setup', text: 'Thanks for sharing this. It is built around one setup: private paths, accounts or tools other people do not have. Make it work for anyone who installs it and share it again.', }, unsafe: { label: 'Not safe to install', text: 'This asks an agent to do things that could put the person who installs it at risk, such as running unreviewed code or sending data away. Remove those steps and share it again.', }, }; const QUALITY_LABEL: Record = { excellent: { label: 'Quality: excellent', cls: 'rec-approve' }, good: { label: 'Quality: good', cls: 'rec-approve' }, thin: { label: 'Quality: thin', cls: 'rec-needs_review' }, poor: { label: 'Quality: poor', cls: 'rec-deny' }, }; function parseAi(json: string | null): AiReport | null { if (!json) return null; try { return JSON.parse(json) as AiReport; } catch { return null; } } const QualityPill = ({ ai }: { ai: AiReport | null }) => (ai?.quality && QUALITY_LABEL[ai.quality] ? {QUALITY_LABEL[ai.quality].label} : null); const OverlapNote = ({ ai }: { ai: AiReport | null }) => { const close = (ai?.similar ?? []).filter((x) => x.overlap !== 'related'); if (!close.length) return null; return {close.some((x) => x.overlap === 'duplicate') ? 'Duplicate of a listed skill' : `Close to ${plural(close.length, 'listed skill')}`}; }; const ReasonPicker = ({ pick = 'quality', label = 'Reason' }: { pick?: string; label?: string }) => ( ); /** The reason that best fits what the AI review found, to preselect in the picker. */ function suggestedReason(ai: AiReport | null): string { if (!ai) return 'quality'; if (ai.risk_level === 'high' || ai.risk_level === 'medium') return 'unsafe'; if ((ai.similar ?? []).some((x) => x.overlap === 'duplicate')) return 'duplicate'; return 'quality'; } const AdminNav = ({ tab, counts }: { tab: string; counts: { queue: number; reports: number } }) => ( ); const PickForm = ({ pick, values, error }: { pick: SkillCard | null; values?: Record; error?: string }) => { const v = values ?? {}; const val = (k: string, cur: string | null | undefined) => v[k] ?? cur ?? ''; const chosen = v.platforms !== undefined ? v.platforms.split(',') : pick ? splitPlatforms(pick.platforms) : PLATFORMS.map((p) => p.key); return (

{pick ? `Edit "${pick.title}"` : 'Add a pick'}

A pick is a skill someone else made. It goes live as soon as you save it. Skillfarm stores no copy. Use plain words in the title, maker, summary and note: no company, product or person names. Say "a cloud company" or "an independent developer" instead.

{error ? : null} {pick ? : null}
Links, if they differ from the repo
Works with {PLATFORMS.map((p) => ( ))}
{pick ? Cancel : null}
); }; export function registerAdmin(app: Hono) { app.get('/admin', async (c) => { admin(c); const tab = ['reports', 'skills', 'picks', 'members', 'system'].includes(c.req.query('tab') ?? '') ? c.req.query('tab')! : 'queue'; const q = (c.req.query('q') ?? '').trim().slice(0, 60); const cnt = await c.env.DB.batch<{ n: number }>([ c.env.DB.prepare("SELECT COUNT(*) AS n FROM skill_versions WHERE status = 'pending'"), c.env.DB.prepare('SELECT COUNT(*) AS n FROM reports WHERE resolved_at IS NULL'), ]); const counts = { queue: cnt[0].results[0]?.n ?? 0, reports: cnt[1].results[0]?.n ?? 0 }; let body; if (tab === 'queue') { // Shared repos come first: one card per repo, with its skills inside. const repos = await c.env.DB.prepare( `SELECT m.id, m.repo, m.status, m.found, m.created_at, m.repo_owner_id, u.id AS owner_id, u.handle, u.avatar_key, u.avatar_fallback, u.strikes, r.stars, (SELECT COUNT(*) FROM skills s2 WHERE s2.owner_id = u.id AND s2.state = 'live') AS live_skills, (SELECT provider_user_id FROM oauth_accounts o WHERE o.user_id = u.id AND o.provider = 'github') AS gh_id FROM repo_imports m JOIN users u ON u.id = m.user_id LEFT JOIN repo_signals r ON r.repo_full_name = m.repo WHERE m.status = 'reading' OR (m.status = 'review' AND EXISTS ( SELECT 1 FROM repo_import_items i JOIN skill_versions v ON v.id = i.version_id WHERE i.import_id = m.id AND v.status = 'pending')) ORDER BY m.created_at ASC LIMIT 40`, ).all(); const waiting = repos.results.length ? await c.env.DB.prepare( `SELECT i.import_id, v.id, v.title, v.scan_status, v.ai_status, v.ai_recommendation, v.ai_report FROM repo_import_items i JOIN skill_versions v ON v.id = i.version_id WHERE v.status = 'pending' AND i.import_id IN (${repos.results.map(() => '?').join(',')}) ORDER BY i.path ASC`, ).bind(...repos.results.map((m) => m.id)).all() : { results: [] as any[] }; const rows = await c.env.DB.prepare( `SELECT v.id, v.version, v.title, v.summary, v.scan_status, v.ai_status, v.ai_recommendation, v.ai_summary, v.ai_report, v.created_at, s.source, s.github_repo, s.slug, u.handle, u.display_name, u.avatar_key, u.avatar_fallback, u.id AS owner_id, u.seeds_total, u.strikes, (SELECT COUNT(*) FROM skills s2 WHERE s2.owner_id = u.id AND s2.state = 'live') AS live_skills FROM skill_versions v JOIN skills s ON s.id = v.skill_id JOIN users u ON u.id = s.owner_id WHERE v.status = 'pending' AND NOT EXISTS ( SELECT 1 FROM repo_import_items i JOIN repo_imports m ON m.id = i.import_id WHERE i.version_id = v.id AND m.status IN ('reading','review')) ORDER BY v.created_at ASC LIMIT 100`, ).all(); body = repos.results.length || rows.results.length ? ( <> {repos.results.length ? (
    {repos.results.map((m) => { const mine = waiting.results.filter((w) => w.import_id === m.id); const tally = { approve: 0, deny: 0, needs_review: 0, waiting: 0 }; for (const w of mine) { if (w.ai_status === 'done' && w.ai_recommendation in tally) tally[w.ai_recommendation as 'approve'] += 1; else tally.waiting += 1; } return (
  • {m.repo} {m.status === 'reading' ? 'still being read' : plural(mine.length, 'skill')}

    @{m.handle} {m.live_skills} live skills{m.strikes ? `, ${m.strikes} strikes` : ''} {m.gh_id && m.gh_id === m.repo_owner_id ? Verified repo owner : null} {typeof m.stars === 'number' ? {plural(m.stars, 'star')} : null} Open on GitHub {timeAgo(m.created_at)}

    {mine.length ? (

    AI says: {tally.approve ? {tally.approve} approve : null} {tally.needs_review ? {tally.needs_review} close look : null} {tally.deny ? {tally.deny} deny : null} {tally.waiting ? {tally.waiting} not reviewed yet : null}

    ) : null}
    Review repo {m.status === 'review' ? (
    ) : null}
    {mine.length ? (
      {mine.map((w) => { const ai = parseAi(w.ai_report); return (
    • {w.title} {w.scan_status !== 'clean' ? Patterns: {w.scan_status === 'high' ? 'high risk' : 'flagged'} : null}
    • ); })}
    ) : null}
  • ); })}
) : null} {rows.results.length ? ( <> {repos.results.length ?

Single skills

: null}
    {rows.results.map((r) => (
  • {r.title} v{r.version}

    {r.ai_summary ?? r.summary}

    @{r.handle} {r.live_skills} live skills{r.strikes ? `, ${r.strikes} strikes` : ''} via {r.source === 'mcp' ? 'MCP' : 'website'} {r.github_repo ? {r.github_repo} : null} {timeAgo(r.created_at)}

    Patterns: {r.scan_status === 'clean' ? 'clean' : r.scan_status === 'high' ? 'high risk' : 'flagged'} Review
  • ))}
) : null} ) : (

Repos that members share show up here. You get an email when one is ready.

); } else if (tab === 'reports') { const rows = await c.env.DB.prepare( `SELECT r.*, u.handle AS reporter FROM reports r JOIN users u ON u.id = r.reporter_id WHERE r.resolved_at IS NULL ORDER BY r.created_at ASC LIMIT 100`, ).all<{ id: string; target_type: string; target_id: string; reason: string; created_at: number; reporter: string }>(); const items = []; for (const r of rows.results) { let link = '/admin'; let label = r.target_id; if (r.target_type === 'skill') { const s = await getSkillCardById(c.env, r.target_id); if (s) { link = `/skills/${s.owner_handle}/${s.slug}`; label = `${s.title} by @${s.owner_handle} (${stateLabel(s.state)})`; } } else if (r.target_type === 'user') { const u = await getUserById(c.env, r.target_id); if (u) { link = `/u/${u.handle}`; label = `@${u.handle}`; } } else if (r.target_type === 'review') { const rv = await c.env.DB.prepare('SELECT r.body, u.handle, s.slug, o.handle AS owner FROM reviews r JOIN users u ON u.id = r.user_id JOIN skills s ON s.id = r.skill_id JOIN users o ON o.id = s.owner_id WHERE r.id = ?').bind(r.target_id).first<{ body: string; handle: string; slug: string; owner: string }>(); if (rv) { link = `/skills/${rv.owner}/${rv.slug}?tab=reviews`; label = `Review by @${rv.handle}: ${rv.body.slice(0, 80)}`; } } else if (r.target_type === 'comment') { const cm = await c.env.DB.prepare('SELECT c.body, c.removed_at, u.handle, s.slug, o.handle AS owner FROM comments c JOIN users u ON u.id = c.user_id JOIN skills s ON s.id = c.skill_id JOIN users o ON o.id = s.owner_id WHERE c.id = ?').bind(r.target_id).first<{ body: string; removed_at: number | null; handle: string; slug: string; owner: string }>(); if (cm) { link = `/skills/${cm.owner}/${cm.slug}#comment-${r.target_id}`; label = `Comment by @${cm.handle}${cm.removed_at ? ' (removed)' : ''}: ${cm.body.slice(0, 80)}`; } } items.push({ r, link, label }); } body = items.length ? (
    {items.map(({ r, link, label }) => (
  • {label}

    {r.reason}

    {r.target_type}reported by @{r.reporter}{timeAgo(r.created_at)}

  • ))}
) : (

Reports from members show up here.

); } else if (tab === 'skills') { const rows = await listSkills(c.env, { q, sort: 'updated', limit: 60, states: ['live', 'hidden', 'pending', 'rejected'] }); const harvester = TIERS[3].threshold; body = ( <> {rows.map((s) => ( ))}
SkillOwnerCategoryStateLikesActions
{s.title}{s.featured_at ? Fresh Harvest : null}{s.kind === 'link' ? Pick : null}{s.off_home ? Off home : null} @{s.owner_handle} {s.kind === 'link' ? null : }
{stateLabel(s.state)} {s.likes_count} {s.state === 'live' && s.kind !== 'link' ? ( <>
) : null} {s.state === 'live' && s.kind === 'link' ? ( <> Edit
) : null} {s.state === 'hidden' ?
: null}
); } else if (tab === 'picks') { const rows = await listSkills(c.env, { kind: 'link', q, sort: 'updated', limit: 100, states: ['live', 'hidden'] }); const editing = c.req.query('edit') ? rows.find((r) => r.id === c.req.query('edit')) ?? null : null; body = ( <>

Skills from other makers that Sprout recommends. {rows.length} listed. Anything you add or remove here changes the public site right away.

{rows.map((s) => ( ))}
PickMakerCategoryLicenseStarsStateActions
{s.title} {s.maker} {s.github_repo} {categoryName(s.category) ?? ''} {s.license ?? 'Not stated'} {s.stars ?? ''} {stateLabel(s.state)} Edit {s.state === 'live' ?
: null} {s.state === 'hidden' ?
: null}
); } else if (tab === 'members') { const like = `%${likeEscape(q)}%`; const rows = await c.env.DB.prepare( `SELECT * FROM users WHERE status != 'deleted' AND (handle LIKE ?1 ESCAPE '\\' OR display_name LIKE ?1 ESCAPE '\\') ORDER BY created_at DESC LIMIT 60`, ).bind(like).all(); const homesteader = TIERS[4].threshold; body = ( <> {rows.results.map((u) => ( ))}
MemberTierSeedsStatusJoinedActions
@{u.handle} {u.is_admin ? Admin : null}{u.is_agent ? Site agent : null}{u.spotlight_at ? Spotlight : null} {tierFor(u.seeds_total).name} {u.seeds_total} {u.status}{u.strikes ? `, ${u.strikes} strikes` : ''} {timeAgo(u.created_at)} {u.status === 'active' && !u.is_admin && !u.is_agent ? ( <>
) : null} {u.status === 'banned' ?
: null}
); } else { const mails = await c.env.DB.prepare('SELECT kind, status, detail, created_at FROM email_log ORDER BY created_at DESC LIMIT 25').all<{ kind: string; status: string; detail: string | null; created_at: number }>(); const e = c.env; const checks: [string, boolean, string][] = [ ['Session secret', !!e.SESSION_SECRET, 'Required for sign-in.'], ['AI review', !!e.ANTHROPIC_API_KEY, `ANTHROPIC_API_KEY. Model: ${e.AI_REVIEW_MODEL}.`], ['Email', !!e.RESEND_API_KEY, `RESEND_API_KEY. Sends from ${e.EMAIL_FROM}.`], ['VirusTotal lookup', !!e.VIRUSTOTAL_API_KEY, 'Optional. VIRUSTOTAL_API_KEY.'], ]; body = ( <>

Integrations

    {checks.map(([name, ok, note]) => (
  • {name} {note}{ok ? 'Configured' : 'Not set'}
  • ))}

Recent email

{mails.results.length ? ( {mails.results.map((m) => )}
KindStatusDetailWhen
{m.kind}{m.status}{m.detail ?? ''}{timeAgo(m.created_at)}
) :

No email has been sent yet.

} ); } return render(c, { title: 'Admin', noindex: true },

Admin

{body}
); }); app.get('/admin/review/:id', async (c) => { admin(c); const v = await getVersion(c.env, c.req.param('id')); if (!v) throw new HttpError(404, 'That submission was not found.'); const skill = await getSkillCardById(c.env, v.skill_id); if (!skill) throw new HttpError(404, 'That skill was not found.'); const files = await readVersionFiles(c.env, v); const manifest = JSON.parse(v.manifest) as ManifestEntry[]; const findings = JSON.parse(v.scan_report) as Finding[]; const ai = v.ai_report ? (JSON.parse(v.ai_report) as AiReport) : null; const dec = new TextDecoder(); const parent = skill.replanted_from_skill_id ? await getSkillCardById(c.env, skill.replanted_from_skill_id) : null; const history = await c.env.DB.prepare("SELECT state, COUNT(*) AS n FROM skills WHERE owner_id = ? GROUP BY state").bind(skill.owner_id).all<{ state: string; n: number }>(); const share = await c.env.DB.prepare('SELECT m.id, m.repo FROM repo_import_items i JOIN repo_imports m ON m.id = i.import_id WHERE i.version_id = ?').bind(v.id).first<{ id: string; repo: string }>(); return render( c, { title: `Review: ${v.title}`, noindex: true },

Review queue / {share ? <>{share.repo} / : null}{v.title}

{v.title} v{v.version}

{v.summary}

@{skill.owner_handle} {history.results.map((h) => `${h.n} ${stateLabel(h.state).toLowerCase()}`).join(', ')} via {skill.source === 'mcp' ? 'MCP' : 'website'} {skill.github_repo ? {skill.github_repo} : uploaded directly} {skill.verified_owner ? Verified repo owner : null} {parent ? replant of {parent.owner_handle}/{parent.slug} : null} submitted {timeAgo(v.created_at)}

AI review

{ai ? ( <>

Risk: {ai.risk_level}. {ai.summary}

{ai.what_it_does.length ? (<>

What it does

    {ai.what_it_does.map((w) =>
  • {w}
  • )}
) : null} {ai.findings.length ? ( <>

Findings

    {ai.findings.map((f) =>
  • {f.severity}{f.file}

    {f.detail}

  • )}
) :

No safety findings.

} {ai.quality_notes ? (<>

Quality

{ai.quality_notes}

) : null} {ai.value_added ? (<>

What it adds

{ai.value_added}

) : null} {ai.similar ? ( <>

Similar skills already listed

{ai.similar.length ? (
    {ai.similar.map((x) => (
  • {x.overlap} {x.skill} {x.note}
  • ))}
) :

Nothing listed does the same job.

} ) : null}

Reviewed by {ai.model ?? c.env.AI_REVIEW_MODEL}. It is a recommendation. The decision is yours.

) : (

{v.ai_status === 'queued' || v.ai_status === 'running' ? 'The AI review is still running. It usually finishes within a few minutes. Reload to check.' : v.ai_summary ?? 'No AI review is available for this submission.'}

)}

Pattern scan {v.scan_status === 'clean' ? 'clean' : v.scan_status === 'high' ? 'high risk' : 'flagged'}

{v.status === 'pending' ? (

Decision

{share ? : null}
) : (
{v.status === 'approved' ? 'Approved' : v.status === 'rejected' ? 'Denied' : 'Superseded'}{v.decided_at ? ` ${timeAgo(v.decided_at)}.` : '.'} {v.decision_note ?? ''}
)}

Files ({manifest.length})

{files.map((f, i) => (
{f.path} {f.data.length} bytes
{dec.decode(f.data)}
))}
, ); }); app.post('/admin/review/:id/decide', async (c) => { const a = admin(c); const form = await c.req.parseBody(); const decision = form.decision === 'approve' ? 'approve' : form.decision === 'reject' ? 'reject' : null; if (!decision) throw new HttpError(400, 'Pick approve or deny.'); const id = c.req.param('id'); const back = safeNext(String(form.back ?? ''), '/admin'); // A denial always carries a reason: the note if one was written, otherwise the quick reason that was picked. let note = String(form.note ?? '').trim().slice(0, 1000); if (decision === 'reject' && !note) note = DENY_REASONS[String(form.preset ?? '')]?.text ?? ''; try { if (decision === 'reject' && !note) throw new HttpError(400, 'Give a reason for the denial. Write a note or pick a quick reason.'); const skill = await decideVersion(c.env, a, id, decision, note, { category: cleanCategory(form.category) }); await settleImportOfVersion(c.env, id); setFlash(c, 'ok', decision === 'approve' ? `Approved. "${skill.title}" is live and the author was notified.` : 'Denied. The author was sent the reason.'); } catch (e) { if (!(e instanceof HttpError)) throw e; setFlash(c, 'error', e.message); if (e.status === 400) return c.redirect(`/admin/review/${id}`); } return c.redirect(back); }); // One shared repo: deny all of it in one step, approve all of it, or take its skills one by one. app.get('/admin/repo/:id', async (c) => { admin(c); const imp = await getImport(c.env, c.req.param('id')); if (!imp) throw new HttpError(404, 'That shared repo was not found.'); const [items, owner, repo, gh] = await Promise.all([ importItems(c.env, imp.id), getUserById(c.env, imp.user_id), c.env.DB.prepare('SELECT stars, forks, pushed_at, license_spdx, archived FROM repo_signals WHERE repo_full_name = ?').bind(imp.repo).first<{ stars: number; forks: number; pushed_at: string | null; license_spdx: string | null; archived: number }>(), c.env.DB.prepare("SELECT provider_user_id FROM oauth_accounts WHERE user_id = ? AND provider = 'github'").bind(imp.user_id).first<{ provider_user_id: string }>(), ]); const waiting = items.filter((i) => i.version_status === 'pending'); const other = items.filter((i) => i.version_status !== 'pending'); const back = `/admin/repo/${imp.id}`; const stateOf = (i: ImportItemView) => i.version_status === 'approved' ? { label: 'Approved', cls: 'pill-verified' } : i.version_status === 'rejected' ? { label: 'Denied', cls: 'pill-rejected' } : i.status === 'unchanged' ? { label: 'No change', cls: '' } : i.status === 'skipped' ? { label: 'Left out', cls: '' } : i.status === 'failed' ? { label: 'Could not be read', cls: 'pill-rejected' } : { label: i.status === 'queued' || i.status === 'working' ? 'Being read' : i.version_status ?? i.status, cls: '' }; return render( c, { title: `Review: ${imp.repo}`, noindex: true },

Review queue / {imp.repo}

{imp.repo}

{owner ? @{owner.handle} : null} {owner ? : null} {gh && gh.provider_user_id === imp.repo_owner_id ? Verified repo owner : Repo owner not verified} Open on GitHub {repo ? {plural(repo.stars, 'star')}, {plural(repo.forks, 'fork')} : null} License: {repo?.license_spdx ?? 'not stated'} {repo?.archived ? Archived : null} shared {timeAgo(imp.created_at)} via {imp.source === 'mcp' ? 'MCP' : 'website'}

{imp.status === 'reading' ?
Still being read. Skillfarm found {plural(imp.found, 'skill')} and is reading them. Reload in a minute.
: null} {imp.decision_note ?
Whole repo denied{imp.decided_at ? ` ${timeAgo(imp.decided_at)}` : ''}. {imp.decision_note}
: null} {waiting.length && imp.status !== 'reading' ? (

Decide the whole repo

{plural(waiting.length, 'skill')} waiting. Deny the repo and all of them are turned down with one email. Or take them one by one below.

Publishes every waiting skill on @{owner?.handle}'s profile, filed under the category the AI review suggested.

) : null} {waiting.length ?

Waiting ({waiting.length})

: null}
    {waiting.map((i) => { const ai = parseAi(i.ai_report); const close = (ai?.similar ?? []).filter((x) => x.overlap !== 'related'); return (
  • {i.title} {i.status === 'updated' ? `new version, v${i.version}` : i.path || '(repo root)'}

    Patterns: {i.scan_status === 'clean' ? 'clean' : i.scan_status === 'high' ? 'high risk' : 'flagged'} {ai?.category ? {categoryName(ai.category)} : null}

    {ai?.summary ?? i.summary}

    {ai?.value_added ?

    What it adds: {ai.value_added}

    : null} {close.length ? (
      {close.map((x) =>
    • {x.overlap} {x.skill} {x.note}
    • )}
    ) : null}
    Read the files
  • ); })}
{other.length ? ( <>

{waiting.length ? 'Everything else in this repo' : 'Skills in this repo'}

{other.map((i) => { const st = stateOf(i); return ( ); })}
SkillFolderStateNote
{i.slug && owner ? {i.title} : i.path.split('/').pop() || imp.repo} {i.path || '(repo root)'} {st.label} {i.decision_note ?? i.detail ?? ''}
) : null}
, ); }); app.post('/admin/repo/:id/decide', async (c) => { const a = admin(c); const id = c.req.param('id'); const form = await c.req.parseBody(); try { if (form.decision === 'reject') { const note = String(form.note ?? '').trim().slice(0, 1000) || (DENY_REASONS[String(form.preset ?? '')] ?? DENY_REASONS.quality).text; const n = await rejectRepo(c.env, a, id, note); setFlash(c, 'ok', n ? `Rejected. ${plural(n, 'skill')} turned down and the member was sent the reason.` : 'Nothing in that repo was waiting.'); return c.redirect('/admin'); } if (form.decision === 'approve') { const res = await approveRepo(c.env, a, id); const more = res.problems.length ? ` ${res.problems.join(' ')}` : res.left ? ` ${res.left} still waiting: press Approve all again.` : ''; setFlash(c, res.problems.length ? 'error' : 'ok', `Approved ${plural(res.approved, 'skill')}. The member was notified.${more}`); return c.redirect(res.left ? `/admin/repo/${id}` : '/admin'); } throw new HttpError(400, 'Pick approve or reject.'); } catch (e) { if (!(e instanceof HttpError)) throw e; setFlash(c, 'error', e.message); return c.redirect(`/admin/repo/${id}`); } }); app.post('/admin/review/:id/rescan', async (c) => { admin(c); const id = c.req.param('id'); await c.env.DB.prepare("UPDATE skill_versions SET ai_attempts = 0, ai_status = 'queued', ai_report = NULL, ai_recommendation = NULL, ai_summary = NULL WHERE id = ?").bind(id).run(); const result = await runAiReview(c.env, id); setFlash(c, result === 'done' ? 'ok' : 'error', result === 'done' ? 'AI review finished.' : result === 'unavailable' ? 'AI review is not configured. Set ANTHROPIC_API_KEY.' : 'The AI review failed. It will be retried automatically.'); return c.redirect(`/admin/review/${id}`); }); app.post('/admin/picks', async (c) => { const a = admin(c); const form = await c.req.parseBody({ all: true }); const str = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : ''); const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string'); const values = { title: str('title'), maker: str('maker'), repo: str('repo'), path: str('path'), category: str('category'), license: str('license'), summary: str('summary'), note: str('note'), install_hint: str('install_hint'), source_url: str('source_url'), maker_url: str('maker_url'), platforms: platforms.join(',') }; try { const pick = await savePick(c.env, a, { id: str('id') || undefined, title: values.title, summary: values.summary, category: values.category, maker: values.maker, makerUrl: values.maker_url, sourceUrl: values.source_url, repo: values.repo.replace(/^https:\/\/github\.com\//i, '').replace(/\/+$/, ''), path: values.path, license: values.license, installHint: values.install_hint, note: values.note, platforms, }); setFlash(c, 'ok', str('id') ? `Saved "${pick.title}".` : `"${pick.title}" is live as one of Sprout's picks.`); return c.redirect('/admin?tab=picks'); } catch (e) { if (!(e instanceof HttpError)) throw e; const editing = str('id') ? await getSkillCardById(c.env, str('id')) : null; return render(c, { title: 'Admin', noindex: true }, , e.status); } }); app.post('/admin/skills/:id/:action', async (c) => { const a = admin(c); const skill = await getSkillCardById(c.env, c.req.param('id')); if (!skill) throw new HttpError(404, 'Skill not found.'); const action = c.req.param('action'); if (action === 'category') { const form = await c.req.parseBody(); await c.env.DB.prepare('UPDATE skills SET category = ? WHERE id = ?').bind(cleanCategory(form.category), skill.id).run(); } else if (action === 'feature') { if (skill.kind === 'link') throw new HttpError(400, 'Fresh Harvest is for skills shared by growers.'); if (tierFor(skill.owner_seeds).threshold < TIERS[3].threshold) throw new HttpError(400, 'Fresh Harvest is for Harvester tier and up.'); await c.env.DB.prepare("UPDATE skills SET featured_at = ? WHERE id = ? AND state = 'live'").bind(now(), skill.id).run(); } else if (action === 'unfeature') await c.env.DB.prepare('UPDATE skills SET featured_at = NULL WHERE id = ?').bind(skill.id).run(); else if (action === 'offhome') await c.env.DB.prepare('UPDATE skills SET off_home = 1, featured_at = NULL WHERE id = ?').bind(skill.id).run(); else if (action === 'onhome') await c.env.DB.prepare('UPDATE skills SET off_home = 0 WHERE id = ?').bind(skill.id).run(); else if (action === 'hide') await setSkillState(c.env, a, skill, 'hidden'); else if (action === 'restore') await setSkillState(c.env, a, skill, 'live'); else if (action === 'remove') await setSkillState(c.env, a, skill, 'removed', 'Removed by a moderator.'); else throw new HttpError(404, 'Unknown action.'); setFlash(c, 'ok', 'Done.'); return c.redirect(safeNext(c.req.header('referer') ? new URL(c.req.header('referer')!).pathname + new URL(c.req.header('referer')!).search : '/admin?tab=skills', '/admin?tab=skills')); }); app.post('/admin/users/:id/:action', async (c) => { const a = admin(c); const target = await getUserById(c.env, c.req.param('id')); if (!target) throw new HttpError(404, 'Member not found.'); const action = c.req.param('action'); const log = (act: string) => c.env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, created_at) VALUES (?,?,?,?,?,?)').bind(newId(), a.id, act, 'user', target.id, now()).run(); if (target.is_agent) throw new HttpError(400, 'Sprout is the site agent, not a member.'); if (action === 'ban') await banUser(c.env, a, target.id, ''); else if (action === 'unban') { await c.env.DB.prepare("UPDATE users SET status = 'active' WHERE id = ? AND status = 'banned'").bind(target.id).run(); await log('unban'); } else if (action === 'strike') { await c.env.DB.prepare('UPDATE users SET strikes = strikes + 1 WHERE id = ?').bind(target.id).run(); await log('strike'); } else if (action === 'spotlight') { if (target.seeds_total < TIERS[4].threshold) throw new HttpError(400, 'The spotlight is for Homesteader tier and up.'); await c.env.DB.prepare('UPDATE users SET spotlight_at = ? WHERE id = ?').bind(now(), target.id).run(); } else if (action === 'unspotlight') await c.env.DB.prepare('UPDATE users SET spotlight_at = NULL WHERE id = ?').bind(target.id).run(); else throw new HttpError(404, 'Unknown action.'); setFlash(c, 'ok', 'Done.'); return c.redirect('/admin?tab=members'); }); app.post('/admin/reports/:id/resolve', async (c) => { const a = admin(c); await c.env.DB.prepare('UPDATE reports SET resolved_at = ?, resolved_by = ? WHERE id = ?').bind(now(), a.id, c.req.param('id')).run(); setFlash(c, 'ok', 'Report resolved.'); return c.redirect('/admin?tab=reports'); }); }