PEP-184: основа эталона, запуск скрытых проверок, задачи 1–4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
139a8618ca
commit
76ff373eee
2
bench/base/.gitignore
vendored
Normal file
2
bench/base/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
product/data/
|
||||
node_modules/
|
||||
36
bench/base/AGENTS.md
Normal file
36
bench/base/AGENTS.md
Normal file
@ -0,0 +1,36 @@
|
||||
# AGENTS.md
|
||||
|
||||
Проект ведётся софтвейр-фабрикой **Пеппа**: задачи (`PEP-42`), цели и вопросы к PM —
|
||||
через MCP-сервер `peppa`, изменения — через OpenSpec (`openspec/`).
|
||||
|
||||
**Общие правила Пеппы** не хранятся в этом репозитории: в сессиях, запущенных Пеппой, они уже в
|
||||
системном промпте. Если ты их не видишь, первым делом вызови `peppa.get_rules`.
|
||||
|
||||
Ниже — специфика этого проекта. Её нужно соблюдать: на ней держатся проверки и выкатка.
|
||||
|
||||
## Стек
|
||||
|
||||
- Продукт — Node.js ≥ 22 **без внешних зависимостей**: только встроенные модули (`node:http`,
|
||||
`node:fs`, `node:test`…). `package.json` с зависимостями не добавлять.
|
||||
- Запуск: `node product/server.mjs`. Слушает `$PORT` (по умолчанию 3000), `GET /healthz` → 200.
|
||||
- Маршруты — `product/routes.mjs` (массив `{method, path, handler}`, параметры пути — `:id`);
|
||||
помощники ответа и разметки — `product/lib/http.mjs`.
|
||||
- Данные — `product/lib/store.mjs`: коллекции в JSON-файлах каталога `$DATA_DIR`
|
||||
(по умолчанию `product/data`, он в `.gitignore`). Данные переживают перезапуск.
|
||||
- Тесты: `node --test "product/test/*.test.mjs"`. Тест, который поднимает сервер, берёт
|
||||
свободный порт и свой временный `DATA_DIR`.
|
||||
|
||||
## Соглашения API
|
||||
|
||||
- Форма продукта отправляет JSON `POST /api/<сущность>` (например `/api/signups`): успех —
|
||||
201 и созданная запись `{id, …}`; ошибка в полях — 400 `{errors: {<поле>: "<текст для человека>"}}`.
|
||||
- Список записей — `GET /api/<сущность>` → 200, JSON-массив.
|
||||
- Одна запись — `GET /api/<сущность>/<id>`; действие над записью — `POST /api/<сущность>/<id>/<действие>`
|
||||
(например `/api/orders/7/cancel`).
|
||||
- Поля в JSON — латиницей в camelCase, как в коде; даты — `YYYY-MM-DD`.
|
||||
- Страницы — HTML с сервера (`page()` из `product/lib/http.mjs`), на русском, обращение на «вы».
|
||||
|
||||
## Продукт по ссылке
|
||||
|
||||
Продукт открывается по ссылке (`<slug>-staging.telecom.quest`): `Dockerfile` в корне собирает
|
||||
образ из `product/`. Подробности — общие правила, разделы «Завершение» и «CD: деплой».
|
||||
7
bench/base/Dockerfile
Normal file
7
bench/base/Dockerfile
Normal file
@ -0,0 +1,7 @@
|
||||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY product/ ./product/
|
||||
ENV NODE_ENV=production PORT=3000 DATA_DIR=/data
|
||||
VOLUME /data
|
||||
EXPOSE 3000
|
||||
CMD ["node", "product/server.mjs"]
|
||||
69
bench/base/product/lib/http.mjs
Normal file
69
bench/base/product/lib/http.mjs
Normal file
@ -0,0 +1,69 @@
|
||||
// Маленький роутер и помощники ответа. Маршрут: { method, path: "/api/items/:id", handler(ctx) }.
|
||||
// ctx = { req, res, params, query, body() }.
|
||||
|
||||
export function match(pattern, pathname) {
|
||||
const a = pattern.split("/").filter(Boolean);
|
||||
const b = pathname.split("/").filter(Boolean);
|
||||
if (a.length !== b.length) return null;
|
||||
const params = {};
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
if (a[i].startsWith(":")) params[a[i].slice(1)] = decodeURIComponent(b[i]);
|
||||
else if (a[i] !== b[i]) return null;
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
export async function handle(routes, req, res) {
|
||||
const url = new URL(req.url ?? "/", "http://local");
|
||||
for (const r of routes) {
|
||||
if (r.method !== req.method) continue;
|
||||
const params = match(r.path, url.pathname);
|
||||
if (!params) continue;
|
||||
await r.handler({ req, res, params, query: Object.fromEntries(url.searchParams), body: () => readBody(req) });
|
||||
return;
|
||||
}
|
||||
html(res, page("Страница не найдена", "<h1>Страница не найдена</h1>"), 404);
|
||||
}
|
||||
|
||||
export async function readBody(req) {
|
||||
const chunks = [];
|
||||
for await (const c of req) chunks.push(c);
|
||||
const raw = Buffer.concat(chunks).toString("utf8");
|
||||
if (!raw) return {};
|
||||
const type = String(req.headers["content-type"] ?? "");
|
||||
if (type.includes("application/x-www-form-urlencoded")) return Object.fromEntries(new URLSearchParams(raw));
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function json(res, status, body) {
|
||||
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
export function html(res, body, status = 200) {
|
||||
res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
||||
res.end(body);
|
||||
}
|
||||
|
||||
export function esc(s) {
|
||||
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
||||
}
|
||||
|
||||
export function page(title, body) {
|
||||
return `<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${esc(title)}</title>
|
||||
<style>body{font-family:system-ui,sans-serif;max-width:760px;margin:2rem auto;padding:0 1rem;line-height:1.5}</style>
|
||||
</head>
|
||||
<body>
|
||||
${body}
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
42
bench/base/product/lib/store.mjs
Normal file
42
bench/base/product/lib/store.mjs
Normal file
@ -0,0 +1,42 @@
|
||||
// Хранилище: коллекции записей в JSON-файлах каталога $DATA_DIR (по умолчанию product/data).
|
||||
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
function dataDir() {
|
||||
return process.env.DATA_DIR || new URL("../data/", import.meta.url).pathname;
|
||||
}
|
||||
|
||||
export function collection(name) {
|
||||
const file = () => join(dataDir(), `${name}.json`);
|
||||
const load = () => {
|
||||
try {
|
||||
return JSON.parse(readFileSync(file(), "utf8"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
const save = (rows) => {
|
||||
mkdirSync(dataDir(), { recursive: true });
|
||||
writeFileSync(`${file()}.tmp`, JSON.stringify(rows, null, 2));
|
||||
renameSync(`${file()}.tmp`, file());
|
||||
};
|
||||
return {
|
||||
all: () => load(),
|
||||
get: (id) => load().find((r) => String(r.id) === String(id)) ?? null,
|
||||
add(fields) {
|
||||
const rows = load();
|
||||
const row = { id: rows.reduce((m, r) => Math.max(m, Number(r.id) || 0), 0) + 1, ...fields };
|
||||
rows.push(row);
|
||||
save(rows);
|
||||
return row;
|
||||
},
|
||||
update(id, patch) {
|
||||
const rows = load();
|
||||
const i = rows.findIndex((r) => String(r.id) === String(id));
|
||||
if (i < 0) return null;
|
||||
rows[i] = { ...rows[i], ...patch, id: rows[i].id };
|
||||
save(rows);
|
||||
return rows[i];
|
||||
},
|
||||
};
|
||||
}
|
||||
17
bench/base/product/routes.mjs
Normal file
17
bench/base/product/routes.mjs
Normal file
@ -0,0 +1,17 @@
|
||||
import { html, page } from "./lib/http.mjs";
|
||||
|
||||
export const routes = [
|
||||
{
|
||||
method: "GET",
|
||||
path: "/healthz",
|
||||
handler: ({ res }) => {
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("ok");
|
||||
},
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "/",
|
||||
handler: ({ res }) => html(res, page("Продукт создаётся", "<h1>Продукт создаётся</h1><p>Скоро здесь будет сайт.</p>")),
|
||||
},
|
||||
];
|
||||
14
bench/base/product/server.mjs
Normal file
14
bench/base/product/server.mjs
Normal file
@ -0,0 +1,14 @@
|
||||
// Точка входа продукта: `node product/server.mjs`. Слушает $PORT, отвечает 200 на GET /healthz.
|
||||
import { createServer } from "node:http";
|
||||
import { handle } from "./lib/http.mjs";
|
||||
import { routes } from "./routes.mjs";
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
|
||||
createServer((req, res) => {
|
||||
handle(routes, req, res).catch((e) => {
|
||||
console.error(e);
|
||||
if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("Внутренняя ошибка");
|
||||
});
|
||||
}).listen(port, "0.0.0.0", () => console.log(`product on :${port}`));
|
||||
13
bench/base/product/test/health.test.mjs
Normal file
13
bench/base/product/test/health.test.mjs
Normal file
@ -0,0 +1,13 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { startApp } from "./helpers.mjs";
|
||||
|
||||
test("healthz отвечает 200", async () => {
|
||||
const app = await startApp();
|
||||
try {
|
||||
const r = await fetch(`${app.url}/healthz`);
|
||||
assert.equal(r.status, 200);
|
||||
} finally {
|
||||
app.stop();
|
||||
}
|
||||
});
|
||||
32
bench/base/product/test/helpers.mjs
Normal file
32
bench/base/product/test/helpers.mjs
Normal file
@ -0,0 +1,32 @@
|
||||
// Поднять продукт для теста: свободный порт, свой временный DATA_DIR.
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtempSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createServer } from "node:net";
|
||||
|
||||
async function freePort() {
|
||||
return new Promise((resolve) => {
|
||||
const s = createServer().listen(0, "127.0.0.1", () => {
|
||||
const { port } = s.address();
|
||||
s.close(() => resolve(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function startApp(env = {}) {
|
||||
const port = await freePort();
|
||||
const dataDir = mkdtempSync(join(tmpdir(), "product-test-"));
|
||||
const child = spawn(process.execPath, [new URL("../server.mjs", import.meta.url).pathname], {
|
||||
env: { PATH: process.env.PATH, PORT: String(port), DATA_DIR: dataDir, ...env },
|
||||
stdio: "ignore",
|
||||
});
|
||||
const url = `http://127.0.0.1:${port}`;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
try {
|
||||
if ((await fetch(`${url}/healthz`)).ok) break;
|
||||
} catch {}
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
return { url, dataDir, stop: () => child.kill() };
|
||||
}
|
||||
58
bench/lib/check-kit.mjs
Normal file
58
bench/lib/check-kit.mjs
Normal file
@ -0,0 +1,58 @@
|
||||
// Помощники скрытых проверок эталона (PEP-184).
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { join, relative } from "node:path";
|
||||
|
||||
/** Видимый текст страницы: без тегов, скриптов, стилей; пробелы схлопнуты. */
|
||||
export function visibleText(html) {
|
||||
return String(html)
|
||||
.replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/ /g, " ")
|
||||
.replace(/«/g, "«")
|
||||
.replace(/»/g, "»")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/&/g, "&")
|
||||
.replace(/[\s ]+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Цифры без пробелов-разделителей: «1 500 ₸» → «1500 ₸». */
|
||||
export function digits(s) {
|
||||
return String(s).replace(/(\d)[\s ](?=\d{3}\b)/g, "$1");
|
||||
}
|
||||
|
||||
export function assertText(html, needle, what = needle) {
|
||||
const text = digits(visibleText(html)).toLowerCase();
|
||||
assert.ok(text.includes(digits(needle).toLowerCase()), `на странице нет «${what}»`);
|
||||
}
|
||||
|
||||
export async function page(t, path) {
|
||||
const r = await t.app.get(path);
|
||||
assert.equal(r.status, 200, `${path} ответил ${r.status}`);
|
||||
return r.text;
|
||||
}
|
||||
|
||||
/** Все файлы рабочей копии (без .git и данных), пути относительно корня. */
|
||||
export function files(root, dir = root) {
|
||||
const out = [];
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === ".git" || name === "node_modules" || name === ".bench-data") continue;
|
||||
const p = join(dir, name);
|
||||
if (statSync(p).isDirectory()) out.push(...files(root, p));
|
||||
else out.push(relative(root, p));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function read(root, path) {
|
||||
return readFileSync(join(root, path), "utf8");
|
||||
}
|
||||
|
||||
/** Вопросы продакту за задачу (контекст фабрики). */
|
||||
export function questions(t) {
|
||||
return Array.isArray(t.ctx.questions) ? t.ctx.questions : [];
|
||||
}
|
||||
187
bench/lib/run-checks.mjs
Normal file
187
bench/lib/run-checks.mjs
Normal file
@ -0,0 +1,187 @@
|
||||
#!/usr/bin/env node
|
||||
// Скрытые проверки эталонной задачи (PEP-184).
|
||||
// node bench/lib/run-checks.mjs <taskDir> <workdir> [context.json]
|
||||
// Копирует рабочую копию во временный каталог (проверки и продукт ничего не пишут в оригинал),
|
||||
// поднимает продукт `node product/server.mjs` на свободном порту со своим DATA_DIR и без
|
||||
// окружения платформы, выполняет случаи из <taskDir>/checks/check.mjs по порядку и печатает
|
||||
// последней строкой JSON {ok, passed, total, cases, error?}. Код выхода 0 — засчитано, 1 — нет.
|
||||
//
|
||||
// check.mjs: `export default [{ name, run(t) }]` и необязательный `export async function setup(t)`
|
||||
// → `{ env?, teardown? }` (например, мок внешнего сервиса). t = { app, ctx, workdir, assert, run }.
|
||||
import { spawn } from "node:child_process";
|
||||
import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, join, resolve } from "node:path";
|
||||
import { createServer } from "node:net";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const CASE_TIMEOUT_MS = Number(process.env.BENCH_CASE_TIMEOUT_MS ?? 30_000);
|
||||
const START_TIMEOUT_MS = Number(process.env.BENCH_START_TIMEOUT_MS ?? 15_000);
|
||||
|
||||
export async function freePort() {
|
||||
return new Promise((ok, fail) => {
|
||||
const s = createServer().once("error", fail).listen(0, "127.0.0.1", () => {
|
||||
const { port } = s.address();
|
||||
s.close(() => ok(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function cleanEnv(extra = {}) {
|
||||
// Только самое нужное: продукт эталона не должен видеть ключи и настройки платформы.
|
||||
return { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: process.env.HOME ?? tmpdir(), LANG: "ru_RU.UTF-8", ...extra };
|
||||
}
|
||||
|
||||
async function response(r) {
|
||||
const text = await r.text();
|
||||
return {
|
||||
status: r.status,
|
||||
headers: r.headers,
|
||||
text,
|
||||
json() {
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
class App {
|
||||
constructor(dir, env) {
|
||||
this.dir = dir;
|
||||
this.env = env;
|
||||
this.dataDir = join(dir, ".bench-data");
|
||||
this.child = null;
|
||||
this.log = "";
|
||||
}
|
||||
|
||||
async start() {
|
||||
const port = await freePort();
|
||||
this.url = `http://127.0.0.1:${port}`;
|
||||
this.log = "";
|
||||
const child = spawn(process.execPath, ["product/server.mjs"], {
|
||||
cwd: this.dir,
|
||||
env: cleanEnv({ PORT: String(port), DATA_DIR: this.dataDir, ...this.env }),
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
this.child = child;
|
||||
let exited = false;
|
||||
child.on("exit", () => (exited = true));
|
||||
const keep = (d) => (this.log = (this.log + d).slice(-4000));
|
||||
child.stdout.on("data", keep);
|
||||
child.stderr.on("data", keep);
|
||||
const until = Date.now() + START_TIMEOUT_MS;
|
||||
while (Date.now() < until && !exited) {
|
||||
try {
|
||||
if ((await fetch(`${this.url}/healthz`)).status === 200) return;
|
||||
} catch {}
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
await this.stop();
|
||||
throw new Error(`продукт не запустился${this.log ? `: ${this.log.trim().split("\n").slice(-5).join(" | ")}` : ""}`);
|
||||
}
|
||||
|
||||
async stop() {
|
||||
const child = this.child;
|
||||
this.child = null;
|
||||
if (!child || child.exitCode !== null) return;
|
||||
await new Promise((r) => {
|
||||
child.once("exit", r);
|
||||
child.kill("SIGTERM");
|
||||
setTimeout(() => child.kill("SIGKILL"), 2000).unref();
|
||||
});
|
||||
}
|
||||
|
||||
async restart() {
|
||||
await this.stop();
|
||||
await this.start();
|
||||
}
|
||||
|
||||
async get(path) {
|
||||
return response(await fetch(this.url + path, { redirect: "manual" }));
|
||||
}
|
||||
|
||||
async post(path, body, { form = false } = {}) {
|
||||
const init = form
|
||||
? { body: new URLSearchParams(body).toString(), headers: { "content-type": "application/x-www-form-urlencoded" } }
|
||||
: { body: body === undefined ? undefined : JSON.stringify(body), headers: { "content-type": "application/json" } };
|
||||
return response(await fetch(this.url + path, { method: "POST", redirect: "manual", ...init }));
|
||||
}
|
||||
}
|
||||
|
||||
/** Команда в копии рабочей папки (например, видимые тесты проекта). */
|
||||
function runIn(dir) {
|
||||
return (cmd, args, { timeoutMs = 120_000 } = {}) =>
|
||||
new Promise((ok) => {
|
||||
const env = cleanEnv();
|
||||
const child = spawn(cmd === "node" ? process.execPath : cmd, args, { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] });
|
||||
let out = "";
|
||||
const keep = (d) => (out = (out + d).slice(-8000));
|
||||
child.stdout.on("data", keep);
|
||||
child.stderr.on("data", keep);
|
||||
const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
ok({ code, out });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms) {
|
||||
let timer;
|
||||
return Promise.race([
|
||||
promise,
|
||||
new Promise((_, fail) => (timer = setTimeout(() => fail(new Error(`не уложилось в ${ms / 1000} с`)), ms))),
|
||||
]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
export async function runChecks(taskDir, workdir, ctx = {}) {
|
||||
const mod = await import(pathToFileURL(join(resolve(taskDir), "checks", "check.mjs")).href);
|
||||
const cases = mod.default ?? [];
|
||||
const copy = mkdtempSync(join(tmpdir(), `bench-${basename(resolve(taskDir))}-`));
|
||||
cpSync(workdir, copy, { recursive: true, filter: (src) => !/(^|\/)(\.git|node_modules|\.bench-data)$/.test(src) });
|
||||
const context = { questions: [], needs: [], ...ctx };
|
||||
const t = { ctx: context, workdir: copy, assert, run: runIn(copy), app: null };
|
||||
const result = { ok: false, passed: 0, total: cases.length, cases: [] };
|
||||
let teardown;
|
||||
let app;
|
||||
try {
|
||||
const prepared = mod.setup ? await mod.setup(t) : {};
|
||||
teardown = prepared?.teardown;
|
||||
app = new App(copy, prepared?.env ?? {});
|
||||
t.app = app;
|
||||
await app.start();
|
||||
for (const c of cases) {
|
||||
try {
|
||||
await withTimeout(Promise.resolve().then(() => c.run(t)), CASE_TIMEOUT_MS);
|
||||
result.cases.push({ name: c.name, ok: true });
|
||||
result.passed++;
|
||||
} catch (e) {
|
||||
result.cases.push({ name: c.name, ok: false, detail: String(e?.message ?? e).slice(0, 500) });
|
||||
}
|
||||
}
|
||||
result.ok = result.total > 0 && result.passed === result.total;
|
||||
} catch (e) {
|
||||
result.error = String(e?.message ?? e).slice(0, 1000);
|
||||
} finally {
|
||||
await app?.stop().catch(() => {});
|
||||
await Promise.resolve(teardown?.()).catch(() => {});
|
||||
rmSync(copy, { recursive: true, force: true });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
|
||||
const [taskDir, workdir, contextPath] = process.argv.slice(2);
|
||||
if (!taskDir || !workdir) {
|
||||
console.error("usage: run-checks.mjs <taskDir> <workdir> [context.json]");
|
||||
process.exit(2);
|
||||
}
|
||||
const ctx = contextPath ? JSON.parse(readFileSync(contextPath, "utf8")) : {};
|
||||
const result = await runChecks(taskDir, workdir, ctx);
|
||||
process.stdout.write(`\n${JSON.stringify(result)}\n`);
|
||||
process.exit(result.ok ? 0 : 1);
|
||||
}
|
||||
67
bench/tasks/01-landing/checks/check.mjs
Normal file
67
bench/tasks/01-landing/checks/check.mjs
Normal file
@ -0,0 +1,67 @@
|
||||
// BENCH-HIDDEN — скрытые проверки задачи 1 (лендинг). Агент их не видит.
|
||||
import { assertText, page } from "../../../lib/check-kit.mjs";
|
||||
|
||||
export default [
|
||||
{
|
||||
name: "заглушка заменена сайтом кофейни",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
t.assert.ok(!html.includes("Продукт создаётся"), "на главной всё ещё заглушка");
|
||||
assertText(html, "Зерно");
|
||||
assertText(html, "Кофе, который обжариваем сами");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "название вкладки",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
const title = html.match(/<title>([^<]*)<\/title>/i)?.[1] ?? "";
|
||||
t.assert.match(title.replace(/—|—|–|-/g, "—"), /Зерно\s*—\s*кофейня/i, `title: «${title}»`);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "три причины прийти",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
assertText(html, "обжар");
|
||||
assertText(html, "десерт");
|
||||
assertText(html, "розетк");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "меню с ценами",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
for (const [item, price] of [["эспрессо", "900"], ["капучино", "1300"], ["раф", "1600"]]) {
|
||||
assertText(html, item);
|
||||
assertText(html, price, `${item} — ${price}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "адрес и часы работы",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
assertText(html, "Панфилова, 98");
|
||||
assertText(html, "8:00");
|
||||
assertText(html, "22:00");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "кнопка «Позвонить» набирает номер",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
const link = html.match(/<a\b[^>]*href=["']tel:([^"']+)["'][^>]*>([\s\S]*?)<\/a>/i);
|
||||
t.assert.ok(link, "нет ссылки tel:");
|
||||
t.assert.equal(link[1].replace(/[^\d+]/g, ""), "+77011234567");
|
||||
t.assert.match(link[2], /Позвонить/);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "страница для телефона",
|
||||
async run(t) {
|
||||
const html = await page(t, "/");
|
||||
t.assert.match(html, /<meta[^>]+name=["']viewport["'][^>]*width=device-width/i);
|
||||
},
|
||||
},
|
||||
];
|
||||
8
bench/tasks/01-landing/meta.json
Normal file
8
bench/tasks/01-landing/meta.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"hidden": "BENCH-HIDDEN",
|
||||
"num": 1,
|
||||
"title": "Лендинг по текстовому описанию",
|
||||
"kind": "landing",
|
||||
"timeLimitMin": 60,
|
||||
"tokenLimit": 4000000
|
||||
}
|
||||
0
bench/tasks/01-landing/repo/.gitkeep
Normal file
0
bench/tasks/01-landing/repo/.gitkeep
Normal file
21
bench/tasks/01-landing/solution/product/routes.mjs
Normal file
21
bench/tasks/01-landing/solution/product/routes.mjs
Normal file
@ -0,0 +1,21 @@
|
||||
// BENCH-HIDDEN — эталонное решение задачи 1.
|
||||
import { html, page } from "./lib/http.mjs";
|
||||
|
||||
const body = `
|
||||
<h1>Зерно</h1>
|
||||
<p>Кофе, который обжариваем сами</p>
|
||||
<h2>Почему к нам</h2>
|
||||
<ul>
|
||||
<li>Свежая обжарка каждую неделю</li>
|
||||
<li>Десерты собственного приготовления</li>
|
||||
<li>Тихий зал для работы, розетки у каждого стола</li>
|
||||
</ul>
|
||||
<h2>Меню</h2>
|
||||
<ul><li>Эспрессо — 900 ₸</li><li>Капучино — 1 300 ₸</li><li>Раф — 1 600 ₸</li></ul>
|
||||
<p>Алматы, ул. Панфилова, 98 · ежедневно с 8:00 до 22:00</p>
|
||||
<p><a href="tel:+77011234567" style="font-size:1.5rem">Позвонить</a></p>`;
|
||||
|
||||
export const routes = [
|
||||
{ method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") },
|
||||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Зерно — кофейня", body)) },
|
||||
];
|
||||
15
bench/tasks/01-landing/story.md
Normal file
15
bench/tasks/01-landing/story.md
Normal file
@ -0,0 +1,15 @@
|
||||
# Сайт для кофейни «Зерно»
|
||||
Эпик: Сайт
|
||||
|
||||
Нам нужен одностраничный сайт кофейни «Зерно». Сейчас по ссылке открывается заглушка «Продукт
|
||||
создаётся», вместо неё должен быть настоящий сайт.
|
||||
|
||||
Что должно быть на странице:
|
||||
- название «Зерно» и короткая фраза «Кофе, который обжариваем сами»;
|
||||
- три причины прийти к нам: свежая обжарка каждую неделю, десерты собственного приготовления,
|
||||
тихий зал для работы с розетками у каждого стола;
|
||||
- меню с ценами: эспрессо — 900 ₸, капучино — 1 300 ₸, раф — 1 600 ₸;
|
||||
- адрес: Алматы, ул. Панфилова, 98; часы работы: ежедневно с 8:00 до 22:00;
|
||||
- большая кнопка «Позвонить», которая на телефоне сразу набирает +7 701 123 45 67.
|
||||
|
||||
Сайт должен нормально выглядеть на телефоне. Название вкладки браузера — «Зерно — кофейня».
|
||||
98
bench/tasks/02-form/checks/check.mjs
Normal file
98
bench/tasks/02-form/checks/check.mjs
Normal file
@ -0,0 +1,98 @@
|
||||
// BENCH-HIDDEN — скрытые проверки задачи 2 (форма записи).
|
||||
import { assertText, page } from "../../../lib/check-kit.mjs";
|
||||
|
||||
const valid = { childName: "Аружан", phone: "+7 (701) 123-45-67", age: 8 };
|
||||
|
||||
async function list(t) {
|
||||
const r = await t.app.get("/api/signups");
|
||||
t.assert.equal(r.status, 200, `GET /api/signups ответил ${r.status}`);
|
||||
const rows = r.json();
|
||||
t.assert.ok(Array.isArray(rows), "GET /api/signups — не массив");
|
||||
return rows;
|
||||
}
|
||||
|
||||
async function rejected(t, body, field) {
|
||||
const before = (await list(t)).length;
|
||||
const r = await t.app.post("/api/signups", body);
|
||||
t.assert.equal(r.status, 400, `ожидали 400 для ${JSON.stringify(body)}, получили ${r.status}`);
|
||||
const msg = r.json()?.errors?.[field];
|
||||
t.assert.ok(typeof msg === "string" && msg.trim().length > 0, `нет текста ошибки для поля ${field}`);
|
||||
t.assert.equal((await list(t)).length, before, "неправильная заявка сохранилась");
|
||||
}
|
||||
|
||||
export default [
|
||||
{
|
||||
name: "правильная заявка сохраняется, телефон в одном виде",
|
||||
async run(t) {
|
||||
const r = await t.app.post("/api/signups", valid);
|
||||
t.assert.equal(r.status, 201, `POST ответил ${r.status}: ${r.text.slice(0, 200)}`);
|
||||
t.assert.ok(r.json()?.id !== undefined, "в ответе нет id");
|
||||
const row = (await list(t)).find((x) => x.childName === "Аружан");
|
||||
t.assert.ok(row, "заявки нет в списке");
|
||||
t.assert.equal(row.phone, "+77011234567");
|
||||
t.assert.equal(Number(row.age), 8);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "номер через 8 тоже нормальный",
|
||||
async run(t) {
|
||||
const r = await t.app.post("/api/signups", { childName: "Тимур", phone: "8 701 765 43 21", age: 12 });
|
||||
t.assert.equal(r.status, 201, `POST ответил ${r.status}: ${r.text.slice(0, 200)}`);
|
||||
t.assert.equal((await list(t)).find((x) => x.childName === "Тимур")?.phone, "+77017654321");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "заявки переживают перезапуск",
|
||||
async run(t) {
|
||||
await t.app.restart();
|
||||
t.assert.ok((await list(t)).some((x) => x.childName === "Аружан"), "после перезапуска заявки нет");
|
||||
},
|
||||
},
|
||||
{ name: "пустое имя — ошибка", run: (t) => rejected(t, { ...valid, childName: "" }, "childName") },
|
||||
{ name: "имя из одной буквы — ошибка", run: (t) => rejected(t, { ...valid, childName: "А" }, "childName") },
|
||||
{ name: "короткий телефон — ошибка", run: (t) => rejected(t, { ...valid, phone: "12345" }, "phone") },
|
||||
{ name: "чужой код страны — ошибка", run: (t) => rejected(t, { ...valid, phone: "+1 701 123 45 67" }, "phone") },
|
||||
{ name: "возраст 5 — ошибка", run: (t) => rejected(t, { ...valid, age: 5 }, "age") },
|
||||
{ name: "возраст 15 — ошибка", run: (t) => rejected(t, { ...valid, age: 15 }, "age") },
|
||||
{
|
||||
name: "границы возраста 6 и 14 принимаются",
|
||||
async run(t) {
|
||||
for (const age of [6, 14]) {
|
||||
const r = await t.app.post("/api/signups", { ...valid, childName: `Граница ${age}`, age });
|
||||
t.assert.equal(r.status, 201, `возраст ${age}: ${r.status}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "страница записи с формой",
|
||||
async run(t) {
|
||||
const html = await page(t, "/signup");
|
||||
t.assert.match(html, /<form\b/i, "на /signup нет формы");
|
||||
assertText(html, "Имя ребёнка");
|
||||
assertText(html, "Телефон");
|
||||
assertText(html, "Возраст");
|
||||
t.assert.ok(html.includes("Спасибо! Мы позвоним вам в течение дня"), "нет сообщения после отправки");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "страница заявок для администратора",
|
||||
async run(t) {
|
||||
for (const path of ["/signups", "/admin/signups", "/admin"]) {
|
||||
const r = await t.app.get(path);
|
||||
if (r.status === 200 && r.text.includes("Аружан")) {
|
||||
assertText(r.text, "+77011234567");
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Ссылка на страницу заявок может быть где угодно — ищем по главной и странице записи.
|
||||
for (const from of ["/", "/signup"]) {
|
||||
const html = (await t.app.get(from)).text;
|
||||
for (const m of html.matchAll(/href=["'](\/[^"'#?]*)["']/g)) {
|
||||
const r = await t.app.get(m[1]);
|
||||
if (r.status === 200 && r.text.includes("Аружан")) return;
|
||||
}
|
||||
}
|
||||
t.assert.fail("не нашли страницу со списком заявок");
|
||||
},
|
||||
},
|
||||
];
|
||||
8
bench/tasks/02-form/meta.json
Normal file
8
bench/tasks/02-form/meta.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"hidden": "BENCH-HIDDEN",
|
||||
"num": 2,
|
||||
"title": "Форма с проверкой полей и сохранением",
|
||||
"kind": "form",
|
||||
"timeLimitMin": 75,
|
||||
"tokenLimit": 5000000
|
||||
}
|
||||
21
bench/tasks/02-form/repo/product/routes.mjs
Normal file
21
bench/tasks/02-form/repo/product/routes.mjs
Normal file
@ -0,0 +1,21 @@
|
||||
import { html, json, page } from "./lib/http.mjs";
|
||||
|
||||
const home = `
|
||||
<h1>Робостарт</h1>
|
||||
<p>Школа робототехники для детей от 6 до 14 лет.</p>
|
||||
<p><a href="/signup">Записаться на пробный урок</a></p>`;
|
||||
|
||||
export const routes = [
|
||||
{
|
||||
method: "GET",
|
||||
path: "/healthz",
|
||||
handler: ({ res }) => {
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("ok");
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Робостарт", home)) },
|
||||
// Запись на пробный урок. Заявка: { childName, phone, age }.
|
||||
{ method: "GET", path: "/signup", handler: ({ res }) => html(res, page("Запись на пробный урок", "<h1>Запись на пробный урок</h1><p>Скоро здесь будет форма.</p>")) },
|
||||
{ method: "POST", path: "/api/signups", handler: ({ res }) => json(res, 501, { error: "Пока не сделано" }) },
|
||||
];
|
||||
65
bench/tasks/02-form/solution/product/routes.mjs
Normal file
65
bench/tasks/02-form/solution/product/routes.mjs
Normal file
@ -0,0 +1,65 @@
|
||||
// BENCH-HIDDEN — эталонное решение задачи 2.
|
||||
import { esc, html, json, page } from "./lib/http.mjs";
|
||||
import { collection } from "./lib/store.mjs";
|
||||
|
||||
const signups = collection("signups");
|
||||
|
||||
export function normalizePhone(raw) {
|
||||
let d = String(raw ?? "").replace(/[\s()-]/g, "");
|
||||
if (/^8\d{10}$/.test(d)) d = `+7${d.slice(1)}`;
|
||||
return /^\+7\d{10}$/.test(d) ? d : null;
|
||||
}
|
||||
|
||||
export function validate(b) {
|
||||
const errors = {};
|
||||
const name = String(b.childName ?? "").trim();
|
||||
if (name.length < 2 || name.length > 50) errors.childName = "Укажите имя ребёнка: от 2 до 50 букв.";
|
||||
const phone = normalizePhone(b.phone);
|
||||
if (!phone) errors.phone = "Укажите номер в виде +7 и 10 цифр.";
|
||||
const age = Number(b.age);
|
||||
if (!Number.isInteger(age) || age < 6 || age > 14) errors.age = "Мы принимаем детей от 6 до 14 лет.";
|
||||
return { errors, value: { childName: name, phone, age } };
|
||||
}
|
||||
|
||||
const form = `
|
||||
<h1>Запись на пробный урок</h1>
|
||||
<form id="f">
|
||||
<label>Имя ребёнка <input name="childName"></label><div data-err="childName"></div>
|
||||
<label>Телефон родителя <input name="phone"></label><div data-err="phone"></div>
|
||||
<label>Возраст ребёнка <input name="age" type="number"></label><div data-err="age"></div>
|
||||
<button>Записаться</button>
|
||||
</form>
|
||||
<p id="ok" hidden>Спасибо! Мы позвоним вам в течение дня</p>
|
||||
<script>
|
||||
f.onsubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
const body = Object.fromEntries(new FormData(f));
|
||||
const r = await fetch("/api/signups", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
document.querySelectorAll("[data-err]").forEach((el) => (el.textContent = ""));
|
||||
if (r.ok) { f.hidden = true; ok.hidden = false; return; }
|
||||
const { errors = {} } = await r.json();
|
||||
for (const [k, v] of Object.entries(errors)) document.querySelector('[data-err="' + k + '"]').textContent = v;
|
||||
};
|
||||
</script>`;
|
||||
|
||||
export const routes = [
|
||||
{ method: "GET", path: "/healthz", handler: ({ res }) => res.writeHead(200).end("ok") },
|
||||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Робостарт", '<h1>Робостарт</h1><a href="/signup">Записаться на пробный урок</a>')) },
|
||||
{ method: "GET", path: "/signup", handler: ({ res }) => html(res, page("Запись на пробный урок", form)) },
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/signups",
|
||||
async handler({ res, body }) {
|
||||
const { errors, value } = validate(await body());
|
||||
if (Object.keys(errors).length) return json(res, 400, { errors });
|
||||
json(res, 201, signups.add(value));
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/api/signups", handler: ({ res }) => json(res, 200, signups.all()) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "/signups",
|
||||
handler: ({ res }) =>
|
||||
html(res, page("Заявки", `<h1>Заявки</h1><table>${signups.all().map((s) => `<tr><td>${esc(s.childName)}</td><td>${esc(s.phone)}</td><td>${s.age}</td></tr>`).join("")}</table>`)),
|
||||
},
|
||||
];
|
||||
18
bench/tasks/02-form/story.md
Normal file
18
bench/tasks/02-form/story.md
Normal file
@ -0,0 +1,18 @@
|
||||
# Запись на пробный урок
|
||||
Эпик: Заявки
|
||||
|
||||
Мы — школа робототехники «Робостарт». На главной уже есть кнопка «Записаться на пробный урок»,
|
||||
но страница записи пока пустая. Сделайте форму записи.
|
||||
|
||||
В форме три поля:
|
||||
- «Имя ребёнка» — обязательно, от 2 до 50 букв;
|
||||
- «Телефон родителя» — казахстанский номер: +7 и ещё 10 цифр. Родители пишут по-разному
|
||||
(«+7 (701) 123-45-67», «8 701 123 45 67») — всё это нормальный номер. Сохраняем его всегда
|
||||
в одном виде: +77011234567;
|
||||
- «Возраст ребёнка» — от 6 до 14 лет, у нас нет групп для других возрастов.
|
||||
|
||||
Если что-то заполнено неправильно, рядом с полем пишем по-человечески, что не так, и заявку не
|
||||
сохраняем. Если всё правильно — показываем «Спасибо! Мы позвоним вам в течение дня».
|
||||
|
||||
Мне нужна страница со всеми заявками (имя, телефон, возраст), чтобы администратор мог обзванивать
|
||||
родителей. Заявки не должны пропадать, даже если сайт перезапустили.
|
||||
37
bench/tasks/03-bugfix/checks/buggy-cart.mjs.txt
Normal file
37
bench/tasks/03-bugfix/checks/buggy-cart.mjs.txt
Normal file
@ -0,0 +1,37 @@
|
||||
// BENCH-HIDDEN — исходный расчёт с ошибкой (для проверки, что тест её ловит).
|
||||
// Расчёт заказа: сумма, скидка по промокоду, доставка, итог.
|
||||
import { findItem } from "./catalog.mjs";
|
||||
|
||||
export const DELIVERY_FEE = 1000;
|
||||
export const FREE_DELIVERY_FROM = 5000;
|
||||
export const PROMOS = { SPRING10: 0.1, FRIEND15: 0.15 };
|
||||
|
||||
export class CartError extends Error {}
|
||||
|
||||
function lines(items) {
|
||||
return (items ?? []).map(({ sku, qty }) => {
|
||||
const item = findItem(sku);
|
||||
if (!item) throw new CartError(`Нет такого товара: ${sku}`);
|
||||
const n = Number(qty);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 99) throw new CartError("Количество — от 1 до 99");
|
||||
return { ...item, qty: n, sum: item.price * n };
|
||||
});
|
||||
}
|
||||
|
||||
function discountFor(subtotal, promo) {
|
||||
const code = String(promo ?? "").trim().toUpperCase();
|
||||
if (!code) return 0;
|
||||
const rate = PROMOS[code];
|
||||
if (rate === undefined) throw new CartError("Такого промокода нет");
|
||||
return Math.round(subtotal * rate);
|
||||
}
|
||||
|
||||
export function quote(items, promo) {
|
||||
const rows = lines(items);
|
||||
if (rows.length === 0) throw new CartError("Корзина пуста");
|
||||
const subtotal = rows.reduce((s, r) => s + r.sum, 0);
|
||||
const discount = discountFor(subtotal, promo);
|
||||
const payable = subtotal - discount;
|
||||
const delivery = payable > FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;
|
||||
return { lines: rows, subtotal, discount, delivery, total: payable + delivery };
|
||||
}
|
||||
60
bench/tasks/03-bugfix/checks/check.mjs
Normal file
60
bench/tasks/03-bugfix/checks/check.mjs
Normal file
@ -0,0 +1,60 @@
|
||||
// BENCH-HIDDEN — скрытые проверки задачи 3 (заложенная ошибка: порог бесплатной доставки).
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const BUGGY = readFileSync(new URL("./buggy-cart.mjs.txt", import.meta.url), "utf8");
|
||||
|
||||
async function q(t, items, promo) {
|
||||
const r = await t.app.post("/api/quote", { items, promo });
|
||||
t.assert.equal(r.status, 200, `POST /api/quote ответил ${r.status}: ${r.text.slice(0, 200)}`);
|
||||
const b = r.json();
|
||||
return [b.subtotal, b.discount, b.delivery, b.total];
|
||||
}
|
||||
|
||||
export default [
|
||||
{
|
||||
name: "заказ ровно на 5 000 ₸ — доставка бесплатно",
|
||||
async run(t) {
|
||||
t.assert.deepEqual(await q(t, [{ sku: "rose", qty: 2 }, { sku: "wrap", qty: 1 }]), [5000, 0, 0, 5000]);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "заказ на 4 900 ₸ — доставка 1 000 ₸",
|
||||
async run(t) {
|
||||
t.assert.deepEqual(await q(t, [{ sku: "vase", qty: 1 }]), [4900, 0, 1000, 5900]);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "порог доставки считается после скидки",
|
||||
async run(t) {
|
||||
// SPRING10: 5 700 → 5 130 (бесплатно); 5 500 → 4 950 (платно).
|
||||
t.assert.deepEqual(await q(t, [{ sku: "peony", qty: 2 }, { sku: "tulip", qty: 1 }], "SPRING10"), [5700, 570, 0, 5130]);
|
||||
t.assert.deepEqual(await q(t, [{ sku: "wrap", qty: 2 }, { sku: "rose", qty: 1 }], "SPRING10"), [5500, 550, 1000, 5950]);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "остальной расчёт не изменился",
|
||||
async run(t) {
|
||||
t.assert.deepEqual(await q(t, [{ sku: "tulip", qty: 3 }]), [2100, 0, 1000, 3100]);
|
||||
t.assert.deepEqual(await q(t, [{ sku: "peony", qty: 2 }], "spring10"), [5000, 500, 1000, 5500]);
|
||||
t.assert.deepEqual(await q(t, [{ sku: "peony", qty: 4 }], "FRIEND15"), [10000, 1500, 0, 8500]);
|
||||
const bad = await t.app.post("/api/quote", { items: [{ sku: "rose", qty: 1 }], promo: "XXX" });
|
||||
t.assert.equal(bad.status, 400);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "тесты проекта зелёные",
|
||||
async run(t) {
|
||||
const r = await t.run("node", ["--test", "product/test/"]);
|
||||
t.assert.equal(r.code, 0, `тесты упали:\n${r.out.slice(-1500)}`);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "тест ловит эту ошибку, если её вернуть",
|
||||
async run(t) {
|
||||
writeFileSync(join(t.workdir, "product", "cart.mjs"), BUGGY);
|
||||
const r = await t.run("node", ["--test", "product/test/"]);
|
||||
t.assert.notEqual(r.code, 0, "со старым расчётом все тесты зелёные — ошибка вернётся незаметно");
|
||||
},
|
||||
},
|
||||
];
|
||||
8
bench/tasks/03-bugfix/meta.json
Normal file
8
bench/tasks/03-bugfix/meta.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"hidden": "BENCH-HIDDEN",
|
||||
"num": 3,
|
||||
"title": "Найти и исправить заложенную ошибку",
|
||||
"kind": "bugfix",
|
||||
"timeLimitMin": 45,
|
||||
"tokenLimit": 3000000
|
||||
}
|
||||
36
bench/tasks/03-bugfix/repo/product/cart.mjs
Normal file
36
bench/tasks/03-bugfix/repo/product/cart.mjs
Normal file
@ -0,0 +1,36 @@
|
||||
// Расчёт заказа: сумма, скидка по промокоду, доставка, итог.
|
||||
import { findItem } from "./catalog.mjs";
|
||||
|
||||
export const DELIVERY_FEE = 1000;
|
||||
export const FREE_DELIVERY_FROM = 5000;
|
||||
export const PROMOS = { SPRING10: 0.1, FRIEND15: 0.15 };
|
||||
|
||||
export class CartError extends Error {}
|
||||
|
||||
function lines(items) {
|
||||
return (items ?? []).map(({ sku, qty }) => {
|
||||
const item = findItem(sku);
|
||||
if (!item) throw new CartError(`Нет такого товара: ${sku}`);
|
||||
const n = Number(qty);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 99) throw new CartError("Количество — от 1 до 99");
|
||||
return { ...item, qty: n, sum: item.price * n };
|
||||
});
|
||||
}
|
||||
|
||||
function discountFor(subtotal, promo) {
|
||||
const code = String(promo ?? "").trim().toUpperCase();
|
||||
if (!code) return 0;
|
||||
const rate = PROMOS[code];
|
||||
if (rate === undefined) throw new CartError("Такого промокода нет");
|
||||
return Math.round(subtotal * rate);
|
||||
}
|
||||
|
||||
export function quote(items, promo) {
|
||||
const rows = lines(items);
|
||||
if (rows.length === 0) throw new CartError("Корзина пуста");
|
||||
const subtotal = rows.reduce((s, r) => s + r.sum, 0);
|
||||
const discount = discountFor(subtotal, promo);
|
||||
const payable = subtotal - discount;
|
||||
const delivery = payable > FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;
|
||||
return { lines: rows, subtotal, discount, delivery, total: payable + delivery };
|
||||
}
|
||||
12
bench/tasks/03-bugfix/repo/product/catalog.mjs
Normal file
12
bench/tasks/03-bugfix/repo/product/catalog.mjs
Normal file
@ -0,0 +1,12 @@
|
||||
export const catalog = [
|
||||
{ sku: "rose", title: "Роза", price: 1500 },
|
||||
{ sku: "tulip", title: "Тюльпан", price: 700 },
|
||||
{ sku: "peony", title: "Пион", price: 2500 },
|
||||
{ sku: "wrap", title: "Упаковка", price: 2000 },
|
||||
{ sku: "card", title: "Открытка", price: 300 },
|
||||
{ sku: "vase", title: "Ваза", price: 4900 },
|
||||
];
|
||||
|
||||
export function findItem(sku) {
|
||||
return catalog.find((i) => i.sku === sku) ?? null;
|
||||
}
|
||||
34
bench/tasks/03-bugfix/repo/product/routes.mjs
Normal file
34
bench/tasks/03-bugfix/repo/product/routes.mjs
Normal file
@ -0,0 +1,34 @@
|
||||
import { esc, html, json, page } from "./lib/http.mjs";
|
||||
import { catalog } from "./catalog.mjs";
|
||||
import { CartError, quote } from "./cart.mjs";
|
||||
|
||||
const home = () => `
|
||||
<h1>Пион</h1>
|
||||
<p>Цветы с доставкой по Алматы. Доставка бесплатно от 5 000 ₸.</p>
|
||||
<ul>${catalog.map((i) => `<li>${esc(i.title)} — ${i.price} ₸</li>`).join("")}</ul>`;
|
||||
|
||||
export const routes = [
|
||||
{
|
||||
method: "GET",
|
||||
path: "/healthz",
|
||||
handler: ({ res }) => {
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("ok");
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Пион — цветы", home())) },
|
||||
{
|
||||
// Расчёт заказа: { items: [{ sku, qty }], promo? } → { subtotal, discount, delivery, total }.
|
||||
method: "POST",
|
||||
path: "/api/quote",
|
||||
async handler({ res, body }) {
|
||||
const b = await body();
|
||||
try {
|
||||
json(res, 200, quote(b.items, b.promo));
|
||||
} catch (e) {
|
||||
if (e instanceof CartError) return json(res, 400, { errors: { items: e.message } });
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
24
bench/tasks/03-bugfix/repo/product/test/cart.test.mjs
Normal file
24
bench/tasks/03-bugfix/repo/product/test/cart.test.mjs
Normal file
@ -0,0 +1,24 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { CartError, quote } from "../cart.mjs";
|
||||
|
||||
test("маленький заказ — платная доставка", () => {
|
||||
const q = quote([{ sku: "tulip", qty: 3 }]);
|
||||
assert.deepEqual([q.subtotal, q.discount, q.delivery, q.total], [2100, 0, 1000, 3100]);
|
||||
});
|
||||
|
||||
test("большой заказ — доставка бесплатно", () => {
|
||||
const q = quote([{ sku: "peony", qty: 3 }]);
|
||||
assert.deepEqual([q.subtotal, q.delivery, q.total], [7500, 0, 7500]);
|
||||
});
|
||||
|
||||
test("промокод уменьшает сумму, порог доставки — после скидки", () => {
|
||||
const q = quote([{ sku: "peony", qty: 2 }], "spring10");
|
||||
assert.deepEqual([q.subtotal, q.discount, q.delivery, q.total], [5000, 500, 1000, 5500]);
|
||||
});
|
||||
|
||||
test("неизвестный промокод и товар — ошибка", () => {
|
||||
assert.throws(() => quote([{ sku: "rose", qty: 1 }], "XXX"), CartError);
|
||||
assert.throws(() => quote([{ sku: "cactus", qty: 1 }]), CartError);
|
||||
assert.throws(() => quote([]), CartError);
|
||||
});
|
||||
37
bench/tasks/03-bugfix/solution/product/cart.mjs
Normal file
37
bench/tasks/03-bugfix/solution/product/cart.mjs
Normal file
@ -0,0 +1,37 @@
|
||||
// BENCH-HIDDEN — эталонное решение задачи 3.
|
||||
// Расчёт заказа: сумма, скидка по промокоду, доставка, итог.
|
||||
import { findItem } from "./catalog.mjs";
|
||||
|
||||
export const DELIVERY_FEE = 1000;
|
||||
export const FREE_DELIVERY_FROM = 5000;
|
||||
export const PROMOS = { SPRING10: 0.1, FRIEND15: 0.15 };
|
||||
|
||||
export class CartError extends Error {}
|
||||
|
||||
function lines(items) {
|
||||
return (items ?? []).map(({ sku, qty }) => {
|
||||
const item = findItem(sku);
|
||||
if (!item) throw new CartError(`Нет такого товара: ${sku}`);
|
||||
const n = Number(qty);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 99) throw new CartError("Количество — от 1 до 99");
|
||||
return { ...item, qty: n, sum: item.price * n };
|
||||
});
|
||||
}
|
||||
|
||||
function discountFor(subtotal, promo) {
|
||||
const code = String(promo ?? "").trim().toUpperCase();
|
||||
if (!code) return 0;
|
||||
const rate = PROMOS[code];
|
||||
if (rate === undefined) throw new CartError("Такого промокода нет");
|
||||
return Math.round(subtotal * rate);
|
||||
}
|
||||
|
||||
export function quote(items, promo) {
|
||||
const rows = lines(items);
|
||||
if (rows.length === 0) throw new CartError("Корзина пуста");
|
||||
const subtotal = rows.reduce((s, r) => s + r.sum, 0);
|
||||
const discount = discountFor(subtotal, promo);
|
||||
const payable = subtotal - discount;
|
||||
const delivery = payable >= FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;
|
||||
return { lines: rows, subtotal, discount, delivery, total: payable + delivery };
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
// BENCH-HIDDEN — эталонное решение задачи 3: тест на порог.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { quote } from "../cart.mjs";
|
||||
|
||||
test("заказ ровно на 5 000 ₸ — доставка бесплатно", () => {
|
||||
const q = quote([{ sku: "rose", qty: 2 }, { sku: "wrap", qty: 1 }]);
|
||||
assert.deepEqual([q.delivery, q.total], [0, 5000]);
|
||||
});
|
||||
11
bench/tasks/03-bugfix/story.md
Normal file
11
bench/tasks/03-bugfix/story.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Сайт берёт деньги за доставку, когда она должна быть бесплатной
|
||||
Эпик: Стабильность
|
||||
|
||||
У нас цветочный магазин «Пион». По нашим правилам доставка бесплатная, если заказ от 5 000 ₸
|
||||
(с учётом скидки по промокоду), иначе — 1 000 ₸.
|
||||
|
||||
Вчера клиентка собрала заказ ровно на 5 000 ₸: две розы по 1 500 ₸ и упаковку за 2 000 ₸, без
|
||||
промокода. Сайт посчитал ей 1 000 ₸ за доставку, итого 6 000 ₸. Она написала жалобу.
|
||||
|
||||
Найдите и исправьте ошибку. Всё остальное в расчёте заказа работает правильно — его не трогать.
|
||||
Сделайте так, чтобы такая ошибка не вернулась незаметно.
|
||||
91
bench/tasks/04-new-field/checks/check.mjs
Normal file
91
bench/tasks/04-new-field/checks/check.mjs
Normal file
@ -0,0 +1,91 @@
|
||||
// BENCH-HIDDEN — скрытые проверки задачи 4 (дата рождения: хранение → API → экран).
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { assertText, page, visibleText } from "../../../lib/check-kit.mjs";
|
||||
|
||||
// Имя поля агент выбирает сам — шлём под всеми разумными именами, читаем любое поле с «birth».
|
||||
const KEYS = ["birthDate", "birthday", "dateOfBirth", "birth_date", "dob"];
|
||||
const withBirth = (v, extra) => ({ ...extra, ...Object.fromEntries(KEYS.map((k) => [k, v])) });
|
||||
const birthOf = (row) => Object.entries(row ?? {}).find(([k]) => /birth|dob/i.test(k))?.[1];
|
||||
|
||||
export async function setup(t) {
|
||||
const dir = join(t.workdir, ".bench-data");
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(join(dir, "patients.json"), JSON.stringify([{ id: 1, name: "Старый Пациент", phone: "+77010000009" }]));
|
||||
return {};
|
||||
}
|
||||
|
||||
async function rejected(t, value) {
|
||||
const before = (await (await t.app.get("/api/patients")).json()).length;
|
||||
const r = await t.app.post("/api/patients", withBirth(value, { name: "Ошибка Датова", phone: "+77015550000" }));
|
||||
t.assert.equal(r.status, 400, `дата ${value}: ожидали 400, получили ${r.status}`);
|
||||
const errors = r.json()?.errors ?? {};
|
||||
const msg = Object.entries(errors).find(([k]) => /birth|dob/i.test(k))?.[1];
|
||||
t.assert.ok(typeof msg === "string" && msg.trim(), `нет текста ошибки про дату: ${JSON.stringify(errors)}`);
|
||||
t.assert.equal((await (await t.app.get("/api/patients")).json()).length, before, "пациент с плохой датой сохранился");
|
||||
}
|
||||
|
||||
export default [
|
||||
{
|
||||
name: "дата рождения сохраняется и отдаётся",
|
||||
async run(t) {
|
||||
const r = await t.app.post("/api/patients", withBirth("1990-05-17", { name: "Айгерим Нурланова", phone: "+7 701 111 22 33" }));
|
||||
t.assert.equal(r.status, 201, `POST ответил ${r.status}: ${r.text.slice(0, 200)}`);
|
||||
const row = (await t.app.get("/api/patients")).json().find((p) => p.name === "Айгерим Нурланова");
|
||||
t.assert.equal(birthOf(row), "1990-05-17", `в записи: ${JSON.stringify(row)}`);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "переживает перезапуск",
|
||||
async run(t) {
|
||||
await t.app.restart();
|
||||
const row = (await t.app.get("/api/patients")).json().find((p) => p.name === "Айгерим Нурланова");
|
||||
t.assert.equal(birthOf(row), "1990-05-17");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "поле необязательное",
|
||||
async run(t) {
|
||||
const r = await t.app.post("/api/patients", { name: "Без Даты", phone: "+77012223344" });
|
||||
t.assert.equal(r.status, 201, `без даты: ${r.status} ${r.text.slice(0, 200)}`);
|
||||
},
|
||||
},
|
||||
{ name: "несуществующая дата — ошибка", run: (t) => rejected(t, "1990-02-31") },
|
||||
{ name: "месяц 13 — ошибка", run: (t) => rejected(t, "1990-13-01") },
|
||||
{ name: "дата из будущего — ошибка", run: (t) => rejected(t, "2999-01-01") },
|
||||
{
|
||||
name: "список показывает дату по-русски и прочерк",
|
||||
async run(t) {
|
||||
const html = await page(t, "/patients");
|
||||
assertText(html, "Дата рождения");
|
||||
assertText(html, "17.05.1990");
|
||||
t.assert.ok(!visibleText(html).includes("1990-05-17"), "дата в списке в виде 1990-05-17");
|
||||
const row = html.split(/<tr\b/i).find((r) => r.includes("Без Даты")) ?? "";
|
||||
t.assert.match(visibleText(row), /[—–-]/, "у пациента без даты нет прочерка");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "в форме есть поле даты рождения",
|
||||
async run(t) {
|
||||
const html = await page(t, "/patients");
|
||||
const form = html.match(/<form[\s\S]*?<\/form>/i)?.[0] ?? "";
|
||||
t.assert.match(form, /Дата рождения/, "в форме нет поля «Дата рождения»");
|
||||
t.assert.match(form, /<input[^>]+name=["'][^"']*(birth|dob)[^"']*["']/i, "нет поля ввода даты в форме");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "старые пациенты на месте",
|
||||
async run(t) {
|
||||
const list = (await t.app.get("/api/patients")).json();
|
||||
t.assert.ok(list.some((p) => p.name === "Старый Пациент"), "старый пациент пропал из API");
|
||||
assertText(await page(t, "/patients"), "Старый Пациент");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "тесты проекта зелёные",
|
||||
async run(t) {
|
||||
const r = await t.run("node", ["--test", "product/test/"]);
|
||||
t.assert.equal(r.code, 0, `тесты упали:\n${r.out.slice(-1500)}`);
|
||||
},
|
||||
},
|
||||
];
|
||||
8
bench/tasks/04-new-field/meta.json
Normal file
8
bench/tasks/04-new-field/meta.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"hidden": "BENCH-HIDDEN",
|
||||
"num": 4,
|
||||
"title": "Новое поле сквозь всё приложение: база → API → экран",
|
||||
"kind": "field",
|
||||
"timeLimitMin": 60,
|
||||
"tokenLimit": 5000000
|
||||
}
|
||||
26
bench/tasks/04-new-field/repo/product/patients.mjs
Normal file
26
bench/tasks/04-new-field/repo/product/patients.mjs
Normal file
@ -0,0 +1,26 @@
|
||||
// Пациенты: проверка полей и хранение.
|
||||
import { collection } from "./lib/store.mjs";
|
||||
|
||||
const patients = collection("patients");
|
||||
|
||||
export function normalizePhone(raw) {
|
||||
const d = String(raw ?? "").replace(/[\s()-]/g, "");
|
||||
return /^\+7\d{10}$/.test(d) ? d : null;
|
||||
}
|
||||
|
||||
export function validatePatient(b) {
|
||||
const errors = {};
|
||||
const name = String(b.name ?? "").trim();
|
||||
if (name.length < 2) errors.name = "Укажите имя и фамилию.";
|
||||
const phone = normalizePhone(b.phone);
|
||||
if (!phone) errors.phone = "Укажите телефон в виде +7 и 10 цифр.";
|
||||
return { errors, value: { name, phone } };
|
||||
}
|
||||
|
||||
export function addPatient(fields) {
|
||||
return patients.add(fields);
|
||||
}
|
||||
|
||||
export function listPatients() {
|
||||
return patients.all();
|
||||
}
|
||||
52
bench/tasks/04-new-field/repo/product/routes.mjs
Normal file
52
bench/tasks/04-new-field/repo/product/routes.mjs
Normal file
@ -0,0 +1,52 @@
|
||||
import { esc, html, json, page } from "./lib/http.mjs";
|
||||
import { addPatient, listPatients, validatePatient } from "./patients.mjs";
|
||||
|
||||
function patientsPage() {
|
||||
const rows = listPatients()
|
||||
.map((p) => `<tr><td>${esc(p.name)}</td><td>${esc(p.phone)}</td></tr>`)
|
||||
.join("");
|
||||
return page(
|
||||
"Пациенты",
|
||||
`<h1>Пациенты</h1>
|
||||
<table><thead><tr><th>Имя</th><th>Телефон</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<h2>Новый пациент</h2>
|
||||
<form method="post" action="/patients">
|
||||
<label>Имя и фамилия <input name="name"></label>
|
||||
<label>Телефон <input name="phone"></label>
|
||||
<button>Добавить</button>
|
||||
</form>`,
|
||||
);
|
||||
}
|
||||
|
||||
export const routes = [
|
||||
{
|
||||
method: "GET",
|
||||
path: "/healthz",
|
||||
handler: ({ res }) => {
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("ok");
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Улыбка", '<h1>Улыбка</h1><a href="/patients">Картотека</a>')) },
|
||||
{ method: "GET", path: "/patients", handler: ({ res }) => html(res, patientsPage()) },
|
||||
{
|
||||
method: "POST",
|
||||
path: "/patients",
|
||||
async handler({ res, body }) {
|
||||
const { errors, value } = validatePatient(await body());
|
||||
if (Object.keys(errors).length) return html(res, page("Ошибка", `<p>${Object.values(errors).map(esc).join("<br>")}</p><a href="/patients">Назад</a>`), 400);
|
||||
addPatient(value);
|
||||
res.writeHead(303, { location: "/patients" }).end();
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/api/patients", handler: ({ res }) => json(res, 200, listPatients()) },
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/patients",
|
||||
async handler({ res, body }) {
|
||||
const { errors, value } = validatePatient(await body());
|
||||
if (Object.keys(errors).length) return json(res, 400, { errors });
|
||||
json(res, 201, addPatient(value));
|
||||
},
|
||||
},
|
||||
];
|
||||
35
bench/tasks/04-new-field/repo/product/test/patients.test.mjs
Normal file
35
bench/tasks/04-new-field/repo/product/test/patients.test.mjs
Normal file
@ -0,0 +1,35 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { startApp } from "./helpers.mjs";
|
||||
|
||||
test("пациент добавляется и виден в списке", async () => {
|
||||
const app = await startApp();
|
||||
try {
|
||||
const r = await fetch(`${app.url}/api/patients`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ name: "Иван Петров", phone: "+7 701 000 00 01" }),
|
||||
});
|
||||
assert.equal(r.status, 201);
|
||||
const list = await (await fetch(`${app.url}/api/patients`)).json();
|
||||
assert.equal(list[0].phone, "+77010000001");
|
||||
assert.match(await (await fetch(`${app.url}/patients`)).text(), /Иван Петров/);
|
||||
} finally {
|
||||
app.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("без телефона — ошибка", async () => {
|
||||
const app = await startApp();
|
||||
try {
|
||||
const r = await fetch(`${app.url}/api/patients`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ name: "Иван Петров" }),
|
||||
});
|
||||
assert.equal(r.status, 400);
|
||||
assert.ok((await r.json()).errors.phone);
|
||||
} finally {
|
||||
app.stop();
|
||||
}
|
||||
});
|
||||
45
bench/tasks/04-new-field/solution/product/patients.mjs
Normal file
45
bench/tasks/04-new-field/solution/product/patients.mjs
Normal file
@ -0,0 +1,45 @@
|
||||
// BENCH-HIDDEN — эталонное решение задачи 4.
|
||||
import { collection } from "./lib/store.mjs";
|
||||
|
||||
const patients = collection("patients");
|
||||
|
||||
export function normalizePhone(raw) {
|
||||
const d = String(raw ?? "").replace(/[\s()-]/g, "");
|
||||
return /^\+7\d{10}$/.test(d) ? d : null;
|
||||
}
|
||||
|
||||
export function parseBirthDate(raw, today = new Date()) {
|
||||
const s = String(raw ?? "").trim();
|
||||
if (!s) return { value: null };
|
||||
const m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
|
||||
if (!m) return { error: "Укажите дату в виде ДД.ММ.ГГГГ." };
|
||||
const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
|
||||
if (d.getUTCFullYear() !== +m[1] || d.getUTCMonth() !== +m[2] - 1 || d.getUTCDate() !== +m[3]) return { error: "Такой даты нет в календаре." };
|
||||
if (d > today) return { error: "Дата рождения не может быть в будущем." };
|
||||
return { value: s };
|
||||
}
|
||||
|
||||
export function formatBirthDate(v) {
|
||||
if (!v) return "—";
|
||||
const [y, mo, d] = v.split("-");
|
||||
return `${d}.${mo}.${y}`;
|
||||
}
|
||||
|
||||
export function validatePatient(b) {
|
||||
const errors = {};
|
||||
const name = String(b.name ?? "").trim();
|
||||
if (name.length < 2) errors.name = "Укажите имя и фамилию.";
|
||||
const phone = normalizePhone(b.phone);
|
||||
if (!phone) errors.phone = "Укажите телефон в виде +7 и 10 цифр.";
|
||||
const birth = parseBirthDate(b.birthDate);
|
||||
if (birth.error) errors.birthDate = birth.error;
|
||||
return { errors, value: { name, phone, birthDate: birth.value ?? null } };
|
||||
}
|
||||
|
||||
export function addPatient(fields) {
|
||||
return patients.add(fields);
|
||||
}
|
||||
|
||||
export function listPatients() {
|
||||
return patients.all();
|
||||
}
|
||||
54
bench/tasks/04-new-field/solution/product/routes.mjs
Normal file
54
bench/tasks/04-new-field/solution/product/routes.mjs
Normal file
@ -0,0 +1,54 @@
|
||||
// BENCH-HIDDEN — эталонное решение задачи 4.
|
||||
import { esc, html, json, page } from "./lib/http.mjs";
|
||||
import { addPatient, formatBirthDate, listPatients, validatePatient } from "./patients.mjs";
|
||||
|
||||
function patientsPage() {
|
||||
const rows = listPatients()
|
||||
.map((p) => `<tr><td>${esc(p.name)}</td><td>${esc(p.phone)}</td><td>${formatBirthDate(p.birthDate)}</td></tr>`)
|
||||
.join("");
|
||||
return page(
|
||||
"Пациенты",
|
||||
`<h1>Пациенты</h1>
|
||||
<table><thead><tr><th>Имя</th><th>Телефон</th><th>Дата рождения</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<h2>Новый пациент</h2>
|
||||
<form method="post" action="/patients">
|
||||
<label>Имя и фамилия <input name="name"></label>
|
||||
<label>Телефон <input name="phone"></label>
|
||||
<label>Дата рождения <input name="birthDate" type="date"></label>
|
||||
<button>Добавить</button>
|
||||
</form>`,
|
||||
);
|
||||
}
|
||||
|
||||
export const routes = [
|
||||
{
|
||||
method: "GET",
|
||||
path: "/healthz",
|
||||
handler: ({ res }) => {
|
||||
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
|
||||
res.end("ok");
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/", handler: ({ res }) => html(res, page("Улыбка", '<h1>Улыбка</h1><a href="/patients">Картотека</a>')) },
|
||||
{ method: "GET", path: "/patients", handler: ({ res }) => html(res, patientsPage()) },
|
||||
{
|
||||
method: "POST",
|
||||
path: "/patients",
|
||||
async handler({ res, body }) {
|
||||
const { errors, value } = validatePatient(await body());
|
||||
if (Object.keys(errors).length) return html(res, page("Ошибка", `<p>${Object.values(errors).map(esc).join("<br>")}</p><a href="/patients">Назад</a>`), 400);
|
||||
addPatient(value);
|
||||
res.writeHead(303, { location: "/patients" }).end();
|
||||
},
|
||||
},
|
||||
{ method: "GET", path: "/api/patients", handler: ({ res }) => json(res, 200, listPatients()) },
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/patients",
|
||||
async handler({ res, body }) {
|
||||
const { errors, value } = validatePatient(await body());
|
||||
if (Object.keys(errors).length) return json(res, 400, { errors });
|
||||
json(res, 201, addPatient(value));
|
||||
},
|
||||
},
|
||||
];
|
||||
13
bench/tasks/04-new-field/story.md
Normal file
13
bench/tasks/04-new-field/story.md
Normal file
@ -0,0 +1,13 @@
|
||||
# Дата рождения пациента
|
||||
Эпик: Картотека
|
||||
|
||||
В картотеке стоматологии «Улыбка» у пациента сейчас только имя и телефон. Администраторам нужна
|
||||
ещё дата рождения: по ней они отличают однофамильцев и поздравляют пациентов.
|
||||
|
||||
- В форме добавления пациента — поле «Дата рождения». Оно необязательное: многие не хотят его
|
||||
называть.
|
||||
- В списке пациентов — колонка «Дата рождения» в привычном виде, например 17.05.1990. У тех, у
|
||||
кого её нет, — прочерк.
|
||||
- Дата из будущего или несуществующая дата (например, 31 февраля) — ошибка с понятным текстом,
|
||||
пациент не сохраняется.
|
||||
- Пациенты, которые уже есть в картотеке, должны остаться и показываться как раньше.
|
||||
236
packages/core/src/bench.ts
Normal file
236
packages/core/src/bench.ts
Normal file
@ -0,0 +1,236 @@
|
||||
// Эталонные задачи фабрики (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 { 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 }[];
|
||||
}
|
||||
|
||||
const here = fileURLToPath(new URL(".", import.meta.url));
|
||||
|
||||
export function benchDir(): string {
|
||||
return process.env.PEPPA_BENCH_DIR ? resolve(process.env.PEPPA_BENCH_DIR) : resolve(here, "../../../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() });
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@ -81,3 +81,4 @@ export * from "./subscription-names.ts";
|
||||
export * from "./transcribe.ts";
|
||||
export * from "./attachments.ts";
|
||||
export * from "./feedback.ts";
|
||||
export * from "./bench.ts";
|
||||
|
||||
Loading…
Reference in New Issue
Block a user