Branchwell

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

Raw 54.8 KB on 154cbccf923a68550a73e85d66bba0b0fb8f1943
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, credits the maker, and links to their repo. Skillfarm stores no copy.</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="Who made it" /></label>
111 <label><span>GitHub 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 on GitHub" /></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 on GitHub" /></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 ['GitHub sign-in', !!(e.GITHUB_CLIENT_ID && e.GITHUB_CLIENT_SECRET), 'GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET. Also raises the GitHub star lookup limit.'],
460 ['Google sign-in', !!(e.GOOGLE_CLIENT_ID && e.GOOGLE_CLIENT_SECRET), 'GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET.'],
461 ['AI review', !!e.ANTHROPIC_API_KEY, `ANTHROPIC_API_KEY. Model: ${e.AI_REVIEW_MODEL}.`],
462 ['Email', !!e.RESEND_API_KEY, `RESEND_API_KEY. Sends from ${e.EMAIL_FROM}.`],
463 ['VirusTotal lookup', !!e.VIRUSTOTAL_API_KEY, 'Optional. VIRUSTOTAL_API_KEY.'],
464 ];
465 body = (
466 <>
467 <h2>Integrations</h2>
468 <ul class="rows card pad">
469 {checks.map(([name, ok, note]) => (
470 <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>
471 ))}
472 </ul>
473 <h2>Recent email</h2>
474 {mails.results.length ? (
475 <table class="table admin-table">
476 <thead><tr><th>Kind</th><th>Status</th><th>Detail</th><th>When</th></tr></thead>
477 <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>
478 </table>
479 ) : <p class="muted">No email has been sent yet.</p>}
480 </>
481 );
482 }
483 return render(c, { title: 'Admin', noindex: true }, <div class="wrap section admin"><h1>Admin</h1><AdminNav tab={tab} counts={counts} />{body}</div>);
484 });
485
486 app.get('/admin/review/:id', async (c) => {
487 admin(c);
488 const v = await getVersion(c.env, c.req.param('id'));
489 if (!v) throw new HttpError(404, 'That submission was not found.');
490 const skill = await getSkillCardById(c.env, v.skill_id);
491 if (!skill) throw new HttpError(404, 'That skill was not found.');
492 const files = await readVersionFiles(c.env, v);
493 const manifest = JSON.parse(v.manifest) as ManifestEntry[];
494 const findings = JSON.parse(v.scan_report) as Finding[];
495 const ai = v.ai_report ? (JSON.parse(v.ai_report) as AiReport) : null;
496 const dec = new TextDecoder();
497 const parent = skill.replanted_from_skill_id ? await getSkillCardById(c.env, skill.replanted_from_skill_id) : null;
498 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 }>();
499 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 }>();
500 return render(
501 c,
502 { title: `Review: ${v.title}`, noindex: true },
503 <div class="wrap section admin review-page">
504 <p class="crumbs"><a href="/admin">Review queue</a> / {share ? <><a href={`/admin/repo/${share.id}`}>{share.repo}</a> / </> : null}{v.title}</p>
505 <h1>{v.title} <small>v{v.version}</small></h1>
506 <p class="lede">{v.summary}</p>
507 <p class="queue-meta">
508 <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>
509 <TierBadge seeds={skill.owner_seeds} size={18} />
510 <span>{history.results.map((h) => `${h.n} ${stateLabel(h.state).toLowerCase()}`).join(', ')}</span>
511 <span>via {skill.source === 'mcp' ? 'MCP' : 'website'}</span>
512 {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>}
513 {skill.verified_owner ? <span class="pill pill-verified">Verified repo owner</span> : null}
514 {parent ? <span>replant of <a href={`/skills/${parent.owner_handle}/${parent.slug}`}>{parent.owner_handle}/{parent.slug}</a></span> : null}
515 <span>submitted {timeAgo(v.created_at)}</span>
516 </p>
517
518 <div class="review-grid">
519 <section class={`card pad ai-box rec-box-${ai?.recommendation ?? 'none'}`}>
520 <h2>AI review <RecPill status={v.ai_status} rec={v.ai_recommendation} /> <QualityPill ai={ai} /></h2>
521 {ai ? (
522 <>
523 <p><strong>Risk: {ai.risk_level}.</strong> {ai.summary}</p>
524 {ai.what_it_does.length ? (<><h3>What it does</h3><ul>{ai.what_it_does.map((w) => <li>{w}</li>)}</ul></>) : null}
525 {ai.findings.length ? (
526 <>
527 <h3>Findings</h3>
528 <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>
529 </>
530 ) : <p class="muted">No safety findings.</p>}
531 {ai.quality_notes ? (<><h3>Quality</h3><p>{ai.quality_notes}</p></>) : null}
532 {ai.value_added ? (<><h3>What it adds</h3><p>{ai.value_added}</p></>) : null}
533 {ai.similar ? (
534 <>
535 <h3>Similar skills already listed</h3>
536 {ai.similar.length ? (
537 <ul class="similar">
538 {ai.similar.map((x) => (
539 <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>
540 ))}
541 </ul>
542 ) : <p class="muted">Nothing listed does the same job.</p>}
543 </>
544 ) : null}
545 <p class="fine">Reviewed by {ai.model ?? c.env.AI_REVIEW_MODEL}. It is a recommendation. The decision is yours.</p>
546 </>
547 ) : (
548 <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>
549 )}
550 <form method="post" action={`/admin/review/${v.id}/rescan`}>
551 <button class="btn btn-ghost btn-sm" type="submit">Run the AI review again</button>
552 </form>
553 </section>
554
555 <section class="card pad">
556 <h2>Pattern scan <span class={`pill scan-${v.scan_status}`}>{v.scan_status === 'clean' ? 'clean' : v.scan_status === 'high' ? 'high risk' : 'flagged'}</span></h2>
557 <FindingsList findings={findings} />
558 </section>
559 </div>
560
561 {v.status === 'pending' ? (
562 <section class="card pad decide">
563 <h2>Decision</h2>
564 <form method="post" action={`/admin/review/${v.id}/decide`} class="form">
565 {share ? <input type="hidden" name="back" value={`/admin/repo/${share.id}`} /> : null}
566 <div class="form-grid">
567 <label>
568 <span>Category{!skill.category && ai?.category ? ' (suggested by the AI review)' : ''}</span>
569 <select name="category">
570 <option value="">None</option>
571 {CATEGORIES.map((cat) => <option value={cat.key} selected={(skill.category ?? ai?.category) === cat.key}>{cat.name}</option>)}
572 </select>
573 </label>
574 <ReasonPicker pick={suggestedReason(ai)} label="Quick reason for a denial" />
575 </div>
576 <label>
577 <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>
578 <textarea name="note" rows={3} maxlength={1000}>{ai && ai.recommendation !== 'approve' ? ai.note_to_author : ''}</textarea>
579 </label>
580 <div class="form-foot">
581 <button class="btn btn-primary" type="submit" name="decision" value="approve">Approve and publish</button>
582 <button class="btn btn-danger" type="submit" name="decision" value="reject">Deny</button>
583 </div>
584 </form>
585 </section>
586 ) : (
587 <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>
588 )}
589
590 <h2>Files ({manifest.length})</h2>
591 {files.map((f, i) => (
592 <details class="card file-box" open={i === 0}>
593 <summary>{f.path} <span class="muted">{f.data.length} bytes</span></summary>
594 <pre class="code-view"><code>{dec.decode(f.data)}</code></pre>
595 </details>
596 ))}
597 </div>,
598 );
599 });
600
601 app.post('/admin/review/:id/decide', async (c) => {
602 const a = admin(c);
603 const form = await c.req.parseBody();
604 const decision = form.decision === 'approve' ? 'approve' : form.decision === 'reject' ? 'reject' : null;
605 if (!decision) throw new HttpError(400, 'Pick approve or deny.');
606 const id = c.req.param('id');
607 const back = safeNext(String(form.back ?? ''), '/admin');
608 // A denial always carries a reason: the note if one was written, otherwise the quick reason that was picked.
609 let note = String(form.note ?? '').trim().slice(0, 1000);
610 if (decision === 'reject' && !note) note = DENY_REASONS[String(form.preset ?? '')]?.text ?? '';
611 try {
612 if (decision === 'reject' && !note) throw new HttpError(400, 'Give a reason for the denial. Write a note or pick a quick reason.');
613 const skill = await decideVersion(c.env, a, id, decision, note, { category: cleanCategory(form.category) });
614 await settleImportOfVersion(c.env, id);
615 setFlash(c, 'ok', decision === 'approve' ? `Approved. "${skill.title}" is live and the author was notified.` : 'Denied. The author was sent the reason.');
616 } catch (e) {
617 if (!(e instanceof HttpError)) throw e;
618 setFlash(c, 'error', e.message);
619 if (e.status === 400) return c.redirect(`/admin/review/${id}`);
620 }
621 return c.redirect(back);
622 });
623
624 // One shared repo: deny all of it in one step, approve all of it, or take its skills one by one.
625 app.get('/admin/repo/:id', async (c) => {
626 admin(c);
627 const imp = await getImport(c.env, c.req.param('id'));
628 if (!imp) throw new HttpError(404, 'That shared repo was not found.');
629 const [items, owner, repo, gh] = await Promise.all([
630 importItems(c.env, imp.id),
631 getUserById(c.env, imp.user_id),
632 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 }>(),
633 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 }>(),
634 ]);
635 const waiting = items.filter((i) => i.version_status === 'pending');
636 const other = items.filter((i) => i.version_status !== 'pending');
637 const back = `/admin/repo/${imp.id}`;
638 const stateOf = (i: ImportItemView) =>
639 i.version_status === 'approved' ? { label: 'Approved', cls: 'pill-verified' }
640 : i.version_status === 'rejected' ? { label: 'Denied', cls: 'pill-rejected' }
641 : i.status === 'unchanged' ? { label: 'No change', cls: '' }
642 : i.status === 'skipped' ? { label: 'Left out', cls: '' }
643 : i.status === 'failed' ? { label: 'Could not be read', cls: 'pill-rejected' }
644 : { label: i.status === 'queued' || i.status === 'working' ? 'Being read' : i.version_status ?? i.status, cls: '' };
645 return render(
646 c,
647 { title: `Review: ${imp.repo}`, noindex: true },
648 <div class="wrap section admin repo-review">
649 <p class="crumbs"><a href="/admin">Review queue</a> / {imp.repo}</p>
650 <h1>{imp.repo}</h1>
651 <p class="queue-meta">
652 {owner ? <a class="by" href={`/u/${owner.handle}`}><Avatar user={owner} size={24} /> <span>@{owner.handle}</span></a> : null}
653 {owner ? <TierBadge seeds={owner.seeds_total} size={18} /> : null}
654 {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>}
655 <a href={`https://github.com/${imp.repo}/tree/${imp.ref}`} target="_blank" rel="noopener noreferrer">Open on GitHub</a>
656 {repo ? <span>{plural(repo.stars, 'star')}, {plural(repo.forks, 'fork')}</span> : null}
657 <span>License: {repo?.license_spdx ?? 'not stated'}</span>
658 {repo?.archived ? <span class="pill">Archived</span> : null}
659 <span>shared {timeAgo(imp.created_at)} via {imp.source === 'mcp' ? 'MCP' : 'website'}</span>
660 </p>
661
662 {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}
663 {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}
664
665 {waiting.length && imp.status !== 'reading' ? (
666 <section class="card pad decide repo-decide">
667 <h2>Decide the whole repo</h2>
668 <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>
669 <div class="repo-decide-grid">
670 <form method="post" action={`/admin/repo/${imp.id}/decide`} class="form">
671 <input type="hidden" name="decision" value="reject" />
672 <ReasonPicker />
673 <label>
674 <span>Or write your own note to the member</span>
675 <textarea name="note" rows={2} maxlength={1000}></textarea>
676 </label>
677 <button class="btn btn-danger" type="submit">Reject whole repo</button>
678 </form>
679 <form method="post" action={`/admin/repo/${imp.id}/decide`} class="form" data-confirm={`Approve and publish all ${waiting.length} waiting skills from ${imp.repo}?`}>
680 <input type="hidden" name="decision" value="approve" />
681 <p>Publishes every waiting skill on @{owner?.handle}'s profile, filed under the category the AI review suggested.</p>
682 <button class="btn btn-primary" type="submit">Approve all {waiting.length}</button>
683 </form>
684 </div>
685 </section>
686 ) : null}
687
688 {waiting.length ? <h2>Waiting ({waiting.length})</h2> : null}
689 <ul class="queue">
690 {waiting.map((i) => {
691 const ai = parseAi(i.ai_report);
692 const close = (ai?.similar ?? []).filter((x) => x.overlap !== 'related');
693 return (
694 <li class={`card pad skill-decide rec-box-${i.ai_status === 'done' ? i.ai_recommendation ?? 'none' : 'none'}`}>
695 <div class="queue-main">
696 <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>
697 <p class="queue-meta">
698 <RecPill status={i.ai_status ?? 'queued'} rec={i.ai_recommendation} />
699 <QualityPill ai={ai} />
700 <OverlapNote ai={ai} />
701 <span class={`pill scan-${i.scan_status}`}>Patterns: {i.scan_status === 'clean' ? 'clean' : i.scan_status === 'high' ? 'high risk' : 'flagged'}</span>
702 {ai?.category ? <span class="pill">{categoryName(ai.category)}</span> : null}
703 </p>
704 <p>{ai?.summary ?? i.summary}</p>
705 {ai?.value_added ? <p class="muted"><strong>What it adds:</strong> {ai.value_added}</p> : null}
706 {close.length ? (
707 <ul class="similar">
708 {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>)}
709 </ul>
710 ) : null}
711 </div>
712 <div class="skill-decide-side">
713 <form method="post" action={`/admin/review/${i.version_id}/decide`}>
714 <input type="hidden" name="back" value={back} />
715 <input type="hidden" name="decision" value="approve" />
716 <input type="hidden" name="category" value={i.category ?? ai?.category ?? ''} />
717 <button class="btn btn-primary btn-sm btn-block" type="submit">Approve</button>
718 </form>
719 <form method="post" action={`/admin/review/${i.version_id}/decide`} class="quick-reject">
720 <input type="hidden" name="back" value={back} />
721 <input type="hidden" name="decision" value="reject" />
722 <ReasonPicker pick={suggestedReason(ai)} label="Deny with" />
723 <button class="btn btn-danger btn-sm btn-block" type="submit">Deny</button>
724 </form>
725 <a class="link-btn" href={`/admin/review/${i.version_id}`}>Read the files</a>
726 </div>
727 </li>
728 );
729 })}
730 </ul>
731
732 {other.length ? (
733 <>
734 <h2>{waiting.length ? 'Everything else in this repo' : 'Skills in this repo'}</h2>
735 <table class="table admin-table">
736 <thead><tr><th>Skill</th><th>Folder</th><th>State</th><th>Note</th></tr></thead>
737 <tbody>
738 {other.map((i) => {
739 const st = stateOf(i);
740 return (
741 <tr>
742 <td>{i.slug && owner ? <a href={`/skills/${owner.handle}/${i.slug}`}>{i.title}</a> : i.path.split('/').pop() || imp.repo}</td>
743 <td class="mono">{i.path || '(repo root)'}</td>
744 <td><span class={`pill ${st.cls}`}>{st.label}</span></td>
745 <td>{i.decision_note ?? i.detail ?? ''}</td>
746 </tr>
747 );
748 })}
749 </tbody>
750 </table>
751 </>
752 ) : null}
753 </div>,
754 );
755 });
756
757 app.post('/admin/repo/:id/decide', async (c) => {
758 const a = admin(c);
759 const id = c.req.param('id');
760 const form = await c.req.parseBody();
761 try {
762 if (form.decision === 'reject') {
763 const note = String(form.note ?? '').trim().slice(0, 1000) || (DENY_REASONS[String(form.preset ?? '')] ?? DENY_REASONS.quality).text;
764 const n = await rejectRepo(c.env, a, id, note);
765 setFlash(c, 'ok', n ? `Rejected. ${plural(n, 'skill')} turned down and the member was sent the reason.` : 'Nothing in that repo was waiting.');
766 return c.redirect('/admin');
767 }
768 if (form.decision === 'approve') {
769 const res = await approveRepo(c.env, a, id);
770 const more = res.problems.length ? ` ${res.problems.join(' ')}` : res.left ? ` ${res.left} still waiting: press Approve all again.` : '';
771 setFlash(c, res.problems.length ? 'error' : 'ok', `Approved ${plural(res.approved, 'skill')}. The member was notified.${more}`);
772 return c.redirect(res.left ? `/admin/repo/${id}` : '/admin');
773 }
774 throw new HttpError(400, 'Pick approve or reject.');
775 } catch (e) {
776 if (!(e instanceof HttpError)) throw e;
777 setFlash(c, 'error', e.message);
778 return c.redirect(`/admin/repo/${id}`);
779 }
780 });
781
782 app.post('/admin/review/:id/rescan', async (c) => {
783 admin(c);
784 const id = c.req.param('id');
785 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();
786 const result = await runAiReview(c.env, id);
787 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.');
788 return c.redirect(`/admin/review/${id}`);
789 });
790
791 app.post('/admin/picks', async (c) => {
792 const a = admin(c);
793 const form = await c.req.parseBody({ all: true });
794 const str = (k: string) => (typeof form[k] === 'string' ? (form[k] as string) : '');
795 const platforms = ([] as unknown[]).concat(form.platforms ?? []).filter((x): x is string => typeof x === 'string');
796 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(',') };
797 try {
798 const pick = await savePick(c.env, a, {
799 id: str('id') || undefined, title: values.title, summary: values.summary, category: values.category, maker: values.maker, makerUrl: values.maker_url, sourceUrl: values.source_url,
800 repo: values.repo.replace(/^https:\/\/github\.com\//i, '').replace(/\/+$/, ''), path: values.path, license: values.license, installHint: values.install_hint, note: values.note, platforms,
801 });
802 setFlash(c, 'ok', str('id') ? `Saved "${pick.title}".` : `"${pick.title}" is live as one of Sprout's picks.`);
803 return c.redirect('/admin?tab=picks');
804 } catch (e) {
805 if (!(e instanceof HttpError)) throw e;
806 const editing = str('id') ? await getSkillCardById(c.env, str('id')) : null;
807 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);
808 }
809 });
810
811 app.post('/admin/skills/:id/:action', async (c) => {
812 const a = admin(c);
813 const skill = await getSkillCardById(c.env, c.req.param('id'));
814 if (!skill) throw new HttpError(404, 'Skill not found.');
815 const action = c.req.param('action');
816 if (action === 'category') {
817 const form = await c.req.parseBody();
818 await c.env.DB.prepare('UPDATE skills SET category = ? WHERE id = ?').bind(cleanCategory(form.category), skill.id).run();
819 } else if (action === 'feature') {
820 if (skill.kind === 'link') throw new HttpError(400, 'Fresh Harvest is for skills shared by growers.');
821 if (tierFor(skill.owner_seeds).threshold < TIERS[3].threshold) throw new HttpError(400, 'Fresh Harvest is for Harvester tier and up.');
822 await c.env.DB.prepare("UPDATE skills SET featured_at = ? WHERE id = ? AND state = 'live'").bind(now(), skill.id).run();
823 } else if (action === 'unfeature') await c.env.DB.prepare('UPDATE skills SET featured_at = NULL WHERE id = ?').bind(skill.id).run();
824 else if (action === 'offhome') await c.env.DB.prepare('UPDATE skills SET off_home = 1, featured_at = NULL WHERE id = ?').bind(skill.id).run();
825 else if (action === 'onhome') await c.env.DB.prepare('UPDATE skills SET off_home = 0 WHERE id = ?').bind(skill.id).run();
826 else if (action === 'hide') await setSkillState(c.env, a, skill, 'hidden');
827 else if (action === 'restore') await setSkillState(c.env, a, skill, 'live');
828 else if (action === 'remove') await setSkillState(c.env, a, skill, 'removed', 'Removed by a moderator.');
829 else throw new HttpError(404, 'Unknown action.');
830 setFlash(c, 'ok', 'Done.');
831 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'));
832 });
833
834 app.post('/admin/users/:id/:action', async (c) => {
835 const a = admin(c);
836 const target = await getUserById(c.env, c.req.param('id'));
837 if (!target) throw new HttpError(404, 'Member not found.');
838 const action = c.req.param('action');
839 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();
840 if (target.is_agent) throw new HttpError(400, 'Sprout is the site agent, not a member.');
841 if (action === 'ban') await banUser(c.env, a, target.id, '');
842 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'); }
843 else if (action === 'strike') { await c.env.DB.prepare('UPDATE users SET strikes = strikes + 1 WHERE id = ?').bind(target.id).run(); await log('strike'); }
844 else if (action === 'spotlight') {
845 if (target.seeds_total < TIERS[4].threshold) throw new HttpError(400, 'The spotlight is for Homesteader tier and up.');
846 await c.env.DB.prepare('UPDATE users SET spotlight_at = ? WHERE id = ?').bind(now(), target.id).run();
847 } else if (action === 'unspotlight') await c.env.DB.prepare('UPDATE users SET spotlight_at = NULL WHERE id = ?').bind(target.id).run();
848 else throw new HttpError(404, 'Unknown action.');
849 setFlash(c, 'ok', 'Done.');
850 return c.redirect('/admin?tab=members');
851 });
852
853 app.post('/admin/reports/:id/resolve', async (c) => {
854 const a = admin(c);
855 await c.env.DB.prepare('UPDATE reports SET resolved_at = ?, resolved_by = ? WHERE id = ?').bind(now(), a.id, c.req.param('id')).run();
856 setFlash(c, 'ok', 'Report resolved.');
857 return c.redirect('/admin?tab=reports');
858 });
859}