diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 6f0f0cad..851119d2 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -39,6 +39,7 @@ import { markOutboxRetry, markOutboxSent, pendingQuestions, + needsPerson, questionByTelegramMessage, setOffset, setSetting, @@ -305,12 +306,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>>(); + const waits = new Set(); + 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 }); const r = renderQuestion(q, ctx); // A push is a "now" signal: questions older than this don't pop up on a fresh subscription. @@ -323,7 +332,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", }); } diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 5536a560..dcff09a2 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -1,5 +1,5 @@ // Telegram message texts and buttons for PM questions. HTML parse mode. -import type { Question, SessionView } from "@peppa/core"; +import { questionType, type Question, type SessionView } from "@peppa/core"; import type { InlineButton } from "./telegram.ts"; import { m as tr } from "@peppa/shared/i18n"; @@ -31,6 +31,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("Чтобы вернуть на доработку — ответьте на это сообщение комментарием."))); @@ -40,23 +41,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) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); @@ -75,8 +77,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; } diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 2148b466..6ce600d7 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -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 {items.map((q) => )} + {ready.length > 0 && ( +
+ {ready.map((q) => )} +
+ )} {reports.length > 0 && (
{t("все обращения")}}> {reports.slice(0, 5).map((f) => )} diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index ac09bb01..47eb7afe 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -37,7 +37,8 @@ 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]; + // 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); @@ -89,12 +90,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal )} {review && } - {/* i18n-ignore: the value is the message to the agent */} - {q.kind === "attention" && !review && } + {/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */} {(q.options ?? []).map((o) => ( - + ))} + {q.defaultOption &&

{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}

} {q.kind !== "permission" && (
diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index 4bd2a7e6..e5598a4e 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -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>[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). */ diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index c9d1bc4e..7d1157da 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -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"; @@ -84,7 +85,7 @@ export async function listChats(db: Db, user: Pick): Promise`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`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((a, b) => (b && (!a || b > a) ? b : a), null); @@ -315,7 +316,7 @@ export async function chatThreads(db: Db, chatId: number, limit = 50): Promise`count(*)`, lastId: sql`max(${chatMessages.id})`, lastAt: sql`max(${chatMessages.createdAt})`, - open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`, + open: sql`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)) @@ -367,6 +368,8 @@ const EVENT_TEXT: Record { 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) }) }), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index d32cfffe..efa518ee 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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"; diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts index df268cce..d8c6d448 100644 --- a/packages/core/src/notifications.ts +++ b/packages/core/src/notifications.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, now return from < to ? m >= from && m < to : m >= from || m < to; } -/** Which event a PM question stands for. */ -export function questionEvent(q: Pick, 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 & Partial>, 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). */ diff --git a/packages/core/src/questions.ts b/packages/core/src/questions.ts new file mode 100644 index 00000000..8a238191 --- /dev/null +++ b/packages/core/src/questions.ts @@ -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): 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 }; +} diff --git a/packages/core/src/review-card.ts b/packages/core/src/review-card.ts index 42035ad0..94135c67 100644 --- a/packages/core/src/review-card.ts +++ b/packages/core/src/review-card.ts @@ -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() }); diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ec796bea..4ca96cca 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -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"; @@ -180,12 +181,12 @@ 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 { 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!; }); diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index aeba839e..56d9e115 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -15,6 +15,7 @@ import { blockersOf, dependentsOf, type Blocker } from "./deps.ts"; import { taskBudgetView, type TaskBudgetView } from "./budgets.ts"; import { productNeeds, type ProductNeedView } from "./product-needs.ts"; import { raiseOnce, type MessageTopic } from "./message-state.ts"; +import { defaultMessageType, type MessageType } from "./questions.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -306,6 +307,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). */ @@ -314,7 +319,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!; }); @@ -324,8 +329,8 @@ 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 { - const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); +export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[]; msgType?: MessageType | null }): Promise { + const [row] = await db.insert(questions).values({ projectId: project.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }).returning(); await notify(db, { type: "question", questionId: row!.id }); return row!; } @@ -378,6 +383,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(o: T, keys: string[]): Record { return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]])); } diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index adf8164b..666b1fe1 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -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(), + // 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"] }), diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index 5b632a87..0c8b0fe2 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -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.", diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 368b5e01..e606617d 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -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"); }); diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts index 422fc5f2..7e65b509 100644 --- a/packages/runner/src/ci-feedback.ts +++ b/packages/runner/src/ci-feedback.ts @@ -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 { 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, gitea: GiteaClient = giteaForBot()): Promise { + 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(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) diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index c355aaa6..08594939 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -31,6 +31,9 @@ import { demoNote, reviewRejections, getSession, + getProject, + needsPerson, + reportProgress, logSessionEvent, peppaInputSentAt, pendingSessionQuestions, @@ -186,13 +189,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 { @@ -209,7 +212,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; } @@ -262,9 +266,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; } diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 61a699a8..9236ff86 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -282,7 +282,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;