Merge remote-tracking branch 'origin/main' into task/pep-154
This commit is contained in:
commit
3accfe155d
@ -45,3 +45,4 @@
|
||||
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`. Состояние — settings `question.state:<id>`, `chat.repeat:<messageId>`. В тесте нужен второй вопрос — меняй статус, коммит в check_runs или текст.
|
||||
- Продукт по ссылке (PEP-145): ссылка и её статус — только через `projectProduct` (`fix`/`broken`/`preparing`) и `productUrls`/`productLookLine`; системную стори заводит `productLinkTick` (в тестах выключен в helpers.ts, свой тест делает `delete process.env.PEPPA_PRODUCT_LINK`); «Показывать всем» — `getPublishMode`/`autoPublish` (вернул true — вопрос с кнопкой не слать). Менял `template/` — после мержа `scripts/push-template.sh`.
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `core/user-text.ts` (`userText`; `stripServiceBlocks` — для слов человека); `raiseSessionQuestion`/`askPm`/`addChatMessage` чистят сами, пусто → PeppaError, исходник — `questionDetails` (инженер/суперадмин). Текст исключения владельцу не слать: `platformFailure` даёт строку только для PeppaError, иначе null (ушло суперадмину и в учёт ошибок). В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`. Конец хода агента вопроса не создаёт: в тестах жди статус сессии `idle`, а не `waitQuestion(sid, "attention")`.
|
||||
|
||||
@ -44,6 +44,7 @@
|
||||
- **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики»
|
||||
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:<userId>`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
|
||||
- **Слова по режиму (PEP-123)**: `@peppa/shared/wording` — `wording(mode)`: `task(форма)` / `Task` / `tasks(n)` («задача» в «Продакте», «стори» в «Инженере»), `runner(форма)` («агент» / «раннер»), формы `nom|gen|dat|acc|ins|pre|pl|genPl|datPl|accPl|insPl|prePl`. Веб: серверный компонент — `const w = await words()` (`lib/auth.ts`), клиентский — `useWords()` (`components/Words.tsx`, `WordsProvider` в раскладке). Что читает только инженер (репозиторий, раннеры, модель, секреты, бюджет, ревьюер в «Настройках проекта», команда терминала, адрес кода, подробная автономность) — под `w.engineer`. Тексты без читателя (события чатов `EVENT_TEXT`, вопросы и сообщения PM из runner, Telegram, push, подписи из core) — всегда словами «Продакта»: «задача», «агент», «Peppa FACTORY», «вы», «Результат:» вместо «PR:». Промпты агентам, MCP и CLI — прежние слова. Страница задачи, полоса лимитов и «Помощь» — PEP-120/121/122. Тест `wording.test.ts`
|
||||
- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0020; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:<taskId>`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts`
|
||||
- **Комментарий уточняет постановку (PEP-115)**: `pm_comment` к стори в бэклоге без живого агента → `storyRefineTick` в тике вачдога (`runner/story-refine.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`/`_MODEL`), промпт `refinePrompt` (core/story-refine.ts: контекст `intakeContext`, текущая постановка, обсуждение, новые комментарии), ответ — JSON аналитика (`parseAnalystNote`) → описание через `intakeDescription` («Исходный запрос» сохраняется, `originalRequest`) + заметка аналитика `intake_note` в «Обсуждении» стори. Курсор `refine.task:<taskId>`, комментарии старше `PEPPA_STORY_REFINE_MAX_AGE_MIN` (60) не трогаются, сбой — одна заметка без повторов, стори взяли в работу до ответа — описание не меняется, роли PEP-84 не закончили — ждёт; `PEPPA_STORY_REFINE=off`. `refinePending` — «Аналитик уточняет постановку…» и исключение из `readyBacklog`. Подпись поля — `apps/web/lib/comment-hint.ts`. Мок — роль `refine` в `mock-intake` (`slowMs`); тест `story-refine.test.ts`
|
||||
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:<userId>`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
|
||||
- **Страница задачи в режиме «Продакт» (PEP-120)**: `t/[key]/page.tsx` при `uiMode()` = product рисует `components/StoryProduct.tsx` — карточку из `storyProductView` (core/story-product.ts, чистая функция; все тексты — `STORY_PRODUCT_TEXT`; `plainStep` не показывает пункт tasks.md с путями, файлами и идентификаторами): что сейчас, «Шаг N из M», «Посмотреть» (`reviewPreview().previewUrl`), что нужно от вас, что дальше, открытые вопросы (`QuestionCard plain`: команда разрешения — под «Подробнее»), «Принять» (`acceptStoryAction`) и «Поправить» (`fixStoryAction` → `fixStory` в runner/flow.ts: только из ревью, комментарий + закрыть «готово к ревью» + `moveTask in_progress` + замечание агенту). Прежнее содержимое страницы и блоки правой панели — под ссылкой «Подробнее» (`?more=1`, также `?tab=`/`?edit=`; закрыто — терминал не монтируется), без правой панели и значка статуса. «Инженер» — без изменений. Тест `story-product.test.ts`
|
||||
|
||||
@ -40,6 +40,7 @@ import {
|
||||
markOutboxSent,
|
||||
pendingQuestions,
|
||||
getUiMode,
|
||||
needsPerson,
|
||||
questionByTelegramMessage,
|
||||
setOffset,
|
||||
setSetting,
|
||||
@ -306,12 +307,20 @@ export function createBot(o: BotOptions) {
|
||||
const waitingFor = async (userId: number) => {
|
||||
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
|
||||
const ids = projectsOf.get(userId)!;
|
||||
return open.filter((x) => ids.has(x.projectId)).length;
|
||||
return open.filter((x) => ids.has(x.projectId) && waits.has(x.id)).length;
|
||||
};
|
||||
// PEP-149: what waits for a person — questions and finished stories; only these push and count.
|
||||
const ctxOf = new Map<number, Awaited<ReturnType<typeof context>>>();
|
||||
const waits = new Set<number>();
|
||||
for (const q of open) {
|
||||
const c = await context(q);
|
||||
ctxOf.set(q.id, c);
|
||||
if (needsPerson(q, c.taskStatus)) waits.add(q.id);
|
||||
}
|
||||
for (const q of open) {
|
||||
const audience = await projectAudience(db, q.projectId);
|
||||
if (!audience.length) continue;
|
||||
const ctx = await context(q);
|
||||
const ctx = ctxOf.get(q.id)!;
|
||||
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
|
||||
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
|
||||
const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS;
|
||||
@ -325,7 +334,7 @@ export function createBot(o: BotOptions) {
|
||||
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
|
||||
pushKey: `q:${q.id}:u${u.id}`,
|
||||
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
|
||||
push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
|
||||
push: fresh && waits.has(q.id) ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
|
||||
urgency: event === "questions" || event === "failures" ? "high" : "normal",
|
||||
});
|
||||
}
|
||||
@ -931,7 +940,8 @@ export function createBot(o: BotOptions) {
|
||||
} else if (kind === "q") {
|
||||
const q = await getQuestion(db, id).catch(() => null);
|
||||
const text = q && choice ? choiceToAnswer(q, choice) : null;
|
||||
toast = q && text ? await answer(q, text) : tr("Вопрос не найден");
|
||||
// PEP-149: the «continue» button of an earlier message answers nothing.
|
||||
toast = q && text ? await answer(q, text) : q && choice === "cont" ? tr("Кнопка устарела — ответьте на сообщение текстом.") : tr("Вопрос не найден");
|
||||
} else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
|
||||
// Decision on a new production error (PEP-58).
|
||||
try {
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||
import { stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
|
||||
import { questionType, stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core";
|
||||
import type { InlineButton } from "./telegram.ts";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
@ -32,6 +32,7 @@ export function renderQuestion(
|
||||
const lines = [head, KIND[q.kind], "", body];
|
||||
|
||||
const buttons: InlineButton[][] = [];
|
||||
const type = questionType(q, ctx.taskStatus);
|
||||
if (q.kind === "approval") {
|
||||
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
|
||||
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
|
||||
@ -41,23 +42,24 @@ export function renderQuestion(
|
||||
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
|
||||
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
|
||||
]);
|
||||
} else if (q.kind === "question") {
|
||||
} else if (type === "question") {
|
||||
// PEP-149: a question always comes with answers to tap; the default goes first.
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
if (q.kind === "attention") lines[1] = KIND.question;
|
||||
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
|
||||
} else if (ctx.taskStatus === "review") {
|
||||
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
|
||||
} else if (type === "done") {
|
||||
lines[1] = tr("✅ Готово к ревью");
|
||||
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
|
||||
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
|
||||
} else {
|
||||
// A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
|
||||
const s = ctx.session;
|
||||
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
|
||||
buttons.push([
|
||||
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
|
||||
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
|
||||
]);
|
||||
} else {
|
||||
buttons.push([{ text: tr("▶️ Продолжай"), callback_data: `q:${q.id}:cont` }]);
|
||||
lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту.")));
|
||||
}
|
||||
}
|
||||
if (ctx.session && ctx.engineer) lines.push(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
|
||||
@ -77,8 +79,8 @@ export function renderAnswered(original: string, q: Question): string {
|
||||
export function choiceToAnswer(q: Question, choice: string): string | null {
|
||||
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
|
||||
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
|
||||
if (q.kind === "attention" && choice === "cont") return "Продолжай."; // i18n-ignore: the answer goes to the agent
|
||||
// PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing.
|
||||
const m = /^o(\d+)$/.exec(choice);
|
||||
if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
|
||||
if (m) return q.options?.[Number(m[1])] ?? null;
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -102,6 +102,12 @@ async function ProductHelp() {
|
||||
</div>
|
||||
<p className="mt-4 mb-0">{t.question}</p>
|
||||
<p className="mt-4 mb-0">{t.product}</p>
|
||||
<section className="mt-4" data-help-messages>
|
||||
<h2 className="m-0 mb-1.5 text-base font-semibold">{t.messages.title}</h2>
|
||||
<ul className="m-0 flex list-disc flex-col gap-1 pl-5">
|
||||
{t.messages.items.map((x) => <li key={x}>{x}</li>)}
|
||||
</ul>
|
||||
</section>
|
||||
<p className="mt-4 mb-0">
|
||||
{t.problem}{" "}
|
||||
<Link href="/feedback" className="text-primary">{tr("Ваши обращения")}</Link>
|
||||
@ -149,6 +155,7 @@ export default async function Help() {
|
||||
<li>{rich(t("<b>Новый терминал</b> — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать."))}</li>
|
||||
<li>{rich(t("<b>Раннеры и стори</b> — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка <code>task/…</code>, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь."))}</li>
|
||||
<li>{rich(t("<b>Изоляция и хосты</b> — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Peppa FACTORY и чужих проектов; хуки, MCP и git идут в Peppa FACTORY через релей и только к репозиторию проекта (PR агент открывает инструментом <code>open_pull_request</code>). «Где запускать раннеры» — Mac Peppa FACTORY или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Peppa FACTORY на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими."))}</li>
|
||||
<li>{rich(t("<b>Сообщения агента</b> — четырёх типов. <b>Вопрос</b> — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. <b>Готово</b> — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. <b>Ход работы</b> — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. <b>Блокер</b> — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY."))}</li>
|
||||
<li>{rich(t("<b>Главная</b> — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе <a href=\"/projects\">Проекты</a>."))}</li>
|
||||
</ul>
|
||||
</Section>
|
||||
|
||||
@ -12,7 +12,7 @@ import { Workspace } from "@/components/Workspace";
|
||||
import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { activeSessions, inbox } from "@/lib/queries";
|
||||
import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
|
||||
|
||||
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
|
||||
const user = await requireUser();
|
||||
@ -20,7 +20,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
|
||||
const t = await getT();
|
||||
const w = await words();
|
||||
if (await claimWelcome(db, user.id)) redirect("/welcome");
|
||||
const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
|
||||
const [items, ready, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), acceptInbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
|
||||
// PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here.
|
||||
const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : [];
|
||||
return (
|
||||
@ -33,6 +33,11 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
|
||||
<PugBanner count={items.length} />
|
||||
{items.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</Section>
|
||||
{ready.length > 0 && (
|
||||
<Section title={t("Ждут «Принять»")} count={ready.length}>
|
||||
{ready.map((q) => <QuestionCard key={q.id} q={q} taskKey={q.taskKey} taskStatus={q.taskStatus} back="/" />)}
|
||||
</Section>
|
||||
)}
|
||||
{reports.length > 0 && (
|
||||
<Section title={t("Обращения пользователей")} count={reports.length} actions={<MoreLink href="/feedback">{t("все обращения")}</MoreLink>}>
|
||||
{reports.slice(0, 5).map((f) => <AdminFeedbackCard key={f.id} f={f} back="/" />)}
|
||||
|
||||
@ -42,6 +42,7 @@ import {
|
||||
taskCiSummary,
|
||||
type GateResult,
|
||||
productUrls,
|
||||
questionType,
|
||||
} from "@peppa/core";
|
||||
import { checkRuns } from "@peppa/db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
@ -236,7 +237,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
);
|
||||
|
||||
// What a product manager reads first: open questions (the «готово к ревью» message is the card's own buttons).
|
||||
const productQuestions = questions.filter((q) => !q.answeredAt && !(q.kind === "attention" && task.status === "review")).reverse();
|
||||
// PEP-149: only messages of type `question`; failures and other factory messages stay under «Подробнее».
|
||||
const productQuestions = questions.filter((q) => !q.answeredAt && questionType(q, task.status) === "question").reverse();
|
||||
const productView = storyProductView({
|
||||
status: task.status,
|
||||
archived: !!task.archivedAt,
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
// Domain cards shared by pages: agent questions, runners, project list.
|
||||
import Link from "next/link";
|
||||
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
|
||||
import { questionDetails, questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
||||
import { questionDetails, questionState, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
import { SubscriptionName } from "@/components/SubscriptionName";
|
||||
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
|
||||
@ -38,7 +38,9 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
|
||||
const t = await getT();
|
||||
const review = q.kind === "attention" && taskStatus === "review";
|
||||
const answered = !!q.answeredAt;
|
||||
const k = KIND[q.kind];
|
||||
const notice = questionType(q, taskStatus) === null && q.taskId == null && q.sessionId == null;
|
||||
// PEP-149: a factory message with answers to choose from is a question for the person.
|
||||
const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind];
|
||||
const Icon = review ? CircleCheck : k.icon;
|
||||
// PEP-151: the same state came again — one message with the time it was last refreshed.
|
||||
const state = await questionState(db, q.id).catch(() => null);
|
||||
@ -79,12 +81,13 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
|
||||
<pre className="m-0 mt-1 max-h-72 overflow-auto font-mono whitespace-pre-wrap">{original}</pre>
|
||||
</details>
|
||||
)}
|
||||
{/* PEP-149: a notice about the product as a whole (released, backlog is empty) asks nothing — no answer form. */}
|
||||
{answered ? (
|
||||
<p className="m-0 flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
{q.answeredVia === "system" ? <Hourglass className="size-3.5" /> : <CircleCheck className="size-3.5 text-ok" />}
|
||||
{q.answeredVia === "system" ? t.text(q.answer) : t("Ответ ({via}): {answer}", { via: q.answeredVia, answer: q.answer })}
|
||||
</p>
|
||||
) : (
|
||||
) : notice ? null : (
|
||||
<form action={answerQuestion} className="flex flex-col gap-2">
|
||||
<Hidden fields={{ questionId: q.id, back }} />
|
||||
<div className="flex flex-wrap gap-2">
|
||||
@ -98,12 +101,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
|
||||
</>
|
||||
)}
|
||||
{review && <Button name="choice" value="__accept" variant="default" size="sm">{t("Принять")}</Button>}
|
||||
{/* i18n-ignore: the value is the message to the agent */}
|
||||
{q.kind === "attention" && !review && <Button name="choice" value="Продолжай." variant="default" size="sm">{t("Продолжай")}</Button>}
|
||||
{/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */}
|
||||
{(q.options ?? []).map((o) => (
|
||||
<Button key={o} name="choice" value={o} size="sm">{t.text(o)}</Button>
|
||||
<Button key={o} name="choice" value={o} size="sm" variant={o === q.defaultOption ? "default" : undefined} data-default-option={o === q.defaultOption ? "" : undefined}>{t.text(o)}</Button>
|
||||
))}
|
||||
</div>
|
||||
{q.defaultOption && <p className="m-0 text-xs text-muted-foreground">{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}</p>}
|
||||
{q.kind !== "permission" && (
|
||||
<div className="flex gap-2">
|
||||
<Input id={`answer-${q.id}`} name="answer" data-hotkey-answer placeholder={q.kind === "approval" || review ? t("Замечание — вернёт на доработку") : t("Свой ответ")} aria-label={t("Ответ")} className="h-8" />
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
|
||||
import { listSessions, needsPerson, questionType, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
|
||||
import { events, projects, questions, sessions, tasks } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
@ -7,8 +7,22 @@ import { db } from "./db";
|
||||
|
||||
export type InboxItem = Awaited<ReturnType<typeof inbox>>[number];
|
||||
|
||||
/** Open PM questions across the user's projects, oldest first. */
|
||||
/**
|
||||
* PEP-149: «Ждут вашего ответа» — open messages of type `question` across the user's projects,
|
||||
* oldest first. Stories waiting for «Принять» (`done`) have their own block; progress, blockers
|
||||
* and factory messages never land here.
|
||||
*/
|
||||
export async function inbox(userId: number) {
|
||||
return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "question");
|
||||
}
|
||||
|
||||
/** PEP-149: finished stories waiting for «Принять» — open messages of type `done`. */
|
||||
export async function acceptInbox(userId: number) {
|
||||
return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "done" && q.taskStatus === "review");
|
||||
}
|
||||
|
||||
/** Every open message of the user's projects (any type), oldest first. */
|
||||
async function openMessages(userId: number) {
|
||||
const ids = await userProjectIds(db, userId);
|
||||
if (!ids.length) return [];
|
||||
const rows = await db
|
||||
@ -65,11 +79,12 @@ export const isActiveSession = (status: string) => !["done", "failed"].includes(
|
||||
export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number; chats: number }> {
|
||||
const ids = await userProjectIds(db, userId);
|
||||
if (!ids.length) return { questions: 0, waitingRunners: 0, chats: 0 };
|
||||
const [q] = await db.select({ n: count() }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)));
|
||||
// PEP-149: only what waits for the person — questions and finished stories to accept.
|
||||
const q = { n: (await openMessages(userId)).filter((x) => needsPerson(x, x.taskStatus)).length };
|
||||
const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input")));
|
||||
// PEP-106: messages of other people in the projects' discussions the user has not read.
|
||||
const chats = [...(await discussionUnread(db, userId)).values()].reduce((a, b) => a + b, 0);
|
||||
return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0, chats };
|
||||
return { questions: q.n, waitingRunners: r?.n ?? 0, chats };
|
||||
}
|
||||
|
||||
/** Latest events of one runner, newest first (runner details panel, PEP-38). */
|
||||
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-16
|
||||
@ -0,0 +1,31 @@
|
||||
# Design: PEP-149
|
||||
|
||||
## Context
|
||||
|
||||
Сообщение пользователю сегодня — строка `questions` с `kind` (`question | permission | approval | attention`). `attention` — это и «готово к ревью», и сбой, и «агент закончил ход». Ход работы (`report_progress`) — событие `progress`, которое `syncChats` кладёт в тред задачи.
|
||||
|
||||
## Decisions
|
||||
|
||||
**1. Где хранится тип.** Две новые колонки `questions`: `msg_type` (`question | done | progress | blocker`, nullable) и `default_option` (текст варианта по умолчанию). `kind` не трогаем: на нём держатся хук разрешений, одобрение плана, «Принять», сбои. Сообщения, у которых нет строки вопроса, типизирует само событие: `progress` и новое `blocker` в `events` (их проекция в `chat_messages` идёт по типу события). Колонку в `chat_messages` не добавляем: у сообщения чата есть `question_id` или оно пришло из события — тип выводится. Альтернатива «расширить enum `kind`» отвергнута: десятки мест сравнивают `kind === "attention"`, в том числе в файлах соседних задач.
|
||||
|
||||
**2. Тип новых и старых строк.** При вставке (`askPm`, `askPmProject`, `raiseSessionQuestion`) тип берётся из аргумента, иначе: не `attention` → `question`; `attention` с вариантами ответа → `question`. Остальные `attention` (сбои, лимиты, выкладки — тексты соседних задач) остаются без типа. Для чтения — одна функция `questionType(q, taskStatus)`: сохранённый тип → правило выше → `attention` у задачи в ревью = `done` → `null` («сообщение от фабрики»). Старые строки не переписываются — работают по тому же правилу.
|
||||
|
||||
**3. Маршруты.**
|
||||
- `question` и `done` — «ждут человека»: «Ждут вашего ответа» (только question), счётчики меню и `/api/attention` (question + done), push, Telegram с кнопками. Одно SQL-условие `NEEDS_PERSON` в `core/questions.ts` для счётчиков.
|
||||
- `progress` — только событие → тред задачи в «Событиях агентов». Ни вопроса, ни Telegram, ни push.
|
||||
- `blocker` — `report_blocker`: продуктовый (с вариантами и вариантом по умолчанию) создаёт question; непродуктовый — событие `blocker` в треде задачи и сообщение администраторам фабрики (`alertAdmins`), владельцу проекта ничего. Что делать с блокером дальше — задача про сбои.
|
||||
- Сообщения без типа (сбои и т. п.) по-прежнему уходят в Telegram и чат проекта, но без кнопки «Продолжай», не в «Ждут вашего ответа», не в счётчик и без push. Их дальнейшая судьба — задача про сбои.
|
||||
|
||||
**4. Конец хода.** Последняя ветка `turnEnd`: событие `progress` (`{text, auto: true}`) вместо вопроса; сессия → `idle` (не `waiting_input`: она не ждёт человека и не должна светиться в «ждут вас»). Чтобы такие сессии не висели вечно, `idleStopTick` останавливает и `idle`-сессии задач (одно условие, тексты не меняются). Открытые сообщения без типа больше не блокируют подталкивание агента — блокируют только question.
|
||||
|
||||
**5. Кто будит агента.** Красные проверки, ревьюер, rebase и комментарии уже будят. Добавляется зелёный случай: отчёт о пройденной проверке, задача в работе, ход агента окончен, гейт ревью открыт → одно сообщение агенту на коммит («проверки прошли — переводи в review»), отметка `ci.woke:<taskId>`.
|
||||
|
||||
**6. `done`.** Только через `sendReviewCard` (гейт PEP-127 без изменений), тип `done`. Если в тексте нет ни одной ссылки — добавляется ссылка на страницу задачи.
|
||||
|
||||
**7. `ask_pm`.** `options` (2–4) и `default` (текст одного из вариантов) проверяются в обработчике, а не схемой, чтобы агент получил объяснение, а не ошибку валидации. Вариант по умолчанию ставится первым и подсвечивается; под вопросом — «Если не ответите, агент продолжит по варианту …».
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- Соседние задачи эпика тоже могут добавить миграцию → конфликт журнала drizzle при rebase: перегенерировать свою миграцию поверх main.
|
||||
- Агент, который закончил ход и ничего не ждёт, остаётся без пинка до остановки по простою — сознательно: это «сбой», а не вопрос продакту (соседняя задача).
|
||||
- Вопрос «проверки не проходят 3 раза» (`ci-feedback.ts`) остаётся вопросом без вариантов — его перепишет задача про сбои.
|
||||
@ -0,0 +1,30 @@
|
||||
# PEP-149: четыре типа сообщений агента
|
||||
|
||||
## Why
|
||||
|
||||
Пользователь Peppa FACTORY — продакт. Сейчас любой конец хода агента превращается в «вопрос» с сырым текстом последней реплики и кнопкой «Продолжай» (PEP-147: девять одинаковых сообщений за 18 минут). В «Ждут вашего ответа» и в Telegram попадает всё подряд, и настоящие вопросы теряются.
|
||||
|
||||
## What Changes
|
||||
|
||||
- У сообщения агента пользователю появляется тип: **question**, **done**, **progress**, **blocker**. От типа зависит маршрут.
|
||||
- Конец хода без смены статуса задачи больше не будит пользователя: реплика агента становится записью хода работы (`progress`) в «Событиях агентов». Агента, который ждёт проверок, будит платформа, когда проверки прошли.
|
||||
- `ask_pm` требует 2–4 варианта ответа и вариант по умолчанию; без них — отказ с объяснением. Новый инструмент `report_blocker`. `report_progress` — тип progress.
|
||||
- «Готово» (`done`) шлёт только платформа, только после зелёных проверок и всегда со ссылкой на результат.
|
||||
- Кнопка «Продолжай» убрана из веба и бота. **BREAKING** для старых сообщений Telegram: кнопка на них больше не срабатывает.
|
||||
- «Ждут вашего ответа», счётчики, напоминания и push считают только question (и done — как «ждёт „Принять“»).
|
||||
- `template/RULES.md` и «Помощь» описывают четыре типа.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
- `agent-messages`: типы сообщений агента пользователю и маршрут каждого типа.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
Нет: поведение прежних спецификаций (хуки, MCP, уведомления) описывается здесь одним новым контрактом; требования соседних возможностей про сбои и повторы не меняются.
|
||||
|
||||
## Impact
|
||||
|
||||
- БД: `questions.msg_type`, `questions.default_option` (миграция; применяет координатор).
|
||||
- `packages/core` (новый `questions.ts`, `tasks.ts`, `sessions.ts`, `review-card.ts`, `notifications.ts`, строка в `EVENT_TEXT`), `packages/runner` (`hook.ts`, `ci-feedback.ts`, одно условие в `recovery.ts`), `packages/mcp` (`agent.ts`, `manager.ts`), `apps/web` (карточка вопроса, «Ждут вашего ответа», счётчики, «Помощь»), `apps/bot` (`render.ts`, `bot.ts`), `template/RULES.md`, переводы en/kk.
|
||||
- Тексты сбоев (`recovery.ts`, `watchdog.ts`, `autonomy.ts`) и логика повторов в `core/chats.ts` не меняются — соседние задачи эпика.
|
||||
@ -0,0 +1,104 @@
|
||||
# Spec Delta
|
||||
|
||||
## Purpose
|
||||
Сообщения агента пользователю делятся на четыре типа — вопрос, готово, ход работы, блокер; от типа зависит, увидит ли его пользователь в «Ждут вашего ответа», в Telegram или только в «Событиях агентов».
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Тип сообщения определяет маршрут
|
||||
Система SHALL присваивать каждому новому сообщению агента пользователю один из типов `question`, `done`, `progress`, `blocker`. В «Ждут вашего ответа» SHALL попадать только `question`; счётчик «ждут вас», напоминания и push SHALL учитывать только `question` и `done`.
|
||||
|
||||
#### Scenario: Вопрос попадает в «Ждут вашего ответа»
|
||||
- **GIVEN** задача PEP-1 в работе
|
||||
- **WHEN** агент задаёт вопрос «Какой цвет кнопки?» с вариантами «Синий» и «Зелёный», по умолчанию «Синий»
|
||||
- **THEN** на Главной в «Ждут вашего ответа» есть этот вопрос с кнопками «Синий» и «Зелёный» и полем «Свой ответ»
|
||||
- **AND** счётчик «ждут вас» равен 1
|
||||
|
||||
#### Scenario: Сообщение о сбое не попадает в «Ждут вашего ответа»
|
||||
- **GIVEN** открытое сообщение фабрики без вариантов ответа «агент остановился с ошибкой»
|
||||
- **WHEN** пользователь открывает Главную
|
||||
- **THEN** в «Ждут вашего ответа» этого сообщения нет
|
||||
- **AND** счётчик «ждут вас» равен 0
|
||||
|
||||
### Requirement: Конец хода — это ход работы, а не вопрос
|
||||
Когда агент закончил ход, а статус задачи не изменился и подталкивания исчерпаны, система SHALL записать последнюю реплику агента как `progress` в «События агентов» и SHALL NOT создавать вопрос, отправлять Telegram или push.
|
||||
|
||||
#### Scenario: Агент закончил ход, статус задачи тот же
|
||||
- **GIVEN** задача PEP-1 в работе, агент уже дважды получил подталкивание
|
||||
- **WHEN** агент заканчивает ход с текстом «Жду проверок»
|
||||
- **THEN** в «Ждут вашего ответа» и в Telegram владельца ничего нового нет
|
||||
- **AND** в «Событиях агентов» проекта, в треде PEP-1, есть запись «Жду проверок»
|
||||
|
||||
#### Scenario: У агента есть открытый вопрос
|
||||
- **GIVEN** агент задал вопрос с вариантами и не получил ответа
|
||||
- **WHEN** агент заканчивает ход
|
||||
- **THEN** новая запись хода работы не создаётся, вопрос остаётся в «Ждут вашего ответа»
|
||||
|
||||
### Requirement: Платформа будит агента, когда проверки прошли
|
||||
Когда все проверки последнего коммита задачи в работе прошли, а ход агента окончен, система SHALL один раз на коммит сообщить агенту, что задачу можно переводить в ревью.
|
||||
|
||||
#### Scenario: Проверки прошли, агент ждал
|
||||
- **GIVEN** задача PEP-1 в работе, агент закончил ход, проверки коммита `abc1234` ещё шли
|
||||
- **WHEN** последняя проверка коммита `abc1234` проходит
|
||||
- **THEN** агент получает сообщение «проверки прошли»
|
||||
|
||||
#### Scenario: Повторный отчёт о том же коммите
|
||||
- **GIVEN** агент уже получил сообщение о коммите `abc1234`
|
||||
- **WHEN** приходит ещё один успешный отчёт по коммиту `abc1234`
|
||||
- **THEN** второго сообщения агент не получает
|
||||
|
||||
### Requirement: «Готово» шлёт платформа после проверок
|
||||
Сообщение типа `done` SHALL отправляться только платформой, только когда проверки последнего коммита прошли и нет конфликта, и SHALL содержать ссылку на результат.
|
||||
|
||||
#### Scenario: Проверки прошли
|
||||
- **GIVEN** задача PEP-1 в ревью, проверки зелёные, результат `https://git.example/pulls/7`
|
||||
- **WHEN** агент заканчивает ход
|
||||
- **THEN** владелец получает сообщение «готова к ревью» типа `done` со ссылкой `https://git.example/pulls/7` и кнопкой «Принять»
|
||||
|
||||
#### Scenario: Проверки ещё идут
|
||||
- **GIVEN** задача PEP-1 в ревью, одна проверка не завершена
|
||||
- **WHEN** агент заканчивает ход
|
||||
- **THEN** владелец ничего не получает, пока проверки не пройдут
|
||||
|
||||
### Requirement: Вопрос агента — с вариантами и вариантом по умолчанию
|
||||
Инструмент `ask_pm` SHALL принимать вопрос только с 2–4 вариантами ответа и вариантом по умолчанию из их числа; иначе SHALL отклонять вызов с объяснением.
|
||||
|
||||
#### Scenario: Вопрос с вариантами принят
|
||||
- **WHEN** агент вызывает `ask_pm` с вариантами «Да», «Нет» и вариантом по умолчанию «Да»
|
||||
- **THEN** вопрос отправлен, вариант «Да» показан первым и отмечен как выбранный по умолчанию
|
||||
|
||||
#### Scenario Outline: Вопрос без вариантов отклонён
|
||||
- **WHEN** агент вызывает `ask_pm` с вариантами <варианты> и вариантом по умолчанию <по умолчанию>
|
||||
- **THEN** вызов отклонён с объяснением «<причина>», вопрос не создан
|
||||
|
||||
| варианты | по умолчанию | причина |
|
||||
|---|---|---|
|
||||
| нет | нет | нужны 2–4 варианта |
|
||||
| «Да» | «Да» | нужны 2–4 варианта |
|
||||
| «Да», «Нет» | нет | нужен вариант по умолчанию |
|
||||
| «Да», «Нет» | «Может быть» | вариант по умолчанию — один из вариантов |
|
||||
|
||||
### Requirement: Блокер идёт по своему маршруту
|
||||
Инструмент `report_blocker` SHALL принимать, что мешает и что агент уже пробовал. Продуктовый блокер SHALL идти пользователю как `question` с вариантами; непродуктовый SHALL записываться в «События агентов» и SHALL NOT отправляться владельцу проекта.
|
||||
|
||||
#### Scenario: Непродуктовый блокер
|
||||
- **WHEN** агент сообщает блокер «нет доступа к серверу сборки», пробовал «повторил три раза»
|
||||
- **THEN** в треде задачи в «Событиях агентов» есть запись о блокере
|
||||
- **AND** владелец не получает ни вопроса, ни сообщения в Telegram
|
||||
|
||||
#### Scenario: Продуктовый блокер без вариантов
|
||||
- **WHEN** агент сообщает продуктовый блокер без вариантов ответа
|
||||
- **THEN** вызов отклонён с объяснением, что нужны варианты и вариант по умолчанию
|
||||
|
||||
### Requirement: Нет кнопки «Продолжай»
|
||||
Веб и Telegram-бот SHALL NOT показывать кнопку «Продолжай» ни у какого сообщения; у `question` SHALL быть кнопки вариантов и возможность своего ответа.
|
||||
|
||||
#### Scenario: Сообщение фабрики в Telegram
|
||||
- **GIVEN** открытое сообщение фабрики без вариантов ответа
|
||||
- **WHEN** бот отправляет его в Telegram
|
||||
- **THEN** у сообщения нет кнопки «Продолжай»
|
||||
|
||||
#### Scenario: Старая кнопка «Продолжай»
|
||||
- **GIVEN** старое сообщение в Telegram с кнопкой «Продолжай»
|
||||
- **WHEN** пользователь нажимает её
|
||||
- **THEN** агенту ничего не отправляется
|
||||
@ -0,0 +1,22 @@
|
||||
# Tasks: PEP-149
|
||||
|
||||
## 1. Ядро
|
||||
- [x] 1.1 Миграция: `questions.msg_type`, `questions.default_option`
|
||||
- [x] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion`
|
||||
- [x] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна
|
||||
- [x] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`)
|
||||
|
||||
## 2. Агент
|
||||
- [x] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle`
|
||||
- [x] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит)
|
||||
- [x] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress`
|
||||
|
||||
## 3. Веб и бот
|
||||
- [x] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике)
|
||||
- [x] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP
|
||||
- [x] 3.3 Переводы en/kk
|
||||
|
||||
## 4. Правила, помощь, проверки
|
||||
- [x] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа
|
||||
- [x] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов
|
||||
- [x] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта
|
||||
104
openspec/specs/agent-messages/spec.md
Normal file
104
openspec/specs/agent-messages/spec.md
Normal file
@ -0,0 +1,104 @@
|
||||
# agent-messages Specification
|
||||
|
||||
## Purpose
|
||||
Сообщения агента пользователю делятся на четыре типа — вопрос, готово, ход работы, блокер; от типа зависит, увидит ли его пользователь в «Ждут вашего ответа», в Telegram или только в «Событиях агентов».
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Тип сообщения определяет маршрут
|
||||
Система SHALL присваивать каждому новому сообщению агента пользователю один из типов `question`, `done`, `progress`, `blocker`. В «Ждут вашего ответа» SHALL попадать только `question`; счётчик «ждут вас», напоминания и push SHALL учитывать только `question` и `done`.
|
||||
|
||||
#### Scenario: Вопрос попадает в «Ждут вашего ответа»
|
||||
- **GIVEN** задача PEP-1 в работе
|
||||
- **WHEN** агент задаёт вопрос «Какой цвет кнопки?» с вариантами «Синий» и «Зелёный», по умолчанию «Синий»
|
||||
- **THEN** на Главной в «Ждут вашего ответа» есть этот вопрос с кнопками «Синий» и «Зелёный» и полем «Свой ответ»
|
||||
- **AND** счётчик «ждут вас» равен 1
|
||||
|
||||
#### Scenario: Сообщение о сбое не попадает в «Ждут вашего ответа»
|
||||
- **GIVEN** открытое сообщение фабрики без вариантов ответа «агент остановился с ошибкой»
|
||||
- **WHEN** пользователь открывает Главную
|
||||
- **THEN** в «Ждут вашего ответа» этого сообщения нет
|
||||
- **AND** счётчик «ждут вас» равен 0
|
||||
|
||||
### Requirement: Конец хода — это ход работы, а не вопрос
|
||||
Когда агент закончил ход, а статус задачи не изменился и подталкивания исчерпаны, система SHALL записать последнюю реплику агента как `progress` в «События агентов» и SHALL NOT создавать вопрос, отправлять Telegram или push.
|
||||
|
||||
#### Scenario: Агент закончил ход, статус задачи тот же
|
||||
- **GIVEN** задача PEP-1 в работе, агент уже дважды получил подталкивание
|
||||
- **WHEN** агент заканчивает ход с текстом «Жду проверок»
|
||||
- **THEN** в «Ждут вашего ответа» и в Telegram владельца ничего нового нет
|
||||
- **AND** в «Событиях агентов» проекта, в треде PEP-1, есть запись «Жду проверок»
|
||||
|
||||
#### Scenario: У агента есть открытый вопрос
|
||||
- **GIVEN** агент задал вопрос с вариантами и не получил ответа
|
||||
- **WHEN** агент заканчивает ход
|
||||
- **THEN** новая запись хода работы не создаётся, вопрос остаётся в «Ждут вашего ответа»
|
||||
|
||||
### Requirement: Платформа будит агента, когда проверки прошли
|
||||
Когда все проверки последнего коммита задачи в работе прошли, а ход агента окончен, система SHALL один раз на коммит сообщить агенту, что задачу можно переводить в ревью.
|
||||
|
||||
#### Scenario: Проверки прошли, агент ждал
|
||||
- **GIVEN** задача PEP-1 в работе, агент закончил ход, проверки коммита `abc1234` ещё шли
|
||||
- **WHEN** последняя проверка коммита `abc1234` проходит
|
||||
- **THEN** агент получает сообщение «проверки прошли»
|
||||
|
||||
#### Scenario: Повторный отчёт о том же коммите
|
||||
- **GIVEN** агент уже получил сообщение о коммите `abc1234`
|
||||
- **WHEN** приходит ещё один успешный отчёт по коммиту `abc1234`
|
||||
- **THEN** второго сообщения агент не получает
|
||||
|
||||
### Requirement: «Готово» шлёт платформа после проверок
|
||||
Сообщение типа `done` SHALL отправляться только платформой, только когда проверки последнего коммита прошли и нет конфликта, и SHALL содержать ссылку на результат.
|
||||
|
||||
#### Scenario: Проверки прошли
|
||||
- **GIVEN** задача PEP-1 в ревью, проверки зелёные, результат `https://git.example/pulls/7`
|
||||
- **WHEN** агент заканчивает ход
|
||||
- **THEN** владелец получает сообщение «готова к ревью» типа `done` со ссылкой `https://git.example/pulls/7` и кнопкой «Принять»
|
||||
|
||||
#### Scenario: Проверки ещё идут
|
||||
- **GIVEN** задача PEP-1 в ревью, одна проверка не завершена
|
||||
- **WHEN** агент заканчивает ход
|
||||
- **THEN** владелец ничего не получает, пока проверки не пройдут
|
||||
|
||||
### Requirement: Вопрос агента — с вариантами и вариантом по умолчанию
|
||||
Инструмент `ask_pm` SHALL принимать вопрос только с 2–4 вариантами ответа и вариантом по умолчанию из их числа; иначе SHALL отклонять вызов с объяснением.
|
||||
|
||||
#### Scenario: Вопрос с вариантами принят
|
||||
- **WHEN** агент вызывает `ask_pm` с вариантами «Да», «Нет» и вариантом по умолчанию «Да»
|
||||
- **THEN** вопрос отправлен, вариант «Да» показан первым и отмечен как выбранный по умолчанию
|
||||
|
||||
#### Scenario Outline: Вопрос без вариантов отклонён
|
||||
- **WHEN** агент вызывает `ask_pm` с вариантами <варианты> и вариантом по умолчанию <по умолчанию>
|
||||
- **THEN** вызов отклонён с объяснением «<причина>», вопрос не создан
|
||||
|
||||
| варианты | по умолчанию | причина |
|
||||
|---|---|---|
|
||||
| нет | нет | нужны 2–4 варианта |
|
||||
| «Да» | «Да» | нужны 2–4 варианта |
|
||||
| «Да», «Нет» | нет | нужен вариант по умолчанию |
|
||||
| «Да», «Нет» | «Может быть» | вариант по умолчанию — один из вариантов |
|
||||
|
||||
### Requirement: Блокер идёт по своему маршруту
|
||||
Инструмент `report_blocker` SHALL принимать, что мешает и что агент уже пробовал. Продуктовый блокер SHALL идти пользователю как `question` с вариантами; непродуктовый SHALL записываться в «События агентов» и SHALL NOT отправляться владельцу проекта.
|
||||
|
||||
#### Scenario: Непродуктовый блокер
|
||||
- **WHEN** агент сообщает блокер «нет доступа к серверу сборки», пробовал «повторил три раза»
|
||||
- **THEN** в треде задачи в «Событиях агентов» есть запись о блокере
|
||||
- **AND** владелец не получает ни вопроса, ни сообщения в Telegram
|
||||
|
||||
#### Scenario: Продуктовый блокер без вариантов
|
||||
- **WHEN** агент сообщает продуктовый блокер без вариантов ответа
|
||||
- **THEN** вызов отклонён с объяснением, что нужны варианты и вариант по умолчанию
|
||||
|
||||
### Requirement: Нет кнопки «Продолжай»
|
||||
Веб и Telegram-бот SHALL NOT показывать кнопку «Продолжай» ни у какого сообщения; у `question` SHALL быть кнопки вариантов и возможность своего ответа.
|
||||
|
||||
#### Scenario: Сообщение фабрики в Telegram
|
||||
- **GIVEN** открытое сообщение фабрики без вариантов ответа
|
||||
- **WHEN** бот отправляет его в Telegram
|
||||
- **THEN** у сообщения нет кнопки «Продолжай»
|
||||
|
||||
#### Scenario: Старая кнопка «Продолжай»
|
||||
- **GIVEN** старое сообщение в Telegram с кнопкой «Продолжай»
|
||||
- **WHEN** пользователь нажимает её
|
||||
- **THEN** агенту ничего не отправляется
|
||||
@ -10,6 +10,7 @@ import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, t
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { getNotifyPrefs, projectAudience } from "./notifications.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { IS_QUESTION } from "./questions.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { projectForUser, userProjectIds, type User } from "./users.ts";
|
||||
import type { OutboxRow } from "./telegram.ts";
|
||||
@ -85,7 +86,7 @@ export async function listChats(db: Db, user: Pick<User, "id">): Promise<ChatLis
|
||||
);
|
||||
const open = new Map(
|
||||
ids.length
|
||||
? (await db.select({ p: questions.projectId, n: sql<number>`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)])
|
||||
? (await db.select({ p: questions.projectId, n: sql<number>`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt), IS_QUESTION)).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)])
|
||||
: [],
|
||||
);
|
||||
const masterAt = [...last.values()].reduce<Date | null>((a, b) => (b && (!a || b > a) ? b : a), null);
|
||||
@ -323,7 +324,7 @@ export async function chatThreads(db: Db, chatId: number, limit = 50): Promise<T
|
||||
count: sql<number>`count(*)`,
|
||||
lastId: sql<number>`max(${chatMessages.id})`,
|
||||
lastAt: sql<number>`max(${chatMessages.createdAt})`,
|
||||
open: sql<number>`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`,
|
||||
open: sql<number>`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL AND ${IS_QUESTION} THEN 1 ELSE 0 END)`,
|
||||
})
|
||||
.from(chatMessages)
|
||||
.leftJoin(questions, eq(chatMessages.questionId, questions.id))
|
||||
@ -375,6 +376,8 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
||||
return { text: said[String(to)] ?? tr("• Статус: {to}", { to: statusRu(String(to)) }), important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
|
||||
},
|
||||
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
|
||||
// PEP-149: the agent cannot go on (not a product decision) — a record, not a question.
|
||||
blocker: (p) => ({ text: `⛔ ${tr("Агент не может продолжить: {what}", { what: cut(s(p.what), 1000) })}${s(p.tried) ? `\n${tr("Что уже пробовал: {tried}", { tried: cut(s(p.tried), 500) })}` : ""}`, author: "agent" }),
|
||||
pm_comment: () => null, // handled separately: a person's message
|
||||
// PEP-4: the project's repo moved to another Gitea namespace.
|
||||
repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }),
|
||||
|
||||
@ -18,6 +18,8 @@ export interface ProductHelpText {
|
||||
problem: string;
|
||||
/** PEP-145: where the product is. */
|
||||
product: string;
|
||||
/** PEP-149: the four kinds of messages an agent sends. */
|
||||
messages: { title: string; items: [string, string, string, string] };
|
||||
more: string;
|
||||
moreLink: string;
|
||||
}
|
||||
@ -62,6 +64,15 @@ export const PRODUCT_HELP: Record<HelpLang, ProductHelpText> = {
|
||||
question: "Агент задал вопрос? Он появится на Главной и в Telegram. Ответьте кнопкой или своими словами — агент продолжит работу.",
|
||||
problem: "Что-то не работает в самой Peppa FACTORY? Нажмите «Сообщить о проблеме» внизу любой страницы: напишите, что случилось, и приложите скриншот. В Telegram то же самое — отправьте боту /problem. Что стало с обращением, видно в разделе «Обращения».",
|
||||
product: "Где посмотреть продукт? На странице проекта и на Главной есть кнопка «Открыть продукт». Ссылка появляется сама, в первый же день проекта; если её пока нет, на её месте написано, что происходит, — делать ничего не нужно.",
|
||||
messages: {
|
||||
title: "Какие сообщения присылает агент",
|
||||
items: [
|
||||
"Вопрос — нужно ваше решение. У него всегда есть кнопки с вариантами ответа; один из них агент выберет сам, если вы не ответите.",
|
||||
"Готово — задачу можно посмотреть и принять. Приходит только когда проверки прошли, вместе со ссылкой на результат.",
|
||||
"Ход работы — что агент уже сделал. Это лежит в «Событиях агентов» в чате проекта; отвечать не нужно, уведомлений не будет.",
|
||||
"Агент не может продолжить — если дело в вашем продукте, он задаст вопрос с вариантами. С остальным Peppa FACTORY разбирается сама.",
|
||||
],
|
||||
},
|
||||
more: "Хотите видеть всё, что делают агенты, и полный справочник? Включите вид «Инженер».",
|
||||
moreLink: "Открыть Настройки",
|
||||
},
|
||||
@ -101,6 +112,15 @@ export const PRODUCT_HELP: Record<HelpLang, ProductHelpText> = {
|
||||
question: "Агент сұрақ қойды ма? Ол Басты бетте және Telegram-да пайда болады. Батырмамен немесе өз сөзіңізбен жауап беріңіз — агент жұмысын жалғастырады.",
|
||||
problem: "Peppa FACTORY-дің өзінде бірдеңе жұмыс істемей тұр ма? Кез келген беттің төменгі жағындағы «Мәселе туралы хабарлау» батырмасын басыңыз: не болғанын жазып, скриншот тіркеңіз. Telegram-да да солай — ботқа /problem жіберіңіз. Өтінішіңіздің не болғаны «Өтініштер» бөлімінде көрінеді.",
|
||||
product: "Өнімді қайдан көруге болады? Жоба бетінде және Басты бетте «Өнімді ашу» батырмасы бар. Сілтеме жобаның бірінші күнінде-ақ өзі пайда болады; әзірге жоқ болса, оның орнында не болып жатқаны жазылған — ештеңе істеудің қажеті жоқ.",
|
||||
messages: {
|
||||
title: "Агент қандай хабарламалар жібереді",
|
||||
items: [
|
||||
"Сұрақ — сіздің шешіміңіз керек. Оның әрқашан жауап нұсқалары бар батырмалары болады; жауап бермесеңіз, агент біреуін өзі таңдайды.",
|
||||
"Дайын — тапсырманы қарап, қабылдауға болады. Тек тексерулер өткенде, нәтижеге сілтемемен бірге келеді.",
|
||||
"Жұмыс барысы — агент не істеп үлгергені. Бұл жоба чатындағы «Агенттер оқиғаларында» тұрады; жауап берудің қажеті жоқ, хабарландыру келмейді.",
|
||||
"Агент жалғастыра алмайды — мәселе сіздің өніміңізде болса, ол нұсқалары бар сұрақ қояды. Қалғанын Peppa FACTORY өзі шешеді.",
|
||||
],
|
||||
},
|
||||
more: "Агенттердің барлық іс-әрекетін және толық анықтамалықты көргіңіз келе ме? «Инженер» көрінісін қосыңыз.",
|
||||
moreLink: "Баптауларды ашу",
|
||||
},
|
||||
@ -140,6 +160,15 @@ export const PRODUCT_HELP: Record<HelpLang, ProductHelpText> = {
|
||||
question: "Did an agent ask a question? It appears on Home and in Telegram. Answer with a button or in your own words — the agent carries on.",
|
||||
problem: "Is something not working in Peppa FACTORY itself? Press “Report a problem” at the bottom of any page: write what happened and attach a screenshot. In Telegram it is the same — send /problem to the bot. What became of your report is shown in “Reports”.",
|
||||
product: "Where is the product? The project page and Home have an «Open product» button. The link appears by itself on the project's first day; if it is not there yet, the same place says what is happening — you don't need to do anything.",
|
||||
messages: {
|
||||
title: "What messages an agent sends",
|
||||
items: [
|
||||
"Question — your decision is needed. It always has buttons with answers; the agent picks one of them itself if you don't reply.",
|
||||
"Done — the task can be looked at and accepted. It comes only when the checks have passed, with a link to the result.",
|
||||
"Progress — what the agent has done so far. It stays in “Agent events” in the project chat; no reply is needed and no notification comes.",
|
||||
"The agent cannot go on — if it is about your product, it asks a question with options. Peppa FACTORY sorts out the rest itself.",
|
||||
],
|
||||
},
|
||||
more: "Want to see everything the agents do and the full reference? Turn on the “Engineer” view.",
|
||||
moreLink: "Open Settings",
|
||||
},
|
||||
|
||||
@ -3,6 +3,7 @@ export * from "./notify.ts";
|
||||
export * from "./project-file.ts";
|
||||
export * from "./projects.ts";
|
||||
export * from "./tasks.ts";
|
||||
export * from "./questions.ts";
|
||||
export * from "./sessions.ts";
|
||||
export * from "./rules.ts";
|
||||
export * from "./settings.ts";
|
||||
|
||||
@ -5,6 +5,7 @@ import { eq, inArray } from "drizzle-orm";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
import { enqueueTelegram, type OutboxRow } from "./telegram.ts";
|
||||
import type { Question } from "./tasks.ts";
|
||||
import { questionType } from "./questions.ts";
|
||||
import type { User } from "./users.ts";
|
||||
import { enqueuePush, type PushPayload } from "./webpush.ts";
|
||||
import { addMasterMessage } from "./chats.ts";
|
||||
@ -139,13 +140,14 @@ export function inQuietHours(prefs: Pick<NotifyPrefs, "quiet" | "timezone">, now
|
||||
return from < to ? m >= from && m < to : m >= from || m < to;
|
||||
}
|
||||
|
||||
/** Which event a PM question stands for. */
|
||||
export function questionEvent(q: Pick<Question, "kind" | "taskId" | "sessionId">, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent {
|
||||
if (q.kind !== "attention") return q.taskId == null && q.sessionId == null ? "releases" : "questions";
|
||||
if (ctx.taskStatus === "review") return "review";
|
||||
if (ctx.sessionStatus && ["failed", "rate_limited", "stalled"].includes(ctx.sessionStatus)) return "failures";
|
||||
if (q.taskId == null && q.sessionId == null) return "releases";
|
||||
return "questions";
|
||||
/** Which event a message for the person stands for (PEP-149: by its type). */
|
||||
export function questionEvent(q: Pick<Question, "kind" | "taskId" | "sessionId"> & Partial<Pick<Question, "msgType" | "options">>, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent {
|
||||
const type = questionType(q, ctx.taskStatus);
|
||||
if (type === "done") return "review";
|
||||
const projectLevel = q.taskId == null && q.sessionId == null;
|
||||
if (type === "question") return projectLevel ? "releases" : "questions";
|
||||
// A message of the factory itself: about the product as a whole, or about an agent's trouble.
|
||||
return projectLevel ? "releases" : "failures";
|
||||
}
|
||||
|
||||
/** Owner and members of a project (whether or not they paired Telegram). */
|
||||
|
||||
56
packages/core/src/questions.ts
Normal file
56
packages/core/src/questions.ts
Normal file
@ -0,0 +1,56 @@
|
||||
// PEP-149: four kinds of agent messages for the person — question, done, progress, blocker.
|
||||
// The kind decides the route: only a `question` lands in «Ждут вашего ответа» and comes to
|
||||
// Telegram as a question; `done` waits for «Принять»; `progress` and a non-product `blocker`
|
||||
// are events of the story thread («События агентов») and never wake the person.
|
||||
import { questions } from "@peppa/db";
|
||||
import { sql, type SQL } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
|
||||
export const MESSAGE_TYPES = ["question", "done", "progress", "blocker"] as const;
|
||||
export type MessageType = (typeof MESSAGE_TYPES)[number];
|
||||
|
||||
type Typed = { kind: string; msgType?: MessageType | null; options?: string[] | null; taskId?: number | null };
|
||||
|
||||
/** The type a new row gets when the caller names none: anything a person must decide is a question. */
|
||||
export function defaultMessageType(q: Pick<Typed, "kind" | "options">): MessageType | null {
|
||||
if (q.kind !== "attention") return "question";
|
||||
return q.options?.length ? "question" : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type of a message: the stored one, else derived (rows before PEP-149 and messages of the
|
||||
* factory itself). null — a factory message nobody has to answer (a failure, a limit, a release).
|
||||
*/
|
||||
export function questionType(q: Typed, taskStatus?: string | null): MessageType | null {
|
||||
if (q.msgType) return q.msgType;
|
||||
const d = defaultMessageType(q);
|
||||
if (d) return d;
|
||||
return q.taskId != null && taskStatus === "review" ? "done" : null;
|
||||
}
|
||||
|
||||
/** True for what waits for a person: a question to answer or a finished story to accept. */
|
||||
export function needsPerson(q: Typed, taskStatus?: string | null): boolean {
|
||||
const t = questionType(q, taskStatus);
|
||||
return t === "question" || t === "done";
|
||||
}
|
||||
|
||||
/** SQL twin of `questionType(q) === "question"` (counters of open questions). */
|
||||
export const IS_QUESTION: SQL = sql`(${questions.msgType} = 'question' OR (${questions.msgType} IS NULL AND (${questions.kind} != 'attention' OR json_array_length(${questions.options}) > 0)))`;
|
||||
|
||||
export const ASK_MIN_OPTIONS = 2;
|
||||
export const ASK_MAX_OPTIONS = 4;
|
||||
|
||||
/**
|
||||
* Checks the answers of an agent's question: 2–4 different options and a default among them.
|
||||
* Returns the options with the default first. The text of the refusal is for the agent.
|
||||
*/
|
||||
export function checkChoices(options: string[] | undefined, def: string | undefined): { options: string[]; defaultOption: string } {
|
||||
const opts = [...new Set((options ?? []).map((o) => o.trim()).filter(Boolean))];
|
||||
if (opts.length < ASK_MIN_OPTIONS || opts.length > ASK_MAX_OPTIONS) {
|
||||
throw new PeppaError(`Not sent: a question to the owner needs ${ASK_MIN_OPTIONS}–${ASK_MAX_OPTIONS} answer options (got ${opts.length}). The owner answers with one tap — give the possible answers as \`options\` and your recommendation as \`default\`. If there is nothing to choose from, it is not a question: decide yourself, or use report_progress / report_blocker.`);
|
||||
}
|
||||
const d = def?.trim();
|
||||
if (!d) throw new PeppaError("Not sent: name the `default` — the option you go on with while the owner has not answered (one of `options`).");
|
||||
if (!opts.includes(d)) throw new PeppaError(`Not sent: \`default\` must be exactly one of \`options\` (${opts.map((o) => `«${o}»`).join(", ")}).`);
|
||||
return { options: [d, ...opts.filter((o) => o !== d)], defaultOption: d };
|
||||
}
|
||||
@ -50,8 +50,10 @@ export async function sendReviewCard(db: Db, ref: TaskRef, text: string, session
|
||||
if (gate?.ok) {
|
||||
await clearReviewHold(db, ref.task.id);
|
||||
// PEP-151: «готово» for the same head commit is one message, however many times it is sent.
|
||||
const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null };
|
||||
return session ? raiseSessionQuestion(db, session, "attention", text, undefined, false, state) : askPm(db, ref, { kind: "attention", text, ...state });
|
||||
// PEP-149: it is a `done` message and always carries a link to the result.
|
||||
const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null, msgType: "done" as const };
|
||||
const card = /https?:\/\//.test(text) ? text : `${text}\n\n${m("Посмотреть: {url}", { url: `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/t/${ref.key}` })}`;
|
||||
return session ? raiseSessionQuestion(db, session, "attention", card, undefined, false, state) : askPm(db, ref, { kind: "attention", text: card, ...state });
|
||||
}
|
||||
const prev = await getReviewHold(db, ref.task.id);
|
||||
await setReviewHold(db, ref.task.id, { ...prev, text, at: Date.now() });
|
||||
|
||||
@ -5,6 +5,7 @@ import { PeppaError } from "./errors.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { actorColumns } from "./actor.ts";
|
||||
import type { Question, QuestionKind } from "./tasks.ts";
|
||||
import { defaultMessageType, type MessageType } from "./questions.ts";
|
||||
import { userProjectIds } from "./users.ts";
|
||||
import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts";
|
||||
import { keepQuestionDetails, messageText } from "./user-text.ts";
|
||||
@ -190,7 +191,7 @@ export async function raiseSessionQuestion(
|
||||
text: string,
|
||||
options?: string[],
|
||||
awaitingHook = false,
|
||||
o: { topic?: MessageTopic; head?: string | null } = {},
|
||||
{ msgType, ...o }: { topic?: MessageTopic; head?: string | null; /** PEP-149: default — by kind (core/questions.ts). */ msgType?: MessageType | null } = {},
|
||||
): Promise<Question> {
|
||||
// PEP-154: no service text (tags, command output, paths) in what the person reads.
|
||||
const original = text;
|
||||
@ -198,7 +199,7 @@ export async function raiseSessionQuestion(
|
||||
const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => {
|
||||
const [created] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook })
|
||||
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, msgType: msgType ?? defaultMessageType({ kind, options }) })
|
||||
.returning();
|
||||
return created!;
|
||||
});
|
||||
|
||||
@ -16,6 +16,7 @@ import { taskBudgetView, type TaskBudgetView } from "./budgets.ts";
|
||||
import { productNeeds, type ProductNeedView } from "./product-needs.ts";
|
||||
import { raiseOnce, type MessageTopic } from "./message-state.ts";
|
||||
import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts";
|
||||
import { defaultMessageType, type MessageType } from "./questions.ts";
|
||||
|
||||
export type Task = typeof tasks.$inferSelect;
|
||||
export type TaskStatus = (typeof taskStatus.enumValues)[number];
|
||||
@ -307,6 +308,10 @@ export interface NewQuestion {
|
||||
topic?: MessageTopic;
|
||||
/** Head commit of the result, when the caller knows it. */
|
||||
head?: string | null;
|
||||
/** PEP-149: what the message is for the person; default — by kind (core/questions.ts). */
|
||||
msgType?: MessageType | null;
|
||||
/** PEP-149: the option the agent goes on with meanwhile (one of `options`). */
|
||||
defaultOption?: string;
|
||||
}
|
||||
|
||||
/** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */
|
||||
@ -318,7 +323,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
|
||||
const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => {
|
||||
const [created] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, ...q })
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, ...q, msgType: q.msgType ?? defaultMessageType(q) })
|
||||
.returning();
|
||||
return created!;
|
||||
});
|
||||
@ -329,9 +334,9 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
|
||||
}
|
||||
|
||||
/** A message for the PM about the project as a whole (releases), not about a task. */
|
||||
export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise<Question> {
|
||||
export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[]; msgType?: MessageType | null }): Promise<Question> {
|
||||
const text = messageText(q.kind, q.text);
|
||||
const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text }).returning();
|
||||
const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text, msgType: q.msgType ?? defaultMessageType(q) }).returning();
|
||||
await keepQuestionDetails(db, row!.id, q.text, text).catch(() => {});
|
||||
await notify(db, { type: "question", questionId: row!.id });
|
||||
return row!;
|
||||
@ -391,6 +396,19 @@ export async function reportProgress(db: Db, ref: TaskRef, text: string, session
|
||||
return row!;
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-149: the agent cannot go on and it is not a product decision — a `blocker` event in the
|
||||
* story thread («События агентов»). The owner is not asked; what happens next is Peppa's job.
|
||||
*/
|
||||
export async function reportBlocker(db: Db, ref: TaskRef, b: { what: string; tried: string }, sessionId?: number) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "blocker", payload: { what: b.what, tried: b.tried }, ...actorColumns(sessionId) })
|
||||
.returning();
|
||||
await notify(db, { type: "progress", eventId: row!.id });
|
||||
return row!;
|
||||
}
|
||||
|
||||
function pick<T extends object>(o: T, keys: string[]): Record<string, unknown> {
|
||||
return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]]));
|
||||
}
|
||||
|
||||
2
packages/db/migrations/0020_fuzzy_plazm.sql
Normal file
2
packages/db/migrations/0020_fuzzy_plazm.sql
Normal file
@ -0,0 +1,2 @@
|
||||
ALTER TABLE `questions` ADD `msg_type` text;--> statement-breakpoint
|
||||
ALTER TABLE `questions` ADD `default_option` text;
|
||||
4372
packages/db/migrations/meta/0020_snapshot.json
Normal file
4372
packages/db/migrations/meta/0020_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@ -141,6 +141,13 @@
|
||||
"when": 1794806148240,
|
||||
"tag": "0019_stormy_vin_gonzales",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 20,
|
||||
"version": "6",
|
||||
"when": 1794812739508,
|
||||
"tag": "0020_fuzzy_plazm",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -377,6 +377,11 @@ export const questions = sqliteTable("questions", {
|
||||
kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
|
||||
text: text("text").notNull(),
|
||||
options: text("options", { mode: "json" }).$type<string[]>(),
|
||||
// PEP-149: what the message is for the person — decides where it shows up (core/questions.ts).
|
||||
// null: a message of the factory itself (failures, limits, releases) and rows before PEP-149.
|
||||
msgType: text("msg_type", { enum: ["question", "done", "progress", "blocker"] }),
|
||||
// PEP-149: the option the agent goes on with while nobody answered (one of `options`).
|
||||
defaultOption: text("default_option"),
|
||||
answer: text("answer"),
|
||||
// "system": closed by Peppa itself (session stopped/resumed), not by a person.
|
||||
answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }),
|
||||
|
||||
@ -4,6 +4,9 @@
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import {
|
||||
askPm,
|
||||
alertAdmins,
|
||||
checkChoices,
|
||||
reportBlocker,
|
||||
createTask,
|
||||
giteaForBot,
|
||||
getIncident,
|
||||
@ -40,6 +43,7 @@ import {
|
||||
import type { Db } from "@peppa/db";
|
||||
import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner";
|
||||
import { z } from "zod";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { formatIncident, formatTask } from "./format.ts";
|
||||
|
||||
export interface AgentServerOptions {
|
||||
@ -216,24 +220,31 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
},
|
||||
);
|
||||
|
||||
// PEP-149: four kinds of messages to the owner — question (here), done (Peppa sends it itself
|
||||
// after green checks), progress (report_progress), blocker (report_blocker).
|
||||
const optionsArg = z.array(z.string()).optional().describe("2–4 possible answers, shown to the owner as buttons");
|
||||
const defaultArg = z.string().optional().describe("Your recommendation — exactly one of `options`; you go on with it while the owner has not answered");
|
||||
|
||||
tool(
|
||||
"ask_pm",
|
||||
"Ask the PM a PRODUCT question only — what users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. Put your recommended answer FIRST in options. Don't wait: keep working with your recommendation in this turn; the PM's answer arrives later as a message, and you adjust if it differs.",
|
||||
"Ask the owner a PRODUCT question — the ONLY kind of message that reaches their «Ждут вашего ответа» and Telegram. What users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. REQUIRED: `options` (2–4 answers as buttons) and `default` (your recommendation, one of the options) — without them the call is refused. Don't wait: keep working with your default in this turn; the owner's answer arrives later as a message, and you adjust if it differs.",
|
||||
{
|
||||
task: taskArg,
|
||||
question: z.string().min(5).describe("One product question in plain words, 1–2 sentences of context, no jargon"),
|
||||
options: z.array(z.string()).max(6).optional().describe("Answers shown as buttons; your recommendation first"),
|
||||
options: optionsArg,
|
||||
default: defaultArg,
|
||||
},
|
||||
async ({ task, question, options }) => {
|
||||
async ({ task, question, options, default: def }) => {
|
||||
const ref = await resolve(task);
|
||||
const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId });
|
||||
return `Question #${q.id} sent to the PM. Don't wait for the answer: continue with your recommended option now (note it in design.md); if the PM answers differently, the answer arrives as a message and you adjust.`;
|
||||
const c = checkChoices(options, def);
|
||||
const q = await askPm(db, ref, { kind: "question", msgType: "question", text: question, options: c.options, defaultOption: c.defaultOption, sessionId });
|
||||
return `Question #${q.id} sent to the owner. Don't wait for the answer: continue with «${c.defaultOption}» now (note it in design.md); if the owner answers differently, the answer arrives as a message and you adjust.`;
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"report_progress",
|
||||
"Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
|
||||
"Log a short progress note on a story. It is a `progress` message: it goes to the story thread in «События агентов» and never wakes the owner (not in «Ждут вашего ответа», not in Telegram). Don't use it to ask for anything.",
|
||||
{ task: taskArg, text: z.string().min(3) },
|
||||
async ({ task, text }) => {
|
||||
const ref = await resolve(task);
|
||||
@ -242,6 +253,31 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"report_blocker",
|
||||
"Say that you cannot go on with the story: what stops you and what you already tried. Use it only after trying another approach or a mock. A PRODUCT blocker (only the owner can decide or give something: `product: true`) goes to the owner as a question — `options` (2–4) and `default` are required. Any other blocker (access, a broken service, CI, git, a limit) is recorded in the story thread and does NOT go to the owner: Peppa's administrators see it. After the call end your turn — Peppa wakes you when there is something to do.",
|
||||
{
|
||||
task: taskArg,
|
||||
what: z.string().min(5).describe("What stops you, in plain words"),
|
||||
tried: z.string().min(3).describe("What you already tried"),
|
||||
product: z.boolean().optional().describe("true: only the owner can unblock it (a product decision, an account or a key only they have)"),
|
||||
options: optionsArg,
|
||||
default: defaultArg,
|
||||
},
|
||||
async ({ task, what, tried, product, options, default: def }) => {
|
||||
const ref = await resolve(task);
|
||||
if (product) {
|
||||
const c = checkChoices(options, def);
|
||||
const q = await askPm(db, ref, { kind: "question", msgType: "question", text: what, options: c.options, defaultOption: c.defaultOption, sessionId });
|
||||
return `Blocker sent to the owner as question #${q.id}. End your turn — the answer arrives as a message.`;
|
||||
}
|
||||
const e = await reportBlocker(db, ref, { what, tried }, sessionId);
|
||||
// Not the owner's business: the administrators of the factory hear about it.
|
||||
await alertAdmins(db, `blocker:${e.id}`, `⛔ ${ref.key}: ${m("Агент не может продолжить: {what}", { what })}\n${m("Что уже пробовал: {tried}", { tried })}`, () => {}).catch(() => 0);
|
||||
return `Blocker recorded on ${ref.key} (the owner is not asked about it). End your turn now; Peppa wakes you when there is something to do.`;
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"list_incidents",
|
||||
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
|
||||
|
||||
@ -46,6 +46,7 @@ import {
|
||||
setTaskAgentSettings,
|
||||
type AgentSettings,
|
||||
type AgentSettingsPatch,
|
||||
needsPerson,
|
||||
} from "@peppa/core";
|
||||
import { questions, projects, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, loadEnv } from "@peppa/shared";
|
||||
@ -511,11 +512,13 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
|
||||
.leftJoin(tasks, eq(questions.taskId, tasks.id))
|
||||
.where(and(inArray(projects.id, ids), isNull(questions.answeredAt)))
|
||||
.orderBy(asc(questions.id));
|
||||
if (!rows.length) return "Inbox is empty — agents need nothing from you.";
|
||||
return rows
|
||||
// PEP-149: only questions and stories waiting for «accept»; factory messages are not the inbox.
|
||||
const waiting = rows.filter(({ q, status }) => needsPerson(q, status));
|
||||
if (!waiting.length) return "Inbox is empty — agents need nothing from you.";
|
||||
return waiting
|
||||
.map(({ q, key, number, status }) => {
|
||||
const kind = q.kind === "attention" && status === "review" ? "ready for review (answer 'accept' or a comment)" : q.kind;
|
||||
return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}`;
|
||||
return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}${q.defaultOption ? `\n default (the agent goes on with it meanwhile): ${q.defaultOption}` : ""}`;
|
||||
})
|
||||
.join("\n");
|
||||
});
|
||||
|
||||
@ -4,6 +4,9 @@
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import {
|
||||
askPm,
|
||||
getSetting,
|
||||
setSetting,
|
||||
pendingReview,
|
||||
giteaForBot,
|
||||
listSessions,
|
||||
listTasks,
|
||||
@ -41,6 +44,31 @@ async function activeSessionId(db: Db, taskId: number): Promise<number | null> {
|
||||
return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null;
|
||||
}
|
||||
|
||||
const wokeKey = (taskId: number) => `ci.woke:${taskId}`;
|
||||
|
||||
/**
|
||||
* PEP-149: an agent that ended its turn waiting for the checks is woken by Peppa, not by the
|
||||
* person: every check of the PR head passed and the story is still in work → one message per
|
||||
* commit. Returns true when the agent was told.
|
||||
*/
|
||||
export async function wakeOnGreen(db: Db, ref: TaskRef, r: Pick<CheckReport, "sha" | "branch" | "prNumber">, gitea: GiteaClient = giteaForBot()): Promise<boolean> {
|
||||
if (!["proposing", "in_progress"].includes(ref.task.status)) return false;
|
||||
const [s] = await listSessions(db, { active: true, taskId: ref.task.id });
|
||||
if (!s || (s.status !== "idle" && s.status !== "waiting_input")) return false;
|
||||
if ((await getSetting<string>(db, wokeKey(ref.task.id))) === r.sha) return false;
|
||||
if (await pendingReview(db, ref.task.id)) return false;
|
||||
const { giteaOwner: o, giteaRepo: repo } = ref.project;
|
||||
const n = taskPrNumber(ref.project, ref.task.prUrl) ?? r.prNumber ?? (r.branch ? (await gitea.openPullForBranch(o, repo, r.branch))?.number : null);
|
||||
if (!n) return false;
|
||||
const gate = await prGate({ ...ref, task: { ...ref.task, prUrl: `/${o}/${repo}/pulls/${n}` } }, gitea);
|
||||
// Only the commit the PR stands on now; a branch behind the base is updated by Peppa itself.
|
||||
if (!(gate.ok || gate.behind) || !gate.summary || gate.pull?.head.sha !== r.sha) return false;
|
||||
await setSetting(db, wokeKey(ref.task.id), r.sha);
|
||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s.id, type: "checks_passed_wake", payload: { sha: r.sha, pr: n } });
|
||||
await sendToSession(db, s.id, `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}). Если работа закончена — update_task(status: review${ref.task.prUrl ? "" : ", pr_url"}); если нет — продолжай.`);
|
||||
return true;
|
||||
}
|
||||
|
||||
export interface CheckOutcome {
|
||||
task: string | null;
|
||||
/** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */
|
||||
@ -56,6 +84,7 @@ export async function recordCheck(db: Db, project: Project, r: CheckReport): Pro
|
||||
if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" };
|
||||
|
||||
if (r.state === "success") {
|
||||
await wakeOnGreen(db, ref, r).catch(() => {});
|
||||
const [red] = await db
|
||||
.select({ id: checkRuns.id })
|
||||
.from(checkRuns)
|
||||
|
||||
@ -31,6 +31,9 @@ import {
|
||||
demoNote,
|
||||
reviewRejections,
|
||||
getSession,
|
||||
getProject,
|
||||
needsPerson,
|
||||
reportProgress,
|
||||
logSessionEvent,
|
||||
peppaInput,
|
||||
pendingSessionQuestions,
|
||||
@ -189,13 +192,13 @@ async function askQuestion(db: Db, s: SessionView, input: HookInput) {
|
||||
}
|
||||
|
||||
const NUDGE = (key: string) =>
|
||||
`Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда стори готова — PR и update_task(status: review).`;
|
||||
`Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Когда стори готова — PR и update_task(status: review). Ждёшь проверок, ревьюера или мержа — просто закончи ход: Пеппа разбудит тебя сама, PM об этом писать не нужно. Не можешь продолжать — report_blocker (что мешает, что пробовал) и закончи ход.`;
|
||||
|
||||
/**
|
||||
* The agent finished a turn. Pending question → PM already has it. Task in review →
|
||||
* "ready for review" (accept / comment). Task still in work → ask the agent to keep going
|
||||
* (Claude only, via the Stop hook's block decision), at most MAX_AUTO_NUDGES in a row.
|
||||
* Otherwise the PM gets "the session is waiting for you".
|
||||
* Otherwise (PEP-149) the last reply becomes a `progress` record — the person is not woken.
|
||||
* Returns the Stop-hook output to print, if any.
|
||||
*/
|
||||
async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise<unknown> {
|
||||
@ -214,7 +217,8 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
|
||||
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
|
||||
return null;
|
||||
}
|
||||
if ((await pendingSessionQuestions(db, s.id)).length > 0) {
|
||||
// PEP-149: only what a person must answer holds the agent; a factory message does not.
|
||||
if ((await pendingSessionQuestions(db, s.id)).some((q) => needsPerson(q, s.taskStatus))) {
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||||
return null;
|
||||
}
|
||||
@ -267,9 +271,11 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
|
||||
await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 });
|
||||
return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") };
|
||||
}
|
||||
// PEP-151: the agent retells the same state in new words — one message, not one per turn.
|
||||
await raiseSessionQuestion(db, s, "attention", clip(text ?? m("Агент закончил ход и ждёт вашего ответа.")), undefined, false, { topic: "turn" });
|
||||
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
|
||||
// PEP-149: the end of a turn is progress, not a question — a record in the story thread
|
||||
// («События агентов»); nobody is woken. Peppa wakes the agent when there is something to do
|
||||
// (checks passed or failed, the reviewer, a rebase, a comment of the person).
|
||||
if (text && task) await reportProgress(db, { project: await getProject(db, s.projectKey), task, key: s.taskKey ?? "" }, clip(text), s.id);
|
||||
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@ -285,7 +285,9 @@ export async function idleStopTick(db: Db, o: { now: Date; cfg: WatchdogSettings
|
||||
if (o.cfg.idleStopHours <= 0) return 0;
|
||||
let stopped = 0;
|
||||
for (const s of await listSessions(db, { active: true })) {
|
||||
if (s.status !== "waiting_input" || !s.taskId || !s.lastActivityAt) continue;
|
||||
// PEP-149: an agent that ended its turn without a question is `idle` while its story is in work.
|
||||
const turnOver = s.status === "waiting_input" || (s.status === "idle" && ["proposing", "in_progress"].includes(s.taskStatus ?? ""));
|
||||
if (!turnOver || !s.taskId || !s.lastActivityAt) continue;
|
||||
const idleMs = o.now.getTime() - s.lastActivityAt.getTime();
|
||||
if (idleMs < o.cfg.idleStopHours * 3600_000) continue;
|
||||
if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) continue;
|
||||
|
||||
@ -94,7 +94,6 @@ export const bot: Dict = {
|
||||
"✅ Принять": "✅ Accept",
|
||||
"Есть замечания — ответь на это сообщение, агент доработает.": "Have remarks? Reply to this message and the agent will rework it.",
|
||||
"🔁 Перезапустить": "🔁 Restart",
|
||||
"▶️ Продолжай": "▶️ Continue",
|
||||
"Или ответь на это сообщение — текст уйдёт в сессию.": "Or reply to this message — the text goes into the session.",
|
||||
"в Telegram": "in Telegram",
|
||||
"в вебе": "on the web",
|
||||
|
||||
@ -287,4 +287,5 @@ export const help: Dict = {
|
||||
" — {n} вопроса ниже.": " — {n} questions below.",
|
||||
" — {n} вопросов ниже.": " — {n} questions below.",
|
||||
"Тихо… Агентам от тебя ничего не нужно, мопс спит.": "All quiet… The agents don't need anything from you, the pug is asleep.",
|
||||
"<b>Сообщения агента</b> — четырёх типов. <b>Вопрос</b> — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. <b>Готово</b> — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. <b>Ход работы</b> — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. <b>Блокер</b> — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY.": "<b>Agent messages</b> come in four types. <b>Question</b> — your product decision is needed: always with answer buttons and a default option; only it lands in “Agent questions” on Home and comes to Telegram as a question. <b>Done</b> — the task can be accepted: it comes only after the checks have passed, with a link to the result. <b>Progress</b> — what the agent did; it stays in “Agent events” in the project chat and wakes nobody. <b>Blocker</b> — the agent cannot go on: if it is about the product, it asks you with answer options; everything else goes to the factory administrators. The “Continue” button is gone: Peppa FACTORY itself wakes an agent that waits for checks.",
|
||||
};
|
||||
|
||||
@ -127,7 +127,6 @@ export const project: Dict = {
|
||||
Разрешить: "Allow",
|
||||
Всегда: "Always",
|
||||
Запретить: "Deny",
|
||||
Продолжай: "Continue",
|
||||
"Замечание — вернёт на доработку": "Remark — sends it back for rework",
|
||||
"Свой ответ": "Your answer",
|
||||
Ответ: "Answer",
|
||||
|
||||
@ -427,4 +427,9 @@ export const story: Dict = {
|
||||
"ждёт сброса лимита": "waiting for the limit reset",
|
||||
закончил: "finished",
|
||||
"остановился с ошибкой": "stopped with an error",
|
||||
"Ждут «Принять»": "Waiting for “Accept”",
|
||||
"Если не ответите, агент продолжит по варианту «{option}».": "If you don't answer, the agent goes on with “{option}”.",
|
||||
"Агент не может продолжить: {what}": "The agent cannot go on: {what}",
|
||||
"Что уже пробовал: {tried}": "What it already tried: {tried}",
|
||||
"Кнопка устарела — ответьте на сообщение текстом.": "This button no longer works — reply to the message with text.",
|
||||
};
|
||||
|
||||
@ -93,7 +93,6 @@ export const bot: Dict = {
|
||||
"✅ Принять": "✅ Қабылдау",
|
||||
"Есть замечания — ответь на это сообщение, агент доработает.": "Ескертулер болса — осы хабарламаға жауап беріңіз, агент жетілдіреді.",
|
||||
"🔁 Перезапустить": "🔁 Қайта іске қосу",
|
||||
"▶️ Продолжай": "▶️ Жалғастыр",
|
||||
"Или ответь на это сообщение — текст уйдёт в сессию.": "Немесе осы хабарламаға жауап беріңіз — мәтін сессияға кетеді.",
|
||||
"в Telegram": "Telegram-да",
|
||||
"в вебе": "вебте",
|
||||
|
||||
@ -235,4 +235,5 @@ export const help: Dict = {
|
||||
" — {n} вопроса ниже.": " — төменде {n} сұрақ.",
|
||||
" — {n} вопросов ниже.": " — төменде {n} сұрақ.",
|
||||
"Тихо… Агентам от тебя ничего не нужно, мопс спит.": "Тыныш… Агенттерге сізден ештеңе керек емес, мопс ұйықтап жатыр.",
|
||||
"<b>Сообщения агента</b> — четырёх типов. <b>Вопрос</b> — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. <b>Готово</b> — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. <b>Ход работы</b> — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. <b>Блокер</b> — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY.": "<b>Агент хабарламалары</b> төрт түрлі. <b>Сұрақ</b> — өнім туралы сіздің шешіміңіз керек: әрқашан жауап нұсқалары батырмалармен және әдепкі нұсқамен; тек осы түрі Басты беттегі «Агенттердің сұрақтары» бөліміне түседі және Telegram-ға сұрақ ретінде келеді. <b>Дайын</b> — тапсырманы қабылдауға болады: тек тексерулер өткеннен кейін, нәтижеге сілтемемен келеді. <b>Жұмыс барысы</b> — агент не істегені; жоба чатындағы «Агенттер оқиғаларында» тұрады және ешкімді мазаламайды. <b>Кедергі</b> — агент жалғастыра алмайды: мәселе өнімде болса, ол сізден жауап нұсқаларымен сұрайды, қалғаны фабрика әкімшілеріне кетеді. «Жалғастыр» батырмасы енді жоқ: тексерулерді күтіп тұрған агентті Peppa FACTORY өзі оятады.",
|
||||
};
|
||||
|
||||
@ -98,7 +98,6 @@ export const project: Dict = {
|
||||
"Разрешить": "Рұқсат беру",
|
||||
"Всегда": "Әрқашан",
|
||||
"Запретить": "Тыйым салу",
|
||||
"Продолжай": "Жалғастырыңыз",
|
||||
"Замечание — вернёт на доработку": "Ескерту — пысықтауға қайтарады",
|
||||
"Свой ответ": "Өз жауабыңыз",
|
||||
"Ответ": "Жауап",
|
||||
|
||||
@ -392,4 +392,9 @@ export const story: Dict = {
|
||||
"ждёт сброса лимита": "лимит тасталуын күтуде",
|
||||
"закончил": "аяқтады",
|
||||
"остановился с ошибкой": "қатемен тоқтады",
|
||||
"Ждут «Принять»": "«Қабылдау» күтуде",
|
||||
"Если не ответите, агент продолжит по варианту «{option}».": "Жауап бермесеңіз, агент «{option}» нұсқасымен жалғастырады.",
|
||||
"Агент не может продолжить: {what}": "Агент жалғастыра алмайды: {what}",
|
||||
"Что уже пробовал: {tried}": "Не істеп көрді: {tried}",
|
||||
"Кнопка устарела — ответьте на сообщение текстом.": "Батырма ескірді — хабарламаға мәтінмен жауап беріңіз.",
|
||||
};
|
||||
|
||||
316
packages/testkit/test/agent-messages.test.ts
Normal file
316
packages/testkit/test/agent-messages.test.ts
Normal file
@ -0,0 +1,316 @@
|
||||
// PEP-149, spec agent-messages: four kinds of agent messages — question, done, progress, blocker —
|
||||
// and where each of them goes. mock-claude runners, mock Gitea.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { chatMessages, events, questions } from "@peppa/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
import { MockGitea } from "../src/mock-gitea.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
process.env.PEPPA_WEB_URL = "http://peppa.test";
|
||||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||||
const { renderQuestion, choiceToAnswer } = await import("@peppa/bot/render");
|
||||
|
||||
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-msg-")), "gitea"));
|
||||
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
|
||||
const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
|
||||
|
||||
before(async () => {
|
||||
await gitea.start();
|
||||
process.env.GITEA_URL = gitea.url;
|
||||
process.env.GITEA_TOKEN = BOT.token;
|
||||
gitea.addUser(BOT);
|
||||
});
|
||||
after(async () => {
|
||||
await gitea.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
type Turns = Parameters<typeof project>[0]["turns"];
|
||||
|
||||
/** A story with an open PR (task/<KEY>-1) in mock Gitea; checks are set by the test. */
|
||||
async function prTask(turns: Turns) {
|
||||
const tp = await project({ turns });
|
||||
const proj = await core.getProject(db, tp.key);
|
||||
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS });
|
||||
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
|
||||
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
|
||||
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
|
||||
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" });
|
||||
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
|
||||
const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
|
||||
const set = (check: string, state: string) => gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${check}`, state);
|
||||
const ref = () => core.resolveTask(db, tp.taskKey);
|
||||
return { tp, proj, sha, prUrl, set, ref };
|
||||
}
|
||||
|
||||
async function agent(projectKey: string, sessionId?: number) {
|
||||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||||
await createAgentServer(db, { defaultKey: projectKey, sessionId }).connect(a);
|
||||
const client = new Client({ name: "mock-agent", version: "0" });
|
||||
await client.connect(b);
|
||||
return async (name: string, args: Record<string, unknown> = {}) => {
|
||||
const r = await client.callTool({ name, arguments: args });
|
||||
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
|
||||
};
|
||||
}
|
||||
|
||||
const projectQuestions = (projectId: number) => db.select().from(questions).where(eq(questions.projectId, projectId));
|
||||
const taskEvents = (taskId: number, type: string) => db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, type)));
|
||||
|
||||
describe("Конец хода — это ход работы, а не вопрос", () => {
|
||||
test("Агент закончил ход, статус задачи тот же", async () => {
|
||||
const tp = await project({ turns: [[{ say: "Начал." }], [{ say: "Продолжаю." }], [{ say: "Жду проверок" }]] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
|
||||
const sid = await tp.start();
|
||||
// Two nudges of the Stop hook, then the turn really ends.
|
||||
await tp.waitStatus(sid, "idle");
|
||||
const task = await tp.task();
|
||||
assert.equal(task.status, "in_progress");
|
||||
|
||||
// Nothing for the person: no message at all (the bot sends to Telegram only what is in `questions`).
|
||||
assert.deepEqual(await projectQuestions(p.id), [], "no question, nothing in «Ждут вашего ответа» or Telegram");
|
||||
|
||||
// «События агентов»: a record in the story thread.
|
||||
const progress = await taskEvents(task.id, "progress");
|
||||
assert.equal(progress.length, 1);
|
||||
assert.equal((progress[0]!.payload as { text: string }).text, "Жду проверок");
|
||||
await core.syncChats(db);
|
||||
const chat = await core.ensureProjectChat(db, p.id);
|
||||
const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`)));
|
||||
const record = thread.find((m) => m.text.includes("Жду проверок"));
|
||||
assert.ok(record, "the reply is in the story thread");
|
||||
assert.equal(record.kind, "event");
|
||||
assert.equal(record.important, false, "not in the master feed");
|
||||
assert.equal(record.questionId, null);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("У агента есть открытый вопрос", async () => {
|
||||
const tp = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], default: "Синий" } }, { say: "Спросил." }]] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
|
||||
const sid = await tp.start();
|
||||
await tp.waitStatus(sid, "waiting_input");
|
||||
const qs = await projectQuestions(p.id);
|
||||
assert.equal(qs.length, 1);
|
||||
assert.equal(core.questionType(qs[0]!, "in_progress"), "question");
|
||||
assert.deepEqual(await taskEvents((await tp.task()).id, "progress"), [], "no progress record on top of the question");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Тип сообщения определяет маршрут", () => {
|
||||
const base = { taskId: 1, sessionId: 1, msgType: null, options: null } as const;
|
||||
|
||||
test("Вопрос попадает в «Ждут вашего ответа»", () => {
|
||||
assert.equal(core.questionType({ ...base, kind: "question", options: ["Синий", "Зелёный"] }, "in_progress"), "question");
|
||||
assert.equal(core.questionType({ ...base, kind: "permission", options: ["allow", "always", "deny"] }), "question");
|
||||
assert.equal(core.questionType({ ...base, kind: "attention", options: ["🚀 Выкатить"] }), "question", "a factory message with answers to choose from");
|
||||
assert.equal(core.needsPerson({ ...base, kind: "question" }, "in_progress"), true);
|
||||
assert.equal(core.questionEvent({ ...base, kind: "question" }, { taskStatus: "in_progress" }), "questions");
|
||||
});
|
||||
|
||||
test("Сообщение о сбое не попадает в «Ждут вашего ответа»", () => {
|
||||
const failure = { ...base, kind: "attention" as const };
|
||||
assert.equal(core.questionType(failure, "in_progress"), null);
|
||||
assert.equal(core.needsPerson(failure, "in_progress"), false);
|
||||
assert.equal(core.questionEvent(failure, { taskStatus: "in_progress", sessionStatus: "failed" }), "failures");
|
||||
// «Готово» — отдельным блоком: ждёт «Принять», но это не вопрос.
|
||||
assert.equal(core.questionType({ ...failure, msgType: "done" }, "review"), "done");
|
||||
assert.equal(core.questionType(failure, "review"), "done", "rows before PEP-149");
|
||||
assert.equal(core.needsPerson(failure, "review"), true);
|
||||
assert.equal(core.questionEvent(failure, { taskStatus: "review" }), "review");
|
||||
});
|
||||
|
||||
test("Сообщения «продукт обновлён» и «бэклог пуст» — не вопросы", async () => {
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
for (const text of ["🚀 Shop: ваш продукт обновлён и открыт для всех", "📭 Shop: все задачи сделаны, бэклог пуст — агентам нечего делать."]) {
|
||||
const q = await core.askPmProject(db, p, { kind: "attention", text });
|
||||
assert.equal(q.msgType, null);
|
||||
assert.equal(core.needsPerson(q), false, "not in «Ждут вашего ответа», not counted, no push");
|
||||
// Telegram: a plain notice — no buttons to press.
|
||||
assert.deepEqual(renderQuestion(q, { taskKey: null, taskTitle: null, session: null, webUrl: "http://peppa.test" }).buttons, []);
|
||||
}
|
||||
// The offer to release has an answer to choose: it is a question.
|
||||
const offer = await core.askPmProject(db, p, { kind: "question", text: "Показать всем?", options: ["🚀 Показать всем"] });
|
||||
assert.equal(core.needsPerson(offer), true);
|
||||
});
|
||||
|
||||
test("Счётчик открытых вопросов чата считает только вопросы", async () => {
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
const ref = await core.resolveTask(db, tp.taskKey);
|
||||
await core.askPm(db, ref, { kind: "attention", text: "агент остановился с ошибкой" });
|
||||
await core.askPm(db, ref, { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], defaultOption: "Синий" });
|
||||
const u = await core.upsertUserFromGitea(db, { id: 9149, login: "mock-pm-149" }, { access_token: "a" });
|
||||
await core.setProjectOwner(db, p.id, u.id);
|
||||
const chat = (await core.listChats(db, u)).find((c) => c.projectId === p.id)!;
|
||||
assert.equal(chat.open, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("«Готово» шлёт платформа после проверок", () => {
|
||||
test("Проверки ещё идут", async () => {
|
||||
const t = await prTask([]);
|
||||
t.set("typecheck", "success");
|
||||
t.set("test", "pending");
|
||||
await core.updateTask(db, await t.ref(), { prUrl: t.prUrl });
|
||||
const sent = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью");
|
||||
assert.equal(sent, null, "held");
|
||||
assert.deepEqual(await projectQuestions(t.proj.id), [], "the owner got nothing");
|
||||
assert.ok(await core.getReviewHold(db, (await t.ref()).task.id));
|
||||
|
||||
// Red checks: still nothing.
|
||||
t.set("test", "failure");
|
||||
assert.equal(await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"), null);
|
||||
assert.deepEqual(await projectQuestions(t.proj.id), []);
|
||||
});
|
||||
|
||||
test("Проверки прошли", async () => {
|
||||
const t = await prTask([]);
|
||||
t.set("typecheck", "success");
|
||||
t.set("test", "success");
|
||||
await core.updateTask(db, await t.ref(), { status: "review", prUrl: t.prUrl });
|
||||
const sent = await core.sendReviewCard(db, await t.ref(), `✅ Задача ${t.tp.taskKey} готова к ревью · Результат: ${t.prUrl}`);
|
||||
assert.ok(sent);
|
||||
assert.equal(sent.msgType, "done");
|
||||
assert.ok(sent.text.includes(t.prUrl), "the link to the result");
|
||||
assert.equal(core.questionType(sent, "review"), "done");
|
||||
|
||||
// A card without any link gets the link to the task page.
|
||||
const bare = await core.sendReviewCard(db, await t.ref(), "✅ Готово");
|
||||
assert.match(bare!.text, new RegExp(`http://peppa\\.test/t/${t.tp.taskKey}`));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Платформа будит агента, когда проверки прошли", () => {
|
||||
test("Проверки прошли, агент ждал; повторный отчёт о том же коммите", async () => {
|
||||
const t = await prTask([[{ say: "PR открыт." }], [{ say: "Жду." }], [{ say: "Жду проверок" }], [{ say: "Перевожу." }], [{ say: "Ок." }], [{ say: "Ок." }]]);
|
||||
await core.updateTask(db, await t.ref(), { status: "in_progress" });
|
||||
t.set("typecheck", "pending");
|
||||
t.set("test", "pending");
|
||||
const sid = await t.tp.start();
|
||||
await t.tp.waitStatus(sid, "idle");
|
||||
const woke = () => t.tp.log().filter((e) => e.ev === "prompt" && String(e.prompt).includes("Проверки PR"));
|
||||
|
||||
// One check of two passed: not yet.
|
||||
t.set("typecheck", "success");
|
||||
await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "typecheck", state: "success" });
|
||||
assert.equal(woke().length, 0);
|
||||
|
||||
t.set("test", "success");
|
||||
await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "test", state: "success" });
|
||||
await waitFor("the agent is told the checks passed", async () => woke().length || undefined);
|
||||
assert.match(String(woke()[0]!.prompt), /прошли/);
|
||||
assert.deepEqual(await projectQuestions(t.proj.id), [], "the person is not involved");
|
||||
|
||||
await t.tp.waitStatus(sid, "idle");
|
||||
assert.equal(await runner.wakeOnGreen(db, await t.ref(), { sha: t.sha, branch: `task/${t.tp.taskKey}` }), false, "once per commit");
|
||||
assert.equal(woke().length, 1);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Вопрос агента — с вариантами и вариантом по умолчанию", () => {
|
||||
test("Вопрос с вариантами принят", async () => {
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
const call = await agent(tp.key);
|
||||
const r = await call("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", options: ["Нет", "Да"], default: "Да" });
|
||||
assert.equal(r.isError, false, r.text);
|
||||
const [q] = await projectQuestions(p.id);
|
||||
assert.equal(q!.msgType, "question");
|
||||
assert.equal(q!.defaultOption, "Да");
|
||||
assert.deepEqual(q!.options, ["Да", "Нет"], "the default goes first");
|
||||
});
|
||||
|
||||
for (const [name, args, why] of [
|
||||
["без вариантов", {}, /2–4 answer options/],
|
||||
["один вариант", { options: ["Да"], default: "Да" }, /2–4 answer options/],
|
||||
["пять вариантов", { options: ["1", "2", "3", "4", "5"], default: "1" }, /2–4 answer options/],
|
||||
["без варианта по умолчанию", { options: ["Да", "Нет"] }, /`default`/],
|
||||
["вариант по умолчанию не из списка", { options: ["Да", "Нет"], default: "Может быть" }, /one of `options`/],
|
||||
] as const) {
|
||||
test(`Вопрос без вариантов отклонён: ${name}`, async () => {
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
const r = await (await agent(tp.key))("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", ...args });
|
||||
assert.equal(r.isError, true);
|
||||
assert.match(r.text, why);
|
||||
assert.deepEqual(await projectQuestions(p.id), [], "no question");
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("Блокер идёт по своему маршруту", () => {
|
||||
test("Непродуктовый блокер", async () => {
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
const r = await (await agent(tp.key))("report_blocker", { task: tp.taskKey, what: "нет доступа к серверу сборки", tried: "повторил три раза" });
|
||||
assert.equal(r.isError, false, r.text);
|
||||
assert.deepEqual(await projectQuestions(p.id), [], "the owner is not asked");
|
||||
const task = await tp.task();
|
||||
assert.equal((await taskEvents(task.id, "blocker")).length, 1);
|
||||
await core.syncChats(db);
|
||||
const chat = await core.ensureProjectChat(db, p.id);
|
||||
const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`)));
|
||||
const record = thread.find((m) => m.text.includes("нет доступа к серверу сборки"));
|
||||
assert.ok(record);
|
||||
assert.equal(record.important, false);
|
||||
assert.match(record.text, /повторил три раза/);
|
||||
});
|
||||
|
||||
test("Продуктовый блокер без вариантов; с вариантами — вопрос", async () => {
|
||||
const tp = await project({ turns: [] });
|
||||
const p = await core.getProject(db, tp.key);
|
||||
const call = await agent(tp.key);
|
||||
const refused = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true });
|
||||
assert.equal(refused.isError, true);
|
||||
assert.match(refused.text, /2–4 answer options/);
|
||||
assert.deepEqual(await projectQuestions(p.id), []);
|
||||
|
||||
const ok = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true, options: ["Оставить демо", "Дам аккаунт"], default: "Оставить демо" });
|
||||
assert.equal(ok.isError, false, ok.text);
|
||||
const [q] = await projectQuestions(p.id);
|
||||
assert.equal(core.questionType(q!), "question");
|
||||
assert.equal(q!.defaultOption, "Оставить демо");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Нет кнопки «Продолжай»", () => {
|
||||
const q = (over: Record<string, unknown>) => ({ id: 7, projectId: 1, taskId: 1, sessionId: null, kind: "attention", text: "агент остановился с ошибкой", options: null, msgType: null, defaultOption: null, answer: null, answeredVia: null, telegramMessageId: null, awaitingHook: false, reminders: 0, createdAt: new Date(), answeredAt: null, ...over }) as never;
|
||||
const ctx = { taskKey: "PEP-1", taskTitle: "t", taskStatus: "in_progress", session: null, webUrl: "http://peppa.test" };
|
||||
|
||||
test("Сообщение фабрики в Telegram", () => {
|
||||
const r = renderQuestion(q({}), ctx);
|
||||
assert.deepEqual(r.buttons, [], "no buttons at all");
|
||||
assert.doesNotMatch(r.text, /Продолжай/);
|
||||
});
|
||||
|
||||
test("Вопрос — кнопки вариантов и вариант по умолчанию", () => {
|
||||
const r = renderQuestion(q({ kind: "question", text: "Какой цвет?", options: ["Синий", "Зелёный"], msgType: "question", defaultOption: "Синий" }), ctx);
|
||||
assert.deepEqual(r.buttons.flat().map((b) => b.text), ["Синий", "Зелёный"]);
|
||||
assert.match(r.text, /продолжит по варианту «Синий»/);
|
||||
assert.match(r.text, /своим текстом/);
|
||||
});
|
||||
|
||||
test("Старая кнопка «Продолжай»", () => {
|
||||
assert.equal(choiceToAnswer(q({}), "cont"), null, "nothing goes to the agent");
|
||||
});
|
||||
|
||||
test("В вебе и боте кнопки нет", () => {
|
||||
const root = join(import.meta.dirname, "../../..");
|
||||
for (const f of ["apps/web/components/cards.tsx", "apps/bot/src/render.ts"]) {
|
||||
assert.doesNotMatch(readFileSync(join(root, f), "utf8").replace(/\/\/.*|\{\/\*.*?\*\/\}/g, ""), /Продолжай|"cont"/, f);
|
||||
}
|
||||
});
|
||||
});
|
||||
@ -42,17 +42,17 @@ describe("autonomous cycle", () => {
|
||||
assert.equal((await core.getQuestion(db, review.id)).answer, "✅ Принято");
|
||||
});
|
||||
|
||||
test("after two nudges in a row the PM is called; a human answer resets the counter", async () => {
|
||||
test("after two nudges in a row the turn ends as progress — the PM is not called (PEP-149); a human message resets the counter", async () => {
|
||||
const p = await project({
|
||||
turns: [[{ mcp: "update_task", args: { task: "1", status: "in_progress" } }, { say: "шаг 1" }], [{ say: "шаг 2" }], [{ say: "застрял на шаге 3" }], [{ say: "понял" }]],
|
||||
});
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
assert.match(q.text, /застрял на шаге 3/);
|
||||
await p.waitStatus(sid, "idle");
|
||||
assert.equal(await nudges(sid), runner.MAX_AUTO_NUDGES);
|
||||
await runner.answerAndDeliver(db, q.id, "делай вариант Б", "telegram");
|
||||
assert.equal((await p.session(sid)).autoNudges, 0);
|
||||
await p.waitLog("answer delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б"));
|
||||
assert.deepEqual(await p.pending(sid), [], "nobody is asked");
|
||||
await runner.sendToSession(db, sid, "делай вариант Б");
|
||||
await p.waitLog("message delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б"));
|
||||
await waitFor("the counter is reset", async () => (await p.session(sid)).autoNudges === 0);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
@ -71,7 +71,7 @@ describe("autonomous cycle", () => {
|
||||
|
||||
describe("task board", () => {
|
||||
test("moving a card to In progress starts an agent; back to Backlog stops it", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?" } }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?", options: ["Да", "Нет"], default: "Да" } }]] });
|
||||
let ref = await core.resolveTask(db, p.taskKey);
|
||||
assert.equal(runner.columnOf(ref.task.status), "backlog");
|
||||
const { started } = await runner.moveTask(db, ref, "in_progress");
|
||||
|
||||
@ -79,7 +79,7 @@ describe("pairing", () => {
|
||||
|
||||
describe("answering from Telegram", () => {
|
||||
test("question with options: button press reaches the agent, message is closed", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду." }], [{ say: "Ок." }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду." }], [{ say: "Ок." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
const m = await messageFor(q.id);
|
||||
@ -138,7 +138,9 @@ describe("answering from Telegram", () => {
|
||||
test("free-text reply to a 'session is waiting' alert is typed into the session", async () => {
|
||||
const p = await project({ turns: [[{ say: "Сделал черновик. Что дальше?" }], [{ say: "Понял." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
// PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
|
||||
const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Сделал черновик. Что дальше?");
|
||||
const m = await messageFor(q.id);
|
||||
assert.match(m.text, /Что дальше/);
|
||||
tg.userSends(PM, "добавь тесты\nи README", m.message_id);
|
||||
@ -154,7 +156,7 @@ describe("several users", () => {
|
||||
await waitFor("bob paired", async () => (await core.getUser(db, bobUser.id))?.telegramChatId === BOB.chatId);
|
||||
|
||||
// PM's project: Bob has no access.
|
||||
const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"] } }], [{ say: "Ок." }]] });
|
||||
const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
|
||||
const sid = await mine.start();
|
||||
const q = await mine.waitQuestion(sid, "question");
|
||||
const m = await messageFor(q.id);
|
||||
@ -198,7 +200,7 @@ describe("review", () => {
|
||||
|
||||
describe("staleness and reliability", () => {
|
||||
test("answered in the terminal: Telegram message is closed and old buttons do nothing", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
const m = await messageFor(q.id);
|
||||
@ -213,7 +215,9 @@ describe("staleness and reliability", () => {
|
||||
test("an update re-delivered after a restart is not replayed", async () => {
|
||||
const p = await project({ turns: [[{ say: "Жду указаний." }], [{ say: "Ок." }], [{ say: "лишний ход" }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
// PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
|
||||
const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Жду указаний.");
|
||||
const m = await messageFor(q.id);
|
||||
const updateId = tg.userSends(PM, "сделай раз", m.message_id);
|
||||
await p.waitLog("delivered once", isPrompt("сделай раз"));
|
||||
@ -227,7 +231,7 @@ describe("staleness and reliability", () => {
|
||||
test("outbox retries after 429 (retry_after) and 5xx", async () => {
|
||||
tg.failNext("sendMessage", 429, 1);
|
||||
tg.failNext("sendMessage", 500);
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?" } }], [{ say: "Ок." }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
const m = await messageFor(q.id);
|
||||
@ -259,7 +263,7 @@ describe("staleness and reliability", () => {
|
||||
});
|
||||
|
||||
test("tmux killed while waiting: answer is saved, PM told the session is down", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?" } }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?", options: ["Да", "Нет"], default: "Да" } }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
const m = await messageFor(q.id);
|
||||
|
||||
@ -21,7 +21,7 @@ const budgetQuestion = (taskId: number) =>
|
||||
async function spentRunner() {
|
||||
const p = await project({ turns: [[{ usage: { input: 1000, output: 500 } }, { say: "Сделал часть." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
await waitFor("usage recorded", async () => core.usageTotals((await core.getSession(db, sid)).usage).total === 1500);
|
||||
return { p, sid, task: await p.task() };
|
||||
}
|
||||
|
||||
@ -76,7 +76,7 @@ describe("Claude: task lifecycle", () => {
|
||||
describe("Claude: questions to the PM", () => {
|
||||
test("ask_pm question answered from Telegram is typed into the session", async () => {
|
||||
const p = await project({
|
||||
turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]],
|
||||
turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]],
|
||||
});
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
@ -90,7 +90,9 @@ describe("Claude: questions to the PM", () => {
|
||||
test("multi-line answer arrives as one prompt (bracketed paste)", async () => {
|
||||
const p = await project({ turns: [[{ say: "Что дальше?" }], [{ say: "Понял." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
// PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
|
||||
const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Что дальше?");
|
||||
await runner.answerAndDeliver(db, q.id, "строка один\nстрока два", PM);
|
||||
const e = await p.waitLog("pasted prompt", isPrompt("строка один"));
|
||||
assert.equal(e.prompt, "строка один\nстрока два");
|
||||
@ -127,7 +129,7 @@ describe("Claude: questions to the PM", () => {
|
||||
});
|
||||
|
||||
test("typing in the terminal answers whatever the session was waiting for", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?" } }], [{ say: "Ок." }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "question");
|
||||
await runner.sendToSession(db, sid, "назови peppa-api", { person: true });
|
||||
@ -242,7 +244,7 @@ describe("Claude: failures and recovery", () => {
|
||||
test("tmux session killed from outside → failed, PM alerted", async () => {
|
||||
const p = await project({ turns: [[{ say: "Работаю." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitStatus(sid, "waiting_input");
|
||||
await p.waitStatus(sid, "idle");
|
||||
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
|
||||
await tick();
|
||||
assert.equal((await p.session(sid)).status, "failed");
|
||||
@ -256,7 +258,7 @@ describe("Claude: failures and recovery", () => {
|
||||
const cleared = await p.waitLog("cleared", (e) => e.ev === "clear");
|
||||
await waitFor("new conversation id stored", async () => (await p.session(sid)).conversationId === cleared.newConversationId);
|
||||
assert.notEqual(before, cleared.newConversationId);
|
||||
await p.waitStatus(sid, "waiting_input");
|
||||
await p.waitStatus(sid, "idle");
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
@ -280,14 +282,14 @@ describe("Codex", () => {
|
||||
const mcpCall = await p.waitLog("codex reaches peppa MCP", (e) => e.ev === "mcp" && e.tool === "get_task");
|
||||
assert.equal(mcpCall.isError, false);
|
||||
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
assert.match(alert.text, /какой фреймворк/);
|
||||
// PEP-149: the end of a turn is a progress record, not a question to the PM.
|
||||
await p.waitStatus(sid, "idle");
|
||||
assert.deepEqual(await p.pending(sid), []);
|
||||
const s = await p.session(sid);
|
||||
assert.equal(s.provider, "codex");
|
||||
assert.equal(s.status, "waiting_input");
|
||||
assert.equal(s.conversationId, start.conversationId);
|
||||
|
||||
await runner.answerAndDeliver(db, alert.id, "Fastify", PM);
|
||||
await runner.sendToSession(db, sid, "Fastify");
|
||||
await p.waitLog("answer typed in", isPrompt("Fastify"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
@ -307,9 +309,9 @@ describe("Codex", () => {
|
||||
test("crash → resume uses `codex resume <thread>`", async () => {
|
||||
const p = await project({ turns: [[{ say: "Первый ход." }], [{ crash: 2 }]], resumeTurns: [[{ say: "Вернулся." }]] });
|
||||
const sid = await p.start({ provider: "codex" });
|
||||
const alert = await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
const thread = (await p.session(sid)).conversationId;
|
||||
await runner.answerAndDeliver(db, alert.id, "продолжай", PM);
|
||||
await runner.sendToSession(db, sid, "продолжай");
|
||||
await p.waitLog("crashed", (e) => e.ev === "exit");
|
||||
await waitFor("failed", async () => {
|
||||
await tick();
|
||||
|
||||
@ -9,7 +9,7 @@ import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { events } from "@peppa/db";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
|
||||
after(teardown);
|
||||
@ -177,7 +177,7 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", ()
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
|
||||
test("Stop: стори в работе → decision block; после двух — PM", async () => {
|
||||
test("Stop: стори в работе → decision block; после двух — ход работы, PM не зовём", async () => {
|
||||
const p = await project({ turns: [[{ sleep: 60_000 }]] });
|
||||
const sid = await p.start();
|
||||
// The prompt hook resets auto_nudges; let it finish before the Stop hooks are counted.
|
||||
@ -190,8 +190,10 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", ()
|
||||
assert.match(first.reason, new RegExp(p.taskKey));
|
||||
assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block");
|
||||
assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null);
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
assert.equal(q.text, fixture("stop-after-block").last_assistant_message);
|
||||
// PEP-149: the last reply becomes a progress record — the PM is not asked.
|
||||
assert.deepEqual(await p.pending(sid), []);
|
||||
const [progress] = await db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, "progress")));
|
||||
assert.equal((progress!.payload as { text: string }).text, fixture("stop-after-block").last_assistant_message);
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
|
||||
@ -90,9 +90,9 @@ describe("Защита от зацикливания", () => {
|
||||
test("Предел достигнут", async () => {
|
||||
const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
await core.updateSession(db, sid, { limitResumes: runner.MAX_LIMIT_RESUMES_PER_DAY, limitResumesDay: new Date().toLocaleDateString("sv-SE") });
|
||||
await runner.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "дальше", "web");
|
||||
await runner.sendToSession(db, sid, "дальше");
|
||||
await p.waitStatus(sid, "rate_limited");
|
||||
const s = await sess(sid);
|
||||
assert.equal(s.resumeAt, null, "no more auto-resumes today");
|
||||
|
||||
@ -96,10 +96,10 @@ describe("Одно состояние — одно сообщение", () => {
|
||||
assert.equal(inThread.length, 1);
|
||||
assert.equal(inThread[0]!.repeats, 8);
|
||||
assert.ok(inThread[0]!.updatedAt);
|
||||
// Telegram: still one message, with the last text and the «Продолжай» button back.
|
||||
// Telegram: still one message, with the last text; PEP-149: no «Продолжай» button any more.
|
||||
const msg = await waitFor("the Telegram message refreshed", async () => {
|
||||
const [m] = tgAbout(t.project.key);
|
||||
return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null;
|
||||
return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && !m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null;
|
||||
});
|
||||
assert.equal(tgAbout(t.project.key).length, 1);
|
||||
assert.ok(msg.edits >= 1);
|
||||
|
||||
@ -94,7 +94,7 @@ async function mcpAs(user: typeof owner) {
|
||||
|
||||
describe("PM tools over MCP", () => {
|
||||
test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => {
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] });
|
||||
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] });
|
||||
const proj = await core.getProject(db, p.key);
|
||||
await core.setProjectOwner(db, proj.id, owner.id);
|
||||
const { client, call } = await mcpAs(owner);
|
||||
|
||||
@ -4,7 +4,7 @@ import { readFileSync } from "node:fs";
|
||||
import { describe, test } from "node:test";
|
||||
import { HELP_LANGS, PRODUCT_HELP, type ProductHelpText } from "@peppa/core";
|
||||
|
||||
const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
|
||||
const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.messages.title, ...t.messages.items, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
|
||||
|
||||
/** «Нельзя» column of docs/glossary.md. */
|
||||
function forbidden(): string[] {
|
||||
|
||||
@ -166,9 +166,9 @@ describe("Предохранители", () => {
|
||||
const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 3600, credential: "caplimA" } }]] });
|
||||
await poolFor(p.key, [a.id, b.id]);
|
||||
const sid = await p.start();
|
||||
const q = await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
for (let i = 0; i < runner.maxRotationsPerHour(); i++) await core.logSessionEvent(db, await sess(sid), runner.SWITCH_EVENT, { reason: "limit" });
|
||||
await runner.answerAndDeliver(db, q.id, "дальше", "web");
|
||||
await runner.sendToSession(db, sid, "дальше");
|
||||
await p.waitStatus(sid, "rate_limited");
|
||||
assert.equal((await sess(sid)).rotateReason, null);
|
||||
assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/);
|
||||
|
||||
@ -142,7 +142,7 @@ describe("PEP-17: агент в контейнере", () => {
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
const before = runs().length;
|
||||
const sid = await p.start();
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
const s = await core.getSession(db, sid);
|
||||
assert.equal(s.container, null);
|
||||
assert.equal(s.host, null);
|
||||
@ -193,7 +193,7 @@ describe("PEP-17: агент в контейнере", () => {
|
||||
await new Promise((r) => setTimeout(r, 1200)); // longer than one relay wait
|
||||
await runner.answerAndDeliver(db, q.id, "allow", "web");
|
||||
await p.waitLog("permission allowed by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "allow");
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
// Stop hook through the relay with the transcript: tokens counted as for a local agent.
|
||||
assert.equal(core.usageTotals((await core.getSession(db, sid)).usage).total, 1500);
|
||||
assert.ok((await evs(sid, "turn_end")).length >= 1);
|
||||
@ -300,7 +300,7 @@ describe("PEP-40: хосты раннеров", () => {
|
||||
const log = join(remoteWs, ".peppa", "mock-log.jsonl");
|
||||
await waitFor("mcp from the host", async () => existsSync(log) && readFileSync(log, "utf8").includes('"tool":"report_progress","args":{"task":"'));
|
||||
assert.match(readFileSync(log, "utf8"), /"tool":"report_progress".*"isError":false/);
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
|
||||
// PEP-9 over SSH: the frame comes from the host's pane.
|
||||
const frame = await new Promise<string>((resolve, reject) => {
|
||||
|
||||
@ -56,7 +56,7 @@ describe("Расход сессии из statusLine и transcript", () => {
|
||||
const p = await project({ turns: [[{ usage: { input: 1200, output: 300, costUsd: 0.42, context: { used: 50000, size: 200000 }, fiveHour: 42, sevenDay: 18 } }, { say: "Готово." }]] });
|
||||
const sid = await p.start();
|
||||
await p.waitLog("statusline", (e) => e.ev === "statusline");
|
||||
await p.waitQuestion(sid, "attention");
|
||||
await p.waitStatus(sid, "idle");
|
||||
const s = await core.getSession(db, sid);
|
||||
const t = core.usageTotals(s.usage);
|
||||
assert.equal(t.total, 1500);
|
||||
|
||||
@ -56,7 +56,8 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
|
||||
выполнения и коммить маленькими шагами: `PEP-42: <что сделано>`.
|
||||
- `peppa.report_progress` на каждые 2–3 пункта или раз в ~30 минут.
|
||||
- Не заканчивай ход посреди работы: если остановишься без вопроса PM, Пеппа попросит
|
||||
продолжить, а на третий раз позовёт PM.
|
||||
продолжить; на третий раз твоя реплика уйдёт в ход работы, а PM никто не позовёт
|
||||
(см. «Сообщения PM: четыре типа»).
|
||||
- Тесты и линтеры проекта должны проходить до PR.
|
||||
|
||||
### Завершение
|
||||
@ -226,13 +227,32 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
|
||||
платёжный сервис подключить), доступ, который есть только у PM (аккаунт, ключ сервиса).
|
||||
- Нельзя: всё техническое — стек, библиотеки, архитектура, данные, CI и проверки, git,
|
||||
раннеры, разрешения, «как лучше сделать». Это решаешь ты.
|
||||
- `peppa.ask_pm`: один вопрос, 1–2 предложения контекста, твой рекомендуемый вариант —
|
||||
первым в `options`. **Не жди ответа и не заканчивай ход**: продолжай по своему
|
||||
варианту и запиши его в `design.md`. Ответ придёт позже сообщением — если он другой,
|
||||
переделаешь.
|
||||
- `peppa.ask_pm`: один вопрос, 1–2 предложения контекста, **обязательно** `options`
|
||||
(2–4 варианта ответа — PM отвечает одной кнопкой) и `default` (твой рекомендуемый
|
||||
вариант, один из `options`); без них вызов отклоняется. **Не жди ответа и не заканчивай
|
||||
ход**: продолжай по `default` и запиши его в `design.md`. Ответ придёт позже
|
||||
сообщением — если он другой, переделаешь.
|
||||
- Нужен ключ или аккаунт, которого нет, — делай на моке (раздел ниже) и объяви его через
|
||||
`peppa.declare_needs`: владелец получит список «что дать и куда вставить».
|
||||
|
||||
## Сообщения PM: четыре типа
|
||||
|
||||
Всё, что ты сообщаешь PM, — одного из четырёх типов. От типа зависит, увидит ли он это.
|
||||
|
||||
| Тип | Что это | Как отправить | Куда попадает |
|
||||
|---|---|---|---|
|
||||
| **question** | нужно решение PM о продукте | `ask_pm` с `options` (2–4) и `default` | «Ждут вашего ответа», Telegram — единственный тип, который будит PM |
|
||||
| **done** | стори готова, можно принять | сам не шлёшь: `update_task(status: review)`, сообщение отправит Пеппа после зелёных проверок, со ссылкой на результат | «Ждут „Принять“», Telegram |
|
||||
| **progress** | ход работы | `report_progress`; последняя реплика твоего хода тоже становится progress | «События агентов» (тред стори); PM не будит |
|
||||
| **blocker** | не можешь продолжать | `report_blocker` (что мешает, что уже пробовал) | продуктовый (`product: true` + `options` и `default`) — PM как question; остальное — в тред стори и администраторам Пеппы, не PM |
|
||||
|
||||
- Последняя реплика хода — не способ что-то спросить: PM её не получит. Нужен ответ — `ask_pm`.
|
||||
- Ждёшь проверок, ревьюера или мержа — просто закончи ход. Пеппа разбудит тебя сама: красные
|
||||
проверки придут с логом, зелёные — сообщением «проверки прошли», замечания — текстом.
|
||||
Писать PM «жду проверок» не нужно и некуда.
|
||||
- Кнопки «Продолжай» у PM нет: никто не подтолкнёт тебя вручную. Не можешь двигаться —
|
||||
сначала смени подход или сделай мок, потом `report_blocker`.
|
||||
|
||||
## Если MCP `peppa` недоступен
|
||||
|
||||
Работай напрямую через OpenSpec CLI (`openspec list`, `openspec show <change>`,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user