// PEP-303: the watchdog's screen guards react to what the agent CLI itself prints, not to the same // phrases quoted by the agent's tools — FORGE agents edit FORGE's code, where these phrases stand. import assert from "node:assert/strict"; import { after, before, describe, test } from "node:test"; import { and, eq } from "drizzle-orm"; process.env.PEPPA_SECRET ??= "mock-secret-for-tests"; import { core, db, project, runner, setDefaultOwner, superadmin, teardown, waitFor } from "./helpers.ts"; const { events } = await import("@peppa/db"); const { claudeCreditsDialog } = await import("../../runner/src/claude-screen.ts"); const { codexModelMenu, codexTrustPrompt } = await import("../../runner/src/codex-screen.ts"); const { startQuestion } = await import("../../runner/src/start-screen.ts"); const { isQuotedLine } = await import("../../runner/src/screen-lines.ts"); type User = Awaited>; let pm: User; before(async () => { pm = await core.upsertUserFromGitea(db, { id: 303, login: "mock-pm-303" }, { access_token: "x" }); setDefaultOwner(pm.id); }); after(teardown); const sess = (id: number) => core.getSession(db, id); const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now }); const eventsOf = async (sid: number, type: string) => db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, type))); const atWork = async (p: { taskKey: string }) => core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" }); /** 26.11, 12:57: the agent of PEP-268 edits watchdog.ts and greps the docs — the phrase is in its tool output. */ const EDIT_AND_GREP = [ "Update(packages/runner/src/watchdog.ts)", " ⎿ Updated packages/runner/src/watchdog.ts with 2 additions", " 331 + // PEP-227: Claude's « now uses usage credits» dialog waits for a choice", " 332 + // 1. Switch to Opus 5.5", "⏺ Bash(grep -rn \"now uses usage credits\" docs)", " ⎿ docs/a.md:3:Fable 5.2 now uses usage credits", " docs/a.md:4:1. Switch to Opus 5.5", " 1. Switch to Opus 5.5", ].join("\n"); /** 26.11, 22:25: the agent of PEP-268 looks at a diff of the mock — a limit line of code with its number. */ const LIMIT_IN_DIFF = [ "• Edited packages/testkit/src/mock-agent.ts (+1 -1)", " 446 } else {", " 447 + out(`■ You’ve hit your usage limit.${spec.reset === \"unknown\" ? \"\" : ` Try again at 8:47 PM.`}\\n`);", " 448 - out(`■ You’ve hit your usage limit.`);", "packages/testkit/src/mock-agent.ts:411: if (spec.afterLimit) out(\"■ You’ve hit your usage limit. Try again at 8:47 PM.\")", " // PEP-205: Codex prints «You’ve hit your usage limit … try again at 8:47 PM».", ].join("\n"); describe("Разбор экрана: строки CLI и цитаты", () => { test("Строки diff, grep и cat -n — цитаты; варианты и плашки — нет", () => { for (const l of [" 331 + // now uses usage credits", "447 +code", " 448 - old", " 12 context", "docs/a.md:4:1. Switch to Opus 5.5", " ⎿ docs/a.md:3:x", "+ added", "@@ -1,3 +1,4 @@", "12:text"]) assert.ok(isQuotedLine(l), l); for (const l of ["❯ 1. Use usage credits", " 2. Switch to Opus 5.5", "■ You’ve hit your usage limit.", "5-hour limit reached ∙ resets 3am", "Fable 5.2 now uses usage credits"]) assert.equal(isQuotedLine(l), false, l); }); test("Фраза кредитов и «1. Switch to Opus» в diff и выводе grep — не диалог", () => { assert.equal(claudeCreditsDialog(EDIT_AND_GREP), null); assert.equal(claudeCreditsDialog(`${EDIT_AND_GREP}\n\n✻ Working… (12s · esc to interrupt)\n`), null); assert.equal(claudeCreditsDialog(`${EDIT_AND_GREP}\n\n> \n`), null); // The agent's answer that names the dialog is not the dialog either. assert.equal(claudeCreditsDialog("⏺ Сторож ловит «Fable 5.2 now uses usage credits» и жмёт:\n 1. Switch to Opus 5.5\n 2. Exit\n\n> "), null); assert.equal(startQuestion("claude", EDIT_AND_GREP), null); }); test("Настоящий диалог узнаётся как раньше, в рамке тоже", () => { const dialog = "Fable 5.2 now uses usage credits\n\n❯ 1. Use usage credits\n 2. Switch to Opus 5.5\n 3. Exit"; assert.deepEqual(claudeCreditsDialog(`${EDIT_AND_GREP}\n\n${dialog}\n\n Enter to confirm · Esc to cancel\n\n\n`), { digit: "2" }); const boxed = ["╭──────────────────────────────────────╮", "│ Fable 5.2 now uses usage credits │", "│ │", "│ ❯ 1. Use usage credits │", "│ 2. Switch to Opus 5.5 │", "│ 3. Exit │", "╰──────────────────────────────────────╯", " Enter to confirm · Esc to cancel"].join("\n"); assert.deepEqual(claudeCreditsDialog(boxed), { digit: "2" }); assert.deepEqual(claudeCreditsDialog("Fable 5.2 now uses usage credits\n 1. Continue\n 2. Exit"), { digit: null }); assert.equal(startQuestion("claude", dialog), "model"); }); test("Меню модели и доверие папке Codex в diff — не вопрос", () => { const menu = " Switch to gpt-6-luna for lower credit usage?\n› 1. Switch to gpt-6-luna\n 2. Keep current model\n 3. Keep current model (never show again)\n\n enter select · esc back"; const quoted = menu.split("\n").map((l, i) => ` ${410 + i} +${l}`).join("\n"); assert.equal(codexModelMenu(quoted), null); assert.equal(codexModelMenu(menu), "2", "the real menu"); const trust = " Trust this folder?\n /w/s1\n\n› 1. Trust and continue\n 2. Back\n\n enter select · esc back"; assert.equal(codexTrustPrompt(trust.split("\n").map((l, i) => `src/mock-agent.ts:${420 + i}:${l}`).join("\n")), null); assert.equal(codexTrustPrompt(trust)?.digit, "1", "the real question"); assert.equal(startQuestion("codex", quoted), null); }); test("Строка лимита в diff, grep и коде — не плашка; настоящие плашки — плашки", () => { assert.deepEqual(runner.limitLines(LIMIT_IN_DIFF), []); assert.equal(runner.freshLimitLine(LIMIT_IN_DIFF, 0), null); for (const banner of [ "■ You’ve hit your usage limit. Upgrade to Pro (https://chatgpt.com/explore/pro) or try again at 8:47 PM.", "⎿ Claude usage limit reached. Your limit will reset at 9pm.", " ⎿ API Error: Claude usage limit reached. Your limit will reset at 9pm.", "⏺ Usage limit reached · resets 9pm", "Claude AI usage limit reached|1700000000", "5-hour limit reached ∙ resets 3am", ]) assert.deepEqual(runner.limitLines(`${LIMIT_IN_DIFF}\n${banner}\n Approaching rate limits`), [banner.trim()], banner); assert.equal(runner.usageWarning(" 90 + out(\"You've used 95% of your weekly limit\")"), false); }); }); describe("Вачдог не трогает работающего агента из-за текста в его выводе", () => { test("Claude: фраза кредитов в diff и grep — ни сообщения, ни нажатия", async () => { const sent = await superadmin(); const p = await project({ turns: [[{ say: EDIT_AND_GREP }]] }); await atWork(p); const sid = await p.start(); await p.waitLog("turn 0", (e) => e.ev === "turn_end"); for (let i = 0; i < 3; i++) await tickAt(new Date()); assert.equal((await eventsOf(sid, "model_dialog_dismissed")).length, 0, "no key pressed"); assert.deepEqual((await sent()).filter((t) => /кредит/.test(t)), [], "no alert"); await runner.stopSession(db, sid); }); test("Claude: настоящий диалог — «Switch to Opus» нажат", async () => { const p = await project({ turns: [[{ credits: true }, { say: "Продолжаю на Opus." }]] }); await atWork(p); const sid = await p.start(); await p.waitLog("dialog", (e) => e.ev === "dialog"); const key = await waitFor("dialog answered", async () => (await tickAt(new Date()), p.log().find((e) => e.ev === "credits"))); assert.equal(key.key, "2"); assert.equal((await eventsOf(sid, "model_dialog_dismissed")).length, 1); await runner.stopSession(db, sid); }); test("Codex: строка лимита в diff — нет usage_limit, подписка не помечена, агент работает", async () => { const sub = await runner.addSubscription(db, { provider: "codex", name: "Codex 303", method: "api_key", secret: "mock-openai-key-303", createdBy: pm.id }); const pool = await core.createPool(db, { name: "Пул 303", subscriptionIds: [sub.id] }); const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }]] }); await core.setProjectPool(db, (await core.getProject(db, p.key)).id, pool.id); await atWork(p); const sid = await p.start({ provider: "codex" }); await p.waitLog("turn 0", (e) => e.ev === "turn_end"); for (let i = 0; i < 3; i++) await tickAt(new Date()); assert.equal((await eventsOf(sid, "usage_limit")).length, 0, "no limit event"); const s = await sess(sid); assert.notEqual(s.status, "rate_limited"); assert.equal(s.subscriptionId, sub.id, "not moved to another subscription"); assert.equal((await core.getSubscription(db, sub.id)).status, "active", "the subscription is not marked limited"); assert.equal((await eventsOf(sid, "exited")).length, 0, "the agent was not stopped"); await runner.stopSession(db, sid); }); test("Codex: настоящая плашка в живом окне — лимит", async () => { const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }, { limit: { resetInSec: 600 } }]] }); await atWork(p); const sid = await p.start({ provider: "codex" }); await waitFor("rate limited", async () => (await tickAt(new Date()), (await sess(sid)).status === "rate_limited")); const [ev] = await eventsOf(sid, "usage_limit"); assert.match((ev!.payload as any).line, /^■ You’ve hit your usage limit\. Try again at/); await runner.stopSession(db, sid); }); test("Codex: настоящая плашка в мёртвом окне — лимит, а не падение", async () => { const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }, { limit: { resetInSec: 600, exit: 1 } }]] }); await atWork(p); const sid = await p.start({ provider: "codex" }); await p.waitLog("exited", (e) => e.ev === "exit"); const [ev] = await waitFor("limit seen", async () => (await tickAt(new Date()), (await eventsOf(sid, "usage_limit")).length ? await eventsOf(sid, "usage_limit") : null)); assert.equal((ev!.payload as any).exited, true); assert.match((ev!.payload as any).line, /^■ You’ve hit your usage limit\. Try again at/); assert.deepEqual((await sess(sid)).watchState?.restarts ?? [], [], "not a crash"); await runner.stopSession(db, sid); }); test("Codex: строка лимита в diff в мёртвом окне — обычное падение", async () => { const p = await project({ turns: [[{ say: LIMIT_IN_DIFF }, { crash: 1 }]] }); await atWork(p); const sid = await p.start({ provider: "codex" }); await p.waitLog("exited", (e) => e.ev === "exit"); await waitFor("exit seen", async () => (await tickAt(new Date()), (await eventsOf(sid, "exited")).length)); assert.equal((await eventsOf(sid, "usage_limit")).length, 0); await runner.stopSession(db, sid); }); });