PEP-227: потерянный разговор Claude — новый запуск вместо resume по кругу; диалог кредитов модели

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-21 14:54:19 +00:00
parent cb513d4153
commit 81730b63c4
13 changed files with 252 additions and 3 deletions

View File

@ -0,0 +1,6 @@
## Решения
- **Где распознаём.** В ветке «pane мёртв» `checkSession` (watchdog.ts), рядом с лимитом и сбоем входа Codex — по `tail` (последние 15 строк экрана, тот же, что в событии `exited`). Только `provider = claude` и только когда у сессии есть `conversationId` (иначе resume не было — значит это не наш случай и круга не будет).
- **Как перезапускаем.** `onConversationLost` (recovery.ts): `conversationId = null`, план перезапуска `restartAt = now`, `restartReason = "conversation_lost"`, `restartFree = true` — тот же механизм, что повтор после сбоя входа (PEP-205): счётчик авто-перезапусков не тратится, `restartBlocker` всё так же проверяет «задача в работе / лимит / бюджет / пауза». `restartTick` зовёт `resumeSession`, который при пустом `conversationId` запускает Claude без `--resume`; промпт по причине: «Прошлый разговор агента потерян… начни новый: сверься с get_task и tasks.md, продолжай с первого невыполненного пункта». Повтор этой ошибки невозможен (нет `--resume`), так что круга нет; любое другое падение нового поколения идёт обычным путём с пределом.
- **Почему не сразу в вачдоге.** Через `restartTick` перезапуск проходит одни и те же проверки (другой агент уже ведёт задачу, пауза проекта) и не дублирует код.
- **Ручной resume** такой сессии после стирания — тоже свежий запуск (поведение `resumeSession`).
- **Диалог Fable.** `claude-screen.ts` — `claudeCreditsDialog(screen)` ищет «now uses usage credits» и пункт `N. Switch to Opus…`; вачдог нажимает цифру и пишет `model_dialog_dismissed`, раз в 2 минуты не чаще. Нет пункта — `alertAdmins` с ключом `credits:<sessionId>:<gen>` (одно сообщение на поколение). Настоящий экран диалога не снят — регэкспы терпимые (регистр, «›»), постоянная мера — `platform.agent model=opus`, уже выставлена.

View File

@ -0,0 +1,15 @@
## Why
Сессия #9 (SBX-1) весь день 20.11 падала при каждом resume: `claude --resume <id>` отвечал «No conversation found with session ID» и выходил с кодом 1. Вачдог тратил три авто-перезапуска на тот же resume, ручной перезапуск сбрасывал счётчик — и так по кругу. Разговора больше нет, повторять resume бессмысленно.
Попутно: Claude без модели в настройках взял Fable 5.2, которая теперь просит отдельные кредиты, — агенты висели на диалоге «Fable 5.2 now uses usage credits».
## What Changes
- Вачдог узнаёт в хвосте экрана упавшего Claude строку «No conversation found with session ID»: стирает `sessions.conversation_id` и сразу (без траты авто-перезапусков) запускает новое поколение без `--resume` с промптом «продолжай стори, сверься с get_task и tasks.md»; событие `conversation_lost` в журнале.
- Если разговор уже стёрт, а агент всё равно падает — обычный путь авто-перезапуска (круга нет).
- Диалог «… now uses usage credits» на экране Claude: вачдог выбирает пункт «Switch to Opus…» (событие `model_dialog_dismissed`); нет такого пункта — одно сообщение суперадмину.
- mock-claude: сценарий `forgetResume` — на `--resume` печатает ту же строку и выходит с кодом 1.
## Impact
- `packages/runner/src/watchdog.ts`, `recovery.ts`, новый `claude-screen.ts`
- `packages/testkit/src/mock-agent.ts`, `scenario.ts`, тест `lost-conversation.test.ts`
- Спека `watchdog-recovery`

View File

@ -0,0 +1,31 @@
## ADDED Requirements
### Requirement: Потерянный разговор — новый запуск, а не resume по кругу
Когда Claude при resume отвечает «No conversation found with session ID» и выходит с ошибкой, вачдог SHALL стереть сохранённый разговор сессии и сразу запустить новое поколение без resume с просьбой продолжить стори по `get_task` и `tasks.md`, не тратя авто-перезапуски; в журнал раннера SHALL писаться событие `conversation_lost`.
#### Scenario: Разговор потерян
- **GIVEN** агент стори PEP-42 «в работе» с сохранённым разговором «865315ef»
- **AND** Claude на `--resume 865315ef` печатает «No conversation found with session ID: 865315ef» и выходит с кодом 1
- **WHEN** вачдог видит мёртвый pane
- **THEN** в журнале раннера событие `conversation_lost`
- **AND** следующий запуск агента идёт без `--resume` с текстом «сверься с get_task и tasks.md»
- **AND** число авто-перезапусков в памяти вачдога не растёт
#### Scenario: Падение без сохранённого разговора
- **GIVEN** у сессии нет сохранённого разговора
- **WHEN** агент падает с той же строкой на экране
- **THEN** вачдог идёт обычным путём авто-перезапуска с пределом `restartMax`
### Requirement: Диалог кредитов модели не держит агента
Когда на экране Claude диалог «… now uses usage credits», вачдог SHALL выбрать пункт «Switch to Opus…»; если такого пункта нет — SHALL один раз сообщить суперадмину.
#### Scenario: Есть пункт перехода на Opus
- **GIVEN** на экране «Fable 5.2 now uses usage credits» и пункт «2. Switch to Opus 5.5»
- **WHEN** вачдог проверяет агента
- **THEN** агенту нажимается «2»
- **AND** в журнале событие `model_dialog_dismissed`
#### Scenario: Пункта нет
- **GIVEN** на экране диалог кредитов без пункта «Switch to Opus»
- **WHEN** вачдог проверяет агента дважды
- **THEN** суперадмин получает одно сообщение

View File

@ -0,0 +1,11 @@
## 1. Потерянный разговор
- [x] 1.1 mock-claude: сценарий `forgetResume` — «No conversation found with session ID: <id>», код 1
- [x] 1.2 `onConversationLost` в recovery.ts и ветка в watchdog.ts; промпт по причине в `restartTick`
- [x] 1.3 Тест `lost-conversation.test.ts`: после падения resume — свежий запуск без `--resume`, счётчик не тронут, событие `conversation_lost`
## 2. Диалог кредитов модели
- [x] 2.1 `claude-screen.ts` + реакция вачдога (выбрать «Switch to Opus», иначе сообщение суперадмину)
- [x] 2.2 Тест на разбор экрана
## 3. Завершение
- [ ] 3.1 Спека, память, проверки, archive, PR

View File

@ -429,6 +429,8 @@ export type WatchState = {
loginFails?: number;
/** PEP-205: when the watchdog last answered the CLI's «Switch to <model>?» menu (ms). */
menuAt?: number;
/** PEP-227: the generation whose «now uses usage credits» dialog (without «Switch to Opus») the superadmin was told about. */
creditsAlertGen?: number;
};
/**

View File

@ -0,0 +1,24 @@
// PEP-227: what the Claude CLI shows on its screen when it is not the agent's work that stopped it —
// the «<model> now uses usage credits» dialog (20.11: Fable 5.2 began to need separate credits and
// agents without a model in their settings hung on it). The real screen is not captured yet, so the
// patterns are lenient: the question anywhere near the bottom, a numbered «Switch to Opus…» choice.
import * as tmux from "./tmux.ts";
const CREDITS_RE = /now uses (?:usage )?credits/i;
const SWITCH_RE = /^\s*(?:[›❯>]\s*)?(\d)[.)]\s*Switch to Opus\b/im;
/** The credits dialog is on screen: `{ digit }` of «Switch to Opus…» (null when there is no such choice), else null. */
export function claudeCreditsDialog(screen: string): { digit: string | null } | null {
// The pane is padded with blank rows below the text.
const tail = screen.trimEnd().split("\n").slice(-30).join("\n");
if (!CREDITS_RE.test(tail)) return null;
return { digit: SWITCH_RE.exec(tail)?.[1] ?? null };
}
/** Picks «Switch to Opus…» in the credits dialog. Returns true when a key was sent. */
export async function dismissCreditsDialog(pane: tmux.Pane, screen: string): Promise<boolean> {
const digit = claudeCreditsDialog(screen)?.digit;
if (!digit) return false;
await tmux.sendKeys(pane, digit);
return true;
}

View File

@ -226,6 +226,27 @@ export async function onLoginFailure(db: Db, s: SessionView, tail: string, o: {
return "down";
}
/** PEP-227: what Claude prints when `--resume` names a conversation it no longer has. */
export const LOST_CONVERSATION_RE = /No conversation found with session ID/i;
/**
* PEP-227: Claude could not resume the saved conversation («No conversation found with session ID»)
* and exited. Resuming it again fails the same way, so the conversation is forgotten and the agent
* starts a new one at once (through `restartTick`: same checks, no automatic restart spent).
*/
export async function onConversationLost(db: Db, s: SessionView, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<void> {
await updateSession(db, s.id, { conversationId: null });
await logSessionEvent(db, s, "conversation_lost", { conversationId: s.conversationId });
o.log(`#${s.id} ${s.taskKey ?? ""}: conversation ${s.conversationId} is gone, starting a new one`);
const blocker = await restartBlocker(db, s, o.cfg, o.now.getTime(), true);
if (blocker) {
await updateSession(db, s.id, { status: "failed", endedAt: o.now });
await sessionDelay(db, s, { reason: "agent", state: "down", exhausted: true, resume: s.id, details: m("{who}: прошлый разговор агента потерян, сам не перезапустится: {reason}.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), reason: blocker }), now: o.now, log: o.log });
return;
}
await patchWatch(db, s, { restartAt: o.now.getTime(), restartReason: "conversation_lost", restartFree: true }, { status: "failed", endedAt: o.now });
}
/** Planned restarts that are due (`failed` runners with `watch_state.restartAt`). */
export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; log: (m: string) => void }): Promise<void> {
const rows = await db
@ -254,11 +275,14 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
await patchWatch(db, s, { ...clear, restarts, screen: undefined, stallAlertAt: undefined });
try {
await resumeSession(db, s.id, {
prompt: free
prompt: ws.restartReason === "conversation_lost"
? "Прошлый разговор потерян (Claude не нашёл его при resume) — это новый разговор. Сверься с peppa.get_task и tasks.md и продолжай с первого невыполненного пункта."
: free
? "Прошлый запуск не смог войти в аккаунт (сбой связи) — это повтор. Продолжай работу с того места, где остановился."
: `Раннер ${ws.restartReason === "stall" ? "завис" : "упал"} и перезапущен вачдогом автоматически (попытка ${restarts.length} из ${o.cfg.restartMax}).`,
});
await logSessionEvent(db, s, free ? "login_retried" : "auto_restarted", { reason: ws.restartReason, attempt: free ? (ws.loginFails ?? 1) : restarts.length, of: free ? LOGIN_RETRY_MIN.length : o.cfg.restartMax });
if (ws.restartReason === "conversation_lost") await logSessionEvent(db, s, "conversation_restarted", {});
else await logSessionEvent(db, s, free ? "login_retried" : "auto_restarted", { reason: ws.restartReason, attempt: free ? (ws.loginFails ?? 1) : restarts.length, of: free ? LOGIN_RETRY_MIN.length : o.cfg.restartMax });
o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`);
if (s.taskId) await clearPlatformDelay(db, { projectId: s.projectId, taskId: s.taskId }, "agent");
} catch (e) {

View File

@ -22,6 +22,7 @@ import {
clearPlatformDelay,
sessionDelay,
updateSession,
alertAdmins,
type SessionView,
expireLoans,
subscriptionWarnTick,
@ -60,8 +61,9 @@ import { productRedeployTick } from "./deploy.ts";
import { productLinkTick } from "./product-link.ts";
import { pickQuestionTick } from "./pick-question.ts";
import { budgetTick } from "./budgets.ts";
import { getWatchdogSettings, idleStopTick, onLoginFailure, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
import { getWatchdogSettings, idleStopTick, LOST_CONVERSATION_RE, onConversationLost, onLoginFailure, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
import { CODEX_LOGIN_FAIL_RE, codexModelMenu, dismissCodexMenu } from "./codex-screen.ts";
import { claudeCreditsDialog, dismissCreditsDialog } from "./claude-screen.ts";
import { serveRunnerCommands, type RunnerService } from "./runner-service.ts";
export interface WatchdogOptions {
@ -238,6 +240,9 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
await logSessionEvent(db, s, "usage_limit", { line, exited: true });
const msg = await recordLimit(db, s, line, nowDate);
if (msg) await limitDelay(db, s, msg, { now: nowDate, log });
} else if (s.provider === "claude" && s.conversationId && LOST_CONVERSATION_RE.test(tail)) {
// PEP-227: the saved conversation is gone — resuming it again would fail the same way.
await onConversationLost(db, s, { now: nowDate, cfg, log });
} else if (s.provider === "codex" && CODEX_LOGIN_FAIL_RE.test(tail)) {
// PEP-205: «account/read failed … timed out» — the way to the provider hiccuped.
await onLoginFailure(db, s, tail, { now: nowDate, cfg, log });
@ -272,6 +277,22 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
else if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await logSessionEvent(db, s, "model_menu_dismissed", {});
await patchWatch(db, s, { menuAt: now });
}
// PEP-227: Claude's «<model> now uses usage credits» dialog waits for a choice — pick «Switch to Opus…»;
// without such a choice the superadmin hears once per generation.
if (s.provider === "claude") {
const dialog = claudeCreditsDialog(screen);
if (dialog?.digit) {
const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000;
if (!again && (await dismissCreditsDialog(tmux.sessionPane(s), screen).catch(() => false))) {
await logSessionEvent(db, s, "model_dialog_dismissed", { choice: dialog.digit });
await patchWatch(db, s, { menuAt: now });
}
} else if (dialog && s.watchState?.creditsAlertGen !== s.generation) {
await patchWatch(db, s, { creditsAlertGen: s.generation });
// glossary-ignore: сообщение мониторинга суперадмину — он меняет модель агентов
await alertAdmins(db, `delay:credits:${s.id}:${s.generation}`, m("{who}: агент ждёт на экране выбора модели — модель просит отдельные кредиты. Укажите агентам другую модель в настройках.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }) }), log);
}
}
// A start that got past the sign-in: earlier sign-in failures are over.
if (s.watchState?.loginFails && s.status === "running") await patchWatch(db, s, { loginFails: undefined });

View File

@ -109,4 +109,6 @@ export const merge_d: Record<string, string> = {
"Не смог уточнить постановку ({why}). Описание задачи не менял — комментарий увидит агент, когда возьмётся за задачу.": "Could not refine the task ({why}). The description is unchanged — the agent will see the comment when it starts on the task.",
"{who}: лимит, свободных подписок нет — продолжит в {time} сам.": "{who}: limit reached, no free subscriptions — will continue at {time} by itself.",
"(лимит сброшен — агент продолжил сам)": "(limit reset — the agent continued by itself)",
"{who}: прошлый разговор агента потерян, сам не перезапустится: {reason}.": "{who}: the agent’s previous conversation is lost and it will not restart by itself: {reason}.",
"{who}: агент ждёт на экране выбора модели — модель просит отдельные кредиты. Укажите агентам другую модель в настройках.": "{who}: the agent is waiting on a model choice screen — the model asks for separate credits. Set another model for agents in the settings.",
};

View File

@ -109,4 +109,6 @@ export const mergeD: Dict = {
"Не смог уточнить постановку ({why}). Описание задачи не менял — комментарий увидит агент, когда возьмётся за задачу.": "Тапсырманы нақтылай алмадым ({why}). Тапсырма сипаттамасын өзгертпедім — пікірді агент тапсырманы қолға алғанда көреді.",
"{who}: лимит, свободных подписок нет — продолжит в {time} сам.": "{who}: лимит, бос жазылымдар жоқ — уақыт {time} болғанда өзі жалғастырады.",
"(лимит сброшен — агент продолжил сам)": "(лимит жаңарды — агент өзі жалғастырды)",
"{who}: прошлый разговор агента потерян, сам не перезапустится: {reason}.": "{who}: агенттің алдыңғы әңгімесі жоғалды, өзі қайта іске қосылмайды: {reason}.",
"{who}: агент ждёт на экране выбора модели — модель просит отдельные кредиты. Укажите агентам другую модель в настройках.": "{who}: агент модель таңдау экранында күтіп тұр — модель бөлек кредиттер сұрайды. Баптауларда агенттерге басқа модель көрсетіңіз.",
};

View File

@ -465,6 +465,12 @@ async function main() {
apiKey: apiKey() ? `…${apiKey()!.slice(-4)}` : null,
});
// PEP-227: the real CLI answers a resume of a conversation it no longer has like this and exits 1.
if (provider === "claude" && args.resume && scenario.forgetResume) {
out(`No conversation found with session ID: ${args.resume}\n`);
log("exit", { code: 1, reason: "no_conversation" });
process.exit(1);
}
if (process.stdin.isTTY) process.stdin.setRawMode(true);
process.stdin.setEncoding("utf8");
process.stdin.on("data", onInput);

View File

@ -30,6 +30,8 @@ export interface Scenario {
turns: Action[][];
/** Used instead of `turns` when the CLI is started with a resume target. */
resumeTurns?: Action[][];
/** PEP-227: Claude forgot every conversation — `--resume <id>` prints «No conversation found…» and exits 1. */
forgetResume?: boolean;
/** PEP-54: env variables the mock prints as `NAME=value` at start and logs (secrets tests). */
echoEnv?: string[];
}

View File

@ -0,0 +1,103 @@
// PEP-227: Claude cannot resume a conversation it no longer has («No conversation found with session
// ID») — the watchdog starts a new conversation instead of resuming the same id in a loop; and the
// «<model> now uses usage credits» dialog does not hold the agent.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, afterEach, describe, test } from "node:test";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET ??= "mock-secret-for-tests";
import { core, db, project, runner, superadmin, teardown, waitFor } from "./helpers.ts";
const { events } = await import("@peppa/db");
const { claudeCreditsDialog } = await import("../../runner/src/claude-screen.ts");
after(teardown);
afterEach(() => runner.setWatchdogSettings(db, ["reset"]));
const MIN = 60_000;
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)));
async function storyAtWork(scenario: Parameters<typeof project>[0]) {
const p = await project(scenario);
await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "in_progress" });
return p;
}
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";
describe("Потерянный разговор — новый запуск, а не resume по кругу", () => {
test("Разговор потерян", async () => {
const p = await storyAtWork({ forgetResume: true, turns: [[{ say: "Жду." }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
const conversationId = await waitFor("conversation saved", async () => (await sess(sid)).conversationId);
// The agent's tmux is gone: a planned restart resumes the saved conversation…
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await sess(sid)).tmuxName}`]);
const t0 = new Date();
await tickAt(t0);
await tickAt(new Date(t0.getTime() + MIN + 1000));
const resumed = await p.waitLog("resume refused", (e) => e.ev === "exit" && e.reason === "no_conversation");
assert.equal(resumed.gen, "2");
assert.equal((await sess(sid)).watchState?.restarts?.length, 1);
// …Claude no longer has it: the conversation is forgotten, a new one starts at once.
const t1 = new Date(t0.getTime() + MIN + 5000);
await waitFor("conversation lost", async () => (await tickAt(t1), (await eventsOf(sid, "conversation_lost")).length));
const [lost] = await eventsOf(sid, "conversation_lost");
assert.equal((lost!.payload as any).conversationId, conversationId);
assert.equal((await sess(sid)).conversationId, null, "the saved conversation is forgotten");
await tickAt(new Date(t1.getTime() + 1000));
const start = await p.waitLog("fresh start", (e) => e.ev === "start" && e.gen === "3");
assert.equal(start.resume, null, "no --resume");
assert.ok((start.argv as string[]).some((a) => a.includes("сверься с peppa.get_task и tasks.md") || a.includes("Сверься с peppa.get_task и tasks.md")), "the prompt sends the agent to get_task and tasks.md");
assert.equal((await sess(sid)).watchState?.restarts?.length, 1, "no automatic restart spent");
assert.equal((await eventsOf(sid, "conversation_restarted")).length, 1);
await runner.stopSession(db, sid);
});
test("Падение без сохранённого разговора", async () => {
const p = await storyAtWork({ turns: [[{ say: "No conversation found with session ID: x" }, { crash: 1 }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
await core.updateSession(db, sid, { conversationId: null });
const t0 = new Date();
await waitFor("restart planned", async () => (await tickAt(t0), (await sess(sid)).watchState?.restartAt));
assert.equal((await sess(sid)).watchState?.restartReason, "crash", "the usual automatic restart");
assert.equal((await eventsOf(sid, "conversation_lost")).length, 0);
await runner.stopSession(db, sid);
});
});
describe("Диалог кредитов модели не держит агента", () => {
test("разбор экрана", () => {
assert.deepEqual(claudeCreditsDialog(`${DIALOG}\n\n\n`), { digit: "2" });
assert.deepEqual(claudeCreditsDialog("Fable 5.2 now uses usage credits\n 1. Continue\n 2. Exit"), { digit: null });
assert.equal(claudeCreditsDialog("⏺ Готово.\n> "), null);
});
test("Есть пункт перехода на Opus", async () => {
const p = await storyAtWork({ turns: [[{ say: DIALOG }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
const [ev] = await waitFor("dismissed", async () => (await tickAt(new Date()), (await eventsOf(sid, "model_dialog_dismissed")).length ? await eventsOf(sid, "model_dialog_dismissed") : null));
assert.equal((ev!.payload as any).choice, "2");
await tickAt(new Date());
assert.equal((await eventsOf(sid, "model_dialog_dismissed")).length, 1, "not pressed again at once");
await runner.stopSession(db, sid);
});
test("Пункта нет", async () => {
const sent = await superadmin();
const p = await storyAtWork({ turns: [[{ say: "Fable 5.2 now uses usage credits\n 1. Continue\n 2. Exit" }]] });
const sid = await p.start();
await p.waitLog("turn 0", (e) => e.ev === "prompt");
const text = await waitFor("superadmin told", async () => (await tickAt(new Date()), (await sent())[0]));
assert.match(text, /просит отдельные кредиты/);
await tickAt(new Date());
assert.equal((await sent()).length, 1, "one message");
await runner.stopSession(db, sid);
});
});