«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
89 lines
4.7 KiB
TypeScript
89 lines
4.7 KiB
TypeScript
// PEP-73: the project's AGENTS.md — its prompt and standards for every agent (Claude reads it
|
||
// through CLAUDE.md, Codex and OpenCode natively) — shown and edited on the project tab
|
||
// «AGENTS.md». The source of truth is the default branch in Gitea, not the working copy (which
|
||
// may sit on a story branch); a save is one commit there, guarded by the blob sha it was based on.
|
||
import { m } from "@peppa/shared/i18n";
|
||
import { existsSync } from "node:fs";
|
||
import { join } from "node:path";
|
||
import { GiteaError, listSessions, logEvent, PeppaError, type Project, type User } from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
import { loadEnv } from "@peppa/shared";
|
||
import { git } from "./git.ts";
|
||
import { repoAdmins } from "./share.ts";
|
||
|
||
export const AGENTS_MD = "AGENTS.md";
|
||
export const AGENTS_MD_MAX = 64 * 1024;
|
||
|
||
export interface AgentsMd {
|
||
/** File text; "" when the repo has no AGENTS.md yet. */
|
||
text: string;
|
||
/** Blob sha the editor saves against; null when the file does not exist. */
|
||
sha: string | null;
|
||
branch: string;
|
||
url: string;
|
||
/** Set when Gitea could not be asked. */
|
||
error: string | null;
|
||
}
|
||
|
||
export async function readAgentsMd(db: Db, project: Project): Promise<AgentsMd> {
|
||
const branch = project.defaultBranch;
|
||
const url = `${loadEnv().GITEA_URL}/${project.giteaOwner}/${project.giteaRepo}/src/branch/${encodeURIComponent(branch)}/${AGENTS_MD}`;
|
||
let last: unknown = null;
|
||
for (const c of await repoAdmins(db, project)) {
|
||
try {
|
||
const f = await c.fileWithSha(project.giteaOwner, project.giteaRepo, AGENTS_MD, branch);
|
||
return { text: f?.text ?? "", sha: f?.sha ?? null, branch, url, error: null };
|
||
} catch (e) {
|
||
last = e;
|
||
}
|
||
}
|
||
// glossary-ignore: вкладка AGENTS.md есть только в виде «Инженер»
|
||
return { text: "", sha: null, branch, url, error: m("Gitea не ответила: {error}", { error: (last as Error | null)?.message ?? m("нет клиента") }) };
|
||
}
|
||
|
||
/**
|
||
* Commits a new AGENTS.md to the default branch. `baseSha` is the blob the editor started from
|
||
* (null for a new file): if someone changed the file meanwhile, the save is refused instead of
|
||
* overwriting their edit. The caller has already checked access to the project.
|
||
*/
|
||
export async function saveAgentsMd(db: Db, user: User, project: Project, text: string, baseSha: string | null): Promise<{ sha: string }> {
|
||
const body = text.replace(/\r\n/g, "\n");
|
||
if (Buffer.byteLength(body, "utf8") > AGENTS_MD_MAX) throw new PeppaError(m("AGENTS.md больше {n} КБ — сократите", { n: AGENTS_MD_MAX / 1024 }));
|
||
const branch = project.defaultBranch;
|
||
const author = { name: user.name || user.login, email: user.email || `${user.login}@users.peppa` };
|
||
let last: unknown = null;
|
||
for (const c of await repoAdmins(db, project)) {
|
||
try {
|
||
const cur = await c.fileWithSha(project.giteaOwner, project.giteaRepo, AGENTS_MD, branch);
|
||
if ((cur?.sha ?? null) !== baseSha) throw new PeppaError(m("AGENTS.md изменили, пока вы редактировали — обновите страницу и повторите правку"));
|
||
if (cur && cur.text === body) return { sha: cur.sha };
|
||
const r = await c.writeFile(project.giteaOwner, project.giteaRepo, AGENTS_MD, {
|
||
text: body,
|
||
branch,
|
||
sha: cur?.sha,
|
||
message: `AGENTS.md: правка из FORGE (${user.login})`,
|
||
author,
|
||
});
|
||
await logEvent(db, { projectId: project.id, type: "agents_md_updated", payload: { login: user.login, commit: r.commit.sha } });
|
||
await pullWorkspace(db, project).catch(() => {});
|
||
return { sha: r.commit.sha };
|
||
} catch (e) {
|
||
if (e instanceof PeppaError && !(e instanceof GiteaError)) throw e;
|
||
last = e;
|
||
}
|
||
}
|
||
// glossary-ignore: вкладка AGENTS.md есть только в виде «Инженер»
|
||
throw new PeppaError(m("Не удалось сохранить AGENTS.md в Gitea: {error}", { error: (last as Error | null)?.message ?? m("нет клиента") }));
|
||
}
|
||
|
||
/** Fast-forwards the project's working copy when it is idle, clean and on the default branch. */
|
||
async function pullWorkspace(db: Db, project: Project): Promise<void> {
|
||
const dir = project.workspacePath;
|
||
if (!dir || !existsSync(join(dir, ".git"))) return;
|
||
if ((await listSessions(db, { active: true, projectId: project.id })).some((s) => !s.workspacePath)) return;
|
||
if ((await git(dir, "rev-parse", "--abbrev-ref", "HEAD")).stdout.trim() !== project.defaultBranch) return;
|
||
if ((await git(dir, "status", "--porcelain")).stdout.trim()) return;
|
||
await git(dir, "fetch", "origin", project.defaultBranch);
|
||
await git(dir, "merge", "--ff-only", `origin/${project.defaultBranch}`);
|
||
}
|