Агент не меняет статус принятой задачи (причина противоречия в PEP-204); «Посмотреть результат» / «Принять» / «Поправить» в сообщении «готово»; переписка сверху вниз с полем ввода внизу; строка состояния вместо служебных сообщений; компактные события; очистка «Всех событий»; выбор проекта списком; «Задача описана. Начать работу?». Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
133 lines
5.5 KiB
TypeScript
133 lines
5.5 KiB
TypeScript
// 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 { autoPickSlots, readyBacklog } from "./autonomy.ts";
|
||
import { moveTask } from "./flow.ts";
|
||
import { onAnswer, resolveTaskById } from "./sessions.ts";
|
||
|
||
// PEP-207: «готова» read as «done» — the story is described, the question is whether to start.
|
||
export const PICK_TAKE = m("Начать");
|
||
export const PICK_LATER = m("Позже");
|
||
/** Buttons of questions sent before PEP-207 still work. */
|
||
const PICK_TAKE_OLD = "В работу";
|
||
|
||
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 the first stories itself; the ones it can't take now
|
||
// (WIP limit reached, limits) wait for a person — they are asked about.
|
||
{
|
||
const autonomy = await getAutonomy(db, project.id);
|
||
const ready = (await readyBacklog(db, project.id, backlog)).slice(await autoPickSlots(db, project, autonomy));
|
||
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 || answer.trim() === PICK_TAKE_OLD;
|
||
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);
|