235 lines
9.8 KiB
TypeScript
235 lines
9.8 KiB
TypeScript
// Эталонные задачи фабрики (PEP-184): набор в bench/tasks/<id>/, сборка стартовой рабочей
|
||
// копии и запуск скрытых проверок. Прогон через фабрику, итоги и отпечаток — следующие этапы.
|
||
import { execFile } from "node:child_process";
|
||
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { dirname, join, relative, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
|
||
/** Файлы задачи, которые агент не видит: в рабочую копию они не копируются. */
|
||
export const BENCH_HIDDEN = ["checks", "solution", "answers.md", "meta.json"] as const;
|
||
/** Метка в каждом скрытом файле — по ней тест ищет утечку в рабочую копию. */
|
||
export const BENCH_HIDDEN_MARK = "BENCH-HIDDEN";
|
||
/** Что из template/ не идёт в проект эталона: как provisionProject (RULES.md, README.md) + заглушка продукта (её заменяет bench/base). */
|
||
const TEMPLATE_SKIP = new Set(["RULES.md", "README.md", "product"]);
|
||
const SKIP_ALWAYS = new Set([".git", "node_modules", ".gitkeep"]);
|
||
|
||
export interface BenchMeta {
|
||
num: number;
|
||
title: string;
|
||
kind: string;
|
||
/** Предел времени от старта до ревью, минуты. */
|
||
timeLimitMin: number;
|
||
/** Предел токенов на задачу (все токены разговора). */
|
||
tokenLimit: number;
|
||
}
|
||
|
||
export interface BenchStory {
|
||
title: string;
|
||
epic: string | null;
|
||
text: string;
|
||
}
|
||
|
||
export interface BenchAnswer {
|
||
keywords: string[];
|
||
answer: string;
|
||
}
|
||
|
||
export interface BenchTask {
|
||
id: string;
|
||
num: number;
|
||
dir: string;
|
||
meta: BenchMeta;
|
||
story: BenchStory;
|
||
answers: BenchAnswer[] | null;
|
||
}
|
||
|
||
export interface BenchCaseResult {
|
||
name: string;
|
||
ok: boolean;
|
||
detail?: string;
|
||
}
|
||
|
||
export interface BenchCheckResult {
|
||
ok: boolean;
|
||
passed: number;
|
||
total: number;
|
||
cases: BenchCaseResult[];
|
||
error?: string;
|
||
}
|
||
|
||
/** Контекст фабрики для проверок: вопросы продакту и объявленные потребности за задачу. */
|
||
export interface BenchContext {
|
||
questions?: { text: string; answer?: string | null; role?: string }[];
|
||
needs?: { title: string; secret?: string | null }[];
|
||
}
|
||
|
||
export function benchDir(): string {
|
||
return process.env.PEPPA_BENCH_DIR ? resolve(process.env.PEPPA_BENCH_DIR) : resolve(dirname(fileURLToPath(import.meta.url)), "../../../bench");
|
||
}
|
||
|
||
function templateDir(): string {
|
||
return resolve(benchDir(), "../template");
|
||
}
|
||
|
||
export function parseBenchStory(md: string): BenchStory {
|
||
const lines = md.replace(/\r/g, "").split("\n");
|
||
let title = "";
|
||
let epic: string | null = null;
|
||
const rest: string[] = [];
|
||
for (const line of lines) {
|
||
if (!title && line.startsWith("# ")) title = line.slice(2).trim();
|
||
else if (epic === null && /^Эпик:/i.test(line)) epic = line.replace(/^Эпик:/i, "").trim() || null;
|
||
else rest.push(line);
|
||
}
|
||
return { title, epic, text: rest.join("\n").trim() };
|
||
}
|
||
|
||
export function parseBenchAnswers(md: string): BenchAnswer[] {
|
||
const out: BenchAnswer[] = [];
|
||
let cur: BenchAnswer | null = null;
|
||
for (const line of md.replace(/\r/g, "").split("\n")) {
|
||
const h = line.match(/^##\s+(.+)$/);
|
||
if (h) {
|
||
cur = { keywords: h[1].split(",").map((k) => k.trim().toLowerCase()).filter(Boolean), answer: "" };
|
||
out.push(cur);
|
||
} else if (cur && !/^<!--.*-->$/.test(line.trim())) {
|
||
cur.answer += `${line}\n`;
|
||
}
|
||
}
|
||
for (const a of out) a.answer = a.answer.trim();
|
||
return out.filter((a) => a.keywords.length && a.answer);
|
||
}
|
||
|
||
function words(s: string): string[] {
|
||
return s.toLowerCase().replace(/ё/g, "е").split(/[^\p{L}\p{N}]+/u).filter((w) => w.length >= 3);
|
||
}
|
||
|
||
/** Основа слова для грубого сравнения русских форм: «модерация» ~ «модерацию». */
|
||
function stem(w: string): string {
|
||
return w.length <= 4 ? w : w.slice(0, Math.max(4, w.length - 2));
|
||
}
|
||
|
||
/** Ответ из answers.md по наибольшему совпадению ключевых слов; без совпадений — null. */
|
||
export function benchAnswer(task: Pick<BenchTask, "answers">, question: string): string | null {
|
||
if (!task.answers?.length) return null;
|
||
const qs = words(question);
|
||
let best: { score: number; answer: string } | null = null;
|
||
for (const a of task.answers) {
|
||
const score = a.keywords.filter((k) => {
|
||
const ks = words(k).map(stem);
|
||
return ks.length > 0 && ks.every((s) => qs.some((w) => w.startsWith(s)));
|
||
}).length;
|
||
if (score > 0 && (!best || score > best.score)) best = { score, answer: a.answer };
|
||
}
|
||
return best?.answer ?? null;
|
||
}
|
||
|
||
function need(dir: string, id: string, name: string): string {
|
||
const p = join(dir, name);
|
||
if (!existsSync(p)) throw new Error(`bench task ${id}: missing ${name}`);
|
||
return p;
|
||
}
|
||
|
||
export function loadBenchTask(dir: string): BenchTask {
|
||
const id = dir.split("/").filter(Boolean).pop() ?? dir;
|
||
const meta = JSON.parse(readFileSync(need(dir, id, "meta.json"), "utf8")) as BenchMeta;
|
||
const story = parseBenchStory(readFileSync(need(dir, id, "story.md"), "utf8"));
|
||
need(dir, id, "repo");
|
||
need(dir, id, join("checks", "check.mjs"));
|
||
need(dir, id, "solution");
|
||
if (!Number.isInteger(meta.num) || meta.num < 1) throw new Error(`bench task ${id}: meta.num must be a positive integer`);
|
||
if (!(meta.timeLimitMin > 0) || !(meta.tokenLimit > 0)) throw new Error(`bench task ${id}: timeLimitMin and tokenLimit are required`);
|
||
if (!story.title) throw new Error(`bench task ${id}: story.md has no "# title"`);
|
||
const answersPath = join(dir, "answers.md");
|
||
const answers = existsSync(answersPath) ? parseBenchAnswers(readFileSync(answersPath, "utf8")) : null;
|
||
return { id, num: meta.num, dir, meta, story, answers };
|
||
}
|
||
|
||
/** Весь набор по номеру; `nums` — только эти задачи (неизвестный номер — ошибка). */
|
||
export function loadBenchTasks(root = benchDir(), nums?: number[]): BenchTask[] {
|
||
const tasksDir = join(root, "tasks");
|
||
const all = readdirSync(tasksDir)
|
||
.filter((n) => statSync(join(tasksDir, n)).isDirectory())
|
||
.map((n) => loadBenchTask(join(tasksDir, n)))
|
||
.sort((a, b) => a.num - b.num);
|
||
const seen = new Set<number>();
|
||
for (const t of all) {
|
||
if (seen.has(t.num)) throw new Error(`bench: two tasks with num ${t.num}`);
|
||
seen.add(t.num);
|
||
}
|
||
if (!nums) return all;
|
||
return nums.map((n) => {
|
||
const t = all.find((x) => x.num === n);
|
||
if (!t) throw new Error(`bench: no task ${n} (have ${all.map((x) => x.num).join(", ")})`);
|
||
return t;
|
||
});
|
||
}
|
||
|
||
function overlay(from: string, to: string, skipTop: Set<string> = new Set()): void {
|
||
for (const name of readdirSync(from)) {
|
||
if (SKIP_ALWAYS.has(name) || skipTop.has(name)) continue;
|
||
cpSync(join(from, name), join(to, name), {
|
||
recursive: true,
|
||
filter: (src) => !SKIP_ALWAYS.has(src.split("/").pop() ?? ""),
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Стартовая рабочая копия задачи: template/ (без RULES.md, README.md, заглушки) → bench/base →
|
||
* repo/ задачи. Скрытые файлы задачи не копируются. `solution: true` — накладывает эталонное
|
||
* решение (только для проверки самих проверок).
|
||
*/
|
||
export function materializeBenchRepo(task: BenchTask, dest: string, opts: { solution?: boolean; root?: string } = {}): void {
|
||
const root = opts.root ?? benchDir();
|
||
mkdirSync(dest, { recursive: true });
|
||
const tpl = opts.root ? resolve(root, "../template") : templateDir();
|
||
if (existsSync(tpl)) overlay(tpl, dest, TEMPLATE_SKIP);
|
||
overlay(join(root, "base"), dest);
|
||
overlay(join(task.dir, "repo"), dest);
|
||
if (opts.solution) overlay(join(task.dir, "solution"), dest);
|
||
}
|
||
|
||
/** Все файлы каталога (без .git), пути относительно него. */
|
||
export function listBenchFiles(dir: string, base = dir): string[] {
|
||
const out: string[] = [];
|
||
for (const name of readdirSync(dir)) {
|
||
if (name === ".git" || name === "node_modules") continue;
|
||
const p = join(dir, name);
|
||
if (statSync(p).isDirectory()) out.push(...listBenchFiles(p, base));
|
||
else out.push(relative(base, p));
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* Скрытые проверки задачи против рабочей копии. Запускаются отдельным процессом вне рабочей
|
||
* копии (`bench/lib/run-checks.mjs`); рабочая копия не меняется.
|
||
*/
|
||
export function runBenchChecks(task: BenchTask, workdir: string, ctx: BenchContext = {}, opts: { root?: string; timeoutMs?: number } = {}): Promise<BenchCheckResult> {
|
||
const root = opts.root ?? benchDir();
|
||
const tmp = mkdtempSync(join(tmpdir(), "bench-ctx-"));
|
||
const ctxFile = join(tmp, "context.json");
|
||
writeFileSync(ctxFile, JSON.stringify(ctx));
|
||
const env = { ...process.env };
|
||
delete env.NODE_TEST_CONTEXT;
|
||
delete env.NODE_TEST_WORKER_ID;
|
||
return new Promise((ok) => {
|
||
execFile(
|
||
process.execPath,
|
||
[join(root, "lib", "run-checks.mjs"), task.dir, resolve(workdir), ctxFile],
|
||
{ cwd: tmp, env, timeout: opts.timeoutMs ?? 10 * 60_000, maxBuffer: 4 * 1024 * 1024 },
|
||
(err, stdout, stderr) => {
|
||
rmSync(tmp, { recursive: true, force: true });
|
||
const last = String(stdout).trim().split("\n").pop() ?? "";
|
||
try {
|
||
ok(JSON.parse(last) as BenchCheckResult);
|
||
} catch {
|
||
ok({ ok: false, passed: 0, total: 0, cases: [], error: `checks crashed: ${(err?.message ?? "").slice(0, 300)} ${String(stderr).slice(-500)}`.trim() });
|
||
}
|
||
},
|
||
);
|
||
});
|
||
}
|