PEP-242: шаблон уходит в Gitea с выкаткой, сверка в вачдоге, ci connect --secrets-only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-23 06:07:20 +00:00
parent 2c01d3330d
commit badad190eb
11 changed files with 461 additions and 4 deletions

View File

@ -78,6 +78,7 @@ import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtect
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core";
import { tidyAgentTasks } from "@peppa/runner";
import { installCrashReporting } from "@peppa/core";
import { pushTemplateOrAlert, syncTemplate } from "@peppa/runner";
import { answerAndDeliver, connectCi, importIssues, deployProd, redeployProject, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
import { spawnSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
@ -108,6 +109,9 @@ const USAGE = `peppa — Peppa software factory CLI
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 ci connect [KEY] --secrets-only (PEP-242: PR adding only the project secrets block to the deploy script)
peppa template push [--alert] (PEP-242: template/ → the template repo in Gitea; --alert: failure → superadmin)
peppa template check (does the template in Gitea differ from template/?)
peppa goal add [KEY] <title> [-d <description>]
peppa goal list [KEY]
peppa task add [KEY] <title> [-g <goal-id>] [-d <description>]
@ -196,6 +200,8 @@ const { values: opts, positionals } = parseArgs({
reason: { type: "string" },
"log-file": { type: "string" },
"commits-file": { type: "string" },
"secrets-only": { type: "boolean" },
alert: { type: "boolean" },
},
});
@ -463,8 +469,26 @@ async function main(): Promise<void> {
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"}`);
const r = await connectCi(db, p, { log: (step) => console.log(`… ${step}`), secretsOnly: opts["secrets-only"] });
if (opts["secrets-only"]) console.log(`${p.key}: secrets block ${r.secrets}${r.prUrl ? `, PR ${r.prUrl}` : ""}`);
else console.log(`${p.key}: runner=${r.runner}, ${r.prUrl ? `PR ${r.prUrl}` : "workflow already on the default branch"}`);
break;
}
case "template push": {
if (opts.alert) {
const r = await pushTemplateOrAlert(db, { log: (m) => console.error(m) });
if (!r) process.exitCode = 1;
else console.log(r.state === "pushed" ? `pushed template (${r.changed.length} files)` : "template unchanged");
} else {
const r = await syncTemplate({ push: true });
console.log(r.state === "pushed" ? `pushed template (${r.changed.length} files)` : "template unchanged");
}
break;
}
case "template check": {
const r = await syncTemplate({ push: false });
console.log(r.state === "unchanged" ? "template in Gitea is up to date" : `template in Gitea is behind: ${r.changed.join(", ")}`);
if (r.state !== "unchanged") process.exitCode = 1;
break;
}
case "deploy prod": {

View File

@ -12,12 +12,16 @@ import { loadEnv } from "@peppa/shared";
import { ensureBranchProtection } from "./branch-protection.ts";
import { repoAdmins } from "./share.ts";
import { git, run, templateRepoUrl } from "./git.ts";
import { addSecretsBlock } from "./template-sync.ts";
/** Files of the CI contract, copied from the template into project repos. */
export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh", ".gitea/workflows/deploy.yml", ".gitea/peppa-deploy.sh"];
/** Starting points copied only when the project has none yet (the project owns them after). */
export const CD_SCAFFOLD = ["deploy/compose.yml", "deploy/Dockerfile.node", "deploy/Dockerfile.python"];
export const CI_BRANCH = "peppa/ci";
/** PEP-242: branch of the «only the secrets block» PR. */
export const SECRETS_BRANCH = "peppa/secrets";
const DEPLOY_SCRIPT = ".gitea/peppa-deploy.sh";
export const CI_SECRET_NAME = "PEPPA_CI_SECRET";
/** Events the project webhook gets: PRs and pushes (PEP-57), issues, comments, reviews (PEP-46). */
@ -78,14 +82,17 @@ export async function setupCi(db: Db, project: Project): Promise<CiSetup> {
export interface ConnectCiResult extends CiSetup {
/** PR with the workflow files; null when the default branch already has them. */
prUrl: string | null;
/** PEP-242, secretsOnly: what happened to the project's deploy script. */
secrets?: "added" | "replaced" | "present";
}
/**
* "Connect CI" for an existing project: runner + secret, then a PR from Peppa that adds the
* workflow files from the template and an empty `checks` in .peppa/project.json.
*/
export async function connectCi(db: Db, project: Project, o: { templateUrl?: string; log?: (s: string) => void } = {}): Promise<ConnectCiResult> {
export async function connectCi(db: Db, project: Project, o: { templateUrl?: string; log?: (s: string) => void; secretsOnly?: boolean } = {}): Promise<ConnectCiResult> {
const log = o.log ?? (() => {});
if (o.secretsOnly) return connectSecretsBlock(project, o);
log("runner + secret");
const setup = await setupCi(db, project);
// PEP-191: the same command also puts the default branch protection back.
@ -142,3 +149,61 @@ export async function connectCi(db: Db, project: Project, o: { templateUrl?: str
rmSync(work, { recursive: true, force: true });
}
}
/**
* PEP-242: `peppa ci connect <KEY> --secrets-only` — the project's deploy script gets only the
* missing secrets block (addSecretsBlock), its own changes stay. A script equal to an older template
* (or none) is not needed here: the plain `ci connect` replaces it whole. No runner, Actions secret or
* webhook changes — those are already in place for a deploying project.
*/
async function connectSecretsBlock(project: Project, o: { templateUrl?: string; log?: (s: string) => void }): Promise<ConnectCiResult> {
const log = o.log ?? (() => {});
const bot = giteaForBot();
const repo = await bot.getRepo(project.giteaOwner, project.giteaRepo);
if (!repo) throw new PeppaError(m("Код проекта {repo} не найден", { repo: `${project.giteaOwner}/${project.giteaRepo}` }));
const base = project.defaultBranch;
const work = mkdtempSync(join(tmpdir(), "peppa-ci-"));
try {
log("clone");
const dest = join(work, "repo");
const tpl = join(work, "tpl");
await git(work, "clone", "-q", repo.clone_url, dest);
await git(work, "clone", "-q", "--depth", "1", templateRepoUrl(o.templateUrl), tpl);
await git(dest, "checkout", "-q", "-B", SECRETS_BRANCH, `origin/${base}`);
const file = join(dest, DEPLOY_SCRIPT);
const template = readFileSync(join(tpl, DEPLOY_SCRIPT), "utf8");
let secrets: "added" | "replaced";
if (!existsSync(file)) {
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, template, { mode: 0o755 });
secrets = "replaced";
} else {
const r = addSecretsBlock(readFileSync(file, "utf8"), template);
if (r.state === "present") return { runner: "bot", prUrl: null, secrets: "present" };
// glossary-ignore: отказ читает администратор платформы в CLI
if (r.state === "unsupported") throw new PeppaError(m("Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.", { key: project.key, reason: r.reason }));
writeFileSync(file, r.script);
secrets = "added";
}
await git(dest, "add", "-A");
log("push");
await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", "Секреты проекта в выкладке (PEP-112)");
await git(dest, "push", "-q", "-f", "origin", `HEAD:refs/heads/${SECRETS_BRANCH}`);
const open = await bot.openPullForBranch(project.giteaOwner, project.giteaRepo, SECRETS_BRANCH);
const pr =
open ??
(await bot.createPullRequest(project.giteaOwner, project.giteaRepo, {
head: SECRETS_BRANCH,
base,
title: "Секреты проекта в выкладке",
body: [
"PR от Peppa FACTORY (PEP-242): скрипт выкладки берёт секреты проекта у Peppa FACTORY («⋯ Настройки проекта → Секреты») и передаёт их сервису как переменные окружения (PEP-112).",
"",
`В \`${DEPLOY_SCRIPT}\` добавлен только блок секретов: функция \`project_secrets\`, её файл в \`docker compose\` внутри \`dc()\` и вызов после \`report deploying\`. Остальные строки скрипта не менялись.`,
].join("\n"),
}));
return { runner: "bot", prUrl: pr.html_url, secrets };
} finally {
rmSync(work, { recursive: true, force: true });
}
}

View File

@ -40,6 +40,7 @@ export * from "./ready-digest.ts";
export * from "./stuck-tasks.ts";
export * from "./project-trash.ts";
export * from "./branch-protection.ts";
export * from "./template-sync.ts";
export * from "./story-refine.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";

View File

@ -0,0 +1,162 @@
// PEP-242: the project template reaches Gitea by itself. From 15.11 to 23.11 nobody ran
// scripts/push-template.sh after merges, so agents read a week-old RULES.md and new projects got
// an old deploy script. Now the platform deploy pushes template/ (`peppa template push --alert`),
// and the watchdog compares Gitea's template with template/ of the running commit once an hour.
// Existing projects get only the missing secrets block in their deploy script (addSecretsBlock).
import { m } from "@peppa/shared/i18n";
import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { alertAdmins, deleteSetting, getSetting, giteaForBot, peppaCommit, setSetting } from "@peppa/core";
import type { Db } from "@peppa/db";
import { loadEnv, peppaRoot } from "@peppa/shared";
import { git, templateRepoUrl } from "./git.ts";
const HOUR_MS = 3600_000;
const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot";
/** template/ of the platform this process runs (the image has it at /app/template). */
export function platformTemplateDir(root?: string): string {
return join(root ?? peppaRoot(resolve(import.meta.dirname, "../../..")), "template");
}
export interface TemplateSyncResult {
/** unchanged — Gitea's template equals template/; behind — differs (check only); pushed — a commit went to main. */
state: "unchanged" | "behind" | "pushed";
/** Paths that differ (git status --porcelain), at most 50. */
changed: string[];
}
/** Creates the template repo when it is missing (the same as push-template.sh). */
async function ensureTemplateRepo(): Promise<void> {
const full = loadEnv().GITEA_TEMPLATE_REPO;
const [owner, name] = full.split("/") as [string, string];
const bot = giteaForBot();
if (await bot.getRepo(owner, name)) return;
await bot.request("POST", owner === botLogin() ? "/user/repos" : `/orgs/${encodeURIComponent(owner)}/repos`, {
name,
description: "Peppa project template",
default_branch: "main",
private: true,
template: true,
});
}
/**
* Compares the template repo with `dir` (template/ of the platform) and, with `push`, makes Gitea's
* main equal to it. The comparison is the push itself without the commit, so "behind" always means
* "a push would change something".
*/
export async function syncTemplate(o: { push: boolean; dir?: string; templateUrl?: string; commit?: string | null }): Promise<TemplateSyncResult> {
const dir = o.dir ?? platformTemplateDir();
if (!existsSync(dir)) throw new Error(`no template dir: ${dir}`);
if (o.push && !o.templateUrl && !process.env.PEPPA_TEMPLATE_URL) await ensureTemplateRepo();
const work = mkdtempSync(join(tmpdir(), "peppa-template-"));
try {
const dest = join(work, "t");
try {
await git(work, "clone", "-q", templateRepoUrl(o.templateUrl), dest);
} catch (e) {
if (!o.push) throw e;
rmSync(dest, { recursive: true, force: true });
await git(work, "init", "-q", "-b", "main", dest);
await git(dest, "remote", "add", "origin", templateRepoUrl(o.templateUrl));
}
for (const f of readdirSync(dest)) if (f !== ".git") rmSync(join(dest, f), { recursive: true, force: true });
cpSync(dir, dest, { recursive: true });
await git(dest, "add", "-A");
const { stdout } = await git(dest, "status", "--porcelain");
const changed = stdout.split("\n").filter(Boolean).map((l) => l.slice(3)).slice(0, 50);
if (!changed.length) return { state: "unchanged", changed };
if (!o.push) return { state: "behind", changed };
const commit = (o.commit ?? peppaCommit() ?? "unknown").slice(0, 7);
await git(dest, "-c", "user.name=Peppa", "-c", `user.email=${botLogin()}@telecom.quest`, "commit", "-qm", `Update Peppa template (${commit})`);
await git(dest, "push", "-q", "origin", "HEAD:main");
return { state: "pushed", changed };
} finally {
rmSync(work, { recursive: true, force: true });
}
}
/** `peppa template push --alert`: a failed push is one message to the superadmin per commit. */
export async function pushTemplateOrAlert(db: Db, o: { dir?: string; templateUrl?: string; log?: (s: string) => void } = {}): Promise<TemplateSyncResult | null> {
const log = o.log ?? (() => {});
try {
return await syncTemplate({ push: true, dir: o.dir, templateUrl: o.templateUrl });
} catch (e) {
const reason = ((e as Error).message ?? String(e)).replace(/\s+/g, " ").slice(0, 300);
const commit = (peppaCommit() ?? "unknown").slice(0, 7);
// glossary-ignore: сообщение читает администратор платформы
await alertAdmins(db, `template:push:${commit}`, m("Шаблон проектов не отправлен в Gitea после выкатки {commit}: {reason}. Агенты получают старые правила; отправить вручную — peppa template push.", { commit, reason }), log);
return null;
}
}
/**
* Watchdog: once an hour Gitea's template is compared with template/ of the running commit. Behind —
* one message to the superadmin per platform commit; equal again — the mark is cleared. It does not
* push by itself: the push belongs to the deploy.
*/
export async function templateSyncTick(db: Db, o: { now?: Date; dir?: string; templateUrl?: string; log?: (s: string) => void } = {}): Promise<TemplateSyncResult | null> {
if (process.env.PEPPA_TEMPLATE_SYNC === "off") return null;
const dir = o.dir ?? platformTemplateDir();
if (!existsSync(dir)) return null;
const now = (o.now ?? new Date()).getTime();
const last = await getSetting<number>(db, "template.sync.last");
if (last != null && now - last < HOUR_MS) return null;
await setSetting(db, "template.sync.last", now);
const r = await syncTemplate({ push: false, dir, templateUrl: o.templateUrl });
if (r.state === "unchanged") {
await deleteSetting(db, "template.drift");
return r;
}
const commit = (peppaCommit() ?? "unknown").slice(0, 7);
const prev = await getSetting<{ commit: string }>(db, "template.drift");
if (prev?.commit === commit) return r;
await setSetting(db, "template.drift", { commit, at: now, changed: r.changed });
const files = r.changed.slice(0, 5).join(", ");
// glossary-ignore: сообщение читает администратор платформы
await alertAdmins(db, `template:drift:${commit}`, m("Шаблон проектов в Gitea отстаёт от работающей версии {commit} (файлы: {files}). Агенты получают старые правила; отправить — peppa template push.", { commit, files }), o.log ?? (() => {}));
return r;
}
// ── the secrets block for existing projects ───────────────────────────────────────────────
export type SecretsBlockResult =
| { state: "added"; script: string }
| { state: "present" }
| { state: "unsupported"; reason: string };
const BLOCK_START = "# PEP-112: секреты проекта из Пеппы";
/**
* Adds only the project secrets block (PEP-112) of the template's deploy script to a project's own
* script: the block before `dc() {`, the override file in dc's `docker compose` line, the call after
* `report deploying`. Every other line stays as it was. No anchor, or the script has its own
* `trap … EXIT` (ours would replace it) — unsupported with the reason.
*/
export function addSecretsBlock(script: string, template: string): SecretsBlockResult {
if (/^\s*project_secrets\(\)\s*\{/m.test(script)) return { state: "present" };
const tl = template.split("\n");
const start = tl.findIndex((l) => l.startsWith(BLOCK_START));
const fn = tl.findIndex((l, i) => i > start && /^project_secrets\(\)\s*\{/.test(l));
const end = tl.findIndex((l, i) => i > fn && l === "}");
if (start < 0 || fn < 0 || end < 0) return { state: "unsupported", reason: "в шаблоне нет блока секретов" };
const block = tl.slice(start, end + 1);
if (/^\s*trap\b.*\bEXIT\b/m.test(script)) return { state: "unsupported", reason: "в скрипте свой trap … EXIT — блок его заменил бы" };
const lines = script.split("\n");
const dc = lines.findIndex((l) => /^dc\(\)\s*\{/.test(l));
if (dc < 0) return { state: "unsupported", reason: "в скрипте нет функции dc()" };
const dcEnd = lines.findIndex((l, i) => i > dc && l === "}");
const compose = lines.findIndex((l, i) => i > dc && i < dcEnd && l.includes("docker compose") && l.includes('-f "$compose"'));
if (compose < 0) return { state: "unsupported", reason: 'в dc() нет docker compose … -f "$compose"' };
const call = lines.findIndex((l) => l.trim() === "report deploying");
if (call < 0) return { state: "unsupported", reason: "в скрипте нет строки report deploying" };
const out = [...lines];
out.splice(call + 1, 0, "project_secrets");
out[compose] = out[compose]!.replace('-f "$compose"', '-f "$compose" ${override:+-f "$override"}');
out.splice(dc, 0, ...block, "");
return { state: "added", script: out.join("\n") };
}

View File

@ -4,6 +4,7 @@ import { asIs, m } from "@peppa/shared/i18n";
import { runnerTick } from "./runners.ts";
import { projectTrashTick } from "./project-trash.ts";
import { branchProtectionTick } from "./branch-protection.ts";
import { templateSyncTick } from "./template-sync.ts";
import { createHash } from "node:crypto";
import {
backupDb,
@ -136,6 +137,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash"));
// PEP-191: once a day the protection of every project's default branch is checked.
await branchProtectionTick(db, { now: opts.now, log }).catch(failed(db, log, "branch protection"));
// PEP-242: once an hour the template in Gitea is compared with template/ of the running commit.
await templateSyncTick(db, { now: opts.now, log }).catch(failed(db, log, "template sync"));
await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake"));
// PEP-115: a comment on a backlog story — the analyst reworks the story.
await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine"));

View File

@ -480,4 +480,7 @@ export const runner: Dict = {
"🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».": "🔑 Subscription “{name}”: sign-in problem — the agent failed to sign in {n} times in a row. The agents move to another subscription of the set; check this one in “Subscriptions”.",
"{who}: агент не может войти в аккаунт, другой подписки в наборе нет.": "{who}: the agent cannot sign in to the account, and there is no other subscription in the set.",
"на прежней не удался вход": "sign-in failed on the previous one",
"Шаблон проектов не отправлен в Gitea после выкатки {commit}: {reason}. Агенты получают старые правила; отправить вручную — peppa template push.": "The project template was not pushed to Gitea after deploy {commit}: {reason}. Agents get the old rules; to push by hand — peppa template push.",
"Шаблон проектов в Gitea отстаёт от работающей версии {commit} (файлы: {files}). Агенты получают старые правила; отправить — peppa template push.": "The project template in Gitea is behind the running version {commit} (files: {files}). Agents get the old rules; to push — peppa template push.",
"Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.": "The secrets block was not added to {key}: {reason}. Add it by hand from the template.",
};

View File

@ -388,4 +388,7 @@ export const runner: Dict = {
"🔑 Подписка «{name}»: проблема со входом — агент {n} раза подряд не смог войти в аккаунт. Агенты переезжают на другую подписку набора; эту проверьте в «Подписках».": "🔑 «{name}» жазылымы: кіру мәселесі — агент аккаунтқа қатарынан {n} рет кіре алмады. Агенттер жиынтықтағы басқа жазылымға көшеді; бұны «Жазылымдар» бөлімінде тексеріңіз.",
"{who}: агент не может войти в аккаунт, другой подписки в наборе нет.": "{who}: агент аккаунтқа кіре алмайды, жиынтықта басқа жазылым жоқ.",
"на прежней не удался вход": "алдыңғысында кіру сәтсіз болды",
"Шаблон проектов не отправлен в Gitea после выкатки {commit}: {reason}. Агенты получают старые правила; отправить вручную — peppa template push.": "Жобалар үлгісі {commit} шығарылымынан кейін Gitea-ға жіберілмеді: {reason}. Агенттер ескі ережелерді алады; қолмен жіберу — peppa template push.",
"Шаблон проектов в Gitea отстаёт от работающей версии {commit} (файлы: {files}). Агенты получают старые правила; отправить — peppa template push.": "Gitea-дағы жобалар үлгісі жұмыс істеп тұрған {commit} нұсқасынан қалып қойды (файлдар: {files}). Агенттер ескі ережелерді алады; жіберу — peppa template push.",
"Блок секретов не добавлен в {key}: {reason}. Добавьте его руками по шаблону.": "Құпиялар блогы {key} жобасына қосылмады: {reason}. Оны үлгі бойынша қолмен қосыңыз.",
};

View File

@ -32,6 +32,7 @@ Object.assign(process.env, {
// accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
PEPPA_PRODUCT_LINK: "off",
PEPPA_BRANCH_PROTECT: "off",
PEPPA_TEMPLATE_SYNC: "off",
// PEP-185: no «Взять в работу?» questions in other suites; pick-question.test.ts turns it on.
PEPPA_PICK_QUESTION: "off",
// PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe.

View File

@ -0,0 +1,186 @@
// PEP-242: the project template reaches Gitea by itself (deploy + watchdog check), and existing
// projects get only the missing secrets block in their deploy script. Tests are named after the
// scenarios of openspec/changes/pep-242-template-sync/specs/project-template.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { cpSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
import { like } from "drizzle-orm";
import { telegramOutbox } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { core, db, runner, superadmin, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-tpl-sync-"));
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
const gitea = new MockGitea(join(TMP, "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-tpl-bot" };
const TEMPLATE = readFileSync(join(ROOT, "template/.gitea/peppa-deploy.sh"), "utf8");
let tplRepo = "";
/** A copy of template/ the tests edit (the real one stays as it is). */
const DIR = join(TMP, "template");
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
tplRepo = gitea.addRepo("peppa-bot", "template", { files: { "RULES.md": "# old rules\n" } }).path;
cpSync(join(ROOT, "template"), DIR, { recursive: true });
await superadmin();
});
after(async () => {
await gitea.stop();
await teardown();
});
const alerts = async (prefix: string) =>
(await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, `${prefix}%`))).map((r) => stripAsIs(String(r.params.text)));
const show = (...args: string[]) => execFileSync("git", ["--git-dir", tplRepo, "show", ...args], { encoding: "utf8" });
describe("Шаблон проектов уходит в Gitea с выкаткой", () => {
test("Сценарий: Выкатка с изменённым шаблоном", async () => {
const deploy = readFileSync(join(ROOT, "scripts/platform-deploy.sh"), "utf8");
execFileSync("bash", ["-n", join(ROOT, "scripts/platform-deploy.sh")]);
const push = deploy.indexOf("push_template ||");
assert.match(deploy, /push_template\(\) \{ docker exec peppa-watchdog peppa template push --alert; \}/);
assert.ok(push > deploy.indexOf('echo "$SHORT" >"$PREV_FILE"'), "the template goes after the deploy is checked and recorded");
assert.ok(push < deploy.indexOf('say "ГОТОВО'));
assert.doesNotMatch(deploy.slice(push, deploy.indexOf("\n", push)), /die|rollback/, "a failed push does not roll the deploy back");
const r = await runner.syncTemplate({ push: true, dir: DIR, templateUrl: tplRepo, commit: "abcdef1234" });
assert.equal(r.state, "pushed");
assert.match(show("main", "--format=%s", "--no-patch"), /^Update Peppa template \(abcdef1\)/);
assert.equal(show("main:RULES.md"), readFileSync(join(ROOT, "template/RULES.md"), "utf8"));
assert.equal(show("main:.gitea/peppa-deploy.sh"), TEMPLATE);
});
test("Сценарий: Шаблон не изменился", async () => {
const head = show("main", "--format=%H", "--no-patch");
assert.equal((await runner.syncTemplate({ push: true, dir: DIR, templateUrl: tplRepo })).state, "unchanged");
assert.equal(show("main", "--format=%H", "--no-patch"), head);
});
test("Сценарий: Gitea недоступна при отправке", async () => {
const r = await runner.pushTemplateOrAlert(db, { dir: DIR, templateUrl: join(TMP, "no-such-repo.git") });
assert.equal(r, null);
const sent = await alerts("template:push:");
assert.equal(sent.length, 1);
assert.match(sent[0]!, /Шаблон проектов не отправлен в Gitea/);
});
});
describe("Сверка шаблона в вачдоге", () => {
test("Сценарий: Шаблон совпадает", async () => {
process.env.PEPPA_TEMPLATE_SYNC = "on";
try {
const r = await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T10:00:00Z") });
assert.equal(r?.state, "unchanged");
assert.equal((await alerts("template:drift:")).length, 0);
} finally {
process.env.PEPPA_TEMPLATE_SYNC = "off";
}
});
test("Сценарий: Шаблон отстаёт", async () => {
process.env.PEPPA_TEMPLATE_SYNC = "on";
try {
writeFileSync(join(DIR, "RULES.md"), `${readFileSync(join(DIR, "RULES.md"), "utf8")}\n## Новое правило\n`);
const r = await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T12:00:00Z") });
assert.equal(r?.state, "behind");
assert.deepEqual(r?.changed, ["RULES.md"]);
// An hour later — the same commit, no second message; within the hour — not even checked.
assert.equal(await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T12:30:00Z") }), null);
assert.equal((await runner.templateSyncTick(db, { dir: DIR, templateUrl: tplRepo, now: new Date("2026-11-23T13:01:00Z") }))?.state, "behind");
const sent = await alerts("template:drift:");
assert.equal(sent.length, 1);
assert.match(sent[0]!, /Шаблон проектов в Gitea отстаёт.*RULES\.md/);
// The check never pushes by itself.
assert.doesNotMatch(show("main:RULES.md"), /Новое правило/);
} finally {
process.env.PEPPA_TEMPLATE_SYNC = "off";
}
});
});
/** The template's deploy script as it was before PEP-112: no block, no override, no call — plus a project's own line. */
function oldProjectScript(): string {
const lines = TEMPLATE.split("\n");
const start = lines.findIndex((l) => l.startsWith("# PEP-112: секреты проекта из Пеппы"));
const end = lines.findIndex((l, i) => i > start && l === "}");
lines.splice(start, end - start + 2);
const out = lines
.filter((l) => l !== "project_secrets" && !l.includes('local files=(-f "$compose")') && !l.includes('files+=(-f "$override")'))
.map((l) => l.replace('docker compose -p "$project" "${files[@]}" "$@"', 'docker compose -p "$project" -f "$compose" "$@"'));
out.splice(out.indexOf("report deploying"), 0, 'echo "custom step"');
return out.join("\n");
}
describe("Блок секретов без затирания доработок", () => {
test("Сценарий: Скрипт проекта с доработками", async () => {
const old = oldProjectScript();
assert.doesNotMatch(old, /project_secrets|override/);
const r = runner.addSecretsBlock(old, TEMPLATE);
assert.equal(r.state, "added");
if (r.state !== "added") return;
// Every old line stays, in order; the added ones are the block, the call and the override in dc.
const next = r.script.split("\n");
let at = 0;
for (const l of old.split("\n")) {
const found = next.indexOf(l.replace('-f "$compose" "$@"', '-f "$compose" ${override:+-f "$override"} "$@"'), at);
assert.ok(found >= at, `line kept: ${l}`);
at = found + 1;
}
assert.match(r.script, /^project_secrets\(\) \{/m);
assert.match(r.script, /^report deploying\nproject_secrets\n/m);
assert.match(r.script, /echo "custom step"/);
execFileSync("bash", ["-n"], { input: r.script });
// The override word disappears when there are no secrets and becomes `-f <file>` with them.
const args = (override: string) =>
execFileSync("bash", ["-c", `compose=c.yml override=${JSON.stringify(override)}; printf '[%s]' -f "$compose" \${override:+-f "$override"}`], { encoding: "utf8" });
assert.equal(args(""), "[-f][c.yml]");
assert.equal(args("/tmp/p env"), "[-f][c.yml][-f][/tmp/p env]");
});
test("Сценарий: Блок уже есть", () => {
assert.deepEqual(runner.addSecretsBlock(TEMPLATE, TEMPLATE), { state: "present" });
});
test("Сценарий: Скрипт без функции dc", () => {
const r = runner.addSecretsBlock(oldProjectScript().replace("dc() {", "compose_run() {"), TEMPLATE);
assert.equal(r.state, "unsupported");
const trap = runner.addSecretsBlock(`trap 'rm -f x' EXIT\n${oldProjectScript()}`, TEMPLATE);
assert.equal(trap.state, "unsupported", "the project's own EXIT trap would be replaced");
});
test("ci connect --secrets-only: PR только с блоком, остальные файлы не тронуты", async () => {
const old = oldProjectScript();
gitea.addRepo(BOT.login, "tplsec", {
admins: [BOT.login],
files: { "README.md": "# x\n", ".gitea/peppa-deploy.sh": old, ".peppa/project.json": JSON.stringify({ slug: "tplsec", key: "TPS", name: "TPS", peppaUrl: "http://peppa.test" }) },
});
const p = await core.createProject(db, { slug: "tplsec", key: "TPS", name: "TPS", giteaOwner: BOT.login, workspacePath: join(TMP, "ws", "tplsec"), ownerId: null });
const r = await runner.connectCi(db, p, { templateUrl: tplRepo, secretsOnly: true });
assert.equal(r.secrets, "added");
assert.ok(r.prUrl?.endsWith("/pulls/1"));
const repo = gitea.repo(BOT.login, "tplsec");
assert.equal(repo.pulls[0]!.head, runner.SECRETS_BRANCH);
const git = (...a: string[]) => execFileSync("git", ["--git-dir", repo.path, ...a], { encoding: "utf8" });
assert.equal(git("diff", "--name-only", "main", runner.SECRETS_BRANCH).trim(), ".gitea/peppa-deploy.sh");
const script = git("show", `${runner.SECRETS_BRANCH}:.gitea/peppa-deploy.sh`);
assert.match(script, /echo "custom step"/);
assert.match(script, /^project_secrets$/m);
assert.equal(repo.secrets.PEPPA_CI_SECRET, undefined, "secrets-only does not touch CI setup");
// Merged — the block is there, nothing more to add.
await core.giteaForBot().mergePullRequest(BOT.login, "tplsec", 1);
const again = await runner.connectCi(db, p, { templateUrl: tplRepo, secretsOnly: true });
assert.deepEqual([again.secrets, again.prUrl], ["present", null]);
});
});

View File

@ -173,4 +173,6 @@ ERRS=$(tail -n +$((MARK + 1)) "$LOG" 2>/dev/null | grep -E "⨯|ERR_SQLITE|no su
[ -z "$ERRS" ] || rollback "server errors after the restart:
$ERRS"
rm -rf "$WEB/.next.prev"
# PEP-242: the project template goes to Gitea with every deploy; a failure does not roll back.
./packages/cli/bin/peppa template push --alert || say "project template not pushed (superadmin alerted)"
say "DONE — the site runs ${TARGET:0:8} (was ${PREV:0:8}); pages and health checked"

View File

@ -5,7 +5,9 @@
# 3. копия базы и миграции новым образом (одноразовый контейнер);
# 4. docker compose --profile platform up -d новым тегом;
# 5. /api/health с коммитом цели и свежими heartbeat; страницы под mock-pm;
# 6. сбой на любом шаге после 4 — откат на предыдущий тег (файл $PEPPA_HOME/platform.tag).
# 6. сбой на любом шаге после 4 — откат на предыдущий тег (файл $PEPPA_HOME/platform.tag);
# 7. PEP-242: шаблон проектов (template/ цели) → репозиторий шаблона в Gitea; сбой — сообщение
# суперадмину (peppa template push --alert), выкатку не откатывает.
# Usage: scripts/platform-deploy.sh [--wait] [--no-ci] [<sha>] PEPPA_PLATFORM_DRY=1 — только план.
# Переезд с launchd (остановить quest.telecom.peppa.*, переключить Traefik) — по явному разрешению PM:
# см. openspec/changes/pep-222-all-in-docker/design.md.
@ -105,4 +107,9 @@ for p in / /projects /chats /help /settings /team; do
done
rm -f "$JAR"
echo "$SHORT" >"$PREV_FILE"
# PEP-242: с 15.11 по 23.11 шаблон в Gitea никто не обновлял — агенты брали старые правила. Теперь его
# отправляет каждая выкатка — из уже запущенного watchdog цели (в образе template/, git с помощником бота,
# сеть и .env — как у сервисов).
push_template() { docker exec peppa-watchdog peppa template push --alert; }
push_template || say "шаблон проектов не отправлен (суперадмину сообщено) — выкатка не откатывается"
say "ГОТОВО — платформа в контейнерах на $SHORT (была ${PREV:-—})"