Also: a subscription the owner connected once is assigned to their new projects; claudePrint never falls back to the machine login for a self-registered owner. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
152 lines
7.9 KiB
TypeScript
152 lines
7.9 KiB
TypeScript
// 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 { 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, 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"]);
|
||
|
||
/**
|
||
* 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<Pick<ProvisionOptions, "gitea" | "owner" | "ownerIsUser">> {
|
||
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 };
|
||
}
|
||
|
||
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(`Slug "${o.slug}": только a–z, 0–9 и дефис`);
|
||
if (!/^[A-Z][A-Z0-9]{1,9}$/.test(key)) throw new PeppaError(`Ключ "${o.key}": 2–10 символов A–Z/0–9, начинается с буквы`);
|
||
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 ? `Slug "${o.slug}" уже занят` : `Ключ "${key}" уже занят`);
|
||
const dest = join(env.PEPPA_WORKSPACES, o.slug);
|
||
if (existsSync(dest)) throw new PeppaError(`Рабочая копия ${dest} уже существует`);
|
||
|
||
// 1. Repository
|
||
let repo = await o.gitea.getRepo(o.owner, o.slug);
|
||
if (o.existing) {
|
||
if (!repo) throw new PeppaError(`Репозиторий ${o.owner}/${o.slug} не найден`);
|
||
if (!repo.permissions?.admin) throw new PeppaError(`Нет прав администратора на ${o.owner}/${o.slug}`);
|
||
} else {
|
||
if (repo) throw new PeppaError(`Репозиторий ${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");
|
||
}
|
||
|
||
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;
|
||
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Проект Пеппы. Ключ стори: \`${key}\`. Правила — в [AGENTS.md](AGENTS.md).\n`);
|
||
}
|
||
mkdirSync(join(dest, ".peppa"), { recursive: true });
|
||
if (!existsSync(join(dest, ".peppa/project.json"))) {
|
||
writeFileSync(join(dest, ".peppa/project.json"), `${JSON.stringify({ slug: o.slug, key, name: o.name, peppaUrl: env.PEPPA_WEB_URL })}\n`);
|
||
}
|
||
|
||
// 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");
|
||
await setupCi(db, project).catch((e) => log(`ci: ${(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(
|
||
`Не удалось подготовить проект: ${(err.stderr || err.message).trim().slice(0, 300)}${o.existing ? "" : ` (репозиторий ${repo.full_name} уже создан — можно подключить его как существующий)`}`,
|
||
);
|
||
}
|
||
}
|