peppa/packages/runner/src/pick-question.ts
2026-11-16 23:40:38 +05:00

129 lines
5.1 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.

// PEP-185: a backlog story that is ready to start comes to the project's people as a question
// «Взять в работу?» (Telegram buttons, the Home page, push, one reminder) — the board is not the
// only place that says the owner is awaited. State — one `settings` row per project, no migration.
import { asIs, m } from "@peppa/shared/i18n";
import {
answerQuestion,
askPm,
getAutonomy,
getQuestion,
getSetting,
isProjectPaused,
listProjects,
listTasks,
platformFailure,
askPmProject,
setSetting,
type Project,
type Question,
} from "@peppa/core";
import type { Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { readyBacklog } from "./autonomy.ts";
import { moveTask } from "./flow.ts";
import { onAnswer, resolveTaskById } from "./sessions.ts";
export const PICK_TAKE = m("В работу");
export const PICK_LATER = m("Пока нет");
interface PickState {
/** taskId → the open question about it. */
open: Record<string, number>;
/** Stories the person said «Пока нет» to: not asked again until they leave the backlog. */
declined: number[];
}
const stateKey = (projectId: number) => `pick.state:${projectId}`;
const getState = async (db: Db, projectId: number): Promise<PickState> => {
const s = await getSetting<Partial<PickState>>(db, stateKey(projectId));
return { open: s?.open ?? {}, declined: s?.declined ?? [] };
};
const maxOpen = () => Math.max(1, Number(process.env.PEPPA_PICK_QUESTION_MAX ?? 3));
export interface PickQuestionTickOptions {
now?: Date;
log?: (m: string) => void;
}
export async function pickQuestionTick(db: Db, o: PickQuestionTickOptions = {}): Promise<void> {
if (process.env.PEPPA_PICK_QUESTION === "off") return;
const log = o.log ?? (() => {});
for (const project of await listProjects(db)) {
try {
if (await isProjectPaused(db, project.id)) continue;
await pickForProject(db, project, log);
} catch (e) {
log(`pick question ${project.key}: ${(e as Error).message}`);
}
}
}
async function pickForProject(db: Db, project: Project, log: (m: string) => void) {
const state = await getState(db, project.id);
const backlog = await listTasks(db, { projectId: project.id, statuses: ["backlog"] });
const inBacklog = new Set(backlog.map((t) => t.id));
let changed = false;
// A story that left the backlog (board button, dispatcher, archive) — its question is moot, silently.
for (const [taskId, qid] of Object.entries(state.open)) {
const q = await getQuestion(db, qid).catch(() => null);
if (!q || q.answeredAt) {
delete state.open[taskId];
changed = true;
} else if (!inBacklog.has(Number(taskId))) {
await answerQuestion(db, qid, m("(неактуально: задача уже не в бэклоге)"), "system").catch(() => {});
delete state.open[taskId];
changed = true;
}
}
const declined = state.declined.filter((id) => inBacklog.has(id));
if (declined.length !== state.declined.length) {
state.declined = declined;
changed = true;
}
// The dispatcher of an «auto» project takes stories itself — nobody is asked.
const auto = (await getAutonomy(db, project.id)).pick === "auto";
if (!auto) {
const ready = await readyBacklog(db, project.id, backlog);
let slots = maxOpen() - Object.keys(state.open).length;
for (const task of ready) {
if (slots <= 0) break;
if (state.open[String(task.id)] || state.declined.includes(task.id)) continue;
const key = formatTaskKey(project.key, task.number);
const q = await askPm(db, { project, task, key }, {
kind: "question",
msgType: "question",
text: m("Задача «{title}» готова. Взять в работу?", { title: asIs(task.title) }),
options: [PICK_TAKE, PICK_LATER],
defaultOption: PICK_TAKE,
});
state.open[String(task.id)] = q.id;
changed = true;
slots--;
log(`${key}: asked to take`);
}
}
if (changed) await setSetting(db, stateKey(project.id), state);
}
/** The answer to «Взять в работу?» (`onAnswer` registry). */
export async function onPickAnswer(db: Db, q: Question, answer: string): Promise<boolean> {
if (!q.taskId) return false;
const state = await getState(db, q.projectId);
if (state.open[String(q.taskId)] !== q.id) return false;
delete state.open[String(q.taskId)];
const ref = await resolveTaskById(db, q.taskId);
const take = answer.trim() === PICK_TAKE;
if (!take && !state.declined.includes(q.taskId)) state.declined.push(q.taskId);
await setSetting(db, stateKey(q.projectId), state);
if (!take || ref.task.status !== "backlog") return true;
try {
await moveTask(db, ref, "in_progress");
} catch (e) {
const why = await platformFailure(db, e, { service: "runner", where: `start ${ref.key}` });
await askPmProject(db, ref.project, { kind: "attention", text: why ? m("⚠️ {key} не запущена: {error}", { key: ref.key, error: why }) : m("⚠️ {key} не запущена. Мы уже разбираемся — попробуйте ещё раз позже.", { key: ref.key }) });
}
return true;
}
onAnswer(onPickAnswer);