// Creates or connects a project: Gitea repo with peppa-bot as collaborator, files from the // shared template, OpenSpec, a working copy for agent sessions, and the Peppa record. // Used by the web (acting as the logged-in user) and the CLI (acting as peppa-bot). import { m } from "@peppa/shared/i18n"; import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createProject, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMode, logEvent, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { eq, or } from "drizzle-orm"; import { setupCi } from "./ci.ts"; import { credentialHelper, git, run, templateRepoUrl } from "./git.ts"; export interface ProvisionOptions { /** Acts in Gitea: the user's OAuth client, or the bot's. */ gitea: GiteaClient; /** Namespace for the repo: the actor's login or an org. */ owner: string; ownerIsUser: boolean; slug: string; key: string; name: string; /** For a new repo; an existing one keeps its visibility. Default public (PEP-64). */ visibility?: "private" | "public"; /** Connect an existing repo `owner/slug` instead of creating one. */ existing?: boolean; /** Peppa user who owns the project (null for CLI/bot projects). */ ownerId?: number | null; /** Override for tests; defaults to the template repo in Gitea. */ templateUrl?: string; log?: (step: string) => void; } // Template files that stay in the template repo (RULES.md is loaded live by the runner). const TEMPLATE_SKIP = new Set([".git", "RULES.md", "README.md"]); // PEP-145: the product placeholder («Продукт создаётся») — only for a new, empty repository; // a connected repository keeps its own code and deploy untouched. const PLACEHOLDER = new Set(["Dockerfile", "product"]); /** `deploy` of a new project: the placeholder opens by the link before the first story. */ export const NEW_PROJECT_DEPLOY = { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" }; /** * Where a user's new project goes: their namespace (or an org) with their Gitea client; a local * user without Gitea (PEP-68) always gets peppa-bot's namespace and the bot client. */ export async function projectNamespace(db: Db, user: User, owner?: string | null): Promise> { if (isLocalUser(user)) return { gitea: giteaForBot(), owner: process.env.GITEA_BOT_USER ?? "peppa-bot", ownerIsUser: true }; const ns = owner || user.login; return { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login }; } /** * PEP-142: the same person sent the same «new project» form twice (a second click while the first * request was still creating the project). The project made a moment ago is the answer to the * second request — not «slug is taken». */ export async function justCreatedProject(db: Db, o: { slug: string; key: string; ownerId: number }, withinMs = 2 * 60_000): Promise { const [p] = await db.select().from(projects).where(eq(projects.slug, o.slug.toLowerCase())); if (!p || p.ownerId !== o.ownerId || p.key !== o.key.toUpperCase()) return null; return Date.now() - p.createdAt.getTime() <= withinMs ? p : null; } const creating: Map> = ((globalThis as { __peppaCreatingProjects?: Map> }).__peppaCreatingProjects ??= new Map()); /** * PEP-142: `provisionProject` for a form a person may send twice. While the first request is still * creating the project, the second one waits for it (and gets the same project or the same error); * after that — `justCreatedProject`. Someone else's or an old project is still «taken». */ export function provisionProjectOnce(db: Db, o: ProvisionOptions): Promise { const ownerId = o.ownerId; if (ownerId == null) return provisionProject(db, o); const id = `${ownerId}:${o.slug.toLowerCase()}:${o.key.toUpperCase()}`; const running = creating.get(id); if (running) return running; // Registered before the first await, so a concurrent request cannot slip past. const p = (async () => (await justCreatedProject(db, { slug: o.slug, key: o.key, ownerId })) ?? (await provisionProject(db, o)))().finally(() => creating.delete(id)); creating.set(id, p); return p; } export async function provisionProject(db: Db, o: ProvisionOptions): Promise { const env = loadEnv(); const log = o.log ?? (() => {}); const key = o.key.toUpperCase(); const botLogin = process.env.GITEA_BOT_USER ?? "peppa-bot"; if (!/^[a-z0-9][a-z0-9-]*$/.test(o.slug)) throw new PeppaError(m("Slug \"{slug}\": только a–z, 0–9 и дефис", { slug: o.slug })); if (!/^[A-Z][A-Z0-9]{1,9}$/.test(key)) throw new PeppaError(m("Ключ \"{key}\": 2–10 символов A–Z/0–9, начинается с буквы", { key: o.key })); const [taken] = await db.select().from(projects).where(or(eq(projects.slug, o.slug), eq(projects.key, key))); if (taken) throw new PeppaError(taken.slug === o.slug ? m("Slug \"{slug}\" уже занят", { slug: o.slug }) : m("Ключ \"{key}\" уже занят", { key })); const dest = join(env.PEPPA_WORKSPACES, o.slug); if (existsSync(dest)) throw new PeppaError(m("Рабочая копия {path} уже существует", { path: dest })); // 1. Repository let repo = await o.gitea.getRepo(o.owner, o.slug); if (o.existing) { if (!repo) throw new PeppaError(m("Код проекта {repo} не найден", { repo: `${o.owner}/${o.slug}` })); if (!repo.permissions?.admin) throw new PeppaError(m("Нет прав администратора на {repo}", { repo: `${o.owner}/${o.slug}` })); } else { if (repo) throw new PeppaError(m("Код проекта {repo} уже есть — подключите его как существующий", { repo: `${o.owner}/${o.slug}` })); log("create repo"); repo = await o.gitea.createRepo(o.owner, o.ownerIsUser, o.slug, o.name, o.visibility === "private"); } if (repo.owner.login !== botLogin) { log("add peppa-bot"); await o.gitea.addCollaborator(repo.owner.login, repo.name, botLogin, "write"); } // PEP-145: a new project with the placeholder asks for its first deploy once CI is connected. let firstDeploy = false; try { // 2. Working copy (git as peppa-bot) log("clone"); mkdirSync(env.PEPPA_WORKSPACES, { recursive: true }); await git(env.PEPPA_WORKSPACES, "clone", "-q", repo.clone_url, dest); const branch = repo.empty ? "main" : repo.default_branch || "main"; if (repo.empty) await git(dest, "symbolic-ref", "HEAD", `refs/heads/${branch}`); await git(dest, "config", "credential.helper", ""); await git(dest, "config", "--add", "credential.helper", credentialHelper()); await git(dest, "config", "user.name", "Peppa"); await git(dest, "config", "user.email", `${botLogin}@telecom.quest`); // 3. Template files that are missing (never overwrite the project's own) log("template"); const tpl = mkdtempSync(join(tmpdir(), "peppa-tpl-")); try { await git(tmpdir(), "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl); for (const entry of readdirSync(tpl)) { if (TEMPLATE_SKIP.has(entry) || existsSync(join(dest, entry))) continue; if (PLACEHOLDER.has(entry) && !repo.empty) continue; cpSync(join(tpl, entry), join(dest, entry), { recursive: true }); } } finally { rmSync(tpl, { recursive: true, force: true }); } if (!existsSync(join(dest, "README.md"))) { writeFileSync(join(dest, "README.md"), `# ${o.name}\n\nПроект Peppa FACTORY. Ключ стори: \`${key}\`. Правила — в [AGENTS.md](AGENTS.md).\n`); } mkdirSync(join(dest, ".peppa"), { recursive: true }); if (!existsSync(join(dest, ".peppa/project.json"))) { const placeholder = repo.empty && existsSync(join(dest, "Dockerfile")) && existsSync(join(dest, NEW_PROJECT_DEPLOY.compose)); writeFileSync(join(dest, ".peppa/project.json"), `${JSON.stringify({ slug: o.slug, key, name: o.name, peppaUrl: env.PEPPA_WEB_URL, ...(placeholder ? { deploy: NEW_PROJECT_DEPLOY } : {}) })}\n`); firstDeploy = placeholder; } // 4. OpenSpec — the template ships openspec/config.yaml, so "set up" means changes/ // exists (init also installs the agent skills); a repo's own config is kept by init. if (!existsSync(join(dest, "openspec", "changes"))) { log("openspec init"); await run(process.env.PEPPA_OPENSPEC_BIN ?? "openspec", ["init", "--tools", "claude,agents", "--no-animation", "."], { cwd: dest }); } // 5. Commit + push await git(dest, "add", "-A"); const { stdout: staged } = await git(dest, "diff", "--cached", "--name-only"); if (staged.trim()) { log("push"); await git(dest, "commit", "-qm", repo.empty ? `Bootstrap ${o.name} from Peppa template` : `Connect ${o.name} to Peppa`); await git(dest, "push", "-q", "-u", "origin", `HEAD:${branch}`); } // 6. Peppa record — last, so a failure above leaves nothing in Peppa const project = await createProject(db, { slug: o.slug, key, name: o.name, giteaOwner: repo.owner.login, giteaRepo: repo.name, workspacePath: dest, ownerId: o.ownerId ?? null, }); // PEP-79: in a new project nobody drags cards — the dispatcher takes stories from the backlog. await setAutonomy(db, project.id, NEW_PROJECT_AUTONOMY); // The owner connected a subscription once: their next projects use it without asking again. const own = o.ownerId ? await ownPool(db, o.ownerId) : null; if (own) await setProjectPool(db, project.id, own.id); // PEP-84: every new story of a new project goes through «продакт» and «аналитик» first. await setIntakeSettings(db, project.id, { enabled: true }); // 7. CI (PEP-57): runner, Actions secret, webhook. Best effort — `peppa ci connect` redoes it. log("ci"); const ci = await setupCi(db, project).then(() => true, (e) => (log(`ci: ${(e as Error).message}`), false)); // PEP-145: new versions reach everyone without a visit to the settings; the bootstrap commit // was pushed before the runner and the secret existed, so the first deploy of the version to // check is asked for with a tag (the PEP-112 mechanism). Best effort: the watchdog and the // first merged story deploy it anyway. await setPublishMode(db, project.id, NEW_PROJECT_PUBLISH); if (ci && firstDeploy) { log("first deploy"); try { const { stdout: head } = await git(dest, "rev-parse", "HEAD"); const tag = `deploy-staging-${new Date().toISOString().replace(/\D/g, "").slice(0, 17)}`; await o.gitea.createTag(repo.owner.login, repo.name, tag, head.trim(), "Первая версия для проверки: заглушка продукта"); await logEvent(db, { projectId: project.id, type: "first_deploy_requested", payload: { tag } }); } catch (e) { log(`first deploy: ${(e as Error).message}`); } } return project; } catch (e) { rmSync(dest, { recursive: true, force: true }); if (e instanceof PeppaError) throw e; const err = e as { stderr?: string; message: string }; throw new PeppaError( o.existing ? m("Не удалось подготовить проект: {error}", { error: (err.stderr || err.message).trim().slice(0, 300) }) : m("Не удалось подготовить проект: {error} (код проекта {repo} уже создан — можно подключить его как существующий)", { error: (err.stderr || err.message).trim().slice(0, 300), repo: repo.full_name }), ); } }