Merge main into task/pep-197
This commit is contained in:
commit
d8cedab5f0
@ -25,13 +25,26 @@
|
||||
- Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts).
|
||||
|
||||
## Соглашения
|
||||
- Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:<taskId>`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди.
|
||||
- i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en/<раздел>.ts` и `i18n/kk/<раздел>.ts` (тесты i18n-check и i18n-kk падают без перевода). Ключ-шаблон, кончающийся плейсхолдером, — специфичный. «Peppa FACTORY» не склоняется; в kk окончание через дефис (Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить — фраза вокруг именительного («Жаңа {task}»); `wording(mode,"kk")` отдаёт именительный. Тексты агентам (RULES.md, промпты) говорят «Пеппа» — не трогаем.
|
||||
- Слова по режиму (PEP-123): в вебе «стори»/«раннер» строкой не пишем — `w.task("acc")`, `w.runner()` из `await words()` / `useWords()`, инженерное — под `w.engineer`; тексты без читателя (чаты, Telegram, push, core) — «задача», «агент», «вы».
|
||||
- Экраны «Продакт» (PEP-120/122): вид — чистая функция в core с текстами в одном объекте (`storyProductView`, `core/help-texts.ts` ru/kk/en), инженерное — под «Подробнее» (`?more=1`); тест сверяет ru с «Нельзя» docs/glossary.md.
|
||||
- «Готова к ревью» (с «Принять») — только через `sendReviewCard` (core/review-card.ts): при зелёном `prGate`, иначе дошлёт `reviewCardTick`. «Принять» при конфликте (PEP-127): `accept.pending:<taskId>`, доводит `pendingAcceptTick`; новые пути «готово к ревью»/мержа пропускают стори с `getPendingAccept`. В тестах Gitea «лежит» — `gitea.down = true`.
|
||||
- Подписки (PEP-107/121): ротация claude↔codex без того же провайдера (PEPPA_ROTATE_CROSS=off); займы и предупреждения — в settings (`subscription.loan:…`, `subscription.warned:…`), картина — `poolOverview`. Имя подписки видят только суперадмин и автор — `visibleSubscriptionName`/`publicSubscriptionName`, в вебе `<SubscriptionName>`.
|
||||
- Инструкция подключения к своему Claude/ChatGPT (PEP-135): `/help/connect`, тексты — `core/connect-texts.ts` (`CONNECT_HELP` ru/kk/en одной формы, тест `connect-help.test.ts`); изменились экраны подключения или инструменты удалённого MCP — править её; копирование — `<CopyText>`.
|
||||
- Словарь в сообщениях ядра (PEP-129/137): `pnpm lint` в packages/core|runner|mcp проверяет литералы внутри `m()/tr()/t()/t.n()`; подсказку агенту в `m()` не оборачивать. Запрещённое слово там роняет lint сразу, `--update` не поможет: переписать (ключ = русская строка — поменять в `i18n/en`, `i18n/kk` и тестах) или `glossary-ignore: <почему>` строкой выше (читает инженер); текст человеку мимо словаря переводов — `glossary-user: <почему>`. Разбор словаря — `@peppa/shared/glossary`.
|
||||
- Долгая форма (PEP-142): кнопка — `<PendingButton pendingText>`; создание проекта из веба — `provisionProjectOnce` (общий промис; повтор за 2 мин — `justCreatedProject`), CLI/MCP — `provisionProject`.
|
||||
- Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ).
|
||||
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`.
|
||||
- Служебный текст (PEP-154): текст агента/терминала человеку — через `core/user-text.ts` (`userText`; `stripServiceBlocks` — для слов человека); `raiseSessionQuestion`/`askPm`/`addChatMessage` чистят сами, пусто → PeppaError, исходник — `questionDetails` (инженер/суперадмин). Текст исключения владельцу не слать: `platformFailure` даёт строку только для PeppaError, иначе null (ушло суперадмину и в учёт ошибок). В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0).
|
||||
- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`. Конец хода агента вопроса не создаёт: в тестах жди статус сессии `idle`, а не `waitQuestion(sid, "attention")`.
|
||||
- Формат сообщения агента (PEP-152): сообщение агента человеку — через `admitAgentMessage` + `renderMain` (core/agent-message.ts): в тексте — основная часть (слова агента в `asIs`), техника — `details` (`messageDetails`), экран режет `splitForDisplay`. Суть с файлом, веткой, командой, «PR #N», статусом из кода, словом «Нельзя» — отказ.
|
||||
- Чужой текст в сообщениях (PEP-139/140): слова человека/модели, название задачи/проекта, логин, варианты агента, причину извне подставляй в `m()` как `asIs(…)` (shared/i18n) — перевод их не трогает; фразы самой фабрики (`PeppaError`, причина гейта) не помечай. Вопрос агента = `questionIsFreeText`, текст переводящему читателю — `questionText(q)`; MCP, CLI, агенту и сравнение текста в тестах — `stripAsIs`.
|
||||
- Вложения (PEP-159): файл грузится отдельно (`POST /api/attachments`, не server action — предел 1 МБ) и привязывается действием через `linkAttachments`; новое место с файлами — `<AttachField projectId target>` в форме и `<Attachments files>` для показа; типы только по содержимому (`sniffAttachment`). Агент читает файлы из `.peppa/attachments/` (папка сама в gitignore).
|
||||
- Переписка проекта (PEP-155): `projectThreadList`/`threadGroup`/`plainLine` (core/chat-threads.ts); поиск кириллицы — в JS.
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; задачу из очереди ёмкости убирай `moveTask(backlog)`, иначе её подхватит тик соседнего теста. Конец хода агента вопроса не создаёт — жди статус сессии `idle`. Сообщения суперадмина — `superadmin()` из helpers.ts. Текст из `chat_messages` сравнивай через `stripAsIs`.
|
||||
- Узкие места: запуск/перенос раннера — `pickSubscription`/`rotationCandidate`; агент, модель, сообщение человеку — `startRunner`/`resumeSession`, `claudePrint`, `deliverToUser` или с `isProjectPaused`; список проектов — `listProjects(db)`/`userProjectIds`, прямой `from(projects)` — с `isNull(projects.deletedAt)`; действие веба, которое запускает/убивает агентов, — через runnerCall.
|
||||
- Сообщения человеку: вопрос — `askPm`/`raiseSessionQuestion` с `msgType` и вариантами; «готово» — только `sendReviewCard`; ход работы/блокер — события; сбой платформы — `platformDelay`/`sessionDelay`, исключение — `platformFailure`; тип читать `questionType`/`needsPerson`, не `kind`. Текст агента — `admitAgentMessage` + `renderMain`, техника в `details`.
|
||||
- Перевод: ключ = русская строка в `t()`/`m()` + `i18n/en` и `i18n/kk`. Чужие слова (человек, модель, название, логин) — в `asIs()`; фразы фабрики не помечать. Текст ИИ-роли — не через localizeText: постоянная строка — `m()` + `ROLE_MESSAGE_KEYS`. kk: «Peppa FACTORY-нің», к {плейсхолдеру} окончание не клеить.
|
||||
- Слова: в вебе «стори»/«раннер» строкой не писать — `w.task(…)`, `w.runner()`; инженерное — под `w.engineer`; тексты без читателя (чаты, Telegram, core) — «задача», «агент», «вы»; слово «команда» про людей запрещено. Промпты агентам говорят «Пеппа».
|
||||
- Словарь в packages/core|runner|mcp: литералы в `m()/tr()/t()` проверяются сразу, `--update` не поможет — переписать или `glossary-ignore: <почему>`; текст человеку мимо переводов — `glossary-user: <почему>`. Подсказку агенту в `m()` не оборачивать.
|
||||
- Файлы от пользователя — route handler с multipart, не server action (предел 1 МБ); тип — только по содержимому. Долгая форма — `<PendingButton pendingText>`.
|
||||
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `INTENT_TEXT`).
|
||||
|
||||
## Решения
|
||||
|
||||
@ -49,6 +49,7 @@ import {
|
||||
} from "@peppa/core";
|
||||
import { checkRuns } from "@peppa/db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { getTeamMatch, matchLine } from "@peppa/core";
|
||||
import { PanelSection } from "@/components/ActivityAside";
|
||||
import { Hidden, SessionCard } from "@/components/cards";
|
||||
import { ago, Disclosure, Flash, PageHeader, Section, StatusBadge } from "@/components/common";
|
||||
@ -103,6 +104,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
const tabHref = (id: StoryTab) => `/t/${ref.key}?tab=${id}`;
|
||||
// PEP-120: «Продакт» sees one plain card; the rest of the page opens by «Подробнее» (?more=1, a tab or the edit form).
|
||||
const engineer = (await uiMode()) === "engineer";
|
||||
// PEP-183: was the story given to a specialist of the team (engineer only).
|
||||
const teamMatchText = engineer ? matchLine(await getTeamMatch(db, task.id)) : null;
|
||||
const detailsOpen = engineer || !!(sp.more || sp.tab || sp.edit);
|
||||
const back = engineer || sp.tab ? tabHref(tab) : detailsOpen ? `/t/${ref.key}?more=1` : `/t/${ref.key}`;
|
||||
const preview = await reviewPreview(db, ref);
|
||||
@ -433,6 +436,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
|
||||
>
|
||||
{engineer && (
|
||||
<span className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{teamMatchText && <span className="text-xs">{t.text(teamMatchText)}</span>}
|
||||
{task.openspecChange ? (
|
||||
<span className="font-mono text-xs">
|
||||
{task.openspecChange}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
"use server";
|
||||
|
||||
import { createAgent, isSuperadmin, PeppaError, setTeamChaseHidden, updateAgent } from "@peppa/core";
|
||||
import { createAgent, isSuperadmin, PeppaError, setTeamChaseHidden, setTeamSettings, updateAgent } from "@peppa/core";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { asWebActor, requireUser } from "@/lib/auth";
|
||||
@ -45,6 +45,14 @@ export async function toggleAgentAction(f: FormData) {
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-183: how long a story waits for its busy specialist. */
|
||||
export async function saveTeamWaitAction(f: FormData) {
|
||||
await run(async () => {
|
||||
await setTeamSettings(db, { waitMin: Number(f.get("waitMin")) });
|
||||
return "/team?saved=wait";
|
||||
});
|
||||
}
|
||||
|
||||
/** PEP-179: «Скрыть» / «Показать» on the team picture — the user's own choice, anyone may. */
|
||||
export async function setTeamChaseHiddenAction(hidden: boolean): Promise<void> {
|
||||
const user = await requireUser();
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import { Plus } from "lucide-react";
|
||||
import { AGENT_CHARACTER_MAX, isSuperadmin, listAgents, teamChaseHidden, teamChaseView } from "@peppa/core";
|
||||
import { AGENT_CHARACTER_MAX, getTeamSettings, isSuperadmin, listAgents, teamChaseHidden, teamChaseView } from "@peppa/core";
|
||||
import { AgentBadge } from "@/components/AgentBadge";
|
||||
import { Empty, Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
@ -14,7 +14,7 @@ import { requireUser, words } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { getT } from "@/lib/i18n";
|
||||
import { acceptInbox } from "@/lib/queries";
|
||||
import { addAgentAction, saveAgentAction, toggleAgentAction } from "./actions";
|
||||
import { addAgentAction, saveAgentAction, saveTeamWaitAction, toggleAgentAction } from "./actions";
|
||||
|
||||
export async function generateMetadata() {
|
||||
const t = await getT();
|
||||
@ -27,12 +27,13 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
|
||||
const t = await getT();
|
||||
const { error, saved } = await searchParams;
|
||||
const w = await words();
|
||||
const [team, admin, chase, chaseHidden, awaiting] = await Promise.all([listAgents(db), isSuperadmin(db, user), teamChaseView(db, user), teamChaseHidden(db, user.id), acceptInbox(user.id)]);
|
||||
const [team, admin, chase, chaseHidden, awaiting, teamSettings] = await Promise.all([listAgents(db), isSuperadmin(db, user), teamChaseView(db, user), teamChaseHidden(db, user.id), acceptInbox(user.id), getTeamSettings(db)]);
|
||||
return (
|
||||
<Workspace>
|
||||
<div className="max-w-3xl">
|
||||
<Flash error={error} />
|
||||
{saved && <Notice>{t("Сохранено — агент получит новый характер при следующем запуске или перезапуске.")}</Notice>}
|
||||
{saved === "wait" && <Notice>{t("Порог ожидания сохранён")}</Notice>}
|
||||
{saved && saved !== "wait" && <Notice>{t("Сохранено — агент получит новый характер при следующем запуске или перезапуске.")}</Notice>}
|
||||
<PageHeader title={t("Команда")}>
|
||||
{t("Это ИИ-агенты, не люди: у каждого своя кличка и характер, одна команда на все проекты. Свободный агент берёт {task} и ведёт её до конца; если все заняты — в команде появляется новый.", { task: w.task("acc") })}
|
||||
{w.engineer ? t(" Характер добавляется к промпту агента поверх правил Peppa FACTORY и AGENTS.md проекта.") : t(" Характер влияет на то, как агент работает и пишет вам.")}
|
||||
@ -54,6 +55,18 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{admin && (
|
||||
<Card>
|
||||
<form action={saveTeamWaitAction} className="flex flex-wrap items-end gap-2">
|
||||
<Label className="min-w-64 flex-1">
|
||||
{t("Сколько минут {task} ждёт занятого специалиста, прежде чем её возьмёт другой агент", { task: w.task() })}
|
||||
<Input name="waitMin" type="number" min={0} max={1440} defaultValue={teamSettings.waitMin} className="max-w-32" />
|
||||
</Label>
|
||||
<Button size="sm" variant="default">{t("Сохранить")}</Button>
|
||||
</form>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Section title={t("Агенты")} count={team.length}>
|
||||
{team.length === 0 && <Empty>{t("Пока никого: первый агент появится, когда {task} уйдёт «В работу».", { task: w.task() })}</Empty>}
|
||||
{team.map((a) => (
|
||||
@ -61,6 +74,8 @@ export default async function Team({ searchParams }: { searchParams: Promise<{ e
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<AgentBadge name={a.name} large />
|
||||
{a.busy > 0 ? <Badge variant="info">{t("работает")}{a.busy > 1 ? ` ×${a.busy}` : ""}</Badge> : <Badge variant="muted">{t("свободен")}</Badge>}
|
||||
{a.specialist && <Badge variant="ok">{t("специалист")}</Badge>}
|
||||
{a.specialist && <span className="text-xs text-muted-foreground">{t("по профилю: {n}", { n: a.profileTasks })}</span>}
|
||||
{a.disabledAt && <Badge variant="danger">{t("не в команде")}</Badge>}
|
||||
<span className="ml-auto text-xs text-muted-foreground">{t("запусков: {n}", { n: a.runs })}</span>
|
||||
</div>
|
||||
|
||||
6
openspec/changes/pep-183-specialist-matching/design.md
Normal file
6
openspec/changes/pep-183-specialist-matching/design.md
Normal file
@ -0,0 +1,6 @@
|
||||
## Решения
|
||||
- Без миграции: результат — `settings` `team.match:<taskId>` (`core/team-match.ts`), порог — `platform.team` `{waitMin}` (по умолчанию 30).
|
||||
- Запрос к модели — `runner/team-match.ts` (`claudePrint`, `PEPPA_TEAM_MATCH_MODEL`=haiku, `PEPPA_TEAM_BIN`); вызывается из `launch` перед `ensureSessionAgent` и из диспетчера. Сбой = «никто» (`failed`), событие журнала `team_match_failed`, владельцу ничего.
|
||||
- `ensureSessionAgent` (синхронная транзакция): прежний агент задачи → свободный подходящий специалист → свободный универсал, дольше всех отдыхавший → свободный специалист, если в бэклоге нет задач его профиля → новый агент. Ёмкость пула (PEP-182) проверяется раньше, выбор подписки не затрагивается.
|
||||
- Ожидание занятого специалиста — в диспетчере (`readyBacklog` → `specialistHold`, `waitSince` в записи); ручное «В работу» не ждёт.
|
||||
- Стёртая специализация делает агента универсалом: проверяется при каждой выдаче.
|
||||
8
openspec/changes/pep-183-specialist-matching/proposal.md
Normal file
8
openspec/changes/pep-183-specialist-matching/proposal.md
Normal file
@ -0,0 +1,8 @@
|
||||
## Why
|
||||
Специализация агента в «Команде» только дописывалась в промпт; задачу получал любой свободный агент. Нужно, чтобы задачи по профилю доставались специалистам.
|
||||
|
||||
## What Changes
|
||||
- Специалист — агент с заполненным «Характером и специализацией»; остальные — универсалы.
|
||||
- При первой выдаче задачи короткий запрос к haiku на подписке проекта решает, подходит ли она специалисту; результат хранится у задачи.
|
||||
- Порядок выбора агента; ожидание занятого специалиста (порог 30 мин, настройка суперадмина).
|
||||
- Пометки: на странице задачи («Инженер»), в «Команде» («специалист», число задач по профилю).
|
||||
@ -0,0 +1,18 @@
|
||||
## ADDED Requirements
|
||||
### Requirement: Задачи по профилю специалистам
|
||||
Система SHALL отдавать задачу, впервые уходящую в работу, подходящему свободному специалисту; решение принимается один раз коротким запросом к самой дешёвой модели и сохраняется у задачи.
|
||||
|
||||
#### Scenario: Задача про безопасность
|
||||
- **GIVEN** специалист «Страж ИБ» свободен и задача про безопасность
|
||||
- **WHEN** задача уходит в работу
|
||||
- **THEN** её ведёт «Страж ИБ»
|
||||
|
||||
#### Scenario: Специалист занят
|
||||
- **GIVEN** подходящий специалист занят
|
||||
- **WHEN** диспетчер выбирает задачи
|
||||
- **THEN** задача ждёт до порога (30 минут по умолчанию), затем уходит универсалу
|
||||
|
||||
#### Scenario: Запрос к модели не удался
|
||||
- **GIVEN** запрос к модели завершился ошибкой
|
||||
- **WHEN** задача уходит в работу
|
||||
- **THEN** её берёт универсал, пользователь ошибки не видит, сбой записан в журнал
|
||||
4
openspec/changes/pep-183-specialist-matching/tasks.md
Normal file
4
openspec/changes/pep-183-specialist-matching/tasks.md
Normal file
@ -0,0 +1,4 @@
|
||||
- [x] 1. core/team-match.ts, выбор агента в ensureSessionAgent
|
||||
- [x] 2. runner/team-match.ts, ожидание в диспетчере, mock-team
|
||||
- [x] 3. Веб: страница задачи, «Команда» (пометка, порог), тексты ru/kk/en
|
||||
- [x] 4. Тесты team-match.test.ts
|
||||
@ -32,6 +32,7 @@ export * from "./ci.ts";
|
||||
export * from "./egov.ts";
|
||||
export * from "./google.ts";
|
||||
export * from "./team.ts";
|
||||
export * from "./team-match.ts";
|
||||
export * from "./team-chase.ts";
|
||||
export * from "./progress.ts";
|
||||
export * from "./platform-dashboard.ts";
|
||||
|
||||
127
packages/core/src/team-match.ts
Normal file
127
packages/core/src/team-match.ts
Normal file
@ -0,0 +1,127 @@
|
||||
// PEP-183: specialists get stories of their profile. A specialist is an agent whose «Характер и
|
||||
// специализация» is filled in; the rest are generalists. Whether a story fits a specialist is
|
||||
// decided once by a short model call (runner/team-match.ts) and kept here in `settings`
|
||||
// (`team.match:<taskId>`); `ensureSessionAgent` (team.ts) and the dispatcher read it.
|
||||
import { asIs, m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, sessions, settings, type Db } from "@peppa/db";
|
||||
import { and, eq, isNull, like, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { getSetting, setSetting } from "./settings.ts";
|
||||
|
||||
export interface TeamMatch {
|
||||
/** The specialist the story fits; null — nobody. */
|
||||
agentId: number | null;
|
||||
name: string | null;
|
||||
/** One phrase: why (or why nobody). */
|
||||
reason: string;
|
||||
at: number;
|
||||
/** The model call failed — treated as «nobody», only the journal knows. */
|
||||
failed?: boolean;
|
||||
/** First time the dispatcher held the story for a busy specialist (ms). */
|
||||
waitSince?: number;
|
||||
/** The story really went to this specialist by profile. */
|
||||
given?: boolean;
|
||||
}
|
||||
|
||||
export interface TeamSettings {
|
||||
/** How long a story waits for its busy specialist before a generalist takes it. */
|
||||
waitMin: number;
|
||||
}
|
||||
export const DEFAULT_TEAM_WAIT_MIN = 30;
|
||||
export const matchKey = (taskId: number) => `team.match:${taskId}`;
|
||||
|
||||
export async function getTeamSettings(db: Db): Promise<TeamSettings> {
|
||||
const v = await getSetting<Partial<TeamSettings>>(db, "platform.team");
|
||||
const n = Number(v?.waitMin);
|
||||
return { waitMin: Number.isFinite(n) && n >= 0 ? n : DEFAULT_TEAM_WAIT_MIN };
|
||||
}
|
||||
export async function setTeamSettings(db: Db, patch: Partial<TeamSettings>): Promise<TeamSettings> {
|
||||
const cur = await getTeamSettings(db);
|
||||
const n = patch.waitMin === undefined ? cur.waitMin : Math.round(Number(patch.waitMin));
|
||||
if (!Number.isFinite(n) || n < 0 || n > 24 * 60) throw new PeppaError(tr("Ожидание: от 0 до 1440 минут"));
|
||||
const next = { waitMin: n };
|
||||
await setSetting(db, "platform.team", next);
|
||||
return next;
|
||||
}
|
||||
|
||||
export const isSpecialist = (a: { character: string; disabledAt: Date | null }) => !a.disabledAt && a.character.trim() !== "";
|
||||
|
||||
/** Enabled agents with a filled-in specialization. */
|
||||
export async function listSpecialists(db: Db) {
|
||||
return (await db.select().from(agents).where(isNull(agents.disabledAt))).filter(isSpecialist);
|
||||
}
|
||||
|
||||
export const getTeamMatch = (db: Db, taskId: number) => getSetting<TeamMatch>(db, matchKey(taskId));
|
||||
export const setTeamMatch = (db: Db, taskId: number, v: TeamMatch) => setSetting(db, matchKey(taskId), v);
|
||||
|
||||
/** Is the agent working in a live runner right now. */
|
||||
export async function agentIsBusy(db: Db, agentId: number): Promise<boolean> {
|
||||
const [r] = await db
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(sessions)
|
||||
.where(and(eq(sessions.agentId, agentId), notInArray(sessions.status, ["done", "failed"])));
|
||||
return Number(r?.n ?? 0) > 0;
|
||||
}
|
||||
|
||||
export function matchPrompt(o: { title: string; description: string; epic: string | null; specialists: Array<{ name: string; character: string }> }): string {
|
||||
return [
|
||||
"Ты распределяешь задачи между агентами команды. Реши, подходит ли задача кому-то из специалистов по его специализации.",
|
||||
"Отвечай одной строкой JSON без пояснений: {\"agent\": \"<кличка специалиста или null>\", \"reason\": \"<одна фраза, почему>\"}.",
|
||||
"Если задача не про профиль ни одного специалиста — agent: null. Не придумывай клички, бери только из списка.",
|
||||
"",
|
||||
"Специалисты:",
|
||||
...o.specialists.map((s) => `- ${s.name}: ${s.character.trim().replace(/\s+/g, " ").slice(0, 600)}`),
|
||||
"",
|
||||
`Задача: ${o.title}`,
|
||||
o.epic ? `Эпик: ${o.epic}` : "",
|
||||
"Описание:",
|
||||
o.description.slice(0, 4000),
|
||||
].filter((l) => l !== "").join("\n");
|
||||
}
|
||||
|
||||
/** The model's answer → the chosen specialist (by nickname, compared in JS) or nobody. Null — not in the form. */
|
||||
export function parseMatch(text: string, specialists: Array<{ id: number; name: string }>): Pick<TeamMatch, "agentId" | "name" | "reason"> | null {
|
||||
const raw = /\{[\s\S]*\}/.exec(text)?.[0];
|
||||
if (!raw) return null;
|
||||
let j: { agent?: unknown; reason?: unknown };
|
||||
try {
|
||||
j = JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const reason = typeof j.reason === "string" ? j.reason.trim().slice(0, 300) : "";
|
||||
if (j.agent === null || j.agent === undefined || (typeof j.agent === "string" && /^(никто|null|none|)$/i.test(j.agent.trim()))) {
|
||||
return { agentId: null, name: null, reason };
|
||||
}
|
||||
if (typeof j.agent !== "string") return null;
|
||||
const want = j.agent.trim().toLowerCase();
|
||||
const hit = specialists.find((s) => s.name.toLowerCase() === want);
|
||||
return hit ? { agentId: hit.id, name: hit.name, reason } : { agentId: null, name: null, reason };
|
||||
}
|
||||
|
||||
/** Stories of the profile of this specialist still in the backlog (queue). */
|
||||
export async function queuedForSpecialist(db: Db, agentId: number): Promise<number> {
|
||||
const rows = await db
|
||||
.select({ key: settings.key, v: settings.value, status: sql<string>`(select status from tasks t where t.id = cast(substr(${settings.key}, 12) as integer))` })
|
||||
.from(settings)
|
||||
.where(and(like(settings.key, "team.match:%"), sql`json_extract(${settings.value}, '$.agentId') = ${agentId}`));
|
||||
return rows.filter((r) => r.status === "backlog").length;
|
||||
}
|
||||
|
||||
/** How many stories went to the specialist by profile. */
|
||||
export async function profileTaskCounts(db: Db): Promise<Map<number, number>> {
|
||||
const rows = await db
|
||||
.select({ id: sql<number>`json_extract(${settings.value}, '$.agentId')`, n: sql<number>`count(*)` })
|
||||
.from(settings)
|
||||
.where(and(like(settings.key, "team.match:%"), sql`json_extract(${settings.value}, '$.given') = 1`))
|
||||
.groupBy(sql`json_extract(${settings.value}, '$.agentId')`);
|
||||
return new Map(rows.map((r) => [Number(r.id), Number(r.n)]));
|
||||
}
|
||||
|
||||
/** «Отдана специалисту Страж ИБ: …» / «Специалиста не нашлось» — for the story page (engineer). */
|
||||
export function matchLine(match: TeamMatch | null): string | null {
|
||||
if (!match || match.failed) return match ? tr("Специалиста не нашлось") : null;
|
||||
if (match.agentId === null) return tr("Специалиста не нашлось");
|
||||
const v = { name: asIs(match.name), reason: asIs(match.reason) };
|
||||
return match.given ? tr("Отдана специалисту {name}: {reason}", v) : tr("Подходит специалисту {name}: {reason}", v);
|
||||
}
|
||||
@ -3,9 +3,10 @@
|
||||
// and across the story's later runners; the PM gives each a character (markdown) that goes into
|
||||
// the agent's prompt on top of the shared rules and the project's AGENTS.md.
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { agents, sessions, type Db } from "@peppa/db";
|
||||
import { agents, sessions, settings, tasks, type Db } from "@peppa/db";
|
||||
import { and, asc, desc, eq, isNotNull, isNull, notInArray, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { isSpecialist, matchKey, profileTaskCounts, type TeamMatch } from "./team-match.ts";
|
||||
import { NoCapacityError, teamHasRoomSync } from "./capacity.ts";
|
||||
|
||||
export type Agent = typeof agents.$inferSelect;
|
||||
@ -27,6 +28,10 @@ export interface AgentView extends Agent {
|
||||
busy: number;
|
||||
/** All runners it has ever worked in. */
|
||||
runs: number;
|
||||
/** PEP-183: «Характер и специализация» is filled in. */
|
||||
specialist: boolean;
|
||||
/** PEP-183: stories that came to it by profile. */
|
||||
profileTasks: number;
|
||||
}
|
||||
|
||||
export async function listAgents(db: Db): Promise<AgentView[]> {
|
||||
@ -40,7 +45,8 @@ export async function listAgents(db: Db): Promise<AgentView[]> {
|
||||
})
|
||||
.from(agents)
|
||||
.orderBy(asc(agents.id));
|
||||
return rows.map((r) => ({ ...r.a, busy: Number(r.busy), runs: Number(r.runs) }));
|
||||
const counts = await profileTaskCounts(db);
|
||||
return rows.map((r) => ({ ...r.a, busy: Number(r.busy), runs: Number(r.runs), specialist: isSpecialist(r.a), profileTasks: counts.get(r.a.id) ?? 0 }));
|
||||
}
|
||||
|
||||
export async function getAgent(db: Db, id: number): Promise<Agent | null> {
|
||||
@ -120,15 +126,29 @@ export async function ensureSessionAgent(db: Db, sessionId: number): Promise<Age
|
||||
.get()?.a;
|
||||
}
|
||||
if (!agent) {
|
||||
const busy = tx.select({ id: sessions.agentId }).from(sessions).where(and(isNotNull(sessions.agentId), notInArray(sessions.status, [...FINISHED]))).all().map((r) => r.id!);
|
||||
agent = tx
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(and(isNull(agents.disabledAt), busy.length ? notInArray(agents.id, busy) : undefined))
|
||||
// The one that rested longest goes first, so the team rotates.
|
||||
.orderBy(sql`(select coalesce(max(s.id), 0) from sessions s where s.agent_id = "agents"."id")`, asc(agents.id))
|
||||
.limit(1)
|
||||
.get();
|
||||
const busy = new Set(tx.select({ id: sessions.agentId }).from(sessions).where(and(isNotNull(sessions.agentId), notInArray(sessions.status, [...FINISHED]))).all().map((r) => r.id!));
|
||||
// The one that rested longest goes first, so the team rotates.
|
||||
const rest = (a: Agent) => tx.select({ n: sql<number>`coalesce(max(${sessions.id}), 0)` }).from(sessions).where(eq(sessions.agentId, a.id)).get()?.n ?? 0;
|
||||
const free = tx.select().from(agents).where(isNull(agents.disabledAt)).orderBy(asc(agents.id)).all().filter((a) => !busy.has(a.id)).map((a) => ({ a, rest: rest(a) })).sort((x, y) => x.rest - y.rest || x.a.id - y.a.id).map((x) => x.a);
|
||||
const match = s.taskId ? (tx.select().from(settings).where(eq(settings.key, matchKey(s.taskId))).get()?.value as TeamMatch | undefined) : undefined;
|
||||
// PEP-183: a story that fits a specialist goes to him when he is free (a busy one is waited for
|
||||
// by the dispatcher; a story that did not wait goes on to a generalist); the specialization
|
||||
// erased since means a generalist from now on.
|
||||
const fit = match?.agentId ? free.find((a) => a.id === match.agentId && isSpecialist(a)) : undefined;
|
||||
if (fit) {
|
||||
agent = fit;
|
||||
tx.update(settings).set({ value: { ...match, given: true }, updatedAt: new Date() }).where(eq(settings.key, matchKey(s.taskId!))).run();
|
||||
} else {
|
||||
agent = free.find((a) => !isSpecialist(a));
|
||||
// No free generalist: a free specialist, unless stories of his profile are in the queue.
|
||||
if (!agent) {
|
||||
const wanted = new Set(
|
||||
tx.select({ key: settings.key, v: settings.value, status: tasks.status }).from(settings).innerJoin(tasks, sql`${tasks.id} = cast(substr(${settings.key}, 12) as integer)`).where(sql`${settings.key} like 'team.match:%'`).all()
|
||||
.filter((r) => r.status === "backlog").map((r) => (r.v as TeamMatch).agentId),
|
||||
);
|
||||
agent = free.find((a) => isSpecialist(a) && !wanted.has(a.id));
|
||||
}
|
||||
}
|
||||
}
|
||||
// PEP-182: the team grows by itself only while the capacity allows one more runner.
|
||||
if (!agent && !teamHasRoomSync(tx, s)) return null;
|
||||
|
||||
@ -59,6 +59,7 @@ import { acceptTask, moveTask, requestRebase } from "./flow.ts";
|
||||
import { autoMergeTask } from "./ci-feedback.ts";
|
||||
import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts";
|
||||
import { syncWorkspace } from "./workspace-sync.ts";
|
||||
import { specialistHold } from "./team-match.ts";
|
||||
import { startDelay } from "./platform-delays.ts";
|
||||
import { pipelineGuard } from "./pipeline-guard.ts";
|
||||
|
||||
@ -364,7 +365,10 @@ export async function readyBacklog<T extends Task = Task & { key: string }>(db:
|
||||
// PEP-115: nor does a story whose fresh comment the analyst is still working into the description.
|
||||
const commented = await pendingRefinements(db, { projectId });
|
||||
// PEP-197: «Предложено» — stories of agents the owner has not decided on — are not taken.
|
||||
const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id) && !t.proposed);
|
||||
const open = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id) && !t.proposed);
|
||||
// PEP-183: a story that fits a busy specialist waits for him (up to the platform's threshold).
|
||||
const held = await specialistHold(db, open);
|
||||
const ready = open.filter((t) => !held.has(t.id));
|
||||
// PEP-103: fixing errors comes first — bug stories, then the rest, each in board order.
|
||||
const bugs = await bugTaskIds(db, projectId);
|
||||
// PEP-145: before everything — the system story that makes the product open by a link.
|
||||
|
||||
@ -39,6 +39,7 @@ export * from "./terminal.ts";
|
||||
export * from "./claude-print.ts";
|
||||
export * from "./reviewer.ts";
|
||||
export * from "./autonomy.ts";
|
||||
export * from "./team-match.ts";
|
||||
export * from "./accept-pending.ts";
|
||||
export * from "./review-card.ts";
|
||||
export * from "./workspace-sync.ts";
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { ensureTaskMatch } from "./team-match.ts";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { chmodSync, existsSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
@ -307,6 +308,7 @@ async function launch(
|
||||
const memDir = s.host ? (await db.select().from(projects).where(eq(projects.id, s.projectId)))[0]?.workspacePath ?? cwd : cwd;
|
||||
const memory = await memoryContext(db, s.projectId, memDir).catch(() => "");
|
||||
// PEP-75: the runner's persona (assigned on the first launch) — name and character in the prompt.
|
||||
if (s.taskId && !s.agentId) await ensureTaskMatch(db, s.taskId).catch(() => null); // PEP-183
|
||||
const persona = await ensureSessionAgent(db, s.id).catch(() => null);
|
||||
// PEP-159: files attached to the story and its discussion lie in the working copy for the agent.
|
||||
if (s.taskId && !s.host) await copyTaskAttachments(db, s.taskId, cwd).catch(() => []);
|
||||
|
||||
64
packages/runner/src/team-match.ts
Normal file
64
packages/runner/src/team-match.ts
Normal file
@ -0,0 +1,64 @@
|
||||
// PEP-183: does a story fit one of the team's specialists — one short model call (the cheapest
|
||||
// model, the project's pool subscription), the answer kept with the story and never recomputed.
|
||||
// A failed call = «nobody» (the story goes to a generalist) and a line in the journal only.
|
||||
import { agents, goals, sessions, tasks, type Db } from "@peppa/db";
|
||||
import { getTeamMatch, getTeamSettings, agentIsBusy, isSpecialist, listSpecialists, logEvent, matchPrompt, parseMatch, setTeamMatch, type TeamMatch } from "@peppa/core";
|
||||
import { and, eq, isNotNull } from "drizzle-orm";
|
||||
import { claudePrint } from "./claude-print.ts";
|
||||
|
||||
/** The story's match; computed on the first call (when it is about to go to an agent for the first time). */
|
||||
export async function ensureTaskMatch(db: Db, taskId: number): Promise<TeamMatch | null> {
|
||||
const known = await getTeamMatch(db, taskId);
|
||||
if (known) return known;
|
||||
const specialists = await listSpecialists(db);
|
||||
if (!specialists.length) return null;
|
||||
// The story already had an agent: the same one goes on, nothing to decide.
|
||||
const [prior] = await db.select({ id: sessions.id }).from(sessions).where(and(eq(sessions.taskId, taskId), isNotNull(sessions.agentId))).limit(1);
|
||||
if (prior) return null;
|
||||
const [t] = await db.select().from(tasks).where(eq(tasks.id, taskId));
|
||||
if (!t) return null;
|
||||
const [epic] = t.goalId ? await db.select({ title: goals.title }).from(goals).where(eq(goals.id, t.goalId)) : [];
|
||||
const fail = async (error: string): Promise<TeamMatch> => {
|
||||
const v: TeamMatch = { agentId: null, name: null, reason: "", at: Date.now(), failed: true };
|
||||
await setTeamMatch(db, taskId, v);
|
||||
await logEvent(db, { projectId: t.projectId, taskId, type: "team_match_failed", payload: { error } }).catch(() => {});
|
||||
return v;
|
||||
};
|
||||
try {
|
||||
const out = await claudePrint(db, { id: t.projectId }, {
|
||||
bin: process.env.PEPPA_TEAM_BIN ?? process.env.PEPPA_INTAKE_BIN ?? "claude",
|
||||
model: process.env.PEPPA_TEAM_MATCH_MODEL ?? "haiku",
|
||||
timeoutMs: Number(process.env.PEPPA_TEAM_MATCH_TIMEOUT_MS) || 60_000,
|
||||
who: "подборщик специалиста",
|
||||
prompt: matchPrompt({ title: t.title, description: t.description ?? "", epic: epic?.title ?? null, specialists: specialists.map((s) => ({ name: s.name, character: s.character })) }),
|
||||
});
|
||||
if (!out.ok) return await fail(out.error);
|
||||
const parsed = parseMatch(out.text, specialists);
|
||||
if (!parsed) return await fail("ответ не по форме");
|
||||
const v: TeamMatch = { ...parsed, at: Date.now() };
|
||||
await setTeamMatch(db, taskId, v);
|
||||
return v;
|
||||
} catch (e) {
|
||||
return await fail((e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stories the dispatcher must hold back: they fit a specialist who is busy right now and have
|
||||
* not waited longer than the platform's threshold. Not a failure — nobody is told.
|
||||
*/
|
||||
export async function specialistHold<T extends { id: number }>(db: Db, list: T[], now = new Date()): Promise<Set<number>> {
|
||||
const held = new Set<number>();
|
||||
if (!list.length || !(await listSpecialists(db)).length) return held;
|
||||
const { waitMin } = await getTeamSettings(db);
|
||||
for (const t of list) {
|
||||
const match = await ensureTaskMatch(db, t.id);
|
||||
if (!match?.agentId) continue;
|
||||
const [a] = await db.select().from(agents).where(eq(agents.id, match.agentId));
|
||||
if (!a || !isSpecialist(a) || !(await agentIsBusy(db, a.id))) continue;
|
||||
const since = match.waitSince ?? now.getTime();
|
||||
if (!match.waitSince) await setTeamMatch(db, t.id, { ...match, waitSince: since });
|
||||
if (now.getTime() - since < waitMin * 60_000) held.add(t.id);
|
||||
}
|
||||
return held;
|
||||
}
|
||||
@ -346,6 +346,14 @@ export const admin: Dict = {
|
||||
"открыть": "open",
|
||||
"с {date}": "since {date}",
|
||||
"пароль": "password",
|
||||
"Специалиста не нашлось": "No specialist found",
|
||||
"Подходит специалисту {name}: {reason}": "Fits specialist {name}: {reason}",
|
||||
"Отдана специалисту {name}: {reason}": "Given to specialist {name}: {reason}",
|
||||
"специалист": "specialist",
|
||||
"по профилю: {n}": "by profile: {n}",
|
||||
"Сколько минут {task} ждёт занятого специалиста, прежде чем её возьмёт другой агент": "How many minutes a {task} waits for a busy specialist before another agent takes it",
|
||||
"Порог ожидания сохранён": "Waiting time saved",
|
||||
"Ожидание: от 0 до 1440 минут": "Waiting time: from 0 to 1440 minutes",
|
||||
"Почта аккаунта Claude — по желанию": "Claude account e-mail — optional",
|
||||
"Почта аккаунта Claude": "Claude account e-mail",
|
||||
"Почта аккаунта": "Account e-mail",
|
||||
|
||||
@ -306,6 +306,14 @@ export const admin: Dict = {
|
||||
"открыть": "ашу",
|
||||
"с {date}": "{date} бастап",
|
||||
"пароль": "құпиясөз",
|
||||
"Специалиста не нашлось": "Маман табылмады",
|
||||
"Подходит специалисту {name}: {reason}": "{name} маманына сәйкес келеді: {reason}",
|
||||
"Отдана специалисту {name}: {reason}": "{name} маманына берілді: {reason}",
|
||||
"специалист": "маман",
|
||||
"по профилю: {n}": "бейін бойынша: {n}",
|
||||
"Сколько минут {task} ждёт занятого специалиста, прежде чем её возьмёт другой агент": "Бос емес маманды күту уақыты (минут): содан кейін {task} басқа агентке беріледі",
|
||||
"Порог ожидания сохранён": "Күту уақыты сақталды",
|
||||
"Ожидание: от 0 до 1440 минут": "Күту: 0-ден 1440 минутқа дейін",
|
||||
"Почта аккаунта Claude — по желанию": "Claude аккаунтының поштасы — қаласаңыз",
|
||||
"Почта аккаунта Claude": "Claude аккаунтының поштасы",
|
||||
"Почта аккаунта": "Аккаунт поштасы",
|
||||
|
||||
3
packages/testkit/bin/mock-team
Executable file
3
packages/testkit/bin/mock-team
Executable file
@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env bash
|
||||
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-team.ts" "$@"
|
||||
26
packages/testkit/src/mock-team.ts
Normal file
26
packages/testkit/src/mock-team.ts
Normal file
@ -0,0 +1,26 @@
|
||||
// mock-team (PEP-183): stands in for `claude -p` as the specialist matcher. The scenario file
|
||||
// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false }.
|
||||
// The first rule whose regexp matches the story's title ("Задача: …") wins; none → agent null.
|
||||
// Every call is appended to <scenario>.log.jsonl.
|
||||
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
|
||||
interface Scenario {
|
||||
rules?: Array<{ match: string; agent: string | null; reason?: string }>;
|
||||
fail?: boolean;
|
||||
}
|
||||
const file = process.env.MOCK_TEAM_SCENARIO;
|
||||
const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
||||
const prompt = readFileSync(0, "utf8");
|
||||
const title = /^Задача: (.*)$/m.exec(prompt)?.[1] ?? "";
|
||||
if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ args: process.argv.slice(2), title, prompt }) + "\n");
|
||||
if (!process.argv.includes("-p")) {
|
||||
console.error("mock-team: expected -p (non-interactive print mode)");
|
||||
process.exit(2);
|
||||
}
|
||||
if (sc.fail) {
|
||||
console.error("mock-team: API Error: 529 overloaded");
|
||||
process.exit(1);
|
||||
}
|
||||
const rule = sc.rules?.find((r) => new RegExp(r.match, "i").test(title));
|
||||
const answer = { agent: rule?.agent ?? null, reason: rule?.reason ?? "mock: никто не подходит" };
|
||||
process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result: JSON.stringify(answer), session_id: "mock-team" }) + "\n");
|
||||
96
packages/testkit/test/team-match.test.ts
Normal file
96
packages/testkit/test/team-match.test.ts
Normal file
@ -0,0 +1,96 @@
|
||||
// PEP-183: specialists get stories of their profile.
|
||||
import assert from "node:assert/strict";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { after, describe, test } from "node:test";
|
||||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||||
|
||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||||
process.env.PEPPA_TEAM_BIN = join(import.meta.dirname, "../bin/mock-team");
|
||||
after(teardown);
|
||||
|
||||
const scenario = (s: object) => {
|
||||
const f = join(process.env.PEPPA_HOME!, `team-${Math.random().toString(36).slice(2)}.json`);
|
||||
writeFileSync(f, JSON.stringify(s));
|
||||
process.env.MOCK_TEAM_SCENARIO = f;
|
||||
return f;
|
||||
};
|
||||
const retitle = async (p: { taskKey: string }, title: string) => core.updateTask(db, await core.resolveTask(db, p.taskKey), { title });
|
||||
const agentOf = async (sid: number) => (await core.getSession(db, sid)).agentName;
|
||||
|
||||
describe("Специалисты и задачи по профилю", () => {
|
||||
let guard: Awaited<ReturnType<typeof core.createAgent>>;
|
||||
let plain: Awaited<ReturnType<typeof core.createAgent>>;
|
||||
|
||||
test("Scenario: задача про безопасность — специалисту, про интерфейс — универсалу", async () => {
|
||||
scenario({ rules: [{ match: "безопасн", agent: "Страж ИБ", reason: "про безопасность" }] });
|
||||
guard = await core.createAgent(db, { name: "Страж ИБ", character: "Безопасность: проверяет ввод и секреты." });
|
||||
plain = await core.createAgent(db, { name: "Универсал" });
|
||||
const sec = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(sec, "Проверить безопасность входа");
|
||||
const ui = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(ui, "Поправить кнопку интерфейса");
|
||||
const s1 = await sec.start();
|
||||
assert.equal(await agentOf(s1), "Страж ИБ");
|
||||
const s2 = await ui.start();
|
||||
assert.equal(await agentOf(s2), "Универсал");
|
||||
const m = await core.getTeamMatch(db, (await sec.task()).id);
|
||||
assert.equal(m?.agentId, guard.id);
|
||||
assert.match(core.matchLine(m)!, /Отдана специалисту/);
|
||||
assert.equal((await core.listAgents(db)).find((a) => a.id === guard.id)!.profileTasks, 1);
|
||||
await runner.stopSession(db, s1);
|
||||
await runner.stopSession(db, s2);
|
||||
});
|
||||
|
||||
test("Scenario: специалист занят — задача ждёт его, через порог уходит универсалу", async () => {
|
||||
const busy = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(busy, "Безопасность: ключи");
|
||||
const s0 = await busy.start();
|
||||
assert.equal(await agentOf(s0), "Страж ИБ");
|
||||
|
||||
const next = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(next, "Ещё про безопасность");
|
||||
const t = await next.task();
|
||||
const [proj] = await core.listProjects(db).then((l) => l.filter((x) => x.key === next.key));
|
||||
const now = new Date();
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "waits for the busy specialist");
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 20 * 60_000)))], [t.id], "still within 30 min");
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 31 * 60_000)))], [], "after the threshold it is free to go");
|
||||
await core.setTeamSettings(db, { waitMin: 5 });
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 6 * 60_000)))], []);
|
||||
const s1 = await next.start();
|
||||
assert.equal(await agentOf(s1), "Универсал", "the specialist is busy → a generalist");
|
||||
assert.ok(proj);
|
||||
await runner.stopSession(db, s0);
|
||||
await runner.stopSession(db, s1);
|
||||
await core.setTeamSettings(db, { waitMin: 30 });
|
||||
});
|
||||
|
||||
test("Scenario: стёрли специализацию — следующая задача идёт как универсалу", async () => {
|
||||
await core.updateAgent(db, guard.id, { character: "" });
|
||||
await core.updateAgent(db, plain.id, { disabled: true });
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(p, "Безопасность: логи");
|
||||
const sid = await p.start();
|
||||
assert.equal(await agentOf(sid), "Страж ИБ");
|
||||
assert.equal(await core.getTeamMatch(db, (await p.task()).id), null, "no specialists left — nothing to decide");
|
||||
await runner.stopSession(db, sid);
|
||||
await core.updateAgent(db, plain.id, { disabled: false });
|
||||
});
|
||||
|
||||
test("Scenario: запрос к модели упал — задача отдана универсалу, ошибки нет", async () => {
|
||||
await core.updateAgent(db, guard.id, { character: "Безопасность." });
|
||||
scenario({ fail: true });
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(p, "Безопасность: пароли");
|
||||
const sid = await p.start();
|
||||
assert.equal(await agentOf(sid), "Универсал");
|
||||
const m = await core.getTeamMatch(db, (await p.task()).id);
|
||||
assert.equal(m?.failed, true);
|
||||
assert.equal(core.matchLine(m), "Специалиста не нашлось");
|
||||
const proj = (await core.listProjects(db)).find((x) => x.key === p.key)!;
|
||||
const j = await core.listJournal(db, { projectId: proj.id } as never);
|
||||
assert.ok(j.some((e) => e.type === "team_match_failed"));
|
||||
await runner.stopSession(db, sid);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user