Branchwell

Skillfarm / website · skillfarm.ai / src / lib / skills.ts

Raw 45.8 KB on 947b01baffc181407e99132c54709fba5e84ae85
1import type { Env, User } from '../env';
2import { runAiReview } from './ai';
3import { mail } from './email';
4import { BUNDLE_LIMITS, isSafePath, isTextPath, refreshRepoSignals } from './github';
5import { parseSkillMd } from './markdown';
6import { grant, grantStatements, reverseSkillPoints } from './points';
7import { rateLimit } from './ratelimit';
8import { staticScan, type Finding } from './scan';
9import { LIMITS, SEEDS, tierFor } from './tiers';
10import { DAY, HttpError, hmacHex, likeEscape, newId, now, sha256Hex, slugify } from './util';
11
12export const PLATFORMS: { key: string; name: string }[] = [
13 { key: 'claude-code', name: 'Claude Code' },
14 { key: 'codex', name: 'Codex CLI' },
15 { key: 'gemini-cli', name: 'Gemini CLI' },
16];
17const PLATFORM_KEYS = new Set(PLATFORMS.map((p) => p.key));
18export const platformName = (key: string) => PLATFORMS.find((p) => p.key === key)?.name ?? key;
19export const splitPlatforms = (csv: string) => csv.split(',').filter((k) => PLATFORM_KEYS.has(k));
20
21export const CATEGORIES: { key: string; name: string }[] = [
22 { key: 'design', name: 'Design' },
23 { key: 'video', name: 'Video' },
24 { key: 'coding', name: 'Coding' },
25 { key: 'testing', name: 'Testing' },
26 { key: 'writing', name: 'Writing and marketing' },
27 { key: 'research', name: 'Data and research' },
28 { key: 'devops', name: 'Cloud and DevOps' },
29 { key: 'productivity', name: 'Productivity' },
30 { key: 'security', name: 'Security' },
31 { key: 'business', name: 'Commerce and sales' },
32 { key: 'finance', name: 'Finance' },
33 { key: 'legal', name: 'Legal' },
34 { key: 'science', name: 'Science and health' },
35 { key: 'education', name: 'Education' },
36];
37const CATEGORY_KEYS = new Set(CATEGORIES.map((c) => c.key));
38export const categoryName = (key: string | null) => CATEGORIES.find((c) => c.key === key)?.name ?? null;
39export const cleanCategory = (key: unknown) => (typeof key === 'string' && CATEGORY_KEYS.has(key) ? key : null);
40
41/** The account Sprout's picks belong to. Created by migration 0002. */
42export const SPROUT_ID = 'sprout00000agent';
43
44export type SkillRow = {
45 id: string; owner_id: string; slug: string; title: string; summary: string; platforms: string; github_repo: string | null; github_path: string | null;
46 github_ref: string | null; replanted_from_skill_id: string | null; verified_owner: number; state: string; current_version_id: string | null;
47 likes_count: number; installs_count: number; reviews_count: number; rating_sum: number; comments_count: number; featured_at: number | null; off_home: number; source: string;
48 created_at: number; updated_at: number; published_at: number | null;
49 /** "link" is a pick: a recommendation that points to the maker's repo. Skillfarm holds no files for it. */
50 kind: 'hosted' | 'link'; category: string | null; maker: string | null; maker_url: string | null; source_url: string | null; license: string | null;
51 install_hint: string | null; pick_note: string | null;
52 /** A converted copy of a pick that reads the same in every supported agent: the public repo and the folder inside it. */
53 multi_repo?: string | null; multi_path?: string | null;
54};
55export type SkillCard = SkillRow & {
56 owner_handle: string; owner_name: string; owner_avatar_key: string | null; owner_avatar_fallback: string | null; owner_seeds: number; owner_is_agent: number;
57 stars: number | null; repo_fetched_at: number | null; repo_unavailable: number | null; repo_license?: string | null; liked?: number | null;
58};
59export type VersionRow = {
60 id: string; skill_id: string; version: number; r2_prefix: string; sha256: string; size: number; manifest: string; title: string; summary: string; platforms: string;
61 status: string; scan_status: string; scan_report: string; ai_status: string; ai_recommendation: string | null; ai_summary: string | null; ai_report: string | null;
62 ai_attempts: number; decided_by: string | null; decided_at: number | null; decision_note: string | null; created_at: number;
63};
64export type ManifestEntry = { path: string; size: number; sha256: string };
65
66const CARD_FROM = `FROM skills s JOIN users u ON u.id = s.owner_id LEFT JOIN repo_signals r ON r.repo_full_name = s.github_repo`;
67const CARD_COLS = `s.*, u.handle AS owner_handle, u.display_name AS owner_name, u.avatar_key AS owner_avatar_key, u.avatar_fallback AS owner_avatar_fallback,
68 u.seeds_total AS owner_seeds, u.is_agent AS owner_is_agent, r.stars AS stars, r.fetched_at AS repo_fetched_at, r.unavailable AS repo_unavailable, r.license_spdx AS repo_license`;
69
70export type ListOpts = {
71 q?: string; platform?: string; category?: string; kind?: 'hosted' | 'link'; sort?: string; limit?: number; offset?: number; ownerId?: string; viewerId?: string | null;
72 featured?: boolean; states?: string[];
73 /** Leave out skills an admin has kept off the home page. */
74 home?: boolean;
75 /** Only skills shared by the member with this handle. */
76 ownerHandle?: string;
77 /** Words to look for in who made it: a pick's maker, the owner of the GitHub repo, or the member who shared it. */
78 maker?: string;
79 /** Only skills from this GitHub repo, as "owner/name". */
80 repo?: string;
81 /** Only skills under this licence, as an SPDX id such as "MIT". */
82 license?: string;
83};
84
85/** Up to six search words. Every word has to match somewhere, so "legal contract" finds a skill that mentions both. */
86function searchTerms(q: string): string[] {
87 return [...new Set(q.toLowerCase().slice(0, 80).split(/[\s,]+/).filter((t) => t.length > 0))].slice(0, 6);
88}
89
90export async function listSkills(env: Env, o: ListOpts): Promise<SkillCard[]> {
91 const where: string[] = [];
92 const args: unknown[] = [];
93 const liked = o.viewerId ? `, (SELECT 1 FROM likes l WHERE l.skill_id = s.id AND l.user_id = ? AND l.removed_at IS NULL) AS liked` : '';
94 if (o.viewerId) args.push(o.viewerId);
95 const states = o.states ?? ['live'];
96 where.push(`s.state IN (${states.map(() => '?').join(',')})`);
97 args.push(...states);
98 if (o.ownerId) { where.push('s.owner_id = ?'); args.push(o.ownerId); }
99 if (o.featured) where.push('s.featured_at IS NOT NULL');
100 if (o.home) where.push('s.off_home = 0');
101 if (o.category && CATEGORY_KEYS.has(o.category)) { where.push('s.category = ?'); args.push(o.category); }
102 if (o.kind === 'hosted' || o.kind === 'link') { where.push('s.kind = ?'); args.push(o.kind); }
103 if (o.platform && PLATFORM_KEYS.has(o.platform)) { where.push(`(',' || s.platforms || ',') LIKE ?`); args.push(`%,${o.platform},%`); }
104 if (o.ownerHandle) { where.push('u.handle = ?'); args.push(o.ownerHandle.toLowerCase().slice(0, 40)); }
105 if (o.repo) { where.push('LOWER(s.github_repo) = ?'); args.push(o.repo.toLowerCase().slice(0, 140)); }
106 if (o.license) { where.push('LOWER(COALESCE(s.license, r.license_spdx)) = ?'); args.push(o.license.toLowerCase().slice(0, 40)); }
107 if (o.maker) {
108 const like = `%${likeEscape(o.maker.slice(0, 60))}%`;
109 where.push(`(s.maker LIKE ? ESCAPE '\\' OR s.github_repo LIKE ? ESCAPE '\\' OR (s.kind = 'hosted' AND (u.handle LIKE ? ESCAPE '\\' OR u.display_name LIKE ? ESCAPE '\\')))`);
110 args.push(like, `${like}/%`, like, like);
111 }
112 for (const term of o.q ? searchTerms(o.q) : []) {
113 const like = `%${likeEscape(term)}%`;
114 const fields = ['s.title', 's.summary', 's.slug', 'u.handle', 'u.display_name', 's.github_repo', 's.maker', 's.platforms', 's.pick_note', 'COALESCE(s.license, r.license_spdx)'];
115 // A word that names a category ("legal", "marketing", "devops") matches everything filed under it.
116 const cats = CATEGORIES.filter((c) => c.key.includes(term) || c.name.toLowerCase().includes(term)).map((c) => c.key);
117 where.push(`(${fields.map((f) => `${f} LIKE ? ESCAPE '\\'`).join(' OR ')}${cats.length ? ` OR s.category IN (${cats.map(() => '?').join(',')})` : ''})`);
118 args.push(...fields.map(() => like), ...cats);
119 }
120 // Stars break ties, so a list of picks nobody has liked yet still has a sensible order. Before stars, a pick's place among the picks
121 // from the same repo: one repo with twenty picks then takes one slot per round instead of filling a page.
122 const repoRank = `(SELECT COUNT(*) FROM skills s3 WHERE s3.kind = 'link' AND s3.state = 'live' AND s3.github_repo = s.github_repo AND s3.published_at > s.published_at)`;
123 let order = 's.published_at DESC, COALESCE(r.stars, 0) DESC';
124 const ts = now();
125 if (o.featured) order = 's.featured_at DESC';
126 else if (o.sort === 'top') order = `s.likes_count DESC, s.installs_count DESC, ${repoRank} ASC, COALESCE(r.stars, 0) DESC, s.published_at DESC`;
127 else if (o.sort === 'trending') {
128 // A new skill from a member starts with a small score so it gets seen. A pick starts at zero and rises only on likes.
129 order = `((SELECT COUNT(*) FROM likes l2 WHERE l2.skill_id = s.id AND l2.removed_at IS NULL AND l2.created_at > ${ts - 7 * DAY}) * 3.0
130 + (SELECT COUNT(*) FROM installs i2 WHERE i2.skill_id = s.id AND i2.created_at > ${ts - 7 * DAY}) + CASE WHEN s.kind = 'link' THEN 0 ELSE 0.5 END)
131 / ((${ts} - COALESCE(s.published_at, s.created_at)) / 86400.0 + 2.0) DESC, ${repoRank} ASC, COALESCE(r.stars, 0) DESC, s.published_at DESC`;
132 } else if (o.sort === 'updated') order = 's.updated_at DESC';
133 args.push(Math.min(o.limit ?? 24, 400), o.offset ?? 0);
134 const res = await env.DB.prepare(`SELECT ${CARD_COLS}${liked} ${CARD_FROM} WHERE ${where.join(' AND ')} ORDER BY ${order} LIMIT ? OFFSET ?`).bind(...args).all<SkillCard>();
135 return res.results;
136}
137
138export async function getSkillCard(env: Env, handle: string, slug: string, viewerId?: string | null): Promise<SkillCard | null> {
139 const liked = viewerId ? `, (SELECT 1 FROM likes l WHERE l.skill_id = s.id AND l.user_id = ? AND l.removed_at IS NULL) AS liked` : '';
140 const args: unknown[] = viewerId ? [viewerId, handle, slug] : [handle, slug];
141 return env.DB.prepare(`SELECT ${CARD_COLS}${liked} ${CARD_FROM} WHERE u.handle = ? AND s.slug = ?`).bind(...args).first<SkillCard>();
142}
143
144export async function getSkillCardById(env: Env, id: string): Promise<SkillCard | null> {
145 return env.DB.prepare(`SELECT ${CARD_COLS} ${CARD_FROM} WHERE s.id = ?`).bind(id).first<SkillCard>();
146}
147
148/** A spread of Sprout's picks for the home page: one pick per repo, then the most-starred pick in each category first. */
149export async function sproutPicks(env: Env, limit: number, viewerId?: string | null): Promise<SkillCard[]> {
150 const liked = viewerId ? `, (SELECT 1 FROM likes l WHERE l.skill_id = s.id AND l.user_id = ? AND l.removed_at IS NULL) AS liked` : '';
151 const args: unknown[] = viewerId ? [viewerId, limit] : [limit];
152 const res = await env.DB.prepare(
153 `SELECT * FROM (
154 SELECT x.*, ROW_NUMBER() OVER (PARTITION BY x.category ORDER BY COALESCE(x.stars, 0) DESC, x.published_at DESC) AS cat_rank
155 FROM (
156 SELECT ${CARD_COLS}${liked}, ROW_NUMBER() OVER (PARTITION BY s.github_repo ORDER BY s.published_at DESC) AS repo_rank
157 ${CARD_FROM} WHERE s.state = 'live' AND s.kind = 'link' AND s.off_home = 0
158 ) x WHERE x.repo_rank = 1
159 ) ORDER BY cat_rank ASC, COALESCE(stars, 0) DESC LIMIT ?`,
160 ).bind(...args).all<SkillCard>();
161 return res.results;
162}
163
164/** How many live skills each category holds, for the filter chips. */
165export async function categoryCounts(env: Env): Promise<Record<string, number>> {
166 const res = await env.DB.prepare("SELECT category, COUNT(*) AS n FROM skills WHERE state = 'live' AND category IS NOT NULL GROUP BY category").all<{ category: string; n: number }>();
167 return Object.fromEntries(res.results.map((r) => [r.category, r.n]));
168}
169
170export function canView(skill: SkillRow, viewer: User | null): boolean {
171 if (skill.state === 'live') return true;
172 return !!viewer && (viewer.id === skill.owner_id || !!viewer.is_admin);
173}
174
175export async function getVersion(env: Env, id: string | null): Promise<VersionRow | null> {
176 if (!id) return null;
177 return env.DB.prepare('SELECT * FROM skill_versions WHERE id = ?').bind(id).first<VersionRow>();
178}
179
180export async function latestVersion(env: Env, skillId: string): Promise<VersionRow | null> {
181 return env.DB.prepare('SELECT * FROM skill_versions WHERE skill_id = ? ORDER BY version DESC LIMIT 1').bind(skillId).first<VersionRow>();
182}
183
184export async function readVersionFile(env: Env, v: VersionRow, path: string): Promise<Uint8Array | null> {
185 const manifest = JSON.parse(v.manifest) as ManifestEntry[];
186 if (!manifest.some((m) => m.path === path)) return null;
187 const obj = await env.SKILLS.get(v.r2_prefix + path);
188 return obj ? new Uint8Array(await obj.arrayBuffer()) : null;
189}
190
191export async function readVersionFiles(env: Env, v: VersionRow): Promise<{ path: string; data: Uint8Array }[]> {
192 const manifest = JSON.parse(v.manifest) as ManifestEntry[];
193 const out: { path: string; data: Uint8Array }[] = [];
194 for (const m of manifest) {
195 const obj = await env.SKILLS.get(v.r2_prefix + m.path);
196 if (obj) out.push({ path: m.path, data: new Uint8Array(await obj.arrayBuffer()) });
197 }
198 return out;
199}
200
201export type SubmitInput = {
202 user: User;
203 source: 'web' | 'mcp';
204 files: { path: string; data: Uint8Array }[];
205 title?: string;
206 summary?: string;
207 platforms?: string[];
208 category?: string | null;
209 github?: { repo: string; path: string; ref: string; ownerId: string };
210 replantedFrom?: SkillRow | null;
211 existing?: SkillRow | null;
212 /** Set when the skill comes in as part of a shared repo: the repo share sends one notice for all of them and has its own limits. */
213 partOfRepoShare?: boolean;
214};
215
216type Waiter = { waitUntil(p: Promise<unknown>): void };
217
218function isBinary(data: Uint8Array): boolean {
219 const n = Math.min(data.length, 8000);
220 for (let i = 0; i < n; i++) if (data[i] === 0) return true;
221 return false;
222}
223
224/** The file list of a bundle and the hash that identifies its exact contents. */
225export async function bundleManifest(files: { path: string; data: Uint8Array }[]): Promise<{ manifest: ManifestEntry[]; sha: string }> {
226 const manifest: ManifestEntry[] = [];
227 for (const f of files) manifest.push({ path: f.path, size: f.data.length, sha256: await sha256Hex(f.data) });
228 manifest.sort((a, b) => (a.path === 'SKILL.md' ? -1 : b.path === 'SKILL.md' ? 1 : a.path.localeCompare(b.path)));
229 return { manifest, sha: await sha256Hex(manifest.map((m) => `${m.path}\0${m.sha256}`).join('\n')) };
230}
231
232/** Validate, scan and store a submission. It always lands in the review queue; nothing goes public here. */
233export async function submitSkill(env: Env, ctx: Waiter, input: SubmitInput): Promise<{ skill: SkillRow; version: VersionRow; ownerHandle: string }> {
234 const { user } = input;
235 if (user.status !== 'active') throw new HttpError(403, 'This account cannot share skills.');
236 const files = input.files;
237 if (!files.length || files.length > BUNDLE_LIMITS.files) throw new HttpError(400, `A skill can hold up to ${BUNDLE_LIMITS.files} files.`);
238 const seen = new Set<string>();
239 let total = 0;
240 for (const f of files) {
241 if (!isSafePath(f.path) || !isTextPath(f.path)) throw new HttpError(400, `"${f.path}" is not an allowed file. Skills hold text files only.`);
242 if (seen.has(f.path.toLowerCase())) throw new HttpError(400, `"${f.path}" appears twice.`);
243 seen.add(f.path.toLowerCase());
244 if (f.data.length > BUNDLE_LIMITS.fileBytes) throw new HttpError(400, `"${f.path}" is larger than ${BUNDLE_LIMITS.fileBytes / 1000} KB.`);
245 if (isBinary(f.data)) throw new HttpError(400, `"${f.path}" looks like a binary file. Skills hold text files only.`);
246 total += f.data.length;
247 }
248 if (total > BUNDLE_LIMITS.totalBytes) throw new HttpError(400, `That skill is ${Math.round(total / 1000)} KB. The limit is ${BUNDLE_LIMITS.totalBytes / 1000} KB.`);
249 const entry = files.find((f) => f.path === 'SKILL.md');
250 if (!entry) throw new HttpError(400, 'A skill needs a SKILL.md file.');
251 const dec = new TextDecoder();
252 const skillMd = dec.decode(entry.data);
253 const { meta, body } = parseSkillMd(skillMd);
254 if (body.trim().length < 40) throw new HttpError(400, 'That SKILL.md is nearly empty. Add the instructions the agent should follow.');
255
256 const existing = input.existing ?? null;
257 // An update keeps the title the skill already has unless a new one is given.
258 const title = (input.title || existing?.title || titleFromName(meta.name ?? '')).trim().replace(/\s+/g, ' ').slice(0, 80);
259 if (title.length < 3) throw new HttpError(400, 'Give the skill a name: add `name:` to the SKILL.md header or fill in the title.');
260 const summary = clip(input.summary || meta.description || existing?.summary || '', 280);
261 if (summary.length < 12) throw new HttpError(400, 'Give the skill a short description: add `description:` to the SKILL.md header or fill in the summary.');
262 const platforms = [...new Set((input.platforms ?? (existing ? splitPlatforms(existing.platforms) : [])).filter((p) => PLATFORM_KEYS.has(p)))];
263 if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key));
264
265 const category = cleanCategory(input.category) ?? existing?.category ?? null;
266
267 const ts = now();
268 if (existing) {
269 if (existing.kind === 'link') throw new HttpError(400, 'A pick has no versions. It links to its maker.');
270 if (existing.owner_id !== user.id) throw new HttpError(403, 'Only the owner can update a skill.');
271 if (existing.state === 'removed') throw new HttpError(400, 'This skill was removed.');
272 if (!(await rateLimit(env, `version:${user.id}`, LIMITS.versionsPerDay, DAY))) throw new HttpError(429, 'You have submitted a lot of updates today. Try again tomorrow.');
273 } else if (!user.is_admin && !input.partOfRepoShare) {
274 const limit = tierFor(user.seeds_total).sharesPerWeek;
275 const recent = await env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE owner_id = ? AND created_at > ? AND state != 'removed'").bind(user.id, ts - 7 * DAY).first<{ n: number }>();
276 if ((recent?.n ?? 0) >= limit) throw new HttpError(429, `${tierFor(user.seeds_total).name}s can share ${limit} skills a week. The limit rises with your tier.`);
277 }
278
279 let slug = existing?.slug ?? slugify(meta.name || title);
280 if (slug.length < 2) throw new HttpError(400, 'That name does not make a usable link. Use letters or numbers.');
281 if (!existing) {
282 const clash = await env.DB.prepare('SELECT id, state FROM skills WHERE owner_id = ? AND slug = ?').bind(user.id, slug).first<{ id: string; state: string }>();
283 if (clash && clash.state !== 'removed') throw new HttpError(409, `You already have a skill called "${slug}". Open it and submit a new version instead.`);
284 if (clash) slug = `${slug}-${newId(4)}`;
285 }
286
287 // Scan.
288 const scan = staticScan(files.filter((f) => !isBinary(f.data)).map((f) => ({ path: f.path, text: dec.decode(f.data) })));
289 const { manifest, sha: bundleSha } = await bundleManifest(files);
290 const findings: Finding[] = scan.findings;
291 const twin = await env.DB.prepare(
292 `SELECT u.handle, s.slug FROM skill_versions v JOIN skills s ON s.id = v.skill_id JOIN users u ON u.id = s.owner_id
293 WHERE v.sha256 = ? AND s.owner_id != ? AND s.state = 'live' LIMIT 1`,
294 ).bind(bundleSha, user.id).first<{ handle: string; slug: string }>();
295 if (twin && !(input.replantedFrom)) {
296 findings.unshift({ severity: 'medium', rule: `Identical to the live skill ${twin.handle}/${twin.slug} by another member`, file: 'SKILL.md', line: 1, excerpt: '' });
297 }
298 const scanStatus = findings.some((f) => f.severity === 'high') ? 'high' : findings.length ? 'flagged' : 'clean';
299
300 const skillId = existing?.id ?? newId();
301 const versionId = newId();
302 const prefix = `skills/${skillId}/${versionId}/`;
303 for (const f of files) await env.SKILLS.put(prefix + f.path, f.data, { httpMetadata: { contentType: 'text/plain; charset=utf-8' } });
304
305 let verified = 0;
306 if (input.github) {
307 const gh = await env.DB.prepare("SELECT provider_user_id FROM oauth_accounts WHERE user_id = ? AND provider = 'github'").bind(user.id).first<{ provider_user_id: string }>();
308 verified = gh && gh.provider_user_id === input.github.ownerId ? 1 : 0;
309 }
310 const lastVersion = existing ? await env.DB.prepare('SELECT COALESCE(MAX(version), 0) AS v FROM skill_versions WHERE skill_id = ?').bind(skillId).first<{ v: number }>() : null;
311 const versionNo = (lastVersion?.v ?? 0) + 1;
312 const aiStatus = env.ANTHROPIC_API_KEY ? 'queued' : 'unavailable';
313 const stmts: D1PreparedStatement[] = [];
314 if (!existing) {
315 stmts.push(
316 env.DB.prepare(
317 `INSERT INTO skills (id, owner_id, slug, title, summary, platforms, category, github_repo, github_path, github_ref, replanted_from_skill_id, verified_owner, state, source, created_at, updated_at)
318 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'pending',?,?,?)`,
319 ).bind(skillId, user.id, slug, title, summary, platforms.join(','), category, input.github?.repo ?? null, input.github?.path ?? null, input.github?.ref ?? null, input.replantedFrom?.id ?? null, verified, input.source, ts, ts),
320 );
321 } else {
322 // A waiting version is replaced by the newer one; the live version stays up until a reviewer approves.
323 stmts.push(env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'pending'").bind(skillId));
324 if (existing.state === 'rejected') stmts.push(env.DB.prepare("UPDATE skills SET state = 'pending', updated_at = ? WHERE id = ?").bind(ts, skillId));
325 if (input.github) stmts.push(env.DB.prepare('UPDATE skills SET github_ref = ? WHERE id = ?').bind(input.github.ref, skillId));
326 if (category !== existing.category) stmts.push(env.DB.prepare('UPDATE skills SET category = ? WHERE id = ?').bind(category, skillId));
327 }
328 stmts.push(
329 env.DB.prepare(
330 `INSERT INTO skill_versions (id, skill_id, version, r2_prefix, sha256, size, manifest, title, summary, platforms, status, scan_status, scan_report, ai_status, created_at)
331 VALUES (?,?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)`,
332 ).bind(versionId, skillId, versionNo, prefix, bundleSha, total, JSON.stringify(manifest), title, summary, platforms.join(','), scanStatus, JSON.stringify(findings), aiStatus, ts),
333 );
334 await env.DB.batch(stmts);
335
336 const skill = (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(skillId).first<SkillRow>())!;
337 const version = (await getVersion(env, versionId))!;
338 const url = `${env.SITE_URL}/skills/${user.handle}/${skill.slug}`;
339 ctx.waitUntil(
340 (async () => {
341 if (!input.partOfRepoShare) await mail.received(env, user, title, url);
342 if (aiStatus === 'unavailable' && !input.partOfRepoShare) await mail.adminReview(env, title, user.handle, 'unavailable', 'AI review is not configured, so this one needs a manual read.');
343 })().catch((e) => console.error('submit notices failed', e)),
344 );
345 return { skill, version, ownerHandle: user.handle };
346}
347
348const SHOUT = new Set(['mcp', 'api', 'cli', 'pdf', 'ui', 'ux', 'ci', 'sql', 'css', 'html', 'ai', 'seo', 'pr', 'json', 'csv', 'sdk', 'url', 'ssh']);
349
350/** "agent-council" reads better as "Agent Council" on a card. A name that already has capitals or spaces is left alone. */
351export function titleFromName(name: string): string {
352 const s = name.trim().replace(/\s+/g, ' ');
353 if (!/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(s)) return s;
354 return s.split(/[-_]/).map((w) => (SHOUT.has(w) ? w.toUpperCase() : w[0].toUpperCase() + w.slice(1))).join(' ');
355}
356
357/** Shorten a long description at the end of a sentence, or failing that a word. Never mid-word. */
358export function clip(text: string, max: number): string {
359 const s = text.trim().replace(/\s+/g, ' ');
360 if (s.length <= max) return s;
361 const head = s.slice(0, max);
362 const stop = Math.max(head.lastIndexOf('. '), head.lastIndexOf('! '), head.lastIndexOf('? '));
363 if (stop >= 60) return head.slice(0, stop + 1);
364 const cut = head.lastIndexOf(' ');
365 return (cut > 0 ? head.slice(0, cut) : head.slice(0, max - 1)).replace(/[,;:.\s]+$/, '') + '…';
366}
367
368export type PickInput = {
369 id?: string; title: string; summary: string; category: string; maker: string; makerUrl: string; sourceUrl: string; repo: string; path?: string; license?: string;
370 installHint?: string; note?: string; platforms?: string[];
371};
372
373/**
374 * Add or edit one of Sprout's picks. Only a moderator can do this, and doing it is the moderator's decision to publish:
375 * a pick goes live at once because there is no submitted file to review, only a link the moderator has chosen.
376 */
377export async function savePick(env: Env, admin: User, input: PickInput): Promise<SkillRow> {
378 if (!admin.is_admin) throw new HttpError(403, 'Moderators only.');
379 const one = (v: string | undefined, max: number) => (v ?? '').trim().replace(/\s+/g, ' ').slice(0, max);
380 const title = one(input.title, 80);
381 const summary = one(input.summary, 280);
382 const maker = one(input.maker, 80);
383 const category = cleanCategory(input.category);
384 const repo = one(input.repo, 140);
385 const https = (v: string | undefined) => {
386 const t = (v ?? '').trim();
387 if (!t) return null;
388 let u: URL;
389 try { u = new URL(t); } catch { throw new HttpError(400, `"${t.slice(0, 80)}" is not a web address.`); }
390 if (u.protocol !== 'https:') throw new HttpError(400, 'Links must start with https://.');
391 return u.toString();
392 };
393 if (title.length < 2) throw new HttpError(400, 'Give the pick a title.');
394 if (summary.length < 12) throw new HttpError(400, 'Say what the skill does in a sentence.');
395 if (!maker) throw new HttpError(400, 'Name the maker. Picks always credit who made the skill.');
396 if (!category) throw new HttpError(400, 'Pick a category.');
397 if (!/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/.test(repo)) throw new HttpError(400, 'Give the GitHub repo as owner/name.');
398 const path = (input.path ?? '').trim().replace(/^\/+|\/+$/g, '').slice(0, 200) || null;
399 const sourceUrl = https(input.sourceUrl) ?? `https://github.com/${repo}${path ? `/tree/HEAD/${path}` : ''}`;
400 const makerUrl = https(input.makerUrl) ?? `https://github.com/${repo.split('/')[0]}`;
401 const platforms = [...new Set((input.platforms ?? []).filter((p) => PLATFORM_KEYS.has(p)))];
402 if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key));
403 const license = one(input.license, 60) || null;
404 const hint = (input.installHint ?? '').trim().slice(0, 400) || null;
405 const note = one(input.note, 600) || null;
406 const sprout = await env.DB.prepare('SELECT id FROM users WHERE id = ? AND is_agent = 1').bind(SPROUT_ID).first();
407 if (!sprout) throw new HttpError(503, 'The Sprout account is missing. Apply the database migrations.');
408 const ts = now();
409 let id = input.id ?? '';
410 if (id) {
411 const cur = await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(id).first<SkillRow>();
412 if (!cur || cur.kind !== 'link') throw new HttpError(404, 'That pick was not found.');
413 await env.DB.batch([
414 env.DB.prepare(
415 `UPDATE skills SET title = ?, summary = ?, platforms = ?, category = ?, maker = ?, maker_url = ?, source_url = ?, github_repo = ?, github_path = ?, license = ?, install_hint = ?, pick_note = ?, updated_at = ? WHERE id = ?`,
416 ).bind(title, summary, platforms.join(','), category, maker, makerUrl, sourceUrl, repo, path, license, hint, note, ts, id),
417 env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'pick_edit', 'skill', id, null, ts),
418 ]);
419 } else {
420 id = newId();
421 let slug = slugify(title);
422 if (slug.length < 2) throw new HttpError(400, 'That title does not make a usable link. Use letters or numbers.');
423 const clash = await env.DB.prepare('SELECT id FROM skills WHERE owner_id = ? AND slug = ?').bind(SPROUT_ID, slug).first();
424 if (clash) slug = `${slug}-${newId(4)}`;
425 await env.DB.batch([
426 env.DB.prepare(
427 `INSERT INTO skills (id, owner_id, slug, title, summary, platforms, category, kind, maker, maker_url, source_url, github_repo, github_path, license, install_hint, pick_note, state, source, created_at, updated_at, published_at)
428 VALUES (?,?,?,?,?,?,?,'link',?,?,?,?,?,?,?,?,'live','pick',?,?,?)`,
429 ).bind(id, SPROUT_ID, slug, title, summary, platforms.join(','), category, maker, makerUrl, sourceUrl, repo, path, license, hint, note, ts, ts, ts),
430 env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'pick', 'skill', id, null, ts),
431 ]);
432 }
433 await refreshRepoSignals(env, repo).catch(() => {});
434 return (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(id).first<SkillRow>())!;
435}
436
437/** A moderator's decision on a waiting version. Apart from a moderator's own picks (savePick), this is the only path to "live". */
438export async function decideVersion(
439 env: Env, admin: User, versionId: string, decision: 'approve' | 'reject', note: string,
440 opts: { category?: string | null; silent?: boolean } = {},
441): Promise<SkillRow> {
442 if (!admin.is_admin) throw new HttpError(403, 'Moderators only.');
443 const v = await getVersion(env, versionId);
444 if (!v) throw new HttpError(404, 'That submission was not found.');
445 if (v.status !== 'pending') throw new HttpError(409, 'That submission was already decided.');
446 const skill = (await env.DB.prepare('SELECT * FROM skills WHERE id = ?').bind(v.skill_id).first<SkillRow>())!;
447 const owner = (await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(skill.owner_id).first<User>())!;
448 const ts = now();
449 const url = `${env.SITE_URL}/skills/${owner.handle}/${skill.slug}`;
450 const log = env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, decision, 'version', v.id, note || null, ts);
451
452 if (decision === 'reject') {
453 const stmts = [
454 env.DB.prepare("UPDATE skill_versions SET status = 'rejected', decided_by = ?, decided_at = ?, decision_note = ? WHERE id = ?").bind(admin.id, ts, note || null, v.id),
455 log,
456 ];
457 if (!skill.current_version_id) stmts.push(env.DB.prepare("UPDATE skills SET state = 'rejected', updated_at = ? WHERE id = ?").bind(ts, skill.id));
458 await env.DB.batch(stmts);
459 if (!opts.silent) await mail.denied(env, owner, v.title, url, note);
460 return { ...skill, state: skill.current_version_id ? skill.state : 'rejected' };
461 }
462
463 if (owner.status !== 'active') throw new HttpError(409, 'The owner of this skill is banned.');
464 const first = !skill.published_at;
465 await env.DB.batch([
466 env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'approved'").bind(skill.id),
467 env.DB.prepare("UPDATE skill_versions SET status = 'approved', decided_by = ?, decided_at = ?, decision_note = ? WHERE id = ?").bind(admin.id, ts, note || null, v.id),
468 env.DB.prepare(
469 `UPDATE skills SET state = CASE WHEN state IN ('pending','rejected') THEN 'live' ELSE state END, current_version_id = ?, title = ?, summary = ?, platforms = ?,
470 category = COALESCE(?, category), updated_at = ?, published_at = COALESCE(published_at, ?) WHERE id = ?`,
471 ).bind(v.id, v.title, v.summary, v.platforms, cleanCategory(opts.category), ts, ts, skill.id),
472 log,
473 ]);
474 if (first) {
475 // Share Seeds are granted once per skill, only after approval. New versions earn nothing.
476 await grant(env, { userId: owner.id, kind: 'share', amount: SEEDS.share, sourceType: 'skill', sourceId: skill.id, skillId: skill.id });
477 if (skill.replanted_from_skill_id) {
478 const parent = await env.DB.prepare('SELECT owner_id, state FROM skills WHERE id = ?').bind(skill.replanted_from_skill_id).first<{ owner_id: string; state: string }>();
479 if (parent && parent.owner_id !== owner.id) {
480 await grant(env, { userId: parent.owner_id, kind: 'replant', amount: SEEDS.replant, sourceType: 'skill', sourceId: skill.id, skillId: skill.id });
481 }
482 }
483 }
484 if (skill.github_repo) await refreshRepoSignals(env, skill.github_repo).catch(() => {});
485 if (!opts.silent) await mail.approved(env, owner, v.title, url, first ? SEEDS.share : 0);
486 return { ...skill, state: 'live', current_version_id: v.id };
487}
488
489export async function setSkillState(env: Env, actor: User, skill: SkillRow, state: 'removed' | 'hidden' | 'live', note = ''): Promise<void> {
490 const isOwner = actor.id === skill.owner_id;
491 if (!actor.is_admin && !(isOwner && state === 'removed')) throw new HttpError(403, 'Not allowed.');
492 if (state === 'live' && !skill.current_version_id && skill.kind !== 'link') throw new HttpError(409, 'This skill has no approved version.');
493 const ts = now();
494 await env.DB.batch([
495 env.DB.prepare('UPDATE skills SET state = ?, featured_at = CASE WHEN ? = \'live\' THEN featured_at ELSE NULL END, updated_at = ? WHERE id = ?').bind(state, state, ts, skill.id),
496 env.DB.prepare("UPDATE skill_versions SET status = 'superseded' WHERE skill_id = ? AND status = 'pending' AND ? = 'removed'").bind(skill.id, state),
497 env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), actor.id, state === 'live' ? 'restore' : state, 'skill', skill.id, note || null, ts),
498 ]);
499 if (state === 'removed') {
500 await reverseSkillPoints(env, skill.id);
501 if (!isOwner) {
502 const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(skill.owner_id).first<User>();
503 if (owner) await mail.removed(env, owner, skill.title, note);
504 }
505 }
506}
507
508function oldEnough(user: User): boolean {
509 return user.created_at <= now() - LIMITS.minAccountAgeDays * DAY;
510}
511
512export async function likeSkill(env: Env, user: User, skill: SkillRow): Promise<{ liked: boolean; likes: number }> {
513 if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.');
514 if (skill.owner_id === user.id) throw new HttpError(400, 'You cannot like your own skill.');
515 if (!(await rateLimit(env, `like:${user.id}`, LIMITS.likeActionsPerHour, 3600))) throw new HttpError(429, 'Slow down a little. Try again in an hour.');
516 const id = newId();
517 const ts = now();
518 const res = await env.DB.batch([
519 env.DB.prepare('INSERT OR IGNORE INTO likes (id, skill_id, user_id, created_at) VALUES (?,?,?,?)').bind(id, skill.id, user.id, ts),
520 env.DB.prepare('UPDATE skills SET likes_count = (SELECT COUNT(*) FROM likes WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(skill.id),
521 ]);
522 const inserted = (res[0].meta.changes ?? 0) > 0;
523 // Likes on a pick are counted but pay nobody: Sprout earns no Seeds, and the maker is not a member here.
524 if (inserted && skill.kind !== 'link' && oldEnough(user) && user.email) {
525 const dayStart = ts - (ts % DAY);
526 const today = await env.DB.prepare("SELECT COUNT(*) AS n FROM point_events WHERE skill_id = ? AND kind = 'like' AND created_at >= ?").bind(skill.id, dayStart).first<{ n: number }>();
527 if ((today?.n ?? 0) < LIMITS.likeSeedsPerSkillPerDay) {
528 await grant(env, { userId: skill.owner_id, kind: 'like', amount: SEEDS.like, sourceType: 'like', sourceId: id, skillId: skill.id });
529 }
530 }
531 const row = await env.DB.prepare('SELECT likes_count FROM skills WHERE id = ?').bind(skill.id).first<{ likes_count: number }>();
532 return { liked: true, likes: row?.likes_count ?? 0 };
533}
534
535export async function unlikeSkill(env: Env, user: User, skill: SkillRow): Promise<{ liked: boolean; likes: number }> {
536 if (!(await rateLimit(env, `like:${user.id}`, LIMITS.likeActionsPerHour, 3600))) throw new HttpError(429, 'Slow down a little. Try again in an hour.');
537 const like = await env.DB.prepare('SELECT id FROM likes WHERE skill_id = ? AND user_id = ? AND removed_at IS NULL').bind(skill.id, user.id).first<{ id: string }>();
538 if (like) await removeLike(env, like.id, skill.id, skill.owner_id);
539 const row = await env.DB.prepare('SELECT likes_count FROM skills WHERE id = ?').bind(skill.id).first<{ likes_count: number }>();
540 return { liked: false, likes: row?.likes_count ?? 0 };
541}
542
543async function removeLike(env: Env, likeId: string, skillId: string, ownerId: string): Promise<void> {
544 const stmts = [
545 env.DB.prepare('UPDATE likes SET removed_at = ? WHERE id = ? AND removed_at IS NULL').bind(now(), likeId),
546 env.DB.prepare('UPDATE skills SET likes_count = (SELECT COUNT(*) FROM likes WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(skillId),
547 ];
548 const paid = await env.DB.prepare("SELECT 1 AS x FROM point_events WHERE kind = 'like' AND source_id = ?").bind(likeId).first();
549 if (paid) stmts.push(...grantStatements(env, { userId: ownerId, kind: 'like_reversal', amount: -SEEDS.like, sourceType: 'like', sourceId: likeId, skillId }));
550 await env.DB.batch(stmts);
551}
552
553export async function addReview(env: Env, user: User, skill: SkillRow, rating: number, body: string): Promise<void> {
554 if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.');
555 if (skill.owner_id === user.id) throw new HttpError(400, 'You cannot review your own skill.');
556 if (skill.kind === 'link') throw new HttpError(400, 'Picks link to their maker and do not take reviews here.');
557 if (!oldEnough(user)) throw new HttpError(403, `Reviews open up once your account is ${LIMITS.minAccountAgeDays} days old.`);
558 const text = body.trim();
559 if (text.length < LIMITS.minReviewLength) throw new HttpError(400, `Write at least ${LIMITS.minReviewLength} characters so the review is useful.`);
560 if (text.length > 2000) throw new HttpError(400, 'Keep reviews under 2,000 characters.');
561 if (!(rating >= 1 && rating <= 5)) throw new HttpError(400, 'Pick a rating from 1 to 5.');
562 const prior = await env.DB.prepare('SELECT id FROM reviews WHERE skill_id = ? AND user_id = ?').bind(skill.id, user.id).first();
563 if (prior) throw new HttpError(409, 'You already reviewed this skill.');
564 if (!(await rateLimit(env, `review:${user.id}`, LIMITS.reviewsPerDay, DAY))) throw new HttpError(429, 'That is a lot of reviews for one day. Try again tomorrow.');
565 const id = newId();
566 await env.DB.batch([
567 env.DB.prepare('INSERT INTO reviews (id, skill_id, user_id, rating, body, created_at) VALUES (?,?,?,?,?,?)').bind(id, skill.id, user.id, Math.round(rating), text, now()),
568 env.DB.prepare('UPDATE skills SET reviews_count = reviews_count + 1, rating_sum = rating_sum + ? WHERE id = ?').bind(Math.round(rating), skill.id),
569 ]);
570 await grant(env, { userId: user.id, kind: 'review', amount: SEEDS.review, sourceType: 'review', sourceId: id, skillId: null });
571}
572
573export async function removeReview(env: Env, actor: User, reviewId: string): Promise<void> {
574 const r = await env.DB.prepare('SELECT * FROM reviews WHERE id = ? AND removed_at IS NULL').bind(reviewId).first<{ id: string; skill_id: string; user_id: string; rating: number }>();
575 if (!r) throw new HttpError(404, 'That review was not found.');
576 if (!actor.is_admin && actor.id !== r.user_id) throw new HttpError(403, 'Not allowed.');
577 await env.DB.batch([
578 env.DB.prepare('UPDATE reviews SET removed_at = ? WHERE id = ?').bind(now(), r.id),
579 env.DB.prepare('UPDATE skills SET reviews_count = MAX(0, reviews_count - 1), rating_sum = MAX(0, rating_sum - ?) WHERE id = ?').bind(r.rating, r.skill_id),
580 ...grantStatements(env, { userId: r.user_id, kind: 'review_reversal', amount: -SEEDS.review, sourceType: 'review', sourceId: r.id }),
581 ]);
582}
583
584/** Count one install per installer per skill. Anonymous installers are a salted hash, never a stored IP. */
585export async function recordInstall(env: Env, skill: SkillRow, viewer: User | null, ip: string, ua: string): Promise<void> {
586 if (skill.state !== 'live' || skill.kind === 'link') return;
587 const key = viewer ? `u:${viewer.id}` : `a:${(await hmacHex(env.SESSION_SECRET ?? 'skillfarm', `${ip}|${ua}`)).slice(0, 32)}`;
588 if (viewer?.id === skill.owner_id) return;
589 const id = newId();
590 const ts = now();
591 const res = await env.DB.batch([
592 env.DB.prepare('INSERT OR IGNORE INTO installs (id, skill_id, installer_key, user_id, created_at) VALUES (?,?,?,?,?)').bind(id, skill.id, key, viewer?.id ?? null, ts),
593 env.DB.prepare('UPDATE skills SET installs_count = (SELECT COUNT(*) FROM installs WHERE skill_id = ?1) WHERE id = ?1').bind(skill.id),
594 ]);
595 if ((res[0].meta.changes ?? 0) === 0) return;
596 const dayStart = ts - (ts % DAY);
597 const today = await env.DB.prepare("SELECT COUNT(*) AS n FROM point_events WHERE skill_id = ? AND kind = 'install' AND created_at >= ?").bind(skill.id, dayStart).first<{ n: number }>();
598 if ((today?.n ?? 0) < LIMITS.installSeedsPerSkillPerDay) {
599 await grant(env, { userId: skill.owner_id, kind: 'install', amount: SEEDS.install, sourceType: 'install', sourceId: id, skillId: skill.id });
600 }
601}
602
603export type CommentRow = {
604 id: string; skill_id: string; user_id: string; body: string; created_at: number;
605 handle: string; display_name: string; avatar_key: string | null; avatar_fallback: string | null; seeds_total: number; is_agent: number;
606};
607
608export const COMMENT_LIMITS = { min: 2, max: 1000, perDay: 40, perMinute: 4 };
609
610export async function listComments(env: Env, skillId: string, limit = 100): Promise<CommentRow[]> {
611 const res = await env.DB.prepare(
612 `SELECT c.id, c.skill_id, c.user_id, c.body, c.created_at, u.handle, u.display_name, u.avatar_key, u.avatar_fallback, u.seeds_total, u.is_agent
613 FROM comments c JOIN users u ON u.id = c.user_id WHERE c.skill_id = ? AND c.removed_at IS NULL AND u.status = 'active' ORDER BY c.created_at ASC LIMIT ?`,
614 ).bind(skillId, limit).all<CommentRow>();
615 return res.results;
616}
617
618/** A comment is plain text from a signed-in member on a live skill. It shows at once; the author or a moderator can remove it. */
619export async function addComment(env: Env, user: User, skill: SkillRow, body: string): Promise<string> {
620 if (user.status !== 'active') throw new HttpError(403, 'This account cannot comment.');
621 if (skill.state !== 'live') throw new HttpError(404, 'That skill is not live.');
622 const text = body.replace(/\r\n/g, '\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim();
623 if (text.length < COMMENT_LIMITS.min) throw new HttpError(400, 'Write a comment first.');
624 if (text.length > COMMENT_LIMITS.max) throw new HttpError(400, `Keep comments under ${COMMENT_LIMITS.max.toLocaleString('en-US')} characters.`);
625 if (!(await rateLimit(env, `comment-fast:${user.id}`, COMMENT_LIMITS.perMinute, 60))) throw new HttpError(429, 'Slow down a little. Try again in a minute.');
626 if (!(await rateLimit(env, `comment:${user.id}`, COMMENT_LIMITS.perDay, DAY))) throw new HttpError(429, 'That is a lot of comments for one day. Try again tomorrow.');
627 const same = await env.DB.prepare('SELECT 1 AS x FROM comments WHERE skill_id = ? AND user_id = ? AND body = ? AND removed_at IS NULL').bind(skill.id, user.id, text).first();
628 if (same) throw new HttpError(409, 'You already posted that comment.');
629 const id = newId();
630 await env.DB.batch([
631 env.DB.prepare('INSERT INTO comments (id, skill_id, user_id, body, created_at) VALUES (?,?,?,?,?)').bind(id, skill.id, user.id, text, now()),
632 env.DB.prepare('UPDATE skills SET comments_count = (SELECT COUNT(*) FROM comments WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(skill.id),
633 ]);
634 return id;
635}
636
637export async function removeComment(env: Env, actor: User, commentId: string): Promise<void> {
638 const row = await env.DB.prepare('SELECT id, skill_id, user_id FROM comments WHERE id = ? AND removed_at IS NULL').bind(commentId).first<{ id: string; skill_id: string; user_id: string }>();
639 if (!row) throw new HttpError(404, 'That comment was not found.');
640 if (!actor.is_admin && actor.id !== row.user_id) throw new HttpError(403, 'Not allowed.');
641 const ts = now();
642 const stmts = [
643 env.DB.prepare('UPDATE comments SET removed_at = ?, removed_by = ? WHERE id = ?').bind(ts, actor.id, row.id),
644 env.DB.prepare('UPDATE skills SET comments_count = (SELECT COUNT(*) FROM comments WHERE skill_id = ?1 AND removed_at IS NULL) WHERE id = ?1').bind(row.skill_id),
645 ];
646 if (actor.id !== row.user_id) stmts.push(env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), actor.id, 'comment_remove', 'comment', row.id, null, ts));
647 await env.DB.batch(stmts);
648}
649
650export async function fileReport(env: Env, user: User, targetType: string, targetId: string, reason: string): Promise<void> {
651 if (!['skill', 'review', 'user', 'comment'].includes(targetType)) throw new HttpError(400, 'Unknown report target.');
652 const text = reason.trim().slice(0, 1000);
653 if (text.length < 10) throw new HttpError(400, 'Say what is wrong in a sentence or two.');
654 if (!(await rateLimit(env, `report:${user.id}`, LIMITS.reportsPerDay, DAY))) throw new HttpError(429, 'You have filed a lot of reports today.');
655 await env.DB.prepare('INSERT INTO reports (id, reporter_id, target_type, target_id, reason, created_at) VALUES (?,?,?,?,?,?)').bind(newId(), user.id, targetType, targetId, text, now()).run();
656}
657
658/** Ban a member: sign them out everywhere, hide their skills, and reverse the Seeds their likes gave. */
659export async function banUser(env: Env, admin: User, targetId: string, note: string): Promise<void> {
660 if (!admin.is_admin) throw new HttpError(403, 'Moderators only.');
661 const target = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(targetId).first<User>();
662 if (!target) throw new HttpError(404, 'Member not found.');
663 if (target.is_admin) throw new HttpError(400, 'Admins cannot be banned here.');
664 const ts = now();
665 await env.DB.batch([
666 env.DB.prepare("UPDATE users SET status = 'banned', spotlight_at = NULL WHERE id = ?").bind(targetId),
667 env.DB.prepare('DELETE FROM sessions WHERE user_id = ?').bind(targetId),
668 env.DB.prepare('UPDATE api_tokens SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL').bind(ts, targetId),
669 env.DB.prepare("UPDATE skills SET state = 'hidden', featured_at = NULL WHERE owner_id = ? AND state = 'live'").bind(targetId),
670 env.DB.prepare("UPDATE skill_versions SET status = 'rejected', decided_by = ?, decided_at = ?, decision_note = 'Account banned' WHERE status = 'pending' AND skill_id IN (SELECT id FROM skills WHERE owner_id = ?)").bind(admin.id, ts, targetId),
671 env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'ban', 'user', targetId, note || null, ts),
672 ]);
673 const likes = await env.DB.prepare('SELECT l.id, l.skill_id, s.owner_id FROM likes l JOIN skills s ON s.id = l.skill_id WHERE l.user_id = ? AND l.removed_at IS NULL LIMIT 500').bind(targetId).all<{ id: string; skill_id: string; owner_id: string }>();
674 for (const l of likes.results) await removeLike(env, l.id, l.skill_id, l.owner_id);
675}
676
677export { runAiReview };