From 311aad4c901b34f0ce2a6bc5236588665fac15d9 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 19:05:39 +0000 Subject: [PATCH 1/5] =?UTF-8?q?PEP-303:=20=D1=81=D1=82=D0=BE=D1=80=D0=BE?= =?UTF-8?q?=D0=B6=D0=B0=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD=D0=B0=20=D1=87?= =?UTF-8?q?=D0=B8=D1=82=D0=B0=D1=8E=D1=82=20=D1=82=D0=BE=D0=BB=D1=8C=D0=BA?= =?UTF-8?q?=D0=BE=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=D0=B8=20CLI,=20=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=B2=D1=8B=D0=B2=D0=BE=D0=B4=20=D0=B8=D0=BD=D1=81?= =?UTF-8?q?=D1=82=D1=80=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=BE=D0=B2=20=D0=B0?= =?UTF-8?q?=D0=B3=D0=B5=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../design.md | 17 ++ .../proposal.md | 20 ++ .../specs/session-watchdog/spec.md | 38 ++++ .../tasks.md | 17 ++ packages/runner/src/claude-screen.ts | 39 +++- packages/runner/src/codex-screen.ts | 7 +- packages/runner/src/limits.ts | 14 +- packages/runner/src/rotation.ts | 4 +- packages/runner/src/screen-lines.ts | 36 ++++ packages/runner/src/start-screen.ts | 10 +- packages/runner/src/watchdog.ts | 13 +- packages/testkit/src/mock-agent.ts | 13 ++ packages/testkit/src/scenario.ts | 6 +- .../testkit/test/lost-conversation.test.ts | 9 +- packages/testkit/test/screen-watchers.test.ts | 173 ++++++++++++++++++ 15 files changed, 390 insertions(+), 26 deletions(-) create mode 100644 openspec/changes/pep-303-screen-watchers-own-lines/design.md create mode 100644 openspec/changes/pep-303-screen-watchers-own-lines/proposal.md create mode 100644 openspec/changes/pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md create mode 100644 openspec/changes/pep-303-screen-watchers-own-lines/tasks.md create mode 100644 packages/runner/src/screen-lines.ts create mode 100644 packages/testkit/test/screen-watchers.test.ts diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/design.md b/openspec/changes/pep-303-screen-watchers-own-lines/design.md new file mode 100644 index 00000000..9c4340ac --- /dev/null +++ b/openspec/changes/pep-303-screen-watchers-own-lines/design.md @@ -0,0 +1,17 @@ +## Context + +Сторожа экрана (PEP-205, PEP-227, PEP-241, PEP-265, PEP-56/166/300) ищут фразы регулярными выражениями в хвосте экрана целиком. Экран работающего агента содержит вывод его инструментов: diff (Claude: ` 447 + код`, Codex: `447 +код`), вывод grep (`путь:12:текст`), `cat` файлов, ответы агента. Платформа FORGE делается своими же агентами, и в её коде эти фразы есть в комментариях, тестах и моках. + +## Decisions + +1. **«Чужая» строка** — `isQuotedLine` (runner/screen-lines.ts): номер строки с `+`/`-` или широким отступом после него (diff, `cat -n`), `число:` в начале (grep -n), строка, начинающаяся с `+`/`-`/`@@` (diff без номеров), `путь:число` (grep). Значок вывода инструмента (`⎿ └ │ ├`) перед ними не спасает. Номер варианта «1. …» не подходит ни под одно правило (после цифры — точка). +2. **Плашка лимита — положительный якорь**, а не поиск фразы где угодно: `LIMIT_LINE_RE` требует, чтобы строка начиналась с фразы лимита, допуская один значок CLI (не `+ - < > | :` и не рамку), `API Error:`, `Claude (AI)`, `5-hour/weekly/Opus weekly`. Без значка — отступ не больше двух пробелов (продолжение вывода инструмента идёт с отступом 5). `LIMIT_SCREEN_RE` остаётся фразой (её используют `parseResetTime` и тесты), но экран читается только через `limitLines`/`isLimitLine`; мёртвое окно — тоже через `limitLines`. +3. **Диалог кредитов — структура**: снизу вверх пропускаются подсказки клавиш, рамки и пустые строки, затем блок вариантов `N. текст` (минимум два, по порядку с 1), над ним (до 8 строк) — строка с фразой, которая начинается с названия модели и не «чужая». Строки в рамке `│ … │` разворачиваются. Приглашение ввода `>` под вариантами означает, что диалог уже не ждёт — `null`. +4. **Неизменность экрана**: вачдог сравнивает хэш экрана с сохранённым в `watch_state.screen` до обновления. Нажатия (кредиты, меню Codex, доверие папке) и сообщение о кредитах — только если экран тот же, что на прошлом проходе: настоящий диалог стоит, работающий агент меняет экран. Это добавляет к реакции один проход вачдога (~30 с) — приемлемо: диалог ждёт сколько угодно. +5. **Остальные сторожа**: `startQuestion` и `usageWarning` читают экран без «чужих» строк (`ownLines`). Плашку лимита в истории разговора после resume по-прежнему считает база PEP-166, срок — PEP-300. +6. Мок: действие `credits` (`{ switch?: boolean }`) — настоящий диалог с ожиданием клавиши, как `menu` у Codex; тесты диалога переведены на него (раньше это была реплика `say`, после которой мок печатал приглашение `>` — такой экран теперь, правильно, не диалог). + +## Risks + +- Настоящие экраны диалога кредитов не сняты (PEP-227) — правило структуры терпимо к рамке, подсказкам и описанию между вопросом и вариантами. Если CLI напишет вопрос с префиксом, которого нет в правиле, будет пропуск диалога; тогда сработает зависание на старте (PEP-265) или «завис» — не ложная тревога. +- Плашка, которую CLI когда-нибудь напечатает с непредусмотренным префиксом, не будет узнана экраном — но у Claude лимит приходит и хуком StopFailure. diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/proposal.md b/openspec/changes/pep-303-screen-watchers-own-lines/proposal.md new file mode 100644 index 00000000..725d69d3 --- /dev/null +++ b/openspec/changes/pep-303-screen-watchers-own-lines/proposal.md @@ -0,0 +1,20 @@ +## Why + +26.11 вачдог дважды принял текст из работы агента за экран самого CLI. В 12:57 суперадмину ушло «агент ждёт на экране выбора модели — модель просит отдельные кредиты»: агент PEP-268 правил watchdog.ts, где эта фраза стоит в комментарии. В 22:25 строка мока `out(`■ You’ve hit your usage limit…`)` в diff стала «плашкой лимита»: подписку пометили «лимит», работающего агента остановили и перезапустили на другой подписке. Агенты FORGE правят код платформы, где все эти фразы написаны, — сторожа экрана должны отличать экран CLI от вывода инструментов. + +## What Changes + +- Диалог «модель просит кредиты» (Claude) — только экран, который ждёт выбора: строка-вопрос (не строка diff/grep/кода), под ней пронумерованные варианты 1…N внизу экрана (ниже — только подсказки клавиш и рамки), и экран не изменился с прошлого прохода вачдога. Тогда — нажатие «Switch to Opus…» или одно сообщение суперадмину, как раньше. +- Меню модели Codex и вопрос о доверии папке: вопрос и варианты ищутся только в строках, которые не похожи на diff, вывод grep или код; нажатие — только на неизменившемся экране. +- Плашка лимита (Claude и Codex, живое и мёртвое окно): строка должна начинаться с фразы лимита (допускаются значок CLI `■ ⎿ ⏺ …`, «API Error:», «Claude (AI)», «5-hour/weekly»). Строка diff (номер, «+»/«-»), вывод grep (`путь:строка:`), код и комментарии плашкой не считаются. +- Вопросы на старте (PEP-265) и предупреждение о пороге подписки читают только «свои» строки экрана. +- Выбор подписки, переключение и учёт срока лимита (PEP-300) не меняются. + +## Capabilities + +### Modified Capabilities +- `session-watchdog`: распознавание экрана CLI отделено от текста в выводе агента. + +## Impact + +`packages/runner/src/screen-lines.ts` (новый), `claude-screen.ts`, `codex-screen.ts`, `start-screen.ts`, `limits.ts`, `rotation.ts` (`usageWarning`), `watchdog.ts`; мок `credits` в `packages/testkit` (`mock-agent.ts`, `scenario.ts`); тест `screen-watchers.test.ts`, правки `lost-conversation.test.ts`. diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md b/openspec/changes/pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md new file mode 100644 index 00000000..6f1257ae --- /dev/null +++ b/openspec/changes/pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md @@ -0,0 +1,38 @@ +## ADDED Requirements + +### Requirement: Экран CLI отличается от вывода агента + +Сторожа экрана вачдога (плашка лимита, диалог кредитов модели Claude, меню модели и доверие папке Codex, вопросы на старте, предупреждение о пороге подписки) SHALL реагировать только на строки, которые печатает сам CLI. Строки diff (номер строки, «+» или «-» перед текстом), вывод grep (`путь:строка:`), код и комментарии SHALL NOT считаться экраном CLI. Диалог, ждущий выбора, SHALL распознаваться только когда под вопросом внизу экрана стоят пронумерованные варианты и экран не изменился с прошлого прохода вачдога; только тогда вачдог нажимает клавишу или сообщает суперадмину. + +#### Scenario: Фраза диалога в diff и выводе grep +- **GIVEN** агент Claude работает над задачей +- **AND** на его экране diff со строкой «331 + // « now uses usage credits»» и вывод grep «docs/a.md:3:1. Switch to Opus 5.5» +- **WHEN** вачдог проходит по экрану два раза подряд +- **THEN** суперадмину не уходит сообщение о кредитах +- **AND** в окно агента не нажата ни одна клавиша + +#### Scenario: Настоящий диалог кредитов +- **GIVEN** агент Claude стоит на экране «Fable 5.2 now uses usage credits» с вариантами «1. Use usage credits», «2. Switch to Opus 5.5», «3. Exit» +- **WHEN** вачдог видит этот экран второй проход подряд +- **THEN** в окно агента нажата клавиша «2» +- **AND** в журнале сессии событие `model_dialog_dismissed` + +#### Scenario: Строка лимита внутри diff +- **GIVEN** агент Codex работает на подписке №1 +- **AND** на его экране строка diff «447 + out(`■ You’ve hit your usage limit. Try again at 8:47 PM.`)» +- **WHEN** вачдог проходит по экрану +- **THEN** события `usage_limit` нет +- **AND** подписка №1 не помечена «лимит» +- **AND** агент продолжает работать + +#### Scenario Outline: Настоящая плашка лимита +- **GIVEN** агент на подписке, у которой кончился лимит +- **AND** CLI печатает «<строка>» +- **WHEN** вачдог проходит по экрану (<окно>) +- **THEN** в журнале событие `usage_limit` с этой строкой + +| cli | строка | окно | +|---|---|---| +| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | живое | +| Claude | ⎿ Claude usage limit reached. Your limit will reset at 9pm. | живое | +| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | мёртвое | diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md b/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md new file mode 100644 index 00000000..4e1f4b4e --- /dev/null +++ b/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md @@ -0,0 +1,17 @@ +## 1. Распознавание экрана + +- [ ] 1.1 `screen-lines.ts`: `isQuotedLine`, `ownLines`, `unbox` +- [ ] 1.2 Плашка лимита: `LIMIT_LINE_RE`/`isLimitLine`, `limitLines` через неё; мёртвое окно в вачдоге — через `limitLines` +- [ ] 1.3 Диалог кредитов: структура «вопрос → варианты внизу» +- [ ] 1.4 Меню модели и доверие папке Codex, `startQuestion`, `usageWarning` — только «свои» строки +- [ ] 1.5 Вачдог: нажатия и сообщение о кредитах — только на неизменившемся экране + +## 2. Тесты + +- [ ] 2.1 Мок `credits`; тесты диалога в `lost-conversation.test.ts` — на нём +- [ ] 2.2 `screen-watchers.test.ts`: diff/grep с фразой и «1. Switch to Opus» — нет тревоги и нажатия; строка лимита в diff — нет `usage_limit`, подписка не помечена, агент не остановлен; настоящие плашки Claude/Codex на живом и мёртвом окне узнаются +- [ ] 2.3 Проверить, что новые тесты падают на старом коде; прогнать связанные тесты (limits, codex-recovery, start-hang, lost-conversation, subscription-*) + +## 3. Завершение + +- [ ] 3.1 Память, archive, PR diff --git a/packages/runner/src/claude-screen.ts b/packages/runner/src/claude-screen.ts index 8975b50a..35b96665 100644 --- a/packages/runner/src/claude-screen.ts +++ b/packages/runner/src/claude-screen.ts @@ -1,18 +1,41 @@ // PEP-227: what the Claude CLI shows on its screen when it is not the agent's work that stopped it — // the « 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. +// patterns are lenient about wording, strict about shape (PEP-303): a question, choices at the bottom. import * as tmux from "./tmux.ts"; +import { isQuotedLine, screenBottom, unbox } from "./screen-lines.ts"; -const CREDITS_RE = /now uses (?:usage )?credits/i; -const SWITCH_RE = /^\s*(?:[›❯>]\s*)?(\d)[.)]\s*Switch to Opus\b/im; +// PEP-303: the question line begins with the model's name («Fable 5.2 now uses usage credits») after at +// most one glyph of the CLI — not a comment, a string in code or a sentence that quotes it. +const CREDITS_LINE_RE = /^\s*(?:[^\w\s"'`«(\[{<>|:+\-#*\/]\s*)?[\w .-]{0,40}?\bnow uses (?:usage )?credits\b/iu; +const CHOICE_RE = /^\s*(?:[›❯>]\s*)?(\d)[.)]\s+(\S.*)$/; +const SWITCH_RE = /^Switch to Opus\b/i; +/** Below a waiting dialog: blank rows, its frame and key hints («Enter to confirm · Esc to cancel»). */ +const FOOTER_RE = /^\s*$|^[\s─━═╭╮╰╯┌┐└┘]+$|\b(?:enter|esc|tab)\b|↑|↓|to (?:select|confirm|cancel|navigate)/i; -/** The credits dialog is on screen: `{ digit }` of «Switch to Opus…» (null when there is no such choice), else null. */ +/** + * The credits dialog waits on screen: `{ digit }` of «Switch to Opus…» (null when there is no such + * choice), else null. PEP-303: a dialog is the question, numbered choices 1…N under it at the bottom + * of the screen and nothing below them but key hints — a diff, grep output or the agent's answer + * that mentions the phrase is not one (the caller also wants the screen unchanged between two passes). + */ 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 }; + const lines = screenBottom(screen, 30).map(unbox); + let end = lines.length; + while (end > 0 && !CHOICE_RE.test(lines[end - 1]!) && FOOTER_RE.test(lines[end - 1]!)) end--; + // The choices block, bottom up (blank rows between choices are allowed). + const choices: { n: number; text: string }[] = []; + let i = end - 1; + for (; i >= 0; i--) { + const c = CHOICE_RE.exec(lines[i]!); + if (c && !isQuotedLine(lines[i]!)) choices.unshift({ n: Number(c[1]), text: c[2]!.trim() }); + else if (!lines[i]!.trim() && choices.length) continue; + else break; + } + if (choices.length < 2 || choices.some((c, k) => c.n !== k + 1)) return null; + const question = lines.slice(Math.max(0, i - 7), i + 1).some((l) => CREDITS_LINE_RE.test(l) && !isQuotedLine(l)); + if (!question) return null; + return { digit: String(choices.find((c) => SWITCH_RE.test(c.text))?.n ?? "") || null }; } /** Picks «Switch to Opus…» in the credits dialog. Returns true when a key was sent. */ diff --git a/packages/runner/src/codex-screen.ts b/packages/runner/src/codex-screen.ts index fef4ba4e..4595b927 100644 --- a/packages/runner/src/codex-screen.ts +++ b/packages/runner/src/codex-screen.ts @@ -2,6 +2,7 @@ // the «Switch to ?» menu near the limit and a sign-in hiccup. Kept apart from the watchdog so // the texts can be checked on real screens (packages/testkit/fixtures). import * as tmux from "./tmux.ts"; +import { ownLines, screenBottom } from "./screen-lines.ts"; /** «Switch to gpt-… for lower credit usage?» with its three choices. */ const MENU_QUESTION_RE = /Switch to \S+.*\?/; @@ -9,8 +10,8 @@ const MENU_KEEP_RE = /^\s*(?:›\s*)?(\d)\.\s*Keep current model\s*$/m; /** The digit of «Keep current model» when the model menu is on screen, else null. */ export function codexModelMenu(screen: string): string | null { - // The pane is padded with blank rows below the text. - const tail = screen.trimEnd().split("\n").slice(-25).join("\n"); + // PEP-303: a diff or grep output that quotes the menu is not the menu. + const tail = ownLines(screenBottom(screen, 25).join("\n")); if (!MENU_QUESTION_RE.test(tail) || !/enter select/i.test(tail)) return null; return MENU_KEEP_RE.exec(tail)?.[1] ?? null; } @@ -38,7 +39,7 @@ export interface CodexTrustPrompt { /** The trust question on Codex's screen: the digit of «Trust and continue» and the folders it names. */ export function codexTrustPrompt(screen: string): CodexTrustPrompt | null { - const tail = screen.trimEnd().split("\n").slice(-30).join("\n"); + const tail = ownLines(screenBottom(screen, 30).join("\n")); if (!TRUST_QUESTION_RE.test(tail)) return null; const digit = TRUST_YES_RE.exec(tail)?.[1]; if (!digit) return null; diff --git a/packages/runner/src/limits.ts b/packages/runner/src/limits.ts index 5c0b378e..c9b03f85 100644 --- a/packages/runner/src/limits.ts +++ b/packages/runner/src/limits.ts @@ -3,6 +3,7 @@ import { m } from "@peppa/shared/i18n"; import { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core"; import type { Db } from "@peppa/db"; import { planRotation } from "./rotation.ts"; +import { isQuotedLine } from "./screen-lines.ts"; /** PEP-107: what to do so agents don't wait for a reset next time. */ export const ADD_SUBSCRIPTION_HINT = m("Чтобы агенты не ждали — добавьте ещё одну подписку Claude или ChatGPT: «Настройки проекта → Подписки»."); @@ -16,8 +17,19 @@ const REPEAT_WINDOW_MS = 5 * 60_000; // PEP-205: Codex prints a typographic apostrophe — «You’ve hit your usage limit … try again at 8:47 PM». export const LIMIT_SCREEN_RE = /(usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (usage )?limit|out of extra usage)/i; +// PEP-303: a banner is a line the CLI printed, so it *begins* with the limit phrase — after at most one +// glyph of the CLI («■ ⎿ ⏺ ● ✗ ⚠ ·»; not «+ - < > | : # * /» nor a frame) and the words it puts in front +// («API Error:», «Claude (AI)», «5-hour», «weekly»). A diff line («447 + out(`■ You’ve hit…`)»), grep +// output, code or a comment that quotes the phrase is not a banner. Without a glyph the line may be +// indented by two spaces at most: the continuation lines of a tool's output are indented by five. +const LIMIT_LINE_RE = + /^(?:\s*[^\w\s"'`(\[{<>|:+\-#*\/─-╿]️?\s*|\s{0,2})(?:API Error:\s*)?(?:Claude(?: AI)?\s+|(?:\d+-hour|(?:opus\s+)?weekly)\s+)?(?:you[’'`]re\s+)?(?:usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (?:usage )?limit|out of extra usage)/iu; + +/** One screen line is the CLI's limit banner (see LIMIT_LINE_RE), not a quote of it. */ +export const isLimitLine = (line: string): boolean => LIMIT_LINE_RE.test(line) && !isQuotedLine(line); + /** Limit banner lines on a captured screen, top to bottom. */ -export const limitLines = (screen: string): string[] => screen.split("\n").filter((l) => LIMIT_SCREEN_RE.test(l)).map((l) => l.trim()); +export const limitLines = (screen: string): string[] => screen.split("\n").filter(isLimitLine).map((l) => l.trim()); /** * PEP-166: is there a limit banner that was not on the screen when this generation started? diff --git a/packages/runner/src/rotation.ts b/packages/runner/src/rotation.ts index 596d9195..196fea12 100644 --- a/packages/runner/src/rotation.ts +++ b/packages/runner/src/rotation.ts @@ -22,6 +22,7 @@ import { events, type Db } from "@peppa/db"; import { and, count, eq, gte } from "drizzle-orm"; import * as tmux from "./tmux.ts"; import { isRunnerClient, runnerCall } from "./runner-client.ts"; +import { ownLines } from "./screen-lines.ts"; export const SWITCH_EVENT = "subscription_switched"; export const ROTATE_WINDOW_MS = 60 * 60_000; @@ -171,7 +172,8 @@ const WARN_RE = /(approaching (?:your )?(?:usage )?limit|(\d{1,3})\s?% of your [ /** True when the screen shows a usage warning at or above the threshold. */ export function usageWarning(screen: string): boolean { - const m = WARN_RE.exec(screen); + // PEP-303: not a warning quoted by a diff or grep output. + const m = WARN_RE.exec(ownLines(screen)); if (!m) return false; const pct = Number(m[2] ?? m[3] ?? NaN); return Number.isNaN(pct) || pct >= rotateThresholdPct(); diff --git a/packages/runner/src/screen-lines.ts b/packages/runner/src/screen-lines.ts new file mode 100644 index 00000000..5ad2bc19 --- /dev/null +++ b/packages/runner/src/screen-lines.ts @@ -0,0 +1,36 @@ +// PEP-303: the watchdog's screen guards look for phrases the agent CLI prints (a limit banner, a +// model dialog, a trust question). FORGE agents edit FORGE's own code, where these phrases stand in +// comments, tests and mocks — and a diff, a grep hit or a `cat` of such a file lands on the agent's +// screen. These helpers tell the CLI's own lines from text quoted by the agent's tools. + +/** A tool-output gutter glyph that may precede a quoted line: Claude «⎿», Codex «└ │ ├». */ +const GUTTER = String.raw`(?:[⎿└│├]\s*)?`; + +const QUOTED: RegExp[] = [ + // A diff or `cat -n` with line numbers: « 447 + code», «447 -x», « 12 context», grep -n «12:text». + new RegExp(String.raw`^\s*${GUTTER}\d+(?:\s+[+-]|\s{2,}\S|:\S)`), + // A diff without numbers: «+code», «- code», «@@ -1,3 +1,4 @@». + new RegExp(String.raw`^\s*${GUTTER}(?:[+-]|@@)`), + // grep / compiler output: «path/to/file.ts:12:text», «file.md:3-…». + new RegExp(String.raw`^\s*${GUTTER}[^\s:]+:\d+[:-]`), +]; + +/** True when the line is text the agent's tools quoted (a diff, grep output, numbered source), not the CLI's own UI. */ +export function isQuotedLine(line: string): boolean { + return QUOTED.some((re) => re.test(line)); +} + +/** A line of a boxed dialog without its frame: «│ Do you trust…? │» → «Do you trust…?». */ +export function unbox(line: string): string { + return line.replace(/^\s*[│┃]\s?/, "").replace(/\s*[│┃]\s*$/, "").trimEnd(); +} + +/** The screen without quoted lines (see `isQuotedLine`). */ +export function ownLines(screen: string): string { + return screen.split("\n").filter((l) => !isQuotedLine(l)).join("\n"); +} + +/** The last `n` rows of a pane, without the blank rows that pad it below the text. */ +export function screenBottom(screen: string, n: number): string[] { + return screen.trimEnd().split("\n").slice(-n); +} diff --git a/packages/runner/src/start-screen.ts b/packages/runner/src/start-screen.ts index dc7f59e1..9d597c57 100644 --- a/packages/runner/src/start-screen.ts +++ b/packages/runner/src/start-screen.ts @@ -4,26 +4,30 @@ // read, and the watchdog asks only while the agent has made no action yet. import { claudeCreditsDialog } from "./claude-screen.ts"; import { codexModelMenu, codexTrustPrompt } from "./codex-screen.ts"; +import { ownLines, screenBottom } from "./screen-lines.ts"; export type StartQuestion = "trust" | "model" | "login" | "setup"; const CLAUDE: [StartQuestion, RegExp][] = [ ["trust", /Do you trust the files in this folder\?|Is this a project you (?:created|trust)|Quick safety check|Yes, I trust this folder|Yes, proceed\b/i], - ["model", /now uses (?:usage )?credits|Select model\b|Choose (?:a|the|your) model/i], + // PEP-303: the credits dialog — only by its shape (`claudeCreditsDialog`), the phrase alone may be quoted. + ["model", /Select model\b|Choose (?:a|the|your) model/i], ["login", /Select login method|Please run \/login|Invalid API key|Not logged in|OAuth token has expired|Paste code here/i], ["setup", /Choose the text style|Bypass Permissions mode|Yes, I accept|Use Claude Code's terminal setup|Press Enter to continue/i], ]; const CODEX: [StartQuestion, RegExp][] = [ ["trust", /Trust this folder\?|Do you trust the contents of this directory\?|Folder access/i], - ["model", /Switch to \S+.*\?|Choose (?:a|the|your) model/i], + // PEP-303: the «Switch to …?» menu — only by its shape (`codexModelMenu`). + ["model", /Choose (?:a|the|your) model/i], ["login", /Sign in with ChatGPT|Provide your own API key|Finish signing in|Login with ChatGPT/i], ["setup", /Approval mode|Allow Codex to work in this folder|Press enter to continue/i], ]; /** Which question the CLI waits on (null — none recognized). `provider`: "claude" | "codex". */ export function startQuestion(provider: string, screen: string): StartQuestion | null { - const tail = screen.trimEnd().split("\n").slice(-30).join("\n"); + // PEP-303: a resumed conversation shows its history — quoted diffs and grep output are not questions. + const tail = ownLines(screenBottom(screen, 30).join("\n")); if (!tail.trim()) return null; if (provider === "codex") { if (codexTrustPrompt(tail)) return "trust"; diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 66fb85c2..495ae226 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -35,7 +35,7 @@ import { projects, type Db } from "@peppa/db"; import { eq } from "drizzle-orm"; import { realpathSync } from "node:fs"; import * as tmux from "./tmux.ts"; -import { ADD_SUBSCRIPTION_HINT, freshLimitLine, LIMIT_SCREEN_RE, limitLines, passedReset, recordLimit } from "./limits.ts"; +import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, passedReset, recordLimit } from "./limits.ts"; import { limitDelay, limitOver } from "./limit-delay.ts"; import { checksQueueTick, platformDelayTick } from "./platform-delays.ts"; import { readyDigestTick } from "./ready-digest.ts"; @@ -271,7 +271,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail }); await killRunner(s).catch(() => {}); if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() }); - else if (LIMIT_SCREEN_RE.test(tail) && !passedReset(limitLines(tail).at(-1)!, nowDate)) { + else if (limitLines(tail).length && !passedReset(limitLines(tail).at(-1)!, nowDate)) { // PEP-205: the CLI gave up on a usage limit — that is a limit, not a crash: another subscription // or a pause until the reset, no automatic restart is spent. const line = limitLines(tail).at(-1)!; @@ -297,6 +297,9 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: const hash = createHash("sha1").update(screen).digest("hex"); const now = (opts.now ?? new Date()).getTime(); let last = s.lastActivityAt?.getTime() ?? now; + // PEP-303: a dialog waits — its screen stands still between two passes; a working agent's screen + // moves (and may well show the dialog's phrase in a diff). Keys and alerts only on a still screen. + const still = s.watchState?.screen === hash; // PEP-28: the screen hash lives in the DB — a restarted watchdog does not see "new activity". if (s.watchState?.screen !== hash) { last = now; @@ -310,7 +313,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: // PEP-205: Codex's «Switch to ?» menu waits for a key and swallows whatever is typed next — // answer «Keep current model» (the digit, then Enter if the menu is still there a tick later). - if (s.provider === "codex" && codexModelMenu(screen)) { + if (still && s.provider === "codex" && codexModelMenu(screen)) { const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000; if (again) await tmux.sendKeys(tmux.sessionPane(s), "Enter").catch(() => {}); else if (await dismissCodexMenu(tmux.sessionPane(s), screen).catch(() => false)) await logSessionEvent(db, s, "model_menu_dismissed", {}); @@ -318,7 +321,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: } // PEP-241: «Trust this folder?» waits for a key before the first turn — answer «Trust and continue», // only for the folder Peppa gave the agent (its worktree, the project's copy and their repository roots). - if (s.provider === "codex" && codexTrustPrompt(screen) && !(s.watchState?.menuAt && now - s.watchState.menuAt < 120_000)) { + if (still && s.provider === "codex" && codexTrustPrompt(screen) && !(s.watchState?.menuAt && now - s.watchState.menuAt < 120_000)) { const allowed = await agentFolders(db, s); const res = await dismissCodexTrust(tmux.sessionPane(s), screen, allowed).catch(() => null); if (res === "sent") await logSessionEvent(db, s, "trust_dismissed", {}); @@ -327,7 +330,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: } // PEP-227: Claude's « 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") { + if (still && s.provider === "claude") { const dialog = claudeCreditsDialog(screen); if (dialog?.digit) { const again = !!s.watchState?.menuAt && now - s.watchState.menuAt < 120_000; diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index b2a0240f..98e55742 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -414,6 +414,14 @@ async function run(action: Action): Promise { log("menu", { key }); out(key === "1" ? "• Switched to gpt-6-luna\n" : "• Keeping the current model\n"); mode = "busy"; + } else if ("credits" in action) { + const spec = typeof action.credits === "object" ? action.credits : {}; + const choices = spec.switch === false ? ["Continue", "Exit"] : ["Use usage credits", "Switch to Opus 5.5", "Exit"]; + out(`\n Fable 5.2 now uses usage credits\n\n${choices.map((c, i) => `${i ? " " : "❯ "}${i + 1}. ${c}`).join("\n")}\n\n Enter to confirm · Esc to cancel\n`); + const key = await dialog(); + log("credits", { key }); + out(`⏺ ${key === "2" && spec.switch !== false ? "Switched to Opus 5.5" : "Continuing"}\n`); + mode = "busy"; } else if ("trust" in action) { const spec = typeof action.trust === "object" ? action.trust : {}; out(` Folder access\n\n Trust this folder?\n ${spec.path ?? cwd}\n\n› 1. Trust and continue\n 2. Back to Agent Command Center\n\n enter select · esc back\n`); @@ -447,6 +455,11 @@ async function run(action: Action): Promise { out(`■ You’ve hit your usage limit.${spec.reset === "unknown" ? "" : ` Try again at ${at}.`}\n`); } log("limit"); + // PEP-303: the CLI gives up on the limit — the banner stays in a dead window. + if (spec.exit != null) { + log("exit", { code: spec.exit, reason: "limit" }); + process.exit(spec.exit); + } return false; } else if ("hang" in action) { log("hang"); diff --git a/packages/testkit/src/scenario.ts b/packages/testkit/src/scenario.ts index 3ef28fda..57438475 100644 --- a/packages/testkit/src/scenario.ts +++ b/packages/testkit/src/scenario.ts @@ -10,8 +10,9 @@ export type Action = | { permission: { tool: string; input: Record } } // claude: PermissionRequest | { ask: Array<{ question: string; options?: string[] }> } // claude: AskUserQuestion // usage limit: StopFailure (claude) / banner only (codex); resetInSec → "resets at HH:MM"; + // exit → the CLI quits with this code after the banner (PEP-303); // credential → only when the run's login (Claude token, Codex auth.json, OpenCode key) contains it - | { limit: true | { resetInSec?: number; reset?: "unknown"; credential?: string } } + | { limit: true | { resetInSec?: number; reset?: "unknown"; credential?: string; exit?: number } } // PEP-5: an assistant message with this token usage in the transcript, then (claude) the // statusLine command with cost / context / limit windows (pct, reset in N seconds) | { usage: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; model?: string; costUsd?: number; context?: { used: number; size: number }; fiveHour?: number; sevenDay?: number; resetInSec?: number } } @@ -21,6 +22,9 @@ export type Action = // PEP-241 (codex 0.171): «Folder access — Trust this folder?» about `path` (default: the cwd) — waits // for a key, logs `trust` with it; «2» (back) ends the run | { trust: true | { path?: string } } + // PEP-227/303 (claude): «Fable 5.2 now uses usage credits» with numbered choices — waits for a key, logs + // `credits` with it; `switch: false` — no «Switch to Opus…» choice + | { credits: true | { switch?: boolean } } // PEP-205 (codex): the CLI cannot sign in — «account/read failed … timed out», exit 1 | { loginFail: true } | { warn: number } // usage warning banner: "You've used N% of your weekly limit" diff --git a/packages/testkit/test/lost-conversation.test.ts b/packages/testkit/test/lost-conversation.test.ts index 76431568..009c28b7 100644 --- a/packages/testkit/test/lost-conversation.test.ts +++ b/packages/testkit/test/lost-conversation.test.ts @@ -81,11 +81,12 @@ describe("Диалог кредитов модели не держит аген }); test("Есть пункт перехода на Opus", async () => { - const p = await storyAtWork({ turns: [[{ say: DIALOG }]] }); + const p = await storyAtWork({ turns: [[{ credits: true }]] }); const sid = await p.start(); - await p.waitLog("turn 0", (e) => e.ev === "prompt"); + await p.waitLog("dialog", (e) => e.ev === "dialog"); 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"); + assert.equal((await p.waitLog("key", (e) => e.ev === "credits")).key, "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); @@ -93,9 +94,9 @@ describe("Диалог кредитов модели не держит аген 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 p = await storyAtWork({ turns: [[{ credits: { switch: false } }]] }); const sid = await p.start(); - await p.waitLog("turn 0", (e) => e.ev === "prompt"); + await p.waitLog("dialog", (e) => e.ev === "dialog"); const text = await waitFor("superadmin told", async () => (await tickAt(new Date()), (await sent())[0])); assert.match(text, /просит отдельные кредиты/); await tickAt(new Date()); diff --git a/packages/testkit/test/screen-watchers.test.ts b/packages/testkit/test/screen-watchers.test.ts new file mode 100644 index 00000000..a6b532c2 --- /dev/null +++ b/packages/testkit/test/screen-watchers.test.ts @@ -0,0 +1,173 @@ +// 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); + }); +}); -- 2.45.2 From 63ef12a1008311b5ee2f463c1e35265327c4c1e9 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 19:09:28 +0000 Subject: [PATCH 2/5] =?UTF-8?q?PEP-303:=20=D0=BF=D0=BB=D0=B0=D1=88=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BB=D0=B8=D0=BC=D0=B8=D1=82=D0=B0=20=E2=80=94=20?= =?UTF-8?q?=D0=B4=D0=BE=20=D0=B4=D0=B2=D1=83=D1=85=20=D0=B7=D0=BD=D0=B0?= =?UTF-8?q?=D1=87=D0=BA=D0=BE=D0=B2=20CLI=20=D0=BF=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=20=D1=84=D1=80=D0=B0=D0=B7=D0=BE=D0=B9;=20=D0=B7=D0=B0=D0=B4?= =?UTF-8?q?=D0=B0=D1=87=D0=B8=20=D0=BE=D1=82=D0=BC=D0=B5=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../pep-303-screen-watchers-own-lines/tasks.md | 16 ++++++++-------- packages/runner/src/limits.ts | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md b/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md index 4e1f4b4e..2fc526c1 100644 --- a/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md +++ b/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md @@ -1,16 +1,16 @@ ## 1. Распознавание экрана -- [ ] 1.1 `screen-lines.ts`: `isQuotedLine`, `ownLines`, `unbox` -- [ ] 1.2 Плашка лимита: `LIMIT_LINE_RE`/`isLimitLine`, `limitLines` через неё; мёртвое окно в вачдоге — через `limitLines` -- [ ] 1.3 Диалог кредитов: структура «вопрос → варианты внизу» -- [ ] 1.4 Меню модели и доверие папке Codex, `startQuestion`, `usageWarning` — только «свои» строки -- [ ] 1.5 Вачдог: нажатия и сообщение о кредитах — только на неизменившемся экране +- [x] 1.1 `screen-lines.ts`: `isQuotedLine`, `ownLines`, `unbox` +- [x] 1.2 Плашка лимита: `LIMIT_LINE_RE`/`isLimitLine`, `limitLines` через неё; мёртвое окно в вачдоге — через `limitLines` +- [x] 1.3 Диалог кредитов: структура «вопрос → варианты внизу» +- [x] 1.4 Меню модели и доверие папке Codex, `startQuestion`, `usageWarning` — только «свои» строки +- [x] 1.5 Вачдог: нажатия и сообщение о кредитах — только на неизменившемся экране ## 2. Тесты -- [ ] 2.1 Мок `credits`; тесты диалога в `lost-conversation.test.ts` — на нём -- [ ] 2.2 `screen-watchers.test.ts`: diff/grep с фразой и «1. Switch to Opus» — нет тревоги и нажатия; строка лимита в diff — нет `usage_limit`, подписка не помечена, агент не остановлен; настоящие плашки Claude/Codex на живом и мёртвом окне узнаются -- [ ] 2.3 Проверить, что новые тесты падают на старом коде; прогнать связанные тесты (limits, codex-recovery, start-hang, lost-conversation, subscription-*) +- [x] 2.1 Мок `credits`; тесты диалога в `lost-conversation.test.ts` — на нём +- [x] 2.2 `screen-watchers.test.ts`: diff/grep с фразой и «1. Switch to Opus» — нет тревоги и нажатия; строка лимита в diff — нет `usage_limit`, подписка не помечена, агент не остановлен; настоящие плашки Claude/Codex на живом и мёртвом окне узнаются +- [x] 2.3 Проверить, что новые тесты падают на старом коде; прогнать связанные тесты (limits, codex-recovery, start-hang, lost-conversation, subscription-*) ## 3. Завершение diff --git a/packages/runner/src/limits.ts b/packages/runner/src/limits.ts index c9b03f85..a7357057 100644 --- a/packages/runner/src/limits.ts +++ b/packages/runner/src/limits.ts @@ -17,13 +17,13 @@ const REPEAT_WINDOW_MS = 5 * 60_000; // PEP-205: Codex prints a typographic apostrophe — «You’ve hit your usage limit … try again at 8:47 PM». export const LIMIT_SCREEN_RE = /(usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (usage )?limit|out of extra usage)/i; -// PEP-303: a banner is a line the CLI printed, so it *begins* with the limit phrase — after at most one -// glyph of the CLI («■ ⎿ ⏺ ● ✗ ⚠ ·»; not «+ - < > | : # * /» nor a frame) and the words it puts in front +// PEP-303: a banner is a line the CLI printed, so it *begins* with the limit phrase — after at most two +// glyphs of the CLI («■ ⎿ ⏺ ● ✗ ⚠ ·»; not «+ - < > | : # * /» nor a frame) and the words it puts in front // («API Error:», «Claude (AI)», «5-hour», «weekly»). A diff line («447 + out(`■ You’ve hit…`)»), grep // output, code or a comment that quotes the phrase is not a banner. Without a glyph the line may be // indented by two spaces at most: the continuation lines of a tool's output are indented by five. const LIMIT_LINE_RE = - /^(?:\s*[^\w\s"'`(\[{<>|:+\-#*\/─-╿]️?\s*|\s{0,2})(?:API Error:\s*)?(?:Claude(?: AI)?\s+|(?:\d+-hour|(?:opus\s+)?weekly)\s+)?(?:you[’'`]re\s+)?(?:usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (?:usage )?limit|out of extra usage)/iu; + /^(?:(?:\s*[^\w\s"'`(\[{<>|:+\-#*\/─-╿]️?){1,2}\s*|\s{0,2})(?:API Error:\s*)?(?:Claude(?: AI)?\s+|(?:\d+-hour|(?:opus\s+)?weekly)\s+)?(?:you[’'`]re\s+)?(?:usage limit reached|limit reached.{0,40}reset|you[’'`]ve hit your (?:usage )?limit|out of extra usage)/iu; /** One screen line is the CLI's limit banner (see LIMIT_LINE_RE), not a quote of it. */ export const isLimitLine = (line: string): boolean => LIMIT_LINE_RE.test(line) && !isQuotedLine(line); -- 2.45.2 From d19881899698e83d782929d4668399015a6cc9b4 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 19:10:07 +0000 Subject: [PATCH 3/5] =?UTF-8?q?PEP-303:=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82?= =?UTF-8?q?=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0,=20archive?= =?UTF-8?q?=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .peppa/memory.md | 5 +-- .../design.md | 0 .../proposal.md | 0 .../specs/session-watchdog/spec.md | 0 .../tasks.md | 2 +- openspec/specs/session-watchdog/spec.md | 37 +++++++++++++++++++ 6 files changed, 40 insertions(+), 4 deletions(-) rename openspec/changes/{pep-303-screen-watchers-own-lines => archive/2026-11-26-pep-303-screen-watchers-own-lines}/design.md (100%) rename openspec/changes/{pep-303-screen-watchers-own-lines => archive/2026-11-26-pep-303-screen-watchers-own-lines}/proposal.md (100%) rename openspec/changes/{pep-303-screen-watchers-own-lines => archive/2026-11-26-pep-303-screen-watchers-own-lines}/specs/session-watchdog/spec.md (100%) rename openspec/changes/{pep-303-screen-watchers-own-lines => archive/2026-11-26-pep-303-screen-watchers-own-lines}/tasks.md (97%) diff --git a/.peppa/memory.md b/.peppa/memory.md index f8f59c81..54f040af 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -18,14 +18,13 @@ - mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`. - git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент. - Новая фраза Claude о лимите — в `parseResetTime` и limits.test.ts. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env. -- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`. +- Правишь live.ts — перезапусти server.ts, не `pkill -f next-server`. - observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее. - Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0). - Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts). - SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234). - QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить. - Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes. -- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare). - Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами. - Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать. - Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`. @@ -34,7 +33,7 @@ - `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299). - Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265). - Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh). -- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287). +- Сторож экрана (PEP-303): строки — через `screen-lines.ts` (`isQuotedLine`/`ownLines`), фразу CLI якорить к началу строки, нажимать только на неизменном экране (`still`). Мок `say` печатает «⏺ » перед текстом. - Пропал `.git/worktrees/s`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`. - Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <версия>` (json + оба Dockerfile), откат `--rollback`. - Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`). diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/design.md b/openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/design.md similarity index 100% rename from openspec/changes/pep-303-screen-watchers-own-lines/design.md rename to openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/design.md diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/proposal.md b/openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/proposal.md similarity index 100% rename from openspec/changes/pep-303-screen-watchers-own-lines/proposal.md rename to openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/proposal.md diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md b/openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md similarity index 100% rename from openspec/changes/pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md rename to openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/specs/session-watchdog/spec.md diff --git a/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md b/openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/tasks.md similarity index 97% rename from openspec/changes/pep-303-screen-watchers-own-lines/tasks.md rename to openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/tasks.md index 2fc526c1..7b37ee20 100644 --- a/openspec/changes/pep-303-screen-watchers-own-lines/tasks.md +++ b/openspec/changes/archive/2026-11-26-pep-303-screen-watchers-own-lines/tasks.md @@ -14,4 +14,4 @@ ## 3. Завершение -- [ ] 3.1 Память, archive, PR +- [x] 3.1 Память, archive, PR diff --git a/openspec/specs/session-watchdog/spec.md b/openspec/specs/session-watchdog/spec.md index a32b3045..550696a4 100644 --- a/openspec/specs/session-watchdog/spec.md +++ b/openspec/specs/session-watchdog/spec.md @@ -67,3 +67,40 @@ - **WHEN** на экране появляется «Usage limit reached · resets 3pm» - **THEN** сессия `rate_limited` со временем продолжения 15:00 - **AND** на следующих проходах в том же поколении повторной обработки нет + +### Requirement: Экран CLI отличается от вывода агента + +Сторожа экрана вачдога (плашка лимита, диалог кредитов модели Claude, меню модели и доверие папке Codex, вопросы на старте, предупреждение о пороге подписки) SHALL реагировать только на строки, которые печатает сам CLI. Строки diff (номер строки, «+» или «-» перед текстом), вывод grep (`путь:строка:`), код и комментарии SHALL NOT считаться экраном CLI. Диалог, ждущий выбора, SHALL распознаваться только когда под вопросом внизу экрана стоят пронумерованные варианты и экран не изменился с прошлого прохода вачдога; только тогда вачдог нажимает клавишу или сообщает суперадмину. + +#### Scenario: Фраза диалога в diff и выводе grep +- **GIVEN** агент Claude работает над задачей +- **AND** на его экране diff со строкой «331 + // « now uses usage credits»» и вывод grep «docs/a.md:3:1. Switch to Opus 5.5» +- **WHEN** вачдог проходит по экрану два раза подряд +- **THEN** суперадмину не уходит сообщение о кредитах +- **AND** в окно агента не нажата ни одна клавиша + +#### Scenario: Настоящий диалог кредитов +- **GIVEN** агент Claude стоит на экране «Fable 5.2 now uses usage credits» с вариантами «1. Use usage credits», «2. Switch to Opus 5.5», «3. Exit» +- **WHEN** вачдог видит этот экран второй проход подряд +- **THEN** в окно агента нажата клавиша «2» +- **AND** в журнале сессии событие `model_dialog_dismissed` + +#### Scenario: Строка лимита внутри diff +- **GIVEN** агент Codex работает на подписке №1 +- **AND** на его экране строка diff «447 + out(`■ You’ve hit your usage limit. Try again at 8:47 PM.`)» +- **WHEN** вачдог проходит по экрану +- **THEN** события `usage_limit` нет +- **AND** подписка №1 не помечена «лимит» +- **AND** агент продолжает работать + +#### Scenario Outline: Настоящая плашка лимита +- **GIVEN** агент на подписке, у которой кончился лимит +- **AND** CLI печатает «<строка>» +- **WHEN** вачдог проходит по экрану (<окно>) +- **THEN** в журнале событие `usage_limit` с этой строкой + +| cli | строка | окно | +|---|---|---| +| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | живое | +| Claude | ⎿ Claude usage limit reached. Your limit will reset at 9pm. | живое | +| Codex | ■ You’ve hit your usage limit. Try again at 8:47 PM. | мёртвое | -- 2.45.2 From ce03df667ce62588301143d96e32c156399ee9af Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 20:36:06 +0000 Subject: [PATCH 4/5] =?UTF-8?q?PEP-272:=20/api/health=20=D0=B0=D0=BD=D0=BE?= =?UTF-8?q?=D0=BD=D0=B8=D0=BC=D1=83=20=E2=80=94=20=D1=82=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=BA=D0=BE=20ok;=20=D0=B1=D0=B5=D0=B7=20X-Powered-By,=20scrip?= =?UTF-8?q?t-src=20=D0=B2=20CSP,=20=D0=B0=D0=B2=D0=B0=D1=82=D0=B0=D1=80=20?= =?UTF-8?q?=D0=BF=D0=BE=20https?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - /api/health без ключа X-Peppa-Health (HMAC от PEPPA_SECRET, принимается и PREVIOUS) отдаёт только {ok}; ключ шлют сторож адреса, сторож отставания выкатки, healthcheck контейнеров, скрипты выкатки - poweredByHeader: false; CSP: script-src 'self' 'unsafe-inline' (unsafe-eval только в dev), worker-src 'self' - httpsAvatar: http → https при записи и показе - тест health-anon.test.ts, change archived Co-Authored-By: Claude Opus 5.5 --- .peppa/memory.md | 5 +- AGENTS.md | 2 +- apps/web/app/(app)/layout.tsx | 4 +- apps/web/app/api/health/route.ts | 15 ++- apps/web/next.config.ts | 11 +- infra/platform/healthcheck.mjs | 7 +- .../2026-11-26-pep-272-anon-health/design.md | 18 +++ .../proposal.md | 19 ++++ .../specs/service-monitoring/spec.md | 26 +++++ .../specs/web-auth/spec.md | 21 ++++ .../2026-11-26-pep-272-anon-health/tasks.md | 12 ++ openspec/specs/service-monitoring/spec.md | 22 +++- openspec/specs/web-auth/spec.md | 20 ++++ packages/core/src/health-token.ts | 38 +++++++ packages/core/src/index.ts | 1 + packages/core/src/users.ts | 18 ++- packages/runner/src/deploy-lag.ts | 4 +- packages/runner/src/domain-guard.ts | 4 +- packages/testkit/test/health-anon.test.ts | 105 ++++++++++++++++++ scripts/lib/health-token.sh | 12 ++ scripts/live-deploy.sh | 4 +- scripts/peppa-release.sh | 3 +- scripts/platform-deploy.sh | 6 +- 23 files changed, 348 insertions(+), 29 deletions(-) create mode 100644 openspec/changes/archive/2026-11-26-pep-272-anon-health/design.md create mode 100644 openspec/changes/archive/2026-11-26-pep-272-anon-health/proposal.md create mode 100644 openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/service-monitoring/spec.md create mode 100644 openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/web-auth/spec.md create mode 100644 openspec/changes/archive/2026-11-26-pep-272-anon-health/tasks.md create mode 100644 packages/core/src/health-token.ts create mode 100644 packages/testkit/test/health-anon.test.ts create mode 100644 scripts/lib/health-token.sh diff --git a/.peppa/memory.md b/.peppa/memory.md index f8f59c81..54b0a121 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -25,7 +25,6 @@ - SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234). - QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить. - Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes. -- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare). - Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами. - Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать. - Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`. @@ -34,7 +33,6 @@ - `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299). - Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265). - Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh). -- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287). - Пропал `.git/worktrees/s`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`. - Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <версия>` (json + оба Dockerfile), откат `--rollback`. - Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`). @@ -62,6 +60,7 @@ - Конфликт PR с main (PEP-269) — только `conflictStep` (runner/conflict-step.ts), не `requestRebase` напрямую; сироты — `orphanConflictTick` (PEP-301). ## Решения +- `/api/health` анониму — только `{ok}` (PEP-272); сводку читать с `healthHeaders()` / `scripts/lib/health-token.sh`. - Access Hub (PEP-254): журнал — только `appendJournal` (core/connection-journal.ts, цепочка хэшей; правка строки задним числом = нарушение), ключ подключения — `sealConnectionSecret`/`openConnectionSecret`, не `encrypt`/`decrypt`. - История (PEP-221): журнал/статусы — `history.db` (core/history.ts), логи — `archive/<вид>/<день>.jsonl.gz`; из основной базы события удаляет только `runRetention` после переноса. - Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`). @@ -71,6 +70,6 @@ - Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`. - `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect [--secrets-only]`. - Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac. -- Речь — свой faster-whisper (``). Google: по почте учётки не склеиваем. +- Речь — свой faster-whisper (``). Google: по почте учётки не склеиваем. Сервер — docs/SERVER.md. - Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`. - Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195). diff --git a/AGENTS.md b/AGENTS.md index 266dad98..e70fb8d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -124,7 +124,7 @@ - **Ночная тишина (PEP-208)**: с 23:00 до 08:00 (`PEPPA_TZ`) никому, включая суперадмина, не уходят новые сообщения Telegram (личные, группы, канал) и push — `core/night-quiet.ts` `inNightQuiet` на выборке очередей: `dueOutbox` и `pendingMonitorMessages` ночью отдают только `editMessageText`, `flushPushOutbox` — ничего; строки ждут `pending` без траты попыток и уходят утром (отвеченные вопросы бот отбрасывает). Прямые ответы бота на сообщение/кнопку человека не через очередь — проходят. Окно — `PEPPA_NIGHT_QUIET` (`HH:MM-HH:MM` | `off`); в тестах и на `peppa-dev` выключено. Новый канал отправки людям — только через эти очереди. Тест `night-quiet.test.ts` - **Застрявшие задачи и приёмка одним экраном (PEP-209)**: причина застревания 18.11 — у долгоживущих агентов отвалился MCP `peppa` (не переподключается; лечит только новый процесс), `call.ts` из worktree был без `.env` (теперь `scripts/lib/load-env.sh` берёт `.env` основной копии; в тестах `PEPPA_ENV_FALLBACK=off`), у задачи пустой `pr_url`, вебхук мержа терялся. `stuckTaskTick` (runner/stuck-tasks.ts, раз в минуту): задача `in_progress`, агент не работает ≥30 мин, нет другой задержки/ревьюера/`review.wanted` → `diagnose` (результат по `pr_url` или ветке `task/` через `GiteaClient.pullForBranch`, state=all): смержен → `closeMergedStory` (gitea-events.ts), зелёный без конфликта → `platformToReview` (review-wanted.ts, общий с `reviewWantedTick`), конфликт/красные/нет результата → `restartAgent` (killRunner + `resumeSession` с причиной), проверки идут → ждём. Счёт — `stuck.heal:` (пока задача в работе), расписание `STUCK_RETRY_MIN` 5/15/60/120, после `STUCK_MAX_ATTEMPTS` (4) — задержка `exhausted` + одно сообщение суперадмину с кнопками `pd:::r|v|x` (`parseDelayCallback`, бот → `delayAction` в runner/delay-actions.ts через команду сервиса `delay`). `platformDelay`: `retryMin`, `retryAt`, `attempts`, `action`, `buttons`, пишет `commit` (`peppaCommit`); sweep снимает исчерпанные `agent|start|turn` с другим коммитом, сбрасывает `watch_state.restarts` и перезапускает задачу (`delay_stale_restarted`). Владелец — `taskDelayLine` («Следующая попытка в ЧЧ:ММ» / «Нужен администратор, мы ему сообщили»; `StoryProductInput.delayLine`, доска). Суперадмин — `/dashboard/delays` (`PlatformDelays actions`), на Главной одна строка (`platformDelayCounts`). Главная: заголовок «Вас ждут: принять N, ответить M, решить K» (`reviewCounts`, `proposedCount`), сначала «Принять работу», вопросы, «Предложено». **Приёмка**: `/p/KEY/accept` — `acceptScreen` (core/accept-screen.ts: задачи `review` по странице первого скриншота превью, «было» — скриншоты staging/prod того же пути, «стало» — превью, суть — `task.result`/название), «Принять всё» с подтверждением → `acceptAllAction` → `acceptAll` (flow.ts, по одной, причина отказа — `accept.fail:` 30 мин), итог `acceptAllSummary` (`?ok&pending&failed`); кнопка «Принять работу · N» на странице проекта и Главной. Шаблон выкладки снимает скриншоты и staging (`env` в отчёте `screenshots`; после мержа — `scripts/push-template.sh`, проектам — `peppa ci connect`). «Объединить в одну» в «Предложено» — `mergeProposals` (runner/proposals.ts). Telegram: `acceptDigestHold` (бот: «готово» ждёт `PEPPA_ACCEPT_DIGEST_SETTLE_SEC` 300 с, потом решение по окну [−1 ч; +пауза]: >2 задач — `held`), `acceptDigestTick` (вачдог) — одна сводка с кнопкой на «Приёмку», `accept.digest:`; `PEPPA_ACCEPT_DIGEST=off` (в тестах выключено). **Задача без агента (PEP-247)**: `stuckTaskTick` берёт и задачу «В работе» без единой сессии (нет `queuedItems`, нет `capacity.wait`, `tasks.updated_at` старше 30 мин) — тот же разбор и запуск агента, задержка `stuck`; законная причина — `taskHoldReason`/`taskHoldReasons` (core/task-hold.ts: пауза, `projectAgentWarning`, бюджет) — не задержка, строка `TASK_HOLD_TEXT` на карточке доски (`Card.hold`) и странице задачи (`StoryProductInput.hold`); сверка снимает `stuck`, пока задача ждёт места. Тесты `stuck-heal.test.ts`, `accept-screen.test.ts`, `stuck-no-agent.test.ts` - **Проверка запуска агентов (PEP-266)**: `runner/launch-smoke.ts` — `smokeTick` в тике вачдога (служба запуска): при смене коммита службы (= выкатка), раз в `PEPPA_SMOKE_EVERY_MIN` (60) или по запросу (`requestSmoke`: «Проверить сейчас» на «Observability», `peppa smoke run`) запускает каждого провайдера, у которого в общем пуле (`sharedPool`, иначе пул песочного проекта) есть пригодная подписка, настоящим `startRunner` (свободный раннер, `StartOptions.worktree` — всегда своя рабочая копия) в песочном проекте (`PEPPA_SMOKE_PROJECT`, по умолчанию платформенный) с задачей «создай `forge-smoke.txt` и закоммить» (`SMOKE_PROMPT`). Тик не ждёт: успех — файл в HEAD рабочей копии агента, провал — процесс кончился или `PEPPA_SMOKE_TIMEOUT_MIN` (5) мин без коммита (хвост экрана сохраняется); агент останавливается, рабочая копия удаляется `worktree remove --force`. Нет подписки, нет места, проект на паузе — «не проверен». Состояние — `settings` `smoke.run` / `smoke.history` (20) / `smoke.request` (`core/launch-smoke.ts`: `smokeStatus`), событие `launch_smoke` в журнале песочного проекта. Сообщение — `alertAdmins` (суперадмины, не канал): провайдер стал красным (или красный на новой версии), снова зелёный — один раз. После старта службы ждёт `PEPPA_SMOKE_SETTLE_SEC` (60); `PEPPA_SMOKE=off` (в тестах выключено). Раздел «Запуск агентов» на `/observability`, CLI `peppa smoke status`. Мок агента: действие `commit`, `providers` в сценарии. Тест `launch-smoke.test.ts` -- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД), `peppa status`, `peppa platform admins [логины|-]` +- **Мониторинг (PEP-20)**: веб (`instrumentation.ts`, раз в минуту), бот и вачдог (каждые 30 с) пишут heartbeat в `settings` (`heartbeat:`); вачдог проверяет бота и веб, бот — вачдог и веб (`checkServices` в core/monitor.ts). Молчит дольше `PEPPA_MONITOR_STALE_MIN` (5) мин → алерт админам платформы в Telegram через outbox (`platform.admins`, по умолчанию `platform.allowed_logins`; без привязки — в лог), потом «снова на связи»; напоминание раз в час, кулдаун 15 мин, дедуп ключом `mon::…`. Упал бот — вачдог шлёт алерт прямо в Bot API. `GET /api/health` (БД, версия, сервисы; 503 без БД; PEP-272: без заголовка `X-Peppa-Health` = HMAC от `PEPPA_SECRET` — только `{ok}`; ключ — `healthHeaders()` (core/health-token.ts), shell — `scripts/lib/health-token.sh`; новый внутренний читатель сводки шлёт ключ), `peppa status`, `peppa platform admins [логины|-]` - **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (сервис `act-runner` в `infra/docker-compose.yml`, конфиг `infra/act-runner/` — `capacity: 4` job одновременно на регистрацию (PEP-157; меняется перезапуском контейнера, тест `ci-runner-config.test.ts`), контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`) - Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью) - **Gitea → Пеппа (PEP-46)**: вебхук подписан на `GITEA_HOOK_EVENTS` (+ issues, issue_comment, pull_request_comment, pull_request_review; обновить у существующих — `peppa ci connect `); `handleGiteaEvent` (runner/gitea-events.ts) определяет событие по форме payload (Gitea 1.22 зовёт и ревью, и комментарий `pull_request_comment`). Issue от владельца/участника (логин Gitea, `users.gitea_id > 0`) → стори в бэклоге (`tasks.gitea_issue`, идемпотентно) + комментарий-ссылка от peppa-bot; чужие игнор; `moveTask(done)` закрывает issue; разовый импорт `peppa project import-issues ` (без проверки автора). Комментарий/ревью «нужны изменения» в PR стори → агенту (живой раннер или новый, из «Ревью» — в работу); одобрения и `GITEA_BOT_LOGIN` (peppa-bot) — игнор. PR смержен руками → стори done, «готово к ревью» закрыт (`acceptTask` терпит гонку с вебхуком) diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index c8d4b89b..b3481dee 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,5 +1,5 @@ import type { ReactNode } from "react"; -import { accountUsageForUser, agentsLine, getNotifyPrefs, isSuperadmin, pendingFeedbackCount } from "@peppa/core"; +import { accountUsageForUser, agentsLine, getNotifyPrefs, httpsAvatar, isSuperadmin, pendingFeedbackCount } from "@peppa/core"; import { db } from "@/lib/db"; import { subscriptionRequestOffers } from "@peppa/runner"; import { requireUser, uiMode } from "@/lib/auth"; @@ -34,7 +34,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
- +
{line ? : } diff --git a/apps/web/app/api/health/route.ts b/apps/web/app/api/health/route.ts index 9af75027..906e8612 100644 --- a/apps/web/app/api/health/route.ts +++ b/apps/web/app/api/health/route.ts @@ -1,15 +1,20 @@ -import { healthReport } from "@peppa/core"; +import { HEALTH_HEADER, healthBody, healthReport } from "@peppa/core"; import { bootId } from "@/lib/boot"; import { db } from "@/lib/db"; export const dynamic = "force-dynamic"; -/** Public health check (PEP-20): DB, version, service heartbeats. 503 if the DB is down. */ -export async function GET() { +/** + * Health check (PEP-20): DB, version, service heartbeats. 503 if the DB is down. + * PEP-272: without the internal key (`X-Peppa-Health`) only `{ok}` — no version, commit or services + * for strangers. Deploy scripts, container healthchecks and the watchdog send the key. + */ +export async function GET(req: Request) { const r = await healthReport(db, { version: process.env.NEXT_PUBLIC_PEPPA_VERSION, commit: process.env.NEXT_PUBLIC_PEPPA_COMMIT || null, }); - // PEP-114: `boot` changes when the web process restarts — open pages compare it with their own. - return Response.json({ ...r, boot: bootId() }, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } }); + // PEP-114: `boot` changes when the web process restarts — the domain guard recognises FORGE by it. + const body = healthBody({ ...r, boot: bootId() }, req.headers.get(HEALTH_HEADER)); + return Response.json(body, { status: r.ok ? 200 : 503, headers: { "Cache-Control": "no-store" } }); } diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 4173ac03..7311a356 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -31,19 +31,24 @@ const config: NextConfig = { experimental: { mcpServer: false }, // No Next.js badge and no «Issue» pill on the live site: a product manager must not see dev tools. devIndicators: false, + // PEP-272: no «X-Powered-By: Next.js» — nothing that tells a stranger what the site runs on. + poweredByHeader: false, // Dev chunks keep their names between edits; Cloudflare turns the dev server's `no-cache` into a // 4 h browser cache, so a reload ran stale code. `private, no-store` is passed through as is. async headers() { // The service worker must not sit in a browser/CDN cache, or fixes to it never arrive (PEP-55). const sw = { source: "/sw.js", headers: [{ key: "Cache-Control", value: "private, no-cache, max-age=0" }] }; - // PEP-133: browser-side hardening on every page. A full script CSP is not set — Next inlines - // its bootstrap scripts; framing, base tag and plugins are locked instead. + // PEP-133: browser-side hardening on every page. PEP-272: scripts only from our own origin — + // Next inlines its bootstrap scripts (a nonce would need middleware and dynamic rendering of every + // page), so 'unsafe-inline' stays; 'unsafe-eval' only for React Refresh in dev. + const dev = process.env.NODE_ENV === "development"; + const scriptSrc = `script-src 'self' 'unsafe-inline'${dev ? " 'unsafe-eval'" : ""}`; const secure = [ { key: "X-Content-Type-Options", value: "nosniff" }, { key: "X-Frame-Options", value: "DENY" }, { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, { key: "Permissions-Policy", value: "camera=(), geolocation=(), payment=(), usb=(), microphone=(self)" }, - { key: "Content-Security-Policy", value: "frame-ancestors 'none'; base-uri 'self'; object-src 'none'" }, + { key: "Content-Security-Policy", value: `frame-ancestors 'none'; base-uri 'self'; object-src 'none'; ${scriptSrc}; worker-src 'self'` }, ...(process.env.NODE_ENV === "development" ? [] : [{ key: "Strict-Transport-Security", value: "max-age=15552000" }]), ]; const all = { source: "/:path*", headers: secure }; diff --git a/infra/platform/healthcheck.mjs b/infra/platform/healthcheck.mjs index f575ffac..5aa37aeb 100644 --- a/infra/platform/healthcheck.mjs +++ b/infra/platform/healthcheck.mjs @@ -1,10 +1,15 @@ // PEP-222: healthcheck контейнера платформы. web — /api/health отвечает 200; остальные сервисы — // их heartbeat в /api/health веба свежий (имя сервиса — PEPPA_SERVICE). +// PEP-272: сводку служб веб отдаёт только с ключом X-Peppa-Health (HMAC от PEPPA_SECRET). +import { createHmac } from "node:crypto"; + const svc = process.env.PEPPA_SERVICE || "web"; const base = process.env.PEPPA_HEALTH_URL || `http://${process.env.PEPPA_WEB_HOST || "web"}:${process.env.PORT || 3100}`; const url = svc === "web" ? `http://127.0.0.1:${process.env.PORT || 3100}/api/health` : `${base}/api/health`; +const secret = process.env.PEPPA_SECRET; +const headers = secret ? { "x-peppa-health": createHmac("sha256", secret).update("peppa-health:v1").digest("hex") } : {}; try { - const r = await fetch(url, { signal: AbortSignal.timeout(8000) }); + const r = await fetch(url, { signal: AbortSignal.timeout(8000), headers }); if (!r.ok) process.exit(1); if (svc !== "web") { const d = await r.json(); diff --git a/openspec/changes/archive/2026-11-26-pep-272-anon-health/design.md b/openspec/changes/archive/2026-11-26-pep-272-anon-health/design.md new file mode 100644 index 00000000..0d38d2bb --- /dev/null +++ b/openspec/changes/archive/2026-11-26-pep-272-anon-health/design.md @@ -0,0 +1,18 @@ +## Решения +- **Как отличить внутреннюю проверку.** Адрес запроса не годится: выкатка и сторожа ходят через + публичный адрес (Cloudflare → Traefik), а Next сам ставит `x-forwarded-for`. Поэтому — + ключ в заголовке `X-Peppa-Health`: `hex(HMAC-SHA256(PEPPA_SECRET, "peppa-health:v1"))`. + Его может посчитать любой процесс с `.env` (Node — `healthToken()`, shell — + `scripts/lib/health-token.sh` через `openssl`), в базе и в логах он не хранится. При ротации + принимается и ключ от `PEPPA_SECRET_PREVIOUS`. Сравнение — `timingSafeEqual`. +- **Что видит аноним.** Только `{ok: true|false}` и код 200/503: этого достаточно мониторингам + (observability, `probeWebPort`, TeamChase проверяют лишь ответ). `boot` анониму не нужен — + вкладки узнают о перезапуске по живому каналу (`VersionWatch`). +- **Сторож адреса (PEP-189)** узнаёт FORGE по `boot` + `services` — шлёт ключ; без ключа + (нет `PEPPA_SECRET`) проверка как раньше и сочла бы ответ чужим, поэтому ключ обязателен. +- **CSP скриптов.** Nonce потребовал бы middleware и динамического рендера всех страниц + (часть страниц статична). Берём `script-src 'self' 'unsafe-inline'`: внешние скрипты и + чужие домены запрещены, встроенные загрузчики Next работают. `'unsafe-eval'` — только в dev + (React Refresh). `worker-src 'self'` — service worker. +- **Аватар.** `httpsAvatar(url)`: `http://` → `https://`, иное не-https → null; применяется при + записи (Gitea) и при показе (старые строки базы). diff --git a/openspec/changes/archive/2026-11-26-pep-272-anon-health/proposal.md b/openspec/changes/archive/2026-11-26-pep-272-anon-health/proposal.md new file mode 100644 index 00000000..52aae450 --- /dev/null +++ b/openspec/changes/archive/2026-11-26-pep-272-anon-health/proposal.md @@ -0,0 +1,19 @@ +## Why +Отчёт тестирования (F-14): любой посетитель без входа видит в `/api/health` версию, коммит, +задержку базы и состояние служб FORGE, в ответах — `X-Powered-By: Next.js`, аватар может +грузиться по http, а CSP не ограничивает источники скриптов. Это лишние подсказки атакующему. + +## What Changes +- `/api/health` без служебного ключа отвечает только `{ok}` (200/503). Полная сводка — с + заголовком `X-Peppa-Health: <ключ>`; ключ — HMAC от `PEPPA_SECRET` (принимается и от + `PEPPA_SECRET_PREVIOUS`). Его шлют все внутренние проверки: выкатка (`live-deploy.sh`, + `platform-deploy.sh`, `peppa-release.sh`), healthcheck контейнеров, сторож адреса (PEP-189), + сторож отставания выкатки (PEP-277). +- Убран заголовок `X-Powered-By`. +- Аватар пользователя — только по https (http переписывается на https, иное отбрасывается). +- CSP дополнен `script-src 'self' 'unsafe-inline'` (в dev ещё `'unsafe-eval'`) и `worker-src 'self'`. + +## Impact +- apps/web: `app/api/health/route.ts`, `next.config.ts`, `app/(app)/layout.tsx`. +- core: `health-token.ts`, `users.ts`; runner: `domain-guard.ts`, `deploy-lag.ts`. +- scripts: `lib/health-token.sh`, выкатка; `infra/platform/healthcheck.mjs`. diff --git a/openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/service-monitoring/spec.md b/openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/service-monitoring/spec.md new file mode 100644 index 00000000..dc948494 --- /dev/null +++ b/openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/service-monitoring/spec.md @@ -0,0 +1,26 @@ +## MODIFIED Requirements + +### Requirement: Health-эндпоинт +Веб SHALL отвечать на `GET /api/health`; код ответа 200, если БД доступна, иначе 503. Запросу без служебного ключа (заголовок `X-Peppa-Health`, HMAC от `PEPPA_SECRET` или `PEPPA_SECRET_PREVIOUS`) ответ SHALL содержать только `ok`. Запросу с верным ключом — JSON-сводку: доступность БД, версия и коммит, состояние сервисов, `boot`. Сводка не содержит логинов и чатов пользователей. Внутренние проверки (выкатка, healthcheck контейнеров, сторож адреса, сторож отставания выкатки) SHALL слать ключ. + +#### Scenario: Аноним видит только «ok» +- **GIVEN** БД доступна +- **WHEN** запрошен `/api/health` без заголовка `X-Peppa-Health` +- **THEN** ответ 200 с телом `{"ok":true}` +- **AND** в нём нет `version`, `commit`, `services`, `db`, `boot` + +#### Scenario: Неверный ключ — как аноним +- **GIVEN** БД доступна +- **WHEN** запрошен `/api/health` с заголовком `X-Peppa-Health: abc` +- **THEN** ответ 200 с телом `{"ok":true}` + +#### Scenario: Всё работает +- **GIVEN** БД доступна, версия Пеппы 0.15.0 +- **WHEN** запрошен `/api/health` с верным ключом +- **THEN** ответ 200 с `ok: true`, `db.ok: true`, `version: "0.15.0"`, коммитом и списком сервисов web, bot, watchdog + +#### Scenario: БД недоступна +- **GIVEN** база не отвечает +- **WHEN** запрошен `/api/health` +- **THEN** ответ 503 с `ok: false` не дольше чем за 3 секунды +- **AND** текст ошибки базы есть только в ответе с верным ключом diff --git a/openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/web-auth/spec.md new file mode 100644 index 00000000..aa2dc36c --- /dev/null +++ b/openspec/changes/archive/2026-11-26-pep-272-anon-health/specs/web-auth/spec.md @@ -0,0 +1,21 @@ +## ADDED Requirements + +### Requirement: Ответы веба не раскрывают служебное +Веб SHALL не отдавать заголовок `X-Powered-By`; SHALL отдавать CSP с `script-src 'self' 'unsafe-inline'` (без внешних источников скриптов; `'unsafe-eval'` — только в режиме разработки) и `worker-src 'self'`; аватар пользователя SHALL загружаться только по https. + +#### Scenario: Заголовки страницы +- **GIVEN** веб запущен в рабочем режиме +- **WHEN** запрошена страница `/login` +- **THEN** в ответе нет `X-Powered-By` +- **AND** `Content-Security-Policy` содержит `script-src 'self' 'unsafe-inline'` и не содержит `unsafe-eval` + +#### Scenario Outline: Адрес аватара +- **GIVEN** у пользователя аватар `<адрес>` +- **WHEN** открыта страница с боковым меню +- **THEN** картинка аватара — `<показ>` + +| адрес | показ | +|---|---| +| http://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 | +| https://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 | +| javascript:alert(1) | нет картинки | diff --git a/openspec/changes/archive/2026-11-26-pep-272-anon-health/tasks.md b/openspec/changes/archive/2026-11-26-pep-272-anon-health/tasks.md new file mode 100644 index 00000000..4e27be79 --- /dev/null +++ b/openspec/changes/archive/2026-11-26-pep-272-anon-health/tasks.md @@ -0,0 +1,12 @@ +## 1. Health +- [x] 1.1 `healthToken`/`healthTokenOk`/`healthHeaders` в core (HMAC от PEPPA_SECRET и PREVIOUS) +- [x] 1.2 `/api/health`: без ключа — только `{ok}` +- [x] 1.3 Ключ шлют: сторож адреса, сторож отставания, healthcheck контейнеров, скрипты выкатки (`scripts/lib/health-token.sh`) +- [x] 1.4 Тест: аноним/неверный/верный ключ, ключ от PREVIOUS + +## 2. Заголовки и аватар +- [x] 2.1 `poweredByHeader: false`, CSP `script-src`, `worker-src` +- [x] 2.2 `httpsAvatar` при записи и показе, тест + +## 3. Завершение +- [x] 3.1 Проверки локально, память, archive, PR diff --git a/openspec/specs/service-monitoring/spec.md b/openspec/specs/service-monitoring/spec.md index 6f26f5ee..79b91ae6 100644 --- a/openspec/specs/service-monitoring/spec.md +++ b/openspec/specs/service-monitoring/spec.md @@ -24,17 +24,29 @@ - **THEN** веб в сводке «нет данных», и алерт о нём не создаётся ### Requirement: Health-эндпоинт -Веб SHALL отвечать на `GET /api/health` JSON-сводкой: доступность БД, версия и коммит, состояние сервисов; код ответа 200, если БД доступна, иначе 503. Сводка не содержит логинов и чатов пользователей. +Веб SHALL отвечать на `GET /api/health`; код ответа 200, если БД доступна, иначе 503. Запросу без служебного ключа (заголовок `X-Peppa-Health`, HMAC от `PEPPA_SECRET` или `PEPPA_SECRET_PREVIOUS`) ответ SHALL содержать только `ok`. Запросу с верным ключом — JSON-сводку: доступность БД, версия и коммит, состояние сервисов, `boot`. Сводка не содержит логинов и чатов пользователей. Внутренние проверки (выкатка, healthcheck контейнеров, сторож адреса, сторож отставания выкатки) SHALL слать ключ. + +#### Scenario: Аноним видит только «ok» +- **GIVEN** БД доступна +- **WHEN** запрошен `/api/health` без заголовка `X-Peppa-Health` +- **THEN** ответ 200 с телом `{"ok":true}` +- **AND** в нём нет `version`, `commit`, `services`, `db`, `boot` + +#### Scenario: Неверный ключ — как аноним +- **GIVEN** БД доступна +- **WHEN** запрошен `/api/health` с заголовком `X-Peppa-Health: abc` +- **THEN** ответ 200 с телом `{"ok":true}` #### Scenario: Всё работает - **GIVEN** БД доступна, версия Пеппы 0.15.0 -- **WHEN** запрошен `/api/health` -- **THEN** ответ 200 с `ok: true`, `db.ok: true`, `version: "0.15.0"` и списком сервисов web, bot, watchdog +- **WHEN** запрошен `/api/health` с верным ключом +- **THEN** ответ 200 с `ok: true`, `db.ok: true`, `version: "0.15.0"`, коммитом и списком сервисов web, bot, watchdog #### Scenario: БД недоступна -- **GIVEN** Postgres не отвечает +- **GIVEN** база не отвечает - **WHEN** запрошен `/api/health` -- **THEN** ответ 503 с `ok: false`, `db.ok: false` и текстом ошибки, не дольше чем за 3 секунды +- **THEN** ответ 503 с `ok: false` не дольше чем за 3 секунды +- **AND** текст ошибки базы есть только в ответе с верным ключом ### Requirement: Алерт админу о молчащем сервисе Вачдог SHALL проверять бота и веб, бот SHALL проверять вачдог и веб; о сервисе, который молчит дольше 5 минут, админы платформы с привязанным Telegram SHALL получать сообщение через очередь outbox, а после восстановления — сообщение «снова на связи». Админы — логины из `platform.admins`, а если настройка не задана — из `platform.allowed_logins`. diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md index e8af4376..e1741127 100644 --- a/openspec/specs/web-auth/spec.md +++ b/openspec/specs/web-auth/spec.md @@ -270,3 +270,23 @@ nonce, созданные сервером для этого потока; по #### Scenario: Подсказка - **GIVEN** учётка без входа с проектами и активная учётка с той же почтой - **THEN** на «Пользователях» метка «Есть проекты — войти нельзя» и кнопка «Объединить с <логин>?»; само ничего не объединяется + +### Requirement: Ответы веба не раскрывают служебное +Веб SHALL не отдавать заголовок `X-Powered-By`; SHALL отдавать CSP с `script-src 'self' 'unsafe-inline'` (без внешних источников скриптов; `'unsafe-eval'` — только в режиме разработки) и `worker-src 'self'`; аватар пользователя SHALL загружаться только по https. + +#### Scenario: Заголовки страницы +- **GIVEN** веб запущен в рабочем режиме +- **WHEN** запрошена страница `/login` +- **THEN** в ответе нет `X-Powered-By` +- **AND** `Content-Security-Policy` содержит `script-src 'self' 'unsafe-inline'` и не содержит `unsafe-eval` + +#### Scenario Outline: Адрес аватара +- **GIVEN** у пользователя аватар `<адрес>` +- **WHEN** открыта страница с боковым меню +- **THEN** картинка аватара — `<показ>` + +| адрес | показ | +|---|---| +| http://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 | +| https://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 | +| javascript:alert(1) | нет картинки | diff --git a/packages/core/src/health-token.ts b/packages/core/src/health-token.ts new file mode 100644 index 00000000..3a50f6f4 --- /dev/null +++ b/packages/core/src/health-token.ts @@ -0,0 +1,38 @@ +// PEP-272: /api/health отдаёт сводку (версия, коммит, службы) только внутренним проверкам. +// Ключ — HMAC-SHA256(PEPPA_SECRET, HEALTH_TOKEN_LABEL) в hex: его считает любой процесс с .env — +// Node (healthToken) и shell (scripts/lib/health-token.sh, openssl). Ни в базе, ни в логах его нет. +import { createHmac, timingSafeEqual } from "node:crypto"; + +export const HEALTH_HEADER = "x-peppa-health"; +export const HEALTH_TOKEN_LABEL = "peppa-health:v1"; + +const tokenFor = (secret: string) => createHmac("sha256", secret).update(HEALTH_TOKEN_LABEL).digest("hex"); + +/** The key of the current PEPPA_SECRET; null when the secret is not set. */ +export function healthToken(): string | null { + const s = process.env.PEPPA_SECRET; + return s ? tokenFor(s) : null; +} + +/** Headers for an internal /api/health request (empty without PEPPA_SECRET). */ +export function healthHeaders(): Record { + const t = healthToken(); + return t ? { [HEALTH_HEADER]: t } : {}; +} + +/** Whether the header value is the key of PEPPA_SECRET or, during a rotation, PEPPA_SECRET_PREVIOUS. */ +export function healthTokenOk(value: string | null | undefined): boolean { + if (!value) return false; + const env = process.env; + const got = Buffer.from(value.trim()); + return [env.PEPPA_SECRET, env.PEPPA_SECRET_PREVIOUS].some((s) => { + if (!s) return false; + const want = Buffer.from(tokenFor(s)); + return want.length === got.length && timingSafeEqual(want, got); + }); +} + +/** What /api/health answers: the full report with the right key, only `{ok}` to everyone else. */ +export function healthBody(full: T, key: string | null | undefined): T | { ok: boolean } { + return healthTokenOk(key) ? full : { ok: full.ok }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e2b31a68..52f90b66 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -19,6 +19,7 @@ export * from "./runners.ts"; export * from "./hosts.ts"; export * from "./telegram.ts"; export * from "./crypto.ts"; +export * from "./health-token.ts"; export * from "./gitea.ts"; export * from "./gitea-server.ts"; export * from "./users.ts"; diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index 9b901842..74869bec 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -12,6 +12,22 @@ import type { Project } from "./projects.ts"; export type User = typeof users.$inferSelect; +/** + * PEP-272: an avatar loads only over https — `http://` becomes `https://`, anything else (another + * scheme, garbage) is dropped. Applied on write and on show (older rows keep Gitea's http address). + */ +export function httpsAvatar(url: string | null | undefined): string | null { + const u = url?.trim(); + if (!u) return null; + try { + const parsed = new URL(u); + if (parsed.protocol === "http:") parsed.protocol = "https:"; + return parsed.protocol === "https:" ? parsed.toString() : null; + } catch { + return null; + } +} + /** Creates or refreshes the Peppa user for a Gitea account after OAuth login. */ export async function upsertUserFromGitea(db: Db, g: GiteaUser, tokens: OAuthTokens): Promise { const values = { @@ -19,7 +35,7 @@ export async function upsertUserFromGitea(db: Db, g: GiteaUser, tokens: OAuthTok login: g.login, name: g.full_name || null, email: g.email || null, - avatarUrl: g.avatar_url || null, + avatarUrl: httpsAvatar(g.avatar_url), ...tokenColumns(tokens), lastLoginAt: new Date(), }; diff --git a/packages/runner/src/deploy-lag.ts b/packages/runner/src/deploy-lag.ts index f2073bd2..4db59609 100644 --- a/packages/runner/src/deploy-lag.ts +++ b/packages/runner/src/deploy-lag.ts @@ -6,7 +6,7 @@ // only on a new merged PR or after a day; caught up — «выкатка догнала main». import { createHash } from "node:crypto"; import { asIs, m } from "@peppa/shared/i18n"; -import { alertAdmins, deleteSetting, getSetting, giteaForBot, platformProjectKey, setSetting } from "@peppa/core"; +import { alertAdmins, deleteSetting, getSetting, giteaForBot, healthHeaders, platformProjectKey, setSetting } from "@peppa/core"; import type { GiteaCommit } from "@peppa/core"; import type { Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; @@ -29,7 +29,7 @@ export function deployLagHealthUrl(): string | null { /** The commit the site runs (null: no answer or no commit — the site's health is someone else's business). */ async function deployedCommit(url: string): Promise { try { - const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache" } }); + const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache", ...healthHeaders() } }); const body = (await res.json()) as { commit?: unknown }; return typeof body.commit === "string" && /^[0-9a-f]{7,40}$/i.test(body.commit) ? body.commit.toLowerCase() : null; } catch { diff --git a/packages/runner/src/domain-guard.ts b/packages/runner/src/domain-guard.ts index 32ac5a9f..835119f5 100644 --- a/packages/runner/src/domain-guard.ts +++ b/packages/runner/src/domain-guard.ts @@ -5,7 +5,7 @@ // glossary-ignore-file: messages here are for the superadmin and the agent. import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { alertAdmins, edgeConfig, findIntruders, getSetting, guardRules, intruderOwner, isPeppaHealth, listProjects, listSessions, observeRemindMin, parseDockerPs, probeWebPort, setSetting, type Intruder } from "@peppa/core"; +import { alertAdmins, edgeConfig, findIntruders, getSetting, guardRules, healthHeaders, intruderOwner, isPeppaHealth, listProjects, listSessions, observeRemindMin, parseDockerPs, probeWebPort, setSetting, type Intruder } from "@peppa/core"; import { m } from "@peppa/shared/i18n"; import type { Db } from "@peppa/db"; import { sendToSession } from "./sessions.ts"; @@ -98,7 +98,7 @@ export async function publicHealthTick(db: Db, o: { now?: Date; log?: (m: string let ok = false; let why = ""; try { - const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache" } }); + const res = await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000), headers: { "cache-control": "no-cache", ...healthHeaders() } }); const body = await res.text(); // 5xx: the web is down or the way in is broken (Cloudflare 502/530). The web itself is the port // check's business (PEP-168); the way in — publicPathCheck (PEP-245). Not "someone else answers". diff --git a/packages/testkit/test/health-anon.test.ts b/packages/testkit/test/health-anon.test.ts new file mode 100644 index 00000000..03694a0c --- /dev/null +++ b/packages/testkit/test/health-anon.test.ts @@ -0,0 +1,105 @@ +// PEP-272: служебные данные — не анониму. /api/health без ключа отдаёт только {ok}; ключ (HMAC от +// PEPPA_SECRET) шлют внутренние проверки; без X-Powered-By, скрипты в CSP — только свои, аватар — https. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createServer, type Server } from "node:http"; +import { 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"; + +const ROOT = resolve(fileURLToPath(import.meta.url), "../../../.."); +process.env.PEPPA_SECRET = "mock-health-secret"; +const full = { ok: true, version: "0.15.0", commit: "abc1234", db: { ok: true, latencyMs: 1 }, services: [{ service: "web", ok: true }], boot: "abc1234-x" }; + +after(teardown); + +describe("PEP-272: /api/health для анонима", () => { + test("Аноним видит только «ok»", () => { + assert.deepEqual(core.healthBody(full, null), { ok: true }); + assert.deepEqual(core.healthBody({ ...full, ok: false }, undefined), { ok: false }); + }); + + test("Неверный ключ — как аноним", () => { + assert.deepEqual(core.healthBody(full, "abc"), { ok: true }); + assert.deepEqual(core.healthBody(full, core.healthToken()!.slice(0, 63) + "0"), { ok: true }); + }); + + test("Всё работает: внутренняя проверка с ключом видит сводку", () => { + const key = core.healthHeaders()[core.HEALTH_HEADER]; + assert.ok(key); + assert.deepEqual(core.healthBody(full, key), full); + }); + + test("Ротация: ключ от PEPPA_SECRET_PREVIOUS тоже принимается", () => { + const old = core.healthToken()!; + process.env.PEPPA_SECRET_PREVIOUS = process.env.PEPPA_SECRET; + process.env.PEPPA_SECRET = "mock-health-secret-new"; + try { + assert.ok(core.healthTokenOk(old)); + assert.ok(core.healthTokenOk(core.healthToken())); + } finally { + process.env.PEPPA_SECRET = "mock-health-secret"; + delete process.env.PEPPA_SECRET_PREVIOUS; + } + }); + + test("Ключ shell-скриптов выкатки совпадает с ключом ядра", () => { + const sh = execFileSync("bash", ["-c", `. "${ROOT}/scripts/lib/health-token.sh"; health_token`], { encoding: "utf8", env: { ...process.env } }).trim(); + assert.equal(sh, core.healthToken()); + }); + + describe("сторож адреса шлёт ключ", () => { + let server: Server; + before(async () => { + server = createServer((req, res) => { + const body = core.healthBody(full, req.headers[core.HEALTH_HEADER] as string | undefined); + res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(body)); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + process.env.PEPPA_PUBLIC_HEALTH_URL = `http://127.0.0.1:${(server.address() as { port: number }).port}/api/health`; + }); + after(() => { + delete process.env.PEPPA_PUBLIC_HEALTH_URL; + server.close(); + }); + test("публичный адрес с полной сводкой узнан как FORGE", async () => { + assert.equal(await runner.publicHealthTick(db), true); + }); + }); +}); + +describe("PEP-272: ответы веба не раскрывают служебное", () => { + test("Заголовки страницы: без X-Powered-By, script-src только свои", async () => { + const prev = process.env.NODE_ENV; + (process.env as Record).NODE_ENV = "production"; + try { + const config = ((await import(new URL("../../../apps/web/next.config.ts", import.meta.url).href)) as { default: { poweredByHeader?: boolean; headers: () => Promise<{ source: string; headers: { key: string; value: string }[] }[]> } }).default; + assert.equal(config.poweredByHeader, false); + const all = (await config.headers()).find((h) => h.source === "/:path*")!; + const csp = all.headers.find((h) => h.key === "Content-Security-Policy")!.value; + assert.match(csp, /script-src 'self' 'unsafe-inline'(;|$)/); + assert.doesNotMatch(csp, /unsafe-eval/); + assert.match(csp, /worker-src 'self'/); + assert.match(csp, /frame-ancestors 'none'/); + } finally { + (process.env as Record).NODE_ENV = prev; + } + }); + + for (const [url, shown] of [ + ["http://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"], + ["https://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"], + ["javascript:alert(1)", null], + ["", null], + ] as const) { + test(`Адрес аватара: ${url || "пусто"} → ${shown ?? "нет картинки"}`, () => { + assert.equal(core.httpsAvatar(url), shown); + }); + } + + test("Аватар Gitea по http сохраняется как https", async () => { + const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.telecom.quest/avatars/7" }, { access_token: "x" }); + assert.equal(u.avatarUrl, "https://git.telecom.quest/avatars/7"); + }); +}); diff --git a/scripts/lib/health-token.sh b/scripts/lib/health-token.sh new file mode 100644 index 00000000..33b73c2f --- /dev/null +++ b/scripts/lib/health-token.sh @@ -0,0 +1,12 @@ +# PEP-272: ключ внутренней проверки /api/health — без него веб отвечает только {"ok":…}. +# health_token [<.env>] печатает hex(HMAC-SHA256(PEPPA_SECRET, "peppa-health:v1")) — тот же, что +# healthToken() в packages/core/src/health-token.ts. PEPPA_SECRET — из окружения, иначе из файла. +# Нет секрета — пустая строка (веб тогда отдаст только ok, проверка коммита не пройдёт). +health_token() { + local secret="${PEPPA_SECRET:-}" + if [ -z "$secret" ] && [ -n "${1:-}" ] && [ -f "$1" ]; then + secret=$(set -a; . "$1" >/dev/null 2>&1; printf '%s' "${PEPPA_SECRET:-}") + fi + [ -n "$secret" ] || return 0 + printf '%s' 'peppa-health:v1' | openssl dgst -sha256 -hmac "$secret" -r | cut -d' ' -f1 +} diff --git a/scripts/live-deploy.sh b/scripts/live-deploy.sh index 4d0b3ef9..74050c00 100755 --- a/scripts/live-deploy.sh +++ b/scripts/live-deploy.sh @@ -138,8 +138,10 @@ restart() { MARK=$(wc -l <"$LOG" 2>/dev/null || echo 0) RESTARTED=$(date -u +%Y-%m-%dT%H:%M:%S) restart +. "$ROOT/scripts/lib/health-token.sh" +HEALTH_KEY=$(health_token "$ROOT/.env") # PEP-272: without it /api/health answers only {"ok"} healthy() { # — the target commit, every service up and heard from after the restart - curl -fsS -m 10 "$URL/api/health" 2>/dev/null | python3 -c ' + curl -fsS -m 10 -H "X-Peppa-Health: $HEALTH_KEY" "$URL/api/health" 2>/dev/null | python3 -c ' import json, sys d = json.load(sys.stdin); since = sys.argv[2] svc = d.get("services", []) diff --git a/scripts/peppa-release.sh b/scripts/peppa-release.sh index 7108d1a2..03d5e3b9 100755 --- a/scripts/peppa-release.sh +++ b/scripts/peppa-release.sh @@ -29,6 +29,7 @@ SERVICES="${PEPPA_RELEASE_SERVICES:-web bot watchdog}" KEEP="${PEPPA_RELEASE_KEEP:-5}" NODE="${PEPPA_NODE:-node}" CURRENT="$RELEASES/current" +. "$(cd "$(dirname "$0")" && pwd)/lib/health-token.sh" # PEP-272: ключ /api/health mkdir -p "$RELEASES/releases" "$RELEASES/logs" "$RELEASES/requests" "$PEPPA_HOME/backups" say() { echo "[$(date '+%F %T')] $*" | tee -a "${LOG:-/dev/null}"; } @@ -70,7 +71,7 @@ kickstart() { health() { # sha since-ms local deadline=$(( $(date +%s) + HEALTH_TIMEOUT )) body why="" while :; do - if body=$(curl -fsS --max-time 5 "$HEALTH_URL" 2>&1); then + if body=$(curl -fsS --max-time 5 -H "X-Peppa-Health: $(health_token "$CURRENT/.env")" "$HEALTH_URL" 2>&1); then why=$(printf '%s' "$body" | SHA="$1" SINCE="$2" WANT="$SERVICES" "$NODE" -e ' let s = ""; process.stdin.on("data", (c) => (s += c)).on("end", () => { const h = JSON.parse(s), sha = process.env.SHA, since = Number(process.env.SINCE); diff --git a/scripts/platform-deploy.sh b/scripts/platform-deploy.sh index a39db883..a1c519fc 100755 --- a/scripts/platform-deploy.sh +++ b/scripts/platform-deploy.sh @@ -37,6 +37,8 @@ export PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}" if [ -z "${PEPPA_ENV_FILE:-}" ] && [ ! -f "$ROOT/.env" ] && [ -f "$ROOT/../.env" ]; then PEPPA_ENV_FILE="$(cd "$ROOT/.." && pwd)/.env"; fi ENV_FILE="${PEPPA_ENV_FILE:-$ROOT/.env}"; export PEPPA_ENV_FILE="$ENV_FILE" URL="${PEPPA_WEB_URL:-https://peppa.telecom.quest}" +# PEP-272: версию и службы /api/health отдаёт только с ключом (HMAC от PEPPA_SECRET). +. "$ROOT/scripts/lib/health-token.sh"; HEALTH_KEY=$(health_token "$ENV_FILE") # PEP-230: на Linux сервисы и агенты работают от пользователя, запустившего выкатку (не root); на Mac — как раньше. if [ "$(uname)" = Linux ]; then export PEPPA_UID="${PEPPA_UID:-$(id -u)}" PEPPA_GID="${PEPPA_GID:-$(id -g)}" PEPPA_DOCKER_GID="${PEPPA_DOCKER_GID:-$(stat -c %g /var/run/docker.sock)}" @@ -112,7 +114,7 @@ TARGET=$(git rev-parse "${TARGET:-origin/main}^{commit}") git merge-base --is-ancestor "$TARGET" origin/main || die "$TARGET не на origin/main" SHORT=${TARGET:0:12} if [ "$AUTO" = 1 ]; then - LIVE=$(curl -fsS -m 10 "$URL/api/health" 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin).get("commit") or "")' 2>/dev/null || true) + LIVE=$(curl -fsS -m 10 -H "X-Peppa-Health: $HEALTH_KEY" "$URL/api/health" 2>/dev/null | python3 -c 'import json,sys; print(json.load(sys.stdin).get("commit") or "")' 2>/dev/null || true) case "$TARGET" in "${LIVE:-—}"*) exit 0;; esac [ -n "$LIVE" ] && git merge-base --is-ancestor "$TARGET" "$LIVE" 2>/dev/null && exit 0 # прод новее (выкатили руками) # Цель, на которой выкатка уже упала, не повторяется каждые 10 минут. PEP-310: через час пробуется @@ -169,7 +171,7 @@ run backup_db || die "копия базы не удалась" run docker run --rm --user "${PEPPA_UID:-0}:${PEPPA_GID:-0}" --env-file "$ENV_FILE" -e PEPPA_HOME -e "PEPPA_DB=$PEPPA_HOME/peppa.db" -v "$PEPPA_HOME:$PEPPA_HOME" "peppa/platform:$SHORT" peppa db migrate || die "миграция не удалась (копия в $PEPPA_HOME/backups)" healthy() { - curl -fsS -m 10 "$URL/api/health" 2>/dev/null | python3 -c ' + curl -fsS -m 10 -H "X-Peppa-Health: $HEALTH_KEY" "$URL/api/health" 2>/dev/null | python3 -c ' import json, sys d = json.load(sys.stdin); ok = d.get("ok") and (d.get("commit") or "").startswith(sys.argv[1][:7]) and all(s.get("ok") for s in d.get("services", [])) sys.exit(0 if ok else 1)' "$1" -- 2.45.2 From 1341d61a05d62ebe858daec45cdaab753280a677 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 21:13:37 +0000 Subject: [PATCH 5/5] =?UTF-8?q?PEP-272:=20=D1=82=D0=B5=D1=81=D1=82=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D1=88=D0=B5=D0=B3=D0=BE=20=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D0=BD=D0=B5=D1=80=D0=B0=20=D0=B6=D0=B4=D1=91=D1=82?= =?UTF-8?q?,=20=D0=BF=D0=BE=D0=BA=D0=B0=20=D1=8D=D0=BA=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=20=D1=83=D1=81=D1=82=D0=BE=D0=B8=D1=82=D1=81=D1=8F,=20=D0=B2?= =?UTF-8?q?=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D0=BF=D0=B0=D1=83=D0=B7=D1=8B?= =?UTF-8?q?=201,5=20=D1=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Под нагрузкой CI ответ мок-агента дорисовывался между тиками, вачдог видел активность. Co-Authored-By: Claude Opus 5.5 --- packages/testkit/test/recovery.test.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/testkit/test/recovery.test.ts b/packages/testkit/test/recovery.test.ts index a9b3e1e9..570fa97a 100644 --- a/packages/testkit/test/recovery.test.ts +++ b/packages/testkit/test/recovery.test.ts @@ -129,7 +129,18 @@ describe("Зависший раннер перезапускается", () => { const p = await storyAtWork({ turns: [[{ say: "Думаю." }, { hang: true }]], resumeTurns: [[{ say: "Отвис." }]] }); const sid = await p.start(); await p.waitLog("turn 0", (e) => e.ev === "prompt"); - await new Promise((r) => setTimeout(r, 1500)); + // The hung agent's screen must settle first: under a loaded CI a fixed pause was too short, the + // reply landed between ticks and the watchdog rightly saw "activity" (PEP-272 CI run 360). + const pane = (await sess(sid)).tmuxName; + await waitFor("hung reply on screen", async () => (await runner.tmux.capturePane(pane)).includes("Думаю.")); + let prev = ""; + await waitFor("screen settled", async () => { + const now = await runner.tmux.capturePane(pane); + const same = now === prev; + prev = now; + if (!same) await new Promise((r) => setTimeout(r, 700)); + return same; + }); const t0 = Date.now(); await tickAt(new Date(t0)); // remembers the screen await tickAt(new Date(t0 + 10 * MIN), 5 * MIN); // stalled → alert -- 2.45.2