115 lines
7.6 KiB
TypeScript
115 lines
7.6 KiB
TypeScript
// PEP-115: a person's comment on a backlog story nobody works on goes to the analyst: it rewrites
|
||
// the story's description and acceptance criteria with the comment in mind and says in the
|
||
// story's discussion what it changed. A story an agent is working on is left alone — the agent
|
||
// reads the comment itself. What is dealt with is a cursor per story in `settings`
|
||
// (`refine.task:<taskId>`): no schema change.
|
||
import { events, tasks, type Db } from "@peppa/db";
|
||
import { and, asc, eq, gt, isNull } from "drizzle-orm";
|
||
import { INTAKE_TONE, type AnalystNote, type IntakeState, type ProductNote } from "./intake.ts";
|
||
import { getSetting, setSetting } from "./settings.ts";
|
||
import { COMMENT_EVENT, type StoryComment, type Task } from "./tasks.ts";
|
||
|
||
export const storyRefineEnabled = () => process.env.PEPPA_STORY_REFINE !== "off";
|
||
/** A comment that waited longer than this is left to the developer agent: a late rewrite only confuses. */
|
||
export const storyRefineMaxAgeMs = () => Math.max(1, Number(process.env.PEPPA_STORY_REFINE_MAX_AGE_MIN ?? 60) || 60) * 60_000;
|
||
|
||
const cursorKey = (taskId: number) => `refine.task:${taskId}`;
|
||
|
||
/** Id of the last comment of the story the analyst has dealt with. */
|
||
export async function refineCursor(db: Db, taskId: number): Promise<number> {
|
||
return (await getSetting<number>(db, cursorKey(taskId))) ?? 0;
|
||
}
|
||
export async function setRefineCursor(db: Db, taskId: number, eventId: number): Promise<void> {
|
||
if (eventId > (await refineCursor(db, taskId))) await setSetting(db, cursorKey(taskId), eventId);
|
||
}
|
||
|
||
export interface RefineComment {
|
||
id: number;
|
||
login: string;
|
||
text: string;
|
||
}
|
||
|
||
/** Backlog stories with people's comments the analyst has not dealt with yet: taskId → comments, oldest first. */
|
||
export async function pendingRefinements(db: Db, opts: { now?: Date; projectId?: number; taskId?: number } = {}): Promise<Map<number, RefineComment[]>> {
|
||
const out = new Map<number, RefineComment[]>();
|
||
if (!storyRefineEnabled()) return out;
|
||
const since = new Date((opts.now ?? new Date()).getTime() - storyRefineMaxAgeMs());
|
||
const rows = await db
|
||
.select({ id: events.id, taskId: tasks.id, payload: events.payload })
|
||
.from(events)
|
||
.innerJoin(tasks, eq(events.taskId, tasks.id))
|
||
.where(
|
||
and(
|
||
eq(events.type, COMMENT_EVENT),
|
||
eq(tasks.status, "backlog"),
|
||
isNull(tasks.archivedAt),
|
||
gt(events.createdAt, since),
|
||
opts.projectId ? eq(tasks.projectId, opts.projectId) : undefined,
|
||
opts.taskId ? eq(tasks.id, opts.taskId) : undefined,
|
||
),
|
||
)
|
||
.orderBy(asc(events.id));
|
||
const cursors = new Map<number, number>();
|
||
for (const r of rows) {
|
||
if (!cursors.has(r.taskId)) cursors.set(r.taskId, await refineCursor(db, r.taskId));
|
||
if (r.id <= cursors.get(r.taskId)!) continue;
|
||
const p = (r.payload ?? {}) as { login?: string; text?: string };
|
||
out.set(r.taskId, [...(out.get(r.taskId) ?? []), { id: r.id, login: p.login ?? "?", text: p.text ?? "" }]);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** Is the analyst still to answer a comment on this story? (the «уточняет постановку…» mark) */
|
||
export async function refinePending(db: Db, task: Pick<Task, "id" | "status" | "archivedAt">, now = new Date()): Promise<boolean> {
|
||
if (task.status !== "backlog" || task.archivedAt) return false;
|
||
return (await pendingRefinements(db, { now, taskId: task.id })).has(task.id);
|
||
}
|
||
|
||
const ORIGINAL_HEADING = "\n## Исходный запрос\n";
|
||
|
||
/** The PM's own words: kept by the intake roles, or cut out of an already formulated description, or the story as it is. */
|
||
export function originalRequest(task: Pick<Task, "title" | "description">, state: IntakeState | null): { title: string; description: string } {
|
||
if (state?.original) return state.original;
|
||
const text = task.description ?? "";
|
||
const at = text.lastIndexOf(ORIGINAL_HEADING);
|
||
if (at < 0) return { title: task.title, description: text };
|
||
const [title = task.title, ...rest] = text.slice(at + ORIGINAL_HEADING.length).split("\n");
|
||
return { title: title.trim() || task.title, description: rest.join("\n").trim() };
|
||
}
|
||
|
||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||
|
||
export function refinePrompt(context: string, story: { title: string; description: string }, thread: StoryComment[], fresh: RefineComment[], product?: ProductNote): string {
|
||
const freshIds = new Set(fresh.map((c) => c.id));
|
||
const earlier = thread.filter((c) => !freshIds.has(c.id)).slice(-10);
|
||
return [
|
||
"Ты — системный аналитик софтвер-фабрики. Стори ещё не взяли в работу, и продакт оставил к ней комментарий. Обнови постановку с учётом комментария — по ней ИИ-разработчик сделает ровно то, что нужно, а продакт проверит результат.",
|
||
"1. Описание: что должно получиться и для кого — 3–8 фраз, без способа реализации. Что комментарий не затрагивает — оставь как было.",
|
||
"2. Критерии приёмки: проверяемые снаружи утверждения, 3–8 штук. Добавь, измени или убери ровно то, чего требует комментарий.",
|
||
"3. Вне задачи и допущения — перенеси из текущей постановки, поправь, если комментарий их меняет. Комментарий продакта важнее твоих прежних допущений.",
|
||
"4. Вопросов продакту не задавай: где есть развилка, реши сам и запиши в assumptions понятными словами. Технические развилки в assumptions не пиши. questions — всегда пустой список.",
|
||
"5. comment — ответ продакту, 1–4 короткие фразы: что именно ты изменил в постановке (добавил, убрал, переписал). Если комментарий — вопрос, ответь на него. Если комментарий не меняет задачу — верни постановку как была и скажи это прямо.",
|
||
INTAKE_TONE,
|
||
"",
|
||
context,
|
||
"",
|
||
"## Стори",
|
||
`Название: ${story.title}`,
|
||
"Текущая постановка:",
|
||
story.description.trim() || "(только название)",
|
||
...(product ? ["", "Решение продакт-менеджера фабрики:", `Цель: ${product.goal}`] : []),
|
||
...(earlier.length ? ["", "## Обсуждение стори раньше", ...earlier.map((c) => `${c.login}: ${clip(c.text, 1500)}`)] : []),
|
||
"",
|
||
"## Новые комментарии продакта",
|
||
...fresh.map((c) => `${c.login}: ${clip(c.text, 4000)}`),
|
||
"",
|
||
'Ответь ОДНОЙ строкой JSON без пояснений: {"description":"…","criteria":["…"],"out_of_scope":["…"],"assumptions":["…"],"questions":[],"comment":"…"}',
|
||
].join("\n");
|
||
}
|
||
|
||
/** What the PM reads in the story's discussion after the analyst reworked it. */
|
||
export function refineMessage(a: AnalystNote): string {
|
||
const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n");
|
||
return [a.comment || "Обновил постановку с учётом комментария.", `Критерии приёмки теперь:\n${bullets(a.criteria)}`, "Нужно иначе — напишите ещё один комментарий."].join("\n\n");
|
||
}
|