Branchwell

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

Raw 16.2 KB on ca5271886e6deb70a55372acda5d273e29b90b31
1import type { Env, User } from '../env';
2import { mail } from './email';
3import { fetchSkillFiles, parseGithubUrl, REPO_SKILL_LIMIT, scanRepo, type TreeFile } from './github';
4import { rateLimit } from './ratelimit';
5import { bundleManifest, decideVersion, latestVersion, PLATFORMS, submitSkill, type SkillRow } from './skills';
6import { SEEDS } from './tiers';
7import { DAY, HttpError, newId, now } from './util';
8
9/**
10 * A repo share: a member hands over a public GitHub repo, Skillfarm finds every skill folder in it and puts each one in the
11 * review queue. Reading the repo is split into small steps, one skill per step, so a large repo never has to fit in one request.
12 */
13
14export type ImportRow = {
15 id: string; user_id: string; repo: string; ref: string; repo_owner_id: string; platforms: string; source: 'web' | 'mcp';
16 status: 'reading' | 'review' | 'decided'; found: number; decision_note: string | null; decided_by: string | null; decided_at: number | null;
17 created_at: number; finished_at: number | null;
18};
19export type ImportItem = {
20 id: string; import_id: string; path: string; files: string; status: 'queued' | 'working' | 'submitted' | 'updated' | 'unchanged' | 'skipped' | 'failed';
21 detail: string | null; skill_id: string | null; version_id: string | null; started_at: number | null; created_at: number;
22};
23/** An item joined with the skill and version it became, for the member's page and the moderator's card. */
24export type ImportItemView = ImportItem & {
25 slug: string | null; title: string | null; summary: string | null; skill_state: string | null; category: string | null;
26 version_status: string | null; version: number | null; scan_status: string | null; ai_status: string | null; ai_recommendation: string | null; ai_summary: string | null;
27 ai_report: string | null; decision_note: string | null;
28};
29
30export const IMPORT_LIMITS = { sharesPerDay: 4, waitingSkills: 40 };
31type Waiter = { waitUntil(p: Promise<unknown>): void };
32
33export async function getImport(env: Env, id: string): Promise<ImportRow | null> {
34 return env.DB.prepare('SELECT * FROM repo_imports WHERE id = ?').bind(id).first<ImportRow>();
35}
36
37export async function importItems(env: Env, importId: string): Promise<ImportItemView[]> {
38 const res = await env.DB.prepare(
39 `SELECT i.*, s.slug, COALESCE(v.title, s.title) AS title, COALESCE(v.summary, s.summary) AS summary, s.state AS skill_state, s.category,
40 v.status AS version_status, v.version, v.scan_status, v.ai_status, v.ai_recommendation, v.ai_summary, v.ai_report, v.decision_note
41 FROM repo_import_items i LEFT JOIN skills s ON s.id = i.skill_id LEFT JOIN skill_versions v ON v.id = i.version_id
42 WHERE i.import_id = ? ORDER BY i.path ASC`,
43 ).bind(importId).all<ImportItemView>();
44 return res.results;
45}
46
47/** Read the repo's file list, find its skills and queue one step per skill. Nothing is downloaded or submitted yet. */
48export async function startRepoShare(env: Env, input: { user: User; source: 'web' | 'mcp'; url: string; platforms?: string[] }): Promise<ImportRow> {
49 const { user } = input;
50 if (user.status !== 'active') throw new HttpError(403, 'This account cannot share skills.');
51 const ref = parseGithubUrl(input.url);
52 if (!ref) throw new HttpError(400, 'That does not look like a repo. Paste the full address of your public repo.');
53 const repoKey = `${ref.owner}/${ref.repo}`.toLowerCase();
54
55 const open = await env.DB.prepare(
56 `SELECT m.id, m.status FROM repo_imports m WHERE m.user_id = ? AND LOWER(m.repo) = ? AND (m.status = 'reading' OR (m.status = 'review' AND EXISTS (
57 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')))
58 ORDER BY m.created_at DESC LIMIT 1`,
59 ).bind(user.id, repoKey).first<{ id: string; status: string }>();
60 if (open) throw new HttpError(409, 'You already shared this repo and it is waiting for review. You will get an email with the decision.', `open:${open.id}`);
61
62 const scan = await scanRepo(env, ref);
63 if (scan.truncated) throw new HttpError(400, `${scan.repo} is too large for Skillfarm to read in one go. Add the folder that holds your skills to the link, for example ${scan.repo}/tree/${scan.info.default_branch}/skills.`);
64 if (!scan.folders.length) throw new HttpError(400, `No SKILL.md was found${ref.path ? ` under "${ref.path}"` : ''} in ${scan.repo}. Each skill needs its own folder with a SKILL.md file in it.`);
65 if (scan.folders.length > REPO_SKILL_LIMIT) {
66 throw new HttpError(400, `${scan.repo} holds ${scan.folders.length} skills. Skillfarm takes up to ${REPO_SKILL_LIMIT} at a time. Add a folder to the link to share part of it, for example ${scan.repo}/tree/${scan.info.default_branch}/${scan.folders[0].path.split('/').slice(0, -1).join('/') || scan.folders[0].path}.`);
67 }
68 const waiting = await env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE owner_id = ? AND state = 'pending'").bind(user.id).first<{ n: number }>();
69 if (!user.is_admin && (waiting?.n ?? 0) + scan.folders.length > IMPORT_LIMITS.waitingSkills) throw new HttpError(429, `You have ${waiting?.n ?? 0} skills waiting for review already. Wait for those decisions before you share more.`);
70
71 if (!user.is_admin && !(await rateLimit(env, `repo-share:${user.id}`, IMPORT_LIMITS.sharesPerDay, DAY))) throw new HttpError(429, 'You have shared a few repos today. Try again tomorrow.');
72
73 const keys = new Set(PLATFORMS.map((p) => p.key));
74 const platforms = [...new Set((input.platforms ?? []).filter((p) => keys.has(p)))];
75 if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key));
76 const id = newId();
77 const ts = now();
78 const stmts: D1PreparedStatement[] = [
79 env.DB.prepare('INSERT INTO repo_imports (id, user_id, repo, ref, repo_owner_id, platforms, source, status, found, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)')
80 .bind(id, user.id, scan.repo, scan.ref, scan.info.owner_id, platforms.join(','), input.source, 'reading', scan.folders.length, ts),
81 ];
82 for (const f of scan.folders) {
83 stmts.push(
84 env.DB.prepare('INSERT INTO repo_import_items (id, import_id, path, files, status, detail, created_at) VALUES (?,?,?,?,?,?,?)')
85 .bind(newId(), id, f.path, JSON.stringify(f.files), f.problem ? 'skipped' : 'queued', f.problem ?? null, ts),
86 );
87 }
88 await env.DB.batch(stmts);
89 return (await getImport(env, id))!;
90}
91
92/** Read one waiting skill of a repo share. Returns how many are still waiting. Safe to call from several places at once. */
93export async function processNextItem(env: Env, ctx: Waiter, importId: string): Promise<{ left: number; processed: boolean }> {
94 const ts = now();
95 // Claim one step. A step that was claimed two minutes ago and never finished is taken again.
96 const item = await env.DB.prepare(
97 `UPDATE repo_import_items SET status = 'working', started_at = ?1 WHERE id = (
98 SELECT id FROM repo_import_items WHERE import_id = ?2 AND (status = 'queued' OR (status = 'working' AND started_at < ?3)) ORDER BY path ASC LIMIT 1
99 ) RETURNING *`,
100 ).bind(ts, importId, ts - 120).first<ImportItem>();
101 if (item) await readItem(env, ctx, item);
102 const left = await env.DB.prepare("SELECT COUNT(*) AS n FROM repo_import_items WHERE import_id = ? AND status IN ('queued','working')").bind(importId).first<{ n: number }>();
103 if ((left?.n ?? 0) === 0) await finishReading(env, importId);
104 return { left: left?.n ?? 0, processed: !!item };
105}
106
107async function readItem(env: Env, ctx: Waiter, item: ImportItem): Promise<void> {
108 const done = (status: ImportItem['status'], detail: string | null, skillId: string | null = null, versionId: string | null = null) =>
109 env.DB.prepare('UPDATE repo_import_items SET status = ?, detail = ?, skill_id = ?, version_id = ? WHERE id = ?').bind(status, detail, skillId, versionId, item.id).run();
110 try {
111 const imp = await getImport(env, item.import_id);
112 const user = imp ? await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first<User>() : null;
113 if (!imp || !user) return void (await done('failed', 'The share this skill belongs to was not found.'));
114 const files = await fetchSkillFiles(env, imp.repo, imp.ref, JSON.parse(item.files) as TreeFile[]);
115 const existing = await env.DB.prepare(
116 "SELECT * FROM skills WHERE owner_id = ? AND kind = 'hosted' AND state != 'removed' AND LOWER(github_repo) = LOWER(?) AND COALESCE(github_path, '') = ? LIMIT 1",
117 ).bind(user.id, imp.repo, item.path).first<SkillRow>();
118 if (existing) {
119 const latest = await latestVersion(env, existing.id);
120 const { sha } = await bundleManifest(files);
121 if (latest && latest.sha256 === sha && latest.status !== 'superseded') {
122 const why = latest.status === 'rejected' ? 'This skill was not approved before and has not changed since.' : latest.status === 'pending' ? 'This skill is already waiting for review.' : 'This skill is already on Skillfarm and has not changed.';
123 return void (await done('unchanged', why, existing.id, null));
124 }
125 }
126 const res = await submitSkill(env, ctx, {
127 user, source: imp.source, files, platforms: imp.platforms.split(','), existing,
128 github: { repo: imp.repo, path: item.path, ref: imp.ref, ownerId: imp.repo_owner_id }, partOfRepoShare: true,
129 });
130 await done(existing ? 'updated' : 'submitted', null, res.skill.id, res.version.id);
131 } catch (e) {
132 if (!(e instanceof HttpError)) console.error('repo share step failed', item.id, e);
133 await done('failed', e instanceof HttpError ? e.message : 'Something broke while reading this skill. Share the repo again to retry it.');
134 }
135}
136
137/** Once every skill has been read: move the share to review and send one notice to the member and one to the moderators. */
138async function finishReading(env: Env, importId: string): Promise<void> {
139 const ts = now();
140 const moved = await env.DB.prepare("UPDATE repo_imports SET status = 'review', finished_at = ? WHERE id = ? AND status = 'reading'").bind(ts, importId).run();
141 if ((moved.meta.changes ?? 0) === 0) return;
142 const imp = (await getImport(env, importId))!;
143 const counts = await env.DB.prepare(
144 "SELECT SUM(CASE WHEN status IN ('submitted','updated') THEN 1 ELSE 0 END) AS queued, SUM(CASE WHEN status IN ('skipped','failed') THEN 1 ELSE 0 END) AS skipped FROM repo_import_items WHERE import_id = ?",
145 ).bind(importId).first<{ queued: number | null; skipped: number | null }>();
146 const queued = counts?.queued ?? 0;
147 if (queued === 0) {
148 await env.DB.prepare("UPDATE repo_imports SET status = 'decided' WHERE id = ?").bind(importId).run();
149 return;
150 }
151 const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first<User>();
152 if (!user) return;
153 await mail.repoReceived(env, user, imp.repo, queued, counts?.skipped ?? 0, `${env.SITE_URL}/share/repo/${imp.id}`);
154 await mail.adminRepo(env, imp.repo, user.handle, queued, `${env.SITE_URL}/admin/repo/${imp.id}`);
155}
156
157/** Cron entry: finish repo shares whose page was closed before every skill was read. */
158export async function processImportQueue(env: Env, ctx: Waiter, max = 3): Promise<number> {
159 const rows = await env.DB.prepare("SELECT id FROM repo_imports WHERE status = 'reading' AND created_at < ? ORDER BY created_at ASC LIMIT 3").bind(now() - 45).all<{ id: string }>();
160 let n = 0;
161 for (const r of rows.results) {
162 while (n < max) {
163 const step = await processNextItem(env, ctx, r.id);
164 if (step.processed) n++;
165 if (!step.processed || step.left === 0) break;
166 }
167 if (n >= max) break;
168 }
169 return n;
170}
171
172/** After a single skill of a share is decided: close the share when nothing in it is waiting any more. */
173export async function settleImportOfVersion(env: Env, versionId: string): Promise<void> {
174 await env.DB.prepare(
175 `UPDATE repo_imports SET status = 'decided', decided_at = COALESCE(decided_at, ?1) WHERE status = 'review'
176 AND id = (SELECT import_id FROM repo_import_items WHERE version_id = ?2)
177 AND NOT EXISTS (SELECT 1 FROM repo_import_items i JOIN skill_versions v ON v.id = i.version_id WHERE i.import_id = repo_imports.id AND v.status = 'pending')`,
178 ).bind(now(), versionId).run();
179}
180
181/** Deny every waiting skill of a shared repo in one step, with one note and one email to the member. */
182export async function rejectRepo(env: Env, admin: User, importId: string, note: string): Promise<number> {
183 if (!admin.is_admin) throw new HttpError(403, 'Moderators only.');
184 const imp = await getImport(env, importId);
185 if (!imp) throw new HttpError(404, 'That shared repo was not found.');
186 if (imp.status === 'reading') throw new HttpError(409, 'Skillfarm is still reading this repo. Try again in a minute.');
187 const ts = now();
188 const inShare = '(SELECT version_id FROM repo_import_items WHERE import_id = ?)';
189 const res = await env.DB.batch([
190 env.DB.prepare(`UPDATE skill_versions SET status = 'rejected', decided_by = ?, decided_at = ?, decision_note = ? WHERE status = 'pending' AND id IN ${inShare}`).bind(admin.id, ts, note || null, importId),
191 env.DB.prepare(
192 `UPDATE skills SET state = 'rejected', updated_at = ? WHERE state = 'pending' AND current_version_id IS NULL AND id IN (SELECT skill_id FROM repo_import_items WHERE import_id = ?)
193 AND NOT EXISTS (SELECT 1 FROM skill_versions v WHERE v.skill_id = skills.id AND v.status = 'pending')`,
194 ).bind(ts, importId),
195 env.DB.prepare("UPDATE repo_imports SET status = 'decided', decision_note = ?, decided_by = ?, decided_at = ? WHERE id = ?").bind(note || null, admin.id, ts, importId),
196 env.DB.prepare('INSERT INTO moderation_actions (id, admin_id, action, target_type, target_id, note, created_at) VALUES (?,?,?,?,?,?,?)').bind(newId(), admin.id, 'reject_repo', 'repo_import', importId, note || null, ts),
197 ]);
198 const count = res[0].meta.changes ?? 0;
199 const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first<User>();
200 if (owner && count > 0) await mail.repoDenied(env, owner, imp.repo, count, note, `${env.SITE_URL}/share/repo/${imp.id}`);
201 return count;
202}
203
204/** How many skills one press of "Approve all" handles. Each approval is several database writes, so a large repo takes more than one press. */
205const APPROVE_BATCH = 12;
206
207/** Approve the waiting skills of a shared repo, with one email to the member. Returns how many were approved and how many still wait. */
208export async function approveRepo(env: Env, admin: User, importId: string): Promise<{ approved: number; left: number; problems: string[] }> {
209 if (!admin.is_admin) throw new HttpError(403, 'Moderators only.');
210 const imp = await getImport(env, importId);
211 if (!imp) throw new HttpError(404, 'That shared repo was not found.');
212 if (imp.status === 'reading') throw new HttpError(409, 'Skillfarm is still reading this repo. Try again in a minute.');
213 const waiting = await env.DB.prepare(
214 `SELECT v.id, v.title, v.ai_report FROM repo_import_items i JOIN skill_versions v ON v.id = i.version_id WHERE i.import_id = ? AND v.status = 'pending' ORDER BY i.path ASC`,
215 ).bind(importId).all<{ id: string; title: string; ai_report: string | null }>();
216 const titles: string[] = [];
217 const problems: string[] = [];
218 let seeds = 0;
219 for (const v of waiting.results.slice(0, APPROVE_BATCH)) {
220 try {
221 let category: string | null = null;
222 try { category = v.ai_report ? (JSON.parse(v.ai_report).category ?? null) : null; } catch { /* an old report without a category */ }
223 const before = await env.DB.prepare('SELECT s.published_at FROM skills s JOIN skill_versions sv ON sv.skill_id = s.id WHERE sv.id = ?').bind(v.id).first<{ published_at: number | null }>();
224 await decideVersion(env, admin, v.id, 'approve', '', { silent: true, category });
225 titles.push(v.title);
226 if (!before?.published_at) seeds += SEEDS.share;
227 } catch (e) {
228 if (!(e instanceof HttpError)) throw e;
229 problems.push(`${v.title}: ${e.message}`);
230 }
231 }
232 const left = Math.max(0, waiting.results.length - APPROVE_BATCH) + problems.length;
233 if (left === 0) await env.DB.prepare("UPDATE repo_imports SET status = 'decided', decided_by = ?, decided_at = ? WHERE id = ?").bind(admin.id, now(), importId).run();
234 const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first<User>();
235 if (owner && titles.length) await mail.repoApproved(env, owner, imp.repo, titles, seeds, `${env.SITE_URL}/u/${owner.handle}`);
236 return { approved: titles.length, left, problems };
237}