106 lines
6.9 KiB
TypeScript
106 lines
6.9 KiB
TypeScript
// PEP-220: work journals live a day; business history and state of open stories stay.
|
||
// Tests are named after the spec scenarios.
|
||
import assert from "node:assert/strict";
|
||
import { after, describe, test } from "node:test";
|
||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||
import { core, db, teardown } from "./helpers.ts";
|
||
import { checkRuns, events, pushOutbox, releases, runnerCommands, settings, telegramOutbox, telegramUpdates } from "@peppa/db";
|
||
import { eq, sql } from "drizzle-orm";
|
||
|
||
after(teardown);
|
||
const DAY = 86_400_000;
|
||
const NOW = new Date("2026-11-20T12:00:00Z");
|
||
const old = new Date(NOW.getTime() - 2 * DAY);
|
||
const fresh = new Date(NOW.getTime() - 3_600_000);
|
||
let seq = 0;
|
||
|
||
async function fixture() {
|
||
const key = `R${String.fromCharCode(65 + seq++)}`;
|
||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: null });
|
||
const t = await core.createTask(db, { projectId: p.id, title: `Задача ${key}`, description: "x" });
|
||
return { p, taskId: t.task.id };
|
||
}
|
||
const count = async (table: Parameters<typeof db.select>[0] extends never ? never : any, where?: any) =>
|
||
Number((await db.select({ n: sql<number>`count(*)` }).from(table).where(where))[0]!.n);
|
||
|
||
describe("PEP-220 retention", () => {
|
||
test("Scenario: Шаги агента старше суток удаляются, свежие и деловые остаются", async () => {
|
||
const { p, taskId } = await fixture();
|
||
const ev = (type: string, createdAt: Date) => ({ projectId: p.id, taskId, type, payload: {}, createdAt });
|
||
await db.insert(events).values([ev("step", old), ev("turn_end", old), ev("step", fresh), ev("task_updated", old), ev("question_answered", old), ev("subscription_switched", old)]);
|
||
const r = await core.runRetention(db, { now: NOW });
|
||
assert.ok(r.deleted.events! >= 2);
|
||
const left = (await db.select().from(events).where(eq(events.projectId, p.id))).map((e) => e.type).sort();
|
||
assert.deepEqual(left, ["question_answered", "step", "subscription_switched", "task_updated"]);
|
||
});
|
||
|
||
test("Scenario: Хвост лога стирается, но у последнего прогона открытой задачи остаётся", async () => {
|
||
const { p, taskId } = await fixture();
|
||
const row = (check: string, sha: string, updatedAt: Date) => ({ projectId: p.id, taskId, sha, check, state: "success" as const, logTail: "log", updatedAt, createdAt: updatedAt });
|
||
await db.insert(checkRuns).values([row("lint", "a1", old), row("lint", "b2", old), row("test", "a1", old)]);
|
||
await core.runRetention(db, { now: NOW });
|
||
const rows = await db.select().from(checkRuns).where(eq(checkRuns.projectId, p.id));
|
||
assert.equal(rows.length, 3, "строки остаются");
|
||
const kept = rows.filter((r) => r.logTail).map((r) => `${r.check}:${r.sha}`).sort();
|
||
assert.deepEqual(kept, ["lint:b2", "test:a1"]);
|
||
});
|
||
|
||
test("Scenario: Хвост лога выкладки стирается, у новейшей выкладки окружения остаётся", async () => {
|
||
const { p } = await fixture();
|
||
const rel = (sha: string, updatedAt: Date) => ({ projectId: p.id, env: "staging" as const, sha, logTail: "tail", updatedAt, createdAt: updatedAt });
|
||
await db.insert(releases).values([rel("s1", old), rel("s2", old)]);
|
||
await core.runRetention(db, { now: NOW });
|
||
const rows = await db.select().from(releases).where(eq(releases.projectId, p.id));
|
||
assert.equal(rows.length, 2);
|
||
assert.deepEqual(rows.filter((r) => r.logTail).map((r) => r.sha), ["s2"]);
|
||
});
|
||
|
||
test("Scenario: Отправленные очереди, команды и обновления Telegram старше суток удаляются", async () => {
|
||
await db.insert(telegramOutbox).values([
|
||
{ dedupeKey: "ret:old", method: "sendMessage", params: {}, status: "sent", createdAt: old },
|
||
{ dedupeKey: "ret:pending", method: "sendMessage", params: {}, status: "pending", createdAt: old },
|
||
{ dedupeKey: "ret:fresh", method: "sendMessage", params: {}, status: "sent", createdAt: fresh },
|
||
]);
|
||
await db.insert(pushOutbox).values([{ dedupeKey: "ret:p-old", payload: {}, status: "sent", createdAt: old }, { dedupeKey: "ret:p-new", payload: {}, status: "pending", createdAt: old }]);
|
||
await db.insert(runnerCommands).values([{ kind: "x", payload: {}, status: "done", createdAt: old }, { kind: "x", payload: {}, status: "queued", createdAt: old }]);
|
||
await db.insert(telegramUpdates).values([{ updateId: 990001, status: "done", createdAt: old }, { updateId: 990002, status: "done", createdAt: fresh }]);
|
||
await core.runRetention(db, { now: NOW });
|
||
const keys = (await db.select().from(telegramOutbox)).map((r) => r.dedupeKey);
|
||
assert.ok(!keys.includes("ret:old") && keys.includes("ret:pending") && keys.includes("ret:fresh"));
|
||
assert.deepEqual((await db.select().from(pushOutbox)).map((r) => r.dedupeKey), ["ret:p-new"]);
|
||
assert.deepEqual((await db.select().from(runnerCommands)).map((r) => r.status), ["queued"]);
|
||
assert.deepEqual((await db.select().from(telegramUpdates)).map((r) => r.updateId), [990002]);
|
||
});
|
||
|
||
test("Scenario: Временные строки настроек убираются, обычные настройки остаются", async () => {
|
||
await db.insert(settings).values([
|
||
{ key: "egov.flow:ret", value: {}, updatedAt: old },
|
||
{ key: "auth.fail:ret", value: {}, updatedAt: old },
|
||
{ key: "egov.flow:ret-new", value: {}, updatedAt: fresh },
|
||
{ key: "project.autonomy:ret", value: {}, updatedAt: old },
|
||
]);
|
||
await core.runRetention(db, { now: NOW });
|
||
const keys = (await db.select().from(settings)).map((s) => s.key).filter((k) => k.includes("ret") && k !== "retention.last");
|
||
assert.deepEqual(keys.sort(), ["egov.flow:ret-new", "project.autonomy:ret"]);
|
||
});
|
||
|
||
test("Scenario Outline: Пачка не больше 5000, остаток уходит со следующим проходом", async () => {
|
||
const { p } = await fixture();
|
||
const rows = Array.from({ length: core.BATCH * 21 + 3 }, () => ({ projectId: p.id, type: "step", payload: {}, createdAt: old }));
|
||
for (let i = 0; i < rows.length; i += 5000) await db.insert(events).values(rows.slice(i, i + 5000));
|
||
const first = await core.runRetention(db, { now: NOW });
|
||
assert.equal(first.deleted.events, core.BATCH * 20);
|
||
const second = await core.runRetention(db, { now: NOW });
|
||
assert.equal(second.deleted.events, core.BATCH + 3);
|
||
});
|
||
|
||
test("Scenario: Срок меняется настройкой platform.retention", async () => {
|
||
const { p } = await fixture();
|
||
await core.setRetention(db, { workDays: 5 });
|
||
await db.insert(events).values({ projectId: p.id, type: "step", payload: {}, createdAt: old });
|
||
await core.runRetention(db, { now: NOW });
|
||
assert.equal(await count(events, eq(events.projectId, p.id)), 1);
|
||
await core.setRetention(db, {});
|
||
});
|
||
});
|