peppa/packages/runner/src/stale-waits.ts
peppa-bot 9e97fd531d
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/test test: success за 1644с
peppa-ci / ci (pull_request) Successful in 29m38s
PEP-279: старые вопросы закрываются вариантом по умолчанию, «Принять» — одна сводка в день
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:06:46 +00:00

233 lines
11 KiB
TypeScript

// PEP-279: what piled up waiting for people.
// 1. Old questions: the superadmin closes questions nobody answered for `days` (7) with their
// default option — the same path as a person's answer (answer handlers, delivery to the agent);
// a question without a default is closed by FORGE with no choice made. Then one summary to
// every person of the projects concerned.
// 2. «Принять» is never pressed for a person: once a day in working time one reminder to everyone
// whose finished stories wait for «Принять» longer than a day, with a link to the Home page.
import { asIs, m } from "@peppa/shared/i18n";
import {
answerQuestion,
deliverToUser,
getNotifyPrefs,
getSetting,
IS_QUESTION,
listUserProjects,
logEvent,
pausedProjectIds,
questionIsFreeText,
projectAudience,
serverTimezone,
setSetting,
type User,
} from "@peppa/core";
import { projects, questions, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, asc, eq, isNull, lt } from "drizzle-orm";
import { getWatchdogSettings, inWorkingTime } from "./recovery.ts";
import { answerAndDeliver } from "./sessions.ts";
export const STALE_DAYS = 7;
/** The answer of a question closed with no default: FORGE chose nothing for the person. */
export const STALE_NO_DEFAULT = m("(закрыто: нет ответа больше 7 дней)");
export interface StaleQuestion {
id: number;
projectId: number;
projectKey: string;
/** «KEY-N», or the project key for a question about the project. */
where: string;
text: string;
/** The agent's own words (PEP-139): shown as written, never translated. */
freeText: boolean;
/** What it will be closed with; null — closed with no choice. */
answer: string | null;
createdAt: Date;
}
/** Open questions (not «готово» cards, not factory notes) older than `days`; paused/deleted projects wait. */
export async function staleQuestions(db: Db, o: { days?: number; now?: Date } = {}): Promise<StaleQuestion[]> {
const days = o.days ?? STALE_DAYS;
const before = new Date((o.now ?? new Date()).getTime() - days * 86_400_000);
const rows = await db
.select({ q: questions, key: projects.key, number: tasks.number })
.from(questions)
.innerJoin(projects, eq(questions.projectId, projects.id))
.leftJoin(tasks, eq(questions.taskId, tasks.id))
.where(and(isNull(questions.answeredAt), IS_QUESTION, lt(questions.createdAt, before), eq(questions.awaitingHook, false), isNull(projects.deletedAt)))
.orderBy(asc(questions.id));
const paused = await pausedProjectIds(db);
return rows
.filter((r) => !paused.has(r.q.projectId))
.map(({ q, key, number }) => ({
id: q.id,
projectId: q.projectId,
projectKey: key,
where: number != null ? formatTaskKey(key, number) : key,
text: q.text,
freeText: questionIsFreeText(q),
answer: q.defaultOption?.trim() || null,
createdAt: q.createdAt,
}));
}
export interface StaleCloseResult {
closed: StaleQuestion[];
failed: number;
/** People who got the summary. */
told: number;
dryRun: boolean;
}
const SUMMARY_LINES = 8;
const short = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
const shownText = (x: StaleQuestion) => {
const s = short(x.text.replace(/\s+/g, " "), 80);
return x.freeText ? asIs(s) : s;
};
/** The summary for one person: how many were closed and with what. */
export function staleSummaryText(items: StaleQuestion[], days: number, url: string): string {
const lines = items.slice(0, SUMMARY_LINES).map((x) =>
x.answer
? m("• {where}: «{question}» → {answer}", { where: x.where, question: shownText(x), answer: asIs(x.answer) })
: m("• {where}: «{question}» → без выбора", { where: x.where, question: shownText(x) }),
);
if (items.length > SUMMARY_LINES) lines.push(m("…и ещё: {n}", { n: items.length - SUMMARY_LINES }));
return [
m("🧹 Закрыли вопросов без ответа старше {days} дней: {n}.", { days, n: items.length }),
m("Агенты продолжили по рекомендованному варианту. Если вариант не подходит — напишите в задаче, что поправить."),
"",
...lines,
"",
url,
].join("\n");
}
/**
* Closes the old questions (or only lists them with `dryRun`). Each question goes on its own:
* one failing (answered meanwhile, a handler error) does not stop the others.
*/
export async function closeStaleQuestions(db: Db, o: { days?: number; now?: Date; dryRun?: boolean; log?: (m: string) => void } = {}): Promise<StaleCloseResult> {
const days = o.days ?? STALE_DAYS;
const now = o.now ?? new Date();
const list = await staleQuestions(db, { days, now });
if (o.dryRun || !list.length) return { closed: o.dryRun ? list : [], failed: 0, told: 0, dryRun: !!o.dryRun };
const closed: StaleQuestion[] = [];
let failed = 0;
for (const x of list) {
try {
if (x.answer) await answerAndDeliver(db, x.id, x.answer, "system");
else await answerQuestion(db, x.id, STALE_NO_DEFAULT, "system");
closed.push(x);
} catch (e) {
failed++;
o.log?.(`stale question #${x.id}: ${(e as Error).message}`);
}
}
// One journal line per project (who pressed it — the actor of the call).
const byProject = new Map<number, StaleQuestion[]>();
for (const x of closed) byProject.set(x.projectId, [...(byProject.get(x.projectId) ?? []), x]);
for (const [projectId, items] of byProject) {
await logEvent(db, { projectId, type: "stale_questions_closed", payload: { days, questionIds: items.map((x) => x.id), withDefault: items.filter((x) => x.answer).length } });
}
// One summary per person across their projects.
const byUser = new Map<number, { user: User; items: StaleQuestion[] }>();
for (const [projectId, items] of byProject) {
for (const u of await projectAudience(db, projectId)) {
const e = byUser.get(u.id) ?? { user: u, items: [] };
e.items.push(...items);
byUser.set(u.id, e);
}
}
const url = `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/`;
const run = now.getTime();
let told = 0;
for (const { user, items } of byUser.values()) {
const text = staleSummaryText(items, days, url);
const r = await deliverToUser(db, user, {
event: "questions",
dedupeKey: `stale:${run}:${user.telegramChatId}`,
pushKey: `stale:${run}:u${user.id}`,
telegram: { params: { text, link_preview_options: { is_disabled: true } } },
push: { title: m("Закрыли старые вопросы"), body: m("Вопросов без ответа: {n}", { n: items.length }), url: "/", tag: "stale-questions" },
now,
}).catch(() => null);
if (r && (r.telegram || r.push)) told++;
}
o.log?.(`stale questions: closed ${closed.length}, failed ${failed}, told ${told}`);
return { closed, failed, told, dryRun: false };
}
// ── «Принять»: one reminder a day ────────────────────────────────────────────────────
const REMIND_AGE_MS = 86_400_000;
const remindKey = (userId: number) => `accept.remind:${userId}`;
const localDay = (now: Date) => new Intl.DateTimeFormat("en-CA", { timeZone: serverTimezone(), year: "numeric", month: "2-digit", day: "2-digit" }).format(now);
export function acceptReminderText(n: number, oldestDays: number, perProject: { name: string; n: number }[], url: string): string {
const lines = perProject.slice(0, 5).map((p) => m("• {project}: {n}", { project: asIs(p.name), n: p.n }));
if (perProject.length > 5) lines.push(m("…и ещё проектов: {n}", { n: perProject.length - 5 }));
return [
m("✅ Ждут «Принять» — задач: {n}, самая давняя ждёт дней: {days}.", { n, days: oldestDays }),
m("Откройте Главную: там всё по порядку — посмотреть, принять или поправить."),
"",
...lines,
"",
url,
].join("\n");
}
/** Once a day in working time: one summary to each person with stories waiting for «Принять» over a day. */
export async function acceptReminderTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
if (process.env.PEPPA_ACCEPT_REMIND === "off") return 0;
const now = o.now ?? new Date();
if (!inWorkingTime(now, await getWatchdogSettings(db))) return 0;
const day = localDay(now);
const open = await db
.select({ projectId: questions.projectId, taskId: questions.taskId, createdAt: questions.createdAt })
.from(questions)
.innerJoin(tasks, eq(questions.taskId, tasks.id))
.innerJoin(projects, eq(questions.projectId, projects.id))
.where(and(isNull(questions.answeredAt), eq(questions.msgType, "done"), eq(tasks.status, "review"), isNull(tasks.archivedAt), isNull(projects.deletedAt), lt(questions.createdAt, new Date(now.getTime() - REMIND_AGE_MS))));
if (!open.length) return 0;
const paused = await pausedProjectIds(db);
const projectIds = [...new Set(open.map((r) => r.projectId))].filter((id) => !paused.has(id));
if (!projectIds.length) return 0;
const people = new Map<number, User>();
for (const id of projectIds) for (const u of await projectAudience(db, id)) people.set(u.id, u);
const url = `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/`;
let sent = 0;
for (const user of people.values()) {
if ((await getSetting<string>(db, remindKey(user.id))) === day) continue;
const mine = new Map((await listUserProjects(db, user.id)).map((p) => [p.id, p]));
const prefsMuted = new Set((await getNotifyPrefs(db, user.id)).mutedProjects);
const items = open.filter((r) => mine.has(r.projectId) && !paused.has(r.projectId) && !prefsMuted.has(r.projectId));
// One story — one line even with several cards (a refreshed «готово»).
const stories = new Map<number, { projectId: number; createdAt: Date }>();
for (const r of items) {
const was = stories.get(r.taskId!);
if (!was || r.createdAt < was.createdAt) stories.set(r.taskId!, { projectId: r.projectId, createdAt: r.createdAt });
}
await setSetting(db, remindKey(user.id), day);
if (!stories.size) continue;
const counts = new Map<number, number>();
for (const s of stories.values()) counts.set(s.projectId, (counts.get(s.projectId) ?? 0) + 1);
const perProject = [...counts].map(([id, n]) => ({ name: mine.get(id)!.name, n })).sort((a, b) => b.n - a.n);
const oldest = Math.min(...[...stories.values()].map((s) => s.createdAt.getTime()));
const days = Math.max(1, Math.floor((now.getTime() - oldest) / 86_400_000));
const text = acceptReminderText(stories.size, days, perProject, url);
const r = await deliverToUser(db, user, {
event: "review",
dedupeKey: `accrem:${day}:${user.telegramChatId}`,
pushKey: `accrem:${day}:u${user.id}`,
telegram: { params: { text, link_preview_options: { is_disabled: true }, ...(/^https?:/.test(url) ? { reply_markup: { inline_keyboard: [[{ text: m("Открыть Главную"), url }]] } } : {}) } },
push: { title: m("Ждут «Принять»"), body: m("Задач: {n}", { n: stories.size }), url: "/", tag: "accept-remind" },
now,
}).catch(() => null);
if (r && (r.telegram || r.push)) sent++;
o.log?.(`accept reminder ${user.login}: ${stories.size} stories`);
}
return sent;
}