PEP-73: project tab AGENTS.md — read and edit the agents' prompt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7bef0d3401
commit
cdc7e62bfc
@ -56,7 +56,7 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner } from "@peppa/runner";
|
||||
import { acceptStory, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, saveAgentsMd } from "@peppa/runner";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
@ -650,3 +650,13 @@ export async function checkGiteaTokenAction(f: FormData) {
|
||||
return `/secrets?gitea=${encodeURIComponent(r.ok ? `ok:${r.login}` : r.problems.join("; "))}`;
|
||||
});
|
||||
}
|
||||
|
||||
// ── PEP-73: the project's AGENTS.md ──────────────────────────────────────────────
|
||||
export async function saveAgentsMdAction(f: FormData) {
|
||||
const user = asWebActor(await requireUser());
|
||||
await attempt(f, async () => {
|
||||
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||
await saveAgentsMd(db, user, p, String(f.get("text") ?? ""), str(f, "sha") || null);
|
||||
return `/p/${p.key}?tab=agents&saved=1`;
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, repoOverview, type Release } from "@peppa/runner";
|
||||
import { columnOf, currentReleases, describeRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, readAgentsMd, repoOverview, type Release } from "@peppa/runner";
|
||||
import { listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, projectAgentWarning, memoryStats, readMemory, projectPool, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
@ -22,7 +22,7 @@ import { cn } from "@/lib/utils";
|
||||
import { db } from "@/lib/db";
|
||||
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
|
||||
import { addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember, saveReviewSettingsAction, setProjectVisibilityAction } from "../../actions";
|
||||
import { CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
|
||||
import { AgentsMdTab, CodeTab, EpicsPanel, MemorySection, ProgressBar, PullsTab, SpecsTab } from "./tabs";
|
||||
import { setProjectPoolAction } from "../../subscriptions/actions";
|
||||
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
|
||||
import { saveProjectBudgetAction } from "../../actions";
|
||||
@ -39,6 +39,7 @@ const TABS = [
|
||||
{ id: "board", label: "Доска" },
|
||||
{ id: "code", label: "Код" },
|
||||
{ id: "specs", label: "Спеки" },
|
||||
{ id: "agents", label: "AGENTS.md" },
|
||||
{ id: "pulls", label: "PR" },
|
||||
{ id: "releases", label: "Релизы" },
|
||||
{ id: "bugs", label: "Баги" },
|
||||
@ -67,10 +68,10 @@ function EnvLine({ name, r }: { name: string; r: Release | null | undefined }) {
|
||||
);
|
||||
}
|
||||
|
||||
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string }> }) {
|
||||
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string; tab?: string; epic?: string; weeks?: string; actor?: string; channel?: string; edit?: string; saved?: string }> }) {
|
||||
const user = await requireUser();
|
||||
const { key } = await params;
|
||||
const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel } = await searchParams;
|
||||
const { error, created, tab: tabParam, epic: epicParam, weeks, actor, channel, edit, saved } = await searchParams;
|
||||
const tab = TABS.find((t) => t.id === tabParam)?.id ?? "board";
|
||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||
if (!p) notFound();
|
||||
@ -129,6 +130,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
// Gitea and the working copy are read only for the open tab.
|
||||
const [code, pulls] = await Promise.all([tab === "code" ? repoOverview(db, p) : null, tab === "pulls" ? openPulls(db, p) : null]);
|
||||
const specs = tab === "specs" ? listSpecs(p) : [];
|
||||
const agentsMd = tab === "agents" ? await readAgentsMd(db, p) : null;
|
||||
const memory = tab === "specs" ? readMemory(p.workspacePath) : "";
|
||||
// PEP-47 metrics, PEP-48 journal, PEP-43 default budget.
|
||||
const metrics = tab === "metrics" ? await projectMetrics(db, p.id, { weeks: Number(weeks) || 8 }) : null;
|
||||
@ -423,6 +425,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
</>
|
||||
)}
|
||||
|
||||
{tab === "agents" && agentsMd && <AgentsMdTab projectId={p.id} projectKey={p.key} md={agentsMd} edit={edit === "1"} saved={saved === "1"} />}
|
||||
|
||||
{tab === "pulls" && pulls && <PullsTab pulls={pulls.pulls} error={pulls.error} repoUrl={repo.url} />}
|
||||
|
||||
{tab === "releases" && (
|
||||
|
||||
@ -1,11 +1,11 @@
|
||||
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
||||
import { Archive, ExternalLink, GitBranch, GitPullRequest } from "lucide-react";
|
||||
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
||||
import type { Epic, SpecSummary } from "@peppa/core";
|
||||
import { Markdown } from "@/components/Markdown";
|
||||
import type { OpenPull, RepoOverview } from "@peppa/runner";
|
||||
import { addEpic, editEpic } from "../../actions";
|
||||
import type { AgentsMd, OpenPull, RepoOverview } from "@peppa/runner";
|
||||
import { addEpic, editEpic, saveAgentsMdAction } from "../../actions";
|
||||
import { Hidden } from "@/components/cards";
|
||||
import { Disclosure, Empty, Key, Section, StatusBadge } from "@/components/common";
|
||||
import { Disclosure, Empty, Key, Notice, Section, StatusBadge } from "@/components/common";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input, Textarea } from "@/components/ui/input";
|
||||
@ -231,3 +231,84 @@ export function EpicsPanel({ projectId, projectKey, epics, progress, back }: { p
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** PEP-73: the project's AGENTS.md — prompt and standards every agent follows; read and edit. */
|
||||
export function AgentsMdTab({ projectId, projectKey, md, edit, saved }: { projectId: number; projectKey: string; md: AgentsMd; edit: boolean; saved: boolean }) {
|
||||
const tabHref = `/p/${projectKey}?tab=agents`;
|
||||
const gitea = (
|
||||
<Button asChild size="sm">
|
||||
<a href={md.url}>
|
||||
В Gitea <ExternalLink />
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
if (md.error) {
|
||||
return (
|
||||
<Section title="AGENTS.md" actions={gitea}>
|
||||
<Empty>{md.error}</Empty>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
if (edit) {
|
||||
return (
|
||||
<Section title="AGENTS.md — правка" actions={gitea}>
|
||||
<form action={saveAgentsMdAction} className="flex flex-col gap-3">
|
||||
<Hidden fields={{ projectId: String(projectId), sha: md.sha ?? "", back: `${tabHref}&edit=1` }} />
|
||||
<Textarea name="text" defaultValue={md.text || AGENTS_MD_STARTER} rows={28} spellCheck={false} className="font-mono text-xs leading-relaxed" aria-label="Текст AGENTS.md" />
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Button variant="default">Сохранить в {md.branch}</Button>
|
||||
<Button asChild variant="ghost">
|
||||
<a href={tabHref}>Отмена</a>
|
||||
</Button>
|
||||
<span className="text-xs text-muted-foreground">Коммит в ветку {md.branch} от вашего имени. Новые и перезапущенные агенты прочитают его сразу.</span>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<Section
|
||||
title="AGENTS.md"
|
||||
actions={
|
||||
<>
|
||||
<Button asChild size="sm" variant="default">
|
||||
<a href={`${tabHref}&edit=1`}>
|
||||
<Pencil /> Изменить
|
||||
</a>
|
||||
</Button>
|
||||
{gitea}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{saved && <Notice>AGENTS.md сохранён в {md.branch}</Notice>}
|
||||
<p className="m-0 text-sm text-muted-foreground">
|
||||
Промпт и стандарты проекта: стек, команды, соглашения, этапы (например, проверка ИБ перед PR). Его читают все агенты — Claude, Codex и OpenCode; общие правила
|
||||
Пеппы добавляются сами.
|
||||
</p>
|
||||
{md.text.trim() ? (
|
||||
<div className="rounded-lg border bg-card p-4">
|
||||
<Markdown text={md.text} />
|
||||
</div>
|
||||
) : (
|
||||
<Empty>В репозитории ещё нет AGENTS.md — нажмите «Изменить», чтобы создать его из заготовки.</Empty>
|
||||
)}
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
const AGENTS_MD_STARTER = `# AGENTS.md
|
||||
|
||||
Проект ведётся софтвейр-фабрикой **Пеппа**. Общие правила (OpenSpec, PR, ревью) агент получает от Пеппы;
|
||||
здесь — только стандарты этого проекта.
|
||||
|
||||
## Стек и команды
|
||||
<!-- Язык, фреймворки, как собрать и запустить тесты. -->
|
||||
|
||||
## Соглашения
|
||||
<!-- Стиль кода, структура, именование, что запрещено. -->
|
||||
|
||||
## Перед PR
|
||||
- Тесты и линтеры проходят.
|
||||
- Безопасность (ИБ): нет секретов в коде и логах; весь ввод проверяется; доступ к данным — только своему пользователю;
|
||||
новые зависимости — без известных уязвимостей. Итог проверки — раздел «ИБ» в описании PR.
|
||||
`;
|
||||
|
||||
@ -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). Открытых вопросов нет.
|
||||
@ -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** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
|
||||
@ -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`
|
||||
@ -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** сохранение отклонено с просьбой обновить страницу, версия коллеги не тронута
|
||||
|
||||
@ -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<void>("PUT", `${this.repoPath(owner, repo)}/actions/secrets/${encodeURIComponent(name)}`, { data });
|
||||
}
|
||||
|
||||
47
packages/db/scripts/export-epics.ts
Normal file
47
packages/db/scripts/export-epics.ts
Normal file
@ -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<string, string> = {
|
||||
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);
|
||||
85
packages/runner/src/agents-md.ts
Normal file
85
packages/runner/src/agents-md.ts
Normal file
@ -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<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;
|
||||
}
|
||||
}
|
||||
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<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}`);
|
||||
}
|
||||
@ -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";
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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 КБ/);
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user