139 lines
9.5 KiB
TypeScript
139 lines
9.5 KiB
TypeScript
// PEP-302: findings of the acceptance agent past the daily limit do not disappear: a breakage goes
|
||
// to «Предложено» the same day, an improvement waits in «Отложено» (board) and both are named in
|
||
// the message to the owner; the weekly digest keeps everything and says what is left.
|
||
import { stripAsIs } from "@peppa/shared/i18n";
|
||
import assert from "node:assert/strict";
|
||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||
import { createServer, type Server } from "node:http";
|
||
import type { AddressInfo } from "node:net";
|
||
import { tmpdir } from "node:os";
|
||
import { join, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, runner, teardown } from "./helpers.ts";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
process.env.PEPPA_WEB_URL = "http://peppa.test";
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
const TMP = mkdtempSync(join(tmpdir(), "peppa-deferred-"));
|
||
const scenario = join(TMP, "scenario.json");
|
||
const found = (...stories: Array<{ title: string; severity: string }>) =>
|
||
writeFileSync(scenario, JSON.stringify({ accept: { summary: "Продукт открывается.", howto: [], not_real: [], needs: [], stories: stories.map((x) => ({ description: "Что должен увидеть пользователь.", ...x })) } }));
|
||
|
||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let pm: User;
|
||
let server: Server;
|
||
let n = 0;
|
||
let sha = 0;
|
||
|
||
async function proj() {
|
||
n++;
|
||
const ws = join(TMP, `ws-${n}`);
|
||
mkdirSync(join(ws, ".peppa"), { recursive: true });
|
||
const p = await core.createProject(db, { slug: `mock-def-${n}`, key: `MDF${String.fromCharCode(64 + n)}`, name: `Сад ${n}`, giteaOwner: "x", giteaRepo: `mock-def-${n}`, workspacePath: ws, ownerId: pm.id });
|
||
await core.setIntakeSettings(db, p.id, { enabled: true });
|
||
// The owner still waits for something: the version is not finished, findings are filed.
|
||
await core.createTask(db, { projectId: p.id, title: "Просьба владельца" });
|
||
return p;
|
||
}
|
||
const pass = async (p: { key: string }) => {
|
||
const project = await core.getProject(db, p.key);
|
||
await runner.recordRelease(db, project, { env: "staging", sha: `sha${++sha}00000`, status: "healthy", host: "staging.mock.test", previousSha: null, commits: [] });
|
||
await runner.productReviewTick(db, { wait: true, log: (m) => process.env.DBG && console.log(m) });
|
||
};
|
||
const chat = async (projectId: number) => (await core.discussionMessages(db, (await core.ensureProjectChat(db, projectId)).id)).map((m) => stripAsIs(m.text));
|
||
const byTitle = async (projectId: number, title: string) => (await core.listTasks(db, { projectId, includeArchived: true })).find((t) => t.title === title);
|
||
// Different words: the mock repeat check calls similar titles one story.
|
||
const IDEAS = ["Тёмная тема", "Экспорт в таблицу", "Поиск по саду", "Крупный шрифт", "Звук уведомления", "Печать отчёта", "Аватар садовника", "Календарь полива"];
|
||
/** Five stories not from a person in the last 24 hours: the daily limit is spent. */
|
||
const spendLimit = async (projectId: number) => {
|
||
for (let i = 1; i <= 5; i++) await core.createTask(db, { projectId, title: `Идея агента ${i}`, origin: "agent" });
|
||
assert.equal((await core.proposalRoom(db, projectId)).room, 0);
|
||
};
|
||
|
||
before(async () => {
|
||
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
|
||
process.env.MOCK_INTAKE_SCENARIO = scenario;
|
||
pm = await core.upsertUserFromGitea(db, { id: 1302, login: "dana" }, { access_token: "x" });
|
||
server = createServer((_req, res) => void res.writeHead(200, { "content-type": "text/html" }).end("<h1>Сад</h1><button>Спросить</button>"));
|
||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||
process.env.PEPPA_PRODUCT_FETCH_BASE = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||
});
|
||
after(async () => {
|
||
server.close();
|
||
await teardown();
|
||
});
|
||
|
||
describe("PEP-302: отложенные находки приёмки", () => {
|
||
test("Scenario: Шестая находка-поломка за сутки — в «Предложено», шестое улучшение — в «Отложено», обе в сообщении", async () => {
|
||
const p = await proj();
|
||
await spendLimit(p.id);
|
||
found({ title: "Ростик не отвечает на свободный вопрос", severity: "breakage" }, { title: "Подписать кнопку «Спросить»", severity: "important" });
|
||
await pass(p);
|
||
|
||
const broken = await byTitle(p.id, "Ростик не отвечает на свободный вопрос");
|
||
assert.ok(broken, "a breakage is filed past the daily limit");
|
||
assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", true, "breakage", "backlog"], "it waits for «Делать» (PEP-295)");
|
||
assert.deepEqual((await runner.readyBacklog(db, p.id)).filter((t) => t.id === broken.id), [], "the dispatcher does not take it");
|
||
assert.equal(await byTitle(p.id, "Подписать кнопку «Спросить»"), undefined);
|
||
const deferred = await core.deferredFindings(db, p.id);
|
||
assert.deepEqual(deferred.items.map((i) => i.title), ["Подписать кнопку «Спросить»"]);
|
||
|
||
const msg = (await chat(p.id)).find((t) => /Агент приёмки посмотрел/.test(t))!;
|
||
assert.match(msg, new RegExp(`${p.key}-\\d+ «Ростик не отвечает на свободный вопрос» — Поломка`));
|
||
assert.match(msg, /Отложено до сводки: 1, из них поломок 0\./);
|
||
assert.match(msg, /«Предложено» → «Отложено»: http:\/\/peppa\.test\/p\//);
|
||
});
|
||
|
||
test("Scenario: 25 отложенных находок не теряются; «Делать» и «Не надо» с доски", async () => {
|
||
const p = await proj();
|
||
await spendLimit(p.id);
|
||
for (let pass5 = 0; pass5 < 5; pass5++) {
|
||
found(...Array.from({ length: 5 }, (_, i) => ({ title: `Улучшение номер ${pass5 * 5 + i + 1}`, severity: i % 2 ? "minor" : "important" })));
|
||
await pass(p);
|
||
}
|
||
const { items } = await core.deferredFindings(db, p.id);
|
||
assert.equal(items.length, 25, "nothing is pushed out");
|
||
assert.deepEqual(new Set(items.map((i) => i.title)), new Set(Array.from({ length: 25 }, (_, i) => `Улучшение номер ${i + 1}`)));
|
||
assert.ok(items.every((i) => i.at), "each item knows when it was put aside");
|
||
assert.ok((await chat(p.id)).some((t) => /Отложено до сводки: 25, из них поломок 0\./.test(t)));
|
||
|
||
// «Делать» — straight to the backlog: a person decided.
|
||
const key = await runner.decideDeferred(db, pm, p.id, "Улучшение номер 3", "do");
|
||
const made = (await byTitle(p.id, "Улучшение номер 3"))!;
|
||
assert.equal(`${p.key}-${made.number}`, key);
|
||
assert.deepEqual([made.origin, made.proposed, made.status], ["acceptance", false, "backlog"]);
|
||
// «Не надо» — gone and never suggested again.
|
||
await runner.decideDeferred(db, pm, p.id, "Улучшение номер 4", "no");
|
||
assert.ok((await core.rejectedTitles(db, p.id)).includes(core.normTitle("Улучшение номер 4")));
|
||
assert.equal((await core.deferredFindings(db, p.id)).items.length, 23);
|
||
await assert.rejects(runner.decideDeferred(db, pm, p.id, "Улучшение номер 3", "do"), /решение уже принято/);
|
||
// Someone without access to the project cannot decide.
|
||
const stranger = await core.upsertUserFromGitea(db, { id: 1303, login: "stranger302" }, { access_token: "x" });
|
||
await assert.rejects(runner.decideDeferred(db, stranger, p.id, "Улучшение номер 5", "do"));
|
||
});
|
||
|
||
test("Scenario: Старая поломка в сводке переносится в «Предложено»; сводка говорит, сколько осталось", async () => {
|
||
const p = await proj();
|
||
// Put aside by the rule before PEP-302: a breakage and 8 improvements in the digest.
|
||
await core.setDigest(db, p.id, {
|
||
items: [{ title: "Сайт падает после входа", description: "Падает.", severity: "breakage" }, ...IDEAS.map((title) => ({ title, description: "Мелочь.", severity: "minor" as const }))],
|
||
sentAt: new Date().toISOString(),
|
||
});
|
||
await runner.productDigestTick(db, new Date());
|
||
const broken = (await byTitle(p.id, "Сайт падает после входа"))!;
|
||
assert.equal(broken.proposed, true);
|
||
assert.equal((await core.deferredFindings(db, p.id)).breakage, 0);
|
||
assert.equal((await core.deferredFindings(db, p.id)).items.length, 8, "the week is not out: improvements wait");
|
||
assert.ok((await chat(p.id)).some((t) => /Поломки, которые ждали сводки, — в «Предложено»: 1\./.test(t)));
|
||
|
||
// A week later: 5 per pass (and 4 left of the day — one went to the breakage), the rest stays and is counted.
|
||
await runner.productDigestTick(db, new Date(Date.now() + 8 * 86_400_000));
|
||
const filed = (await core.listTasks(db, { projectId: p.id })).filter((t) => IDEAS.includes(t.title));
|
||
const left = (await core.deferredFindings(db, p.id)).items.length;
|
||
assert.equal(filed.length + left, 8, "nothing lost");
|
||
assert.ok(left > 0);
|
||
assert.ok((await chat(p.id)).some((t) => new RegExp(`Осталось отложенными: ${left} — они на доске`).test(t)));
|
||
});
|
||
});
|