138 lines
12 KiB
TypeScript
138 lines
12 KiB
TypeScript
// mock-intake (PEP-84): stands in for `claude -p --output-format json` as the AI roles of Peppa.
|
||
// PEP-198: role `intake` — the one analyst on intake ({goal, title, deferred[], split[], description,
|
||
// criteria[], out_of_scope[], decisions[], comment}; scenario key `intake`, merged over the default);
|
||
// role `relay` — the analyst deciding what of a developer's message reaches the owner
|
||
// ({verdict: product|technical|repeat, text, options[], default}; scenario key `relay`; without
|
||
// it: a question naming stack words is technical, one repeating an earlier question is a repeat).
|
||
// 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-197: the repeat check: {duplicate_of: KEY|null, reason}; default — the candidate sharing half the words. */
|
||
dedup?: object;
|
||
/** PEP-143: the feedback agent: {summary, kind, cause, confident, options[], recommended, duplicate_of}. */
|
||
feedback?: object;
|
||
/** PEP-153: the message classifier: {kind: question|task|unsure, answer}. */
|
||
intent?: object;
|
||
/** PEP-110: the analyst in the project chat: {reply, create[]} (PEP-153: + kind). */
|
||
chat?: object;
|
||
/** PEP-115: the analyst reworking a backlog story after a comment (the analyst's JSON). */
|
||
refine?: object;
|
||
/** PEP-198: the analyst on intake (merged over the default answer). */
|
||
intake?: Record<string, unknown>;
|
||
/** PEP-198: the analyst relaying a developer's question. */
|
||
relay?: 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("Ты — аналитик софтвер-фабрики на входе задачи") ? "intake" : prompt.startsWith("Ты — аналитик софтвер-фабрики между агентами") ? "relay" : prompt.startsWith("Ты — проверка на повтор") ? "dedup" : prompt.startsWith("Ты — диспетчер сообщений") ? "intent" : prompt.startsWith("Ты — агент обратной связи") ? "feedback" : 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" || role === "dedup" || role === "intake" || role === "feedback" || role === "chat" || role === "refine" ? 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-153, intent: without a scenario a «?» is a question (answered «Ответ на: …»), «может»/«наверное»
|
||
// is unsure, anything else is a task.
|
||
const said = /## Сообщение\n([\s\S]*?)\n\nОтветь ОДНОЙ/.exec(prompt)?.[1]?.trim() ?? "";
|
||
const intent = sc.intent ?? (/[??]\s*$/.test(said) ? { kind: "question", answer: `Ответ на: ${said}` } : /может|наверное/i.test(said) ? { kind: "unsure", answer: "" } : { kind: "task", answer: "" });
|
||
// 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- На странице нет поля «Токен запуска»" }] : [],
|
||
};
|
||
// PEP-143, feedback: without a scenario — a bug with three options, the second recommended.
|
||
const feedback = sc.feedback ?? {
|
||
summary: "Кнопка не реагирует на нажатие.",
|
||
kind: "bug",
|
||
cause: "Обработчик нажатия не подключён на этой странице.",
|
||
confident: true,
|
||
options: [
|
||
{ title: "Починить обработчик", what: "Подключить обработчик кнопки на странице.", pros: "Быстро", cons: "Не закрывает похожие места", size: "S" },
|
||
{ title: "Общая кнопка", what: "Вынести кнопку в общий компонент и заменить на всех страницах.", pros: "Чинит все места сразу", cons: "Дольше", size: "M" },
|
||
{ title: "Убрать кнопку", what: "Скрыть кнопку, пока действие недоступно.", pros: "Никто не упрётся", cons: "Действие пропадает", size: "S" },
|
||
],
|
||
recommended: 2,
|
||
duplicate_of: null,
|
||
};
|
||
// PEP-197, repeat check: without a scenario a candidate sharing at least half of the words is a repeat.
|
||
const words = (x: string) => new Set(x.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 2));
|
||
const newWords = words(/Название: (.*)/.exec(prompt)?.[1] ?? "");
|
||
const similar = [...prompt.matchAll(/^- (\S+) «(.*)» \[/gm)].find((c) => { const w = words(c[2]!); const common = [...newWords].filter((x) => w.has(x)).length; return newWords.size > 0 && common / Math.min(newWords.size, w.size || 1) >= 0.5; });
|
||
const dedup = sc.dedup ?? { duplicate_of: similar?.[1] ?? null, reason: similar ? "та же тема" : "" };
|
||
// PEP-198, intake: the default keeps the story whole, decides one product fork.
|
||
const intake = {
|
||
goal: `Сделать: ${title}`,
|
||
title,
|
||
deferred: [],
|
||
split: [],
|
||
description: `Нужно: ${title}.`,
|
||
criteria: ["Результат виден пользователю", "Ошибки показаны понятным текстом"],
|
||
out_of_scope: ["Оформление сверх необходимого"],
|
||
decisions: ["Страница открывается с телефона"],
|
||
comment: "В запросе не сказано, кто пользователь.",
|
||
...sc.intake,
|
||
};
|
||
// PEP-198, relay: stack words — technical; the same words as an earlier question to the owner — a repeat.
|
||
const asked = /## Вопрос агента\n([\s\S]*?)\n\n/.exec(prompt)?.[1]?.trim() ?? "";
|
||
const earlier = [...(/## Уже спрошено у владельца\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? "").matchAll(/^- #(\d+): (.*)$/gm)];
|
||
const askedWords = words(asked);
|
||
const repeatOf = earlier.find((e) => { const w = words(e[2]!); const common = [...askedWords].filter((x) => w.has(x)).length; return askedWords.size > 0 && common / Math.min(askedWords.size, w.size || 1) >= 0.5; });
|
||
const relay = sc.relay ?? (/баз[аеуы] данных|библиотек|фреймворк|postgres|sqlite|стек|миграц/i.test(asked) ? { verdict: "technical", text: "", options: [], default: "" } : repeatOf ? { verdict: "repeat", repeat_of: Number(repeatOf[1]), text: "", options: [], default: "" } : { verdict: "product", text: `Агент спрашивает: ${asked.split("\n")[0]}`, options: (/Варианты агента: (.*)/.exec(prompt)?.[1] ?? "Да | Нет").split(" | "), default: /По умолчанию: (.*)/.exec(prompt)?.[1] ?? "Да" });
|
||
if (sc.slowMs) await new Promise((r) => setTimeout(r, sc.slowMs));
|
||
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "intake" ? intake : role === "relay" ? relay : role === "dedup" ? dedup : role === "intent" ? intent : role === "feedback" ? feedback : 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");
|