+ Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила
+ Пеппы добавляются сами.
+
+ {md.text.trim() ? (
+
+
+
+ ) : (
+ В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.
+ )}
+
+ );
+}
+
+const AGENTS_MD_STARTER = `# AGENTS.md
+
+Проект ведётся софтвейр-фабрикой **Пеппа**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы;
+здесь — только стандарты этого проекта.
+
+## Стек и команды
+
+
+## Соглашения
+
+
+## Перед PR
+- Тесты и линтеры проходят.
+- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
+ новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
+`;
diff --git a/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md
new file mode 100644
index 00000000..d5261b29
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/proposal.md
@@ -0,0 +1,20 @@
+# PEP-73: вкладка AGENTS.md в проекте
+
+## Why
+PM хочет задавать проекту стандарты, которым следуют все агенты, — по сути промпт проекта (стек, соглашения, этапы
+вроде проверки ИБ перед PR). Такой файл уже есть: `AGENTS.md`. Claude читает его через `CLAUDE.md`, Codex и OpenCode — сами.
+Но правка доступна только через git.
+
+## What Changes
+- Вкладка «AGENTS.md» рядом с Доской/Кодом/Спеками: файл из ветки по умолчанию в Gitea (не рабочей копии), Markdown,
+ «Изменить» → редактор → «Сохранить в main». Это один коммит через contents API Gitea от имени пользователя (клиент владельца,
+ затем peppa-bot), событие `agents_md_updated` в журнале.
+- Защита от перезаписи: сохранение идёт против blob sha, с которого начали; файл изменился — отказ «изменили, пока вы редактировали».
+ Предел — 64 КБ. Нет файла — редактор открывается с заготовкой (стек, соглашения, «Перед PR» с чек-листом ИБ).
+- После сохранения рабочая копия проекта делает fast-forward, если она свободна, чистая и на main.
+
+Вне scope: CI-сканер ИБ (gitleaks/semgrep) — отдельная стори.
+
+## Impact
+`core/gitea.ts` (`fileWithSha`, `writeFile`), `runner/agents-md.ts`, вкладка на странице проекта, `saveAgentsMdAction`,
+`mock-gitea` (POST/PUT contents, sha в GET). Открытых вопросов нет.
diff --git a/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md
new file mode 100644
index 00000000..cfe4f211
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/specs/web-workspace/spec.md
@@ -0,0 +1,16 @@
+## ADDED Requirements
+
+### Requirement: Вкладка AGENTS.md
+Страница проекта SHALL иметь вкладку «AGENTS.md», которая показывает `AGENTS.md` из ветки
+по умолчанию репозитория проекта и даёт владельцу и участникам изменить его. Сохранение —
+один коммит в ветку по умолчанию от имени пользователя.
+
+#### Scenario: Создать и изменить
+- **GIVEN** в репозитории проекта нет `AGENTS.md`
+- **WHEN** участник открывает вкладку, нажимает «Изменить» и сохраняет текст с разделом «ИБ»
+- **THEN** в main появляется коммит с `AGENTS.md`, вкладка показывает этот текст, в журнале — событие правки
+
+#### Scenario: Файл изменили параллельно
+- **GIVEN** участник открыл редактор, а коллега тем временем закоммитил другой `AGENTS.md`
+- **WHEN** участник сохраняет свою версию
+- **THEN** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
diff --git a/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md
new file mode 100644
index 00000000..5d2ad8a8
--- /dev/null
+++ b/openspec/changes/archive/2026-11-14-pep-73-agents-md-tab/tasks.md
@@ -0,0 +1,4 @@
+- [x] 1 `fileWithSha`/`writeFile` в GiteaClient, contents API в mock-gitea
+- [x] 2 `readAgentsMd`/`saveAgentsMd` (sha-guard, предел, событие, ff рабочей копии)
+- [x] 3 Вкладка «AGENTS.md»: просмотр, редактор, заготовка
+- [x] 4 Тесты `project-tabs.test.ts`, проверка в браузере, `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 40449d50..476bfab6 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -366,3 +366,18 @@ PM SHALL уметь убрать стори в архив и вернуть её
#### Scenario: Список сочетаний
- **WHEN** PM нажимает `?` вне поля ввода
- **THEN** открывается окно со списком сочетаний, тот же список — на `/help/shortcuts`
+
+### Requirement: Вкладка AGENTS.md
+Страница проекта SHALL иметь вкладку «AGENTS.md», которая показывает `AGENTS.md` из ветки
+по умолчанию репозитория проекта и даёт владельцу и участникам изменить его. Сохранение —
+один коммит в ветку по умолчанию от имени пользователя.
+
+#### Scenario: Создать и изменить
+- **GIVEN** в репозитории проекта нет `AGENTS.md`
+- **WHEN** участник открывает вкладку, нажимает «Изменить» и сохраняет текст с разделом «ИБ»
+- **THEN** в main появляется коммит с `AGENTS.md`, вкладка показывает этот текст, в журнале — событие правки
+
+#### Scenario: Файл изменили параллельно
+- **GIVEN** участник открыл редактор, а коллега тем временем закоммитил другой `AGENTS.md`
+- **WHEN** участник сохраняет свою версию
+- **THEN** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts
index 01361bb8..b599903e 100644
--- a/packages/core/src/gitea.ts
+++ b/packages/core/src/gitea.ts
@@ -259,6 +259,23 @@ export class GiteaClient {
}
}
+ /** A file at `ref` with its blob sha (for an update), or null if absent. */
+ async fileWithSha(owner: string, repo: string, path: string, ref: string): Promise<{ text: string; sha: string } | null> {
+ try {
+ const f = await this.request<{ content: string; sha: string }>("GET", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`);
+ return { text: Buffer.from(f.content, "base64").toString("utf8"), sha: f.sha };
+ } catch (e) {
+ if (e instanceof GiteaError && e.status === 404) return null;
+ throw e;
+ }
+ }
+
+ /** Creates (no `sha`) or updates (with the current blob `sha`) a file with one commit on `branch`. */
+ writeFile(owner: string, repo: string, path: string, o: { text: string; branch: string; message: string; sha?: string; author?: { name: string; email: string } }) {
+ const body = { content: Buffer.from(o.text, "utf8").toString("base64"), branch: o.branch, message: o.message, ...(o.sha ? { sha: o.sha } : {}), ...(o.author ? { author: o.author, committer: o.author } : {}) };
+ return this.request<{ commit: { sha: string; html_url: string } }>(o.sha ? "PUT" : "POST", `${this.repoPath(owner, repo)}/contents/${path.split("/").map(encodeURIComponent).join("/")}`, body);
+ }
+
setActionsSecret(owner: string, repo: string, name: string, data: string) {
return this.request("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data });
}
diff --git a/packages/db/scripts/export-epics.ts b/packages/db/scripts/export-epics.ts
new file mode 100644
index 00000000..603caae4
--- /dev/null
+++ b/packages/db/scripts/export-epics.ts
@@ -0,0 +1,47 @@
+// Dumps a project's goals (epics) and their tasks with descriptions into Markdown.
+// Usage: tsx packages/db/scripts/export-epics.ts [KEY=PEP] [out=PEPPE_EPICS.md]
+import { writeFileSync } from "node:fs";
+import { asc, eq } from "drizzle-orm";
+import { createDb, goals, projects, tasks } from "../src/index.ts";
+
+const [key = "PEP", out = "PEPPE_EPICS.md"] = process.argv.slice(2);
+const db = createDb();
+
+const [project] = await db.select().from(projects).where(eq(projects.key, key));
+if (!project) throw new Error(`no project ${key}`);
+const gs = await db.select().from(goals).where(eq(goals.projectId, project.id)).orderBy(asc(goals.id));
+const ts = await db.select().from(tasks).where(eq(tasks.projectId, project.id)).orderBy(asc(tasks.number));
+
+const STATUS: Record = {
+ backlog: "Бэклог", proposing: "Proposal", awaiting_approval: "Ждёт одобрения",
+ in_progress: "В работе", review: "Ревью", done: "Готово", blocked: "Заблокирована",
+};
+
+function section(title: string, desc: string | null, items: typeof ts) {
+ const done = items.filter((t) => t.status === "done").length;
+ const lines = [`## ${title}`, "", `Задач: ${items.length}, готово: ${done}`, ""];
+ if (desc?.trim()) lines.push(desc.trim(), "");
+ for (const t of items) {
+ lines.push(`### ${key}-${t.number}: ${t.title}`, "");
+ const meta = [`Статус: ${STATUS[t.status] ?? t.status}`];
+ if (t.openspecChange) meta.push(`OpenSpec: \`${t.openspecChange}\``);
+ if (t.prUrl) meta.push(`PR: ${t.prUrl}`);
+ lines.push(meta.join(" · "), "");
+ if (t.description?.trim()) lines.push(t.description.trim(), "");
+ }
+ return lines.join("\n");
+}
+
+const parts = [
+ `# ${project.name} (${key}) — эпики и задачи`,
+ "",
+ `Выгружено ${new Date().toISOString().slice(0, 16).replace("T", " ")}: целей ${gs.length}, задач ${ts.length}.`,
+ "",
+ ...gs.map((g) => section(`${g.title}${g.status === "open" ? "" : ` (${g.status})`}`, g.description, ts.filter((t) => t.goalId === g.id))),
+];
+const orphans = ts.filter((t) => !t.goalId || !gs.some((g) => g.id === t.goalId));
+if (orphans.length) parts.push(section("Без цели", null, orphans));
+
+writeFileSync(out, parts.join("\n").trimEnd() + "\n");
+console.log(`${out}: ${gs.length} goals, ${ts.length} tasks`);
+process.exit(0);
diff --git a/packages/runner/src/agents-md.ts b/packages/runner/src/agents-md.ts
new file mode 100644
index 00000000..1a6e1616
--- /dev/null
+++ b/packages/runner/src/agents-md.ts
@@ -0,0 +1,85 @@
+// 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 { 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 {
+ 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;
+ }
+ }
+ return { text: "", sha: null, branch, url, error: `Gitea не ответила: ${(last as Error | null)?.message ?? "нет клиента"}` };
+}
+
+/**
+ * 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(`AGENTS.md больше ${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("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: правка из Пеппы (${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;
+ }
+ }
+ throw new PeppaError(`Не удалось сохранить AGENTS.md в Gitea: ${(last as Error | null)?.message ?? "нет клиента"}`);
+}
+
+/** 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 {
+ 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}`);
+}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index d70cf480..d8956b45 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -18,6 +18,7 @@ export * from "./ci-feedback.ts";
export * from "./deploy.ts";
export * from "./platform-release.ts";
export * from "./code.ts";
+export * from "./agents-md.ts";
export * from "./terminal.ts";
export * from "./claude-print.ts";
export * from "./reviewer.ts";
diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts
index acdc608c..026c6423 100644
--- a/packages/testkit/src/mock-gitea.ts
+++ b/packages/testkit/src/mock-gitea.ts
@@ -4,7 +4,8 @@
// (`deliver` signs like Gitea: X-Gitea-Signature = hex HMAC-SHA256 of the body) and tags.
import { execFileSync } from "node:child_process";
import { createHmac } from "node:crypto";
-import { mkdirSync } from "node:fs";
+import { mkdirSync, mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
@@ -451,12 +452,40 @@ export class MockGitea {
}
if (method === "GET" && (m = sub.match(/^contents\/(.+)$/))) {
try {
- const text = execFileSync("git", ["--git-dir", r.path, "show", `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
- return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64" } };
+ const spec = `${q.get("ref") ?? "main"}:${decodeURIComponent(m[1]!)}`;
+ const text = execFileSync("git", ["--git-dir", r.path, "show", spec], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
+ const sha = execFileSync("git", ["--git-dir", r.path, "rev-parse", spec], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
+ return { status: 200, body: { content: Buffer.from(text).toString("base64"), encoding: "base64", sha } };
} catch {
return { status: 404, body: { message: "not found" } };
}
}
+ if ((method === "POST" || method === "PUT") && (m = sub.match(/^contents\/(.+)$/))) {
+ // Gitea's create (POST, file must not exist) / update (PUT, `sha` = current blob) — one commit on `branch`.
+ const path = decodeURIComponent(m[1]!);
+ const branch = String(body.branch ?? "main");
+ const git = (args: string[], env?: NodeJS.ProcessEnv, input?: string) =>
+ execFileSync("git", ["--git-dir", r.path, ...args], { encoding: "utf8", input, env: { ...process.env, ...env }, stdio: ["pipe", "pipe", "ignore"] }).trim();
+ let parent: string | null = null;
+ try {
+ parent = git(["rev-parse", `refs/heads/${branch}`]);
+ } catch {}
+ let current: string | null = null;
+ try {
+ current = parent ? git(["rev-parse", `${parent}:${path}`]) : null;
+ } catch {}
+ if (method === "POST" && current) return { status: 422, body: { message: "repository file already exists" } };
+ if (method === "PUT" && current !== body.sha) return { status: 409, body: { message: `sha does not match [given: ${body.sha}, expected: ${current}]` } };
+ const blob = git(["hash-object", "-w", "--stdin"], undefined, Buffer.from(String(body.content), "base64").toString("utf8"));
+ const index = join(mkdtempSync(join(tmpdir(), "mock-gitea-idx-")), "index");
+ const env = { GIT_INDEX_FILE: index, GIT_AUTHOR_NAME: String(body.author?.name ?? me.login), GIT_AUTHOR_EMAIL: String(body.author?.email ?? "mock@example.invalid"), GIT_COMMITTER_NAME: me.login, GIT_COMMITTER_EMAIL: "mock@example.invalid" };
+ if (parent) git(["read-tree", parent], env);
+ git(["update-index", "--add", "--cacheinfo", `100644,${blob},${path}`], env);
+ const tree = git(["write-tree"], env);
+ const commit = git(["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", String(body.message ?? "update")], env);
+ git(["update-ref", `refs/heads/${branch}`, commit]);
+ return { status: method === "POST" ? 201 : 200, body: { content: { sha: blob, path }, commit: { sha: commit, html_url: `${this.url}/${r.owner}/${r.name}/commit/${commit}` } } };
+ }
if (method === "GET" && sub === "issues") {
const page = Number(q.get("page") ?? 1);
const limit = Number(q.get("limit") ?? 30);
diff --git a/packages/testkit/test/project-tabs.test.ts b/packages/testkit/test/project-tabs.test.ts
index 80bc9a0e..1c9ca2bb 100644
--- a/packages/testkit/test/project-tabs.test.ts
+++ b/packages/testkit/test/project-tabs.test.ts
@@ -153,3 +153,35 @@ describe("Эпики (цели как метки стори)", () => {
await assert.rejects(core.createTask(db, { projectId: a.id, title: "x", goalId: foreign.id }));
});
});
+
+describe("Вкладка «AGENTS.md» (PEP-73)", () => {
+ test("Scenario: читать, создать и изменить AGENTS.md — коммит в main от имени пользователя", async () => {
+ const p = await tabsProject("MTAG", { "README.md": "# Ag" });
+ const empty = await runner.readAgentsMd(db, p);
+ assert.equal(empty.error, null);
+ assert.equal(empty.text, "");
+ assert.equal(empty.sha, null);
+ assert.match(empty.url, /\/src\/branch\/main\/AGENTS\.md$/);
+
+ await runner.saveAgentsMd(db, alice, p, "# AGENTS.md\r\n\r\n## ИБ\r\n- без секретов\r\n", null);
+ const created = await runner.readAgentsMd(db, p);
+ assert.equal(created.text, "# AGENTS.md\n\n## ИБ\n- без секретов\n", "CRLF → LF");
+ assert.ok(created.sha);
+ assert.deepEqual(gitea.filesAt(ALICE.login, p.giteaRepo, "main").sort(), ["AGENTS.md", "README.md"], "other files kept");
+
+ await runner.saveAgentsMd(db, alice, p, created.text + "- зависимости без уязвимостей\n", created.sha);
+ const updated = await runner.readAgentsMd(db, p);
+ assert.match(updated.text, /зависимости без уязвимостей/);
+ const ev = await core.listJournal(db, { projectId: p.id, limit: 50 });
+ assert.ok(ev.some((e) => e.type === "agents_md_updated"), "journal entry");
+ });
+
+ test("Scenario: файл изменили, пока редактировали — сохранение отклонено, чужая правка цела", async () => {
+ const p = await tabsProject("MTAGC", { "README.md": "# C", "AGENTS.md": "v1\n" });
+ const stale = await runner.readAgentsMd(db, p);
+ gitea.commit(ALICE.login, p.giteaRepo, "main", { "AGENTS.md": "v2 от коллеги\n" }, "edit");
+ await assert.rejects(runner.saveAgentsMd(db, alice, p, "моя v1+\n", stale.sha), /изменили, пока вы редактировали/);
+ assert.equal((await runner.readAgentsMd(db, p)).text, "v2 от коллеги\n");
+ await assert.rejects(runner.saveAgentsMd(db, alice, p, "x".repeat(70 * 1024), (await runner.readAgentsMd(db, p)).sha), /больше 64 КБ/);
+ });
+});