peppa/packages/cli/src/index.ts
Асель 13ad9cb51e Platform release offers switch: no "deploy to prod?" for Peppa before the launch
peppa platform release-offers on|off (setting platform.release_offers, default on). Off closes the
open offer and hides the button on the project's releases tab. Turned off now: Peppa runs as
next dev from the working copy and has no prod yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 02:24:37 +05:00

450 lines
20 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.

// `peppa` CLI: manage projects, goals, tasks and PM questions until the web UI exists.
import { parseArgs } from "node:util";
import { resolve } from "node:path";
import {
backupDb,
createGoal,
createProject,
createTask,
findProjectFile,
getProject,
createLoginLink,
createPairingCode,
listUsers,
unpairTelegram,
upsertUserFromGitea,
getSession,
allowedLogins,
adminRecipients,
describeState,
outboxStats,
platformAdmins,
serviceStatus,
setPlatformAdmins,
SERVICE_NAMES,
getSetting,
setAllowedLogins,
getUserByLogin,
linkEgovIin,
maskIin,
giteaForBot,
setProjectOwner,
getTaskDetails,
listSessions,
listGoals,
listProjects,
listTasks,
pendingQuestions,
PeppaError,
resolveTask,
TASK_STATUSES,
updateTask,
type TaskStatus,
} from "@peppa/core";
import { createDb, migrateDb } from "@peppa/db";
import { answerAndDeliver, connectCi, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { loadEnv } from "@peppa/shared";
const USAGE = `peppa — Peppa software factory CLI
peppa project create <slug> <KEY> <name> [--existing] [--public] (repo in peppa-bot's Gitea namespace)
peppa project add <slug> <KEY> <name> [--owner peppa] [--repo <name>] [--path <dir>] (register only)
peppa project owner <KEY> <gitea-login|->
peppa project list
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
peppa release list [KEY]
peppa release report [KEY] --sha <sha> -s <deploying|healthy|rolled_back|failed> [--previous <sha>] [--reason <text>]
[--log-file <f>] [--commits-file <f>] (prod release step, from scripts/peppa-release.sh)
peppa ci connect [KEY] (runner + secret + PR with the CI workflow from the template)
peppa goal add [KEY] <title> [-d <description>]
peppa goal list [KEY]
peppa task add [KEY] <title> [-g <goal-id>] [-d <description>]
peppa task list [KEY] [-s <status>]
peppa task show <PEP-42|42>
peppa task set <PEP-42|42> -s <status>
peppa q list [KEY]
peppa q answer <id> <answer> (delivered into the session's terminal)
peppa session start <PEP-42|42> [--provider claude|codex] [-p <extra prompt>] [--mode <permission-mode>] [--model <m>]
peppa session list [--all]
peppa session send <id> <text>
peppa session attach <id>
peppa session stop <id>
peppa session resume <id> [-p <extra prompt>] (new generation, claude --resume)
peppa platform allowlist | allow <login> | deny <login> (who may log into Peppa)
peppa platform release-offers [on|off] ("deploy to prod?" after a green main of Peppa; off before launch)
peppa platform admins [login,… | -] (who gets service alerts; default: the allowlist)
peppa status (services, outbox, runners, questions, admins)
peppa telegram pair <login> | status | unpair <login> (users normally pair in web Settings)
peppa user ensure mock-<name> (local test user)
peppa user egov <login> <ИИН|-> (eGov QR login: link the IIN, "-" unlinks; users link it in web Settings)
peppa web login-link <gitea-login> (one-time admin login, 10 minutes)
peppa watchdog [--once] [--interval <sec>] [--stall <min>]
peppa db migrate (apply schema migrations to PEPPA_DB)
peppa db backup [file] (checked VACUUM INTO copy; default: today's daily copy)
peppa db migrate-to-sqlite <file> (one-time copy from Postgres DATABASE_URL, read-only)
KEY defaults to the project of the current directory (.peppa/project.json).
Statuses: ${TASK_STATUSES.join(", ")}`;
const { values: opts, positionals } = parseArgs({
allowPositionals: true,
options: {
owner: { type: "string", default: "peppa-bot" },
existing: { type: "boolean" },
public: { type: "boolean" },
repo: { type: "string" },
path: { type: "string" },
description: { type: "string", short: "d" },
goal: { type: "string", short: "g" },
status: { type: "string", short: "s" },
help: { type: "boolean", short: "h" },
prompt: { type: "string", short: "p" },
mode: { type: "string" },
provider: { type: "string" },
model: { type: "string" },
all: { type: "boolean" },
once: { type: "boolean" },
interval: { type: "string", default: "30" },
stall: { type: "string", default: "15" },
sha: { type: "string" },
previous: { type: "string" },
reason: { type: "string" },
"log-file": { type: "string" },
"commits-file": { type: "string" },
},
});
const env = loadEnv();
// `db` commands run before the database is opened: they create or replace the file.
if (positionals[0] === "db") {
try {
if (positionals[1] === "migrate") {
migrateDb(createDb(env.PEPPA_DB));
console.log(`migrated ${env.PEPPA_DB}`);
} else if (positionals[1] === "backup") {
const db = createDb(env.PEPPA_DB);
const r = await backupDb(db, { force: true, file: positionals[2] ? resolve(positionals[2]) : undefined, log: (m) => console.error(m) });
db.$client.close();
if (!r.file) throw new PeppaError(`backup failed: ${r.error}`);
console.log(r.file);
} else if (positionals[1] === "migrate-to-sqlite" && positionals[2]) {
if (!env.DATABASE_URL) throw new PeppaError("DATABASE_URL (the Postgres source) is not set");
const { migrateToSqlite } = await import("./migrate-to-sqlite.ts");
const r = await migrateToSqlite(env.DATABASE_URL, resolve(positionals[2]));
for (const t of r.tables) console.log(`${t.name.padEnd(20)} ${t.copied}`);
console.log(`перенесено, расхождений нет: ${r.file} (${r.ms} мс)`);
} else {
console.error(USAGE);
process.exit(1);
}
process.exit(0);
} catch (e) {
console.error(`peppa: ${(e as Error).message}`);
process.exit(1);
}
}
const db = createDb(env.PEPPA_DB);
const here = findProjectFile(process.cwd())?.data.key;
const [group, cmd, ...args] = positionals;
/** Optional leading project KEY: used when there are more args than required. */
function withKey(rest: string[], required: number): [string, string[]] {
if (rest.length > required) return [rest[0]!, rest.slice(1)];
if (!here) throw new PeppaError("No project KEY given and no .peppa/project.json here");
return [here, rest];
}
function provider(p: string | undefined): Provider | undefined {
if (p === undefined) return undefined;
if (!(PROVIDERS as string[]).includes(p)) throw new PeppaError(`Unknown provider "${p}" (${PROVIDERS.join(", ")})`);
return p as Provider;
}
function status(s: string | undefined): TaskStatus | undefined {
if (s === undefined) return undefined;
if (!(TASK_STATUSES as readonly string[]).includes(s)) throw new PeppaError(`Unknown status "${s}"`);
return s as TaskStatus;
}
async function main(): Promise<void> {
switch (`${group ?? ""} ${cmd ?? ""}`.trim()) {
case "project add": {
const [slug, key, name] = args;
if (!slug || !key || !name) throw new PeppaError("usage: peppa project add <slug> <KEY> <name>");
const p = await createProject(db, {
slug,
key,
name,
giteaOwner: opts.owner!,
giteaRepo: opts.repo,
workspacePath: resolve(opts.path ?? `${env.PEPPA_WORKSPACES}/${slug}`),
});
console.log(`Project ${p.key} (${p.slug}) → ${p.workspacePath}`);
break;
}
case "project create": {
const [slug, key, name] = args;
if (!slug || !key || !name) throw new PeppaError("usage: peppa project create <slug> <KEY> <name> [--existing] [--public]");
const bot = giteaForBot();
const p = await provisionProject(db, {
gitea: bot,
owner: process.env.GITEA_BOT_USER ?? "peppa-bot",
ownerIsUser: true,
slug,
key,
name,
existing: opts.existing,
visibility: opts.public ? "public" : "private",
log: (step) => console.log(`… ${step}`),
});
console.log(`Project ${p.key} → ${p.workspacePath} (${env.GITEA_URL}/${p.giteaOwner}/${p.giteaRepo})`);
break;
}
case "project owner": {
const [key, login] = args;
if (!key || !login) throw new PeppaError("usage: peppa project owner <KEY> <gitea-login|->");
const p = await getProject(db, key);
const u = login === "-" ? null : await getUserByLogin(db, login);
if (login !== "-" && !u) throw new PeppaError(`User ${login} has never logged into the web`);
await setProjectOwner(db, p.id, u?.id ?? null);
console.log(`${p.key} owner → ${u?.login ?? "none"}`);
break;
}
case "project list":
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}${p.ownerId ? ` owner #${p.ownerId}` : ""}`);
break;
case "ci connect": {
const [key] = withKey(args, 0);
const p = await getProject(db, key);
const r = await connectCi(db, p, { log: (step) => console.log(`… ${step}`) });
console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`);
break;
}
case "deploy prod": {
const [key] = withKey(args, 0);
const p = await getProject(db, key);
const r = await deployProd(db, p, process.env.USER ?? "cli");
console.log(`${p.key}: ${r.sha.slice(0, 7)} → prod (release #${r.id}, tasks: ${r.tasks.join(", ") || "—"})`);
break;
}
case "release list": {
const [key] = withKey(args, 0);
const p = await getProject(db, key);
for (const r of await listReleases(db, p.id)) console.log(`#${r.id} ${r.env.padEnd(8)} ${r.sha.slice(0, 7)} ${r.status.padEnd(11)} ${r.tasks.join(",")} ${r.deployedBy} ${r.reason ?? ""}`);
break;
}
case "release report": {
const [key] = withKey(args, 0);
const p = await getProject(db, key);
if (!opts.sha || !opts.status) throw new PeppaError("usage: peppa release report [KEY] --sha <sha> -s <status>");
const read = (f: string | undefined) => (f ? readFileSync(f, "utf8") : null);
const r = await recordRelease(db, p, {
env: "prod",
sha: opts.sha,
previousSha: opts.previous || null,
status: opts.status as ReleaseStatus,
reason: opts.reason || null,
logTail: read(opts["log-file"])?.trimEnd().split("\n").slice(-100).join("\n") || null,
commits: read(opts["commits-file"])?.split("\n").filter(Boolean),
});
console.log(`#${r.id} ${r.env} ${r.sha.slice(0, 7)} ${r.status} ${r.tasks.join(",")}`);
break;
}
case "goal add": {
const [key, [title]] = withKey(args, 1);
if (!title) throw new PeppaError("usage: peppa goal add [KEY] <title>");
const g = await createGoal(db, (await getProject(db, key)).id, title, opts.description);
console.log(`Goal #${g.id}: ${g.title}`);
break;
}
case "goal list": {
const [key] = withKey(args, 0);
for (const g of await listGoals(db, (await getProject(db, key)).id)) console.log(`#${g.id} ${g.title}`);
break;
}
case "task add": {
const [key, [title]] = withKey(args, 1);
if (!title) throw new PeppaError("usage: peppa task add [KEY] <title>");
const p = await getProject(db, key);
const ref = await createTask(db, {
projectId: p.id,
goalId: opts.goal ? Number(opts.goal) : undefined,
title,
description: opts.description,
});
console.log(`${ref.key}: ${title}`);
break;
}
case "task list": {
const projectId = args[0] ?? here ? (await getProject(db, (args[0] ?? here)!)).id : undefined;
const s = status(opts.status);
for (const t of await listTasks(db, { projectId, statuses: s ? [s] : undefined })) {
console.log(`${t.key.padEnd(10)} ${t.status.padEnd(18)} ${t.title}`);
}
break;
}
case "task show": {
const ref = await resolveTask(db, args[0] ?? "", here);
const d = await getTaskDetails(db, ref);
console.log(JSON.stringify({ key: d.key, ...d.task, goal: d.goal, questions: d.questions }, null, 2));
break;
}
case "task set": {
const ref = await resolveTask(db, args[0] ?? "", here);
const t = await updateTask(db, ref, { status: status(opts.status) });
console.log(`${ref.key} → ${t.status}`);
break;
}
case "q list": {
const projectId = args[0] ?? here ? (await getProject(db, (args[0] ?? here)!)).id : undefined;
for (const q of await pendingQuestions(db, projectId)) console.log(`#${q.id} [${q.kind}] task=${q.taskId ?? "-"} ${q.text}`);
break;
}
case "q answer": {
const [id, ...answer] = args;
const { delivered, question } = await answerAndDeliver(db, Number(id), answer.join(" "), "terminal");
console.log(`Answered #${question.id}${delivered ? " (sent to session)" : ""}`);
break;
}
case "session start": {
const s = await startSession(db, args[0] ?? "", { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model, defaultProjectKey: here, provider: provider(opts.provider) });
console.log(`Session #${s.id} for ${s.taskKey} → tmux attach -t ${s.tmuxName}`);
break;
}
case "session list":
for (const s of await listSessions(db, { active: !opts.all })) {
const ago = s.lastActivityAt ? `${Math.round((Date.now() - s.lastActivityAt.getTime()) / 60000)}m ago` : "-";
console.log(`#${String(s.id).padEnd(4)} ${(s.taskKey ?? "-").padEnd(10)} ${s.provider.padEnd(7)} ${s.status.padEnd(14)} ${ago.padEnd(9)} ${s.tmuxName}`);
}
break;
case "session send":
await sendToSession(db, Number(args[0]), args.slice(1).join(" "));
console.log("sent");
break;
case "session attach": {
const s = await getSession(db, Number(args[0]));
const socket = process.env.PEPPA_TMUX_SOCKET ? ["-L", process.env.PEPPA_TMUX_SOCKET] : [];
spawnSync("tmux", [...socket, "attach", "-t", s.tmuxName], { stdio: "inherit" });
break;
}
case "session resume": {
const s = await resumeSession(db, Number(args[0]), { prompt: opts.prompt, permissionMode: opts.mode, model: opts.model });
console.log(`Session #${s.id} resumed (generation ${s.generation}) → tmux attach -t ${s.tmuxName}`);
break;
}
case "session stop":
await stopSession(db, Number(args[0]));
console.log("stopped");
break;
case "web login-link": {
const u = await getUserByLogin(db, args[0] ?? "");
if (!u) throw new PeppaError(`User "${args[0]}" has never logged into the web`);
console.log(`${env.PEPPA_WEB_URL}/auth/link?code=${await createLoginLink(db, u.id)}`);
break;
}
case "platform allowlist":
console.log((await allowedLogins(db)).join("\n"));
break;
case "platform allow":
case "platform deny": {
if (!args[0]) throw new PeppaError(`usage: peppa platform ${cmd} <login>`);
const cur = await allowedLogins(db);
const l = args[0].toLowerCase();
await setAllowedLogins(db, cmd === "allow" ? [...cur, l] : cur.filter((x) => x !== l));
console.log((await allowedLogins(db)).join(", "));
break;
}
case "platform admins": {
if (args[0]) await setPlatformAdmins(db, args[0] === "-" ? null : args[0].split(","));
console.log((await platformAdmins(db)).join(", "));
break;
}
case "status": {
for (const s of await serviceStatus(db)) {
const hb = s.heartbeat;
const info = hb ? ` v${hb.version} pid ${hb.pid} ${hb.host}, с ${hb.startedAt.slice(0, 16).replace("T", " ")}` : "";
console.log(`${SERVICE_NAMES[s.service].padEnd(7)} ${describeState(s).padEnd(16)}${info}`);
}
const ob = await outboxStats(db);
console.log(`outbox: ${ob.pending} ожидают, ${ob.failed} не доставлены`);
console.log(`раннеры: ${(await listSessions(db, { active: true })).length} активных · вопросы: ${(await pendingQuestions(db)).length} открытых`);
const paired = new Set((await adminRecipients(db)).map((u) => u.login));
const admins = (await platformAdmins(db)).map((l) => `${l}${paired.has(l) ? " (Telegram)" : " (без Telegram)"}`);
console.log(`админы: ${admins.join(", ") || "нет"}`);
break;
}
case "telegram pair": {
if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env");
const u = await getUserByLogin(db, args[0] ?? "");
if (!u) throw new PeppaError("usage: peppa telegram pair <login> (the user must exist; users normally pair in web Settings)");
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
const code = await createPairingCode(db, env.TELEGRAM_BOT_TOKEN, u.id);
console.log(`Открой в Telegram (ссылка живёт 10 минут):\n https://t.me/${bot?.username ?? "<bot>"}?start=${code}`);
break;
}
case "telegram status": {
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
console.log(`bot: ${bot ? `@${bot.username}` : "не запускался"}`);
const paired = (await listUsers(db)).filter((u) => u.telegramChatId);
for (const u of paired) console.log(`${u.login}: chat ${u.telegramChatId}${u.telegramUsername ? ` (@${u.telegramUsername})` : ""}`);
if (!paired.length) console.log("никто не привязан — веб → Настройки → Telegram");
break;
}
case "telegram unpair": {
const u = await getUserByLogin(db, args[0] ?? "");
if (!u) throw new PeppaError("usage: peppa telegram unpair <login>");
await unpairTelegram(db, u.id);
console.log("отвязано");
break;
}
case "user ensure": {
// Local user without a Gitea account — for the dev stand and manual checks.
if (!args[0]?.startsWith("mock-")) throw new PeppaError("usage: peppa user ensure mock-<name>");
const u = (await getUserByLogin(db, args[0])) ?? (await upsertUserFromGitea(db, { id: -Math.floor(Math.random() * 1e9) - 1, login: args[0] }, { access_token: "mock-no-gitea-access" }));
console.log(`${u.login} (#${u.id})`);
break;
}
case "platform release-offers": {
// PEP-18: "deploy to prod?" after a green main of Peppa; off before the official launch.
if (args[0] === "on" || args[0] === "off") await setPlatformReleaseOffers(db, args[0] === "on");
else if (args[0]) throw new PeppaError("usage: peppa platform release-offers [on|off]");
console.log(`выкатка Пеппы в прод: ${(await platformReleaseOffers(db)) ? "предлагается" : "выключена"}`);
break;
}
case "user egov": {
// PEP-65: link (or unlink with "-") the IIN a user logs in with through eGov QR.
if (!args[0] || !args[1]) throw new PeppaError("usage: peppa user egov <login> <ИИН|->");
const u = await getUserByLogin(db, args[0]);
if (!u) throw new PeppaError(`нет пользователя ${args[0]}`);
const linked = await linkEgovIin(db, u.id, args[1] === "-" ? null : args[1]);
console.log(linked.egovIin ? `${u.login}: eGov ${maskIin(linked.egovIin)}` : `${u.login}: eGov отвязан`);
break;
}
case "watchdog": {
const wopts = {
intervalMs: Number(opts.interval) * 1000,
stallMs: Number(opts.stall) * 60000,
log: (m: string) => console.log(`${new Date().toISOString()} ${m}`),
};
if (opts.once) await tick(db, wopts);
else await runWatchdog(db, wopts);
break;
}
default:
console.log(USAGE);
}
}
try {
if (opts.help) console.log(USAGE);
else await main();
process.exit(0);
} catch (e) {
console.error(e instanceof PeppaError ? `peppa: ${e.message}` : e);
process.exit(1);
}