diff --git a/.peppa/memory.md b/.peppa/memory.md index c180bff6..87f896d8 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -1,43 +1,45 @@ # Память проекта -Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения. +Пишет агент через MCP `remember` (PEP-30). ## Команды -- Экраны без живых данных: `PEPPA_HOME= PEPPA_DB=/peppa.db PEPPA_SECRET=x peppa db migrate`, `DATABASE_URL=/peppa.db node apps/web/scripts/mock-ui-seed.ts mock-pm` (принимает путь SQLite, шапка про Postgres устарела), `next dev -p <порт>` в apps/web с тем же env и `PEPPA_WEB_URL`, `peppa web login-link mock-pm`; страницы — curl с cookie (текст без `')], + ["page.html", Buffer.from("")], + ["fake.txt", Buffer.from("")], + ["run.sh", Buffer.from("#!/bin/sh\nrm -rf /\n")], + ["fake.txt", Buffer.from("#!/bin/sh\nrm -rf /\n")], + ["a.zip", zip(["a.txt"])], + ["app.exe", Buffer.concat([Buffer.from("MZ"), Buffer.alloc(64, 1)])], + ["bin.txt", Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0, 0, 0])], + ["notes.json", Buffer.from("{не json")], + ]; + for (const [name, data] of bad) assert.throws(() => core.sniffAttachment(data, name), /не принят/, name); + await assert.rejects(upload("logo.svg", bad[0]![1]), /не принят.*картинку.*PDF/s); + assert.equal((await db.select().from((await import("@peppa/db")).attachments)).length, 0, "nothing saved"); + }); + + test("Scenario: файл больше 20 МБ — понятная ошибка", async () => { + await assert.rejects(upload("big.png", Buffer.concat([PNG, Buffer.alloc(20 * 1024 * 1024)])), /больше 20 МБ/); + }); +}); + +describe("PEP-159: access", () => { + test("Scenario: посторонний не открывает файл чужого проекта", async () => { + const a = await upload("макет.png", PNG); + const mine = await core.attachmentForUser(db, pm, a.id); + assert.ok(mine && existsSync(mine.path) && mine.path.includes(`/files/${proj.id}/${a.id}/`), "stored under files///"); + assert.equal(await core.attachmentForUser(db, stranger, a.id), null, "outsider: not found"); + await assert.rejects(upload("x.png", PNG, stranger), /Не найдено/, "and cannot upload into the project either"); + }); + + test("Scenario: чужой файл нельзя привязать к своему сообщению", async () => { + const a = await upload("секрет.png", PNG); + await assert.rejects(core.linkAttachments(db, stranger, proj.id, [a.id], { taskId: 1 }), /Файл не найден/); + await assert.rejects(core.linkAttachments(db, pm, proj.id + 999, [a.id], { taskId: 1 }), /Файл не найден/, "nor into another project"); + }); +}); + +describe("PEP-159: chat with the analyst", () => { + test("Scenario: приложенные PDF, картинка и текст доходят до аналитика", async () => { + const files = [await upload("макет.png", PNG), await upload("тз.pdf", PDF), await upload("требования.txt", TXT), await upload("тз.docx", DOCX)]; + const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "Посмотрите файлы", via: "web", attachmentIds: files.map((f) => f.id) }); + const shown = (await core.attachmentsByMessage(db, [message.id])).get(message.id)!; + assert.deepEqual(shown.map((f) => [f.name, f.kind]), [["макет.png", "image"], ["тз.pdf", "pdf"], ["требования.txt", "text"], ["тз.docx", "office"]]); + await runner.analystChatTick(db, { wait: true }); + const c = calls().filter((x) => x.role === "chat").at(-1)!; + assert.deepEqual(c.files!.filter((f) => f.startsWith("file-")).sort(), [`file-${files[0]!.id}.png`, `file-${files[1]!.id}.pdf`], "image and PDF are files in the call's directory"); + assert.match(c.prompt, /«макет.png» \(\d+ B\) — картинка, файл file-\d+\.png/); + assert.match(c.prompt, /«требования.txt»[^\n]* — текстовый файл:\n---\nТребования заказчика:\n- кнопка «Купить» зелёная/, "text files go in as content"); + assert.match(c.prompt, /«тз.docx»[^\n]* документ Office/, "office files by name and type"); + }); + + test("Scenario: сообщение только с файлом получает подпись из имён", async () => { + const f = await upload("логотип.png", PNG); + const { message } = await runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web", attachmentIds: [f.id] }); + assert.equal(message.text, "📎 логотип.png"); + await assert.rejects(runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text: "", via: "web" }), /Пустое сообщение/); + }); + + test("Scenario: больше пяти файлов не принимается", () => { + assert.throws(() => core.parseAttachmentIds([1, 2, 3, 4, 5, 6]), /не больше 5/); + }); +}); + +describe("PEP-159: story comment and the story's agent", () => { + test("Scenario: файл комментария к стори в бэклоге уходит аналитику", async () => { + const ref = await core.createTask(db, { projectId: proj.id, title: "Корзина", description: "Покупатель складывает товары в корзину" }); + const f = await upload("скриншот.png", PNG); + const c = await core.addStoryComment(db, ref, pm, "Вот как должно выглядеть"); + await core.linkAttachments(db, pm, proj.id, [f.id], { taskId: ref.task.id, eventId: c.id }); + await runner.storyRefineTick(db, { wait: true }); + const call = calls().filter((x) => x.role === "refine").at(-1)!; + assert.ok(call.files!.includes(`file-${f.id}.png`)); + assert.match(call.prompt, /«скриншот.png»/); + assert.equal((await core.attachmentsByEvent(db, [c.id])).get(c.id)![0]!.name, "скриншот.png", "shown under the comment"); + }); + + test("Scenario: агент находит файлы в .peppa/attachments/ и в get_task", async () => { + const p = await mockProject({ turns: [[{ mcp: "get_task", args: { task: "1" } }, { say: "ok" }]] }); + const pr = await core.getProject(db, p.key); + const ref = await core.resolveTask(db, p.taskKey); + const a = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "ТЗ клиента.pdf", data: PDF }); + const own = await core.saveAttachment(db, { id: pr.ownerId! }, { projectId: pr.id, name: "лого.png", data: PNG }); + const c = await core.addStoryComment(db, ref, { id: pr.ownerId!, login: "asel" }, "Вот ТЗ от клиента"); + await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [a.id], { taskId: ref.task.id, eventId: c.id }); + await core.linkAttachments(db, { id: pr.ownerId! }, pr.id, [own.id], { taskId: ref.task.id }); + const sid = await p.start(); + const dir = join(p.dir, ".peppa/attachments"); + await waitFor("files copied", async () => existsSync(dir) && readdirSync(dir).length >= 3); + assert.deepEqual(readdirSync(dir).sort(), [".gitignore", `${a.id}-ТЗ_клиента.pdf`, `${own.id}-лого.png`].sort()); + assert.equal(readFileSync(join(dir, ".gitignore"), "utf8"), "*\n", "never committed"); + const text = formatTask(await core.getTaskDetails(db, ref)); + assert.match(text, new RegExp(`## Приложенные файлы\\n- \`.peppa/attachments/${a.id}-ТЗ_клиента.pdf\` — «ТЗ клиента.pdf» \\(application/pdf, \\d+ B\\), приложил asel: Вот ТЗ от клиента`)); + assert.match(text, /`.peppa\/attachments\/\d+-лого.png` — «лого.png»/); + await runner.stopSession(db, sid); + }); + + test("Scenario: неотправленные файлы старше суток удаляются", async () => { + const f = await upload("забытый.png", PNG); + const found = (await core.attachmentForUser(db, pm, f.id))!; + assert.equal(await core.pruneAttachments(db, new Date()), 0, "fresh ones stay"); + assert.ok(await core.pruneAttachments(db, new Date(Date.now() + 25 * 3600_000)) >= 1); + assert.equal(existsSync(found.path), false); + assert.equal(await core.attachmentForUser(db, pm, f.id), null); + }); +}); diff --git a/packages/testkit/test/autonomy.test.ts b/packages/testkit/test/autonomy.test.ts index 06330323..ba64e6ac 100644 --- a/packages/testkit/test/autonomy.test.ts +++ b/packages/testkit/test/autonomy.test.ts @@ -29,7 +29,9 @@ describe("autonomous cycle", () => { const sid = await p.start(); const review = await p.waitQuestion(sid, "attention"); assert.match(review.text, /готова к ревью/); - assert.match(review.text, /pr\/7/); + // PEP-152: the address of the result is a technical detail — under «Подробнее». + assert.doesNotMatch(review.text, /pr\/7/); + assert.match((await core.messageDetails(db, [review.id])).get(review.id) ?? "", /pr\/7/); assert.equal(await nudges(sid), 1, "the agent was nudged once instead of pinging the PM"); assert.ok(p.log().some((e) => e.ev === "continue"), "mock continued via the Stop hook"); const qs = await db.select().from(questions).where(eq(questions.sessionId, sid)); diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts index a9f1e97d..6f8f7297 100644 --- a/packages/testkit/test/bot.test.ts +++ b/packages/testkit/test/bot.test.ts @@ -204,7 +204,7 @@ describe("staleness and reliability", () => { const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); const m = await messageFor(q.id); - await runner.sendToSession(db, sid, "порт 9000"); + await runner.sendToSession(db, sid, "порт 9000", { person: true }); await waitFor("closed as answered in terminal", async () => /Ответ в терминале/.test(m.text)); const cb = tg.userClicks(PM, m.message_id, `q:${q.id}:o0`); await waitFor("stale toast", async () => tg.callbackAnswers.find((a) => a.id === cb && /Уже отвечено/.test(a.text ?? ""))); diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts index 0baf4e8f..9c38b55a 100644 --- a/packages/testkit/test/cjm.test.ts +++ b/packages/testkit/test/cjm.test.ts @@ -53,7 +53,9 @@ describe("Claude: task lifecycle", () => { assert.equal(doneAttempt?.isError, true, "agent must not be able to mark the task done"); const attention = await p.waitQuestion(sid, "attention"); - assert.match(attention.text, /PR открыт/); + // PEP-152: «готово» in the common format; the agent's last reply is under «Подробнее». + assert.match(attention.text, /готова к ревью\nЧто нужно от вас: /); + assert.match((await core.messageDetails(db, [attention.id])).get(attention.id) ?? "", /PR открыт/); await runner.stopSession(db, sid); }); @@ -132,7 +134,7 @@ describe("Claude: questions to the PM", () => { const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] }); const sid = await p.start(); const q = await p.waitQuestion(sid, "question"); - await runner.sendToSession(db, sid, "назови peppa-api"); + await runner.sendToSession(db, sid, "назови peppa-api", { person: true }); await waitFor("answered via terminal", async () => (await core.getQuestion(db, q.id)).answeredVia === "terminal"); assert.equal((await core.getQuestion(db, q.id)).answer, "назови peppa-api"); await runner.stopSession(db, sid); diff --git a/packages/testkit/test/claude-live.test.ts b/packages/testkit/test/claude-live.test.ts index 96d26177..4b2f055d 100644 --- a/packages/testkit/test/claude-live.test.ts +++ b/packages/testkit/test/claude-live.test.ts @@ -193,7 +193,10 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", () // PEP-149: the last reply becomes a progress record — the PM is not asked. assert.deepEqual(await p.pending(sid), []); const [progress] = await db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, "progress"))); - assert.equal((progress!.payload as { text: string }).text, fixture("stop-after-block").last_assistant_message); + // PEP-152: in the common format — a plain reply is the gist, a technical one is under «Подробнее». + const said = progress!.payload as { text: string; details?: string }; + assert.ok(`${said.text}\n${said.details ?? ""}`.includes(String(fixture("stop-after-block").last_assistant_message).trim())); + assert.ok(said.text.split("\n").length <= core.MAIN_MAX_LINES); await runner.stopSession(db, sid); }); }); diff --git a/packages/testkit/test/discussion.test.ts b/packages/testkit/test/discussion.test.ts index f612717f..eafb88eb 100644 --- a/packages/testkit/test/discussion.test.ts +++ b/packages/testkit/test/discussion.test.ts @@ -99,4 +99,24 @@ describe("PEP-106: project discussion", () => { const rest = await core.chatMessagesView(db, chat.id, {}); assert.ok(rest.every((m) => m.kind === "user" && m.threadKey === null && !m.text.startsWith("/")), "events, threads and commands are pruned"); }); + + // PEP-161, spec project-chats: «Чат с аналитиком из раздела „Проекты“». + test("PEP-161: Ссылка на аналитика у своего проекта · Непрочитанный ответ аналитика виден на карточке", async () => { + await core.markDiscussionRead(db, owner.id, chat.id); + const before = (await core.analystLinks(db, owner)).get(project.id); + assert.deepEqual(before, { href: "/chats/MTLK", unread: 0 }); + await core.addChatMessage(db, { chatId: chat.id, kind: "user", authorKind: "agent", authorLogin: "Аналитик", text: "Готово: каталог открыт." }); + assert.deepEqual((await core.analystLinks(db, owner)).get(project.id), { href: "/chats/MTLK", unread: 1 }); + assert.equal((await core.analystLinks(db, member)).get(project.id)?.href, "/chats/MTLK", "a member writes to the analyst too"); + }); + + test("PEP-161: У чужого проекта ссылки нет", async () => { + await core.setPlatformAdmins(db, [stranger.login]); + try { + assert.ok((await core.listOtherProjects(db, stranger.id)).some((p) => p.key === "MTLK"), "the superadmin sees the project among other people's"); + assert.equal((await core.analystLinks(db, stranger)).size, 0); + } finally { + await core.setPlatformAdmins(db, null); + } + }); }); diff --git a/packages/testkit/test/factory-messages-verbatim.test.ts b/packages/testkit/test/factory-messages-verbatim.test.ts index dd1d2373..286c70b1 100644 --- a/packages/testkit/test/factory-messages-verbatim.test.ts +++ b/packages/testkit/test/factory-messages-verbatim.test.ts @@ -106,8 +106,11 @@ describe("бот: Telegram на английском", () => { const msg = await waitFor("ready for review in Telegram", async () => toPm().find((x) => x.text.includes("is ready for review"))); assert.ok(msg.text.includes(`${TITLE}`), msg.text); assert.ok(msg.text.includes(`✅ Task ${p.taskKey} is ready for review`), msg.text); - assert.ok(msg.text.includes(SAID), msg.text); - assert.doesNotMatch(msg.text.replace(TITLE, "").replace(SAID, ""), CYR, msg.text); + // PEP-152: the agent's last reply is a technical detail — not in Telegram, verbatim under «Подробнее». + assert.ok(!msg.text.includes(SAID), msg.text); + assert.ok((msg.text.match(/Where to look: /g) ?? []).length <= 1, msg.text); + assert.ok(localizeText("en", (await core.messageDetails(db, [q.id])).get(q.id) ?? "").includes(SAID)); + assert.doesNotMatch(msg.text.replace(TITLE, ""), CYR, msg.text); assert.doesNotMatch(msg.text, MARKS); await runner.stopSession(db, sid).catch(() => {}); }); diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index e500b1d5..f86496bb 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -31,6 +31,8 @@ Object.assign(process.env, { // PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with // accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on. PEPPA_PRODUCT_LINK: "off", + // PEP-168: no real HTTP probe of the live site :3100 from tests; monitor tests pass their own probe. + PEPPA_WEB_PROBE: "off", }); mkdirSync(process.env.PEPPA_HOME!, { recursive: true }); diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts index 11ebd45c..6705073a 100644 --- a/packages/testkit/test/limits.test.ts +++ b/packages/testkit/test/limits.test.ts @@ -19,6 +19,11 @@ describe("Время сброса лимита", () => { ["resets at 3:10 AM", "2026-11-13T03:10:00"], ["resets in 2h 15m", "2026-11-13T00:55:00"], ["try again at 23:30", "2026-11-12T23:30:00"], + // PEP-166: Claude Code's newer banner — the time was not read, a 30-minute probe made the + // subscription look free again while it stayed limited until the evening. + ["⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel", "2026-11-13T18:00:00"], + ["continuing automatically at 9:30 AM", "2026-11-13T09:30:00"], + ["continuing work on the task", null], ["limit reached", null], ] as const) { test(`Форматы времени сброса: «${text}»`, () => { @@ -27,6 +32,15 @@ describe("Время сброса лимита", () => { }); } + test("PEP-166: баннер лимита из истории возобновлённого разговора — не новый лимит", () => { + const old = "⏺ Usage limit reached · continuing automatically at 6pm · esc to cancel"; + const resumed = `> продолжай\n${old}\n⏺ Продолжаю работу над задачей…`; + assert.equal(runner.freshLimitLine(resumed, 1), null, "the old account's banner was there when the generation started"); + assert.equal(runner.freshLimitLine(`${resumed}\n⏺ Usage limit reached · resets 9pm`, 1), "⏺ Usage limit reached · resets 9pm", "a new banner after it counts"); + assert.equal(runner.freshLimitLine("⏺ Работаю…", 0), null); + assert.equal(runner.freshLimitLine(old, 0), old, "a generation that started clean sees its first banner"); + }); + test("Время сброса указано", async () => { const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Продолжаю после лимита." }]] }); const sid = await p.start(); @@ -114,6 +128,28 @@ describe("Защита от зацикливания", () => { }); }); +describe("Новая фраза Claude (PEP-166)", () => { + // Scenario: Новая фраза Claude — подписка в лимите до вечера + test("Новая фраза Claude — подписка в лимите до вечера", async () => { + const p = await project({ turns: [] }); + const sub = await core.createSubscription(db, { provider: "claude", name: "Claude — mock-asel", authKind: "oauth" }); + await core.updateSubscription(db, sub.id, { status: "active" }); + const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id, subscriptionId: sub.id })).id; + const now = at("2026-11-16T13:34:00"); + const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached · continuing automatically at 6pm", now); + const s = await sess(sid); + assert.equal(s.status, "rate_limited"); + assert.equal(s.resumeAt?.getTime(), at("2026-11-16T18:01:00").getTime(), "continues at the reset time + grace"); + assert.equal(s.limitProbeMin, null, "no 30-minute probe"); + assert.match(text ?? "", /продолжит в 18:01 сам/); + const limited = await core.getSubscription(db, sub.id); + assert.equal(limited.status, "limited"); + assert.equal(limited.limitedUntil?.getTime(), at("2026-11-16T18:00:00").getTime(), "limited until 18:00"); + assert.equal(core.isUsable(limited, at("2026-11-16T14:04:00")), false, "still limited half an hour later"); + assert.equal(core.isUsable(limited, at("2026-11-16T18:00:00")), true); + }); +}); + describe("Отключение", () => { test("Выключено", async () => { const p = await project({ turns: [] }); @@ -145,3 +181,10 @@ describe("Codex", () => { await runner.stopSession(db, sid); }); }); + +describe("PEP-171: запуск Codex без удалённого флага", () => { + test("по умолчанию — без подтверждений и песочницы, флага --full-auto нет", () => { + assert.equal(runner.CODEX_DEFAULT_MODE, "--sandbox danger-full-access --ask-for-approval never"); + assert.ok(!runner.CODEX_DEFAULT_MODE.includes("--full-auto")); + }); +}); diff --git a/packages/testkit/test/monitor.test.ts b/packages/testkit/test/monitor.test.ts index 8f72d6ed..6aea0ef0 100644 --- a/packages/testkit/test/monitor.test.ts +++ b/packages/testkit/test/monitor.test.ts @@ -2,7 +2,7 @@ // (controlled clock, mock-telegram, the real bot), `peppa status`. import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdtempSync } from "node:fs"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; @@ -55,7 +55,7 @@ before(async () => { await core.setAllowedLogins(db, [ADMIN.login, OTHER.login]); }); beforeEach(async () => { - db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key = 'platform.admins'`); + db.run(sql`delete from settings where key like 'heartbeat:%' or key like 'monitor.alert:%' or key like 'monitor.port:%' or key = 'platform.admins'`); await db.delete(telegramOutbox); await core.setPlatformAdmins(db, [ADMIN.login]); await pair(ADMIN.login, ADMIN.chatId, 9001); @@ -117,6 +117,82 @@ describe("Health-эндпоинт", () => { }); }); +describe("PEP-168: веб жив по heartbeat, но порт закрыт", () => { + let open = false; + const probe = async () => open; + const checkPort = (m: number) => core.checkServices(db, { self: "watchdog", now: at(m), log, probe }); + + test("Порт закрыт несколько проверок подряд — алерт, в status «порт не отвечает», потом «снова на связи»", async () => { + open = false; + for (const m of [0, 1]) { + await beatAt("web", m); + await checkPort(m); + } + assert.deepEqual(await queued(ADMIN.chatId), [], "две проверки — ещё не отказ"); + await beatAt("web", 2); + await checkPort(2); + const msgs = await queued(ADMIN.chatId); + assert.equal(msgs.length, 1); + assert.match(msgs[0]!, /веб не отвечает: процесс жив .* порт закрыт/); + // heartbeat is fresh, yet the state says so + const s = (await core.serviceStatus(db, { now: at(2), probe })).find((x) => x.service === "web")!; + assert.equal(s.portDown, true); + assert.equal(core.describeState(s), "процесс жив, порт не отвечает"); + // the same outage is not repeated by the next checks + await beatAt("web", 3); + await checkPort(3); + assert.equal((await queued(ADMIN.chatId)).length, 1); + // the port is back + open = true; + await beatAt("web", 4); + await checkPort(4); + const after = await queued(ADMIN.chatId); + assert.equal(after.length, 2); + assert.match(after[1]!, /веб снова на связи/); + }); + + test("Устойчивый отказ порта — вачдог перезапускает веб (с пределом)", async () => { + const bin = join(mkdtempSync(join(tmpdir(), "peppa-launchctl-")), "mock-launchctl"); + const calls = join(mkdtempSync(join(tmpdir(), "peppa-launchctl-log-")), "calls.txt"); + writeFileSync(bin, `#!/bin/sh\necho "$@" >> "${calls}"\n`, { mode: 0o755 }); + process.env.PEPPA_LAUNCHCTL_BIN = bin; + process.env.PEPPA_WEB_RESTART_AFTER = "4"; + process.env.PEPPA_WEB_RESTART_MAX = "1"; + try { + open = false; + for (const m of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) { + await beatAt("web", m); + await checkPort(m); + await runner.webRestartTick(db, { now: at(m), log }); + } + const lines = readFileSync(calls, "utf8").trim().split("\n"); + assert.equal(lines.length, 1, "в час не больше одного перезапуска"); + assert.match(lines[0]!, /^kickstart -k gui\/\d+\/quest\.telecom\.peppa\.web$/); + } finally { + delete process.env.PEPPA_LAUNCHCTL_BIN; + delete process.env.PEPPA_WEB_RESTART_AFTER; + delete process.env.PEPPA_WEB_RESTART_MAX; + } + }); + + test("Порт открыт — тишина; одиночный сбой не считается", async () => { + open = true; + await beatAt("web", 0); + await checkPort(0); + open = false; + await checkPort(1); + open = true; + await checkPort(2); + open = false; + await checkPort(3); + await checkPort(4); + assert.deepEqual(await queued(ADMIN.chatId), []); + open = true; + const s = (await core.serviceStatus(db, { now: at(5), probe })).find((x) => x.service === "web")!; + assert.equal(s.portDown, undefined); + }); +}); + describe("Алерт админу о молчащем сервисе", () => { test("Бот молчит", async () => { await beatAt("bot", 0); diff --git a/packages/testkit/test/platform-dashboard.test.ts b/packages/testkit/test/platform-dashboard.test.ts new file mode 100644 index 00000000..afc91c5c --- /dev/null +++ b/packages/testkit/test/platform-dashboard.test.ts @@ -0,0 +1,46 @@ +// PEP-167: the superadmin's dashboard — totals, a row per user and per project, what needs attention. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { tasks } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { core, db, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; +after(teardown); + +let ownerId = 0; +let loneId = 0; +before(async () => { + const owner = await core.upsertUserFromGitea(db, { id: 167, login: "mock-dash-owner" }, { access_token: "x" }); + const lone = await core.upsertUserFromGitea(db, { id: 168, login: "mock-dash-lone" }, { access_token: "x" }); + ownerId = owner.id; + loneId = lone.id; + const p = await core.createProject(db, { slug: "mock-dash", key: "MDASH", name: "Dash", ownerId: owner.id, giteaOwner: "mock", workspacePath: "/tmp/mock-dash" }); + const a = await core.createTask(db, { projectId: p.id, title: "Готовая" }); + const b = await core.createTask(db, { projectId: p.id, title: "На приёмке" }); + await core.createTask(db, { projectId: p.id, title: "В бэклоге" }); + await db.update(tasks).set({ status: "done" }).where(eq(tasks.id, a.task.id)); + // «Принять» waits for two days. + await db.update(tasks).set({ status: "review", updatedAt: new Date(Date.now() - 48 * 3600_000) }).where(eq(tasks.id, b.task.id)); +}); + +describe("PEP-167: дашборд суперадмина", () => { + test("итоги, строка пользователя и проекта", async () => { + const d = await core.platformDashboard(db); + const p = d.projects.find((x) => x.key === "MDASH")!; + assert.deepEqual({ done: p.done, review: p.review, backlog: p.backlog, total: p.total, owner: p.ownerLogin }, { done: 1, review: 1, backlog: 1, total: 3, owner: "mock-dash-owner" }); + const u = d.users.find((x) => x.id === ownerId)!; + assert.deepEqual(u.projects, ["MDASH"]); + assert.equal(u.done, 1); + assert.ok(d.totals.total >= 3 && d.totals.users >= 2); + }); + + test("«Требует внимания»: «Принять» ждёт дольше суток; пользователь без проекта — через час", async () => { + const d = await core.platformDashboard(db); + assert.ok(d.attention.some((a) => a.kind === "review" && a.text.includes("MDASH"))); + assert.ok(!d.attention.some((a) => a.kind === "no_project" && a.who === "mock-dash-lone"), "just signed up — not yet"); + const later = await core.platformDashboard(db, new Date(Date.now() + 2 * 3600_000)); + assert.ok(later.attention.some((a) => a.kind === "no_project" && a.who === "mock-dash-lone")); + void loneId; + }); +}); diff --git a/packages/testkit/test/reviewer.test.ts b/packages/testkit/test/reviewer.test.ts index de664355..eb7a50d6 100644 --- a/packages/testkit/test/reviewer.test.ts +++ b/packages/testkit/test/reviewer.test.ts @@ -82,6 +82,8 @@ async function reviewTask(turns: Action[][], settings?: Parameters (await core.messageDetails(db, [q.id])).get(q.id) ?? ""; const readyQuestions = async (t: ReviewTask) => (await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind === "attention" && q.text.includes("готова к ревью")); const stopAll = async (t: ReviewTask) => { for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id); @@ -120,7 +122,7 @@ describe("Агент-ревьюер до ревью PM", () => { return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); - assert.match(stripAsIs(q!.text), /Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть/); + assert.match(stripAsIs(await cardDetails(q!)), /Ревьюер: ок — деление и ошибка на ноль сделаны, тесты есть/); assert.ok(await runner.isReviewQuestion(db, q!), "«Принять» works on it"); // Exactly one ready-for-review, whichever finished first (the agent's turn or the reviewer). await new Promise((r) => setTimeout(r, 1500)); @@ -146,7 +148,7 @@ describe("Агент-ревьюер до ревью PM", () => { return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); - assert.match(q!.text, /лимит итераций исчерпан[\s\S]*src\/divide\.ts — замечание 2/); + assert.match(await cardDetails(q!), /лимит итераций исчерпан[\s\S]*src\/divide\.ts — замечание 2/); assert.equal(calls().length, 0, "the reviewer was not called again"); await stopAll(t); }); @@ -160,7 +162,7 @@ describe("Агент-ревьюер до ревью PM", () => { return qs.length ? qs : null; }); assert.equal((await t.ref()).task.status, "review"); - assert.match(q!.text, /Ревьюер не отработал: ревьюер завершился с кодом 1/); + assert.match(await cardDetails(q!), /Ревьюер не отработал: ревьюер завершился с кодом 1/); assert.equal((await core.latestReview(db, (await t.ref()).task.id))?.state, "error"); await stopAll(t); }); @@ -202,7 +204,7 @@ describe("reviewer details", () => { assert.equal(done.error, "ревьюер ответил не по формату"); // No runner: the PM gets "ready for review" directly. assert.equal((await t.ref()).task.status, "review"); - assert.match((await readyQuestions(t))[0]!.text, /Ревьюер не отработал: ревьюер ответил не по формату/); + assert.match(await cardDetails((await readyQuestions(t))[0]!), /Ревьюер не отработал: ревьюер ответил не по формату/); // Approved head → asking again goes straight to review with the note. await core.updateTask(db, await t.ref(), { status: "in_progress" }); diff --git a/packages/testkit/test/rotation.test.ts b/packages/testkit/test/rotation.test.ts index dd9bf13b..cd6bed08 100644 --- a/packages/testkit/test/rotation.test.ts +++ b/packages/testkit/test/rotation.test.ts @@ -7,6 +7,8 @@ import { events } from "@peppa/db"; import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; +// PEP-170: early switching (at the warning threshold) is off by default; this file covers it too. +process.env.PEPPA_ROTATE_EARLY = "on"; type User = Awaited>; let pm: User; diff --git a/packages/testkit/test/service-text.test.ts b/packages/testkit/test/service-text.test.ts new file mode 100644 index 00000000..816ca019 --- /dev/null +++ b/packages/testkit/test/service-text.test.ts @@ -0,0 +1,233 @@ +// PEP-154: service text never reaches the person. Blocks like , command +// output, shell prompts, stack traces and absolute paths are cut out of messages and answers; +// an exception inside Peppa goes to the superadmins and the error tracker, not to the owner. +// Tests are named after the spec scenarios. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { projects, questions, sessions, telegramOutbox, users } from "@peppa/db"; +import { and, eq, isNull, sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); +const { renderQuestion, renderAnswered } = await import("@peppa/bot/render"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../.."); +const bugsink = await new MockBugsink().start(); +process.env.BUGSINK_URL = bugsink.url; + +const NOTIFICATION = "\nb7f3\n/private/tmp/claude-501/tasks/b7f3.output\ncompleted\nBackground command finished\n"; +const TERMINAL_REPLY = [ + "Проверки не прошли, нужен ваш ответ.", + "", + "$ pnpm test", + "```", + "FAIL src/app.test.ts", + " ● оплата › считает сумму", + "```", + "TypeError: total is not a function", + " at sum (/Users/telecom/Dev/pay/src/app.ts:12:5)", + " at async run (node:internal/process/task_queues:95:5)", + "Файл: /Users/telecom/Dev/pay/src/app.ts", + "\x1b[31mЧто выбрать: чинить сейчас или отложить?\x1b[0m", +].join("\n"); + +let owner: Awaited>; +let admin: Awaited>; +let seq = 0; + +/** A story at work with its agent's session (no tmux: messages are raised as the hook does). */ +async function story() { + const key = `F${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: owner.id }); + const created = await core.createTask(db, { projectId: p.id, title: "Оплата картой" }); + await core.updateTask(db, await core.resolveTask(db, created.key), { status: "in_progress" }); + const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning(); + return { + project: p, + key: created.key, + taskId: created.task.id, + sessionId: s!.id, + session: () => core.getSession(db, s!.id), + ref: () => core.resolveTask(db, created.key), + asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id), + thread: async () => { + await core.syncChats(db); + return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); + }, + }; +} + +/** Runs the real peppa-hook like Claude Code does: payload on stdin. */ +function hook(event: string, payload: unknown, sessionId: number): Promise { + return new Promise((done) => { + const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: "0" }, stdio: ["pipe", "ignore", "inherit"] }); + p.on("close", (code) => { + assert.equal(code, 0); + done(); + }); + p.stdin.end(JSON.stringify(payload)); + }); +} + +const outboxTo = async (chatId: number) => + (await db.select().from(telegramOutbox).where(sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`).orderBy(telegramOutbox.id)).map((r) => String(r.params.text)); +const openOf = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt))); + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 541, login: "mock-owner" }, { access_token: "x" }); + admin = await core.upsertUserFromGitea(db, { id: 542, login: "mock-admin" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 5410, telegramUserId: 5410 }).where(eq(users.id, owner.id)); + await db.update(users).set({ telegramChatId: 5420, telegramUserId: 5420 }).where(eq(users.id, admin.id)); + await core.setPlatformAdmins(db, [admin.login]); +}); +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-154: фильтр служебного текста", () => { + test("userText: блоки, ANSI, вывод команд, приглашение оболочки, трассировка и пути убираются; адреса остаются", () => { + const out = core.userText(TERMINAL_REPLY); + assert.equal(out, "Проверки не прошли, нужен ваш ответ.\n\nЧто выбрать: чинить сейчас или отложить?"); + assert.equal(core.userText(out), out, "idempotent"); + assert.equal(core.userText(NOTIFICATION), ""); + assert.equal(core.userText("Готово. не для людей Результат: https://git.example.com/pay/pulls/7"), "Готово. Результат: https://git.example.com/pay/pulls/7"); + assert.equal(core.userText("Поправил `packages/core/src/chats.ts` и C:\\Users\\pm\\app.ts, проверил."), "Поправил и, проверил."); + // A person's own words are not rewritten: only what is certainly service text. + assert.equal(core.stripServiceBlocks("Синий, как в /Users/me/макет.png"), "Синий, как в /Users/me/макет.png"); + assert.equal(core.isServiceInput(NOTIFICATION), true); + assert.equal(core.isServiceInput("Синий"), false); + }); + + test("Реплика агента с выводом терминала и путём", async () => { + const st = await story(); + // Two automatic nudges first (the story is at work), then the reply reaches the story thread. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + const thread = await st.thread(); + const said = thread.find((m) => m.text.includes("Проверки не прошли, нужен ваш ответ.")); + assert.ok(said, "the owner sees the reply"); + assert.match(said.text, /чинить сейчас или отложить/); + for (const m of thread) for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!m.text.includes(bad), `no «${bad}» in the thread`); + // The same reply as a question to the person: stored, sent to Telegram — all without it. + const q = await core.askPm(db, await st.ref(), { kind: "question", text: TERMINAL_REPLY, sessionId: st.sessionId }); + for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!q.text.includes(bad), `no «${bad}» in the message`); + const tg = renderQuestion(q, { taskKey: st.key, taskTitle: "Оплата картой", taskStatus: "in_progress", session: await st.session(), webUrl: "http://peppa.test" }); + assert.match(tg.text, /Проверки не прошли, нужен ваш ответ\./); + assert.ok(!tg.text.includes("/Users/") && !tg.text.includes("tmux attach"), "Telegram: no path, no terminal command"); + assert.ok(renderQuestion(q, { taskKey: st.key, taskTitle: null, session: await st.session(), webUrl: "http://peppa.test", engineer: true }).text.includes("tmux attach"), "«Инженер» keeps the terminal command"); + }); + + test("Исходный текст для инженера", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Нужен ваш ответ. Файл /Users/telecom/Dev/pay/src/app.ts не открывается."); + assert.ok(!q.text.includes("/Users/")); + assert.match((await core.questionDetails(db, q.id)) ?? "", /\/Users\/telecom\/Dev\/pay\/src\/app\.ts/); + const clean = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"] }); + assert.equal(await core.questionDetails(db, clean.id), null, "nothing was cut — nothing to keep"); + // A permission request keeps its command: that is what the person allows. + const perm = await core.raiseSessionQuestion(db, await st.session(), "permission", "Разрешить Bash: rm /Users/telecom/Dev/pay/tmp.txt", ["allow", "deny"]); + assert.match(perm.text, /\/Users\/telecom/); + }); + + test("От реплики ничего не осталось", async () => { + const st = await story(); + await assert.rejects(core.askPm(db, await st.ref(), { kind: "question", text: "только служебное" }), /служебный текст/); + assert.equal((await st.asked()).length, 0); + // The end of a turn with nothing for a person leaves nothing in the story thread. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: NOTIFICATION }, st.sessionId); + assert.equal((await st.asked()).length, 0); + assert.ok(!(await st.thread()).some((m) => /task-notification|private\/tmp|Background command/.test(m.text))); + assert.equal(await core.addChatMessage(db, { chatId: (await core.ensureProjectChat(db, st.project.id)).id, kind: "event", authorKind: "agent", text: NOTIFICATION, dedupeKey: `mock:${st.key}` }), null); + }); +}); + +describe("PEP-154: ответом вопроса считается только ввод человека", () => { + test("Служебное уведомление в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: NOTIFICATION }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredAt, null, "the question stays open"); + assert.equal(after.answer, null); + const thread = await st.thread(); + assert.ok(!thread.some((m) => m.text.includes("task-notification") || (m.question?.answer ?? "").includes("task-notification")), "not in the chat: neither text nor answer"); + // Even if such a block came glued to a person's words, only the words are the answer. + const answered = await core.answerQuestion(db, q.id, `Синий\n${NOTIFICATION}`, "terminal"); + assert.equal(answered.answer, "Синий"); + assert.ok(!renderAnswered("Вопрос", answered).includes("task-notification")); + await assert.rejects(core.answerQuestion(db, (await core.askPm(db, await st.ref(), { kind: "question", text: "А размер?", sessionId: st.sessionId })).id, NOTIFICATION, "web")); + }); + + test("Человек печатает в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answer, "Синий"); + assert.equal(after.answeredVia, "terminal"); + }); + + test("Peppa сама пишет агенту", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Агент закончил ход и ждёт вашего ответа."); + const report = "Проверки PR красные: test\n$ pnpm test\nFAIL src/app.test.ts"; + await core.logSessionEvent(db, await st.session(), "input_sent", { text: report }); + await hook("prompt", { prompt: report }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredVia, "system", "closed as stale, not answered"); + assert.ok(!(after.answer ?? "").includes("FAIL")); + // A person's message that Peppa only carried to the terminal is still that person's answer. + const q2 = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await core.logSessionEvent(db, await st.session(), "input_sent", { text: "Синий", person: true }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + assert.equal((await core.getQuestion(db, q2.id)).answer, "Синий"); + }); +}); + +describe("PEP-154: ошибки платформы не идут владельцу проекта", () => { + const NO_QUIET = { quietFrom: null, quietTo: null }; + const autonomy = (now = new Date()) => runner.autonomyTick(db, { now, log: () => {} }); + + test("Диспетчер упал с исключением; та же ошибка повторяется", async () => { + // The platform project is connected to the error tracker (mock). + const platform = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = platform.key; + core.resetErrorReporting(); + const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); + await runner.connectErrorTracking(db, await core.getProject(db, platform.key), client, "http://peppa.test"); + + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + await db.update(projects).set({ ownerId: owner.id }).where(eq(projects.id, p.id)); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + // The start blows up inside Peppa: the sessions table is gone for one tick. + const now = new Date(); + const ingested = bugsink.ingested.length; + db.run(sql`ALTER TABLE runner_tasks RENAME TO runner_tasks_x`); + try { + await autonomy(now); + assert.equal((await openOf(p.id)).length, 0, "the owner gets no message"); + assert.equal((await outboxTo(5410)).length, 0, "nothing for the owner in Telegram"); + const alerts = (await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")); + assert.equal(alerts.length, 1, "the superadmin gets one message"); + assert.ok(bugsink.ingested.length > ingested, "the error tracker has the exception"); + // Ten minutes later the same error: no second message. + await autonomy(new Date(now.getTime() + 10 * 60_000)); + assert.equal((await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")).length, 1); + assert.equal((await openOf(p.id)).length, 0); + } finally { + db.run(sql`ALTER TABLE runner_tasks_x RENAME TO runner_tasks`); + } + }); + + test("Понятный отказ", async () => { + assert.equal(await core.platformFailure(db, new core.PeppaError("Подписка не выбрана — выберите её в настройках проекта."), { service: "watchdog", where: "dispatch PAY-7" }), "Подписка не выбрана — выберите её в настройках проекта."); + assert.equal(await core.platformFailure(db, new Error("SQLITE_ERROR: no such column: x"), { service: "watchdog", where: "dispatch PAY-7" }), null); + }); +}); diff --git a/packages/testkit/test/subscription-failover.test.ts b/packages/testkit/test/subscription-failover.test.ts index 759bb40b..12cfae7a 100644 --- a/packages/testkit/test/subscription-failover.test.ts +++ b/packages/testkit/test/subscription-failover.test.ts @@ -39,6 +39,42 @@ const outboxTexts = async (prefix: string) => .map((r) => String((JSON.parse(String((r as { params: string }).params)) as { text: string }).text)); const typeEvents = async (type: string) => (await db.select().from(events)).filter((e) => e.type === type); +describe("Простая картина подписок (PEP-170)", () => { + test("Агент на одной подписке — свободная помечена «следующая»; переключение видно в наборе", async () => { + const [a, b] = [await claudeSub("Next A", "nextA"), await claudeSub("Next B", "nextB")]; + const p = await project({ turns: [[{ work: 4000 }, { say: "Готово." }]] }); + const pool = await poolFor(p.key, [a.id, b.id]); + const sid = await p.start(); + const on = (await sess(sid)).subscriptionId; + const o = (await core.poolOverview(db, pool.id))!; + const at = o.subscriptions.find((x) => x.id === on)!; + const free = o.subscriptions.find((x) => x.id !== on)!; + assert.equal(at.activeSessions, 1); + assert.equal(at.next, false); + assert.equal(free.next, true, "the free subscription is where agents go next"); + const projectId = (await core.getProject(db, p.key)).id; + await core.logEvent(db, { projectId, sessionId: sid, type: runner.SWITCH_EVENT, payload: { fromId: at.id, fromName: at.name, toId: free.id, toName: free.name, reason: "limit" } }); + const [sw] = (await core.poolOverview(db, pool.id))!.switches; + assert.deepEqual({ from: sw!.fromName, to: sw!.toName, reason: sw!.reason, session: sw!.sessionId }, { from: at.name, to: free.name, reason: "limit", session: sid }); + await runner.stopSession(db, sid); + }); + + test("Одна подписка — «следующей» нет", async () => { + const a = await claudeSub("Solo A", "soloA"); + const p = await project({ turns: [] }); + const pool = await poolFor(p.key, [a.id]); + assert.equal((await core.poolOverview(db, pool.id))!.subscriptions.some((x) => x.next), false); + }); + + test("Заранее по порогу не переключает по умолчанию (PEPPA_ROTATE_EARLY не задан)", () => { + delete process.env.PEPPA_ROTATE_EARLY; + assert.equal(runner.earlyRotationEnabled(), false); + process.env.PEPPA_ROTATE_EARLY = "on"; + assert.equal(runner.earlyRotationEnabled(), true); + delete process.env.PEPPA_ROTATE_EARLY; + }); +}); + describe("Переезд на подписку другого провайдера", () => { test("Claude упёрся в лимит, в пуле есть ChatGPT: новый запуск Codex без resume, PM получает «переехал»", async () => { const a = await claudeSub("Cross A", "xlimA"); diff --git a/packages/testkit/test/subscriptions.test.ts b/packages/testkit/test/subscriptions.test.ts index 6c3e18eb..801a5969 100644 --- a/packages/testkit/test/subscriptions.test.ts +++ b/packages/testkit/test/subscriptions.test.ts @@ -385,3 +385,18 @@ describe("PEP-76: владелец выбирает подписку проек assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "and nobody is pinged about it"); }); }); + +describe("PEP-164: ещё одна подписка прямо в пул", () => { + test("суперадмин добавляет Claude в пул одной кнопкой: подписка в пуле и ждёт входа по ссылке", async () => { + const first = await claudeSub("Claude — пул ротации", "pep164a"); + const pool = await core.createPool(db, { name: "Пул ротации PEP-164", subscriptionIds: [first.id] }); + const added = await runner.addPoolSubscription(db, { poolId: pool.id, provider: "claude", createdBy: asel.id }); + assert.equal(added.status, "pending", "waits for the sign-in"); + assert.match(added.name, /^Claude 2 — Пул ротации PEP-164$/); + const members = (await core.poolSubscriptions(db, pool.id)).map((s) => s.id); + assert.deepEqual(members, [first.id, added.id], "already a member of the pool, the first one stays"); + const login = await runner.pendingLogin(db, added.id); + assert.ok(login?.url, "the sign-in link is ready"); + await runner.cancelLogin(db, added.id); + }); +}); diff --git a/scripts/install-launchd.sh b/scripts/install-launchd.sh index 763f7b40..e3111fb7 100755 --- a/scripts/install-launchd.sh +++ b/scripts/install-launchd.sh @@ -9,8 +9,9 @@ # ~/.peppa/release-queue has requests (the PM's button) # Prod runs from the release directory: ~/peppa/current/scripts/install-launchd.sh, so every # path below (and PEPPA_ROOT for hooks and git config) is ~/peppa/current, not a release. -# Pre-launch (everything is dev): PEPPA_WEB_MODE=dev scripts/install-launchd.sh watchdog web bot -# from the working copy — no release agent, so nothing replaces what this checkout serves. +# Pre-launch (PEP-165): scripts/install-launchd.sh watchdog web bot from the working copy — web in +# `start` mode (build first: `next build` in apps/web), no release agent. Never `next dev` on the live +# site: its rebuilds made every open tab reload in a loop (16.11). # Usage: scripts/install-launchd.sh [watchdog] [web] [bot] [release] (default: all) # Remove: launchctl bootout gui/$(id -u)/