Main's new wording (PEP-123 «Продакт» words) kept and wrapped in t()/m();
wording(mode, locale) gives English words for {task}/{runner} placeholders;
glossary check (pnpm lint) passes; English for all new keys (en/merge-*.ts).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
191 lines
11 KiB
TypeScript
191 lines
11 KiB
TypeScript
// PEP-46, spec gitea-integration: «Issues становятся стори», «Комментарии в PR уходят агенту»,
|
||
// «Мерж руками закрывает стори» — Gitea webhooks (signed like Gitea) against mock Gitea and
|
||
// mock-claude runners.
|
||
import assert from "node:assert/strict";
|
||
import { createHmac } from "node:crypto";
|
||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, project, runner, setDefaultOwner, teardown, type TestProject } from "./helpers.ts";
|
||
import { MockGitea } from "../src/mock-gitea.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-gev-")), "gitea"));
|
||
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
|
||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
await gitea.start();
|
||
process.env.GITEA_URL = gitea.url;
|
||
process.env.GITEA_TOKEN = BOT.token;
|
||
gitea.addUser(BOT);
|
||
pm = await core.upsertUserFromGitea(db, { id: 61, login: "mock-pm" }, { access_token: "x" });
|
||
setDefaultOwner(pm.id);
|
||
});
|
||
after(async () => {
|
||
await gitea.stop();
|
||
await teardown();
|
||
});
|
||
|
||
interface GitTask {
|
||
p: TestProject;
|
||
proj: Awaited<ReturnType<typeof core.getProject>>;
|
||
ref: () => ReturnType<typeof core.resolveTask>;
|
||
pr: number;
|
||
repo: string;
|
||
hook(event: string, payload: Record<string, unknown>): ReturnType<typeof runner.handleGiteaHook>;
|
||
}
|
||
|
||
/** Project (owned by mock-pm) with a repo in mock Gitea and a story with an open PR. */
|
||
async function gitTask(turns: Parameters<typeof project>[0]["turns"] = []): Promise<GitTask> {
|
||
const p = await project({ turns });
|
||
const proj = await core.getProject(db, p.key);
|
||
const pj = JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: "http://test" });
|
||
writeFileSync(join(p.dir, ".peppa/project.json"), pj);
|
||
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
|
||
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
|
||
const branch = `task/${p.taskKey}`;
|
||
gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { "a.txt": "a" });
|
||
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
|
||
const ref = () => core.resolveTask(db, p.taskKey);
|
||
await core.updateTask(db, await ref(), { status: "in_progress", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
|
||
const repo = `${proj.giteaOwner}/${proj.giteaRepo}`;
|
||
return {
|
||
p,
|
||
proj,
|
||
ref,
|
||
pr: pr.number,
|
||
repo,
|
||
hook(event, payload) {
|
||
const body = JSON.stringify({ repository: { full_name: repo }, ...payload });
|
||
const signature = createHmac("sha256", core.projectHookSecret(proj.id)).update(body).digest("hex");
|
||
return runner.handleGiteaHook(db, { event, signature, body });
|
||
},
|
||
};
|
||
}
|
||
|
||
const issuePayload = (t: GitTask, i: { number: number; title: string; body: string; author: string }, action = "opened") => ({
|
||
action,
|
||
number: i.number,
|
||
issue: { number: i.number, title: i.title, body: i.body, html_url: `${gitea.url}/${t.repo}/issues/${i.number}`, user: { login: i.author } },
|
||
sender: { login: i.author },
|
||
});
|
||
|
||
const prComment = (t: GitTask, from: string, body: string) => ({
|
||
action: "created",
|
||
is_pull: true,
|
||
issue: { number: t.pr, title: "PR", pull_request: { merged: false } },
|
||
comment: { body, user: { login: from }, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}#issuecomment-1` },
|
||
sender: { login: from },
|
||
});
|
||
|
||
const action = (r: Awaited<ReturnType<typeof runner.handleGiteaHook>>) => (r.body as { action: string }).action;
|
||
|
||
describe("Issues становятся стори", () => {
|
||
test("Scenario: Участник открыл issue — стори в бэклоге со ссылкой, комментарий в issue", async () => {
|
||
const t = await gitTask();
|
||
const issue = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Экспорт в CSV", "mock-pm", "Нужна кнопка");
|
||
const r = await t.hook("issues", issuePayload(t, { ...issue, author: "mock-pm" }));
|
||
assert.equal(r.status, 200);
|
||
assert.equal(action(r), "imported");
|
||
const key = (r.body as { task: string }).task;
|
||
const story = await core.resolveTask(db, key);
|
||
assert.equal(story.task.title, "Экспорт в CSV");
|
||
assert.equal(story.task.status, "backlog");
|
||
assert.equal(story.task.giteaIssue, issue.number);
|
||
assert.match(story.task.description!, /Нужна кнопка[\s\S]*issues\/100/);
|
||
assert.equal(issue.comments.length, 1);
|
||
assert.equal(issue.comments[0]!.author, BOT.login);
|
||
assert.match(issue.comments[0]!.body, new RegExp(`Стори ${key} в Peppa FACTORY: .*/t/${key}`));
|
||
assert.match((await core.reviewPreview(db, story)).issueUrl!, /\/issues\/100$/);
|
||
// Redelivery (or "reopened") doesn't duplicate.
|
||
assert.equal(action(await t.hook("issues", issuePayload(t, { ...issue, author: "mock-pm" }, "reopened"))), "exists");
|
||
assert.equal(issue.comments.length, 1);
|
||
});
|
||
|
||
test("Scenario: Чужой issue — стори не создаётся; бот и подделка подписи тоже", async () => {
|
||
const t = await gitTask();
|
||
const before = (await core.listTasks(db, { projectId: t.proj.id })).length;
|
||
assert.equal(action(await t.hook("issues", issuePayload(t, { number: 100, title: "spam", body: "", author: "random-user" }))), "no_access");
|
||
assert.equal(action(await t.hook("issues", issuePayload(t, { number: 101, title: "bot", body: "", author: BOT.login }))), "none");
|
||
const forged = await runner.handleGiteaHook(db, { event: "issues", signature: "deadbeef", body: JSON.stringify({ repository: { full_name: t.repo }, ...issuePayload(t, { number: 102, title: "x", body: "", author: "mock-pm" }) }) });
|
||
assert.equal(forged.status, 401);
|
||
assert.equal((await core.listTasks(db, { projectId: t.proj.id })).length, before);
|
||
});
|
||
|
||
test("Scenario: Стори готова — issue закрыт с комментарием; разовый импорт открытых issues", async () => {
|
||
const t = await gitTask();
|
||
const a = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Старый баг", "someone");
|
||
const b = gitea.addIssue(t.proj.giteaOwner, t.proj.giteaRepo, "Ещё один", "mock-pm");
|
||
const out = await runner.importIssues(db, t.proj);
|
||
assert.deepEqual(out.map((x) => x.created), [true, true]);
|
||
assert.deepEqual((await runner.importIssues(db, t.proj)).map((x) => x.created), [false, false]);
|
||
const story = await core.resolveTask(db, out[0]!.key);
|
||
await runner.moveTask(db, story, "done");
|
||
assert.equal(a.state, "closed");
|
||
assert.match(a.comments.at(-1)!.body, new RegExp(`Стори ${out[0]!.key} готова`));
|
||
assert.equal(b.state, "open");
|
||
});
|
||
});
|
||
|
||
describe("Комментарии в PR уходят агенту", () => {
|
||
test("Scenario: Комментарий в PR — агент получает текст, стори снова в работе", async () => {
|
||
const t = await gitTask([[{ say: "PR открыт" }], [{ say: "исправляю" }]]);
|
||
const id = await t.p.start();
|
||
await t.p.waitLog("agent started", (e) => e.ev === "prompt");
|
||
await core.updateTask(db, await t.ref(), { status: "review" });
|
||
const r = await t.hook("issue_comment", prComment(t, "mock-pm", "Переименуй кнопку"));
|
||
assert.equal(action(r), "agent");
|
||
await t.p.waitLog("comment delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("Переименуй кнопку") && String(e.prompt).includes("mock-pm"));
|
||
assert.equal((await t.ref()).task.status, "in_progress");
|
||
await runner.stopSession(db, id);
|
||
});
|
||
|
||
test("review «changes requested» with no live runner starts the agent; approval is ignored", async () => {
|
||
const t = await gitTask([[{ say: "чиню" }]]);
|
||
await core.updateTask(db, await t.ref(), { status: "review" });
|
||
const pull = { number: t.pr, merged: false, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}`, head: { ref: `task/${t.p.taskKey}` } };
|
||
assert.equal(action(await t.hook("pull_request_approved", { action: "reviewed", pull_request: pull, review: { type: "pull_request_review_approved", content: "LGTM" }, sender: { login: "mock-pm" } })), "none");
|
||
assert.equal((await t.ref()).task.status, "review");
|
||
const r = await t.hook("pull_request_rejected", { action: "reviewed", pull_request: pull, review: { type: "pull_request_review_rejected", content: "Нет тестов" }, sender: { login: "mock-pm" } });
|
||
assert.equal(action(r), "restarted");
|
||
await t.p.waitLog("review delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("Нет тестов") && String(e.prompt).includes("просит изменений"));
|
||
assert.equal((await t.ref()).task.status, "in_progress");
|
||
for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id);
|
||
});
|
||
|
||
test("Scenario: Комментарий бота — агенту ничего; чужой комментатор тоже", async () => {
|
||
const t = await gitTask();
|
||
await core.updateTask(db, await t.ref(), { status: "review" });
|
||
assert.equal(action(await t.hook("issue_comment", prComment(t, BOT.login, "Стори готова"))), "none");
|
||
assert.equal(action(await t.hook("issue_comment", prComment(t, "random-user", "сделай мне ещё"))), "no_access");
|
||
assert.equal((await t.ref()).task.status, "review");
|
||
assert.equal((await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })).length, 0);
|
||
});
|
||
});
|
||
|
||
describe("Мерж руками закрывает стори", () => {
|
||
test("Scenario: PM смержил PR в Gitea — стори «Готово», «готово к ревью» закрыто", async () => {
|
||
const t = await gitTask();
|
||
const ref = await t.ref();
|
||
await core.updateTask(db, ref, { status: "review" });
|
||
const q = await core.askPm(db, ref, { kind: "attention", text: `✅ Стори ${ref.key} готова к ревью` });
|
||
const pull = { number: t.pr, merged: true, html_url: `${gitea.url}/${t.repo}/pulls/${t.pr}`, head: { ref: `task/${t.p.taskKey}` } };
|
||
assert.equal(action(await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: { ...pull, merged: false }, sender: { login: "mock-pm" } })), "none");
|
||
assert.equal((await t.ref()).task.status, "review");
|
||
const r = await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: pull, sender: { login: "mock-pm" } });
|
||
assert.equal(action(r), "done");
|
||
assert.equal((await t.ref()).task.status, "done");
|
||
const closed = await core.getQuestion(db, q.id);
|
||
assert.ok(closed.answeredAt);
|
||
assert.match(closed.answer!, /Изменения приняты в код проекта/);
|
||
// A redelivery does nothing.
|
||
assert.equal(action(await t.hook("pull_request", { action: "closed", number: t.pr, pull_request: pull, sender: { login: "mock-pm" } })), "none");
|
||
});
|
||
|
||
test("the project webhook subscribes to issues, comments and reviews", () => {
|
||
for (const e of ["issues", "issue_comment", "pull_request_comment", "pull_request_review", "pull_request", "push"]) assert.ok(runner.GITEA_HOOK_EVENTS.includes(e), e);
|
||
});
|
||
});
|