peppa/packages/testkit/src/mock-intake.ts
2026-11-15 15:30:54 +05:00

53 lines
3.6 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.

// mock-intake (PEP-84): stands in for `claude -p --output-format json` as «продакт» and «аналитик».
// Reads the prompt on stdin and answers with the CLI's JSON envelope. The role is read off the
// prompt's first line. Behaviour comes from MOCK_INTAKE_SCENARIO (a JSON file):
// { "product": {goal, comment, title, split[]}, "analyst": {description, criteria[], out_of_scope[],
// assumptions[], questions[{q, default}], comment}, "garbage": false, "fail": false }
// Without a scenario: the product manager keeps the story as is, the analyst asks one question
// (none once the prompt carries the PM's answer). Every call is appended to <scenario>.log.jsonl.
import { appendFileSync, existsSync, readFileSync } from "node:fs";
interface Scenario {
/** PEP-110: the analyst in the project chat: {reply, create[]}. */
chat?: object;
product?: object;
analyst?: { questions?: unknown[] } & Record<string, unknown>;
garbage?: boolean;
fail?: boolean;
}
const file = process.env.MOCK_INTAKE_SCENARIO;
const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
const prompt = readFileSync(0, "utf8");
const role = prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : "analyst";
const answered = /Ответ продакта:\n/.test(prompt);
const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? "";
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
if (!process.argv.includes("-p")) {
console.error("mock-intake: expected -p (non-interactive print mode)");
process.exit(2);
}
if (sc.fail) {
console.error("mock-intake: API Error: 529 overloaded");
process.exit(1);
}
const product = sc.product ?? { goal: `Сделать: ${title}`, comment: "Берём как есть. Лишнего нет.", title, split: [] };
const analyst = {
description: `Нужно: ${title}.`,
criteria: ["Результат виден пользователю", "Ошибки показаны понятным текстом"],
out_of_scope: ["Оформление сверх необходимого"],
assumptions: ["Язык интерфейса — русский"],
questions: [{ q: "Нужна ли мобильная версия?", default: "Да, страница открывается с телефона" }],
comment: "В запросе не сказано, кто пользователь.",
...sc.analyst,
};
if (answered) analyst.questions = [];
// PEP-110, chat: without a scenario it answers the last line; «заведи» in it files one story.
const lastLine = /## Переписка[^\n]*\n([\s\S]*?)\n\nОтветь на последнее/.exec(prompt)?.[1]?.trim().split("\n").at(-1) ?? "";
const chat = sc.chat ?? {
reply: `Ответ на: ${lastLine.replace(/^[^:]*: /, "")}`,
create: /заведи|создай/i.test(lastLine) ? [{ title: "Страница отзывов", description: "Клиент видит отзывы.\n- Отзывы видны на странице" }] : [],
};
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "product" ? product : role === "chat" ? chat : analyst);
process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n");