peppa/packages/testkit/src/glossary-check.ts
Асель 094ab632cc PEP-152: формат сообщения агента — суть, что нужно от вас, где посмотреть, подробности под «Подробнее»
Сообщение агента пользователю собирается из полей summary / need / link / details
(core/agent-message.ts); основной текст проверяется при приёме (длина, словарь, файлы,
ветки, команды, номера PR, статусы из кода) — нарушение возвращается агенту, после трёх
отказов подряд сообщение уходит с нейтральной первой строкой. Разбор словаря — общий
модуль @peppa/shared/glossary. Сайт и Telegram показывают основной текст, details — под
«Подробнее». Карточка «готово» и реплика конца хода — в том же формате. Правила агентам,
переводы en/kk, тесты по сценариям, change pep-152-agent-message-format в архиве.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 17:38:04 +05:00

235 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-124: the glossary check. Reads the «Нельзя» column of docs/glossary.md, collects the texts
// a person sees on the screens (JSX text, user-facing attributes, Cyrillic string literals,
// translation files) and fails when a forbidden word shows up — with the file, the line, the word
// and what to write instead.
//
// PEP-129: messages built outside the screens (Telegram notifications, chat events, the digest —
// packages/core, packages/runner, packages/mcp) are checked too. Those files also hold prompts for
// agents and output for developers, so only the texts marked as «for a person» count there:
// m("…") / tr("…") / t("…") / t.n(…) — the translation-dictionary mark (PEP-98)
// // glossary-user: <why> — this line and the next one (a text that skips the dictionary)
// // glossary-user-file: <why> — the whole file is read like a screen
//
// pnpm lint check (exit 1 on a new forbidden word)
// pnpm lint --update rewrite the list of old debts
//
// Old debts live in docs/glossary-baseline.json (file → word → count): the check fails only when
// a file has more occurrences of a word than recorded there, so the list can only shrink.
// PEP-137: the list holds screens only — files of packages/core, packages/runner and packages/mcp
// are never recorded there, a forbidden word in a message fails the check at once.
// A text that is shown in «Инженер» mode only is marked in the source:
// // glossary-ignore: <why> — this line and the next one
// // glossary-ignore-file: <why> — the whole file
// The same mark fits a word used in its everyday meaning («команда агентов» is not a terminal command).
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { glossaryMatcher, parseGlossary, termRegExp, wordForms, type GlossaryRule, type Matcher } from "@peppa/shared/glossary";
// PEP-152: the parsing of the glossary lives in @peppa/shared/glossary — agents' messages are checked by the same code.
export { glossaryMatcher, parseGlossary, termRegExp, wordForms, type GlossaryRule, type Matcher };
export type Violation = { file: string; line: number; word: string; found: string; write: string; text: string };
export type Baseline = Record<string, Record<string, number>>;
/** Where the texts of the product live: every Cyrillic string there is a text on a screen. */
export const GLOSSARY_ROOTS = ["apps/web/app", "apps/web/components", "apps/bot/src"];
/** Where messages are built next to prompts for agents and developer output: only marked texts count. */
export const MESSAGE_ROOTS = ["packages/core/src", "packages/runner/src", "packages/mcp/src"];
/** How a source file is read: `screen` — every text; `messages` — only texts marked as «for a person». */
export type TextMode = "screen" | "messages";
export const TRANSLATION_ROOTS = ["apps", "packages"];
export const GLOSSARY_FILE = "docs/glossary.md";
export const BASELINE_FILE = "docs/glossary-baseline.json";
export type TextPiece = { line: number; text: string };
const VISIBLE_ATTRS = new Set(["title", "placeholder", "alt", "aria-label", "label", "description", "hint"]);
const CYRILLIC = /[а-яё]/i;
// The calls that mark a text for the translation dictionary (scripts/i18n-check.ts knows the same names).
const USER_TEXT_CALL = /^(t|m|tr|tn)$|\.(t|m|n)$/;
const calleeName = (e: ts.Expression): string => (ts.isIdentifier(e) ? e.text : ts.isPropertyAccessExpression(e) ? `${calleeName(e.expression)}.${e.name.text}` : "");
const USER_FILE = /glossary-user-file/;
const USER_LINE = /glossary-user(?!-file)/;
/**
* Texts of a .ts/.tsx source that reach a person. `screen`: JSX text, user-facing attributes, Cyrillic
* strings. `messages`: the same, but only inside `m()`/`tr()`/`t()`/`t.n()` calls (every string in the
* arguments, values of placeholders included) and on lines marked `glossary-user`.
*/
export function sourceTexts(fileName: string, source: string, mode: TextMode = "screen"): TextPiece[] {
const all = mode === "screen" || USER_FILE.test(source);
const lines = all ? [] : source.split("\n");
const sf = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, true, fileName.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
const out: TextPiece[] = [];
// JSX text keeps its leading line breaks, so its lines are counted from the raw start.
const add = (node: ts.Node, text: string) => {
const start = ts.isJsxText(node) ? node.pos : node.getStart(sf);
if (text.trim()) out.push({ line: sf.getLineAndCharacterOfPosition(start).line + 1, text });
};
const userLine = (node: ts.Node) => {
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line;
return USER_LINE.test(lines[line] ?? "") || USER_LINE.test(lines[line - 1] ?? "");
};
const visit = (node: ts.Node, marked: boolean) => {
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) return;
if (!marked && ts.isCallExpression(node) && USER_TEXT_CALL.test(calleeName(node.expression))) {
visit(node.expression, false);
for (const arg of node.arguments) visit(arg, true);
return;
}
if (ts.isJsxText(node)) {
if (marked) add(node, node.text);
} else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) || ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) {
const attr = ts.isJsxAttribute(node.parent) && VISIBLE_ATTRS.has(node.parent.name.getText(sf));
if ((attr || CYRILLIC.test(node.text)) && (marked || userLine(node))) add(node, node.text);
}
ts.forEachChild(node, (child) => visit(child, marked));
};
visit(sf, all);
return out;
}
/** Every string of a translation file (messages/ru.json and the like). */
export function jsonTexts(source: string): TextPiece[] {
const out: TextPiece[] = [];
const lines = source.split("\n");
const walk = (v: unknown) => {
if (typeof v === "string") {
const needle = JSON.stringify(v).slice(1, -1);
const at = lines.findIndex((l) => l.includes(needle));
out.push({ line: at < 0 ? 1 : at + 1, text: v });
} else if (v && typeof v === "object") Object.values(v).forEach(walk);
};
walk(JSON.parse(source));
return out;
}
const IGNORE_FILE = /glossary-ignore-file/;
const IGNORE_LINE = /glossary-ignore(?!-file)/;
/** Forbidden words in one file. `file` is the path shown in the report. */
export function checkText(file: string, source: string, matcher: Matcher, mode: TextMode = "screen"): Violation[] {
if (IGNORE_FILE.test(source)) return [];
const lines = source.split("\n");
const pieces = file.endsWith(".json") ? jsonTexts(source) : sourceTexts(file, source, mode);
const out: Violation[] = [];
for (const piece of pieces) {
for (const hit of matcher.find(piece.text)) {
const line = piece.line + piece.text.slice(0, hit.index).split("\n").length - 1;
if (IGNORE_LINE.test(lines[line - 1] ?? "") || IGNORE_LINE.test(lines[line - 2] ?? "")) continue;
out.push({ file, line, word: hit.word, found: hit.found, write: hit.write, text: (lines[line - 1] ?? "").trim().slice(0, 160) });
}
}
return out;
}
const isTranslation = (path: string) => /(^|\/)(messages|locales|i18n|translations)\/.*\.json$/.test(path);
const isSource = (path: string) => /\.tsx?$/.test(path) && !/\.(test|d)\.ts$/.test(path);
function walk(dir: string, out: string[]) {
for (const name of readdirSync(dir).sort()) {
if (name === "node_modules" || name.startsWith(".")) continue;
const path = join(dir, name);
if (statSync(path).isDirectory()) walk(path, out);
else out.push(path);
}
}
/** All forbidden words under the roots of a checkout. */
export function scanGlossary(root: string, roots = GLOSSARY_ROOTS, glossaryFile = GLOSSARY_FILE, messageRoots = MESSAGE_ROOTS): Violation[] {
const matcher = glossaryMatcher(parseGlossary(readFileSync(join(root, glossaryFile), "utf8")));
const rel = (path: string) => relative(root, path).split(sep).join("/");
const under = (dirs: string[]) => {
const files: string[] = [];
for (const d of dirs) if (existsSync(join(root, d))) walk(join(root, d), files);
return files.map(rel);
};
// Sources — the screens and the marked texts of the messages; translation files — wherever they appear.
const screens = new Set([...under(roots).filter(isSource), ...under(TRANSLATION_ROOTS).filter(isTranslation)]);
const messages = under(messageRoots).filter((f) => isSource(f) && !screens.has(f));
return [...screens, ...messages]
.sort()
.flatMap((file) => checkText(file, readFileSync(join(root, file), "utf8"), matcher, screens.has(file) ? "screen" : "messages"));
}
export function countViolations(violations: Violation[]): Baseline {
const counts: Baseline = {};
for (const v of violations) {
const file = (counts[v.file] ??= {});
file[v.word] = (file[v.word] ?? 0) + 1;
}
return counts;
}
/** Violations above the recorded old debts: every occurrence of a word in a file that has more of it than before. */
export function newViolations(violations: Violation[], baseline: Baseline): Violation[] {
const counts = countViolations(violations);
return violations.filter((v) => (counts[v.file]?.[v.word] ?? 0) > (baseline[v.file]?.[v.word] ?? 0));
}
/** One file per line, sorted: parallel changes rarely touch the same line. */
export function formatBaseline(baseline: Baseline): string {
const files = Object.keys(baseline).sort();
const rows = files.map((f) => {
const words = Object.keys(baseline[f]!).sort();
return ` ${JSON.stringify(f)}: {${words.map((w) => `${JSON.stringify(w)}: ${baseline[f]![w]}`).join(", ")}}`;
});
return `{\n${rows.join(",\n")}\n}\n`;
}
export function formatViolation(v: Violation, baseline: Baseline = {}): string {
const old = baseline[v.file]?.[v.word] ?? 0;
const debt = old ? ` (в файле было ${old} — стало больше)` : "";
const write = v.write ? ` Пишем: ${v.write}.` : "";
return `${v.file}:${v.line}: слово «${v.found}» нельзя показывать пользователю (словарь: «${v.word}»)${debt}.${write}\n ${v.text}`;
}
export function runGlossaryCheck(root: string, opts: { update?: boolean; log?: (line: string) => void } = {}): number {
const log = opts.log ?? console.log;
const baselinePath = join(root, BASELINE_FILE);
const all = scanGlossary(root);
// PEP-137: messages have no list of old debts — a forbidden word there always fails, and
// `--update` does not record it.
const inMessages = (file: string) => MESSAGE_ROOTS.some((dir) => file.startsWith(`${dir}/`));
const noDebt = all.filter((v) => inMessages(v.file));
const failMessages = (recorded: string[]) => {
for (const v of noDebt) log(formatViolation(v));
for (const file of recorded) log(`${BASELINE_FILE}: файл ${file} в списке старых долгов — для сообщений долгов нет, уберите запись.`);
log("");
log(`glossary: FAIL — запрещённых слов: ${noDebt.length}. Для сообщений (${MESSAGE_ROOTS.join(", ")}) старые долги не записываются.`);
log("Замените слово словом из колонки «Пишем» или, если текст читает только инженер, пометьте строку `glossary-ignore: <почему>`.");
return 1;
};
if (opts.update) {
if (noDebt.length) return failMessages([]);
writeFileSync(baselinePath, formatBaseline(countViolations(all)));
log(`glossary: список старых долгов обновлён — ${all.length} в ${new Set(all.map((v) => v.file)).size} файлах (${BASELINE_FILE})`);
return 0;
}
const baseline: Baseline = existsSync(baselinePath) ? JSON.parse(readFileSync(baselinePath, "utf8")) : {};
const recorded = Object.keys(baseline).filter(inMessages);
if (noDebt.length || recorded.length) return failMessages(recorded);
const fresh = newViolations(all, baseline);
if (fresh.length) {
for (const v of fresh) log(formatViolation(v, baseline));
log("");
log(`glossary: FAIL — запрещённых слов: ${fresh.length}. Замените их словами из колонки «Пишем» ${GLOSSARY_FILE}.`);
log("Текст виден только в режиме «Инженер» или слово стоит в другом значении — пометьте строку комментарием `glossary-ignore: <почему>`.");
log("Подсказки агентам в packages/* не проверяются: в `m()` оборачивается только текст для человека.");
return 1;
}
const counts = countViolations(all);
const paid = Object.entries(baseline).flatMap(([f, words]) => Object.entries(words).filter(([w, n]) => (counts[f]?.[w] ?? 0) < n));
log(`glossary: ok — новых запрещённых слов нет (старых долгов: ${all.length})`);
if (paid.length) log(`glossary: долгов стало меньше — зафиксируйте: pnpm lint --update`);
return 0;
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = resolve(fileURLToPath(import.meta.url), "../../../..");
process.exit(runGlossaryCheck(root, { update: process.argv.includes("--update") }));
}