From 956938014306954e425aafa944517f47d314b37b Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 21:21:50 +0500 Subject: [PATCH] =?UTF-8?q?PEP-198:=20=D0=B2=D0=BE=D0=BF=D1=80=D0=BE=D1=81?= =?UTF-8?q?=D1=8B=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=BE=D0=B2=20=D1=87?= =?UTF-8?q?=D0=B5=D1=80=D0=B5=D0=B7=20=D0=90=D0=BD=D0=B0=D0=BB=D0=B8=D1=82?= =?UTF-8?q?=D0=B8=D0=BA=D0=B0,=20=D1=81=D0=B2=D0=BE=D0=B4=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D1=8B=D1=85,=20=D0=B7=D0=B0?= =?UTF-8?q?=D1=81=D1=82=D1=80=D1=8F=D0=B2=D1=88=D0=B8=D0=B5=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=B4=D0=B0=D1=87=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/bot/src/bot.ts | 4 +- apps/bot/src/render.ts | 7 +- .../changes/pep-198-one-analyst/design.md | 2 +- openspec/changes/pep-198-one-analyst/tasks.md | 2 +- packages/core/src/index.ts | 1 + packages/core/src/platform-delay.ts | 5 +- packages/core/src/ready-digest.ts | 59 +++++++++ packages/mcp/src/agent.ts | 16 ++- packages/runner/src/index.ts | 3 + packages/runner/src/platform-delays.ts | 5 + packages/runner/src/question-relay.ts | 124 ++++++++++++++++++ packages/runner/src/ready-digest.ts | 37 ++++++ packages/runner/src/stuck-tasks.ts | 48 +++++++ packages/runner/src/watchdog.ts | 7 +- 14 files changed, 309 insertions(+), 11 deletions(-) create mode 100644 packages/core/src/ready-digest.ts create mode 100644 packages/runner/src/question-relay.ts create mode 100644 packages/runner/src/ready-digest.ts create mode 100644 packages/runner/src/stuck-tasks.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 8252a97f..31990849 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -2,7 +2,7 @@ // alerts) to the paired chat and turns button presses / replies into answers delivered // back into the agent session. Telegram is an adapter over the DB, not a remote shell: // it can only answer a specific pending question or resume/stop the session it is about. -import { duringPause, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core"; +import { duringPause, heldForDigest, isProjectPaused, LOCALIZED_PARAM, localizeMessage, messageDetails, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core"; import { asIs, localizeRoleMessage, m as tr, stripAsIs } from "@peppa/shared/i18n"; import { accountUsageForUser, @@ -343,6 +343,8 @@ export function createBot(o: BotOptions) { // 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; const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`; + // PEP-198: a finished story nobody waits for comes in the evening digest, not one by one. + if (await heldForDigest(db, q, ctx.taskStatus ?? null)) continue; for (const u of audience) { // PEP-154: the terminal command is for the «Инженер» view only. const r = renderQuestion(q, { ...ctx, engineer: (await getUiMode(db, u.id)) === "engineer" }); diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 19fa61fa..fec9bd77 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -11,9 +11,12 @@ const KIND: Record = { approval: tr("📝 Нужно одобрение плана"), question: tr("❓ Вопрос"), permission: tr("🔐 Нужно разрешение"), - attention: tr("👀 Сообщение от фабрики"), + attention: tr("👀 Сообщение"), }; +/** PEP-198: the name the owner sees on every message of the factory. */ +export const VOICE = tr("🔎 Аналитик"); + export interface Rendered { text: string; buttons: InlineButton[][]; @@ -33,6 +36,7 @@ export function renderQuestion( const free = questionIsFreeText(q); const shown = q.kind === "permission" ? { main: q.text, more: null } : splitForDisplay(questionText({ ...q, text: userText(q.text) || q.text })); const body = esc(clip(shown.main, 3300)); + // PEP-198: one voice — every message to the owner comes from the analyst. const lines = [head, KIND[q.kind], "", body]; const buttons: InlineButton[][] = []; @@ -68,6 +72,7 @@ export function renderQuestion( if (s.status === "rate_limited" && s.subscriptionId != null) buttons.push([{ text: tr("🙋 Попросить подписку у администратора"), callback_data: `s:${s.id}:ask` }]); } } + lines[1] = `${VOICE} · ${lines[1]}`; if (ctx.session && ctx.engineer) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); const web = ctx.webUrl.replace(/\/$/, ""); if ((ctx.details || shown.more) && ctx.taskKey && /^https?:\/\//.test(web)) buttons.push([{ text: tr("Подробнее"), url: `${web}/t/${ctx.taskKey}?more=1` }]); diff --git a/openspec/changes/pep-198-one-analyst/design.md b/openspec/changes/pep-198-one-analyst/design.md index 89d68bb2..7dd568b6 100644 --- a/openspec/changes/pep-198-one-analyst/design.md +++ b/openspec/changes/pep-198-one-analyst/design.md @@ -21,7 +21,7 @@ - Перед созданием части — `checkDuplicate` (PEP-197); повтор — часть не создаётся, в решении «уже есть KEY». ### Один собеседник -- `runner/agent-relay.ts` `relayAgentQuestion(db, ref, q)`: правило без модели (технические слова — стек, база, библиотека, тест, ветка, сборка…) → technical; иначе модель (роль `relay`, haiku, `PEPPA_RELAY_MODEL`) с последними сообщениями задачи владельцу: `{verdict: product|technical|repeat, text, options[], default}`. Сбой модели → передаём как есть (лучше дойти, чем потеряться). +- `runner/question-relay.ts` `relayAgentQuestion(db, ref, q)`: правило без модели (технические слова — стек, база, библиотека, тест, ветка, сборка…) → technical; иначе модель (роль `relay`, haiku, `PEPPA_RELAY_MODEL`) с последними сообщениями задачи владельцу: `{verdict: product|technical|repeat, text, options[], default}`. Сбой модели → передаём как есть (лучше дойти, чем потеряться). - technical → вопрос не создаётся, агенту ответ «Это технический вопрос — решите сами и запишите в design.md», событие `relay_held`. - repeat → не создаётся, агенту «владельцу уже задан такой вопрос #N». - product → `askPm` с текстом Аналитика и вариантами; `settings question.voice:` = `analyst`. diff --git a/openspec/changes/pep-198-one-analyst/tasks.md b/openspec/changes/pep-198-one-analyst/tasks.md index ac611204..ebaaafd9 100644 --- a/openspec/changes/pep-198-one-analyst/tasks.md +++ b/openspec/changes/pep-198-one-analyst/tasks.md @@ -8,7 +8,7 @@ - [ ] 2.3 readyBacklog: часть разбивки ждёт приёмки первой - [ ] 2.4 Веб: блок «Фабрика решила за вас» на странице задачи ## 3. Один собеседник -- [ ] 3.1 runner/agent-relay.ts + MCP ask_pm / report_blocker +- [ ] 3.1 runner/question-relay.ts + MCP ask_pm / report_blocker - [ ] 3.2 Telegram: подпись «Аналитик»; находки агента приёмки — от Аналитика, «Агент приёмки» - [ ] 3.3 Готовые задачи агентов — сводкой в конце дня - [ ] 3.4 Застрявшая задача — суперадмину и строка владельцу diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index f794ee62..1e8c6417 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -7,6 +7,7 @@ export * from "./tasks.ts"; export * from "./task-origin.ts"; export * from "./task-dedup.ts"; export * from "./task-decisions.ts"; +export * from "./ready-digest.ts"; export * from "./questions.ts"; export * from "./agent-message.ts"; export * from "./message-details.ts"; diff --git a/packages/core/src/platform-delay.ts b/packages/core/src/platform-delay.ts index dae431f1..f3cd6f05 100644 --- a/packages/core/src/platform-delay.ts +++ b/packages/core/src/platform-delay.ts @@ -30,7 +30,9 @@ export type DelayReason = /** An update of the product failed or was rolled back. */ | "deploy" /** An accept could not be carried through. */ - | "accept"; + | "accept" + /** PEP-198: the story is in work, its agent has been idle over an hour, the checks are green — nobody moves it. */ + | "stuck"; export interface DelayScope { projectId: number; @@ -211,6 +213,7 @@ export const DELAY_REASON_NAMES: Record = { switch: tr("агент не может взять задачу"), deploy: tr("версия продукта не обновилась"), accept: tr("приёмка не доведена"), + stuck: tr("задача не движется"), }; export interface DelayView extends PlatformDelay { diff --git a/packages/core/src/ready-digest.ts b/packages/core/src/ready-digest.ts new file mode 100644 index 00000000..f09f4a5c --- /dev/null +++ b/packages/core/src/ready-digest.ts @@ -0,0 +1,59 @@ +// PEP-198: finished stories reach the owner in the analyst's voice — at once when the owner is +// waiting for the story, otherwise in one message at the end of the working day. A story is +// awaited when a person asked for it (origin human), commented on it or said «Делать» to the +// factory's proposal. The «готово» card of a story nobody waits for is still on the site +// («Ждут „Принять“»); only Telegram and push hold it for the evening (`readyDigestTick`). +import { events, questions, tasks, type Db } from "@peppa/db"; +import { and, eq, inArray, isNull } from "drizzle-orm"; +import { m as tr, asIs } from "@peppa/shared/i18n"; +import { formatTaskKey } from "@peppa/shared"; +import { questionType, type MessageType } from "./questions.ts"; +import { getSetting, setSetting } from "./settings.ts"; +import { COMMENT_EVENT } from "./tasks.ts"; + +/** Does a person wait for this story (its «готово» goes at once)? */ +export async function taskAwaited(db: Db, taskId: number): Promise { + const [t] = await db.select({ origin: tasks.origin }).from(tasks).where(eq(tasks.id, taskId)); + if (!t || t.origin === "human") return true; + const [e] = await db + .select({ id: events.id }) + .from(events) + .where(and(eq(events.taskId, taskId), inArray(events.type, [COMMENT_EVENT, "proposal_approved"]))) + .limit(1); + return !!e; +} + +/** The bot's question: is this message held for the evening digest (not sent one by one)? */ +export async function heldForDigest(db: Db, q: { taskId: number | null; kind: string; msgType?: MessageType | null; options?: string[] | null }, taskStatus: string | null): Promise { + if (!q.taskId || questionType(q, taskStatus) !== "done") return false; + return !(await taskAwaited(db, q.taskId)); +} + +const sentKey = (projectId: number) => `ready.digest:${projectId}`; +export const readyDigestDay = (db: Db, projectId: number) => getSetting(db, sentKey(projectId)); +export const markReadyDigest = (db: Db, projectId: number, day: string) => setSetting(db, sentKey(projectId), day); + +export interface ReadyItem { + key: string; + title: string; +} + +/** Stories of a project in review with an open «готово» nobody waits for. */ +export async function heldReadyStories(db: Db, project: { id: number; key: string }): Promise { + const rows = await db + .select({ q: questions, t: tasks }) + .from(questions) + .innerJoin(tasks, eq(questions.taskId, tasks.id)) + .where(and(eq(questions.projectId, project.id), isNull(questions.answeredAt), eq(tasks.status, "review"), isNull(tasks.archivedAt))); + const out = new Map(); + for (const { q, t } of rows) if (!out.has(t.id) && (await heldForDigest(db, q, t.status))) out.set(t.id, { key: formatTaskKey(project.key, t.number), title: t.title }); + return [...out.values()]; +} + +export function readyDigestText(items: ReadyItem[], url: string): string { + return [ + tr("За день готовы задачи: {n}. Примите их или напишите, что поправить.", { n: items.length }), + items.map((i) => `• ${i.key} «${asIs(i.title)}»`).join("\n"), + tr("Где посмотреть: {url}", { url }), + ].join("\n"); +} diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index fd2675f0..b9553f20 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -50,7 +50,7 @@ import { productOnlySecret, } from "@peppa/core"; import type { Db } from "@peppa/db"; -import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner"; +import { relayAgentQuestion, relayRefusal, requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner"; import { z } from "zod"; import { asIs, m } from "@peppa/shared/i18n"; import { formatIncident, formatTask } from "./format.ts"; @@ -267,8 +267,11 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer const ref = await resolve(task); const c = checkChoices(options, def); const msg = await admit(ref, "question", { summary: question, link, details }, { summaryLines: 3, options: c.options, field: "question" }); - const q = await askPm(db, ref, { kind: "question", msgType: "question", text: renderMain(msg, { defaultNeed: m("выберите вариант ответа") }), details: renderDetails(msg), options: c.options, defaultOption: c.defaultOption, sessionId }); - return `Question #${q.id} sent to the owner${sentAs(msg)}. 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.`; + // PEP-198: the analyst decides what reaches the owner and says it in its own words. + const r = await relayAgentQuestion(db, ref, { text: question, options: c.options, defaultOption: c.defaultOption }); + if (r.kind !== "product") return relayRefusal(r, ref.key); + const q = await askPm(db, ref, { kind: "question", msgType: "question", text: renderMain({ ...msg, summary: r.text }, { defaultNeed: m("выберите вариант ответа") }), details: [r.byModel ? m("Агент спросил: {text}", { text: asIs(question) }) : null, renderDetails(msg)].filter(Boolean).join("\n\n") || null, options: r.options, defaultOption: r.defaultOption, sessionId }); + return `Question #${q.id} sent to the owner by the analyst${sentAs(msg)}. Don't wait for the answer: continue with «${r.defaultOption}» now (note it in design.md); if the owner answers differently, the answer arrives as a message and you adjust.`; }, ); @@ -308,9 +311,12 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer if (product) { const c = checkChoices(options, def); const msg = await admit(ref, "question", { summary: what, link, details }, { summaryLines: 3, options: c.options, field: "what" }); + // PEP-198: through the analyst, like any question to the owner. + const r = await relayAgentQuestion(db, ref, { text: what, options: c.options, defaultOption: c.defaultOption }); + if (r.kind !== "product") return relayRefusal(r, ref.key); // What the agent tried is technical: it opens under «Подробнее» together with the details. - const more = [m("Что уже пробовал: {tried}", { tried: asIs(tried) }), renderDetails(msg)].filter(Boolean).join("\n\n"); - const q = await askPm(db, ref, { kind: "question", msgType: "question", text: renderMain(msg, { defaultNeed: m("выберите вариант ответа") }), details: more, options: c.options, defaultOption: c.defaultOption, sessionId }); + const more = [r.byModel ? m("Агент спросил: {text}", { text: asIs(what) }) : null, m("Что уже пробовал: {tried}", { tried: asIs(tried) }), renderDetails(msg)].filter(Boolean).join("\n\n"); + const q = await askPm(db, ref, { kind: "question", msgType: "question", text: renderMain({ ...msg, summary: r.text }, { defaultNeed: m("выберите вариант ответа") }), details: more, options: r.options, defaultOption: r.defaultOption, sessionId }); return `Blocker sent to the owner as question #${q.id}${sentAs(msg)}. End your turn — the answer arrives as a message.`; } const msg = await admit(ref, "blocker", { summary: what, link, details }, { field: "what" }); diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 287c7337..3a3437e4 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -34,6 +34,9 @@ export * from "./project-subscription.ts"; export * from "./subscription-request.ts"; export * from "./intake.ts"; export * from "./decisions.ts"; +export * from "./question-relay.ts"; +export * from "./ready-digest.ts"; +export * from "./stuck-tasks.ts"; export * from "./project-trash.ts"; export * from "./branch-protection.ts"; export * from "./story-refine.ts"; diff --git a/packages/runner/src/platform-delays.ts b/packages/runner/src/platform-delays.ts index 17976c70..32e71309 100644 --- a/packages/runner/src/platform-delays.ts +++ b/packages/runner/src/platform-delays.ts @@ -199,6 +199,11 @@ async function sweep(db: Db, d: PlatformDelay, now: number, log: Log) { if (live.some((s) => ["running", "idle", "waiting_input"].includes(s.status))) await clear(); return; } + if (d.reason === "stuck") { + // PEP-198: over once the story left work or its agent is working again. + if (ref.task.status !== "in_progress" || live.some((s) => s.status === "running")) await clear(); + return; + } if (d.reason === "limit") { if (!live.some((s) => s.status === "rate_limited")) await limitOver(db, { id: d.sessionId ?? 0, projectId: d.projectId, taskId: d.taskId }); return; diff --git a/packages/runner/src/question-relay.ts b/packages/runner/src/question-relay.ts new file mode 100644 index 00000000..923199be --- /dev/null +++ b/packages/runner/src/question-relay.ts @@ -0,0 +1,124 @@ +// PEP-198: the analyst is the only one who talks to the owner. A developer agent's question +// (MCP ask_pm, a product blocker) comes to the analyst first, and the analyst decides: +// - a technical question (stack, base, libraries, architecture, which service to plug in) does +// not reach the owner — the agent decides itself; +// - the same question by meaning as one already asked does not reach the owner again; +// - a product question goes to the owner once, in the analyst's words, with answers to tap. +// Cheap rules first (no model), then one short model call on the project's subscription +// (`PEPPA_RELAY_MODEL`, haiku). A failing model lets the question through as the agent wrote it: +// better asked twice than lost. `PEPPA_AGENT_RELAY=off` — the old way, straight to the owner. +import { questions, type Db } from "@peppa/db"; +import { and, desc, eq, gte } from "drizzle-orm"; +import { logEvent, normTitle, type Project, type TaskRef } from "@peppa/core"; +import { stripAsIs } from "@peppa/shared/i18n"; +import { claudePrint } from "./claude-print.ts"; + +export const RELAY_PROMPT_HEAD = "Ты — аналитик софтвер-фабрики между агентами и владельцем продукта."; +const WINDOW_MS = 7 * 86_400_000; + +/** Words that make a question technical by themselves: the owner (not a programmer) cannot answer it. */ +const TECH = /(баз[аеуыой]{1,2} данных|postgres|sqlite|mysql|mongo|redis|библиотек|фреймворк|(? }): string { + return [ + `${RELAY_PROMPT_HEAD} Агент-разработчик хочет спросить владельца. Владелец — не программист. Реши, что из этого дойдёт до него.`, + "verdict:", + "- technical — вопрос о том, как сделать (стек, база, библиотеки, архитектура, какой внешний сервис подключить, тесты, сборка): владелец на него ответить не может, агент решает сам. Если продукту нужен внешний сервис или ключ — это тоже technical: сервис выбирает агент, а не владелец.", + "- repeat — по смыслу то же, что уже спрошено у владельца (список ниже), даже другими словами. repeat_of — номер того вопроса.", + "- product — вопрос о продукте, на который может ответить только владелец: что увидит или получит пользователь, правила, тексты, деньги. Тогда text — твой пересказ вопроса для владельца: одна-две фразы, простые слова, на «вы», без жаргона, без названий файлов и веток; options — 2–4 варианта ответа (вариант агента по умолчанию — первым), default — вариант по умолчанию.", + "", + `Проект: ${o.project}`, + `Задача: ${o.task}`, + "", + "## Вопрос агента", + o.question.text.trim(), + "", + `Варианты агента: ${o.question.options.join(" | ")}`, + `По умолчанию: ${o.question.defaultOption}`, + "", + "## Уже спрошено у владельца", + o.earlier.length ? o.earlier.map((q) => `- #${q.id}: ${q.text.replace(/\s+/g, " ").slice(0, 300)}`).join("\n") : "(ничего)", + "", + 'Ответь ОДНОЙ строкой JSON без пояснений: {"verdict":"product|technical|repeat","repeat_of":null,"text":"…","options":["…"],"default":"…"}', + ].join("\n"); +} + +export function parseRelay(text: string): { verdict: "product" | "technical" | "repeat"; repeatOf: number | null; text: string; options: string[]; default: string } | null { + const m = /\{[\s\S]*\}/.exec(text); + if (!m) return null; + try { + const o = JSON.parse(m[0]) as Record; + const verdict = o.verdict === "product" || o.verdict === "technical" || o.verdict === "repeat" ? o.verdict : null; + if (!verdict) return null; + const options = (Array.isArray(o.options) ? o.options : []).map((x) => String(x ?? "").trim().slice(0, 120)).filter(Boolean).slice(0, 4); + return { verdict, repeatOf: Number(o.repeat_of) || null, text: typeof o.text === "string" ? o.text.trim().slice(0, 600) : "", options, default: typeof o.default === "string" ? o.default.trim() : "" }; + } catch { + return null; + } +} + +/** What the owner was already asked about this story lately (open first). */ +async function earlierQuestions(db: Db, taskId: number): Promise> { + const rows = await db + .select({ id: questions.id, text: questions.text, answeredAt: questions.answeredAt, msgType: questions.msgType }) + .from(questions) + .where(and(eq(questions.taskId, taskId), eq(questions.kind, "question"), gte(questions.createdAt, new Date(Date.now() - WINDOW_MS)))) + .orderBy(desc(questions.id)) + .limit(10); + return rows.map((r) => ({ id: r.id, text: stripAsIs(r.text).split("\n")[0] ?? "", open: !r.answeredAt })); +} + +export async function relayAgentQuestion(db: Db, ref: TaskRef, q: AgentQuestion, o: { log?: (m: string) => void } = {}): Promise { + const asIsQuestion: RelayVerdict = { kind: "product", text: q.text, options: q.options, defaultOption: q.defaultOption, byModel: false }; + if (process.env.PEPPA_AGENT_RELAY === "off") return asIsQuestion; + const decided = async (v: RelayVerdict) => { + await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "relay_decided", payload: { verdict: v.kind, question: q.text.slice(0, 500), ...(v.kind === "repeat" ? { of: v.questionId } : {}) } }).catch(() => {}); + return v; + }; + if (TECH.test(q.text)) return decided({ kind: "technical", reason: "rule" }); + const earlier = await earlierQuestions(db, ref.task.id); + const same = earlier.find((e) => normTitle(e.text) === normTitle(q.text)); + if (same) return decided({ kind: "repeat", questionId: same.id }); + const out = await ask(db, ref.project, relayPrompt({ project: ref.project.name, task: `${ref.key} «${ref.task.title}»`, question: q, earlier })); + const r = out.ok ? parseRelay(out.text) : null; + if (!r) { + o.log?.(`relay ${ref.key}: ${out.ok ? "unparsable" : out.error} — passed as is`); + return asIsQuestion; + } + if (r.verdict === "technical") return decided({ kind: "technical", reason: "model" }); + if (r.verdict === "repeat") { + const of = earlier.find((e) => e.id === r.repeatOf) ?? earlier[0]; + if (of) return decided({ kind: "repeat", questionId: of.id }); + return asIsQuestion; + } + const options = r.options.length >= 2 ? r.options : q.options; + const defaultOption = options.includes(r.default) ? r.default : options.includes(q.defaultOption) ? q.defaultOption : options[0]!; + return decided({ kind: "product", text: r.text || q.text, options: [defaultOption, ...options.filter((x) => x !== defaultOption)], defaultOption, byModel: true }); +} + +const ask = (db: Db, project: Project, prompt: string) => + claudePrint(db, project, { + bin: process.env.PEPPA_INTAKE_BIN ?? "claude", + model: process.env.PEPPA_RELAY_MODEL ?? process.env.PEPPA_INTENT_MODEL ?? "haiku", + timeoutMs: Number(process.env.PEPPA_INTENT_TIMEOUT_MS ?? 30_000), + who: "аналитик", + prompt, + }); + +/** What the agent is told when its question does not reach the owner. */ +export function relayRefusal(v: Exclude, key: string): string { + return v.kind === "technical" + ? `Not sent to the owner: the analyst sees a technical question (how to build it — stack, data, libraries, which service to use). The owner is a product person and cannot answer it. Decide yourself, note the choice and why in design.md and project memory (remember, «Решения»), and go on with ${key}.` + : `Not sent to the owner: the same question (#${v.questionId}) is already with the owner. Don't ask again — go on with your default; the answer arrives as a message.`; +} diff --git a/packages/runner/src/ready-digest.ts b/packages/runner/src/ready-digest.ts new file mode 100644 index 00000000..98311947 --- /dev/null +++ b/packages/runner/src/ready-digest.ts @@ -0,0 +1,37 @@ +// PEP-198: the evening digest of finished stories nobody waited for (core/ready-digest.ts). Once a +// working day per project, after the end of the working hours of the watchdog (PEP-173: +// `workTo`, `workDays`, platform time zone): one message of the analyst in the project's +// discussion — it reaches the project's people in Telegram and the browser like any message of +// the analyst. An empty digest is not sent. +import { ensureProjectChat, heldReadyStories, markReadyDigest, pausedProjectIds, readyDigestDay, readyDigestText, listProjects } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { sayInDiscussion } from "./analyst-chat.ts"; +import { getWatchdogSettings } from "./recovery.ts"; + +/** The day (YYYY-MM-DD), hour and weekday (1 = Mon) in the platform's time zone. */ +function localNow(now: Date): { day: string; hour: number; weekday: number } { + const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, year: "numeric", month: "2-digit", day: "2-digit", weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now); + const get = (t: string) => parts.find((x) => x.type === t)?.value ?? ""; + return { day: `${get("year")}-${get("month")}-${get("day")}`, hour: Number(get("hour")), weekday: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(get("weekday")) + 1 }; +} + +export async function readyDigestTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise { + if (process.env.PEPPA_READY_DIGEST === "off") return 0; + const now = o.now ?? new Date(); + const cfg = await getWatchdogSettings(db); + const t = localNow(now); + if (!cfg.workDays.includes(t.weekday) || t.hour < cfg.workTo) return 0; + const paused = await pausedProjectIds(db); + let sent = 0; + for (const project of await listProjects(db)) { + if (paused.has(project.id) || (await readyDigestDay(db, project.id)) === t.day) continue; + const items = await heldReadyStories(db, project); + await markReadyDigest(db, project.id, t.day); + if (!items.length) continue; + const chat = await ensureProjectChat(db, project.id); + await sayInDiscussion(db, project, chat.id, readyDigestText(items, `${process.env.PEPPA_WEB_URL ?? ""}/`)); + o.log?.(`ready digest ${project.key}: ${items.length}`); + sent++; + } + return sent; +} diff --git a/packages/runner/src/stuck-tasks.ts b/packages/runner/src/stuck-tasks.ts new file mode 100644 index 00000000..1fdf65ab --- /dev/null +++ b/packages/runner/src/stuck-tasks.ts @@ -0,0 +1,48 @@ +// PEP-198 (6.3): the analyst notices a stuck story — in work, its agent idle for over an hour, +// the checks of its result green, and still not in review. Nobody moves it: that is the +// factory's fault, not the owner's. The superadmin hears about it (a platform delay, PEP-150); +// the owner gets one line from the analyst, once per episode. `PEPPA_STUCK_TASKS=off`. +import { m } from "@peppa/shared/i18n"; +import { ensureProjectChat, getPlatformDelay, listProjects, listSessions, listTasks, pausedProjectIds, platformDelay, taskCiSummary, type TaskRef } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { sayInDiscussion } from "./analyst-chat.ts"; + +export const STUCK_IDLE_MS = 60 * 60_000; + +export async function stuckTaskTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise { + if (process.env.PEPPA_STUCK_TASKS === "off") return 0; + const now = (o.now ?? new Date()).getTime(); + const paused = await pausedProjectIds(db); + let found = 0; + for (const project of await listProjects(db)) { + if (paused.has(project.id)) continue; + for (const task of await listTasks(db, { projectId: project.id, statuses: ["in_progress"] })) { + const scope = { projectId: project.id, taskId: task.id }; + if (await getPlatformDelay(db, scope, "stuck")) continue; + const [s] = (await listSessions(db, { taskId: task.id })).sort((a, b) => b.id - a.id); + // No agent at all is the start retry's business (PEP-150); a working or limited one is not idle. + if (!s || !["idle", "waiting_input", "done"].includes(s.status)) continue; + const since = (s.lastActivityAt ?? s.endedAt ?? s.startedAt).getTime(); + if (now - since < STUCK_IDLE_MS) continue; + const key = formatTaskKey(project.key, task.number); + const ref: TaskRef = { project, task, key }; + const ci = await taskCiSummary(db, ref); + if (ci.state !== "success") continue; + const hours = Math.floor((now - since) / 3_600_000); + await platformDelay(db, scope, { + reason: "stuck", + state: "idle", + // glossary-ignore: сообщение суперадмину + details: `⏳ ${key}: агент ${s.agentName ?? `s${s.id}`} свободен ${hours} ч, проверки ${ci.passed} из ${ci.total} пройдены, задача не на ревью. Посмотрите, почему она не движется.`, + now: new Date(now), + log: o.log, + }); + const chat = await ensureProjectChat(db, project.id); + await sayInDiscussion(db, project, chat.id, m("Задача {key} задерживается на нашей стороне. От вас ничего не нужно — мы уже разбираемся.", { key })); + o.log?.(`${key}: stuck (agent idle ${hours} h, checks green)`); + found++; + } + } + return found; +} diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 9867ede6..0d9cd68c 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -32,6 +32,8 @@ import * as tmux from "./tmux.ts"; import { ADD_SUBSCRIPTION_HINT, freshLimitLine, limitLines, recordLimit } from "./limits.ts"; import { limitDelay, limitOver } from "./limit-delay.ts"; import { checksQueueTick, platformDelayTick } from "./platform-delays.ts"; +import { readyDigestTick } from "./ready-digest.ts"; +import { stuckTaskTick } from "./stuck-tasks.ts"; import { domainGuardTick } from "./domain-guard.ts"; import { NET_WATCH_EVERY_MS, netWatchTick } from "./net-watch.ts"; import { killRunner, resumeSession, stopSession } from "./sessions.ts"; @@ -124,7 +126,7 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { await expireLoans(db, opts.now ?? new Date()).catch(failed(db, log, "subscription loans")); await subscriptionWarnTick(db, opts.now ?? new Date()).catch(failed(db, log, "subscription warnings")); // Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher. - // PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them. + // PEP-84 / PEP-198: the analyst formulates new stories before the dispatcher sees them. // PEP-163: deleted projects leave for good after their week. await projectTrashTick(db, { now: opts.now, log }).catch(failed(db, log, "project trash")); // PEP-191: once a day the protection of every project's default branch is checked. @@ -342,6 +344,9 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS await reviewCardTick(db, { log }).catch(failed(db, log, "review cards failed")); // PEP-150: checks that have not started for too long — a delay, not a question to the owner. await checksQueueTick(db, { stuckMin: (await getWatchdogSettings(db)).checksStuckMin, log }).catch(failed(db, log, "checks queue failed")); + // PEP-198: the analyst's evening digest of finished stories nobody waited for; stuck stories. + await readyDigestTick(db, { log }).catch(failed(db, log, "ready digest failed")); + await stuckTaskTick(db, { log }).catch(failed(db, log, "stuck tasks failed")); // PEP-189: no container takes the platform's port or domain; the public address answers Peppa. await domainGuardTick(db, { log }).catch(failed(db, log, "domain guard failed")); }