peppa/packages/shared/src/glossary.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

118 lines
5.8 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 / PEP-152: the glossary of words a person sees (docs/glossary.md) — parsing of the table
// «Понятие | Пишем | Нельзя | Пояснение» and the search of forbidden words in a text. Pure: used
// by the check of screens (`pnpm lint`, packages/testkit/src/glossary-check.ts) and by the check
// of agents' messages at the moment they are sent (core/agent-message.ts).
export type GlossaryRule = { concept: string; write: string; forbidden: string[]; allowed: string[] };
const cells = (line: string) =>
line
.trim()
.replace(/^\||\|$/g, "")
.split("|")
.map((c) => c.trim());
const terms = (cell: string) =>
cell
.split(",")
.map((t) => t.trim())
.filter((t) => t && !/^[—–-]+$/.test(t));
/** Rows of the table «Понятие | Пишем | Нельзя | Пояснение». */
export function parseGlossary(markdown: string): GlossaryRule[] {
const rules: GlossaryRule[] = [];
let cols: { concept: number; write: number; forbidden: number } | null = null;
for (const line of markdown.split("\n")) {
if (!line.trim().startsWith("|")) {
cols = null;
continue;
}
const row = cells(line);
if (!cols) {
const forbidden = row.indexOf("Нельзя");
if (forbidden >= 0) cols = { concept: Math.max(row.indexOf("Понятие"), 0), write: row.indexOf("Пишем"), forbidden };
continue;
}
if (row.every((c) => /^:?-+:?$/.test(c))) continue;
const write = cols.write >= 0 ? (row[cols.write] ?? "") : "";
rules.push({ concept: row[cols.concept] ?? "", write, forbidden: terms(row[cols.forbidden] ?? ""), allowed: terms(write) });
}
if (!rules.some((r) => r.forbidden.length)) throw new Error("В словаре нет таблицы с колонкой «Нельзя»");
return rules;
}
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const CONSONANT = /[бвгджзклмнпрстфхцчшщ]$/i;
/** Russian case forms of a noun, by its ending: «раннер» → раннера, раннеров…; «ветка» → ветки, веток. */
export function wordForms(word: string): string[] {
const w = word;
const cyr = /[а-яё]$/i.test(w) && w.length >= 3;
if (!cyr || /(ть|ться)$/i.test(w)) return [w];
const with_ = (stem: string, ends: string[]) => [...new Set([w, ...ends.map((e) => stem + e)])];
const hard = ["", "а", "у", "ом", "ем", "е", "ы", "и", "ов", "ей", "ам", "ами", "ах"];
if (/ия$/i.test(w)) return with_(w.slice(0, -1), ["я", "и", "ю", "ей", "й", "е", "ем", "ям", "ями", "ях"]);
if (/[аеиоу]й$/i.test(w)) return with_(w.slice(0, -1), ["й", "я", "ю", "ё", "е", "ем", "и", "ев", "ям", "ями", "ях"]);
if (/ь$/i.test(w)) return with_(w.slice(0, -1), ["ь", "и", "я", "ю", "ью", "ем", "ей", "ям", "ями", "ях"]);
if (/а$/i.test(w)) {
const stem = w.slice(0, -1);
const forms = with_(stem, ["а", "ы", "и", "е", "у", "ой", "ою", "", "ам", "ами", "ах"]);
// «ветка» → «веток», «выкатка» → «выкаток».
if (/[бвгджзлмнпрстфхцчшщ]к$/i.test(stem)) forms.push(`${stem.slice(0, -1)}ок`, `${stem.slice(0, -1)}ек`);
return forms;
}
// A plural in the glossary («токены», «инциденты»): the singular is forbidden as well.
if (w.length >= 5 && (/[бвгджзклмнпрстфхцчшщ]ы$/i.test(w) || /[гкхжчшщ]и$/i.test(w))) return with_(w.slice(0, -1), hard);
if (CONSONANT.test(w)) return with_(w, hard);
return [w];
}
const EDGE_BEFORE = "(?<![\\p{L}\\p{N}_])";
const EDGE_AFTER = "(?![\\p{L}\\p{N}_])";
/** A term of the glossary as a regular expression: whole words, any case (acronyms — exact case). */
export function termRegExp(term: string): RegExp {
if (!/[\p{L}\p{N}]/u.test(term)) return new RegExp(esc(term), "gu");
let body: string;
if (/\s/.test(term)) {
body = term.split(/\s+/).map(esc).join("\\s+");
} else {
// «API-ключ», «превью-стенд»: the last part declines.
const cut = term.lastIndexOf("-") + 1;
body = `${esc(term.slice(0, cut))}(?:${wordForms(term.slice(cut)).map(esc).join("|")})`;
}
const flags = /^[A-Z]{2,}$/.test(term) ? "gu" : "giu";
return new RegExp(`${/^[\p{L}\p{N}_]/u.test(term) ? EDGE_BEFORE : ""}${body}${/[\p{L}\p{N}_]$/u.test(term) ? EDGE_AFTER : ""}`, flags);
}
export type Matcher = { find(text: string): { word: string; found: string; index: number; write: string }[] };
export function glossaryMatcher(rules: GlossaryRule[]): Matcher {
const forbidden = rules.flatMap((r) => r.forbidden.map((word) => ({ word, write: r.write, re: termRegExp(word) })));
// «Peppa FACTORY» is what we write although «Peppa» alone is forbidden: such phrases are
// blanked out before the search.
const allowed = rules
.flatMap((r) => r.allowed)
.filter((phrase) => forbidden.some((f) => new RegExp(f.re.source, f.re.flags).test(phrase)))
.map(termRegExp);
return {
find(text) {
let clean = text;
for (const re of allowed) clean = clean.replace(re, (m) => " ".repeat(m.length));
const hits: { word: string; found: string; index: number; write: string }[] = [];
for (const f of forbidden) {
for (const m of clean.matchAll(f.re)) hits.push({ word: f.word, found: m[0], index: m.index, write: f.write });
}
// «pull request» also contains nothing shorter, but «merge request» ⊃ … — keep the longest hit per place.
hits.sort((a, b) => a.index - b.index || b.found.length - a.found.length);
const out: typeof hits = [];
let end = -1;
for (const h of hits) {
if (h.index < end) continue;
out.push(h);
end = h.index + h.found.length;
}
return out;
},
};
}