PEP-110: the analyst answers in the project chat on the project's subscription and files stories on request
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
91eca5ce23
commit
e163086b01
@ -37,6 +37,7 @@
|
||||
- **Выбор подписки проекта (PEP-76)**: общий пул платформы — `platform.shared_pool` (`sharedPool`/`setSharedPool`, CLI `peppa platform shared-pool [id|-]`); владелец проекта (или суперадмин) в «⋯ Настройки проекта → Подписки» жмёт «Общая подписка Пеппы» (`chooseSharedSubscription`) или вставляет токен `claude setup-token` — «Своя подписка Claude» (`connectOwnSubscription`, runner/project-subscription.ts: подписка + личный пул `ownPool`); `projectAgentWarning` для проекта без пула и без права на вход машины — «подписка не выбрана»
|
||||
- **Чаты (PEP-62)**: таблицы `chats` (master на пользователя / project на проект, связанная Telegram-группа `tg_chat_id`) и `chat_messages` (тред = `thread_key` `task:|incident:|release:<id>`, null — канал; `important` → мастер-лента; `dedupe_key`), `telegram_outbox.chat_message_id` (миграция 0015). `core/chats.ts`: `syncChats` — идемпотентная проекция `events` (курсор `chat.cursor.events`, список `EVENT_TEXT`), `questions`, `releases`/`incidents` (по `updated_at`, ключ `<вид>:<id>:<статус>`) в чаты; зовут бот (`reconcile`), вачдог (`tick`) и страница `/chats`; `masterFeed` = свои сообщения мастер-чата ∪ `important` проектов; `pruneChats` — TTL `PEPPA_CHAT_TTL_DAYS` (14) в вачдоге раз в час; мониторинг и дайджест из `deliverToUser` пишутся в мастер-чат. `runner/chats.ts` `postToChat`: тред стори → `answerAndDeliver` открытого вопроса, иначе `addStoryComment` (`chatMessageId` в payload, проекция не дублирует) + `sendToSession`; `/status|/task|/move|/help` без LLM. Telegram (бот): связка кодом (`createChatLinkCode`, `c…`, 10 мин; `t.me/<bot>?startgroup=<код>` или `/link <код>`), зеркало по курсору `chat.mirror.cursor` (тред — реплаем на первое сообщение: `threadAnchor` при отправке), в группу принимаются только реплаи и команды от пользователя с личной привязкой (`telegramAccountUser`) и доступом; кнопки вопросов работают в группе. Веб `/chats/[master|KEY]?thread=`, live-область `chats`. Тест `chats.test.ts`
|
||||
- **Обсуждение проекта (PEP-106)**: чат проекта открывается на «Обсуждении» — только сообщения людей в канале (`discussionMessages`: `thread_key` null, `kind` user, не команда); события агентов — `/chats/KEY?thread=feed`. `markDiscussionRead`/`discussionUnread` (`chat.read:<user>:<chat>`) → счётчик `navCounts.chats`, плашки чатов, ссылка «Обсуждение» после «Доски» на странице проекта. `postToChat` в канал проекта уведомляет остальных (`projectAudience`) событием уведомлений `chat`. `pruneChats` обсуждение не удаляет. Агентам обсуждение не уходит. Тест `discussion.test.ts`
|
||||
- **Чат с аналитиком (PEP-110)**: сообщение человека в обсуждении проекта (PEP-106) → `analystChatTick` в тике вачдога (`runner/analyst-chat.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`, `PEPPA_ANALYST_CHAT_MODEL`), контекст `core/analyst-chat.ts` (`intakeContext` + `projectStatusBlock` со ссылками «где что смотреть»), ответ `{reply, create[]}` → сообщение `kind: user, authorKind: agent, authorLogin: «Аналитик»` в то же обсуждение + событие уведомлений `chat`; стори из `create` — только по явной просьбе, intake у них `done`. Курсор `chat.analyst:<chatId>`, `analystPending` («печатает…»), сообщения старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) пропускаются, сбой — одна заметка без повторов, `PEPPA_ANALYST_CHAT=off`. Мок — роль `chat` в `mock-intake`; тест `analyst-chat.test.ts`
|
||||
- **Прогресс на Главной (PEP-77)**: `progressOverview` (core/progress.ts: стори по колонкам доски без архивных, стори в работе с агентом и прогрессом tasks.md, ждущие «Принять»; итог — только свои проекты, суперадмину отдельно `others`), раздел «Прогресс» — `components/ProgressOverview.tsx`
|
||||
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
|
||||
- **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние)
|
||||
|
||||
@ -1,11 +1,12 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Bot, Hash, Link2, MessagesSquare, Send, Unlink, User as UserIcon } from "lucide-react";
|
||||
import { isSuperadmin, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
|
||||
import { analystPending, isSuperadmin, chatMessagesView, chatThreads, chatTtlMs, discussionMessages, discussionUnread, getSetting, listChats, markDiscussionRead, masterFeed, syncChats, threadTitle, THREAD_KEY, type ChatMessageView, type Question } from "@peppa/core";
|
||||
import { projects, questions, tasks } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { ago, Empty, Flash, PageHeader } from "@/components/common";
|
||||
import { Hidden, QuestionCard } from "@/components/cards";
|
||||
import { Workspace } from "@/components/Workspace";
|
||||
@ -38,6 +39,8 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
const discussion = !master && rawThread === undefined;
|
||||
const unread = await discussionUnread(db, user.id);
|
||||
if (discussion) await markDiscussionRead(db, user.id, chat.id);
|
||||
// PEP-110: a person's message the analyst has not answered yet — «печатает…».
|
||||
const typing = discussion && (await analystPending(db, chat.id));
|
||||
|
||||
const threads = master ? [] : await chatThreads(db, chat.id);
|
||||
const messages = master
|
||||
@ -67,7 +70,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
const placeholder = master
|
||||
? "/status, /task KEY-N, /move KEY-N in_progress, /help"
|
||||
: discussion
|
||||
? "Напишите сообщение участникам проекта…"
|
||||
? "Спросите аналитика, что с проектом, или опишите идею — он поможет сформулировать стори…"
|
||||
: taskThread
|
||||
? "Ответ агенту: на открытый вопрос, иначе комментарий, который он увидит сразу"
|
||||
: thread
|
||||
@ -147,7 +150,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<PageHeader title="Чаты">
|
||||
{master
|
||||
? "Мастер-чат: всё важное по вашим проектам в одной ленте."
|
||||
: "Обсуждение — обычный чат участников проекта: статусы, вопросы, договорённости. Агенты его не читают; чтобы написать агенту, откройте стори."}
|
||||
: "Чат с аналитиком — ИИ-агентом вашего проекта. Спросите, что сделано и где это посмотреть, или опишите идею: он уточнит, предложит стори и заведёт их в бэклог, когда вы скажете."}
|
||||
</PageHeader>
|
||||
|
||||
<nav className="mb-4 flex flex-wrap gap-1.5" aria-label="Чаты">
|
||||
@ -178,7 +181,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
<div className={cn("grid gap-4", !master && "lg:grid-cols-[230px_minmax(0,1fr)]")}>
|
||||
{!master && (
|
||||
<nav aria-label="Треды" className="flex flex-col gap-0.5 self-start rounded-lg border bg-card/50 p-1.5 text-sm max-lg:max-h-48 max-lg:overflow-y-auto">
|
||||
<ThreadLink href={url({})} active={discussion} title="💬 Обсуждение" meta="чат участников проекта" />
|
||||
<ThreadLink href={url({})} active={discussion} title="💬 Чат с аналитиком" meta="вопросы и новые задачи" />
|
||||
<ThreadLink href={url({ thread: FEED })} active={!discussion && thread === undefined} title="События агентов" meta="вопросы, ревью, релизы" />
|
||||
{threads.length > 0 && <div className="mx-2 my-1 border-t" />}
|
||||
{threads.map((t) => (
|
||||
@ -196,7 +199,7 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
</div>
|
||||
)}
|
||||
{messages.length === 0 ? (
|
||||
<Empty>{discussion ? "Здесь пока тихо. Напишите первое сообщение — его увидят участники проекта." : master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}</Empty>
|
||||
<Empty>{discussion ? "Напишите, что хотите узнать или сделать, — аналитик ответит здесь же. Например: «Что сейчас в работе?» или «Хочу страницу с отзывами клиентов»." : master ? "Пока тихо: здесь появятся вопросы агентов, сбои, релизы и ошибки твоих проектов." : thread === undefined ? "Сообщений пока нет: они появятся, когда агенты возьмутся за стори." : "В этом треде пока пусто."}</Empty>
|
||||
) : (
|
||||
<ol className="m-0 flex list-none flex-col gap-2 p-0">
|
||||
{messages.map((m) => (
|
||||
@ -206,11 +209,16 @@ export default async function ChatPage({ params, searchParams }: { params: Promi
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
{typing && (
|
||||
<p className="m-0 flex items-center gap-2 text-sm text-muted-foreground" aria-live="polite">
|
||||
<AgentBadge name="Аналитик" /> <span className="animate-pulse">печатает…</span>
|
||||
</p>
|
||||
)}
|
||||
<form action={postChatAction} className="sticky bottom-16 flex flex-col gap-2 rounded-lg border bg-card p-3 md:bottom-3">
|
||||
<Hidden fields={{ chatId: chat.id, thread: thread ?? "", back: here }} />
|
||||
<Textarea name="text" rows={2} required maxLength={8000} placeholder={placeholder} aria-label="Сообщение" />
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-muted-foreground">{discussion ? "видят участники проекта · агенты не читают" : thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
|
||||
<span className="text-xs text-muted-foreground">{discussion ? "отвечает аналитик на подписке проекта · переписку видят участники проекта" : thread ? "в тред" : master ? "в мастер-чат" : "в канал"}{chat.tgTitle ? ` · и в Telegram «${chat.tgTitle}»` : ""}</span>
|
||||
<Button size="sm" className="ml-auto">
|
||||
<Send />
|
||||
Отправить
|
||||
@ -244,6 +252,19 @@ function TaskLink({ messages }: { messages: ChatMessageView[] }) {
|
||||
return key ? <Link href={`/t/${key}`} className="text-xs">открыть стори →</Link> : null;
|
||||
}
|
||||
|
||||
/** URLs in a message become links (the analyst points at the board, a story, a stand). */
|
||||
function linkify(text: string) {
|
||||
return text.split(/(https?:\/\/[^\s<>«»"]+[^\s<>«»".,;:!?)])/g).map((part, i) =>
|
||||
i % 2 ? (
|
||||
<a key={i} href={part} target={part.startsWith(process.env.PEPPA_WEB_URL ?? "\0") ? undefined : "_blank"} rel="noreferrer">
|
||||
{part}
|
||||
</a>
|
||||
) : (
|
||||
part
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function threadHref(m: ChatMessageView) {
|
||||
return m.projectKey && m.threadKey ? `/chats/${m.projectKey}?thread=${encodeURIComponent(m.threadKey)}` : m.projectKey ? `/chats/${m.projectKey}` : null;
|
||||
}
|
||||
@ -254,8 +275,12 @@ function MessageItem({ m, q, back, showThread, masterView, mine = false }: { m:
|
||||
const label = [masterView && m.projectKey ? m.projectKey : null, m.threadTitle].filter(Boolean).join(" · ");
|
||||
const head = (
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? <Bot className="size-3.5" /> : <MessagesSquare className="size-3.5" />}
|
||||
<span className="font-medium text-foreground">{m.authorKind === "user" ? (mine ? "вы" : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? "агент" : "Пеппа"}</span>
|
||||
{m.authorKind === "user" ? <UserIcon className="size-3.5" /> : m.authorKind === "agent" ? (m.authorLogin ? null : <Bot className="size-3.5" />) : <MessagesSquare className="size-3.5" />}
|
||||
{m.authorKind === "agent" && m.authorLogin ? (
|
||||
<AgentBadge name={m.authorLogin} className="text-foreground" />
|
||||
) : (
|
||||
<span className="font-medium text-foreground">{m.authorKind === "user" ? (mine ? "вы" : (m.authorLogin ?? "?")) : m.authorKind === "agent" ? "агент" : "Пеппа"}</span>
|
||||
)}
|
||||
{m.via === "telegram" && <span title="из Telegram">· Telegram</span>}
|
||||
{where && href && (
|
||||
<Link href={href} className="max-w-full truncate">
|
||||
@ -276,7 +301,7 @@ function MessageItem({ m, q, back, showThread, masterView, mine = false }: { m:
|
||||
return (
|
||||
<article className={cn("flex flex-col gap-1 rounded-lg border bg-card px-3 py-2", m.kind === "user" && "border-primary/30 bg-primary/5", m.kind === "system" && "border-dashed bg-transparent")}>
|
||||
{head}
|
||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{m.text}</p>
|
||||
<p className="m-0 text-sm break-words whitespace-pre-wrap">{linkify(m.text)}</p>
|
||||
{m.url && (
|
||||
<a href={m.url} target="_blank" rel="noreferrer" className="truncate text-xs">
|
||||
{m.url}
|
||||
|
||||
@ -446,7 +446,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
{/* PEP-106: the people's chat of the project lives in «Чаты»; the link sits right after the board. */}
|
||||
{t.id === "board" && (
|
||||
<a href={`/chats/${p.key}`} className="-mb-px flex items-center gap-1.5 border-b-2 border-transparent px-3 py-2 text-sm whitespace-nowrap text-muted-foreground hover:text-foreground hover:no-underline">
|
||||
Обсуждение
|
||||
Чат с аналитиком
|
||||
{discussionNew > 0 && <span className="rounded-full bg-info px-1.5 font-mono text-[11px] text-background tabular-nums">{discussionNew}</span>}
|
||||
</a>
|
||||
)}
|
||||
|
||||
@ -65,6 +65,25 @@ export default async function Welcome() {
|
||||
))}
|
||||
</ol>
|
||||
</Section>
|
||||
<Section title="Три способа говорить с фабрикой">
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="font-medium">Чат с аналитиком</span>
|
||||
<span className="text-sm text-muted-foreground">ИИ-агент вашего проекта: спросите, что сделано и где это посмотреть, или опишите идею — он поможет сформулировать стори и заведёт их.</span>
|
||||
<Link href="/chats" className="mt-1 text-sm">Открыть чаты →</Link>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="font-medium">Свой Telegram-бот</span>
|
||||
<span className="text-sm text-muted-foreground">Через него приходят вопросы и статусы, и ему же можно написать или наговорить новую задачу.</span>
|
||||
<Link href="/settings#telegram" className="mt-1 text-sm">Подключить бота →</Link>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 rounded-xl border bg-card px-4 py-3">
|
||||
<span className="font-medium">Ваш Claude или ChatGPT</span>
|
||||
<span className="text-sm text-muted-foreground">Подключите Peppa FACTORY к своему чату (MCP) — и ведите проекты прямо из него: «создай стори», «что ждёт моего ответа?».</span>
|
||||
<Link href="/help" className="mt-1 text-sm">Как подключить →</Link>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="Слова, которые встретятся">
|
||||
<dl className="m-0 grid gap-2 sm:grid-cols-2">
|
||||
{WORDS.map(([t, d]) => (
|
||||
|
||||
25
openspec/changes/pep-110-analyst-chat/proposal.md
Normal file
25
openspec/changes/pep-110-analyst-chat/proposal.md
Normal file
@ -0,0 +1,25 @@
|
||||
# Proposal: PEP-110 — чат с аналитиком
|
||||
|
||||
## Why
|
||||
PM: чат проекта — это разговор пользователя с ИИ-аналитиком на подписке проекта, а не только
|
||||
переписка людей. Пример: владелец проекта спросила в чате «где работает этот агент? где увидеть
|
||||
предложения по стажировкам?» — и ей никто не ответил.
|
||||
|
||||
## What Changes
|
||||
- `core/analyst-chat.ts`: контекст (`intakeContext` + `projectStatusBlock`: стори со статусами
|
||||
простыми словами и агентами, открытые вопросы, «где что смотреть» со ссылками), промпт,
|
||||
разбор ответа `{reply, create[]}`, курсор `chat.analyst:<chatId>`, `analystPending`.
|
||||
- `runner/analyst-chat.ts`: `analystChatTick` в тике вачдога — сообщение человека в обсуждении
|
||||
без ответа → `claudePrint` на подписке проекта (как продакт/аналитик intake) → ответ в то же
|
||||
обсуждение от «Аналитика» (ИИ-агент) + уведомление участникам (событие `chat`, свой бот).
|
||||
Стори заводятся только по явной просьбе человека (`create`), состояние intake у них `done`.
|
||||
Сбой/неформат — одна честная заметка без повторов; нет подписки — «подключите»; сообщения
|
||||
старше `PEPPA_ANALYST_CHAT_MAX_AGE_MIN` (60) не получают позднего ответа;
|
||||
`PEPPA_ANALYST_CHAT=off` выключает; модель — `PEPPA_ANALYST_CHAT_MODEL` (sonnet).
|
||||
- Веб: «Чат с аналитиком» вместо «Обсуждения», «печатает…», бейдж ИИ-агента, ссылки в
|
||||
сообщениях кликабельны; на «О Пеппе» — три способа говорить с фабрикой (чат, свой бот, MCP).
|
||||
- Мок: роль `chat` в `mock-intake`; тест `analyst-chat.test.ts`; проверено на настоящей модели.
|
||||
|
||||
## Вне scope
|
||||
Разговор с аналитиком прямо в Telegram-боте (сейчас текст боту = черновик стори); подписки
|
||||
ChatGPT (`claudePrint` умеет только Claude).
|
||||
@ -0,0 +1,20 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Аналитик отвечает в чате проекта
|
||||
Чат проекта SHALL отвечать человеку от имени ИИ-аналитика на подписке проекта: о состоянии проекта и о том, как сформулировать новую стори.
|
||||
|
||||
#### Scenario: Вопрос о проекте
|
||||
- **WHEN** участник пишет в чат проекта «где увидеть результат?»
|
||||
- **THEN** аналитик отвечает в том же чате по данным проекта (стори, статусы, ссылки), ответ приходит и в Telegram-бот участника
|
||||
|
||||
#### Scenario: Новая задача
|
||||
- **WHEN** участник описывает идею
|
||||
- **THEN** аналитик уточняет по продукту (не по технике), предлагает стори и заводит их в бэклог только после явной просьбы
|
||||
|
||||
#### Scenario: Нет подписки или сбой
|
||||
- **WHEN** у проекта нет подписки Claude или модель не ответила
|
||||
- **THEN** в чате появляется одна понятная заметка, повторных попыток нет
|
||||
|
||||
#### Scenario: Старое сообщение
|
||||
- **WHEN** сообщение ждало больше часа
|
||||
- **THEN** аналитик на него не отвечает
|
||||
4
openspec/changes/pep-110-analyst-chat/tasks.md
Normal file
4
openspec/changes/pep-110-analyst-chat/tasks.md
Normal file
@ -0,0 +1,4 @@
|
||||
- [x] 1.1 core: контекст, промпт, разбор, курсор
|
||||
- [x] 1.2 runner: analystChatTick в вачдоге, заведение стори, уведомления
|
||||
- [x] 1.3 веб: чат с аналитиком, «печатает…», ссылки, «О Пеппе»
|
||||
- [x] 1.4 мок и тесты; прогон на настоящей модели на копии базы
|
||||
145
packages/core/src/analyst-chat.ts
Normal file
145
packages/core/src/analyst-chat.ts
Normal file
@ -0,0 +1,145 @@
|
||||
// PEP-110: the analyst in the project's chat. A person writes in the discussion (PEP-106) in
|
||||
// plain words; «аналитик» — an AI agent on the project's own subscription — answers: where
|
||||
// things are and in what state, and helps turn an idea into stories, which it files on request.
|
||||
// This module is the pure part (context, prompt, parsing); the model call is runner/analyst-chat.ts.
|
||||
import { chatMessages, questions, releases, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey } from "@peppa/shared";
|
||||
import { and, desc, eq, isNull } from "drizzle-orm";
|
||||
import { intakeContext } from "./intake.ts";
|
||||
import type { Project } from "./projects.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
import { taskAgentNames } from "./team.ts";
|
||||
|
||||
/** The analyst's name on its messages (an AI agent, shown with the robot badge). */
|
||||
export const ANALYST_NAME = "Аналитик";
|
||||
export const ANALYST_MAX_STORIES = 5;
|
||||
const HISTORY = 20;
|
||||
|
||||
const STATUS_RU: Record<string, string> = {
|
||||
backlog: "в бэклоге (ждёт очереди)",
|
||||
proposing: "агент составляет план",
|
||||
awaiting_approval: "ждёт одобрения плана",
|
||||
in_progress: "в работе у агента",
|
||||
review: "готова, ждёт приёмки",
|
||||
done: "готова и принята",
|
||||
blocked: "заблокирована",
|
||||
};
|
||||
|
||||
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
|
||||
|
||||
/** What is going on in the project right now, in words a product manager understands. */
|
||||
export async function projectStatusBlock(db: Db, project: Project, webUrl = process.env.PEPPA_WEB_URL ?? ""): Promise<string> {
|
||||
const stories = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt))).orderBy(desc(tasks.id)).limit(60);
|
||||
const agentOf = await taskAgentNames(db, project.id);
|
||||
const open = await db.select().from(questions).where(and(eq(questions.projectId, project.id), isNull(questions.answeredAt))).orderBy(desc(questions.id)).limit(10);
|
||||
const rels = await db.select().from(releases).where(eq(releases.projectId, project.id)).orderBy(desc(releases.id)).limit(30);
|
||||
const live = (env: "preview" | "staging" | "prod") => rels.find((r) => r.env === env && r.status === "healthy" && r.host);
|
||||
const key = (t: { number: number }) => formatTaskKey(project.key, t.number);
|
||||
const line = (t: (typeof stories)[number]) =>
|
||||
`- ${key(t)} «${t.title}» — ${STATUS_RU[t.status] ?? t.status}${agentOf.get(t.id) ? `, агент ${agentOf.get(t.id)}` : ""}${t.prUrl && t.status !== "backlog" ? `; страница стори: ${webUrl}/t/${key(t)}` : ""}`;
|
||||
const where = [
|
||||
`- Доска проекта (все стори и их статусы): ${webUrl}/p/${project.key}`,
|
||||
`- Страница стори — план, обсуждение с агентом, проверки, результат: ${webUrl}/t/${project.key}-<номер>`,
|
||||
...(live("staging") ? [`- Собранный продукт для проверки (staging): https://${live("staging")!.host}`] : []),
|
||||
...(live("prod") ? [`- Рабочий продукт (прод): https://${live("prod")!.host}`] : []),
|
||||
...(live("preview") ? [`- Предпросмотр последней стори на ревью: https://${live("preview")!.host}`] : []),
|
||||
...(!rels.length ? ["- Продукт ещё никуда не выкатывался: посмотреть результат можно на странице стори (вкладка «Результат») и в коде проекта."] : []),
|
||||
];
|
||||
return [
|
||||
"## Что сейчас в проекте",
|
||||
stories.length ? stories.map(line).join("\n") : "(стори ещё нет)",
|
||||
"",
|
||||
"## Вопросы агентов, которые ждут ответа человека",
|
||||
open.length ? open.map((q) => `- #${q.id}: ${clip(q.text.replace(/\s+/g, " "), 200)}`).join("\n") : "(нет)",
|
||||
"",
|
||||
"## Где что смотреть",
|
||||
where.join("\n"),
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export interface ChatTurn {
|
||||
/** Login of the person, or ANALYST_NAME. */
|
||||
who: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** The last messages of the discussion, oldest first (people and the analyst). */
|
||||
export async function discussionHistory(db: Db, chatId: number, limit = HISTORY): Promise<ChatTurn[]> {
|
||||
const rows = await db
|
||||
.select({ kind: chatMessages.authorKind, login: chatMessages.authorLogin, text: chatMessages.text })
|
||||
.from(chatMessages)
|
||||
.where(and(eq(chatMessages.chatId, chatId), isNull(chatMessages.threadKey), eq(chatMessages.kind, "user")))
|
||||
.orderBy(desc(chatMessages.id))
|
||||
.limit(limit);
|
||||
return rows.reverse().filter((r) => !r.text.startsWith("/") && r.kind !== "system").map((r) => ({ who: r.kind === "agent" ? ANALYST_NAME : (r.login ?? "пользователь"), text: r.text }));
|
||||
}
|
||||
|
||||
export async function analystChatContext(db: Db, project: Project): Promise<string> {
|
||||
return [await intakeContext(db, project, { id: 0, goalId: null }), "", await projectStatusBlock(db, project)].join("\n");
|
||||
}
|
||||
|
||||
export function analystChatPrompt(context: string, history: ChatTurn[]): string {
|
||||
return [
|
||||
"Ты — аналитик проекта в чате софтвер-фабрики Peppa FACTORY. С тобой переписывается продакт-менеджер проекта — не программист. Ты ИИ-агент и не выдаёшь себя за человека.",
|
||||
"Что ты делаешь:",
|
||||
"1. Отвечаешь на вопросы о проекте по данным ниже: что сделано, что в работе и у какого агента, чего ждут от человека, где посмотреть результат (давай ссылки из раздела «Где что смотреть»). Если в данных ответа нет — скажи прямо, что не знаешь, не выдумывай.",
|
||||
"2. Помогаешь сформулировать новую задачу: уточняешь, для кого это и что должно получиться; задаёшь не больше двух вопросов за раз и только о продукте (что увидит пользователь, правила, тексты, деньги) — никогда о технике (стек, база, архитектура). Где можно решить самому — решаешь и говоришь, что решил.",
|
||||
`3. Когда задача понятна — предлагаешь стори: название и что должно получиться, с критериями приёмки. Большое делишь на несколько (не больше ${ANALYST_MAX_STORIES}). Заводишь стори в бэклог (поле create) только когда человек явно попросил: «заведи», «создай», «да, делаем», «в работу». Пока он не подтвердил — create пустой, а в reply спроси, заводить ли.`,
|
||||
"Тон: коллега, а не помощник. Коротко, по делу, простыми словами, без жаргона (PR, CI, API, ветка, деплой — нельзя; «стенд для проверки», «проверки», «код» — можно). Не хвали и не благодари, без восклицаний. Отвечай на языке собеседника.",
|
||||
"",
|
||||
context,
|
||||
"",
|
||||
"## Переписка (последние сообщения, старые сверху)",
|
||||
...history.map((t) => `${t.who}: ${t.text.trim()}`),
|
||||
"",
|
||||
'Ответь на последнее сообщение ОДНОЙ строкой JSON без пояснений: {"reply":"…","create":[{"title":"…","description":"…"}]}',
|
||||
"reply — твой ответ в чат (обычный текст, можно с переносами строк и списком через «•»). create — стори, которые нужно завести прямо сейчас (обычно пустой список); description — что должно получиться, для кого, и критерии приёмки списком.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export interface AnalystReply {
|
||||
reply: string;
|
||||
create: Array<{ title: string; description: string }>;
|
||||
}
|
||||
|
||||
/** The model's answer; null when it is not the JSON asked for. */
|
||||
export function parseAnalystReply(text: string): AnalystReply | null {
|
||||
const m = /\{[\s\S]*\}/.exec(text);
|
||||
if (!m) return null;
|
||||
try {
|
||||
const o = JSON.parse(m[0]) as { reply?: unknown; create?: unknown };
|
||||
const reply = typeof o.reply === "string" ? o.reply.trim().slice(0, 6000) : "";
|
||||
if (!reply) return null;
|
||||
const create = (Array.isArray(o.create) ? o.create : [])
|
||||
.map((s) => s as { title?: unknown; description?: unknown })
|
||||
.filter((s) => typeof s.title === "string" && s.title.trim())
|
||||
.slice(0, ANALYST_MAX_STORIES)
|
||||
.map((s) => ({ title: String(s.title).trim().slice(0, 120), description: typeof s.description === "string" ? s.description.trim().slice(0, 6000) : "" }));
|
||||
return { reply, create };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── what the analyst has already answered ─────────────────────────────────────
|
||||
|
||||
const cursorKey = (chatId: number) => `chat.analyst:${chatId}`;
|
||||
|
||||
/** Id of the last discussion message the analyst has dealt with. */
|
||||
export async function analystCursor(db: Db, chatId: number): Promise<number> {
|
||||
return (await getSetting<number>(db, cursorKey(chatId))) ?? 0;
|
||||
}
|
||||
export async function setAnalystCursor(db: Db, chatId: number, messageId: number): Promise<void> {
|
||||
await setSetting(db, cursorKey(chatId), messageId);
|
||||
}
|
||||
|
||||
/** Is a person's message in the discussion still waiting for the analyst? (the «печатает…» mark) */
|
||||
export async function analystPending(db: Db, chatId: number): Promise<boolean> {
|
||||
const [last] = await db
|
||||
.select({ id: chatMessages.id, kind: chatMessages.authorKind, text: chatMessages.text })
|
||||
.from(chatMessages)
|
||||
.where(and(eq(chatMessages.chatId, chatId), isNull(chatMessages.threadKey), eq(chatMessages.kind, "user")))
|
||||
.orderBy(desc(chatMessages.id))
|
||||
.limit(1);
|
||||
return !!last && last.kind === "user" && !last.text.startsWith("/") && last.id > (await analystCursor(db, chatId));
|
||||
}
|
||||
@ -25,6 +25,7 @@ export * from "./google.ts";
|
||||
export * from "./team.ts";
|
||||
export * from "./progress.ts";
|
||||
export * from "./intake.ts";
|
||||
export * from "./analyst-chat.ts";
|
||||
export * from "./local-users.ts";
|
||||
export * from "./specs.ts";
|
||||
export * from "./subscriptions.ts";
|
||||
|
||||
127
packages/runner/src/analyst-chat.ts
Normal file
127
packages/runner/src/analyst-chat.ts
Normal file
@ -0,0 +1,127 @@
|
||||
// PEP-110: the analyst answers in the project's discussion. The watchdog calls
|
||||
// `analystChatTick`; a person's message that nobody answered yet goes to the model (on the
|
||||
// project's own subscription, like the intake roles) together with the project's context and
|
||||
// the last messages, and the answer is posted into the same discussion. Stories the person
|
||||
// asked for are filed into the backlog, already formulated (the intake roles skip them).
|
||||
import {
|
||||
addChatMessage,
|
||||
analystChatContext,
|
||||
analystChatPrompt,
|
||||
analystCursor,
|
||||
ANALYST_NAME,
|
||||
createTask,
|
||||
deliverToUser,
|
||||
discussionHistory,
|
||||
notify,
|
||||
parseAnalystReply,
|
||||
projectAudience,
|
||||
setAnalystCursor,
|
||||
setIntakeState,
|
||||
type Project,
|
||||
} from "@peppa/core";
|
||||
import { chatMessages, chats, projects, type Db } from "@peppa/db";
|
||||
import { and, desc, eq, gt, isNull } from "drizzle-orm";
|
||||
import { claudePrint } from "./claude-print.ts";
|
||||
|
||||
const inFlight = new Set<number>();
|
||||
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
|
||||
const ask = (db: Db, project: Project, prompt: string) =>
|
||||
claudePrint(db, project, {
|
||||
bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
|
||||
model: process.env.PEPPA_ANALYST_CHAT_MODEL ?? process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
|
||||
timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
|
||||
prompt,
|
||||
who: "аналитик",
|
||||
});
|
||||
|
||||
export interface AnalystChatOptions {
|
||||
log?: (m: string) => void;
|
||||
now?: Date;
|
||||
/** Wait for the model calls (tests); the watchdog lets them run in the background. */
|
||||
wait?: boolean;
|
||||
}
|
||||
|
||||
/** People's messages in project discussions that the analyst has not answered yet. */
|
||||
export async function analystChatTick(db: Db, opts: AnalystChatOptions = {}): Promise<void> {
|
||||
if (process.env.PEPPA_ANALYST_CHAT === "off") return;
|
||||
const log = opts.log ?? (() => {});
|
||||
const now = (opts.now ?? new Date()).getTime();
|
||||
const maxAgeMs = Math.max(1, Number(process.env.PEPPA_ANALYST_CHAT_MAX_AGE_MIN ?? 60) || 60) * 60_000;
|
||||
const jobs: Promise<void>[] = [];
|
||||
const rows = await db.select({ chat: chats, project: projects }).from(chats).innerJoin(projects, eq(chats.projectId, projects.id)).where(eq(chats.kind, "project"));
|
||||
for (const { chat, project } of rows) {
|
||||
if (inFlight.has(chat.id)) continue;
|
||||
const cursor = await analystCursor(db, chat.id);
|
||||
const [last] = await db
|
||||
.select({ id: chatMessages.id, kind: chatMessages.authorKind, text: chatMessages.text, at: chatMessages.createdAt })
|
||||
.from(chatMessages)
|
||||
.where(and(eq(chatMessages.chatId, chat.id), isNull(chatMessages.threadKey), eq(chatMessages.kind, "user"), gt(chatMessages.id, cursor)))
|
||||
.orderBy(desc(chatMessages.id))
|
||||
.limit(1);
|
||||
if (!last) continue;
|
||||
// The analyst's own message or a command on top: nothing to answer, move on. So is a message
|
||||
// that waited too long (written before the analyst existed, or during an outage): a late
|
||||
// answer to a stale question only confuses — the person asks again.
|
||||
const stale = now - last.at.getTime() > maxAgeMs;
|
||||
if (last.kind !== "user" || last.text.startsWith("/") || stale) {
|
||||
await setAnalystCursor(db, chat.id, last.id);
|
||||
continue;
|
||||
}
|
||||
inFlight.add(chat.id);
|
||||
jobs.push(
|
||||
answer(db, project, chat.id, last.id, log)
|
||||
.catch((e) => log(`analyst chat ${project.key}: ${(e as Error).message}`))
|
||||
.finally(() => inFlight.delete(chat.id)),
|
||||
);
|
||||
}
|
||||
if (opts.wait) await Promise.all(jobs);
|
||||
}
|
||||
|
||||
async function say(db: Db, project: Project, chatId: number, text: string, agent = true) {
|
||||
const m = await addChatMessage(db, agent ? { chatId, kind: "user", authorKind: "agent", authorLogin: ANALYST_NAME, text } : { chatId, kind: "user", authorKind: "system", text });
|
||||
await notify(db, { type: "chat_message", messageId: m?.id ?? 0 });
|
||||
// The answer reaches the project's people in their own Telegram bot / browser too.
|
||||
if (agent && m) {
|
||||
const short = text.length > 800 ? `${text.slice(0, 800)}…` : text;
|
||||
for (const u of await projectAudience(db, project.id)) {
|
||||
await deliverToUser(db, u, {
|
||||
event: "chat",
|
||||
projectId: project.id,
|
||||
dedupeKey: `chat:m${m.id}:${u.telegramChatId}`,
|
||||
pushKey: `chat:m${m.id}:u${u.id}`,
|
||||
telegram: { params: { text: `💬 <b>${esc(project.name)}</b> · ${ANALYST_NAME}:\n${esc(short)}\n\nОтветить: ${process.env.PEPPA_WEB_URL ?? ""}/chats/${project.key}`, parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
|
||||
push: { title: `${project.name}: ${ANALYST_NAME}`, body: short.slice(0, 200), url: `/chats/${project.key}`, tag: `chat:${project.id}` },
|
||||
}).catch(() => null);
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
async function answer(db: Db, project: Project, chatId: number, upTo: number, log: (m: string) => void): Promise<void> {
|
||||
const history = await discussionHistory(db, chatId);
|
||||
const out = await ask(db, project, analystChatPrompt(await analystChatContext(db, project), history));
|
||||
// Whatever happens, this message is dealt with: a failure is said once, not retried forever.
|
||||
await setAnalystCursor(db, chatId, upTo);
|
||||
if (!out.ok) {
|
||||
const noSub = /нет подписки/.test(out.error);
|
||||
await say(db, project, chatId, noSub ? "Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз." : `Аналитик сейчас не смог ответить (${out.error.slice(0, 200)}). Напишите ещё раз чуть позже.`, false);
|
||||
log(`analyst chat ${project.key}: ${out.error}`);
|
||||
return;
|
||||
}
|
||||
const reply = parseAnalystReply(out.text);
|
||||
if (!reply) {
|
||||
await say(db, project, chatId, "Аналитик ответил не по форме — напишите вопрос ещё раз, пожалуйста.", false);
|
||||
log(`analyst chat ${project.key}: unparsable answer`);
|
||||
return;
|
||||
}
|
||||
const filed: string[] = [];
|
||||
for (const s of reply.create) {
|
||||
const ref = await createTask(db, { projectId: project.id, title: s.title, description: s.description });
|
||||
// Formulated in the conversation already: «продакт» and «аналитик» of the intake skip it.
|
||||
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: "сформулирована с аналитиком в чате" });
|
||||
filed.push(`• ${ref.key} «${s.title}»`);
|
||||
}
|
||||
await say(db, project, chatId, filed.length ? `${reply.reply}\n\nЗавёл в бэклог:\n${filed.join("\n")}` : reply.reply);
|
||||
log(`analyst chat ${project.key}: answered${filed.length ? `, filed ${filed.length}` : ""}`);
|
||||
}
|
||||
@ -14,6 +14,7 @@ export * from "./monitor.ts";
|
||||
export * from "./ci.ts";
|
||||
export * from "./transfer.ts";
|
||||
export * from "./incidents.ts";
|
||||
export * from "./analyst-chat.ts";
|
||||
export * from "./triage.ts";
|
||||
export * from "./ci-feedback.ts";
|
||||
export * from "./deploy.ts";
|
||||
|
||||
@ -33,6 +33,7 @@ import { pollChecks } from "./ci-feedback.ts";
|
||||
import { reviewTick } from "./reviewer.ts";
|
||||
import { autonomyTick } from "./autonomy.ts";
|
||||
import { intakeTick } from "./intake.ts";
|
||||
import { analystChatTick } from "./analyst-chat.ts";
|
||||
import { budgetTick } from "./budgets.ts";
|
||||
import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts";
|
||||
import { serveRunnerCommands, type RunnerService } from "./runner-service.ts";
|
||||
@ -87,6 +88,8 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
// PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them.
|
||||
await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake"));
|
||||
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
|
||||
// PEP-110: the analyst answers people in the projects' discussions.
|
||||
await analystChatTick(db, { log }).catch(failed(db, log, "analyst chat"));
|
||||
// Errors of running products (PEP-58): Bugsink poll + incident policies.
|
||||
await incidentTick(db, { now: opts.now, log }).catch(failed(db, log, "incidents"));
|
||||
// Daily digest at each user's time (PEP-29); a no-op outside their window.
|
||||
|
||||
@ -8,6 +8,8 @@
|
||||
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
|
||||
interface Scenario {
|
||||
/** PEP-110: the analyst in the project chat: {reply, create[]}. */
|
||||
chat?: object;
|
||||
product?: object;
|
||||
analyst?: { questions?: unknown[] } & Record<string, unknown>;
|
||||
garbage?: boolean;
|
||||
@ -17,7 +19,7 @@ interface Scenario {
|
||||
const file = process.env.MOCK_INTAKE_SCENARIO;
|
||||
const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
||||
const prompt = readFileSync(0, "utf8");
|
||||
const role = prompt.startsWith("Ты — продакт-менеджер") ? "product" : "analyst";
|
||||
const role = prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : "analyst";
|
||||
const answered = /Ответ продакта:\n/.test(prompt);
|
||||
const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? "";
|
||||
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n");
|
||||
@ -40,5 +42,11 @@ const analyst = {
|
||||
...sc.analyst,
|
||||
};
|
||||
if (answered) analyst.questions = [];
|
||||
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "product" ? product : analyst);
|
||||
// PEP-110, chat: without a scenario it answers the last line; «заведи» in it files one story.
|
||||
const lastLine = /## Переписка[^\n]*\n([\s\S]*?)\n\nОтветь на последнее/.exec(prompt)?.[1]?.trim().split("\n").at(-1) ?? "";
|
||||
const chat = sc.chat ?? {
|
||||
reply: `Ответ на: ${lastLine.replace(/^[^:]*: /, "")}`,
|
||||
create: /заведи|создай/i.test(lastLine) ? [{ title: "Страница отзывов", description: "Клиент видит отзывы.\n- Отзывы видны на странице" }] : [],
|
||||
};
|
||||
const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "product" ? product : role === "chat" ? chat : analyst);
|
||||
process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n");
|
||||
|
||||
138
packages/testkit/test/analyst-chat.test.ts
Normal file
138
packages/testkit/test/analyst-chat.test.ts
Normal file
@ -0,0 +1,138 @@
|
||||
// PEP-110: the analyst answers in the project's chat on the project's subscription — questions
|
||||
// about the project, help with a new story, filing stories on request (mock-intake, role "chat").
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { core, db, runner, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
process.env.PEPPA_WEB_URL = "http://peppa.test";
|
||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||
const TMP = mkdtempSync(join(tmpdir(), "peppa-analyst-chat-"));
|
||||
const scenario = join(TMP, "scenario.json");
|
||||
const calls = () => readFileSync(`${scenario}.log.jsonl`, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { role: string; prompt: string });
|
||||
const setScenario = (s: object) => writeFileSync(scenario, JSON.stringify(s));
|
||||
const tick = () => runner.analystChatTick(db, { wait: true });
|
||||
|
||||
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||||
let pm: User;
|
||||
let project: Awaited<ReturnType<typeof core.createProject>>;
|
||||
let chat: Awaited<ReturnType<typeof core.ensureProjectChat>>;
|
||||
const post = (text: string) => runner.postToChat(db, pm, { chatId: chat.id, threadKey: null, text, via: "web" });
|
||||
const talk = async () => (await core.discussionMessages(db, chat.id)).map((m) => [m.authorKind, m.authorLogin, m.text] as const);
|
||||
|
||||
before(async () => {
|
||||
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
|
||||
process.env.MOCK_INTAKE_SCENARIO = scenario;
|
||||
setScenario({});
|
||||
// An allowlisted owner: the machine's login stands in for a subscription in tests.
|
||||
pm = await core.upsertUserFromGitea(db, { id: 1101, login: "asel" }, { access_token: "x" });
|
||||
const ws = join(TMP, "ws");
|
||||
mkdirSync(join(ws, ".peppa"), { recursive: true });
|
||||
writeFileSync(join(ws, "AGENTS.md"), "# AGENTS.md\n\n- Интерфейс на русском\n");
|
||||
project = await core.createProject(db, { slug: "mock-achat", key: "MACH", name: "Стажировки", giteaOwner: "x", workspacePath: ws, ownerId: pm.id });
|
||||
await core.createTask(db, { projectId: project.id, title: "Поиск стажировок" });
|
||||
chat = await core.ensureProjectChat(db, project.id);
|
||||
});
|
||||
after(teardown);
|
||||
|
||||
describe("PEP-110: analyst in the project chat", () => {
|
||||
test("a question is answered in the same chat, with the project's context and the conversation", async () => {
|
||||
await post("Где я могу увидеть предложения по стажировкам?");
|
||||
assert.equal(await core.analystPending(db, chat.id), true, "«печатает…» until answered");
|
||||
await tick();
|
||||
assert.equal(await core.analystPending(db, chat.id), false);
|
||||
const t = await talk();
|
||||
assert.deepEqual(t.at(-1), ["agent", "Аналитик", "Ответ на: Где я могу увидеть предложения по стажировкам?"]);
|
||||
const c = calls().at(-1)!;
|
||||
assert.equal(c.role, "chat");
|
||||
assert.match(c.prompt, /Интерфейс на русском/, "AGENTS.md");
|
||||
assert.match(c.prompt, /MACH-1 «Поиск стажировок» — в бэклоге/, "stories and their state in plain words");
|
||||
assert.match(c.prompt, /Доска проекта[^\n]*http:\/\/peppa\.test\/p\/MACH/, "where to look");
|
||||
assert.match(c.prompt, /asel: Где я могу увидеть предложения по стажировкам\?/, "the conversation");
|
||||
assert.match(c.prompt, /никогда о технике/, "no technical questions to the PM");
|
||||
});
|
||||
|
||||
test("answered once: another tick does not call the model again", async () => {
|
||||
const n = calls().length;
|
||||
await tick();
|
||||
assert.equal(calls().length, n);
|
||||
});
|
||||
|
||||
test("stories are filed only when the person asks; they skip the intake roles", async () => {
|
||||
setScenario({ chat: { reply: "Предлагаю стори «Страница отзывов». Заводить?", create: [] } });
|
||||
await post("Хочу страницу с отзывами клиентов");
|
||||
await tick();
|
||||
assert.equal((await core.listTasks(db, { projectId: project.id })).length, 1, "nothing filed without a yes");
|
||||
setScenario({});
|
||||
await post("Да, заведи");
|
||||
await tick();
|
||||
const stories = await core.listTasks(db, { projectId: project.id });
|
||||
const filed = stories.find((s) => s.title === "Страница отзывов")!;
|
||||
assert.ok(filed, "the story is in the backlog");
|
||||
assert.match(filed.description!, /Отзывы видны на странице/);
|
||||
assert.equal((await core.getIntakeState(db, filed.id))!.stage, "done", "already formulated — intake skips it");
|
||||
assert.match((await talk()).at(-1)![2], /Завёл в бэклог:\n• MACH-2 «Страница отзывов»/);
|
||||
assert.match(calls().at(-1)!.prompt, /Аналитик: Предлагаю стори «Страница отзывов»\. Заводить\?\nasel: Да, заведи/, "its own earlier words are in the history");
|
||||
});
|
||||
|
||||
test("the answer reaches the person's Telegram (their own bot) — and can be muted", async () => {
|
||||
db.run(sql`update users set telegram_chat_id = 9110 where id = ${pm.id}`);
|
||||
await post("Что сейчас в работе?");
|
||||
await tick();
|
||||
const out = await db.all<{ params: string }>(sql`select params from telegram_outbox where dedupe_key like 'chat:m%' order by id desc limit 1`);
|
||||
const p = JSON.parse(out[0]!.params) as { chat_id: number; text: string };
|
||||
assert.equal(p.chat_id, 9110);
|
||||
assert.match(p.text, /Стажировки<\/b> · Аналитик:\nОтвет на: Что сейчас в работе\?/);
|
||||
assert.match(p.text, /http:\/\/peppa\.test\/chats\/MACH/);
|
||||
});
|
||||
|
||||
test("model failure or a broken answer: one honest note, no retries", async () => {
|
||||
setScenario({ fail: true });
|
||||
await post("Ты тут?");
|
||||
await tick();
|
||||
assert.match((await talk()).at(-1)![2], /Аналитик сейчас не смог ответить/);
|
||||
const n = calls().length;
|
||||
await tick();
|
||||
assert.equal(calls().length, n, "not retried");
|
||||
setScenario({ garbage: true });
|
||||
await post("А теперь?");
|
||||
await tick();
|
||||
assert.match((await talk()).at(-1)![2], /не по форме/);
|
||||
setScenario({});
|
||||
});
|
||||
|
||||
test("no subscription: the analyst says to connect one; commands and story threads are not its business", async () => {
|
||||
const stranger = await core.registerEgovUser(db, { iin: "900101300019", name: "НОВЫЙ ПРОДАКТ" });
|
||||
const p2 = await core.createProject(db, { slug: "mock-achat-2", key: "MACB", name: "Без подписки", giteaOwner: "x", workspacePath: join(TMP, "ws2"), ownerId: stranger.id });
|
||||
const c2 = await core.ensureProjectChat(db, p2.id);
|
||||
await runner.postToChat(db, stranger, { chatId: c2.id, threadKey: null, text: "Привет", via: "web" });
|
||||
await tick();
|
||||
assert.match((await core.discussionMessages(db, c2.id)).at(-1)!.text, /подписке проекта, а она не подключена/);
|
||||
const n = calls().length;
|
||||
await post("/status");
|
||||
await tick();
|
||||
assert.equal(calls().length, n, "a command is not a question to the analyst");
|
||||
});
|
||||
|
||||
test("a message that waited over an hour is not answered late", async () => {
|
||||
await post("Старый вопрос");
|
||||
const n = calls().length;
|
||||
await runner.analystChatTick(db, { wait: true, now: new Date(Date.now() + 61 * 60_000) });
|
||||
assert.equal(calls().length, n, "no model call");
|
||||
assert.equal(await core.analystPending(db, chat.id), false, "and no «печатает…» forever");
|
||||
});
|
||||
|
||||
test("PEPPA_ANALYST_CHAT=off switches the analyst off", async () => {
|
||||
process.env.PEPPA_ANALYST_CHAT = "off";
|
||||
const n = calls().length;
|
||||
await post("Есть кто?");
|
||||
await tick();
|
||||
assert.equal(calls().length, n);
|
||||
delete process.env.PEPPA_ANALYST_CHAT;
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user