81 lines
6.2 KiB
TypeScript
81 lines
6.2 KiB
TypeScript
// 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, readdirSync, readFileSync } from "node:fs";
|
||
|
||
interface Scenario {
|
||
/** PEP-112: the product agent on acceptance: {summary, howto[], not_real[], needs[], stories[]}. */
|
||
accept?: object;
|
||
/** PEP-110: the analyst in the project chat: {reply, create[]}. */
|
||
chat?: object;
|
||
/** PEP-115: the analyst reworking a backlog story after a comment (the analyst's JSON). */
|
||
refine?: object;
|
||
/** Answer after this many ms (a race with the PM taking the story to work). */
|
||
slowMs?: number;
|
||
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("Ты — продакт-менеджер софтвер-фабрики на приёмке") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "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, argv: process.argv.slice(2), files: role === "accept" ? readdirSync(process.cwd()) : undefined, 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- Отзывы видны на странице" }] : [],
|
||
};
|
||
// PEP-115, refine: without a scenario the last new comment becomes one more criterion.
|
||
const lastComment = /## Новые комментарии продакта\n([\s\S]*?)\n\nОтветь ОДНОЙ/.exec(prompt)?.[1]?.trim().split("\n").at(-1)?.replace(/^[^:]*: /, "") ?? "";
|
||
const refine = sc.refine ?? {
|
||
description: `Нужно: ${title}. Учтён комментарий.`,
|
||
criteria: ["Результат виден пользователю", `Учтено: ${lastComment}`],
|
||
out_of_scope: ["Оформление сверх необходимого"],
|
||
assumptions: [],
|
||
questions: [],
|
||
comment: `Добавил критерий: ${lastComment}`,
|
||
};
|
||
// PEP-112, acceptance: without a scenario it reads the page text in the prompt — a «демо» notice
|
||
// becomes a not-real item and a need, a «токен» field becomes a story.
|
||
const demo = /демо-режим[^\n]*/i.exec(prompt.split("## Что видит пользователь")[1]?.split("## Уже объявлено")[0] ?? "")?.[0];
|
||
const tokenField = /\[поле: [^\]]*токен[^\]]*\]/i.test(prompt);
|
||
const accept = sc.accept ?? {
|
||
summary: "Продукт открывается и показывает главную страницу.",
|
||
howto: ["Откройте адрес продукта", "Нажмите главную кнопку"],
|
||
not_real: demo ? [demo] : [],
|
||
needs: demo && !/Уже объявлено: что нужно от владельца\n- /.test(prompt) ? [{ title: "Ключ сервиса", why: "без него показаны примеры", how: "В кабинете сервиса" }] : [],
|
||
stories: tokenField ? [{ title: "Убрать служебное поле «Токен запуска» с экрана", description: "Пользователь не видит служебных полей.\n- На странице нет поля «Токен запуска»" }] : [],
|
||
};
|
||
if (sc.slowMs) await new Promise((r) => setTimeout(r, sc.slowMs));
|
||
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "accept" ? accept : role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst);
|
||
process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n");
|