Агенты: усечённый пакет в 11:50, вход 7 с текстом, аудит 3000 символов, правило про молчание менеджеров
All checks were successful
ci / test (push) Successful in 1m19s
ci / deploy (push) Successful in 3m30s

- jobs.ts: при дневной перепроверке агент шага 2 получает пакеты ВСЕХ проектов менеджера, если изменился хотя бы один (раньше только изменённые - агент считал пакет усечённым)
- queries.ts/step2.ts: во входе (7) показывается текст последнего напоминания (jt_task_id в reminder_history не заполнен)
- audit.ts: текст сообщения для классификатора 3000 символов вместо 700, пачки по 20
- p-manager-dialog.md и шаг 2 (из кода): молчание менеджеров - организационная проблема, игнорировать, не эскалировать в ИТ
- known-issues.md: реестр проблем агентов

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 22:00:00 +03:00
parent 798580a908
commit b331d145da
6 changed files with 41 additions and 9 deletions

View File

@@ -16,7 +16,7 @@ interface PackageRow {
assignees: string[];
related_task_name: string | null;
days_until_start: number | null;
payload: { reminders?: number; last_reminded_at?: string; last_reply_outcome?: string; last_reply_summary?: string } | null;
payload: { reminders?: number; last_reminded_at?: string; last_reply_outcome?: string; last_reply_summary?: string; last_reminder_text?: string } | null;
}
const INPUT_TITLES: Record<number, string> = {
@@ -39,7 +39,7 @@ export function formatPackage(rows: PackageRow[]): string {
for (const r of items) {
if (no === 7) {
const p = r.payload ?? {};
out.push(`- задача ${r.jt_task_id ?? "(без задачи)"}: напоминаний ${p.reminders ?? "?"}, последнее ${p.last_reminded_at ?? "?"}, ответ: ${p.last_reply_outcome ?? "-"} ${p.last_reply_summary ?? ""}`.trim());
out.push(`- задача ${r.jt_task_id ?? "(без задачи)"}: напоминаний ${p.reminders ?? "?"}, последнее ${p.last_reminded_at ?? "?"}, ответ: ${p.last_reply_outcome ?? "-"} ${p.last_reply_summary ?? ""}${p.last_reminder_text ? ` | текст последнего напоминания: «${String(p.last_reminder_text).replace(/s+/g, " ")}»` : ""}`.trim());
continue;
}
const dates = r.start_date || r.end_date ? ` | ${r.start_date ?? "?"} .. ${r.end_date ?? "?"}` : "";
@@ -54,6 +54,10 @@ export function formatPackage(rows: PackageRow[]): string {
return out.join("\n").trim();
}
/** Правило от 04.12.2026: молчание менеджеров - организационная проблема (ищем Execution-менеджера), не повод для обращений в ИТ и эскалации. Дублирует правило в p-manager-dialog.md; в p-step2-prepare.md (approved) не добавляется. */
const SILENCE_RULE =
"Молчание людей - не твоя проблема. То, что менеджеры не отвечают, не присылают обновления и не выполняют напоминания, - организационная проблема компании (ищем Execution-менеджера), а не сбой системы. Не обращайся из-за этого в ИТ (раздел Обращение в ИТ), не пиши об этом в лог проблем, не делай выводов вида «доставка не работает» только из-за отсутствия ответа и не усиливай напоминания: игнорируй молчание и составляй список по обычным правилам.";
/** Собирает входной промт шага 2 для менеджера по его пакетам. */
export async function buildStep2Prompt(ctx: AgentContext, managerId: string, packageIds: string[], today: string): Promise<string> {
const { rows } = await ctx.pool.query(
@@ -73,6 +77,8 @@ export async function buildStep2Prompt(ctx: AgentContext, managerId: string, pac
return [
loadPrompt("p-step2-prepare.md"),
"",
SILENCE_RULE,
"",
"Не используй инструменты, только текст.",
"",
`# Дата\n${today} (America/New_York)`,

View File

@@ -119,6 +119,8 @@ export interface ReminderSummary {
last_reminded_at: string;
last_reply_outcome: string | null;
last_reply_summary: string | null;
/** Начало текста последнего напоминания: записи без привязки к задаче (jt_task_id пуст) иначе ничего не говорят агенту. */
last_reminder_text: string | null;
}
/** Вход (7): компактная история напоминаний за последние days дней: по задаче - сколько раз напоминали и чем ответил менеджер. */
@@ -126,7 +128,8 @@ export async function input7(db: Queryable, assistantProjectId: string, since: D
const { rows } = await db.query(
`select jt_task_id, count(*)::int as reminders, max(reminded_at) as last_reminded_at,
(array_agg(reply_outcome order by reminded_at desc))[1] as last_reply_outcome,
(array_agg(reply_summary order by reminded_at desc))[1] as last_reply_summary
(array_agg(reply_summary order by reminded_at desc))[1] as last_reply_summary,
left((array_agg(reminder_text order by reminded_at desc))[1], 300) as last_reminder_text
from reminder_history where assistant_project_id = $1 and reminded_at >= $2
group by jt_task_id order by max(reminded_at) desc`,
[assistantProjectId, since],

View File

@@ -76,7 +76,8 @@ export async function runPrepJob(deps: PrepDeps, job: PrepJob, opts: { projectId
);
const outcomes: ProjectOutcome[] = [];
const byManager = new Map<string, { name: string; packageIds: string[]; outcomes: ProjectOutcome[]; tasks: number }>();
/** changed: хотя бы в одном проекте менеджера данные изменились (в 11:50 агент запускается только тогда, но получает пакеты ВСЕХ проектов менеджера, а не только изменённых). */
const byManager = new Map<string, { name: string; packageIds: string[]; outcomes: ProjectOutcome[]; tasks: number; changed: boolean }>();
for (const pr of projects as { id: string; jt_job_id: string; jt_membership_id: string; manager_id: string; manager_name: string }[]) {
const out: ProjectOutcome = { assistantProjectId: pr.id, jtJobId: pr.jt_job_id };
try {
@@ -87,13 +88,13 @@ export async function runPrepJob(deps: PrepDeps, job: PrepJob, opts: { projectId
});
Object.assign(out, { packageId: pkg.id, items: items.length, changedSinceMorning: pkg.changedSinceMorning });
const needAgent = job === "collect_morning" || pkg.changedSinceMorning === true;
if (!needAgent) out.agent = "not_needed";
else if (opts.dryRun) out.agent = "dry_run";
if (opts.dryRun) out.agent = needAgent ? "dry_run" : "not_needed";
else {
const g = byManager.get(pr.manager_id) ?? { name: pr.manager_name, packageIds: [], outcomes: [], tasks: 0 };
const g = byManager.get(pr.manager_id) ?? { name: pr.manager_name, packageIds: [], outcomes: [], tasks: 0, changed: false };
g.packageIds.push(pkg.id);
g.tasks += items.filter((i) => i.input_no !== 7).length;
g.outcomes.push(out);
if (needAgent) g.changed = true;
byManager.set(pr.manager_id, g);
}
} catch (e) {
@@ -105,6 +106,10 @@ export async function runPrepJob(deps: PrepDeps, job: PrepJob, opts: { projectId
// шаги 2-3: один консольный агент на менеджера (параллельно, ограничено пулом agent.gate)
await Promise.all(
[...byManager.entries()].map(async ([managerId, g]) => {
if (!g.changed) {
for (const o of g.outcomes) o.agent = "not_needed";
return;
}
if (!g.tasks) {
// нет работ и todo во входах (1)-(5): список не строим (память не заменяет данные), менеджеру не пишем, обращение в ИТ не нужно
deps.log.info({ managerId, manager: g.name }, "у менеджера нет задач во входах - шаг 2 пропущен");

View File

@@ -38,7 +38,7 @@ export interface AuditCandidate {
export const REPLY_WINDOW_SEC = 2 * 3600;
/** Короткие реплики («ok», «thanks») и служебные сообщения не проверяем. */
export const MIN_TEXT = 20;
const BATCH = 50;
const BATCH = 20;
/** Сообщения людей без ответа агента: нет сообщения бота в окне после него (и в его треде), текст не служебный. */
export function pickUnanswered(msgs: SlackHistoryMessage[], logged: Map<string, string>): { msg: SlackHistoryMessage; logged: string | null }[] {
@@ -167,7 +167,7 @@ export async function runMissedAudit(
const picked = pickUnanswered(msgs, new Map(lg.rows.map((r) => [String(r.message_ts), String(r.status)])));
for (const p of picked) {
const author = (p.msg.userId && (await slack.userName?.(p.msg.userId))) || p.msg.userId || "?";
candidates.push({ n: candidates.length + 1, channel: ch, ts: p.msg.ts, author, text: p.msg.text.slice(0, 700), logged: p.logged });
candidates.push({ n: candidates.length + 1, channel: ch, ts: p.msg.ts, author, text: p.msg.text.slice(0, 3000), logged: p.logged });
senders.set(`${ch.id}:${p.msg.ts}`, { userId: p.msg.userId, full: p.msg.text });
}
}