PEP-139: free text of people and agents is marked and never rewritten by the translation of rendered messages
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
873daa4fb4
commit
27e24c592b
@ -90,6 +90,7 @@
|
||||
- **Память проекта (PEP-30)**: `.peppa/memory.md` в репо проекта (разделы Команды/Соглашения/Грабли/Решения), `core/memory.ts` (`rememberFact` — дубли пропускаются, предел `PEPPA_MEMORY_MAX_CHARS` 12 000 → отказ с просьбой ужать; `replaceMemory`; `memoryContext` = файл рабочей копии + 5 последних `done` стори). MCP агента `get_memory`/`remember` (файл рядом с `.peppa/project.json`, коммитит агент в ветке стори). Раннер (`launch` в runner/sessions.ts) дописывает `memoryContext` к общим правилам при каждом запуске/resume. Правило — «Завершение» в `template/RULES.md`; веб — вкладка «Спеки» (`MemorySection`)
|
||||
- **Модель агента (PEP-41)**: `core/agent-model.ts`, наследование `platform.agent` → `project.agent:<id>` → `task.agent:<taskId>` (`settings`): `provider`, `model`, `effort` (Claude `--effort`, Codex `-c model_reasoning_effort`, xhigh/max → high), `escalateModel`/`escalateEffort`/`escalateAfter` (по умолчанию 2; null — выкл), `fallbackProvider`/`fallbackModel`. Модель — только своему провайдеру (`launchModelFor`). Неудачи стори = `ci_attempts` + `reviewRejections`; порог → `agent.escalated:<taskId>` (липко). `startRunner`: провайдер из настроек, нет рабочей подписки → запасной (событие `provider_fallback`); `launch` пишет `model`/`effort` в `started`/`resumed`. `sendWithEscalation` (runner/escalation.ts, из ci-feedback и reviewer; у клиентов PEP-21 — команда сервиса `sendEscalated`): эскалация наступила, а модель живого запуска другая → kill tmux + `resumeSession` с сообщением (событие `model_escalated`). Веб «⋯ Настройки проекта → Модель агента», раздел «Агент» стори (`components/AgentModel.tsx`); MCP PM `agent` в `update_project_settings`/`update_task`; CLI `peppa project agent <KEY|KEY-N|--platform> k=v…`
|
||||
- **Язык интерфейса (PEP-98)**: `@peppa/shared/i18n` — ключ словаря = русская строка-шаблон (`{name}`), словари `packages/shared/src/i18n/en/*.ts` (по разделам), `kk.ts` (PEP-99, пока откат на русский). `t(locale, key, vars)` / `translator(locale)` (`t.n` — множественное, `t.text` — перевод уже собранного текста), `m(key, vars)` — пометка шаблона в core/runner/bot (рендерит русский), `localizeText` — обратное сопоставление по шаблонам (целиком → строки → куски между HTML-тегами → «a · b», «Метка: значение»; захваченные значения переводятся рекурсивно). Язык: `settings` `user.locale:<id>` (`getUserLocale`/`setUserLocale`, core/locale.ts) + cookie `peppa_lang`; веб `getLocale`/`getT` (lib/i18n.ts: пользователь → cookie → Accept-Language до входа → ru), клиент `useT()`/`LanguageSwitcher` (components/I18n.tsx), вход переносит язык (`adoptLocale`); ошибки server actions — `t.text` в `attempt()`. Бот переводит `text`/`caption`/кнопки/тосты по языку читателя (`localizeParams`, `telegramChatLocale`: группа — язык связавшего); push — в `deliverToUser`. Английское название — «Peppa FACTORY». Новый текст пользователю = ключ в `en/*.ts`, иначе падает `node scripts/i18n-check.ts` (тест `i18n.test.ts`); тексты агентам не переводятся (`// i18n-ignore`). **Сообщения ИИ-ролей (PEP-138)**: в сообщении роли в обсуждении проекта (аналитик, продакт, список «чтобы заработало по-настоящему») свободный текст модели общим `localizeText` не переводить — он его переписывает; постоянная фраза = отдельная строка через `m()` + ключ в `ROLE_MESSAGE_KEYS`, перевод — `localizeRoleMessage` (веб `t.role`); Telegram и push из `sayInDiscussion` собираются на языке получателя и помечаются `Delivery.localized` (в outbox `peppa_localized`, бот снимает и не переводит). Тест `i18n-role-messages.test.ts`
|
||||
- **Свободный текст не переводится (PEP-139)**: чужие слова внутри собираемого сообщения (текст человека или модели, название задачи, логин, варианты ответа агента) оборачивай `asIs()` из `@peppa/shared/i18n` — невидимые U+2068/U+2069; `localizeText` такой кусок не трогает и не считает, пометку снимают сам перевод (`localizeText`, `t.text`, `t.role`, `localizeMessage`) и бот перед отправкой (`localizeParams`, всегда), иначе — `stripAsIs`. Помечено: зеркало чатов в Telegram-группы (`mirrorOne`: человек — дословно, ИИ-роль — `localizeRoleMessage` на языке группы; заметка фабрики `authorKind: system` переводится), события чата (`progress`, `intake_note`, текст вопроса, название задачи в `threadTitle` — пометка хранится в `chat_messages`), вопросы агента (`questionIsFreeText` в core: есть `sessionId` и вид `question`/`approval` — текст, кнопки, push; вопросы фабрики — шаблоны, переводятся), ответ человека в `renderAnswered`. Свободные значения внутри шаблонов runner («готова к ревью» с названием задачи) пока не помечены. Тест `free-text-verbatim.test.ts`
|
||||
- **«Помощь» по виду (PEP-122)**: `/help` при `uiMode() === "product"` — один экран `ProductHelp` (три блока: поставить задачу, принять, поправить), «Инженер» — прежний справочник (его и держать в актуальном состоянии при изменении инструментов MCP). Тексты — файл переводов `core/help-texts.ts` (`PRODUCT_HELP`: ru/kk/en одной формы; показывается ru, пока нет языка интерфейса); тест `product-help.test.ts` сверяет ru с колонкой «Нельзя» `docs/glossary.md`
|
||||
- **Вход и старт для продактов (PEP-83)**: `/login` — зачем фабрика, пять шагов, что понадобится, вход справа (на телефоне: заголовок → вход → подробности); шаги `onboardingChecklist` для обычного пользователя: telegram → project → subscription (нет `projectAgentWarning` хотя бы у одного проекта) → story → started → accepted (первая `done`), у шага `action` — подпись кнопки; суперадмину subscription первым; тексты для непрограммиста
|
||||
- **Онбординг (PEP-31)**: `core/onboarding.ts` — `onboardingChecklist` (шаги из БД: подписка — только суперадмину, Telegram, eGov — необязательный, проект, стори, сессия стори; скрыт после выполнения или `onboarding.dismissed:<userId>`), `projectAgentWarning` (у пула проекта нет рабочей подписки; без пула — не проверяется). Веб: `components/Onboarding.tsx` на Главной, плашка «Агенты не запустятся» на странице проекта
|
||||
|
||||
@ -2,8 +2,8 @@
|
||||
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||
import { LOCALIZED_PARAM, localizeMessage, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { LOCALIZED_PARAM, localizeMessage, questionIsFreeText, reportPlatformError, telegramChatLocale } from "@peppa/core";
|
||||
import { asIs, localizeRoleMessage, m as tr, stripAsIs } from "@peppa/shared/i18n";
|
||||
import {
|
||||
accountUsageForUser,
|
||||
describeUsage,
|
||||
@ -158,8 +158,8 @@ const PUSH_TITLE: Record<NotifyEvent, string> = {
|
||||
function pushFor(q: Question, event: NotifyEvent, ctx: { taskKey: string | null; taskTitle: string | null }): { title: string; body: string } {
|
||||
const what = q.kind === "approval" ? tr("нужно одобрение") : q.kind === "permission" ? tr("нужно разрешение") : PUSH_TITLE[event];
|
||||
const title = ctx.taskKey ? `${ctx.taskKey}: ${what}` : what;
|
||||
const body = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
|
||||
return { title, body };
|
||||
const short = q.text.length > 200 ? `${q.text.slice(0, 199)}…` : q.text;
|
||||
return { title, body: questionIsFreeText(q) ? asIs(short) : short };
|
||||
}
|
||||
|
||||
export function createBot(o: BotOptions) {
|
||||
@ -186,16 +186,21 @@ export function createBot(o: BotOptions) {
|
||||
// Texts are rendered in Russian everywhere (core, runner, this file); right before the Bot API
|
||||
// call the text, caption and button labels are translated for the chat's user.
|
||||
const readerChat = new AsyncLocalStorage<number>();
|
||||
/** PEP-139: the marks around free text never reach Telegram (the translation takes them off itself). */
|
||||
const unmarked = (params: Record<string, unknown>): Record<string, unknown> => {
|
||||
const raw = JSON.stringify(params);
|
||||
return raw.includes("\u2068") || raw.includes("\u2069") ? (JSON.parse(stripAsIs(raw)) as Record<string, unknown>) : params;
|
||||
};
|
||||
const localizeParams = async (params: Record<string, unknown>): Promise<Record<string, unknown>> => {
|
||||
if (LOCALIZED_PARAM in params) {
|
||||
// PEP-138: written for this reader already (an AI role's message with free text inside).
|
||||
const { [LOCALIZED_PARAM]: _done, ...rest } = params;
|
||||
return rest;
|
||||
return unmarked(rest);
|
||||
}
|
||||
const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore();
|
||||
if (chatId == null) return params;
|
||||
if (chatId == null) return unmarked(params);
|
||||
const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const);
|
||||
if (locale === "ru") return params;
|
||||
if (locale === "ru") return unmarked(params);
|
||||
const loc = (v: unknown) => (typeof v === "string" ? localizeMessage(locale, v) : v);
|
||||
const out: Record<string, unknown> = { ...params, text: loc(params.text), caption: loc(params.caption) };
|
||||
if (params.text === undefined) delete out.text;
|
||||
@ -414,8 +419,17 @@ export function createBot(o: BotOptions) {
|
||||
buttons = r.buttons;
|
||||
questionId = q.id;
|
||||
} else {
|
||||
const said = esc(m.text.slice(0, 3500));
|
||||
const who = m.kind === "user" ? `<b>${esc(m.authorLogin ?? "?")}</b>` : m.authorKind === "agent" ? "🤖 " : "";
|
||||
// PEP-139: a person's words go as written; an AI role's message gets its fixed lines in the
|
||||
// group's language and is then free text too. Events are factory phrases (free parts are
|
||||
// marked where the event text is built) and are translated when sent.
|
||||
const role = m.kind === "user" && m.authorKind === "agent";
|
||||
const inRole = role ? await telegramChatLocale(db, tgChatId).catch(() => "ru" as const) : null;
|
||||
const own = (s: string) => (inRole ? localizeRoleMessage(inRole, s) : s);
|
||||
// A note the factory itself writes into a discussion (authorKind system) is a phrase, not free text.
|
||||
const free = m.kind === "user" && m.authorKind !== "system";
|
||||
const said = free ? asIs(esc(own(m.text).slice(0, 3500))) : esc(m.text.slice(0, 3500));
|
||||
const login = own(m.authorLogin ?? "?");
|
||||
const who = m.kind === "user" ? `<b>${asIs(esc(login))}</b>` : m.authorKind === "agent" ? "🤖 " : "";
|
||||
const body = m.kind === "user" ? (m.via === "telegram" ? `: ${said}` : tr(" (веб): {text}", { text: said })) : said;
|
||||
text = `${where ? `${where}\n` : ""}${who}${body}${m.url ? `\n${esc(m.url)}` : ""}`;
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
// Telegram message texts and buttons for PM questions. HTML parse mode.
|
||||
import { questionType, type Question, type SessionView } from "@peppa/core";
|
||||
import { questionIsFreeText, questionType, type Question, type SessionView } from "@peppa/core";
|
||||
import type { InlineButton } from "./telegram.ts";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
|
||||
export const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const italic = (s: string) => `<i>${s}</i>`;
|
||||
@ -24,10 +24,12 @@ export function renderQuestion(
|
||||
q: Question,
|
||||
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
|
||||
): Rendered {
|
||||
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${esc(clip(ctx.taskTitle, 80))}</i>` : null]
|
||||
const head = ["<b>" + esc(ctx.taskKey ?? (q.sessionId ? tr("Агент №{id}", { id: q.sessionId }) : tr("Обновления продукта"))) + "</b>", ctx.taskTitle ? `<i>${asIs(esc(clip(ctx.taskTitle, 80)))}</i>` : null]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
const body = esc(clip(q.text, 3300));
|
||||
// PEP-139: what the agent wrote itself is free text — only the factory's phrases are translated.
|
||||
const free = questionIsFreeText(q);
|
||||
const body = free ? asIs(esc(clip(q.text, 3300))) : esc(clip(q.text, 3300));
|
||||
const lines = [head, KIND[q.kind], "", body];
|
||||
|
||||
const buttons: InlineButton[][] = [];
|
||||
@ -43,7 +45,7 @@ export function renderQuestion(
|
||||
]);
|
||||
} else if (type === "question") {
|
||||
// PEP-149: a question always comes with answers to tap; the default goes first.
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: free ? asIs(clip(o, 60)) : clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
|
||||
if (q.kind === "attention") lines[1] = KIND.question;
|
||||
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
|
||||
if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
|
||||
@ -69,7 +71,9 @@ 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}: <b>{answer}</b>", { via, answer: esc(clip(q.answer ?? "", 500)) });
|
||||
// A person's answer is free text; a button of a factory question (and a system answer) is a phrase.
|
||||
const own = q.answeredVia !== "system" && !(q.options ?? []).includes(q.answer ?? "") ? asIs : (x: string) => x;
|
||||
const said = q.answeredVia === "system" ? esc(q.answer ?? "") : tr("Ответ {via}: <b>{answer}</b>", { via, answer: own(esc(clip(q.answer ?? "", 500))) });
|
||||
return `${original}\n\n${mark} ${said}`;
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-16
|
||||
24
openspec/changes/pep-139-free-text-verbatim/design.md
Normal file
24
openspec/changes/pep-139-free-text-verbatim/design.md
Normal file
@ -0,0 +1,24 @@
|
||||
## Context
|
||||
|
||||
Тексты собираются по-русски (core, runner, бот), перевод — в слое доставки обратным сопоставлением `localizeText`. Он не знает, где в сообщении постоянная фраза, а где чужие слова, и выбирает вариант с наименьшим числом русских букв — свободный текст переписывается. PEP-138 обошла это для одного пути (`sayInDiscussion`): текст собирается сразу на языке читателя и помечается `Delivery.localized`.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** свободный текст человека или модели в Telegram (личный чат, группа), push и вебе — дословно; постоянные фразы вокруг него по-прежнему переводятся.
|
||||
|
||||
**Non-Goals:** перевод свободного текста; свободные значения внутри шаблонов сообщений фабрики, написанных в runner (название задачи в «готова к ревью» и т. п.) — отдельная задача; замена обратного сопоставления ключами.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Пометка внутри текста, а не признак у сообщения.** Одно сообщение смешивает постоянное и свободное («[KEY] 🧵 тред / anna (веб): текст»), а события чата хранятся одной строкой на всех читателей. Поэтому свободный кусок оборачивается `asIs()` — парой невидимых символов Unicode U+2068/U+2069 (изоляция направления письма: для показа безвредны, даже если где-то не сняты). Альтернативы: собирать каждое сообщение на языке читателя (как PEP-138) — не годится для хранимых событий и требует знать читателя в core; колонка «свободный текст» — миграция и не решает смешанные строки.
|
||||
- **`localizeText` пропускает помеченное.** Перед сопоставлением помеченные куски заменяются жетонами без кириллицы (не делятся на строки и части, не идут в счёт «русских букв»), после — возвращаются без пометки. Для русского языка пометка просто снимается. `localizeRoleMessage` тоже снимает пометку. Незакрытая пометка (текст обрезан) действует до конца текста.
|
||||
- **Снятие пометки — в тех же местах, где перевод:** `localizeMessage` (push), `localizeParams` бота (в том числе для русского читателя и для `peppa_localized`), `t.text` / `t.role` в вебе.
|
||||
- **Кто написал вопрос.** Свободным считается текст и варианты вопроса, заданного агентом через MCP: `sessionId` есть и вид `question` или `approval` (`questionIsFreeText` в core). Вопросы фабрики (бюджет, простой, «готова к ревью») — шаблоны, переводятся как раньше. Разрешения — команда, кириллицы нет.
|
||||
- **Зеркало**: сообщение человека — `asIs`; сообщение ИИ-роли — `localizeRoleMessage` на языке группы (`telegramChatLocale`), затем `asIs`; логин автора и название треда — `asIs`.
|
||||
- **Хранимые тексты**: заметка о прогрессе, реплики `intake_note`, текст вопроса в ленте чата, название задачи в `threadTitle` помечаются при записи в `chat_messages`.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- Пометка попадает в `chat_messages.text` → места, которые показывают текст без перевода, получат два невидимых символа; на вид и поиск по словам не влияет.
|
||||
- Пользователь сам вставил U+2068/U+2069 → его текст останется дословным, символы снимутся — безвредно.
|
||||
- Уже записанные в чат события без пометки переводятся по-старому, пока не уйдут по сроку хранения (14 дней).
|
||||
23
openspec/changes/pep-139-free-text-verbatim/proposal.md
Normal file
23
openspec/changes/pep-139-free-text-verbatim/proposal.md
Normal file
@ -0,0 +1,23 @@
|
||||
## Why
|
||||
|
||||
При английском и казахском языке общий перевод уже собранных сообщений (`localizeText`, «меньше всего русских букв») переписывает свободный текст людей и агентов: «Сделано три задачи из пяти.» приходит в Telegram как «три задачи of пяти. done». PEP-138 закрыла это только для сообщений ИИ-ролей в обсуждении.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Свободный текст (сообщение человека, слова модели, название задачи, варианты ответа агента) помечается при сборке сообщения как «дословный»; общий перевод его не трогает и не считает, перед показом пометка снимается.
|
||||
- Зеркало чатов в Telegram-группы: сообщения людей доходят дословно, сообщения ИИ-ролей — с переведёнными постоянными строками (как в вебе), подписи фабрики переводятся.
|
||||
- События агентов со свободным текстом (заметка о прогрессе, реплики продакта и аналитика в задаче) и название задачи в заголовке треда — дословно.
|
||||
- Вопросы агента (текст, варианты, план на одобрение) и ответ человека под закрытым вопросом — дословно в Telegram и push; вопросы самой фабрики переводятся как раньше.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `interface-language`: новое требование — свободный текст людей и агентов доходит до читателя без изменений на любом языке.
|
||||
|
||||
## Impact
|
||||
|
||||
- `packages/shared/src/i18n/index.ts` (пометка `asIs`, `stripAsIs`, перевод с пропуском помеченного), `packages/core` (`chats.ts`, `notifications.ts`, `tasks.ts`), `apps/bot` (`bot.ts`, `render.ts`), тесты testkit.
|
||||
- Ветка стоит поверх `task/pep-138` (ещё не слита): использует `localizeRoleMessage`.
|
||||
- Миграций нет; пометка — невидимые символы в тексте.
|
||||
@ -0,0 +1,37 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Свободный текст людей и агентов доходит без изменений
|
||||
Текст, который написал человек или модель (сообщение в чате, заметка агента о прогрессе, вопрос агента и его варианты ответа, ответ человека, название задачи), SHALL доходить до читателя в Telegram, push и вебе дословно на любом языке интерфейса. Постоянные фразы фабрики в том же сообщении SHALL показываться на языке читателя.
|
||||
|
||||
#### Scenario: Сообщение человека в Telegram-группе с английским языком
|
||||
- **GIVEN** чат проекта DEMO связан с Telegram-группой, язык связавшего пользователя — English
|
||||
- **WHEN** участник пишет в обсуждении проекта в вебе «Сделано три задачи из пяти.»
|
||||
- **THEN** в группу приходит сообщение с текстом «Сделано три задачи из пяти.» без изменений
|
||||
- **AND** подпись рядом с именем автора — «(web)»
|
||||
|
||||
#### Scenario: Заметка агента о прогрессе
|
||||
- **GIVEN** чат проекта связан с Telegram-группой с английским языком
|
||||
- **WHEN** агент записывает прогресс «Сделано три задачи из пяти.»
|
||||
- **THEN** в группу приходит «📈 Сделано три задачи из пяти.»
|
||||
|
||||
#### Scenario: Вопрос агента с вариантами
|
||||
- **GIVEN** пользователь с языком интерфейса English и привязанным Telegram
|
||||
- **WHEN** агент спрашивает «Какой формат из двух оставить? Готово три задачи из пяти.» с вариантами «Задачи из списка» и «Готово»
|
||||
- **THEN** в Telegram текст вопроса и подписи кнопок — как написал агент
|
||||
- **AND** заголовок сообщения — «❓ Question»
|
||||
|
||||
#### Scenario: Сообщение ИИ-роли в группе
|
||||
- **GIVEN** чат проекта связан с Telegram-группой с английским языком
|
||||
- **WHEN** аналитик отвечает «Сделано три задачи из пяти.» и заводит задачу
|
||||
- **THEN** в группе ответ показан как написан
|
||||
- **AND** строка под ним — «Added to the backlog:»
|
||||
|
||||
#### Scenario: Вопрос фабрики по-прежнему переводится
|
||||
- **GIVEN** пользователь с языком интерфейса English и привязанным Telegram
|
||||
- **WHEN** фабрика сообщает, что бюджет задачи исчерпан
|
||||
- **THEN** сообщение в Telegram на английском, русских постоянных фраз в нём нет
|
||||
|
||||
#### Scenario: Русский читатель не видит служебных пометок
|
||||
- **GIVEN** пользователь с русским языком интерфейса
|
||||
- **WHEN** ему приходит вопрос агента «Какой формат из двух оставить?»
|
||||
- **THEN** текст в Telegram совпадает с написанным посимвольно
|
||||
16
openspec/changes/pep-139-free-text-verbatim/tasks.md
Normal file
16
openspec/changes/pep-139-free-text-verbatim/tasks.md
Normal file
@ -0,0 +1,16 @@
|
||||
## 1. Пометка свободного текста
|
||||
|
||||
- [x] 1.1 `asIs` / `stripAsIs` в `@peppa/shared/i18n`; `localizeText` и `localizeRoleMessage` пропускают помеченное и снимают пометку
|
||||
- [x] 1.2 Тесты: дословность, перевод вокруг, русский язык, незакрытая пометка
|
||||
|
||||
## 2. Доставка
|
||||
|
||||
- [x] 2.1 Бот: `localizeParams` снимает пометку всегда; зеркало чатов (`mirrorOne`) помечает сообщения людей и ИИ-ролей, логин, название треда
|
||||
- [x] 2.2 Вопросы агента: `questionIsFreeText` в core; `renderQuestion`, `renderAnswered`, push — дословно
|
||||
- [x] 2.3 События чата: прогресс, реплики продакта и аналитика, текст вопроса, название задачи в заголовке треда
|
||||
- [x] 2.4 Тесты бота: сценарии требования (группа en, вопрос агента, вопрос фабрики, русский читатель)
|
||||
|
||||
## 3. Завершение
|
||||
|
||||
- [ ] 3.1 Проверки (lint, typecheck, test, build), AGENTS.md, память проекта
|
||||
- [ ] 3.2 Архив change, PR
|
||||
@ -2,7 +2,7 @@
|
||||
// chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events,
|
||||
// questions, releases and incidents, which stay in their own tables; people's messages are
|
||||
// stored here too. Telegram groups linked to chats are the bot's business (apps/bot).
|
||||
import { m as tr, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { asIs, m as tr, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||
import { createHmac, randomBytes } from "node:crypto";
|
||||
import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
@ -12,6 +12,7 @@ import { getNotifyPrefs, projectAudience } from "./notifications.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { IS_QUESTION } from "./questions.ts";
|
||||
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
|
||||
import { questionIsFreeText } from "./tasks.ts";
|
||||
import { projectForUser, userProjectIds, type User } from "./users.ts";
|
||||
import type { OutboxRow } from "./telegram.ts";
|
||||
import { chatRepeatKey, chatRepeats, normalizeMessage, pruneMessageStates, questionStates, type ChatRepeat } from "./message-state.ts";
|
||||
@ -129,7 +130,7 @@ export async function threadTitle(db: Db, key: string): Promise<string | null> {
|
||||
const id = Number(raw);
|
||||
if (kind === "task") {
|
||||
const [t] = await db.select({ key: projects.key, n: tasks.number, title: tasks.title }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, id));
|
||||
return t ? `${formatTaskKey(t.key, t.n)} · ${t.title}` : null;
|
||||
return t ? `${formatTaskKey(t.key, t.n)} · ${asIs(t.title)}` : null;
|
||||
}
|
||||
if (kind === "incident") {
|
||||
const [i] = await db.select({ title: incidents.title }).from(incidents).where(eq(incidents.id, id));
|
||||
@ -367,14 +368,15 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
|
||||
};
|
||||
return { text: said[String(to)] ?? tr("• Статус: {to}", { to: statusRu(String(to)) }), important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
|
||||
},
|
||||
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
|
||||
// PEP-139: the agent's and the roles' own words are marked free text — never translated.
|
||||
progress: (p) => ({ text: `📈 ${asIs(cut(s(p.text), 1500))}`, author: "agent" }),
|
||||
// PEP-149: the agent cannot go on (not a product decision) — a record, not a question.
|
||||
blocker: (p) => ({ text: `⛔ ${tr("Агент не может продолжить: {what}", { what: cut(s(p.what), 1000) })}${s(p.tried) ? `\n${tr("Что уже пробовал: {tried}", { tried: cut(s(p.tried), 500) })}` : ""}`, author: "agent" }),
|
||||
blocker: (p) => ({ text: `⛔ ${tr("Агент не может продолжить: {what}", { what: asIs(cut(s(p.what), 1000)) })}${s(p.tried) ? `\n${tr("Что уже пробовал: {tried}", { tried: asIs(cut(s(p.tried), 500)) })}` : ""}`, author: "agent" }),
|
||||
pm_comment: () => null, // handled separately: a person's message
|
||||
// PEP-4: the project's repo moved to another Gitea namespace.
|
||||
repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }),
|
||||
// PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread.
|
||||
intake_note: (p) => ({ text: p.role === "product" ? tr("🧭 Продакт: {text}", { text: cut(s(p.text), 3000) }) : tr("🔎 Аналитик: {text}", { text: cut(s(p.text), 3000) }), important: true, author: "agent" }),
|
||||
intake_note: (p) => ({ text: p.role === "product" ? tr("🧭 Продакт: {text}", { text: asIs(cut(s(p.text), 3000)) }) : tr("🔎 Аналитик: {text}", { text: asIs(cut(s(p.text), 3000)) }), important: true, author: "agent" }),
|
||||
pr_merged_in_gitea: (p) => ({ text: p.by ? tr("🔀 Изменения задачи приняты в код проекта ({by})", { by: s(p.by) }) : tr("🔀 Изменения задачи приняты в код проекта") }),
|
||||
started: () => ({ text: tr("▶️ Агент начал работу") }),
|
||||
resumed: () => ({ text: tr("🔁 Агент продолжает работу") }),
|
||||
@ -518,7 +520,7 @@ export async function syncChats(db: Db, o: { now?: Date } = {}): Promise<number>
|
||||
kind: "question",
|
||||
important: true,
|
||||
authorKind: q.sessionId ? "agent" : "system",
|
||||
text: `${head}\n${cut(q.text, 3000)}`,
|
||||
text: `${head}\n${questionIsFreeText(q) ? asIs(cut(q.text, 3000)) : cut(q.text, 3000)}`,
|
||||
questionId: q.id,
|
||||
dedupeKey: `question:${q.id}`,
|
||||
createdAt: q.createdAt,
|
||||
|
||||
@ -10,7 +10,7 @@ import type { User } from "./users.ts";
|
||||
import { enqueuePush, type PushPayload } from "./webpush.ts";
|
||||
import { addMasterMessage } from "./chats.ts";
|
||||
import { getUserLocale } from "./locale.ts";
|
||||
import { localizeText, m as tr, type Locale } from "@peppa/shared/i18n";
|
||||
import { localizeText, m as tr, stripAsIs, type Locale } from "@peppa/shared/i18n";
|
||||
|
||||
|
||||
/** PEP-98: a rendered message (Telegram text, push body) in `locale` — see localizeText. */
|
||||
@ -210,7 +210,9 @@ export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: Not
|
||||
if (ch.push && d.push && !quiet) {
|
||||
// PEP-98: push text in the user's language (Telegram is translated by the bot when sent).
|
||||
const locale = await getUserLocale(db, user.id);
|
||||
const push = locale === "ru" || d.localized ? d.push : { ...d.push, title: localizeMessage(locale, d.push.title), body: localizeMessage(locale, d.push.body) };
|
||||
// PEP-139: free text inside is marked — the translation leaves it and takes the marks off.
|
||||
const shown = (s: string) => (d.localized ? stripAsIs(s) : localizeMessage(locale, s));
|
||||
const push = { ...d.push, title: shown(d.push.title), body: shown(d.push.body) };
|
||||
out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...push, sound: d.push.sound ?? p.sound }, urgency: d.urgency });
|
||||
}
|
||||
return out;
|
||||
|
||||
@ -328,6 +328,12 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-139: the question's text and options are the agent's own words (asked through MCP), not
|
||||
* a factory template — they reach the reader as written, in any interface language.
|
||||
*/
|
||||
export const questionIsFreeText = (q: Pick<Question, "kind" | "sessionId">): boolean => q.sessionId != null && (q.kind === "question" || q.kind === "approval");
|
||||
|
||||
/** 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();
|
||||
|
||||
@ -262,6 +262,17 @@ function line(locale: Locale, s: string): Rendered {
|
||||
* stays as it is.
|
||||
*/
|
||||
export function localizeText(locale: Locale, text: string): string {
|
||||
if (!text) return text;
|
||||
if (!text.includes(AS_IS_OPEN)) return rendered(locale, stripAsIs(text));
|
||||
if (locale === "ru") return stripAsIs(text);
|
||||
// PEP-139: free text goes around the matching as tokens without Cyrillic — it is neither
|
||||
// split into lines and pieces nor counted as "Russian left", and comes back as written.
|
||||
const kept: string[] = [];
|
||||
const skeleton = text.replace(AS_IS_SPAN, (_all, inner: string) => `${AS_IS_OPEN}${kept.push(inner) - 1}${AS_IS_CLOSE}`);
|
||||
return stripAsIs(rendered(locale, skeleton).replace(AS_IS_TOKEN, (_all, i: string) => kept[Number(i)] ?? ""));
|
||||
}
|
||||
|
||||
function rendered(locale: Locale, text: string): string {
|
||||
if (locale === "ru" || !text || !CYR.test(text)) return text;
|
||||
let cache = caches.get(locale);
|
||||
if (!cache) caches.set(locale, (cache = new Map()));
|
||||
@ -276,6 +287,27 @@ export function localizeText(locale: Locale, text: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- Free text inside rendered messages (PEP-139) -----------------------------------------
|
||||
|
||||
// U+2068 / U+2069 (directional isolates): invisible and harmless where a text is shown unstripped.
|
||||
const AS_IS_OPEN = "\u2068";
|
||||
const AS_IS_CLOSE = "\u2069";
|
||||
/** A marked piece; a mark left open (the text was cut) runs to the end. */
|
||||
const AS_IS_SPAN = /\u2068([^\u2069]*)(?:\u2069|$)/g;
|
||||
const AS_IS_TOKEN = /\u2068(\d+)\u2069/g;
|
||||
const AS_IS_MARKS = /[\u2068\u2069]/g;
|
||||
|
||||
/** Removes the free-text marks: the text as it is shown to a reader. */
|
||||
export const stripAsIs = (text: string): string => (text.includes(AS_IS_OPEN) || text.includes(AS_IS_CLOSE) ? text.replace(AS_IS_MARKS, "") : text);
|
||||
|
||||
/**
|
||||
* Marks free text — a person's or a model's own words, a story title, a login — inside a
|
||||
* message that is rendered in Russian and translated later: `localizeText` leaves the marked
|
||||
* piece exactly as written and translates only the factory's phrases around it. Whoever shows
|
||||
* the message translates it (`localizeText`, `Translator.text`) or calls `stripAsIs`.
|
||||
*/
|
||||
export const asIs = (text: string | null | undefined): string => (text ? `${AS_IS_OPEN}${stripAsIs(text)}${AS_IS_CLOSE}` : "");
|
||||
|
||||
// ---- Messages of the AI roles: fixed lines among free text (PEP-138) ----------------------
|
||||
|
||||
/**
|
||||
@ -330,7 +362,9 @@ function compileRoleLines(locale: Locale) {
|
||||
* (indentation kept, placeholder values as written); every other line stays as it is.
|
||||
*/
|
||||
export function localizeRoleMessage(locale: Locale, text: string | null | undefined): string {
|
||||
if (!text || locale === "ru" || !CYR.test(text)) return text ?? "";
|
||||
if (!text) return "";
|
||||
text = stripAsIs(text);
|
||||
if (locale === "ru" || !CYR.test(text)) return text;
|
||||
const c = compileRoleLines(locale);
|
||||
return text
|
||||
.split("\n")
|
||||
|
||||
165
packages/testkit/test/free-text-verbatim.test.ts
Normal file
165
packages/testkit/test/free-text-verbatim.test.ts
Normal file
@ -0,0 +1,165 @@
|
||||
// PEP-139: free text of people and agents reaches the reader as written — the translation of
|
||||
// rendered messages touches only the factory's own phrases. Unit checks of the marks, and the
|
||||
// real bot against mock-telegram: a linked group and a private chat reading English.
|
||||
import assert from "node:assert/strict";
|
||||
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, runner, teardown, waitFor } from "./helpers.ts";
|
||||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||||
import { users } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { asIs, localizeRoleMessage, localizeText, m, stripAsIs, translator } from "@peppa/shared/i18n";
|
||||
import type { Bot } from "@peppa/bot";
|
||||
|
||||
const { createBot } = await import("@peppa/bot");
|
||||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||||
const { renderAnswered, renderQuestion } = await import("@peppa/bot/render");
|
||||
|
||||
const FREE = "Сделано три задачи из пяти.";
|
||||
const MARKS = /[]/;
|
||||
|
||||
describe("пометка свободного текста", () => {
|
||||
test("общий перевод переписывает непомеченный свободный текст — причина стори", () => {
|
||||
assert.notEqual(localizeText("en", FREE), FREE);
|
||||
});
|
||||
|
||||
test("помеченный текст остаётся дословным, фразы вокруг переводятся", () => {
|
||||
assert.equal(localizeText("en", asIs(FREE)), FREE);
|
||||
assert.equal(localizeText("kk", asIs(FREE)), FREE);
|
||||
assert.equal(localizeText("en", `${m("❓ Вопрос")}\n${asIs(FREE)}`), `❓ Question\n${FREE}`);
|
||||
assert.equal(localizeText("en", m("Ошибка: {message}", { message: asIs(FREE) })), `Error: ${FREE}`);
|
||||
// Several lines of free text are not split into lines and translated one by one.
|
||||
assert.equal(localizeText("en", `<b>${asIs("anna")}</b>${m(" (веб): {text}", { text: asIs(`Проекты\n${FREE}`) })}`), `<b>anna</b> (web): Проекты\n${FREE}`);
|
||||
});
|
||||
|
||||
test("русскому читателю и без перевода пометка снимается", () => {
|
||||
assert.equal(localizeText("ru", `📈 ${asIs(FREE)}`), `📈 ${FREE}`);
|
||||
assert.equal(stripAsIs(asIs(FREE)), FREE);
|
||||
assert.equal(localizeRoleMessage("en", `📈 ${asIs(FREE)}`), `📈 ${FREE}`);
|
||||
assert.equal(translator("en").text(asIs("Проекты")), "Проекты");
|
||||
assert.equal(asIs(""), "");
|
||||
assert.equal(asIs(null), "");
|
||||
});
|
||||
|
||||
test("обрезанная пометка действует до конца текста, вложенная не ломает", () => {
|
||||
const cut = `${m("❓ Вопрос")}\n${asIs(FREE).slice(0, -1)}`;
|
||||
assert.equal(localizeText("en", cut), `❓ Question\n${FREE}`);
|
||||
assert.equal(localizeText("en", asIs(`до ${asIs(FREE)} после`)), `до ${FREE} после`);
|
||||
assert.equal(localizeText("en", `${FREE}`), localizeText("en", FREE));
|
||||
});
|
||||
});
|
||||
|
||||
describe("вопросы", () => {
|
||||
const ctx = { taskKey: "DEMO-1", taskTitle: "Готово три задачи из пяти", session: null, webUrl: "http://peppa.test" };
|
||||
const q = (over: Record<string, unknown>) => ({ id: 7, kind: "question", text: "Какой формат из двух оставить? Готово три задачи из пяти.", options: ["Задачи из списка", "Готово"], sessionId: 3, answer: null, answeredVia: null, ...over }) as never;
|
||||
|
||||
test("Scenario: Вопрос агента с вариантами", () => {
|
||||
const r = renderQuestion(q({}), ctx);
|
||||
const en = localizeText("en", r.text);
|
||||
assert.match(en, /❓ Question/);
|
||||
assert.ok(en.includes("Какой формат из двух оставить? Готово три задачи из пяти."), en);
|
||||
assert.ok(en.includes("<i>Готово три задачи из пяти</i>"), en);
|
||||
assert.deepEqual(r.buttons.map((b) => localizeText("en", b[0]!.text)), ["Задачи из списка", "Готово"]);
|
||||
// The same button unmarked would be translated.
|
||||
assert.notEqual(localizeText("en", "Готово"), "Готово");
|
||||
});
|
||||
|
||||
test("Scenario: Вопрос фабрики по-прежнему переводится", () => {
|
||||
const text = m("⚠️ {key}: изменения затрагивают проверки или выкатку продукта — сама задача не закроется, нужно ваше «Принять».", { key: "DEMO-1" });
|
||||
const r = renderQuestion(q({ sessionId: null, text, options: null }), { ...ctx, taskTitle: null });
|
||||
assert.doesNotMatch(localizeText("en", r.text), /[А-Яа-яЁё]/);
|
||||
assert.doesNotMatch(r.text, MARKS);
|
||||
});
|
||||
|
||||
test("ответ человека под закрытым вопросом — дословно", () => {
|
||||
const original = renderQuestion(q({}), ctx).text;
|
||||
const en = localizeText("en", renderAnswered(original, q({ answer: FREE, answeredVia: "telegram" })));
|
||||
assert.ok(en.includes(`<b>${FREE}</b>`), en);
|
||||
assert.doesNotMatch(en.split("\n").at(-1)!.replace(FREE, ""), /[А-Яа-яЁё]/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("бот: Telegram на английском", () => {
|
||||
const tg = new MockTelegram();
|
||||
const PM = { id: 801, chatId: 801, username: "pm" };
|
||||
const BOB = { id: 802, chatId: 802, username: "bob" };
|
||||
const GROUP = { id: -100900, title: "DEMO team" };
|
||||
let bot: Bot;
|
||||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let bob: typeof pm;
|
||||
let p: Awaited<ReturnType<typeof core.createProject>>;
|
||||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||||
const group = () => tg.botMessages(GROUP.id);
|
||||
const sentTo = (chatId: number) => tg.calls.filter((c) => c.params.chat_id === chatId);
|
||||
|
||||
before(async () => {
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
await tg.start();
|
||||
pm = await core.upsertUserFromGitea(db, { id: 91, login: "mock-pm" }, { access_token: "x" });
|
||||
bob = await core.upsertUserFromGitea(db, { id: 92, login: "mock-bob" }, { access_token: "y" });
|
||||
await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
|
||||
await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
|
||||
pm = (await core.getUser(db, pm.id))!;
|
||||
bob = (await core.getUser(db, bob.id))!;
|
||||
// The PM reads English (their private chat and the group they link); Bob reads Russian.
|
||||
await core.setUserLocale(db, pm.id, "en");
|
||||
p = await core.createProject(db, { slug: "demo", key: "DEMO", name: "Демо", giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
|
||||
await core.addMember(db, p, bob.login, pm.id);
|
||||
chat = await core.ensureProjectChat(db, p.id);
|
||||
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, changesIntervalMs: 200, log: (x) => process.env.MOCK_DEBUG && console.log(x) });
|
||||
await bot.start();
|
||||
await bot.reconcile(); // first start: mirroring begins from here
|
||||
tg.userSendsInGroup(PM, GROUP, `/link@mock_peppa_bot ${await core.createChatLinkCode(db, tg.token, pm, chat.id, { sharedBot: true })}`);
|
||||
await waitFor("linked", async () => (await core.getChat(db, chat.id)).tgChatId === GROUP.id);
|
||||
});
|
||||
after(async () => {
|
||||
await bot?.stop();
|
||||
await tg.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
test("Scenario: Сообщение человека в Telegram-группе с английским языком", async () => {
|
||||
await runner.postToChat(db, bob, { chatId: chat.id, threadKey: null, text: FREE, via: "web" });
|
||||
const msg = await waitFor("mirrored", async () => group().find((x) => x.text.includes("mock-bob")));
|
||||
assert.equal(msg.text, `<b>mock-bob</b> (web): ${FREE}`);
|
||||
});
|
||||
|
||||
test("Scenario: Заметка агента о прогрессе", async () => {
|
||||
const ref = await core.resolveTask(db, (await core.createTask(db, { projectId: p.id, title: "Готово три задачи из пяти" })).key);
|
||||
const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id });
|
||||
await core.reportProgress(db, ref, FREE, s.id);
|
||||
const msg = await waitFor("progress mirrored", async () => group().find((x) => x.text.includes("📈")));
|
||||
assert.ok(msg.text.endsWith(`📈 ${FREE}`), msg.text);
|
||||
// The story title in the thread line is the person's own words too.
|
||||
assert.ok(msg.text.includes("<i>DEMO-1 · Готово три задачи из пяти</i>"), msg.text);
|
||||
assert.doesNotMatch(msg.text, MARKS);
|
||||
});
|
||||
|
||||
test("Scenario: Вопрос агента с вариантами; русский читатель не видит служебных пометок", async () => {
|
||||
const ref = await core.resolveTask(db, "DEMO-1");
|
||||
const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id });
|
||||
const text = "Какой формат из двух оставить? Готово три задачи из пяти.";
|
||||
await core.askPm(db, ref, { kind: "question", text, options: ["Задачи из списка", "Готово"], sessionId: s.id });
|
||||
const en = await waitFor("question to the PM", async () => tg.botMessages(PM.chatId).find((x) => x.text.includes("Какой формат")));
|
||||
assert.match(en.text, /❓ Question/);
|
||||
assert.ok(en.text.includes(text), en.text);
|
||||
assert.deepEqual(en.reply_markup?.inline_keyboard.flat().map((b) => b.text), ["Задачи из списка", "Готово"]);
|
||||
const ru = await waitFor("question to Bob", async () => tg.botMessages(BOB.chatId).find((x) => x.text.includes("Какой формат")));
|
||||
assert.match(ru.text, /❓ Вопрос/);
|
||||
assert.ok(ru.text.includes(text));
|
||||
for (const c of [...sentTo(PM.chatId), ...sentTo(BOB.chatId), ...sentTo(GROUP.id)]) assert.doesNotMatch(JSON.stringify(c.params), MARKS, "the marks do not reach Telegram");
|
||||
});
|
||||
|
||||
test("Scenario: Сообщение ИИ-роли в группе", async () => {
|
||||
await runner.sayInDiscussion(db, p, chat.id, `${FREE}\n\n${m("Завёл в бэклог:")}\n• DEMO-2 «Экспорт в PDF»`);
|
||||
const msg = await waitFor("role message mirrored", async () => group().find((x) => x.text.includes("Added to the backlog:")));
|
||||
assert.equal(msg.text, `<b>Analyst</b> (web): ${FREE}\n\nAdded to the backlog:\n• DEMO-2 «Экспорт в PDF»`);
|
||||
});
|
||||
|
||||
test("Scenario: Вопрос фабрики по-прежнему переводится", async () => {
|
||||
const ref = await core.resolveTask(db, "DEMO-1");
|
||||
await core.askPm(db, ref, { kind: "question", text: m("⚠️ {key}: изменения затрагивают проверки или выкатку продукта — сама задача не закроется, нужно ваше «Принять».", { key: ref.key }) });
|
||||
const msg = await waitFor("factory question", async () => tg.botMessages(PM.chatId).find((x) => x.text.includes("⚠️ DEMO-1")));
|
||||
assert.doesNotMatch(msg.text.replace("Готово три задачи из пяти", ""), /[А-Яа-яЁё]/, msg.text);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user