From c80a31f5cb93fb2892f055ea4cf9a6c421c1193a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 13:23:45 +0500 Subject: [PATCH] =?UTF-8?q?PEP-154:=20=D1=84=D0=B8=D0=BB=D1=8C=D1=82=D1=80?= =?UTF-8?q?=20=D1=81=D0=BB=D1=83=D0=B6=D0=B5=D0=B1=D0=BD=D0=BE=D0=B3=D0=BE?= =?UTF-8?q?=20=D1=82=D0=B5=D0=BA=D1=81=D1=82=D0=B0,=20=D0=BE=D1=82=D0=B2?= =?UTF-8?q?=D0=B5=D1=82=20=E2=80=94=20=D1=82=D0=BE=D0=BB=D1=8C=D0=BA=D0=BE?= =?UTF-8?q?=20=D0=B2=D0=B2=D0=BE=D0=B4=20=D1=87=D0=B5=D0=BB=D0=BE=D0=B2?= =?UTF-8?q?=D0=B5=D0=BA=D0=B0,=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BB=D0=B0=D1=82=D1=84=D0=BE=D1=80=D0=BC=D1=8B=20?= =?UTF-8?q?=E2=80=94=20=D1=81=D1=83=D0=BF=D0=B5=D1=80=D0=B0=D0=B4=D0=BC?= =?UTF-8?q?=D0=B8=D0=BD=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- apps/bot/package.json | 2 +- apps/bot/src/bot.ts | 5 +- apps/bot/src/render.ts | 12 +- apps/web/app/(app)/t/[key]/page.tsx | 2 +- apps/web/components/AgentSteps.tsx | 27 ++- apps/web/components/cards.tsx | 15 +- packages/core/src/chats.ts | 11 + packages/core/src/index.ts | 2 + packages/core/src/platform-failure.ts | 39 ++++ packages/core/src/sessions.ts | 5 + packages/core/src/tasks.ts | 15 +- packages/core/src/user-text.ts | 142 +++++++++++++ packages/runner/src/autonomy.ts | 20 +- packages/runner/src/deploy.ts | 6 +- packages/runner/src/hook.ts | 18 +- packages/runner/src/recovery.ts | 5 +- packages/shared/src/i18n/en/runner.ts | 4 + packages/shared/src/i18n/en/story.ts | 11 + packages/shared/src/i18n/kk/runner.ts | 4 + packages/shared/src/i18n/kk/story.ts | 11 + packages/testkit/test/service-text.test.ts | 229 +++++++++++++++++++++ 21 files changed, 558 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/platform-failure.ts create mode 100644 packages/core/src/user-text.ts create mode 100644 packages/testkit/test/service-text.test.ts diff --git a/apps/bot/package.json b/apps/bot/package.json index 5e87285a..1313b8b1 100644 --- a/apps/bot/package.json +++ b/apps/bot/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "type": "module", - "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, + "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" }, "bin": { "peppa-bot": "./bin/peppa-bot" }, "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." }, "dependencies": { diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 6f0f0cad..b98f7456 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -39,6 +39,7 @@ import { markOutboxRetry, markOutboxSent, pendingQuestions, + getUiMode, questionByTelegramMessage, setOffset, setSetting, @@ -312,11 +313,12 @@ export function createBot(o: BotOptions) { if (!audience.length) continue; const ctx = await context(q); 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. const fresh = Date.now() - q.createdAt.getTime() < PUSH_MAX_AGE_MS; const url = ctx.taskKey ? `/t/${ctx.taskKey}` : `/p/${await projectKey(q.projectId)}`; 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" }); await deliverToUser(db, u, { event, projectId: q.projectId, @@ -331,6 +333,7 @@ export function createBot(o: BotOptions) { // fresh text and its buttons back, at most once in `repeatEditMs`. const repeats = states.get(q.id)?.repeats ?? 0; if (!repeats) continue; + const r = renderQuestion(q, ctx); for (const sent of await sentQuestionMessages(db, q.id)) { const key = repeatEditKey(sent.id, repeats); if (await getOutbox(db, key)) continue; diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 5536a560..cb2df129 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 { stripServiceBlocks, userText, type Question, type SessionView } from "@peppa/core"; import type { InlineButton } from "./telegram.ts"; import { m as tr } from "@peppa/shared/i18n"; @@ -22,12 +22,13 @@ export interface Rendered { // callback_data (≤64 bytes): "q::", "s::" or "i::" (core/incidents.ts) export function renderQuestion( q: Question, - ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, + ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string; /** PEP-154: the reader's view is «Инженер» — the terminal command is shown. */ engineer?: boolean }, ): Rendered { const head = ["" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "", ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); - const body = esc(clip(q.text, 3300)); + // PEP-154: no service text in the message (a permission request keeps its command). + const body = esc(clip(q.kind === "permission" ? q.text : userText(q.text) || q.text, 3300)); const lines = [head, KIND[q.kind], "", body]; const buttons: InlineButton[][] = []; @@ -59,7 +60,7 @@ export function renderQuestion( lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту."))); } } - if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); + if (ctx.session && ctx.engineer) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`); return { text: lines.join("\n"), buttons }; } @@ -67,7 +68,8 @@ export function renderQuestion( export function renderAnswered(original: string, q: Question): string { const mark = q.answeredVia === "system" ? "⌛" : "✅"; const via = { telegram: tr("в Telegram"), web: tr("в вебе"), terminal: tr("в терминале"), system: "" }[q.answeredVia ?? "telegram"]; - const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: {answer}", { via, answer: esc(clip(q.answer ?? "", 500)) }); + const answer = stripServiceBlocks(q.answer ?? ""); + const said = q.answeredVia === "system" ? esc(answer) : tr("Ответ {via}: {answer}", { via, answer: esc(clip(answer, 500)) }); return `${original}\n\n${mark} ${said}`; } diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx index b75d6fce..7b07875c 100644 --- a/apps/web/app/(app)/t/[key]/page.tsx +++ b/apps/web/app/(app)/t/[key]/page.tsx @@ -309,7 +309,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom {live ? ( // PEP-9 terminal + PEP-33 step feed of the newest unfinished runner. - + ) : (
diff --git a/apps/web/components/AgentSteps.tsx b/apps/web/components/AgentSteps.tsx index 9cd8ccb6..b240cb92 100644 --- a/apps/web/components/AgentSteps.tsx +++ b/apps/web/components/AgentSteps.tsx @@ -19,6 +19,19 @@ const KIND: Record = { other: { icon: Wrench, label: m("инструмент") }, }; +// PEP-154: a step for the «Продакт» view — what the agent does, in words: no command, file name or path. +const STEP_PLAIN: Record = { + command: m("Выполняет действие в проекте"), + test: m("Запускает проверки"), + edit: m("Вносит изменения"), + read: m("Изучает проект"), + search: m("Ищет нужное в проекте"), + web: m("Смотрит в интернете"), + agent: m("Поручил часть работы помощнику"), + mcp: m("Сверяется с задачей"), + other: m("Работает над задачей"), +}; + const KEEP = 30; function since(iso: string, now: number, t: Translator): string { @@ -32,7 +45,7 @@ function since(iso: string, now: number, t: Translator): string { * What the agent is doing now (PEP-33): its latest tool calls, newest first. Initial steps * come from the server, new ones from the live channel (PEP-37, `steps:`). */ -export function AgentSteps({ sessionId, initial, live, hooks = true }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean }) { +export function AgentSteps({ sessionId, initial, live, hooks = true, plain = false }: { sessionId: number; initial: StepView[]; live: boolean; hooks?: boolean; /** PEP-154: «Продакт» — what the agent does in words, no commands, file names or paths. */ plain?: boolean }) { const [steps, setSteps] = useState(initial); const [now, setNow] = useState(() => Date.now()); const t = useT(); @@ -59,7 +72,7 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session if (!steps.length) return (

- {hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")} + {hooks ? (live ? t("Агент ещё ничего не сделал — шаги появятся здесь.") : t("Шагов не записано.")) : plain ? t("Этот агент не сообщает о шагах.") : t("Этот агент не сообщает шаги (нет хуков) — смотри терминал.")}

); return ( @@ -70,9 +83,13 @@ export function AgentSteps({ sessionId, initial, live, hooks = true }: { session return (
  • - - {s.text} - + {plain ? ( + {t(STEP_PLAIN[s.kind] ?? STEP_PLAIN.other)} + ) : ( + + {s.text} + + )} {!s.ok && {t("ошибка")}} {since(s.at, now, t)}
  • diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index ac09bb01..1f271405 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -1,7 +1,7 @@ // Domain cards shared by pages: agent questions, runners, project list. import Link from "next/link"; import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react"; -import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; +import { questionDetails, questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core"; import { db } from "@/lib/db"; import { SubscriptionName } from "@/components/SubscriptionName"; import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions"; @@ -15,6 +15,7 @@ import { RunnerTerminal } from "@/components/RunnerTerminal"; import { SessionUsageLine } from "@/components/Accounting"; import { cn } from "@/lib/utils"; import { getT } from "@/lib/i18n"; +import { subscriptionNamesVisible, uiMode } from "@/lib/auth"; import { m } from "@peppa/shared/i18n"; const KIND = { @@ -42,6 +43,8 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal // 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); const updatedAt = state?.updatedAt ? new Date(state.updatedAt) : null; + // PEP-154: what the filter removed (command output, paths) — for «Инженер» and a superadmin only. + const original = (await uiMode()) === "engineer" || (await subscriptionNamesVisible()) ? await questionDetails(db, q.id).catch(() => null) : null; return (
    @@ -70,6 +73,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal

    {t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}

    )} + {original && ( +
    + {t("Подробнее: исходный текст")} +
    {original}
    +
    + )} {answered ? (

    {q.answeredVia === "system" ? : } @@ -152,7 +161,7 @@ export function AttachCommand({ name }: { name: string }) { } /** `steps` (PEP-33): the live step feed of the agent, shown with the terminal. */ -export async function SessionCard({ s, back, showTitle = false, terminal = false, steps }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[] }) { +export async function SessionCard({ s, back, showTitle = false, terminal = false, steps, plainSteps = false }: { s: SessionView; back: string; showTitle?: boolean; terminal?: boolean; steps?: StepView[]; /** PEP-154: «Продакт» — steps in words. */ plainSteps?: boolean }) { const t = await getT(); return (

    @@ -179,7 +188,7 @@ export async function SessionCard({ s, back, showTitle = false, terminal = false )} - {steps && } + {steps && } {terminal && }
    ); diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index c9d1bc4e..77067015 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -13,6 +13,7 @@ import { notify } from "./notify.ts"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; import { projectForUser, userProjectIds, type User } from "./users.ts"; import type { OutboxRow } from "./telegram.ts"; +import { pruneQuestionDetails, userText } from "./user-text.ts"; import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts"; export type Chat = typeof chats.$inferSelect; @@ -101,6 +102,13 @@ export async function listChats(db: Db, user: Pick): Promise { + // PEP-154: what an agent or Peppa says goes through the service-text filter; nothing left — no message. + // A question's text was filtered when it was asked (a permission request keeps its command). + if (m.authorKind !== "user" && !m.questionId) { + const text = userText(m.text); + if (!text) return null; + m = { ...m, text }; + } if (m.threadKey && m.threadTitle == null) { const [prev] = await db .select({ t: chatMessages.threadTitle }) @@ -462,6 +470,8 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise let repeated = 0; const add = async (m: NewChatMessage) => { // PEP-151: the same event of a story again in a row is a counter on the line already there. + if (m.authorKind !== "user" && !m.questionId) m.text = userText(m.text); // PEP-154: compared and stored without service text + if (!m.text) return; if (await repeatsLastEvent(db, m)) return void repeated++; if (m.threadKey) m.threadTitle = await titleOf(m.threadKey); if (await addChatMessage(db, m)) added++; @@ -570,6 +580,7 @@ export async function pruneChats(db: Db, o: { now?: Date } = {}): Promise void; + now?: Date; +} + +/** + * What to tell the project owner about a failure: the text of a clear refusal, or null — it is + * a platform error (reported to the error tracker and to the superadmins, one message per error + * a day) and the owner gets nothing. Never throws. + */ +export async function platformFailure(db: Db, e: unknown, ctx: FailureContext): Promise { + if (e instanceof PeppaError) return e.message; + const message = (e as Error)?.message ?? String(e); + try { + await reportPlatformError(db, e, { service: ctx.service, where: ctx.where }); + // The same error of the same part (numbers aside) is one message a day. + const fp = createHash("sha1").update(`${ctx.service}|${normalizeMessage(ctx.where)}|${normalizeMessage(message)}`).digest("hex").slice(0, 12); + const day = (ctx.now ?? new Date()).toISOString().slice(0, 10); + // glossary-ignore: read by superadmins only + const text = tr("⚠️ Сбой в Peppa FACTORY ({where}): {error}", { where: ctx.where, error: message.length > 300 ? `${message.slice(0, 300)}…` : message }); + await alertAdmins(db, `fail:${fp}:${day}`, text, ctx.log ?? (() => {})); + } catch {} + return null; +} diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts index ec796bea..47309f95 100644 --- a/packages/core/src/sessions.ts +++ b/packages/core/src/sessions.ts @@ -7,6 +7,7 @@ import { actorColumns } from "./actor.ts"; import type { Question, QuestionKind } from "./tasks.ts"; import { userProjectIds } from "./users.ts"; import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts"; +import { keepQuestionDetails, messageText } from "./user-text.ts"; export type Session = typeof sessions.$inferSelect; export type SessionStatus = (typeof sessionStatus.enumValues)[number]; @@ -182,6 +183,9 @@ export async function raiseSessionQuestion( awaitingHook = false, o: { topic?: MessageTopic; head?: string | null } = {}, ): Promise { + // PEP-154: no service text (tags, command output, paths) in what the person reads. + const original = text; + text = messageText(kind, text); 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) @@ -189,6 +193,7 @@ export async function raiseSessionQuestion( .returning(); return created!; }); + await keepQuestionDetails(db, row.id, original, text).catch(() => {}); await notify(db, { type: "question", questionId: row.id }); return row; } diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index aeba839e..f4d551a1 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 { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-text.ts"; export type Task = typeof tasks.$inferSelect; export type TaskStatus = (typeof taskStatus.enumValues)[number]; @@ -310,6 +311,9 @@ export interface NewQuestion { /** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQuestion): Promise { + // PEP-154: no service text (tags, command output, paths) in what the person reads. + const original = q.text; + q = { ...q, text: messageText(q.kind, q.text) }; // PEP-151: the same state of the story again refreshes the earlier message instead of adding one. 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 @@ -318,6 +322,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues .returning(); return created!; }); + await keepQuestionDetails(db, row.id, original, q.text).catch(() => {}); if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId); await notify(db, { type: "question", questionId: row.id }); return row; @@ -325,7 +330,9 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues /** A message for the PM about the project as a whole (releases), not about a task. */ export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise { - const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning(); + const text = messageText(q.kind, q.text); + const [row] = await db.insert(questions).values({ projectId: project.id, ...q, text }).returning(); + await keepQuestionDetails(db, row!.id, q.text, text).catch(() => {}); await notify(db, { type: "question", questionId: row!.id }); return row!; } @@ -344,6 +351,12 @@ export async function answerQuestion( answer: string, via: NonNullable, ): Promise { + // PEP-154: an answer is a person's words — service blocks never land in it. + if (via !== "system") { + const said = stripServiceBlocks(answer); + if (!said && answer.trim()) throw new PeppaError(`Question #${questionId}: the answer is service text only`); + answer = said; + } const [row] = await db .update(questions) .set({ answer, answeredVia: via, answeredAt: new Date() }) diff --git a/packages/core/src/user-text.ts b/packages/core/src/user-text.ts new file mode 100644 index 00000000..1f6cbe19 --- /dev/null +++ b/packages/core/src/user-text.ts @@ -0,0 +1,142 @@ +// PEP-154: what a person reads must not carry service text. One filter for everything shown to +// the user from an agent's mouth or from a terminal: service blocks (, +// , any XML/HTML-like tag), ANSI sequences, code and command output, shell +// prompt lines, stack traces, absolute paths. The original stays under «Подробнее» for a +// superadmin and the «Инженер» view (`question.details:`), never in the main text. +import { settings, type Db } from "@peppa/db"; +import { and, like, lt } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +/** Blocks Claude Code and Peppa put into a conversation for the model, never for a person. */ +const SERVICE_TAGS = [ + "task-notification", + "system-reminder", + "local-command-stdout", + "local-command-stderr", + "local-command-caveat", + "command-name", + "command-message", + "command-args", + "command-contents", + "bash-input", + "bash-stdout", + "bash-stderr", + "user-prompt-submit-hook", + "user-memory-input", + "persisted-output", + "tool_use_error", + "function_calls", + "function_results", + "new-diagnostics", + "ide_opened_file", + "ide_selection", + "pasted_content", +].join("|"); + +// CSI / OSC / two-byte escapes, then the other control characters (tab, \n and \r stay). +const ANSI_RE = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g; +const SERVICE_BLOCK_RE = new RegExp(`<(${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*?`, "gi"); +/** A service block cut off before its closing tag (clipped text): everything after it is its body. */ +const SERVICE_OPEN_RE = new RegExp(`<(?:${SERVICE_TAGS})\\b[^>]*>[\\s\\S]*$`, "i"); + +/** + * Removes only what is certainly not a person's words: known service blocks and terminal + * escape sequences. Safe for a person's own text (an answer, input typed into a terminal). + */ +export function stripServiceBlocks(text: string): string { + return text.replace(/\r\n?/g, "\n").replace(ANSI_RE, "").replace(SERVICE_BLOCK_RE, "").replace(SERVICE_OPEN_RE, "").trim(); +} + +/** Input that reached a session but was not typed by anyone: nothing is left without service blocks. */ +export const isServiceInput = (text: string) => !!text.trim() && !stripServiceBlocks(text); + +// Where a removed block stood (private-use character: never in real text). +const CUT = ""; +// Any paired block whose tag name has a hyphen or an underscore — nobody writes prose like that. +const CUSTOM_BLOCK_RE = /<([a-z][\w.]*[-_][\w.-]*)\b[^>]*>[\s\S]*?<\/\1\s*>/gi; +const FENCE_RE = /^[ \t]*(```|~~~)[^\n]*\n[\s\S]*?(?:^[ \t]*\1[ \t]*$|(?![\s\S]))/gm; +const TAG_RE = /<\/?[a-zA-Z][\w:.-]*(?:\s[^<>]*)?\/?>/g; +const PROMPT_LINE_RE = /^\s*(?:[\w.-]+@[\w.-]+[^\n$#%]*[$#%]|\$|❯|➜|>>>|PS [A-Za-z]:\\[^>\n]*>)\s+\S.*$/; +const TRACE_LINE_RE = /^\s*(?:at\s.+(?::\d+:\d+\)?|\))\s*$|File ".+", line \d+.*$|Traceback \(most recent call last\):?\s*$|\.{3} \d+ more\s*$|Caused by: .+$)/; +const ERROR_HEAD_RE = /^\s*(?:Uncaught\s+)?(?:[\w$]+\.)*[\w$]*(?:Error|Exception)\b.*$/; +const PATH_SRC = String.raw`(?()\[\],;]*`; +const PATH_RE = new RegExp(PATH_SRC, "g"); +const HAS_PATH_RE = new RegExp(PATH_SRC); +const INLINE_CODE_RE = /`[^`\n]*`/g; +const HAS_WORD_RE = /[\p{L}\p{N}]/u; + +/** + * Text of an agent or a terminal, as a person may read it: without service blocks, tags, code + * and command output, shell prompts, stack traces and absolute paths. Idempotent. An empty + * result means there was nothing for a person in it. + */ +export function userText(text: string): string { + const src = stripServiceBlocks(text); + let s = src.replace(CUSTOM_BLOCK_RE, "").replace(FENCE_RE, `${CUT}\n`); + const lines = s.split("\n"); + const kept: string[] = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]!; + const cutLine = PROMPT_LINE_RE.test(line) || TRACE_LINE_RE.test(line) || (ERROR_HEAD_RE.test(line) && TRACE_LINE_RE.test(lines[i + 1] ?? "")); + kept.push(cutLine ? CUT : line); + } + s = kept.join("\n"); + s = s.replace(INLINE_CODE_RE, (code) => (HAS_PATH_RE.test(code) ? "" : code)).replace(PATH_RE, (path) => /[.!?]$/.test(path) ? path.slice(-1) : "").replace(TAG_RE, ""); + const out: string[] = []; + const srcLines = new Set(src.split("\n").map((l) => l.trim())); + for (const raw of s.split("\n")) { + if (raw.includes(CUT)) { + // «Вот вывод:» before a removed block: the colon promises what is no longer there. + for (let j = out.length - 1; j >= 0; j--) { + if (!out[j]) continue; + if (/[::]$/.test(out[j]!)) out[j] = `${out[j]!.slice(0, -1)}.`; + break; + } + out.push(""); + continue; + } + const line = raw + .replace(/[ \t]+$/g, "") + .replace(/(\S)[ \t]{2,}/g, "$1 ") + .replace(/\(\s*[,;:]?\s*\)|\[\s*\]|«\s*»|"\s*"|``/g, "") + .replace(/[ \t]+([.,;:!?)»])/g, "$1") + .replace(/([(«])[ \t]+/g, "$1") + .replace(/[ \t]+$/g, ""); + // A line the filter emptied (a bullet with only a path) goes away; an untouched one stays. + if (line.trim() && !HAS_WORD_RE.test(line) && !srcLines.has(raw.trim())) continue; + out.push(line); + } + return out.join("\n").replace(/\n{3,}/g, "\n\n").trim(); +} + +/** + * The text of a message for the user as it is stored. A permission request keeps its command + * (that is what the person allows; «Продакт» has it under «Подробнее», PEP-120). Nothing left + * after the filter — no message: PeppaError (an agent's `ask_pm` gets it as a hint). + */ +export function messageText(kind: string, text: string): string { + if (kind === "permission") return text; + const shown = userText(text); + // i18n-ignore: read by the agent (ask_pm) or the log, not by the user + if (!shown) throw new PeppaError("В сообщении только служебный текст (теги, вывод команд, пути) — показать пользователю нечего. Напиши его простыми словами."); + return shown; +} + +const DETAILS_PREFIX = "question.details:"; +const detailsKey = (questionId: number) => `${DETAILS_PREFIX}${questionId}`; + +/** Keeps the original of a filtered message for «Подробнее» (superadmin, «Инженер»); none when nothing was cut. */ +export async function keepQuestionDetails(db: Db, questionId: number, original: string, shown: string): Promise { + if (original.trim() === shown.trim()) await deleteSetting(db, detailsKey(questionId)); + else await setSetting(db, detailsKey(questionId), { text: original.slice(0, 8000) }); +} + +/** The unfiltered text of a message, if the filter removed something. Show only to a superadmin or in «Инженер». */ +export async function questionDetails(db: Db, questionId: number): Promise { + return (await getSetting<{ text: string }>(db, detailsKey(questionId)))?.text ?? null; +} + +export async function pruneQuestionDetails(db: Db, before: Date): Promise { + await db.delete(settings).where(and(like(settings.key, `${DETAILS_PREFIX}%`), lt(settings.updatedAt, before))); +} diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index f28aca66..86599800 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -24,6 +24,7 @@ import { projectPoolExhausted, questionRecipients, raiseSessionQuestion, + platformFailure, setSetting, taskPrNumber, type AutonomySettings, @@ -213,7 +214,9 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n const key = `auto:closefail:${q.id}`; if (!(await getSetting(db, key))) { await setSetting(db, key, true); - await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: (e as Error).message }) }); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `auto-close ${ref.key}`, log }); + if (why) await askPm(db, ref, { kind: "question", text: m("⚠️ {key}: не получилось закрыть автоматически — {error}", { key: ref.key, error: why }) }); } log(`${ref.key}: auto-close failed — ${(e as Error).message}`); } @@ -268,10 +271,13 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date const fresh = await resolveTaskById(db, task.id).catch(() => null); if (fresh && fresh.task.status === "in_progress") await moveTask(db, fresh, "backlog").catch(() => {}); await setIdle(db, project.id, { ...state, failUntil: now.getTime() + DISPATCH_RETRY_MS }); - await askPmProject(db, project, { - kind: "attention", - text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: (e as Error).message })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`, - }); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `dispatch ${ref.key}`, log, now }); + if (why) + await askPmProject(db, project, { + kind: "attention", + text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: project.name, key: ref.key, error: why })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`, + }); log(`${ref.key}: dispatch failed — ${(e as Error).message}`); return; } @@ -374,7 +380,9 @@ export async function onIdleAnswer(db: Db, q: Question, answer: string): Promise try { await moveTask(db, ref, "in_progress"); } catch (e) { - await askPmProject(db, ref.project, { kind: "attention", text: m("⚠️ {key} не запущена: {error}", { key: ref.key, error: (e as Error).message }) }); + // PEP-154: the person pressed a button and gets an answer, but never the text of an exception. + const why = await platformFailure(db, e, { service: "runner", where: `start ${ref.key}` }); + await askPmProject(db, ref.project, { kind: "attention", text: why ? m("⚠️ {key} не запущена: {error}", { key: ref.key, error: why }) : m("⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.", { key: ref.key }) }); } return true; } diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 5f781a13..e9dfc265 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -3,7 +3,7 @@ // here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a // `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). import { m } from "@peppa/shared/i18n"; -import { answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { answerQuestion, askPmProject, platformFailure, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; import { projects, questions, releases, settings, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; import { deployPlatform, isPlatform } from "./platform-release.ts"; @@ -288,7 +288,9 @@ export async function onReleaseAnswer(db: Db, q: Question, answer: string, by: s try { await deployProd(db, project, by); } catch (e) { - await askPmProject(db, project, { kind: "attention", text: m("Обновление рабочей версии не запущено: {error}", { error: (e as Error).message }) }); + // PEP-154: the person pressed a button and gets an answer, but never the text of an exception. + const why = await platformFailure(db, e, { service: "runner", where: `deploy prod ${project.key}` }); + await askPmProject(db, project, { kind: "attention", text: why ? m("Обновление рабочей версии не запущено: {error}", { error: why }) : m("Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.") }); } return true; } diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts index c355aaa6..68f87e46 100644 --- a/packages/runner/src/hook.ts +++ b/packages/runner/src/hook.ts @@ -34,6 +34,9 @@ import { logSessionEvent, peppaInputSentAt, pendingSessionQuestions, + isServiceInput, + userText, + reportPlatformError, raiseSessionQuestion, releaseHookQuestion, updateSession, @@ -197,6 +200,8 @@ const NUDGE = (key: string) => */ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise { await logSessionEvent(db, s, "turn_end", { text }); + // PEP-154: a reply that is service text only (a tag block, command output) says nothing to a person. + if (text && !userText(text)) text = null; // PEP-43: the story's budget is spent — the PM was asked; don't push the agent further. if (s.taskId && (await getBudgetState(db, s.taskId))) { await logSessionEvent(db, s, "budget_hold", {}); @@ -326,9 +331,17 @@ async function handle(event: string, input: HookInput): Promise { // pending for this session is now answered — except hook-held questions, and, // when Peppa typed this text itself, questions raised after it did (e.g. a CI // failure pasted while the PM is being asked about the next one). + // PEP-154: a service notification of the CLI (…) is nobody's answer — + // the questions stay open and the nudge counter keeps counting. + if (isServiceInput(input.prompt ?? "")) { + await updateSession(db, s.id, { status: "running", lastActivityAt: now }); + break; + } const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null; for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) { - await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); + // What Peppa typed itself (a red check, «лимит сброшен») makes earlier messages stale; it is not an answer. + if (sentAt) await answerQuestion(db, q.id, m("(неактуально: агент продолжил работу)"), "system").catch(() => {}); + else await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); } await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now }); break; @@ -425,5 +438,8 @@ try { else await handle(event, raw ? (JSON.parse(raw) as HookInput) : {}); } catch (e) { log(`${event} session=${process.env.PEPPA_SESSION_ID}: ${(e as Error).stack ?? e}`); + // PEP-154: the hook's own failure goes to the error tracker, never to the project owner. + // A clear refusal (PeppaError) is not a failure of the platform. + if ((e as Error)?.name !== "PeppaError") await reportPlatformError(createDb(), e, { service: "hook", where: event }).catch(() => {}); } process.exit(0); diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 61a699a8..d3cff078 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -16,6 +16,7 @@ import { PeppaError, projectAudience, raiseSessionQuestion, + platformFailure, touchQuestion, sendProjectMessage, setSetting, @@ -184,7 +185,9 @@ export async function restartTick(db: Db, o: { now: Date; cfg: WatchdogSettings; o.log(`#${s.id} ${s.taskKey ?? ""}: restarted automatically (${restarts.length}/${o.cfg.restartMax})`); } catch (e) { await logSessionEvent(db, s, "restart_failed", { error: (e as Error).message }); - await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: (e as Error).message })); + // PEP-154: a platform error goes to the superadmins and the error tracker, not to the owner. + const why = await platformFailure(db, e, { service: "watchdog", where: `restart ${s.taskKey ?? `#${s.id}`}`, log: o.log, now: o.now }); + if (why) await raiseSessionQuestion(db, s, "attention", m("{who}: не удалось перезапустить автоматически — {error}", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), error: why })); } } } diff --git a/packages/shared/src/i18n/en/runner.ts b/packages/shared/src/i18n/en/runner.ts index 09db54cf..a26831fb 100644 --- a/packages/shared/src/i18n/en/runner.ts +++ b/packages/shared/src/i18n/en/runner.ts @@ -329,6 +329,10 @@ export const runner: Dict = { "Не удалось подготовить рабочую копию для агента: {error}": "Could not prepare a working copy for the agent: {error}", "(неактуально: агент перезапущен)": "(no longer relevant: the agent was restarted)", "(неактуально: агент остановлен)": "(no longer relevant: the agent was stopped)", + "(неактуально: агент продолжил работу)": "(no longer relevant: the agent went on working)", + "Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "The update of the live version did not start. We are already looking into it — please try again later.", + "⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} was not started. We are already looking into it — please try again later.", + "⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Failure in Peppa FACTORY ({where}): {error}", // Sharing and visibility "Участниками управляет только владелец проекта": "Only the project owner manages members", diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts index 8a984261..53e4fe96 100644 --- a/packages/shared/src/i18n/en/story.ts +++ b/packages/shared/src/i18n/en/story.ts @@ -236,6 +236,17 @@ export const story: Dict = { инструмент: "tool", "Агент ещё ничего не сделал — шаги появятся здесь.": "The agent hasn't done anything yet — steps will appear here.", "Шагов не записано.": "No steps recorded.", + "Этот агент не сообщает о шагах.": "This agent does not report its steps.", + "Выполняет действие в проекте": "Doing something in the project", + "Запускает проверки": "Running the checks", + "Вносит изменения": "Making changes", + "Изучает проект": "Studying the project", + "Ищет нужное в проекте": "Searching the project", + "Смотрит в интернете": "Looking it up on the web", + "Поручил часть работы помощнику": "Handed part of the work to a helper", + "Сверяется с задачей": "Checking against the task", + "Работает над задачей": "Working on the task", + "Подробнее: исходный текст": "Details: the original text", "Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "This agent doesn't report steps (no hooks) — watch the terminal.", "Шаги агента": "Agent steps", ошибка: "error", diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts index 07de1745..c6c329cd 100644 --- a/packages/shared/src/i18n/kk/runner.ts +++ b/packages/shared/src/i18n/kk/runner.ts @@ -252,6 +252,10 @@ export const runner: Dict = { "Не удалось подготовить рабочую копию для агента: {error}": "Агентке жұмыс көшірмесін дайындау мүмкін болмады: {error}", "(неактуально: агент перезапущен)": "(өзекті емес: агент қайта іске қосылды)", "(неактуально: агент остановлен)": "(өзекті емес: агент тоқтатылды)", + "(неактуально: агент продолжил работу)": "(өзекті емес: агент жұмысын жалғастырды)", + "Обновление рабочей версии не запущено. Мы уже разбираемся — попробуйте ещё раз позже.": "Жұмыс нұсқасын жаңарту іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.", + "⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.": "⚠️ {key} іске қосылмады. Біз себебін анықтап жатырмыз — кейінірек қайталап көріңіз.", + "⚠️ Сбой в Peppa FACTORY ({where}): {error}": "⚠️ Peppa FACTORY жүйесінде ақау ({where}): {error}", "Участниками управляет только владелец проекта": "Қатысушыларды тек жоба иесі басқарады", "Укажите логин участника": "Қатысушының логинін көрсетіңіз", "Нет доступа к коду проекта — войдите заново": "Жоба кодына қолжетімділік жоқ — қайта кіріңіз", diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts index 6735bea4..57b9a8ea 100644 --- a/packages/shared/src/i18n/kk/story.ts +++ b/packages/shared/src/i18n/kk/story.ts @@ -220,6 +220,17 @@ export const story: Dict = { "инструмент": "құрал", "Агент ещё ничего не сделал — шаги появятся здесь.": "Агент әлі ештеңе жасаған жоқ — қадамдар осында пайда болады.", "Шагов не записано.": "Қадамдар жазылмаған.", + "Этот агент не сообщает о шагах.": "Бұл агент қадамдары туралы хабарламайды.", + "Выполняет действие в проекте": "Жобада әрекет орындап жатыр", + "Запускает проверки": "Тексерулерді іске қосып жатыр", + "Вносит изменения": "Өзгерістер енгізіп жатыр", + "Изучает проект": "Жобаны зерттеп жатыр", + "Ищет нужное в проекте": "Жобадан керегін іздеп жатыр", + "Смотрит в интернете": "Интернеттен қарап жатыр", + "Поручил часть работы помощнику": "Жұмыстың бір бөлігін көмекшіге тапсырды", + "Сверяется с задачей": "Тапсырмамен салыстырып жатыр", + "Работает над задачей": "Тапсырмамен жұмыс істеп жатыр", + "Подробнее: исходный текст": "Толығырақ: бастапқы мәтін", "Этот агент не сообщает шаги (нет хуков) — смотри терминал.": "Бұл агент қадамдарын хабарламайды (хуктар жоқ) — терминалды қараңыз.", "Шаги агента": "Агент қадамдары", "ошибка": "қате", diff --git a/packages/testkit/test/service-text.test.ts b/packages/testkit/test/service-text.test.ts new file mode 100644 index 00000000..2f761c0b --- /dev/null +++ b/packages/testkit/test/service-text.test.ts @@ -0,0 +1,229 @@ +// PEP-154: service text never reaches the person. Blocks like , command +// output, shell prompts, stack traces and absolute paths are cut out of messages and answers; +// an exception inside Peppa goes to the superadmins and the error tracker, not to the owner. +// Tests are named after the spec scenarios. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +// helpers must load first: it sets the isolated test env that runner modules read on load. +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockBugsink } from "../src/mock-bugsink.ts"; +import { projects, questions, sessions, telegramOutbox, users } from "@peppa/db"; +import { and, eq, isNull, sql } from "drizzle-orm"; + +const { createBugsinkClient } = await import("@peppa/bugsink"); +const { renderQuestion, renderAnswered } = await import("@peppa/bot/render"); + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../.."); +const bugsink = await new MockBugsink().start(); +process.env.BUGSINK_URL = bugsink.url; + +const NOTIFICATION = "\nb7f3\n/private/tmp/claude-501/tasks/b7f3.output\ncompleted\nBackground command finished\n"; +const TERMINAL_REPLY = [ + "Проверки не прошли, нужен ваш ответ.", + "", + "$ pnpm test", + "```", + "FAIL src/app.test.ts", + " ● оплата › считает сумму", + "```", + "TypeError: total is not a function", + " at sum (/Users/telecom/Dev/pay/src/app.ts:12:5)", + " at async run (node:internal/process/task_queues:95:5)", + "Файл: /Users/telecom/Dev/pay/src/app.ts", + "\x1b[31mЧто выбрать: чинить сейчас или отложить?\x1b[0m", +].join("\n"); + +let owner: Awaited>; +let admin: Awaited>; +let seq = 0; + +/** A story at work with its agent's session (no tmux: messages are raised as the hook does). */ +async function story() { + const key = `F${String.fromCharCode(65 + seq++)}`; + const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: `Проект ${key}`, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: owner.id }); + const created = await core.createTask(db, { projectId: p.id, title: "Оплата картой" }); + await core.updateTask(db, await core.resolveTask(db, created.key), { status: "in_progress" }); + const [s] = await db.insert(sessions).values({ projectId: p.id, taskId: created.task.id, tmuxName: `mock-${key}`, status: "waiting_input" }).returning(); + return { + project: p, + key: created.key, + taskId: created.task.id, + sessionId: s!.id, + session: () => core.getSession(db, s!.id), + ref: () => core.resolveTask(db, created.key), + asked: () => db.select().from(questions).where(eq(questions.taskId, created.task.id)).orderBy(questions.id), + thread: async () => { + await core.syncChats(db); + return core.chatMessagesView(db, (await core.ensureProjectChat(db, p.id)).id, { threadKey: `task:${created.task.id}` }); + }, + }; +} + +/** Runs the real peppa-hook like Claude Code does: payload on stdin. */ +function hook(event: string, payload: unknown, sessionId: number): Promise { + return new Promise((done) => { + const p = spawn(join(ROOT, "packages/runner/bin/peppa-hook"), [event], { env: { ...process.env, PEPPA_SESSION_ID: String(sessionId), PEPPA_GENERATION: "0" }, stdio: ["pipe", "ignore", "inherit"] }); + p.on("close", (code) => { + assert.equal(code, 0); + done(); + }); + p.stdin.end(JSON.stringify(payload)); + }); +} + +const outboxTo = async (chatId: number) => + (await db.select().from(telegramOutbox).where(sql`cast(json_extract(${telegramOutbox.params}, '$.chat_id') as text) = ${String(chatId)}`).orderBy(telegramOutbox.id)).map((r) => String(r.params.text)); +const openOf = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt))); + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 541, login: "mock-owner" }, { access_token: "x" }); + admin = await core.upsertUserFromGitea(db, { id: 542, login: "mock-admin" }, { access_token: "x" }); + await db.update(users).set({ telegramChatId: 5410, telegramUserId: 5410 }).where(eq(users.id, owner.id)); + await db.update(users).set({ telegramChatId: 5420, telegramUserId: 5420 }).where(eq(users.id, admin.id)); + await core.setPlatformAdmins(db, [admin.login]); +}); +after(async () => { + await bugsink.stop(); + await teardown(); +}); + +describe("PEP-154: фильтр служебного текста", () => { + test("userText: блоки, ANSI, вывод команд, приглашение оболочки, трассировка и пути убираются; адреса остаются", () => { + const out = core.userText(TERMINAL_REPLY); + assert.equal(out, "Проверки не прошли, нужен ваш ответ.\n\nФайл:\nЧто выбрать: чинить сейчас или отложить?"); + assert.equal(core.userText(out), out, "idempotent"); + assert.equal(core.userText(NOTIFICATION), ""); + assert.equal(core.userText("Готово. не для людей Результат: https://git.example.com/pay/pulls/7"), "Готово. Результат: https://git.example.com/pay/pulls/7"); + assert.equal(core.userText("Поправил `packages/core/src/chats.ts` и C:\\Users\\pm\\app.ts, проверил."), "Поправил и, проверил."); + // A person's own words are not rewritten: only what is certainly service text. + assert.equal(core.stripServiceBlocks("Синий, как в /Users/me/макет.png"), "Синий, как в /Users/me/макет.png"); + assert.equal(core.isServiceInput(NOTIFICATION), true); + assert.equal(core.isServiceInput("Синий"), false); + }); + + test("Реплика агента с выводом терминала и путём", async () => { + const st = await story(); + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + // Two automatic nudges first (the story is at work), then the message for the person. + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + await hook("stop", { last_assistant_message: TERMINAL_REPLY }, st.sessionId); + const [q] = await st.asked(); + assert.ok(q, "the owner got a message"); + assert.match(q.text, /Проверки не прошли, нужен ваш ответ\./); + assert.match(q.text, /чинить сейчас или отложить/); + for (const bad of ["/Users/", "pnpm test", "FAIL", "TypeError", "at sum", "\x1b", "```"]) assert.ok(!q.text.includes(bad), `no «${bad}» in the message`); + const thread = await st.thread(); + assert.ok(thread.some((m) => m.text.includes("Проверки не прошли"))); + assert.ok(!thread.some((m) => m.text.includes("/Users/") || m.text.includes("pnpm test"))); + const tg = renderQuestion(q, { taskKey: st.key, taskTitle: "Оплата картой", taskStatus: "in_progress", session: await st.session(), webUrl: "http://peppa.test" }); + assert.ok(!tg.text.includes("/Users/") && !tg.text.includes("tmux attach"), "Telegram: no path, no terminal command"); + assert.ok(renderQuestion(q, { taskKey: st.key, taskTitle: null, session: await st.session(), webUrl: "http://peppa.test", engineer: true }).text.includes("tmux attach"), "«Инженер» keeps the terminal command"); + }); + + test("Исходный текст для инженера", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Нужен ваш ответ. Файл /Users/telecom/Dev/pay/src/app.ts не открывается."); + assert.ok(!q.text.includes("/Users/")); + assert.match((await core.questionDetails(db, q.id)) ?? "", /\/Users\/telecom\/Dev\/pay\/src\/app\.ts/); + const clean = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"] }); + assert.equal(await core.questionDetails(db, clean.id), null, "nothing was cut — nothing to keep"); + // A permission request keeps its command: that is what the person allows. + const perm = await core.raiseSessionQuestion(db, await st.session(), "permission", "Разрешить Bash: rm /Users/telecom/Dev/pay/tmp.txt", ["allow", "deny"]); + assert.match(perm.text, /\/Users\/telecom/); + }); + + test("От реплики ничего не осталось", async () => { + const st = await story(); + await assert.rejects(core.askPm(db, await st.ref(), { kind: "question", text: "только служебное" }), /служебный текст/); + assert.equal((await st.asked()).length, 0); + // The end of a turn with nothing for a person: the plain «агент ждёт» line, not the block. + for (let i = 0; i < 3; i++) await hook("stop", { last_assistant_message: NOTIFICATION }, st.sessionId); + const [q] = await st.asked(); + assert.equal(q?.text, "Агент закончил ход и ждёт вашего ответа."); + assert.equal(await core.addChatMessage(db, { chatId: (await core.ensureProjectChat(db, st.project.id)).id, kind: "event", authorKind: "agent", text: NOTIFICATION, dedupeKey: `mock:${st.key}` }), null); + }); +}); + +describe("PEP-154: ответом вопроса считается только ввод человека", () => { + test("Служебное уведомление в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: NOTIFICATION }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredAt, null, "the question stays open"); + assert.equal(after.answer, null); + const thread = await st.thread(); + assert.ok(!thread.some((m) => m.text.includes("task-notification") || (m.question?.answer ?? "").includes("task-notification")), "not in the chat: neither text nor answer"); + // Even if such a block came glued to a person's words, only the words are the answer. + const answered = await core.answerQuestion(db, q.id, `Синий\n${NOTIFICATION}`, "terminal"); + assert.equal(answered.answer, "Синий"); + assert.ok(!renderAnswered("Вопрос", answered).includes("task-notification")); + await assert.rejects(core.answerQuestion(db, (await core.askPm(db, await st.ref(), { kind: "question", text: "А размер?", sessionId: st.sessionId })).id, NOTIFICATION, "web")); + }); + + test("Человек печатает в терминале", async () => { + const st = await story(); + const q = await core.askPm(db, await st.ref(), { kind: "question", text: "Какой цвет кнопки?", sessionId: st.sessionId }); + await hook("prompt", { prompt: "Синий" }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answer, "Синий"); + assert.equal(after.answeredVia, "terminal"); + }); + + test("Peppa сама пишет агенту", async () => { + const st = await story(); + const q = await core.raiseSessionQuestion(db, await st.session(), "attention", "Агент закончил ход и ждёт вашего ответа."); + const report = "Проверки PR красные: test\n$ pnpm test\nFAIL src/app.test.ts"; + await core.logSessionEvent(db, await st.session(), "input_sent", { text: report }); + await hook("prompt", { prompt: report }, st.sessionId); + const after = await core.getQuestion(db, q.id); + assert.equal(after.answeredVia, "system", "closed as stale, not answered"); + assert.ok(!(after.answer ?? "").includes("FAIL")); + }); +}); + +describe("PEP-154: ошибки платформы не идут владельцу проекта", () => { + const NO_QUIET = { quietFrom: null, quietTo: null }; + const autonomy = (now = new Date()) => runner.autonomyTick(db, { now, log: () => {} }); + + test("Диспетчер упал с исключением; та же ошибка повторяется", async () => { + // The platform project is connected to the error tracker (mock). + const platform = await project({ turns: [] }); + process.env.PEPPA_PLATFORM_KEY = platform.key; + core.resetErrorReporting(); + const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); + await runner.connectErrorTracking(db, await core.getProject(db, platform.key), client, "http://peppa.test"); + + const tp = await project({ turns: [] }); + const p = await core.getProject(db, tp.key); + await db.update(projects).set({ ownerId: owner.id }).where(eq(projects.id, p.id)); + await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET }); + // The start blows up inside Peppa: the sessions table is gone for one tick. + const now = new Date(); + const ingested = bugsink.ingested.length; + db.run(sql`ALTER TABLE runner_tasks RENAME TO runner_tasks_x`); + try { + await autonomy(now); + assert.equal((await openOf(p.id)).length, 0, "the owner gets no message"); + assert.equal((await outboxTo(5410)).length, 0, "nothing for the owner in Telegram"); + const alerts = (await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")); + assert.equal(alerts.length, 1, "the superadmin gets one message"); + assert.ok(bugsink.ingested.length > ingested, "the error tracker has the exception"); + // Ten minutes later the same error: no second message. + await autonomy(new Date(now.getTime() + 10 * 60_000)); + assert.equal((await outboxTo(5420)).filter((t) => t.includes("Сбой в Peppa FACTORY")).length, 1); + assert.equal((await openOf(p.id)).length, 0); + } finally { + db.run(sql`ALTER TABLE runner_tasks_x RENAME TO runner_tasks`); + } + }); + + test("Понятный отказ", async () => { + assert.equal(await core.platformFailure(db, new core.PeppaError("Подписка не выбрана — выберите её в настройках проекта."), { service: "watchdog", where: "dispatch PAY-7" }), "Подписка не выбрана — выберите её в настройках проекта."); + assert.equal(await core.platformFailure(db, new Error("SQLITE_ERROR: no such column: x"), { service: "watchdog", where: "dispatch PAY-7" }), null); + }); +});