PEP-140: foreign text put into the factory's messages is marked free text (titles, names, reviewer's and agent's words, outside reasons)

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Асель 2026-11-16 10:45:08 +05:00
parent f3ab7ee6f2
commit 2531e0ee7f
24 changed files with 85 additions and 74 deletions

View File

@ -545,7 +545,7 @@ export function createBot(o: BotOptions) {
// ── stories from messages (PEP-45) ─────────────────────────────────────────────
const cancelRow = (d: Draft): InlineButton[] => [{ text: tr("✖️ Отмена"), callback_data: `d:${d.id}:x` }];
const rows = (buttons: InlineButton[], per = 2) => buttons.reduce<InlineButton[][]>((acc, b, i) => (i % per ? acc[acc.length - 1]!.push(b) : acc.push([b]), acc), []);
const storyLine = (d: Draft) => `«${esc(splitStory(d.text).title)}»`;
const storyLine = (d: Draft) => `«${asIs(esc(splitStory(d.text).title))}»`;
/** Send (or, for a button press, edit in place) a bot message with buttons. */
async function show(chatId: number, text: string, buttons: InlineButton[][], editId?: number) {
@ -567,7 +567,7 @@ export function createBot(o: BotOptions) {
async function askEpic(d: Draft, project: Project, editId?: number) {
const epics = (await listGoals(db, project.id)).slice(0, 10);
const buttons = epics.length
? [...epics.map((g) => ({ text: g.title.slice(0, 40), callback_data: `d:${d.id}:g:${g.id}` })), { text: tr("Без эпика"), callback_data: `d:${d.id}:g:0` }]
? [...epics.map((g) => ({ text: asIs(g.title.slice(0, 40)), callback_data: `d:${d.id}:g:${g.id}` })), { text: tr("Без эпика"), callback_data: `d:${d.id}:g:0` }]
: [{ text: tr("✅ Создать в {key}", { key: project.key }), callback_data: `d:${d.id}:g:0` }];
const text = tr("📝 Новая задача в <b>{key}</b>: {title}", { key: esc(project.key), title: storyLine(d) }) + (epics.length ? "\n" + tr("Эпик?") : "");
await show(d.chatId, text, [...rows(buttons), cancelRow(d)], editId);
@ -602,7 +602,7 @@ export function createBot(o: BotOptions) {
return reply(m.chat.id, tr("Не получилось расшифровать голосовое. Напишите задачу текстом."), m.message_id).then(() => null);
}
if (!text) return reply(m.chat.id, tr("Не разобрал ни слова. Попробуйте ещё раз или напишите текстом."), m.message_id).then(() => null);
await reply(m.chat.id, tr("🎙 Расслышал: «{text}»", { text: esc(text) }), m.message_id);
await reply(m.chat.id, tr("🎙 Расслышал: «{text}»", { text: asIs(esc(text)) }), m.message_id);
return text;
}
@ -709,7 +709,7 @@ export function createBot(o: BotOptions) {
if (!t || !(await canAccess(user, t.projectId))) return tr("Задача не найдена");
const [project] = await db.select().from(projects).where(eq(projects.id, t.projectId));
const ref = { project: project!, task: t, key: formatTaskKey(project!.key, t.number) };
const head = `📥 ${esc(ref.key)}: ${esc(t.title)}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
const head = `📥 ${esc(ref.key)}: ${asIs(esc(t.title))}\n${esc(o.webUrl)}/t/${esc(ref.key)}`;
if (parts[2] === "keep") {
await show(chatId, head + "\n" + tr("В бэклоге."), [], msgId);
return tr("Оставил в бэклоге");
@ -756,7 +756,7 @@ export function createBot(o: BotOptions) {
await dropDraft(db, d.id);
await show(
chatId,
[tr("📥 Создал <b>{key}</b>: {title}", { key: esc(ref.key), title: esc(title) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`, tr("Взять в работу сейчас?")].join("\n"),
[tr("📥 Создал <b>{key}</b>: {title}", { key: esc(ref.key), title: asIs(esc(title)) }), `${esc(o.webUrl)}/t/${esc(ref.key)}`, tr("Взять в работу сейчас?")].join("\n"),
[[{ text: tr("▶️ Взять в работу"), callback_data: `t:${ref.task.id}:start` }, { text: tr("Оставить в бэклоге"), callback_data: `t:${ref.task.id}:keep` }]],
msgId,
);

View File

@ -5,6 +5,7 @@ import { activeSessions, inbox } from "@/lib/queries";
import { SESSION_STATUS, TONE_BG } from "@/lib/status";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { questionText } from "@peppa/core";
/** Default right panel: what waits for the PM and what is running now. */
export async function ActivityAside({ questions = true }: { questions?: boolean }) {
@ -22,7 +23,7 @@ export async function ActivityAside({ questions = true }: { questions?: boolean
items.slice(0, 6).map((q) => (
<Link key={q.id} href={q.taskKey ? `/t/${q.taskKey}` : "/"} className="block rounded-md border border-primary/25 bg-primary/5 px-3 py-2 text-sm text-foreground hover:border-primary/50 hover:no-underline">
<span className="font-mono text-xs text-primary">{q.taskKey ?? `#${q.id}`}</span>{" "}
<span className="line-clamp-2 text-muted-foreground">{q.text}</span>
<span className="line-clamp-2 text-muted-foreground">{t.text(questionText(q))}</span>
</Link>
))
)}

View File

@ -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, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
import { questionIsFreeText, questionState, questionText, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
import { db } from "@/lib/db";
import { SubscriptionName } from "@/components/SubscriptionName";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
@ -15,7 +15,7 @@ import { RunnerTerminal } from "@/components/RunnerTerminal";
import { SessionUsageLine } from "@/components/Accounting";
import { cn } from "@/lib/utils";
import { getT } from "@/lib/i18n";
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
const KIND = {
approval: { label: m("Одобрение плана"), icon: FileCheck, border: "border-l-primary" },
@ -59,12 +59,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
<p className="m-0 text-sm">{t("Агенту нужно ваше разрешение, чтобы продолжить работу.")}</p>
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground">{t("Подробнее")}</summary>
<p className="m-0 mt-1 max-h-40 overflow-auto whitespace-pre-wrap">{t.text(q.text)}</p>
<p className="m-0 mt-1 max-h-40 overflow-auto whitespace-pre-wrap">{t.text(questionText(q))}</p>
{!!state?.repeats && <p className="m-0 mt-1 text-xs text-muted-foreground">{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}</p>}
</details>
</>
) : (
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{t.text(q.text)}</p>
<p className={cn("m-0 overflow-auto text-sm whitespace-pre-wrap", compact ? "max-h-40" : "max-h-72")}>{t.text(questionText(q))}</p>
)}
{!!state?.repeats && !(plain && q.kind === "permission") && (
<details className="text-xs text-muted-foreground">
@ -94,7 +94,7 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
{review && <Button name="choice" value="__accept" variant="default" size="sm">{t("Принять")}</Button>}
{/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */}
{(q.options ?? []).map((o) => (
<Button key={o} name="choice" value={o} size="sm" variant={o === q.defaultOption ? "default" : undefined} data-default-option={o === q.defaultOption ? "" : undefined}>{t.text(o)}</Button>
<Button key={o} name="choice" value={o} size="sm" variant={o === q.defaultOption ? "default" : undefined} data-default-option={o === q.defaultOption ? "" : undefined}>{t.text(questionIsFreeText(q) ? asIs(o) : o)}</Button>
))}
</div>
{q.defaultOption && <p className="m-0 text-xs text-muted-foreground">{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}</p>}

View File

@ -81,6 +81,7 @@ import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, pl
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { loadEnv } from "@peppa/shared";
import { stripAsIs } from "@peppa/shared/i18n";
const USAGE = `peppa — Peppa software factory CLI
@ -478,7 +479,7 @@ async function main(): Promise<void> {
}
case "q list": {
const projectId = args[0] ?? here ? (await getProject(db, (args[0] ?? here)!)).id : undefined;
for (const q of await pendingQuestions(db, projectId)) console.log(`#${q.id} [${q.kind}] task=${q.taskId ?? "-"} ${q.text}`);
for (const q of await pendingQuestions(db, projectId)) console.log(`#${q.id} [${q.kind}] task=${q.taskId ?? "-"} ${stripAsIs(q.text)}`);
break;
}
case "q answer": {

View File

@ -134,7 +134,7 @@ export async function threadTitle(db: Db, key: string): Promise<string | null> {
}
if (kind === "incident") {
const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id));
return i ? tr("Ошибка: {title}", { title: i.title }) : null;
return i ? tr("Ошибка: {title}", { title: asIs(i.title) }) : null;
}
if (kind === "release") {
const [r] = await db.select({ env: releases.env, createdAt: releases.createdAt }).from(releases).where(eq(releases.id, id));
@ -416,7 +416,7 @@ const INCIDENT_RU: Record<string, string> = {
/** "🐞 <status>: <title>[\n<culprit>][ · <env>][ · N раз]". */
function incidentText(i: { status: string; title: string; culprit: string | null; environment: string | null; events: number }): string {
const base = `${tr("🐞 {status}: {title}", { status: INCIDENT_RU[i.status] ?? i.status, title: cut(i.title, 300) })}${i.culprit ? `\n${cut(i.culprit, 200)}` : ""}${i.environment ? ` · ${i.environment}` : ""}`;
const base = `${tr("🐞 {status}: {title}", { status: INCIDENT_RU[i.status] ?? i.status, title: asIs(cut(i.title, 300)) })}${i.culprit ? `\n${asIs(cut(i.culprit, 200))}` : ""}${i.environment ? ` · ${i.environment}` : ""}`;
return i.events > 1 ? tr("{text} · {n} раз", { text: base, n: i.events }) : base;
}
@ -543,7 +543,7 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
threadKey: `release:${r.id}`,
kind: "event",
important: r.env !== "preview" || r.status === "failed" || r.status === "rolled_back",
text: `${RELEASE_ICON[r.status] ?? "•"} ${ENV_RU[r.env] ?? r.env}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${cut(r.reason, 300)}` : ""}`,
text: `${RELEASE_ICON[r.status] ?? "•"} ${ENV_RU[r.env] ?? r.env}: ${RELEASE_RU[r.status] ?? r.status}${tasksIn}${r.reason ? `\n${asIs(cut(r.reason, 300))}` : ""}`,
url: r.host ? `https://${r.host}` : r.runUrl,
dedupeKey: `release:${r.id}:${r.status}`,
});

View File

@ -1,7 +1,7 @@
// Daily digest (PEP-29): per user, per project — done in the last day, in progress, in
// review, waiting for the user, stuck, limits. Sent from the watchdog tick at the user's
// time; /digest in the bot renders it on demand.
import { m as tr } from "@peppa/shared/i18n";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { projects, pushSubscriptions, questions, sessions, tasks, users, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { and, asc, gte, inArray, isNull, notInArray } from "drizzle-orm";
@ -92,7 +92,7 @@ const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replac
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
function taskList(webUrl: string, items: TaskLine[], max = 8): string {
const shown = items.slice(0, max).map((t) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a> ${esc(clip(t.title, 60))}`);
const shown = items.slice(0, max).map((t) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a> ${asIs(esc(clip(t.title, 60)))}`);
if (items.length > max) shown.push(`…${tr("и ещё {n}", { n: items.length - max })}`);
return shown.map((s) => ` • ${s}`).join("\n");
}
@ -105,7 +105,7 @@ export function renderDigest(d: Digest, o: { webUrl: string; title?: string }):
return lines.join("\n");
}
for (const p of d.projects) {
lines.push("", `<b>${esc(p.name)}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">${tr("доска")}</a>`);
lines.push("", `<b>${asIs(esc(p.name))}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">${tr("доска")}</a>`);
if (p.done.length) lines.push(tr("✅ Сделано: {n}", { n: p.done.length }), taskList(o.webUrl, p.done));
if (p.inProgress.length) lines.push(tr("🔨 В работе: {n}", { n: p.inProgress.length }), taskList(o.webUrl, p.inProgress, 5));
if (p.review.length) lines.push(tr("👀 На ревью: {n}", { n: p.review.length }), taskList(o.webUrl, p.review));

View File

@ -1,7 +1,7 @@
// Incidents (PEP-58): Bugsink issues seen in Peppa, the project's incident policy settings,
// bug tasks made from incidents and their Telegram messages. The policy itself (which may
// start a runner) is applied in runner/incidents.ts.
import { m as tr } from "@peppa/shared/i18n";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { randomBytes } from "node:crypto";
import type { BugsinkIssue } from "@peppa/bugsink";
import { errorSources, incidentPolicies, incidents, incidentSettings, incidentStatuses, projects, telegramOutbox, type Db, type IncidentPolicy } from "@peppa/db";
@ -297,14 +297,14 @@ export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i:
const head = m.kind === "regressed" ? `🔁 ${tr("Ошибка вернулась ({source}, {env})", where)}` : `🐞 ${tr("Новая ошибка ({source}, {env})", where)}`;
const lines = [
`<b>${esc(project.key)}</b> · ${head}`,
`<b>${esc(clip(i.title, 300))}</b>`,
[i.culprit && `📍 ${esc(i.culprit)}`, i.lastRelease && tr("версия {release}", { release: esc(i.lastRelease) }), tr("событий: {n}", { n: i.events })].filter(Boolean).join(" · "),
`<b>${asIs(esc(clip(i.title, 300)))}</b>`,
[i.culprit && `📍 ${asIs(esc(i.culprit))}`, i.lastRelease && tr("версия {release}", { release: esc(i.lastRelease) }), tr("событий: {n}", { n: i.events })].filter(Boolean).join(" · "),
];
if (i.url) lines.push(`<a href="${esc(i.url)}">${tr("Подробности ошибки")}</a>`);
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
if (m.kind === "task") {
lines.push("", m.started ? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) }) : tr("📥 Задача в бэклоге: {link}", { link: taskLink(m.task) }));
if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: esc(clip(m.reason, 500)) }));
if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: asIs(esc(clip(m.reason, 500))) }));
} else if (m.kind === "ask") {
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
lines.push("", tr("Что делаем?"));
@ -335,8 +335,8 @@ export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessag
pushKey: `inc:${i.id}:${kind}:r${i.regressions}:u${u.id}`,
telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) } },
push: {
title: m.kind === "regressed" ? tr("Ошибка вернулась в {project}", { project: project.name }) : tr("Ошибка в {project}", { project: project.name }),
body: clip(i.title, 200),
title: m.kind === "regressed" ? tr("Ошибка вернулась в {project}", { project: asIs(project.name) }) : tr("Ошибка в {project}", { project: asIs(project.name) }),
body: asIs(clip(i.title, 200)),
url: taskKey ? `/t/${taskKey}` : `/p/${project.key}`,
tag: `inc:${i.id}`,
},

View File

@ -2,7 +2,7 @@
// gets platform events (releases, service outages, restarts) and the daily platform digest;
// paired users get the platform digest too (notification event «platform»). No migrations:
// everything lives in `settings`; messages go through the Telegram outbox with retries.
import { m as tr } from "@peppa/shared/i18n";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { projects, questions, sessions, tasks, users, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { and, asc, eq, gte, isNotNull, isNull, notInArray } from "drizzle-orm";
@ -231,7 +231,7 @@ async function storyTitles(db: Db, keys: string[]): Promise<Map<string, string>>
}
function storyLine(webUrl: string, key: string, title: string | undefined): string {
return ` • <a href="${esc(`${webUrl}/t/${key}`)}">${esc(key)}</a>${title ? ` ${esc(title.length > 70 ? `${title.slice(0, 70)}…` : title)}` : ""}`;
return ` • <a href="${esc(`${webUrl}/t/${key}`)}">${esc(key)}</a>${title ? ` ${asIs(esc(title.length > 70 ? `${title.slice(0, 70)}…` : title))}` : ""}`;
}
/**

View File

@ -9,7 +9,7 @@ import { eq } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { secretNameError } from "./secrets.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { m as tr } from "@peppa/shared/i18n";
import { asIs, m as tr } from "@peppa/shared/i18n";
export type NeedSource = "agent" | "product";
@ -133,10 +133,11 @@ export function needsText(needs: ProductNeed[], webUrl: string, projectKey: stri
}
/** One line for messages and the card: «нужно: Ключ Claude API, Аккаунт Stripe». */
export const needsLine = (needs: Pick<ProductNeed, "title">[]) => needs.map((n) => n.title).join(", ");
/** `mark` — `asIs` when the line goes into a message that is translated later (PEP-140). */
export const needsLine = (needs: Pick<ProductNeed, "title">[], mark: (s: string) => string = (s) => s) => needs.map((n) => mark(n.title)).join(", ");
/** A line for «готово к ревью»: the story is done, but the product is not real yet ("" when it is). */
export async function demoNote(db: Db, projectId: number, projectKey: string, webUrl = process.env.PEPPA_WEB_URL ?? ""): Promise<string> {
const open = await openNeeds(db, projectId).catch(() => []);
return open.length ? `${tr("⚠️ Продукт пока работает в демо-режиме. Нужно от вас: {needs}", { needs: needsLine(open) })}\n${tr("Вставить можно в карточке «Ваш продукт»: {url}", { url: `${webUrl}/p/${projectKey}` })}` : "";
return open.length ? `${tr("⚠️ Продукт пока работает в демо-режиме. Нужно от вас: {needs}", { needs: needsLine(open, asIs) })}\n${tr("Вставить можно в карточке «Ваш продукт»: {url}", { url: `${webUrl}/p/${projectKey}` })}` : "";
}

View File

@ -1,6 +1,6 @@
// Reviewer agent of a project (PEP-26): settings, the review queue and what the task card shows.
// Running the reviewer itself lives in the runner (runner/reviewer.ts).
import { m as tr } from "@peppa/shared/i18n";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { codeReviews, reviewSettings, type Db, type ReviewFinding } from "@peppa/db";
import { and, count, desc, eq, inArray, isNull, lt, or, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
@ -112,13 +112,13 @@ export function formatFindings(findings: ReviewFinding[]): string {
export function reviewLabel(r: CodeReview): string {
if (r.state === "queued" || r.state === "running") return tr("Ревьюер проверяет изменения…");
if (r.state === "error") return tr("Ревьюер не отработал: {error}", { error: r.error ?? tr("неизвестная ошибка") });
if (r.verdict === "ok") return r.summary ? tr("Ревьюер: ок — {summary}", { summary: r.summary }) : tr("Ревьюер: ок");
return r.summary ? tr("Ревьюер: замечаний {n} — {summary}", { n: r.findings.length, summary: r.summary }) : tr("Ревьюер: замечаний {n}", { n: r.findings.length });
if (r.verdict === "ok") return r.summary ? tr("Ревьюер: ок — {summary}", { summary: asIs(r.summary) }) : tr("Ревьюер: ок");
return r.summary ? tr("Ревьюер: замечаний {n} — {summary}", { n: r.findings.length, summary: asIs(r.summary) }) : tr("Ревьюер: замечаний {n}", { n: r.findings.length });
}
/** Text about the latest review for the PM's "ready for review" message (empty when there is none). */
export function reviewNote(r: CodeReview | null, limitReached = false): string {
if (!r || r.state === "queued" || r.state === "running") return "";
const head = limitReached ? tr("🔎 Ревьюер: лимит итераций исчерпан, последние замечания ({sha}):", { sha: r.sha.slice(0, 7) }) : `🔎 ${reviewLabel(r)}`;
return r.verdict === "changes" && r.findings.length ? `${head}\n${formatFindings(r.findings)}` : head;
return r.verdict === "changes" && r.findings.length ? `${head}\n${asIs(formatFindings(r.findings))}` : head;
}

View File

@ -2,7 +2,7 @@
// «шаг N из M», what is needed from them and what comes next. A pure function: the page gives
// it facts it has already read. All the words live here (docs/glossary.md), in one place.
// PEP-98: texts are dictionary keys (m); the page shows them through t.text.
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
export interface StoryProductInput {
status: string;
@ -84,7 +84,7 @@ export function storyProductView(i: StoryProductInput): StoryProductView {
if (i.status === "backlog") {
if (i.refining === "waiting") return { ...base, ...T.refiningWaiting, need: T.answerBelow };
if (i.refining) return { ...base, ...T.refining };
if (i.waitsFor?.length) return { ...base, now: T.waits.now(i.waitsFor.map((t) => `«${t}»`).join(", ")), next: T.waits.next };
if (i.waitsFor?.length) return { ...base, now: T.waits.now(i.waitsFor.map((t) => `«${asIs(t)}»`).join(", ")), next: T.waits.next };
return { ...base, ...T.backlog };
}
if (i.status === "awaiting_approval") return { ...base, ...T.approval };

View File

@ -1,4 +1,4 @@
import { m as tr } from "@peppa/shared/i18n";
import { asIs, m as tr } from "@peppa/shared/i18n";
import { actorColumns, currentActor, runAsActor } from "./actor.ts";
import { events, goals, projects, questions, taskStatus, tasks, type Db } from "@peppa/db";
import { formatTaskKey, parseTaskKey } from "@peppa/shared";
@ -334,6 +334,9 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
*/
export const questionIsFreeText = (q: Pick<Question, "kind" | "sessionId">): boolean => q.sessionId != null && (q.kind === "question" || q.kind === "approval");
/** The question's text for a translating reader (`t.text`, `localizeText`): an agent's own words are marked free text. */
export const questionText = (q: Pick<Question, "kind" | "sessionId" | "text">): string => (questionIsFreeText(q) ? asIs(q.text) : q.text);
/** 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[]; msgType?: MessageType | null }): Promise<Question> {
const [row] = await db.insert(questions).values({ projectId: project.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }).returning();

View File

@ -1,4 +1,5 @@
import { agentAutonomyNote, describeBudget, fmtCost, fmtHours, fmtPct, fmtTokens, PROVIDER_NAMES, type MetricsBucket, type ProjectMetrics, formatFindings, INCIDENT_STATUS_RU, reviewLabel, type Incident, type TaskDetails, type TaskStatus } from "@peppa/core";
import { stripAsIs } from "@peppa/shared/i18n";
const NEXT_STEP: Record<TaskStatus, string> = {
backlog: "Proposal (workflow openspec-propose) → update_task(status: proposing, openspec_change) → если нет архитектурных решений, сразу update_task(status: in_progress) и Apply в этом же ходе.",
@ -32,7 +33,7 @@ export function formatTask(d: TaskDetails): string {
lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`);
for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`);
if (d.review) {
lines.push(`- ${reviewLabel(d.review)} (коммит ${d.review.sha.slice(0, 7)})`);
lines.push(`- ${stripAsIs(reviewLabel(d.review))} (коммит ${d.review.sha.slice(0, 7)})`);
if (d.review.verdict === "changes") lines.push(formatFindings(d.review.findings).replace(/^/gm, " "));
}
// PEP-43/5: spend against the budget («≈» = estimated cost, «∞» = no limit).
@ -44,7 +45,7 @@ export function formatTask(d: TaskDetails): string {
if (d.questions.length) {
lines.push("", "## Вопросы к PM");
for (const q of d.questions) {
lines.push("", `- [${q.kind} #${q.id}] ${q.text}`, q.answer ? ` - Ответ (${q.answeredVia}): ${q.answer}` : " - _ожидает ответа_");
lines.push("", `- [${q.kind} #${q.id}] ${stripAsIs(q.text)}`, q.answer ? ` - Ответ (${q.answeredVia}): ${q.answer}` : " - _ожидает ответа_");
}
}
// PEP-112: what the owner still has to give before the product is real.
@ -86,7 +87,7 @@ export function formatIncident(i: Incident): string {
];
if (i.regressions) lines.push(`- Возвращалась: ${i.regressions} раз`);
if (i.resolvedAt) lines.push(`- Отмечена исправленной: ${fmt(i.resolvedAt)}${i.resolvedRelease ? ` в релизе ${i.resolvedRelease}` : ""}`);
if (i.decision) lines.push(`- Решение: ${i.decision} (${i.decidedBy})${i.decisionReason ? ` — ${i.decisionReason}` : ""}`);
if (i.decision) lines.push(`- Решение: ${i.decision} (${i.decidedBy})${i.decisionReason ? ` — ${stripAsIs(i.decisionReason)}` : ""}`);
if (i.url) lines.push(`- Bugsink: ${i.url}`);
lines.push("", "Верх стека (внутренний кадр первым):", "", "```", i.stack ?? "(стек недоступен — смотри Bugsink)", "```");
return lines.join("\n");

View File

@ -50,6 +50,7 @@ import {
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { stripAsIs } from "@peppa/shared/i18n";
import { applyPlan, archiveTask, planEpic, reorderBoardTask, type PlannedStory, currentReleases, deployProd, listReleases, decideIncident, resolveIncident, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
import { z } from "zod";
@ -518,7 +519,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
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(" | ")}` : ""}${q.defaultOption ? `\n default (the agent goes on with it meanwhile): ${q.defaultOption}` : ""}`;
return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${stripAsIs(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");
});

View File

@ -3,7 +3,7 @@
// is merged and the story closed. The PM hears when it closed, or once if it could not be done.
import { answerQuestion, askPm, clearPendingAccept, productLookLine, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef } from "@peppa/core";
import { questions, type Db } from "@peppa/db";
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { and, eq, isNull } from "drizzle-orm";
import { notifyPm } from "./autonomy.ts";
import { mergeOrCloseEmpty } from "./ci-feedback.ts";
@ -85,7 +85,7 @@ async function finish(db: Db, ref: TaskRef, log: (m: string) => void) {
for (const s of await listSessions(db, { taskId: ref.task.id })) if (s.workspacePath && ["done", "failed"].includes(s.status)) await cleanupWorktree(db, s).catch(() => {});
await syncWorkspace(db, ref).catch(() => {});
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_completed", payload: { pr: ref.task.prUrl } });
await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: ref.task.title })}${await productLookLine(db, ref.project.id)}`);
await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: asIs(ref.task.title) })}${await productLookLine(db, ref.project.id)}`);
log(`${ref.key}: accepted story merged and closed`);
}
@ -93,6 +93,6 @@ async function finish(db: Db, ref: TaskRef, log: (m: string) => void) {
async function fail(db: Db, ref: TaskRef, why: string, todo: string, log: (m: string) => void) {
await clearPendingAccept(db, ref.task.id);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_failed", payload: { why } });
await askPm(db, ref, { kind: "attention", text: m("⚠️ {key} «{title}»: не получилось довести приёмку до конца — {why}. {todo}", { key: ref.key, title: ref.task.title, why, todo }) });
await askPm(db, ref, { kind: "attention", text: m("⚠️ {key} «{title}»: не получилось довести приёмку до конца — {why}. {todo}", { key: ref.key, title: asIs(ref.task.title), why, todo }) });
log(`${ref.key}: accepted story not merged — ${why}`);
}

View File

@ -3,7 +3,7 @@
// - closing a story N hours after "ready for review" without comments (PEP-23);
// - the backlog dispatcher: either an agent works, or the PM got a push (PEP-24).
// Everything here is driven by core/autonomy.ts settings; "manual" (default) does nothing.
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import {
answerQuestion,
askPm,
@ -158,7 +158,7 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c
async function afterMerge(db: Db, ref: TaskRef, a: AutonomySettings, state: MergeState, log: (m: string) => void) {
if (a.close === "after_merge") {
await closeStory(db, ref, m("✅ Закрыто автоматически: изменения приняты"));
await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: ref.task.title })}${await productLookLine(db, ref.project.id)}`);
await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: asIs(ref.task.title) })}${await productLookLine(db, ref.project.id)}`);
log(`${ref.key}: closed after merge`);
return;
}
@ -207,7 +207,7 @@ async function autoCloseReviews(db: Db, project: Project, a: AutonomySettings, n
const r = await acceptTask(db, q.id, "system", m("✅ Принято автоматически: {n} ч без замечаний", { n: a.closeAfterHours }));
// PEP-127: not mergeable yet — remembered, `pendingAcceptTick` closes the story and tells the PM.
if (r.pending) continue;
await notifyPm(db, project.id, `auto:accepted:${q.id}`, m("🤖 {key} «{title}» закрыта автоматически: {n} ч без замечаний.", { key: ref.key, title: task.title, n: a.closeAfterHours }));
await notifyPm(db, project.id, `auto:accepted:${q.id}`, m("🤖 {key} «{title}» закрыта автоматически: {n} ч без замечаний.", { key: ref.key, title: asIs(task.title), n: a.closeAfterHours }));
log(`${ref.key}: closed after ${a.closeAfterHours}h`);
} catch (e) {
const key = `auto:closefail:${q.id}`;
@ -270,7 +270,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
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 })}`,
text: `${m("⚠️ {project}: диспетчер не смог запустить агента на {key} — {error}", { project: asIs(project.name), key: ref.key, error: (e as Error).message })}\n${m("Повторю через {n} мин.", { n: DISPATCH_RETRY_MS / 60_000 })}`,
});
log(`${ref.key}: dispatch failed — ${(e as Error).message}`);
return;
@ -284,7 +284,7 @@ async function dispatch(db: Db, project: Project, a: AutonomySettings, now: Date
await askPmProject(db, project, {
kind: "attention",
text: [
m("📭 {project}: все задачи сделаны, бэклог пуст — агентам нечего делать.", { project: project.name }),
m("📭 {project}: все задачи сделаны, бэклог пуст — агентам нечего делать.", { project: asIs(project.name) }),
...(product ? [product.live ? m("Ваш продукт: {url}", { url: product.url }) : m("Версия для проверки: {url}", { url: product.url })] : []),
m("Что дальше: опишите следующую задачу аналитику в чате проекта ({url}) или добавьте задачу на доске — агенты возьмут её сами.", { url: `${web}/chats/${project.key}` }),
].join("\n"),
@ -345,7 +345,7 @@ async function offerStory(db: Db, project: Project, task: Task, now: Date) {
const left = (await listTasks(db, { projectId: project.id, statuses: ["backlog"] })).length;
const q = await askPm(db, ref, {
kind: "question",
text: m("😴 {project}: агенты простаивают, в бэклоге {n}. Взять в работу {key} «{title}»?", { project: project.name, n: left, key: ref.key, title: task.title }),
text: m("😴 {project}: агенты простаивают, в бэклоге {n}. Взять в работу {key} «{title}»?", { project: asIs(project.name), n: left, key: ref.key, title: asIs(task.title) }),
options: [`${IDLE_TAKE} ${ref.key}`, IDLE_NEXT, m("💤 Не сейчас ({n} ч)", { n: a.idlePushHours })],
});
const state = await getIdle(db, project.id);

View File

@ -1,7 +1,7 @@
// PEP-62: a person's message in a chat (web or a linked Telegram group). In a story thread it
// answers the story's open question or becomes a PM comment typed into the live runner; in
// other threads and the channel it is a note; a text starting with "/" is a command.
import { m, m as tr } from "@peppa/shared/i18n";
import { asIs, m, m as tr } from "@peppa/shared/i18n";
import {
addChatMessage,
addStoryComment,
@ -135,8 +135,8 @@ async function notifyDiscussion(db: Db, author: User, projectId: number, m: Chat
projectId,
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
pushKey: `chat:m${m.id}:u${u.id}`,
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${esc(author.login)}:\n${esc(short)}\n\n${tr("Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}${url}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: `${project.name}: ${author.login}`, body: short.slice(0, 200), url, tag: `chat:${projectId}` },
telegram: { params: { text: `💬 <b>${asIs(esc(project.name))}</b> · ${asIs(esc(author.login))}:\n${asIs(esc(short))}\n\n${tr("Ответить: {url}", { url: `${process.env.PEPPA_WEB_URL ?? ""}${url}` })}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: asIs(`${project.name}: ${author.login}`), body: asIs(short.slice(0, 200)), url, tag: `chat:${projectId}` },
});
}
}
@ -190,7 +190,7 @@ export async function runCommand(db: Db, user: User, chat: Chat, text: string):
if (cmd === "/task") {
const open = (await pendingQuestions(db)).filter((q) => q.taskId === ref.task.id);
const [live] = await listSessions(db, { active: true, taskId: ref.task.id });
return [`${ref.key}: ${ref.task.title}`, m("Статус: {status}", { status: statusRu(ref.task.status) }), live ? m("Агент: {status}", { status: live.status }) : m("Агент не запущен"), open.length ? m("Ждёт ответа: {n}", { n: open.length }) : m("Открытых вопросов нет")].join("\n");
return [`${ref.key}: ${asIs(ref.task.title)}`, m("Статус: {status}", { status: statusRu(ref.task.status) }), live ? m("Агент: {status}", { status: live.status }) : m("Агент не запущен"), open.length ? m("Ждёт ответа: {n}", { n: open.length }) : m("Открытых вопросов нет")].join("\n");
}
const col = COLUMNS[args.slice(1).join(" ").toLowerCase()];
// glossary-ignore: команды чата (/status, /move) — не команды терминала; названия колонок — часть команды

View File

@ -2,7 +2,7 @@
// the host (docker compose behind Traefik, health check, rollback) and reports each step
// 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 { asIs, 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 { projects, questions, releases, settings, type Db } from "@peppa/db";
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
@ -114,7 +114,7 @@ export async function recordRelease(db: Db, project: Project, r: DeployReport):
async function notifyRelease(db: Db, project: Project, rel: Release) {
const tasks = rel.tasks.join(", ");
const v = { project: project.name, sha: short(rel.sha), tasks };
const v = { project: asIs(project.name), sha: short(rel.sha), tasks };
const log = runLink(rel.runUrl);
if (rel.status === "rolled_back" || rel.status === "failed") {
const head =
@ -123,14 +123,14 @@ async function notifyRelease(db: Db, project: Project, rel: Release) {
: m("❌ {project}: обновление {sha} ({env}) не прошло проверку.", { ...v, env: rel.env });
await askPmProject(db, project, {
kind: "attention",
text: `${head}\n${m("Причина: {reason}", { reason: rel.reason ?? m("неизвестна") })}${log ? `\n${m("Подробности: {url}", { url: log })}` : ""}`,
text: `${head}\n${m("Причина: {reason}", { reason: rel.reason ? asIs(rel.reason) : m("неизвестна") })}${log ? `\n${m("Подробности: {url}", { url: log })}` : ""}`,
});
} else if (rel.status === "healthy" && rel.env !== "preview" && rel.previousSha === rel.sha) {
// PEP-112: the same version started again (the project's secrets changed) — not a new one.
const open = await openNeeds(db, project.id);
await askPmProject(db, project, {
kind: "attention",
text: `${rel.env === "prod" ? m("🔑 {project}: ваш продукт перезапущен с новыми настройками", v) : m("🔑 {project}: версия для проверки перезапущена с новыми настройками", v)}${rel.host ? `\n${m("Открыть: {url}", { url: `https://${rel.host}` })}` : ""}${open.length ? `\n${m("Ещё работает в демо-режиме, нужно: {needs}", { needs: needsLine(open) })}` : ""}`,
text: `${rel.env === "prod" ? m("🔑 {project}: ваш продукт перезапущен с новыми настройками", v) : m("🔑 {project}: версия для проверки перезапущена с новыми настройками", v)}${rel.host ? `\n${m("Открыть: {url}", { url: `https://${rel.host}` })}` : ""}${open.length ? `\n${m("Ещё работает в демо-режиме, нужно: {needs}", { needs: needsLine(open, asIs) })}` : ""}`,
});
} else if (rel.status === "healthy" && rel.env === "staging") {
await expireProdOffers(db, project.id);

View File

@ -3,7 +3,7 @@
// PEPPA_SESSION_ID / PEPPA_GENERATION point to. Must never break the Claude session:
// always exits 0, errors go to ~/.peppa/hook.log, and blocking hooks fall back to
// Claude's own terminal dialog when the PM doesn't answer in time.
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
@ -247,7 +247,7 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
// PEP-44: the preview stand, the diff and the checks — the PM reviews without a terminal.
const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId));
const look = project ? [reviewPreviewNote(await reviewPreview(db, { project, task, key: s.taskKey ?? "" }).catch(() => ({ previewUrl: null, releaseId: null, sha: null, diffUrl: null, checks: "", screenshots: [], issueUrl: null }))), await demoNote(db, project.id, project.key)].filter(Boolean).join("\n") : "";
const card = clip(`${m("✅ Задача {key} готова к ревью", { key: s.taskKey })}${task.prUrl ? ` · ${m("Результат: {url}", { url: task.prUrl })}` : ""}\n\n${look ? `${look}\n\n` : ""}${note ? `${note}\n\n` : ""}${text ?? ""}`.trim());
const card = clip(`${m("✅ Задача {key} готова к ревью", { key: s.taskKey })}${task.prUrl ? ` · ${m("Результат: {url}", { url: task.prUrl })}` : ""}\n\n${look ? `${look}\n\n` : ""}${note ? `${note}\n\n` : ""}${asIs(text?.trim())}`.trim());
// PEP-127: the PM gets it only when the PR can be merged now; otherwise the watchdog sends it later.
if (project) await sendReviewCard(db, { project, task, key: s.taskKey ?? "" }, card, s);
else await raiseSessionQuestion(db, s, "attention", card);
@ -390,7 +390,7 @@ async function handle(event: string, input: HookInput): Promise<void> {
db,
s,
"attention",
`${m("{who}: ход оборвался с ошибкой {error}.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), error: input.error ?? "unknown" })}${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`,
`${m("{who}: ход оборвался с ошибкой {error}.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), error: input.error ?? "unknown" })}${input.error_details ? `\n${asIs(clip(input.error_details, 400))}` : ""}`,
);
break;
}

View File

@ -1,7 +1,7 @@
// Incident flow (PEP-58): Bugsink webhook/poll → ingest → the project's incident policy
// (notify / backlog / start / ask / triage) → bug task, runner, Telegram. Also the PM's
// decisions, manual "fixed" and regressions. See openspec/changes/pep-58-bugsink/design.md.
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { bugsinkFromEnv, issueFromEvent, parseWebhook, type BugsinkClient, type BugsinkIssueJson } from "@peppa/bugsink";
import {
addErrorSource,
@ -89,7 +89,7 @@ export async function applyIncidentPolicy(db: Db, i: Incident, o: IncidentOption
if (!r.ok) return execute(db, i, s, "ask", "triage", null, o, m("Триажёр недоступен ({error}) — реши сам.", { error: r.error }));
const d = r.decision;
if (d.action === "ask" || d.confidence < TRIAGE_MIN_CONFIDENCE) {
return execute(db, i, s, "ask", "triage", d.reason, o, d.action !== "ask" ? m("Триажёр не уверен (склоняется: {action}): {reason}", { action: ACTION_RU[d.action], reason: d.reason }) : m("Триажёр не уверен: {reason}", { reason: d.reason }));
return execute(db, i, s, "ask", "triage", d.reason, o, d.action !== "ask" ? m("Триажёр не уверен (склоняется: {action}): {reason}", { action: ACTION_RU[d.action], reason: asIs(d.reason) }) : m("Триажёр не уверен: {reason}", { reason: asIs(d.reason) }));
}
return execute(db, i, s, d.action, "triage", d.reason, o);
}
@ -120,7 +120,7 @@ async function execute(
if (today >= s.dailyLimit) {
const limitNote =
by === "triage"
? m("Суточный предел задач из ошибок ({n}) исчерпан — задача не создана; триажёр предлагал «{action}»: {reason}.", { n: s.dailyLimit, action: ACTION_RU[action], reason })
? m("Суточный предел задач из ошибок ({n}) исчерпан — задача не создана; триажёр предлагал «{action}»: {reason}.", { n: s.dailyLimit, action: ACTION_RU[action], reason: asIs(reason) })
: m("Суточный предел задач из ошибок ({n}) исчерпан — задача не создана.", { n: s.dailyLimit });
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });

View File

@ -4,7 +4,7 @@
// `launchctl`), so the PM's button queues a request on this host and the launchd agent
// quest.telecom.peppa.release runs scripts/peppa-release.sh, which reports back through
// `peppa release report` → recordRelease (same releases table and PM messages as projects).
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { askPmProject, configuredChecks, getProject, getSetting, setSetting, summarizeChecks, PeppaError, type Project } from "@peppa/core";
import { checkRuns, releases, type Db } from "@peppa/db";
import { peppaHome } from "@peppa/shared";
@ -80,7 +80,7 @@ export async function offerPlatformRelease(db: Db, project: Project, sha: string
await askPmProject(db, project, {
kind: "question",
options: [PROD_OPTION],
text: m("✅ {project}: main зелёный — {sha}. Выкатить в прод?", { project: project.name, sha: short(sha) }),
text: m("✅ {project}: main зелёный — {sha}. Выкатить в прод?", { project: asIs(project.name), sha: short(sha) }),
});
return true;
}

View File

@ -1,7 +1,7 @@
// PEP-76: the project owner's choice of what its agents run on — the platform's shared pool
// («Общая подписка Пеппы») or the owner's own Claude subscription (a `claude setup-token` token,
// kept encrypted like every subscription, in the owner's personal pool).
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { askPmProject, deleteSetting, getProject, getSetting, platformProjectKey, setSetting, type Question, createPool, getPool, listLoans, logEvent, ownPool, PeppaError, setProjectPool, sharedPool, updatePool, isSuperadmin, listPools, listSubscriptions, poolSubscriptions, projectPool, type Project, type User } from "@peppa/core";
import type { Db } from "@peppa/db";
import { finishClaudeLogin, pendingLogin, pollCodexLogin, removeSubscription } from "./subscription-login.ts";
@ -60,7 +60,7 @@ export async function chooseSharedSubscription(db: Db, user: User, project: Proj
const q = await askPmProject(db, platform, {
kind: "question",
options: [SHARED_APPROVE, SHARED_DENY],
text: m("🔑 {login} просит подписку Peppa FACTORY для проекта «{project}» ({key}).\nАгенты проекта будут работать на подписке фабрики и тратить её лимит.\nРазрешить?", { login: user.login, project: project.name, key: project.key }),
text: m("🔑 {login} просит подписку Peppa FACTORY для проекта «{project}» ({key}).\nАгенты проекта будут работать на подписке фабрики и тратить её лимит.\nРазрешить?", { login: asIs(user.login), project: asIs(project.name), key: project.key }),
});
await setSetting(db, requestKey(project.id), { userId: user.id, login: user.login, questionId: q.id, at: new Date().toISOString() } satisfies SharedRequest);
await setSetting(db, questionKey(q.id), project.id);
@ -82,10 +82,10 @@ export async function onSharedAnswer(db: Db, q: Question, answer: string): Promi
const pool = await sharedPool(db);
if (answer.trim() === SHARED_APPROVE && pool) {
await switchToShared(db, project, pool.id, req.login, "superadmin");
await askPmProject(db, project, { kind: "attention", text: m("✅ {project}: подписка Peppa FACTORY разрешена — агенты могут работать. Перейти на свою подписку можно в любой момент в настройках проекта.", { project: project.name }) });
await askPmProject(db, project, { kind: "attention", text: m("✅ {project}: подписка Peppa FACTORY разрешена — агенты могут работать. Перейти на свою подписку можно в любой момент в настройках проекта.", { project: asIs(project.name) }) });
} else {
await logEvent(db, { projectId: project.id, type: "project_subscription", payload: { login: req.login, choice: "shared_denied" } });
await askPmProject(db, project, { kind: "attention", text: m("{project}: подписку Peppa FACTORY для этого проекта не разрешили. Подключите свою подписку Claude или ChatGPT — {url}", { project: project.name, url: `${web}/p/${project.key}` }) });
await askPmProject(db, project, { kind: "attention", text: m("{project}: подписку Peppa FACTORY для этого проекта не разрешили. Подключите свою подписку Claude или ChatGPT — {url}", { project: asIs(project.name), url: `${web}/p/${project.key}` }) });
}
return true;
}

View File

@ -1,7 +1,7 @@
// PEP-28: watchdog 2.0 — the watchdog fixes what it can by itself (restarts a crashed or
// stalled runner within a limit), reminds about unanswered questions and escalates them,
// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env.
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { and, eq, gte, inArray, isNull, sql } from "drizzle-orm";
import {
alertAdmins,
@ -14,6 +14,7 @@ import {
logSessionEvent,
pendingSessionQuestions,
PeppaError,
questionIsFreeText,
projectAudience,
raiseSessionQuestion,
touchQuestion,
@ -248,7 +249,9 @@ export async function remindTick(db: Db, o: { now: Date; cfg: WatchdogSettings;
if (!claimed) continue;
const where = taskNumber != null ? formatTaskKey(projectKey, taskNumber) : projectKey;
const url = taskNumber != null ? `/t/${where}` : "/";
const body = q.text.length > 300 ? `${q.text.slice(0, 300)}…` : q.text;
const short = q.text.length > 300 ? `${q.text.slice(0, 300)}…` : q.text;
// PEP-139/140: an agent's own question is free text — the reminder keeps it as written.
const body = questionIsFreeText(q) ? asIs(short) : short;
if (escalate) {
await alertAdmins(db, `esc:q${q.id}`, `${m("🚨 {where}: {kind} #{id} без ответа {min} мин — агент ждёт.", { where, kind: KIND_RU[q.kind]?.toLowerCase() ?? "вопрос", id: q.id, min: ageMin })}\n\n${body}`, o.log);
} else {

View File

@ -1,6 +1,6 @@
// Watchdog: polls Peppa's tmux sessions, tracks activity, and alerts the PM when a
// session dies, stalls, or hits a usage limit. Run under launchd with caffeinate.
import { m } from "@peppa/shared/i18n";
import { asIs, m } from "@peppa/shared/i18n";
import { runnerTick } from "./runners.ts";
import { createHash } from "node:crypto";
import {
@ -184,7 +184,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
await logSessionEvent(db, s, "exited", { exitStatus: pane.exitStatus, tail });
await killRunner(s).catch(() => {});
if (ok) await updateSession(db, s.id, { status: "done", endedAt: new Date() });
else await onRunnerCrash(db, s, "crash", `${m("{where}: работа оборвалась с ошибкой (код {code}).", { where: s.taskKey ?? m("Агент #{id}", { id: s.id }), code: pane.exitStatus })}\n\n${tail}`, { now: nowDate, cfg, log });
else await onRunnerCrash(db, s, "crash", `${m("{where}: работа оборвалась с ошибкой (код {code}).", { where: s.taskKey ?? m("Агент #{id}", { id: s.id }), code: pane.exitStatus })}\n\n${asIs(tail)}`, { now: nowDate, cfg, log });
return;
}
@ -239,7 +239,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg:
db,
s,
"attention",
`${m("{who}: ничего не происходит {n} мин — похоже, работа зависла.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), n: Math.round((now - last) / 60000) })}\n\n${tail}`,
`${m("{who}: ничего не происходит {n} мин — похоже, работа зависла.", { who: s.taskKey ?? m("Агент #{id}", { id: s.id }), n: Math.round((now - last) / 60000) })}\n\n${asIs(tail)}`,
);
}
}