import type { Env, User } from '../env'; import { mail } from './email'; import { fetchSkillFiles, parseGithubUrl, REPO_SKILL_LIMIT, scanRepo, type TreeFile } from './github'; import { rateLimit } from './ratelimit'; import { bundleManifest, decideVersion, latestVersion, PLATFORMS, submitSkill, type SkillRow } from './skills'; import { SEEDS } from './tiers'; import { DAY, HttpError, newId, now } from './util'; /** * A repo share: a member hands over a public GitHub repo, Skillfarm finds every skill folder in it and puts each one in the * 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. */ export type ImportRow = { id: string; user_id: string; repo: string; ref: string; repo_owner_id: string; platforms: string; source: 'web' | 'mcp'; status: 'reading' | 'review' | 'decided'; found: number; decision_note: string | null; decided_by: string | null; decided_at: number | null; created_at: number; finished_at: number | null; }; export type ImportItem = { id: string; import_id: string; path: string; files: string; status: 'queued' | 'working' | 'submitted' | 'updated' | 'unchanged' | 'skipped' | 'failed'; detail: string | null; skill_id: string | null; version_id: string | null; started_at: number | null; created_at: number; }; /** An item joined with the skill and version it became, for the member's page and the moderator's card. */ export type ImportItemView = ImportItem & { slug: string | null; title: string | null; summary: string | null; skill_state: string | null; category: string | null; version_status: string | null; version: number | null; scan_status: string | null; ai_status: string | null; ai_recommendation: string | null; ai_summary: string | null; ai_report: string | null; decision_note: string | null; }; export const IMPORT_LIMITS = { sharesPerDay: 4, waitingSkills: 40 }; type Waiter = { waitUntil(p: Promise): void }; export async function getImport(env: Env, id: string): Promise { return env.DB.prepare('SELECT * FROM repo_imports WHERE id = ?').bind(id).first(); } export async function importItems(env: Env, importId: string): Promise { const res = await env.DB.prepare( `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, 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 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 WHERE i.import_id = ? ORDER BY i.path ASC`, ).bind(importId).all(); return res.results; } /** Read the repo's file list, find its skills and queue one step per skill. Nothing is downloaded or submitted yet. */ export async function startRepoShare(env: Env, input: { user: User; source: 'web' | 'mcp'; url: string; platforms?: string[] }): Promise { const { user } = input; if (user.status !== 'active') throw new HttpError(403, 'This account cannot share skills.'); const ref = parseGithubUrl(input.url); if (!ref) throw new HttpError(400, 'That does not look like a GitHub repo. Paste its address, for example https://github.com/you/your-skills.'); const repoKey = `${ref.owner}/${ref.repo}`.toLowerCase(); const open = await env.DB.prepare( `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 ( SELECT 1 FROM repo_import_items i JOIN skill_versions v ON v.id = i.version_id WHERE i.import_id = m.id AND v.status = 'pending'))) ORDER BY m.created_at DESC LIMIT 1`, ).bind(user.id, repoKey).first<{ id: string; status: string }>(); 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}`); const scan = await scanRepo(env, ref); 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.`); 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.`); if (scan.folders.length > REPO_SKILL_LIMIT) { 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}.`); } const waiting = await env.DB.prepare("SELECT COUNT(*) AS n FROM skills WHERE owner_id = ? AND state = 'pending'").bind(user.id).first<{ n: number }>(); 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.`); 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.'); const keys = new Set(PLATFORMS.map((p) => p.key)); const platforms = [...new Set((input.platforms ?? []).filter((p) => keys.has(p)))]; if (!platforms.length) platforms.push(...PLATFORMS.map((p) => p.key)); const id = newId(); const ts = now(); const stmts: D1PreparedStatement[] = [ env.DB.prepare('INSERT INTO repo_imports (id, user_id, repo, ref, repo_owner_id, platforms, source, status, found, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)') .bind(id, user.id, scan.repo, scan.ref, scan.info.owner_id, platforms.join(','), input.source, 'reading', scan.folders.length, ts), ]; for (const f of scan.folders) { stmts.push( env.DB.prepare('INSERT INTO repo_import_items (id, import_id, path, files, status, detail, created_at) VALUES (?,?,?,?,?,?,?)') .bind(newId(), id, f.path, JSON.stringify(f.files), f.problem ? 'skipped' : 'queued', f.problem ?? null, ts), ); } await env.DB.batch(stmts); return (await getImport(env, id))!; } /** Read one waiting skill of a repo share. Returns how many are still waiting. Safe to call from several places at once. */ export async function processNextItem(env: Env, ctx: Waiter, importId: string): Promise<{ left: number; processed: boolean }> { const ts = now(); // Claim one step. A step that was claimed two minutes ago and never finished is taken again. const item = await env.DB.prepare( `UPDATE repo_import_items SET status = 'working', started_at = ?1 WHERE id = ( 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 ) RETURNING *`, ).bind(ts, importId, ts - 120).first(); if (item) await readItem(env, ctx, item); 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 }>(); if ((left?.n ?? 0) === 0) await finishReading(env, importId); return { left: left?.n ?? 0, processed: !!item }; } async function readItem(env: Env, ctx: Waiter, item: ImportItem): Promise { const done = (status: ImportItem['status'], detail: string | null, skillId: string | null = null, versionId: string | null = null) => env.DB.prepare('UPDATE repo_import_items SET status = ?, detail = ?, skill_id = ?, version_id = ? WHERE id = ?').bind(status, detail, skillId, versionId, item.id).run(); try { const imp = await getImport(env, item.import_id); const user = imp ? await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first() : null; if (!imp || !user) return void (await done('failed', 'The share this skill belongs to was not found.')); const files = await fetchSkillFiles(env, imp.repo, imp.ref, JSON.parse(item.files) as TreeFile[]); const existing = await env.DB.prepare( "SELECT * FROM skills WHERE owner_id = ? AND kind = 'hosted' AND state != 'removed' AND LOWER(github_repo) = LOWER(?) AND COALESCE(github_path, '') = ? LIMIT 1", ).bind(user.id, imp.repo, item.path).first(); if (existing) { const latest = await latestVersion(env, existing.id); const { sha } = await bundleManifest(files); if (latest && latest.sha256 === sha && latest.status !== 'superseded') { 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.'; return void (await done('unchanged', why, existing.id, null)); } } const res = await submitSkill(env, ctx, { user, source: imp.source, files, platforms: imp.platforms.split(','), existing, github: { repo: imp.repo, path: item.path, ref: imp.ref, ownerId: imp.repo_owner_id }, partOfRepoShare: true, }); await done(existing ? 'updated' : 'submitted', null, res.skill.id, res.version.id); } catch (e) { if (!(e instanceof HttpError)) console.error('repo share step failed', item.id, e); await done('failed', e instanceof HttpError ? e.message : 'Something broke while reading this skill. Share the repo again to retry it.'); } } /** Once every skill has been read: move the share to review and send one notice to the member and one to the moderators. */ async function finishReading(env: Env, importId: string): Promise { const ts = now(); const moved = await env.DB.prepare("UPDATE repo_imports SET status = 'review', finished_at = ? WHERE id = ? AND status = 'reading'").bind(ts, importId).run(); if ((moved.meta.changes ?? 0) === 0) return; const imp = (await getImport(env, importId))!; const counts = await env.DB.prepare( "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 = ?", ).bind(importId).first<{ queued: number | null; skipped: number | null }>(); const queued = counts?.queued ?? 0; if (queued === 0) { await env.DB.prepare("UPDATE repo_imports SET status = 'decided' WHERE id = ?").bind(importId).run(); return; } const user = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first(); if (!user) return; await mail.repoReceived(env, user, imp.repo, queued, counts?.skipped ?? 0, `${env.SITE_URL}/share/repo/${imp.id}`); await mail.adminRepo(env, imp.repo, user.handle, queued, `${env.SITE_URL}/admin/repo/${imp.id}`); } /** Cron entry: finish repo shares whose page was closed before every skill was read. */ export async function processImportQueue(env: Env, ctx: Waiter, max = 3): Promise { 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 }>(); let n = 0; for (const r of rows.results) { while (n < max) { const step = await processNextItem(env, ctx, r.id); if (step.processed) n++; if (!step.processed || step.left === 0) break; } if (n >= max) break; } return n; } /** After a single skill of a share is decided: close the share when nothing in it is waiting any more. */ export async function settleImportOfVersion(env: Env, versionId: string): Promise { await env.DB.prepare( `UPDATE repo_imports SET status = 'decided', decided_at = COALESCE(decided_at, ?1) WHERE status = 'review' AND id = (SELECT import_id FROM repo_import_items WHERE version_id = ?2) 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')`, ).bind(now(), versionId).run(); } /** Deny every waiting skill of a shared repo in one step, with one note and one email to the member. */ export async function rejectRepo(env: Env, admin: User, importId: string, note: string): Promise { if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); const imp = await getImport(env, importId); if (!imp) throw new HttpError(404, 'That shared repo was not found.'); if (imp.status === 'reading') throw new HttpError(409, 'Skillfarm is still reading this repo. Try again in a minute.'); const ts = now(); const inShare = '(SELECT version_id FROM repo_import_items WHERE import_id = ?)'; const res = await env.DB.batch([ 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), env.DB.prepare( `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 = ?) AND NOT EXISTS (SELECT 1 FROM skill_versions v WHERE v.skill_id = skills.id AND v.status = 'pending')`, ).bind(ts, importId), env.DB.prepare("UPDATE repo_imports SET status = 'decided', decision_note = ?, decided_by = ?, decided_at = ? WHERE id = ?").bind(note || null, admin.id, ts, importId), 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), ]); const count = res[0].meta.changes ?? 0; const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first(); if (owner && count > 0) await mail.repoDenied(env, owner, imp.repo, count, note, `${env.SITE_URL}/share/repo/${imp.id}`); return count; } /** How many skills one press of "Approve all" handles. Each approval is several database writes, so a large repo takes more than one press. */ const APPROVE_BATCH = 12; /** Approve the waiting skills of a shared repo, with one email to the member. Returns how many were approved and how many still wait. */ export async function approveRepo(env: Env, admin: User, importId: string): Promise<{ approved: number; left: number; problems: string[] }> { if (!admin.is_admin) throw new HttpError(403, 'Moderators only.'); const imp = await getImport(env, importId); if (!imp) throw new HttpError(404, 'That shared repo was not found.'); if (imp.status === 'reading') throw new HttpError(409, 'Skillfarm is still reading this repo. Try again in a minute.'); const waiting = await env.DB.prepare( `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`, ).bind(importId).all<{ id: string; title: string; ai_report: string | null }>(); const titles: string[] = []; const problems: string[] = []; let seeds = 0; for (const v of waiting.results.slice(0, APPROVE_BATCH)) { try { let category: string | null = null; try { category = v.ai_report ? (JSON.parse(v.ai_report).category ?? null) : null; } catch { /* an old report without a category */ } 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 }>(); await decideVersion(env, admin, v.id, 'approve', '', { silent: true, category }); titles.push(v.title); if (!before?.published_at) seeds += SEEDS.share; } catch (e) { if (!(e instanceof HttpError)) throw e; problems.push(`${v.title}: ${e.message}`); } } const left = Math.max(0, waiting.results.length - APPROVE_BATCH) + problems.length; 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(); const owner = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(imp.user_id).first(); if (owner && titles.length) await mail.repoApproved(env, owner, imp.repo, titles, seeds, `${env.SITE_URL}/u/${owner.handle}`); return { approved: titles.length, left, problems }; }