Branchwell

Skillfarm / website · skillfarm.ai / src / routes / admin.tsx

Raw 54.7 KB on a4acba8fed02ff053e24fa2ab137b32f1b601fa1
1import type { Hono } from 'hono';
2import type { AppEnv, Ctx, User } from '../env';
3import { runAiReview, type AiReport } from '../lib/ai';
4import { approveRepo, getImport, importItems, rejectRepo, settleImportOfVersion, type ImportItemView } from '../lib/imports';
5import type { Finding } from '../lib/scan';
6import { setFlash } from '../lib/session';
7import { banUser, CATEGORIES, categoryName, cleanCategory, decideVersion, getSkillCardById, getVersion, listSkills, PLATFORMS, readVersionFiles, savePick, setSkillState, splitPlatforms, type ManifestEntry, type SkillCard } from '../lib/skills';
8import { TIERS, tierFor } from '../lib/tiers';
9import { getUserById } from '../lib/users';
10import { HttpError, likeEscape, newId, now, plural, safeNext, timeAgo } from '../lib/util';
11import { Avatar, Empty, stateLabel, TierBadge } from '../views/components';
12import { render } from '../views/layout';
13import { FindingsList } from './skills';
14
15function admin(c: Ctx): User {
16 const u = c.get('user');
17 if (!u || !u.is_admin) throw new HttpError(404, 'Not found.');
18 return u;
19}
20
21const REC_LABEL: Record<string, string> = { approve: 'Approve', deny: 'Deny', needs_review: 'Needs a close look' };
22
23const RecPill = ({ status, rec }: { status: string; rec: string | null }) => {
24 if (status === 'done' && rec) return <span class={`pill rec-${rec}`}>AI: {REC_LABEL[rec] ?? rec}</span>;
25 if (status === 'queued' || status === 'running') return <span class="pill">AI review running</span>;
26 if (status === 'unavailable') return <span class="pill">AI review not configured</span>;
27 return <span class="pill pill-rejected">AI review failed</span>;
28};
29
30/** Ready-made reasons for a denial. The text is emailed to the member as the reviewer's note. */
31export const DENY_REASONS: Record<string, { label: string; text: string }> = {
32 quality: {
33 label: 'Not strong enough yet',
34 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.',
35 },
36 duplicate: {
37 label: 'Too close to one we list',
38 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.',
39 },
40 personal: {
41 label: 'Only works on your setup',
42 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.',
43 },
44 unsafe: {
45 label: 'Not safe to install',
46 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.',
47 },
48};
49
50const QUALITY_LABEL: Record<string, { label: string; cls: string }> = {
51 excellent: { label: 'Quality: excellent', cls: 'rec-approve' },
52 good: { label: 'Quality: good', cls: 'rec-approve' },
53 thin: { label: 'Quality: thin', cls: 'rec-needs_review' },
54 poor: { label: 'Quality: poor', cls: 'rec-deny' },
55};
56
57function parseAi(json: string | null): AiReport | null {
58 if (!json) return null;
59 try { return JSON.parse(json) as AiReport; } catch { return null; }
60}
61
62const QualityPill = ({ ai }: { ai: AiReport | null }) => (ai?.quality && QUALITY_LABEL[ai.quality] ? <span class={`pill ${QUALITY_LABEL[ai.quality].cls}`}>{QUALITY_LABEL[ai.quality].label}</span> : null);
63
64const OverlapNote = ({ ai }: { ai: AiReport | null }) => {
65 const close = (ai?.similar ?? []).filter((x) => x.overlap !== 'related');
66 if (!close.length) return null;
67 return <span class="pill rec-needs_review">{close.some((x) => x.overlap === 'duplicate') ? 'Duplicate of a listed skill' : `Close to ${plural(close.length, 'listed skill')}`}</span>;
68};
69
70const ReasonPicker = ({ pick = 'quality', label = 'Reason' }: { pick?: string; label?: string }) => (
71 <label class="reason-pick">
72 <span>{label}</span>
73 <select name="preset">
74 {Object.entries(DENY_REASONS).map(([k, r]) => <option value={k} selected={k === pick}>{r.label}</option>)}
75 </select>
76 </label>
77);
78
79/** The reason that best fits what the AI review found, to preselect in the picker. */
80function suggestedReason(ai: AiReport | null): string {
81 if (!ai) return 'quality';
82 if (ai.risk_level === 'high' || ai.risk_level === 'medium') return 'unsafe';
83 if ((ai.similar ?? []).some((x) => x.overlap === 'duplicate')) return 'duplicate';
84 return 'quality';
85}
86
87const AdminNav = ({ tab, counts }: { tab: string; counts: { queue: number; reports: number } }) => (
88 <div class="tabs page-tabs">
89 <a href="/admin" class={tab === 'queue' ? 'is-active' : ''}>Review queue ({counts.queue})</a>
90 <a href="/admin?tab=reports" class={tab === 'reports' ? 'is-active' : ''}>Reports ({counts.reports})</a>
91 <a href="/admin?tab=skills" class={tab === 'skills' ? 'is-active' : ''}>Skills</a>
92 <a href="/admin?tab=picks" class={tab === 'picks' ? 'is-active' : ''}>Sprout's picks</a>
93 <a href="/admin?tab=members" class={tab === 'members' ? 'is-active' : ''}>Members</a>
94 <a href="/admin?tab=system" class={tab === 'system' ? 'is-active' : ''}>System</a>
95 </div>
96);
97
98const PickForm = ({ pick, values, error }: { pick: SkillCard | null; values?: Record<string, string>; error?: string }) => {
99 const v = values ?? {};
100 const val = (k: string, cur: string | null | undefined) => v[k] ?? cur ?? '';
101 const chosen = v.platforms !== undefined ? v.platforms.split(',') : pick ? splitPlatforms(pick.platforms) : PLATFORMS.map((p) => p.key);
102 return (
103 <form method="post" action="/admin/picks" class="form card pad" id="pick-form">
104 <h2>{pick ? `Edit "${pick.title}"` : 'Add a pick'}</h2>
105 <p class="muted">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.</p>
106 {error ? <div class="notice notice-error" role="alert">{error}</div> : null}
107 {pick ? <input type="hidden" name="id" value={pick.id} /> : null}
108 <div class="form-grid">
109 <label><span>Title</span><input name="title" required maxlength={80} value={val('title', pick?.title)} /></label>
110 <label><span>Maker</span><input name="maker" required maxlength={80} value={val('maker', pick?.maker)} placeholder="What kind of maker, such as a cloud company" /></label>
111 <label><span>Repo</span><input name="repo" required value={val('repo', pick?.github_repo)} placeholder="owner/name" autocapitalize="none" spellcheck={false} /></label>
112 <label><span>Folder in the repo (optional)</span><input name="path" value={val('path', pick?.github_path)} placeholder="skills/my-skill" autocapitalize="none" spellcheck={false} /></label>
113 <label>
114 <span>Category</span>
115 <select name="category" required>
116 <option value="">Choose one</option>
117 {CATEGORIES.map((cat) => <option value={cat.key} selected={val('category', pick?.category) === cat.key}>{cat.name}</option>)}
118 </select>
119 </label>
120 <label><span>License</span><input name="license" maxlength={60} value={val('license', pick?.license)} placeholder="MIT, Apache-2.0, or leave empty" /></label>
121 </div>
122 <label><span>What it does</span><input name="summary" required maxlength={280} value={val('summary', pick?.summary)} /></label>
123 <label><span>Why Sprout recommends it</span><textarea name="note" rows={3} maxlength={600}>{val('note', pick?.pick_note)}</textarea></label>
124 <label><span>Install command, from the maker's README</span><textarea name="install_hint" rows={2} maxlength={400} class="mono" spellcheck={false}>{val('install_hint', pick?.install_hint)}</textarea></label>
125 <details class="optional">
126 <summary>Links, if they differ from the repo</summary>
127 <label><span>Where to get it</span><input name="source_url" type="url" value={val('source_url', pick?.source_url)} placeholder="Defaults to the repo or folder" /></label>
128 <label><span>Maker's page</span><input name="maker_url" type="url" value={val('maker_url', pick?.maker_url)} placeholder="Defaults to the repo owner" /></label>
129 </details>
130 <fieldset class="checks">
131 <legend>Works with</legend>
132 {PLATFORMS.map((p) => (
133 <label><input type="checkbox" name="platforms" value={p.key} checked={chosen.includes(p.key)} /><span>{p.name}</span></label>
134 ))}
135 </fieldset>
136 <div class="form-foot">
137 <button class="btn btn-primary" type="submit">{pick ? 'Save changes' : 'Publish pick'}</button>
138 {pick ? <a class="btn btn-ghost" href="/admin?tab=picks">Cancel</a> : null}
139 </div>
140 </form>
141 );
142};
143
144export function registerAdmin(app: Hono<AppEnv>) {
145 app.get('/admin', async (c) => {
146 admin(c);
147 const tab = ['reports', 'skills', 'picks', 'members', 'system'].includes(c.req.query('tab') ?? '') ? c.req.query('tab')! : 'queue';
148 const q = (c.req.query('q') ?? '').trim().slice(0, 60);
149 const cnt = await c.env.DB.batch<{ n: number }>([
150 c.env.DB.prepare("SELECT COUNT(*) AS n FROM skill_versions WHERE status = 'pending'"),
151 c.env.DB.prepare('SELECT COUNT(*) AS n FROM reports WHERE resolved_at IS NULL'),
152 ]);
153 const counts = { queue: cnt[0].results[0]?.n ?? 0, reports: cnt[1].results[0]?.n ?? 0 };
154 let body;
155 if (tab === 'queue') {
156 // Shared repos come first: one card per repo, with its skills inside.
157 const repos = await c.env.DB.prepare(
158 `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,
159 (SELECT COUNT(*) FROM skills s2 WHERE s2.owner_id = u.id AND s2.state = 'live') AS live_skills,
160 (SELECT provider_user_id FROM oauth_accounts o WHERE o.user_id = u.id AND o.provider = 'github') AS gh_id
161 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
162 WHERE m.status = 'reading' OR (m.status = 'review' AND EXISTS (
163 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'))
164 ORDER BY m.created_at ASC LIMIT 40`,
165 ).all<any>();
166 const waiting = repos.results.length
167 ? await c.env.DB.prepare(
168 `SELECT i.import_id, v.id, v.title, v.scan_status, v.ai_status, v.ai_recommendation, v.ai_report
169 FROM repo_import_items i JOIN skill_versions v ON v.id = i.version_id
170 WHERE v.status = 'pending' AND i.import_id IN (${repos.results.map(() => '?').join(',')}) ORDER BY i.path ASC`,
171 ).bind(...repos.results.map((m) => m.id)).all<any>()
172 : { results: [] as any[] };
173 const rows = await c.env.DB.prepare(
174 `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,
175 u.handle, u.display_name, u.avatar_key, u.avatar_fallback, u.id AS owner_id, u.seeds_total, u.strikes,
176 (SELECT COUNT(*) FROM skills s2 WHERE s2.owner_id = u.id AND s2.state = 'live') AS live_skills
177 FROM skill_versions v JOIN skills s ON s.id = v.skill_id JOIN users u ON u.id = s.owner_id
178 WHERE v.status = 'pending' AND NOT EXISTS (
179 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'))
180 ORDER BY v.created_at ASC LIMIT 100`,
181 ).all<any>();
182 body = repos.results.length || rows.results.length ? (
183 <>
184 {repos.results.length ? (
185 <ul class="queue">
186 {repos.results.map((m) => {
187 const mine = waiting.results.filter((w) => w.import_id === m.id);
188 const tally = { approve: 0, deny: 0, needs_review: 0, waiting: 0 };
189 for (const w of mine) {
190 if (w.ai_status === 'done' && w.ai_recommendation in tally) tally[w.ai_recommendation as 'approve'] += 1;
191 else tally.waiting += 1;
192 }
193 return (
194 <li class="card pad repo-card">
195 <div class="repo-card-head">
196 <div class="queue-main">
197 <h3><a href={`/admin/repo/${m.id}`}>{m.repo}</a> <small>{m.status === 'reading' ? 'still being read' : plural(mine.length, 'skill')}</small></h3>
198 <p class="queue-meta">
199 <a class="by" href={`/u/${m.handle}`}><Avatar user={{ id: m.owner_id, handle: m.handle, avatar_key: m.avatar_key, avatar_fallback: m.avatar_fallback }} size={22} /> <span>@{m.handle}</span></a>
200 <span>{m.live_skills} live skills{m.strikes ? `, ${m.strikes} strikes` : ''}</span>
201 {m.gh_id && m.gh_id === m.repo_owner_id ? <span class="pill pill-verified">Verified repo owner</span> : null}
202 {typeof m.stars === 'number' ? <span>{plural(m.stars, 'star')}</span> : null}
203 <a href={`https://github.com/${m.repo}`} target="_blank" rel="noopener noreferrer">Open on GitHub</a>
204 <span>{timeAgo(m.created_at)}</span>
205 </p>
206 {mine.length ? (
207 <p class="queue-meta">
208 <span>AI says:</span>
209 {tally.approve ? <span class="pill rec-approve">{tally.approve} approve</span> : null}
210 {tally.needs_review ? <span class="pill rec-needs_review">{tally.needs_review} close look</span> : null}
211 {tally.deny ? <span class="pill rec-deny">{tally.deny} deny</span> : null}
212 {tally.waiting ? <span class="pill">{tally.waiting} not reviewed yet</span> : null}
213 </p>
214 ) : null}
215 </div>
216 <div class="queue-side">
217 <a class="btn btn-primary btn-sm" href={`/admin/repo/${m.id}`}>Review repo</a>
218 {m.status === 'review' ? (
219 <form method="post" action={`/admin/repo/${m.id}/decide`} class="quick-reject" data-confirm={`Reject all of ${m.repo}? The member gets an email with the reason.`}>
220 <input type="hidden" name="decision" value="reject" />
221 <ReasonPicker label="Reject with" />
222 <button class="btn btn-danger btn-sm" type="submit">Reject whole repo</button>
223 </form>
224 ) : null}
225 </div>
226 </div>
227 {mine.length ? (
228 <ul class="repo-skills">
229 {mine.map((w) => {
230 const ai = parseAi(w.ai_report);
231 return (
232 <li>
233 <a href={`/admin/review/${w.id}`}>{w.title}</a>
234 <RecPill status={w.ai_status} rec={w.ai_recommendation} />
235 <QualityPill ai={ai} />
236 <OverlapNote ai={ai} />
237 {w.scan_status !== 'clean' ? <span class={`pill scan-${w.scan_status}`}>Patterns: {w.scan_status === 'high' ? 'high risk' : 'flagged'}</span> : null}
238 </li>
239 );
240 })}
241 </ul>
242 ) : null}
243 </li>
244 );
245 })}
246 </ul>
247 ) : null}
248 {rows.results.length ? (
249 <>
250 {repos.results.length ? <h2 class="queue-split">Single skills</h2> : null}
251 <ul class="queue">
252 {rows.results.map((r) => (
253 <li class="card pad queue-row">
254 <div class="queue-main">
255 <h3><a href={`/admin/review/${r.id}`}>{r.title}</a> <small>v{r.version}</small></h3>
256 <p class="muted">{r.ai_summary ?? r.summary}</p>
257 <p class="queue-meta">
258 <a class="by" href={`/u/${r.handle}`}><Avatar user={{ id: r.owner_id, handle: r.handle, avatar_key: r.avatar_key, avatar_fallback: r.avatar_fallback }} size={22} /> <span>@{r.handle}</span></a>
259 <span>{r.live_skills} live skills{r.strikes ? `, ${r.strikes} strikes` : ''}</span>
260 <span>via {r.source === 'mcp' ? 'MCP' : 'website'}</span>
261 {r.github_repo ? <span>{r.github_repo}</span> : null}
262 <span>{timeAgo(r.created_at)}</span>
263 </p>
264 </div>
265 <div class="queue-side">
266 <RecPill status={r.ai_status} rec={r.ai_recommendation} />
267 <QualityPill ai={parseAi(r.ai_report)} />
268 <span class={`pill scan-${r.scan_status}`}>Patterns: {r.scan_status === 'clean' ? 'clean' : r.scan_status === 'high' ? 'high risk' : 'flagged'}</span>
269 <a class="btn btn-primary btn-sm" href={`/admin/review/${r.id}`}>Review</a>
270 </div>
271 </li>
272 ))}
273 </ul>
274 </>
275 ) : null}
276 </>
277 ) : (
278 <Empty title="The queue is empty" art="harvest"><p>Repos that members share show up here. You get an email when one is ready.</p></Empty>
279 );
280 } else if (tab === 'reports') {
281 const rows = await c.env.DB.prepare(
282 `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`,
283 ).all<{ id: string; target_type: string; target_id: string; reason: string; created_at: number; reporter: string }>();
284 const items = [];
285 for (const r of rows.results) {
286 let link = '/admin';
287 let label = r.target_id;
288 if (r.target_type === 'skill') {
289 const s = await getSkillCardById(c.env, r.target_id);
290 if (s) { link = `/skills/${s.owner_handle}/${s.slug}`; label = `${s.title} by @${s.owner_handle} (${stateLabel(s.state)})`; }
291 } else if (r.target_type === 'user') {
292 const u = await getUserById(c.env, r.target_id);
293 if (u) { link = `/u/${u.handle}`; label = `@${u.handle}`; }
294 } else if (r.target_type === 'review') {
295 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 }>();
296 if (rv) { link = `/skills/${rv.owner}/${rv.slug}?tab=reviews`; label = `Review by @${rv.handle}: ${rv.body.slice(0, 80)}`; }
297 } else if (r.target_type === 'comment') {
298 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 }>();
299 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)}`; }
300 }
301 items.push({ r, link, label });
302 }
303 body = items.length ? (
304 <ul class="queue">
305 {items.map(({ r, link, label }) => (
306 <li class="card pad queue-row">
307 <div class="queue-main">
308 <h3><a href={link}>{label}</a></h3>
309 <p>{r.reason}</p>
310 <p class="queue-meta"><span>{r.target_type}</span><span>reported by @{r.reporter}</span><span>{timeAgo(r.created_at)}</span></p>
311 </div>
312 <div class="queue-side">
313 <form method="post" action={`/admin/reports/${r.id}/resolve`}>
314 <button class="btn btn-ghost btn-sm" type="submit">Mark resolved</button>
315 </form>
316 </div>
317 </li>
318 ))}
319 </ul>
320 ) : (
321 <Empty title="No open reports" art="tend"><p>Reports from members show up here.</p></Empty>
322 );
323 } else if (tab === 'skills') {
324 const rows = await listSkills(c.env, { q, sort: 'updated', limit: 60, states: ['live', 'hidden', 'pending', 'rejected'] });
325 const harvester = TIERS[3].threshold;
326 body = (
327 <>
328 <form method="get" action="/admin" class="search">
329 <input type="hidden" name="tab" value="skills" />
330 <input type="search" name="q" value={q} placeholder="Search skills" aria-label="Search skills" />
331 <button class="btn btn-ghost" type="submit">Search</button>
332 </form>
333 <table class="table admin-table">
334 <thead><tr><th>Skill</th><th>Owner</th><th>Category</th><th>State</th><th class="num">Likes</th><th>Actions</th></tr></thead>
335 <tbody>
336 {rows.map((s) => (
337 <tr>
338 <td><a href={`/skills/${s.owner_handle}/${s.slug}`}>{s.title}</a>{s.featured_at ? <span class="pill pill-verified">Fresh Harvest</span> : null}{s.kind === 'link' ? <span class="pill pill-pick">Pick</span> : null}{s.off_home ? <span class="pill">Off home</span> : null}</td>
339 <td><a href={`/u/${s.owner_handle}`}>@{s.owner_handle}</a> {s.kind === 'link' ? null : <TierBadge seeds={s.owner_seeds} size={18} label={false} />}</td>
340 <td>
341 <form method="post" action={`/admin/skills/${s.id}/category`} class="inline-set">
342 <select name="category" aria-label={`Category for ${s.title}`}>
343 <option value="">None</option>
344 {CATEGORIES.map((cat) => <option value={cat.key} selected={s.category === cat.key}>{cat.name}</option>)}
345 </select>
346 <button class="link-btn" type="submit">Set</button>
347 </form>
348 </td>
349 <td>{stateLabel(s.state)}</td>
350 <td class="num">{s.likes_count}</td>
351 <td class="actions">
352 {s.state === 'live' && s.kind !== 'link' ? (
353 <>
354 <form method="post" action={`/admin/skills/${s.id}/${s.featured_at ? 'unfeature' : 'feature'}`}>
355 <button class="link-btn" type="submit" disabled={!s.featured_at && s.owner_seeds < harvester} title={s.owner_seeds < harvester ? 'Fresh Harvest is for Harvester tier and up' : ''}>{s.featured_at ? 'Unfeature' : 'Feature'}</button>
356 </form>
357 <form method="post" action={`/admin/skills/${s.id}/${s.off_home ? 'onhome' : 'offhome'}`}>
358 <button class="link-btn" type="submit" title={s.off_home ? 'Let this skill appear on the home page again' : 'Keep this skill off the home page. It stays in the catalog.'}>{s.off_home ? 'Allow on home' : 'Keep off home'}</button>
359 </form>
360 <form method="post" action={`/admin/skills/${s.id}/hide`}><button class="link-btn" type="submit">Hide</button></form>
361 </>
362 ) : null}
363 {s.state === 'live' && s.kind === 'link' ? (
364 <>
365 <a class="link-btn" href={`/admin?tab=picks&edit=${s.id}#pick-form`}>Edit</a>
366 <form method="post" action={`/admin/skills/${s.id}/hide`}><button class="link-btn" type="submit">Hide</button></form>
367 </>
368 ) : null}
369 {s.state === 'hidden' ? <form method="post" action={`/admin/skills/${s.id}/restore`}><button class="link-btn" type="submit">Restore</button></form> : null}
370 <form method="post" action={`/admin/skills/${s.id}/remove`} data-confirm="Remove this skill and reverse its Seeds?"><button class="link-btn danger" type="submit">Remove</button></form>
371 </td>
372 </tr>
373 ))}
374 </tbody>
375 </table>
376 </>
377 );
378 } else if (tab === 'picks') {
379 const rows = await listSkills(c.env, { kind: 'link', q, sort: 'updated', limit: 100, states: ['live', 'hidden'] });
380 const editing = c.req.query('edit') ? rows.find((r) => r.id === c.req.query('edit')) ?? null : null;
381 body = (
382 <>
383 <p class="lede">Skills from other makers that Sprout recommends. {rows.length} listed. Anything you add or remove here changes the public site right away.</p>
384 <PickForm pick={editing} />
385 <form method="get" action="/admin" class="search">
386 <input type="hidden" name="tab" value="picks" />
387 <input type="search" name="q" value={q} placeholder="Search picks" aria-label="Search picks" />
388 <button class="btn btn-ghost" type="submit">Search</button>
389 </form>
390 <table class="table admin-table">
391 <thead><tr><th>Pick</th><th>Maker</th><th>Category</th><th>License</th><th class="num">Stars</th><th>State</th><th>Actions</th></tr></thead>
392 <tbody>
393 {rows.map((s) => (
394 <tr>
395 <td><a href={`/skills/${s.owner_handle}/${s.slug}`}>{s.title}</a></td>
396 <td>{s.maker} <span class="muted">{s.github_repo}</span></td>
397 <td>{categoryName(s.category) ?? ''}</td>
398 <td>{s.license ?? 'Not stated'}</td>
399 <td class="num">{s.stars ?? ''}</td>
400 <td>{stateLabel(s.state)}</td>
401 <td class="actions">
402 <a class="link-btn" href={`/admin?tab=picks&edit=${s.id}#pick-form`}>Edit</a>
403 {s.state === 'live' ? <form method="post" action={`/admin/skills/${s.id}/hide`}><button class="link-btn" type="submit">Hide</button></form> : null}
404 {s.state === 'hidden' ? <form method="post" action={`/admin/skills/${s.id}/restore`}><button class="link-btn" type="submit">Restore</button></form> : null}
405 <form method="post" action={`/admin/skills/${s.id}/remove`} data-confirm="Remove this pick from the site?"><button class="link-btn danger" type="submit">Remove</button></form>
406 </td>
407 </tr>
408 ))}
409 </tbody>
410 </table>
411 </>
412 );
413 } else if (tab === 'members') {
414 const like = `%${likeEscape(q)}%`;
415 const rows = await c.env.DB.prepare(
416 `SELECT * FROM users WHERE status != 'deleted' AND (handle LIKE ?1 ESCAPE '\\' OR display_name LIKE ?1 ESCAPE '\\') ORDER BY created_at DESC LIMIT 60`,
417 ).bind(like).all<User>();
418 const homesteader = TIERS[4].threshold;
419 body = (
420 <>
421 <form method="get" action="/admin" class="search">
422 <input type="hidden" name="tab" value="members" />
423 <input type="search" name="q" value={q} placeholder="Search members" aria-label="Search members" />
424 <button class="btn btn-ghost" type="submit">Search</button>
425 </form>
426 <table class="table admin-table">
427 <thead><tr><th>Member</th><th>Tier</th><th class="num">Seeds</th><th>Status</th><th>Joined</th><th>Actions</th></tr></thead>
428 <tbody>
429 {rows.results.map((u) => (
430 <tr>
431 <td><a href={`/u/${u.handle}`}>@{u.handle}</a> {u.is_admin ? <span class="pill">Admin</span> : null}{u.is_agent ? <span class="pill pill-agent">Site agent</span> : null}{u.spotlight_at ? <span class="pill pill-verified">Spotlight</span> : null}</td>
432 <td>{tierFor(u.seeds_total).name}</td>
433 <td class="num">{u.seeds_total}</td>
434 <td>{u.status}{u.strikes ? `, ${u.strikes} strikes` : ''}</td>
435 <td>{timeAgo(u.created_at)}</td>
436 <td class="actions">
437 {u.status === 'active' && !u.is_admin && !u.is_agent ? (
438 <>
439 <form method="post" action={`/admin/users/${u.id}/${u.spotlight_at ? 'unspotlight' : 'spotlight'}`}>
440 <button class="link-btn" type="submit" disabled={!u.spotlight_at && u.seeds_total < homesteader} title={u.seeds_total < homesteader ? 'The spotlight is for Homesteader tier and up' : ''}>{u.spotlight_at ? 'End spotlight' : 'Spotlight'}</button>
441 </form>
442 <form method="post" action={`/admin/users/${u.id}/strike`}><button class="link-btn" type="submit">Strike</button></form>
443 <form method="post" action={`/admin/users/${u.id}/ban`} data-confirm="Ban this member, hide their skills and sign them out?"><button class="link-btn danger" type="submit">Ban</button></form>
444 </>
445 ) : null}
446 {u.status === 'banned' ? <form method="post" action={`/admin/users/${u.id}/unban`}><button class="link-btn" type="submit">Unban</button></form> : null}
447 </td>
448 </tr>
449 ))}
450 </tbody>
451 </table>
452 </>
453 );
454 } else {
455 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 }>();
456 const e = c.env;
457 const checks: [string, boolean, string][] = [
458 ['Session secret', !!e.SESSION_SECRET, 'Required for sign-in.'],
459 ['AI review', !!e.ANTHROPIC_API_KEY, `ANTHROPIC_API_KEY. Model: ${e.AI_REVIEW_MODEL}.`],
460 ['Email', !!e.RESEND_API_KEY, `RESEND_API_KEY. Sends from ${e.EMAIL_FROM}.`],
461 ['VirusTotal lookup', !!e.VIRUSTOTAL_API_KEY, 'Optional. VIRUSTOTAL_API_KEY.'],
462 ];
463 body = (
464 <>
465 <h2>Integrations</h2>
466 <ul class="rows card pad">
467 {checks.map(([name, ok, note]) => (
468 <li><span class="row-main"><strong>{name}</strong> <em>{note}</em></span><span class={`pill ${ok ? 'pill-verified' : 'pill-rejected'}`}>{ok ? 'Configured' : 'Not set'}</span></li>
469 ))}
470 </ul>
471 <h2>Recent email</h2>
472 {mails.results.length ? (
473 <table class="table admin-table">
474 <thead><tr><th>Kind</th><th>Status</th><th>Detail</th><th>When</th></tr></thead>
475 <tbody>{mails.results.map((m) => <tr><td>{m.kind}</td><td>{m.status}</td><td>{m.detail ?? ''}</td><td>{timeAgo(m.created_at)}</td></tr>)}</tbody>
476 </table>
477 ) : <p class="muted">No email has been sent yet.</p>}
478 </>
479 );
480 }
481 return render(c, { title: 'Admin', noindex: true }, <div class="wrap section admin"><h1>Admin</h1><AdminNav tab={tab} counts={counts} />{body}</div>);
482 });
483
484 app.get('/admin/review/:id', async (c) => {
485 admin(c);
486 const v = await getVersion(c.env, c.req.param('id'));
487 if (!v) throw new HttpError(404, 'That submission was not found.');
488 const skill = await getSkillCardById(c.env, v.skill_id);
489 if (!skill) throw new HttpError(404, 'That skill was not found.');
490 const files = await readVersionFiles(c.env, v);
491 const manifest = JSON.parse(v.manifest) as ManifestEntry[];
492 const findings = JSON.parse(v.scan_report) as Finding[];
493 const ai = v.ai_report ? (JSON.parse(v.ai_report) as AiReport) : null;
494 const dec = new TextDecoder();
495 const parent = skill.replanted_from_skill_id ? await getSkillCardById(c.env, skill.replanted_from_skill_id) : null;
496 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 }>();
497 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 }>();
498 return render(
499 c,
500 { title: `Review: ${v.title}`, noindex: true },
501 <div class="wrap section admin review-page">
502 <p class="crumbs"><a href="/admin">Review queue</a> / {share ? <><a href={`/admin/repo/${share.id}`}>{share.repo}</a> / </> : null}{v.title}</p>
503 <h1>{v.title} <small>v{v.version}</small></h1>
504 <p class="lede">{v.summary}</p>
505 <p class="queue-meta">
506 <a class="by" href={`/u/${skill.owner_handle}`}><Avatar user={{ id: skill.owner_id, handle: skill.owner_handle, avatar_key: skill.owner_avatar_key, avatar_fallback: skill.owner_avatar_fallback }} size={24} /> <span>@{skill.owner_handle}</span></a>
507 <TierBadge seeds={skill.owner_seeds} size={18} />
508 <span>{history.results.map((h) => `${h.n} ${stateLabel(h.state).toLowerCase()}`).join(', ')}</span>
509 <span>via {skill.source === 'mcp' ? 'MCP' : 'website'}</span>
510 {skill.github_repo ? <a href={`https://github.com/${skill.github_repo}${skill.github_path ? `/tree/${skill.github_ref ?? 'HEAD'}/${skill.github_path}` : ''}`} rel="noopener">{skill.github_repo}</a> : <span>uploaded directly</span>}
511 {skill.verified_owner ? <span class="pill pill-verified">Verified repo owner</span> : null}
512 {parent ? <span>replant of <a href={`/skills/${parent.owner_handle}/${parent.slug}`}>{parent.owner_handle}/{parent.slug}</a></span> : null}
513 <span>submitted {timeAgo(v.created_at)}</span>
514 </p>
515
516 <div class="review-grid">
517 <section class={`card pad ai-box rec-box-${ai?.recommendation ?? 'none'}`}>
518 <h2>AI review <RecPill status={v.ai_status} rec={v.ai_recommendation} /> <QualityPill ai={ai} /></h2>
519 {ai ? (
520 <>
521 <p><strong>Risk: {ai.risk_level}.</strong> {ai.summary}</p>
522 {ai.what_it_does.length ? (<><h3>What it does</h3><ul>{ai.what_it_does.map((w) => <li>{w}</li>)}</ul></>) : null}
523 {ai.findings.length ? (
524 <>
525 <h3>Findings</h3>
526 <ul class="findings">{ai.findings.map((f) => <li class={`sev-${f.severity}`}><strong>{f.severity}</strong><span>{f.file}</span><p>{f.detail}</p></li>)}</ul>
527 </>
528 ) : <p class="muted">No safety findings.</p>}
529 {ai.quality_notes ? (<><h3>Quality</h3><p>{ai.quality_notes}</p></>) : null}
530 {ai.value_added ? (<><h3>What it adds</h3><p>{ai.value_added}</p></>) : null}
531 {ai.similar ? (
532 <>
533 <h3>Similar skills already listed</h3>
534 {ai.similar.length ? (
535 <ul class="similar">
536 {ai.similar.map((x) => (
537 <li><span class={`pill ${x.overlap === 'duplicate' ? 'rec-deny' : x.overlap === 'close' ? 'rec-needs_review' : ''}`}>{x.overlap}</span> <a href={`/skills/${x.skill}`} target="_blank" rel="noopener">{x.skill}</a> <span>{x.note}</span></li>
538 ))}
539 </ul>
540 ) : <p class="muted">Nothing listed does the same job.</p>}
541 </>
542 ) : null}
543 <p class="fine">Reviewed by {ai.model ?? c.env.AI_REVIEW_MODEL}. It is a recommendation. The decision is yours.</p>
544 </>
545 ) : (
546 <p class="muted">{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.'}</p>
547 )}
548 <form method="post" action={`/admin/review/${v.id}/rescan`}>
549 <button class="btn btn-ghost btn-sm" type="submit">Run the AI review again</button>
550 </form>
551 </section>
552
553 <section class="card pad">
554 <h2>Pattern scan <span class={`pill scan-${v.scan_status}`}>{v.scan_status === 'clean' ? 'clean' : v.scan_status === 'high' ? 'high risk' : 'flagged'}</span></h2>
555 <FindingsList findings={findings} />
556 </section>
557 </div>
558
559 {v.status === 'pending' ? (
560 <section class="card pad decide">
561 <h2>Decision</h2>
562 <form method="post" action={`/admin/review/${v.id}/decide`} class="form">
563 {share ? <input type="hidden" name="back" value={`/admin/repo/${share.id}`} /> : null}
564 <div class="form-grid">
565 <label>
566 <span>Category{!skill.category && ai?.category ? ' (suggested by the AI review)' : ''}</span>
567 <select name="category">
568 <option value="">None</option>
569 {CATEGORIES.map((cat) => <option value={cat.key} selected={(skill.category ?? ai?.category) === cat.key}>{cat.name}</option>)}
570 </select>
571 </label>
572 <ReasonPicker pick={suggestedReason(ai)} label="Quick reason for a denial" />
573 </div>
574 <label>
575 <span>Note to the author. A denial always goes out with a reason: this note if you write one, otherwise the quick reason above.</span>
576 <textarea name="note" rows={3} maxlength={1000}>{ai && ai.recommendation !== 'approve' ? ai.note_to_author : ''}</textarea>
577 </label>
578 <div class="form-foot">
579 <button class="btn btn-primary" type="submit" name="decision" value="approve">Approve and publish</button>
580 <button class="btn btn-danger" type="submit" name="decision" value="reject">Deny</button>
581 </div>
582 </form>
583 </section>
584 ) : (
585 <div class="notice notice-info"><strong>{v.status === 'approved' ? 'Approved' : v.status === 'rejected' ? 'Denied' : 'Superseded'}</strong>{v.decided_at ? ` ${timeAgo(v.decided_at)}.` : '.'} {v.decision_note ?? ''}</div>
586 )}
587
588 <h2>Files ({manifest.length})</h2>
589 {files.map((f, i) => (
590 <details class="card file-box" open={i === 0}>
591 <summary>{f.path} <span class="muted">{f.data.length} bytes</span></summary>
592 <pre class="code-view"><code>{dec.decode(f.data)}</code></pre>
593 </details>
594 ))}
595 </div>,
596 );
597 });
598
599 app.post('/admin/review/:id/decide', async (c) => {
600 const a = admin(c);
601 const form = await c.req.parseBody();
602 const decision = form.decision === 'approve' ? 'approve' : form.decision === 'reject' ? 'reject' : null;
603 if (!decision) throw new HttpError(400, 'Pick approve or deny.');
604 const id = c.req.param('id');
605 const back = safeNext(String(form.back ?? ''), '/admin');
606 // A denial always carries a reason: the note if one was written, otherwise the quick reason that was picked.
607 let note = String(form.note ?? '').trim().slice(0, 1000);
608 if (decision === 'reject' && !note) note = DENY_REASONS[String(form.preset ?? '')]?.text ?? '';
609 try {
610 if (decision === 'reject' && !note) throw new HttpError(400, 'Give a reason for the denial. Write a note or pick a quick reason.');
611 const skill = await decideVersion(c.env, a, id, decision, note, { category: cleanCategory(form.category) });
612 await settleImportOfVersion(c.env, id);
613 setFlash(c, 'ok', decision === 'approve' ? `Approved. "${skill.title}" is live and the author was notified.` : 'Denied. The author was sent the reason.');
614 } catch (e) {
615 if (!(e instanceof HttpError)) throw e;
616 setFlash(c, 'error', e.message);
617 if (e.status === 400) return c.redirect(`/admin/review/${id}`);
618 }
619 return c.redirect(back);
620 });
621
622 // One shared repo: deny all of it in one step, approve all of it, or take its skills one by one.
623 app.get('/admin/repo/:id', async (c) => {
624 admin(c);
625 const imp = await getImport(c.env, c.req.param('id'));
626 if (!imp) throw new HttpError(404, 'That shared repo was not found.');
627 const [items, owner, repo, gh] = await Promise.all([
628 importItems(c.env, imp.id),
629 getUserById(c.env, imp.user_id),
630 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 }>(),
631 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 }>(),
632 ]);
633 const waiting = items.filter((i) => i.version_status === 'pending');
634 const other = items.filter((i) => i.version_status !== 'pending');
635 const back = `/admin/repo/${imp.id}`;
636 const stateOf = (i: ImportItemView) =>
637 i.version_status === 'approved' ? { label: 'Approved', cls: 'pill-verified' }
638 : i.version_status === 'rejected' ? { label: 'Denied', cls: 'pill-rejected' }
639 : i.status === 'unchanged' ? { label: 'No change', cls: '' }
640 : i.status === 'skipped' ? { label: 'Left out', cls: '' }
641 : i.status === 'failed' ? { label: 'Could not be read', cls: 'pill-rejected' }
642 : { label: i.status === 'queued' || i.status === 'working' ? 'Being read' : i.version_status ?? i.status, cls: '' };
643 return render(
644 c,
645 { title: `Review: ${imp.repo}`, noindex: true },
646 <div class="wrap section admin repo-review">
647 <p class="crumbs"><a href="/admin">Review queue</a> / {imp.repo}</p>
648 <h1>{imp.repo}</h1>
649 <p class="queue-meta">
650 {owner ? <a class="by" href={`/u/${owner.handle}`}><Avatar user={owner} size={24} /> <span>@{owner.handle}</span></a> : null}
651 {owner ? <TierBadge seeds={owner.seeds_total} size={18} /> : null}
652 {gh && gh.provider_user_id === imp.repo_owner_id ? <span class="pill pill-verified">Verified repo owner</span> : <span class="pill">Repo owner not verified</span>}
653 <a href={`https://github.com/${imp.repo}/tree/${imp.ref}`} target="_blank" rel="noopener noreferrer">Open on GitHub</a>
654 {repo ? <span>{plural(repo.stars, 'star')}, {plural(repo.forks, 'fork')}</span> : null}
655 <span>License: {repo?.license_spdx ?? 'not stated'}</span>
656 {repo?.archived ? <span class="pill">Archived</span> : null}
657 <span>shared {timeAgo(imp.created_at)} via {imp.source === 'mcp' ? 'MCP' : 'website'}</span>
658 </p>
659
660 {imp.status === 'reading' ? <div class="notice notice-info"><strong>Still being read.</strong> Skillfarm found {plural(imp.found, 'skill')} and is reading them. Reload in a minute.</div> : null}
661 {imp.decision_note ? <div class="notice notice-info"><strong>Whole repo denied{imp.decided_at ? ` ${timeAgo(imp.decided_at)}` : ''}.</strong> {imp.decision_note}</div> : null}
662
663 {waiting.length && imp.status !== 'reading' ? (
664 <section class="card pad decide repo-decide">
665 <h2>Decide the whole repo</h2>
666 <p class="muted">{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.</p>
667 <div class="repo-decide-grid">
668 <form method="post" action={`/admin/repo/${imp.id}/decide`} class="form">
669 <input type="hidden" name="decision" value="reject" />
670 <ReasonPicker />
671 <label>
672 <span>Or write your own note to the member</span>
673 <textarea name="note" rows={2} maxlength={1000}></textarea>
674 </label>
675 <button class="btn btn-danger" type="submit">Reject whole repo</button>
676 </form>
677 <form method="post" action={`/admin/repo/${imp.id}/decide`} class="form" data-confirm={`Approve and publish all ${waiting.length} waiting skills from ${imp.repo}?`}>
678 <input type="hidden" name="decision" value="approve" />
679 <p>Publishes every waiting skill on @{owner?.handle}'s profile, filed under the category the AI review suggested.</p>
680 <button class="btn btn-primary" type="submit">Approve all {waiting.length}</button>
681 </form>
682 </div>
683 </section>
684 ) : null}
685
686 {waiting.length ? <h2>Waiting ({waiting.length})</h2> : null}
687 <ul class="queue">
688 {waiting.map((i) => {
689 const ai = parseAi(i.ai_report);
690 const close = (ai?.similar ?? []).filter((x) => x.overlap !== 'related');
691 return (
692 <li class={`card pad skill-decide rec-box-${i.ai_status === 'done' ? i.ai_recommendation ?? 'none' : 'none'}`}>
693 <div class="queue-main">
694 <h3><a href={`/admin/review/${i.version_id}`}>{i.title}</a> <small>{i.status === 'updated' ? `new version, v${i.version}` : i.path || '(repo root)'}</small></h3>
695 <p class="queue-meta">
696 <RecPill status={i.ai_status ?? 'queued'} rec={i.ai_recommendation} />
697 <QualityPill ai={ai} />
698 <OverlapNote ai={ai} />
699 <span class={`pill scan-${i.scan_status}`}>Patterns: {i.scan_status === 'clean' ? 'clean' : i.scan_status === 'high' ? 'high risk' : 'flagged'}</span>
700 {ai?.category ? <span class="pill">{categoryName(ai.category)}</span> : null}
701 </p>
702 <p>{ai?.summary ?? i.summary}</p>
703 {ai?.value_added ? <p class="muted"><strong>What it adds:</strong> {ai.value_added}</p> : null}
704 {close.length ? (
705 <ul class="similar">
706 {close.map((x) => <li><span class={`pill ${x.overlap === 'duplicate' ? 'rec-deny' : 'rec-needs_review'}`}>{x.overlap}</span> <a href={`/skills/${x.skill}`} target="_blank" rel="noopener">{x.skill}</a> <span>{x.note}</span></li>)}
707 </ul>
708 ) : null}
709 </div>
710 <div class="skill-decide-side">
711 <form method="post" action={`/admin/review/${i.version_id}/decide`}>
712 <input type="hidden" name="back" value={back} />
713 <input type="hidden" name="decision" value="approve" />
714 <input type="hidden" name="category" value={i.category ?? ai?.category ?? ''} />
715 <button class="btn btn-primary btn-sm btn-block" type="submit">Approve</button>
716 </form>
717 <form method="post" action={`/admin/review/${i.version_id}/decide`} class="quick-reject">
718 <input type="hidden" name="back" value={back} />
719 <input type="hidden" name="decision" value="reject" />
720 <ReasonPicker pick={suggestedReason(ai)} label="Deny with" />
721 <button class="btn btn-danger btn-sm btn-block" type="submit">Deny</button>
722 </form>
723 <a class="link-btn" href={`/admin/review/${i.version_id}`}>Read the files</a>
724 </div>
725 </li>
726 );
727 })}
728 </ul>
729
730 {other.length ? (
731 <>
732 <h2>{waiting.length ? 'Everything else in this repo' : 'Skills in this repo'}</h2>
733 <table class="table admin-table">
734 <thead><tr><th>Skill</th><th>Folder</th><th>State</th><th>Note</th></tr></thead>
735 <tbody>
736 {other.map((i) => {
737 const st = stateOf(i);
738 return (
739 <tr>
740 <td>{i.slug && owner ? <a href={`/skills/${owner.handle}/${i.slug}`}>{i.title}</a> : i.path.split('/').pop() || imp.repo}</td>
741 <td class="mono">{i.path || '(repo root)'}</td>
742 <td><span class={`pill ${st.cls}`}>{st.label}</span></td>
743 <td>{i.decision_note ?? i.detail ?? ''}</td>
744 </tr>
745 );
746 })}
747 </tbody>
748 </table>
749 </>
750 ) : null}
751 </div>,
752 );
753 });
754
755 app.post('/admin/repo/:id/decide', async (c) => {
756 const a = admin(c);
757 const id = c.req.param('id');
758 const form = await c.req.parseBody();
759 try {
760 if (form.decision === 'reject') {
761 const note = String(form.note ?? '').trim().slice(0, 1000) || (DENY_REASONS[String(form.preset ?? '')] ?? DENY_REASONS.quality).text;
762 const n = await rejectRepo(c.env, a, id, note);
763 setFlash(c, 'ok', n ? `Rejected. ${plural(n, 'skill')} turned down and the member was sent the reason.` : 'Nothing in that repo was waiting.');
764 return c.redirect('/admin');
765 }
766 if (form.decision === 'approve') {
767 const res = await approveRepo(c.env, a, id);
768 const more = res.problems.length ? ` ${res.problems.join(' ')}` : res.left ? ` ${res.left} still waiting: press Approve all again.` : '';
769 setFlash(c, res.problems.length ? 'error' : 'ok', `Approved ${plural(res.approved, 'skill')}. The member was notified.${more}`);
770 return c.redirect(res.left ? `/admin/repo/${id}` : '/admin');
771 }
772 throw new HttpError(400, 'Pick approve or reject.');
773 } catch (e) {
774 if (!(e instanceof HttpError)) throw e;
775 setFlash(c, 'error', e.message);
776 return c.redirect(`/admin/repo/${id}`);
777 }
778 });
779
780 app.post('/admin/review/:id/rescan', async (c) => {
781 admin(c);
782 const id = c.req.param('id');
783 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();
784 const result = await runAiReview(c.env, id);
785 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.');
786 return c.redirect(`/admin/review/${id}`);
787 });
788
789 app.post('/admin/picks', async (c) => {
790 const a = admin(c);
791 const form = await c.req.parseBody({ all: true });
792 const str = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : '');
793 const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string');
794 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(',') };
795 try {
796 const pick = await savePick(c.env, a, {
797 id: str('id') || undefined, title: values.title, summary: values.summary, category: values.category, maker: values.maker, makerUrl: values.maker_url, sourceUrl: values.source_url,
798 repo: values.repo.replace(/^https:\/\/github\.com\//i, '').replace(/\/+$/, ''), path: values.path, license: values.license, installHint: values.install_hint, note: values.note, platforms,
799 });
800 setFlash(c, 'ok', str('id') ? `Saved "${pick.title}".` : `"${pick.title}" is live as one of Sprout's picks.`);
801 return c.redirect('/admin?tab=picks');
802 } catch (e) {
803 if (!(e instanceof HttpError)) throw e;
804 const editing = str('id') ? await getSkillCardById(c.env, str('id')) : null;
805 return render(c, { title: 'Admin', noindex: true }, <div class="wrap section admin"><h1>Admin</h1><p class="crumbs"><a href="/admin?tab=picks">Sprout's picks</a></p><PickForm pick={editing} values={values} error={e.message} /></div>, e.status);
806 }
807 });
808
809 app.post('/admin/skills/:id/:action', async (c) => {
810 const a = admin(c);
811 const skill = await getSkillCardById(c.env, c.req.param('id'));
812 if (!skill) throw new HttpError(404, 'Skill not found.');
813 const action = c.req.param('action');
814 if (action === 'category') {
815 const form = await c.req.parseBody();
816 await c.env.DB.prepare('UPDATE skills SET category = ? WHERE id = ?').bind(cleanCategory(form.category), skill.id).run();
817 } else if (action === 'feature') {
818 if (skill.kind === 'link') throw new HttpError(400, 'Fresh Harvest is for skills shared by growers.');
819 if (tierFor(skill.owner_seeds).threshold < TIERS[3].threshold) throw new HttpError(400, 'Fresh Harvest is for Harvester tier and up.');
820 await c.env.DB.prepare("UPDATE skills SET featured_at = ? WHERE id = ? AND state = 'live'").bind(now(), skill.id).run();
821 } else if (action === 'unfeature') await c.env.DB.prepare('UPDATE skills SET featured_at = NULL WHERE id = ?').bind(skill.id).run();
822 else if (action === 'offhome') await c.env.DB.prepare('UPDATE skills SET off_home = 1, featured_at = NULL WHERE id = ?').bind(skill.id).run();
823 else if (action === 'onhome') await c.env.DB.prepare('UPDATE skills SET off_home = 0 WHERE id = ?').bind(skill.id).run();
824 else if (action === 'hide') await setSkillState(c.env, a, skill, 'hidden');
825 else if (action === 'restore') await setSkillState(c.env, a, skill, 'live');
826 else if (action === 'remove') await setSkillState(c.env, a, skill, 'removed', 'Removed by a moderator.');
827 else throw new HttpError(404, 'Unknown action.');
828 setFlash(c, 'ok', 'Done.');
829 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'));
830 });
831
832 app.post('/admin/users/:id/:action', async (c) => {
833 const a = admin(c);
834 const target = await getUserById(c.env, c.req.param('id'));
835 if (!target) throw new HttpError(404, 'Member not found.');
836 const action = c.req.param('action');
837 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();
838 if (target.is_agent) throw new HttpError(400, 'Sprout is the site agent, not a member.');
839 if (action === 'ban') await banUser(c.env, a, target.id, '');
840 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'); }
841 else if (action === 'strike') { await c.env.DB.prepare('UPDATE users SET strikes = strikes + 1 WHERE id = ?').bind(target.id).run(); await log('strike'); }
842 else if (action === 'spotlight') {
843 if (target.seeds_total < TIERS[4].threshold) throw new HttpError(400, 'The spotlight is for Homesteader tier and up.');
844 await c.env.DB.prepare('UPDATE users SET spotlight_at = ? WHERE id = ?').bind(now(), target.id).run();
845 } else if (action === 'unspotlight') await c.env.DB.prepare('UPDATE users SET spotlight_at = NULL WHERE id = ?').bind(target.id).run();
846 else throw new HttpError(404, 'Unknown action.');
847 setFlash(c, 'ok', 'Done.');
848 return c.redirect('/admin?tab=members');
849 });
850
851 app.post('/admin/reports/:id/resolve', async (c) => {
852 const a = admin(c);
853 await c.env.DB.prepare('UPDATE reports SET resolved_at = ?, resolved_by = ? WHERE id = ?').bind(now(), a.id, c.req.param('id')).run();
854 setFlash(c, 'ok', 'Report resolved.');
855 return c.redirect('/admin?tab=reports');
856 });
857}