peppa/packages/runner/src/provision.ts
peppa-bot 5d23e7f2e4
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 48с
peppa/build build: success за 35с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1723с
peppa-ci / ci (pull_request) Successful in 30m52s
PEP-330: общее пространство кода — чужой код не подключается, неудачная попытка не занимает название
Проекты пользователей создаются клиентом бота в пространстве peppa-bot, а бот
там администратор каждого репозитория. Создание проекта проверяло только права
клиента.

- Шаблон проектов (GITEA_TEMPLATE_REPO) проектом не становится ни у кого.
- В общем пространстве не суперадмин подключает как существующий только пустой
  репозиторий: раньше так подключались шаблон и код удалённых проектов.
- Пустой репозиторий, не занятый проектом, новый проект берёт заново: сбой
  после создания репозитория больше не занимает название навсегда.
- Сбой подготовки (и ответ Git-сервера в общем пространстве) уходит в учёт
  ошибок и суперадмину; человеку — фраза без вывода команды.
- Форма показывает «У меня уже есть код» только тому, кому есть что подключать.
- тест new-project-shared-space.test.ts (до исправления падали все сценарии).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-29 21:06:35 +05:00

301 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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, setAgentSecretsEnabled, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMode, logEvent, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, userGitea, isSuperadmin, platformFailure, GiteaError, PeppaError, type GiteaClient, type GiteaOrg, type GiteaRepo, type Project, type User } from "@peppa/core";
import { projects, type Db } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { and, eq, or, sql } from "drizzle-orm";
import { ensureBranchProtection } from "./branch-protection.ts";
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 private (PEP-280; PEP-64 had public). */
visibility?: "private" | "public";
/** Connect an existing repo `owner/slug` instead of creating one. */
existing?: boolean;
/**
* PEP-330: a person acts with the bot's client in peppa-bot's shared namespace (no own access to
* the Git server). The bot administers every repository there — the template, what failed
* attempts and deleted projects left behind — so «you have admin rights» proves nothing about the
* person: they take only a repository with no code in it.
*/
sharedSpace?: boolean;
/** PEP-330: …and that person is a superadmin: the shared namespace is theirs to manage, code included. */
sharedSpaceAdmin?: 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 user
* without an own access to the Git server that works — a local account (PEP-68) or an old access
* that expired and cannot be renewed (PEP-329) — always gets peppa-bot's namespace and the bot
* client; the namespace chosen in the form is not used: there is nothing to create in it with.
*/
export async function projectNamespace(db: Db, user: User, owner?: string | null): Promise<Pick<ProvisionOptions, "gitea" | "owner" | "ownerIsUser" | "sharedSpace" | "sharedSpaceAdmin">> {
const gitea = await userGitea(db, user);
if (!gitea) return { gitea: giteaForBot(), owner: process.env.GITEA_BOT_USER ?? "peppa-bot", ownerIsUser: true, sharedSpace: true, sharedSpaceAdmin: await isSuperadmin(db, user) };
const ns = owner || user.login;
return { gitea, owner: ns, ownerIsUser: ns === user.login };
}
/**
* PEP-329: what the «Новый проект» form offers. `own` — the user's namespace on the Git server and
* the orgs they may create repositories in; without an own access that works the code goes to
* peppa-bot's namespace and there is nothing to choose (and nothing to report as an error).
*/
export async function newProjectSpaces(db: Db, user: User): Promise<{ own: boolean; orgs: GiteaOrg[]; connect: boolean }> {
const gitea = await userGitea(db, user);
// PEP-330: «У меня уже есть код» — for whoever has code of their own to connect: a namespace
// of their own on the Git server, or a superadmin (the shared namespace is theirs to manage).
if (!gitea) return { own: false, orgs: [], connect: await isSuperadmin(db, user) };
// The list of orgs did not load: the personal namespace alone is still a valid choice.
return { own: true, orgs: await gitea.orgsWithRepoCreate(user.login).catch(() => []), connect: true };
}
/** PEP-330: the project (a deleted one in the trash included) whose code this repository is. */
async function repoProject(db: Db, repo: GiteaRepo): Promise<Project | null> {
const [p] = await db
.select()
.from(projects)
.where(and(sql`lower(${projects.giteaOwner}) = ${repo.owner.login.toLowerCase()}`, sql`lower(${projects.giteaRepo}) = ${repo.name.toLowerCase()}`));
return p ?? null;
}
/**
* 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<Project | null> {
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<string, Promise<Project>> = ((globalThis as { __peppaCreatingProjects?: Map<string, Promise<Project>> }).__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<Project> {
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<Project> {
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 }));
/**
* PEP-330: what a failure of the preparation becomes. A clear refusal («slug занят», «код не ваш»)
* is told as it is. Anything else is FORGE's failure, not the person's — in the shared namespace
* the Git server's errors too, the bot talks to it: the reason goes to the error tracker and the
* superadmins (PEP-154), the person gets a plain phrase — no command output and no advice they
* cannot follow. A repository made a moment ago stays empty: the next attempt takes it again.
*/
const fail = async (e: unknown): Promise<never> => {
if (e instanceof PeppaError && !(e instanceof GiteaError && o.sharedSpace)) throw e;
const err = e as { stderr?: string; message: string };
const detail = (err.stderr || err.message).trim().slice(0, 300);
if (o.ownerId != null) {
await platformFailure(db, new Error(detail, { cause: e }), { service: "web", where: `создание проекта ${o.owner}/${o.slug}` });
throw new PeppaError(m("Не удалось подготовить проект — это сбой на стороне FORGE, администратор уже знает. Попробуйте ещё раз позже."));
}
// The CLI: the machine admin reads the reason right here.
throw new PeppaError(m("Не удалось подготовить проект: {error}", { error: detail }));
};
// 1. Repository
const repo = await repository().catch(fail);
// 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Проект FORGE. Ключ стори: \`${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 });
// PEP-253: agents of a new project get no secrets in env — external services go through Access Hub.
await setAgentSecretsEnabled(db, null, project.id, false);
// PEP-191: after the first commit only peppa-bot writes to the default branch. Best effort:
// the project works without it; the superadmin is told once and the watchdog retries daily.
log("protect branch");
const bot = (() => {
try {
return giteaForBot();
} catch {
return null; // no bot token (tests, a half-set machine): protect with the owner's client alone
}
})();
await ensureBranchProtection(db, project, { clients: bot ? [o.gitea, bot] : [o.gitea], log });
// 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 });
return fail(e);
}
/** Step 1: the repository — an existing one to connect, an empty leftover to take again, or a new one. */
async function repository(): Promise<GiteaRepo> {
let repo = await o.gitea.getRepo(o.owner, o.slug);
// PEP-330: the template every project is made from (files of new projects, the agents' rules)
// is never a project itself — for nobody, the CLI included.
if (repo && repo.full_name.toLowerCase() === env.GITEA_TEMPLATE_REPO.toLowerCase()) {
throw new PeppaError(m("{repo} — шаблон проектов FORGE, проектом он стать не может", { repo: repo.full_name }));
}
const restricted = !!o.sharedSpace && !o.sharedSpaceAdmin;
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}` }));
// PEP-330: in the shared namespace the admin rights are the bot's, not the person's.
if (restricted && !repo.empty) throw new PeppaError(m("Код проекта {repo} принадлежит не вам — подключить его может администратор FORGE", { repo: `${o.owner}/${o.slug}` }));
} else if (repo) {
// PEP-330: in the shared namespace an empty repository no project uses is what a failed attempt
// left behind. The new project takes it — the name is not taken forever (the person cannot
// «connect it as existing» themselves). Anything with code in it stays untouched.
const free = !!o.sharedSpace && repo.empty && !!repo.permissions?.admin && !(await repoProject(db, repo));
if (!free) {
throw new PeppaError(
restricted
? m("Адрес кода «{slug}» уже занят — измените его в разделе «Дополнительно»", { slug: o.slug })
: m("Код проекта {repo} уже есть — подключите его как существующий", { repo: `${o.owner}/${o.slug}` }),
);
}
log("reuse empty repo");
const isPrivate = o.visibility !== "public";
if (repo.private !== isPrivate) await o.gitea.setRepoPrivate(repo.owner.login, repo.name, isPrivate);
} else {
log("create repo");
repo = await o.gitea.createRepo(o.owner, o.ownerIsUser, o.slug, o.name, o.visibility !== "public");
}
if (repo.owner.login !== botLogin) {
log("add peppa-bot");
await o.gitea.addCollaborator(repo.owner.login, repo.name, botLogin, "write");
}
return repo;
}
}