peppa/packages/runner/src/template-sync.ts
peppa-bot 7bedf9d342
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 42с
peppa/build build: success за 31с
peppa/test test: success за 1278с
peppa-ci / ci (pull_request) Successful in 23m28s
PEP-242: якорь блока секретов не зависит от названия платформы (после PEP-243 «из FORGE»)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:08:01 +00:00

163 lines
9.1 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.

// 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: секреты проекта из "; // «из Пеппы» before PEP-243, «из FORGE» after
/**
* 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") };
}