PEP-198: вопросы агентов через Аналитика, сводка готовых, застрявшие задачи

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-17 21:21:50 +05:00
parent 024ee18982
commit 9569380143
14 changed files with 309 additions and 11 deletions

View File

@ -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" });

View File

@ -11,9 +11,12 @@ const KIND: Record<Question["kind"], string> = {
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(`<code>tmux attach -t ${esc(ctx.session.tmuxName)}</code>`);
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` }]);

View File

@ -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:<qid>` = `analyst`.

View File

@ -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 Застрявшая задача — суперадмину и строка владельцу

View File

@ -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";

View File

@ -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<DelayReason, string> = {
switch: tr("агент не может взять задачу"),
deploy: tr("версия продукта не обновилась"),
accept: tr("приёмка не доведена"),
stuck: tr("задача не движется"),
};
export interface DelayView extends PlatformDelay {

View File

@ -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<boolean> {
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<boolean> {
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<string>(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<ReadyItem[]> {
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<number, ReadyItem>();
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");
}

View File

@ -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" });

View File

@ -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";

View File

@ -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;

View File

@ -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|библиотек|фреймворк|(?<![а-яё])стек(?![а-яё])|миграци|схем[аеуы] данных|архитектур|\bapi\b|эндпоинт|\bendpoint|\bsdk\b|\bdocker|контейнер|(?<![а-яё])ветк[аеиу](?![а-яё])|\bgit\b|\bci\b|линтер|typescript|python|\breact\b|next\.?js|node\.?js|\bnpm\b|\bpnpm\b|webhook|вебхук|\borm\b|\bjwt\b|oauth|автотест|юнит-тест)/i;
export type RelayVerdict =
| { kind: "product"; text: string; options: string[]; defaultOption: string; byModel: boolean }
| { kind: "technical"; reason: string }
| { kind: "repeat"; questionId: number };
export interface AgentQuestion {
text: string;
options: string[];
defaultOption: string;
}
export function relayPrompt(o: { project: string; task: string; question: AgentQuestion; earlier: Array<{ id: number; text: string }> }): 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<string, unknown>;
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<Array<{ id: number; text: string; open: boolean }>> {
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<RelayVerdict> {
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<RelayVerdict, { kind: "product" }>, 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.`;
}

View File

@ -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<number> {
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;
}

View File

@ -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<number> {
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;
}

View File

@ -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<void> {
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"));
}