Merge pull request 'PEP-295: задача не от человека — в работу только через «Предложено»' (#268) from task/pep-295 into main
This commit is contained in:
commit
edac120990
@ -35,6 +35,7 @@
|
|||||||
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
|
- Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265).
|
||||||
- Песочница раннера: нет tmux, Node 26 (без 26 тесты падают на импортах — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp). tmux — .deb deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, тесты хостов в sandbox-hosts.test.ts (нет ssh).
|
- Песочница раннера: нет tmux, Node 26 (без 26 тесты падают на импортах — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp). tmux — .deb deb.debian.org (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, тесты хостов в sandbox-hosts.test.ts (нет ssh).
|
||||||
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
|
- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287).
|
||||||
|
- Пропал `.git/worktrees/s<id>`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`.
|
||||||
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
|
- Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <cli> <версия>` (json + оба Dockerfile), откат `--rollback`.
|
||||||
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
- Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`).
|
||||||
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
- tmux на сервере (PEP-256) — контейнер `peppa-tmux`, сервисы — клиенты (`PEPPA_TMUX_EXTERNAL`); его образ меняет только `platform-deploy.sh --tmux`. Нет docker — compose проверяй парсером `yaml` (`{merge:true}`).
|
||||||
@ -52,7 +53,7 @@
|
|||||||
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
||||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
||||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall; функция от внешнего сервиса — `featureGateView` + `<FeatureGate>` (PEP-224).
|
||||||
- Задачу агента — createTask с origin (acceptance|incident|analyst|agent) через fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + proposed; суточный предел предложений — `proposalRoom` (PEP-270); автомерж — autonomy.acceptOwn.
|
- Задача не от человека — `createTask` с origin сама в «Предложено» (PEP-295), путь — проверить `proposalRoom` до создания; новый вызов `createTask` — в список `proposals-only.test.ts`; автомерж — autonomy.acceptOwn.
|
||||||
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
||||||
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
- Bugsink API (PEP-218): схема — `GET /api/canonical/0/schema/` (2.6.3); `q` = текст + теги `key:value`; числа пользователей нет. Экран — `core/bugsink-errors.ts` (кэш 45 с), действия — `runner/bugsink-errors.ts`.
|
||||||
- Access Hub (PEP-249): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (получает проверенный `address`, сам DNS не разрешает) и мок в testkit/mock-access.ts. Ответ сервиса агенту (PEP-258) — только через `connectionKeyForms`+`maskConnectionKey`; новый способ ключа — в тест-ловушку access-hub.test.ts.
|
- Access Hub (PEP-249): новый HTTP-сервис — карточка в `core/connection-catalog.ts` (тест сверяет каждую); меняет данные через GET (Slack) — чтение по методам. Новый не-HTTP вид (PEP-251) — операция в `PROTOCOL_OPERATIONS`, драйвер `GatewayDrivers` (получает проверенный `address`, сам DNS не разрешает) и мок в testkit/mock-access.ts. Ответ сервиса агенту (PEP-258) — только через `connectionKeyForms`+`maskConnectionKey`; новый способ ключа — в тест-ловушку access-hub.test.ts.
|
||||||
|
|||||||
@ -26,6 +26,8 @@ import {
|
|||||||
type IncidentPolicy,
|
type IncidentPolicy,
|
||||||
getUser,
|
getUser,
|
||||||
isSuperadmin,
|
isSuperadmin,
|
||||||
|
getDirectOrigins,
|
||||||
|
setDirectOrigins,
|
||||||
setUserDisabled,
|
setUserDisabled,
|
||||||
setSuperadmin,
|
setSuperadmin,
|
||||||
mergeAccounts,
|
mergeAccounts,
|
||||||
@ -686,6 +688,17 @@ export async function connectErrorTrackingAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** PEP-295: the owner's exception — errors of the product go to work without «Делать». */
|
||||||
|
export async function setDirectIncidentsAction(f: FormData) {
|
||||||
|
const user = asWebActor(await requireUser());
|
||||||
|
await attempt(f, async () => {
|
||||||
|
const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
|
||||||
|
if (p.ownerId !== user.id && !(await isSuperadmin(db, user))) throw new PeppaError(m("Это решает владелец проекта."));
|
||||||
|
const rest = (await getDirectOrigins(db, p.id)).filter((o) => o !== "incident");
|
||||||
|
await setDirectOrigins(db, p.id, str(f, "on") === "yes" ? [...rest, "incident"] : rest);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function saveIncidentSettings(f: FormData) {
|
export async function saveIncidentSettings(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
|
|||||||
@ -5,7 +5,7 @@ import { PublishPanel } from "@/components/PublishPanel";
|
|||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
import { ExternalLink, Plus, Rocket, SquareTerminal } from "lucide-react";
|
||||||
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
|
import { columnOf, currentReleases, peekRepo, isPlatform, listReleases, bugsinkWebhookBase, openPulls, platformReleaseCandidate, platformReleaseOffers, ownPendingLogins, readAgentsMd, repoOverview, type Release, sharedRequest, subscriptionRequestOffer } from "@peppa/runner";
|
||||||
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
import { getProjectPause, getPublishMode, poolSubscriptions, PRODUCT_PROJECT_TABS, userProjectIds, projectProduct, discussionUnread, ensureProjectChat, listHosts, DEFAULT_RUNNER_SETTINGS, DEFAULT_AGENT_SETTINGS, getProjectAgentSettings, getSystemAgentSettings, getProjectRunnerSettings, getSystemRunnerSettings, blockedLabel, blockersMap, epicProgress, progressLabel, taskProgress, getProjectBudget, listJournal, listProjectSecrets, agentSecretsEnabled, secretsAgentReport, secretNameHints, projectMetrics, type ActorChannel, type ActorKind, getAutonomy, getIncidentSettings, getDirectOrigins, getReviewSettings, isSuperadmin, listEpics, listErrorSources, listIncidents, listMembers, listPools, listSpecs, taskAgentNames, getIntakeSettings, intakePendingTasks, projectAgentWarning, taskHoldReasons, memoryStats, readMemory, projectPool, sharedPool, ownPool, poolOverview, repoAudience, repoVisibilityLabel } from "@peppa/core";
|
||||||
import { productNeeds, lastProductReview } from "@peppa/core";
|
import { productNeeds, lastProductReview } from "@peppa/core";
|
||||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||||
import { PanelSection } from "@/components/ActivityAside";
|
import { PanelSection } from "@/components/ActivityAside";
|
||||||
@ -103,7 +103,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
|
const tab = visibleTabs.find((x) => x.id === tabParam)?.id ?? "board";
|
||||||
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
const p = await projectForUserByKey(user.id, key).catch(() => null);
|
||||||
if (!p) notFound();
|
if (!p) notFound();
|
||||||
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps] = await Promise.all([
|
const [{ tasks }, epics, sessions, team, repo, incidentSettings, sources, incidents, releases, current, reviewer, progress, deps, directOrigins] = await Promise.all([
|
||||||
board(p.id),
|
board(p.id),
|
||||||
listEpics(db, p.id),
|
listEpics(db, p.id),
|
||||||
projectSessions(p.id),
|
projectSessions(p.id),
|
||||||
@ -117,6 +117,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
getReviewSettings(db, p.id),
|
getReviewSettings(db, p.id),
|
||||||
epicProgress(db, p.id),
|
epicProgress(db, p.id),
|
||||||
blockersMap(db, p.id),
|
blockersMap(db, p.id),
|
||||||
|
getDirectOrigins(db, p.id),
|
||||||
]);
|
]);
|
||||||
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
|
// Peppa itself has no staging: its prod candidate is the newest green main (PEP-18).
|
||||||
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
const prodCandidate = isPlatform(p) ? ((await platformReleaseOffers(db)) ? await platformReleaseCandidate(db, p) : null) : (current.staging?.sha ?? null);
|
||||||
@ -360,6 +361,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
projectId={p.id}
|
projectId={p.id}
|
||||||
back={back}
|
back={back}
|
||||||
isOwner={isOwner}
|
isOwner={isOwner}
|
||||||
|
direct={directOrigins.includes("incident")}
|
||||||
settings={incidentSettings}
|
settings={incidentSettings}
|
||||||
sources={sources}
|
sources={sources}
|
||||||
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
|
// Project page «Баги» (PEP-58, PEP-66): incidents list (tab) and Bugsink settings (⋯ Настройки проекта).
|
||||||
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
|
import { Bug, CircleCheck, EyeOff, Inbox, MapPin, Play } from "lucide-react";
|
||||||
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
|
import { INCIDENT_STATUS_RU, incidentPolicies, POLICY_RU, type ErrorSource, type Incident, type IncidentSettings } from "@peppa/core";
|
||||||
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings } from "@/app/(app)/actions";
|
import { connectErrorTrackingAction, decideIncidentAction, resolveIncidentAction, saveIncidentSettings, setDirectIncidentsAction } from "@/app/(app)/actions";
|
||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
|
import { ago, Disclosure, Empty, Key, Section } from "@/components/common";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@ -61,6 +61,8 @@ export async function IncidentSettingsPanel(props: {
|
|||||||
settings: IncidentSettings | null;
|
settings: IncidentSettings | null;
|
||||||
sources: ErrorSource[];
|
sources: ErrorSource[];
|
||||||
webhookUrl: string | null;
|
webhookUrl: string | null;
|
||||||
|
/** PEP-295: the owner let errors of the product go to work without «Делать». */
|
||||||
|
direct: boolean;
|
||||||
w: Words;
|
w: Words;
|
||||||
}) {
|
}) {
|
||||||
const { projectId, back, settings: s, w } = props;
|
const { projectId, back, settings: s, w } = props;
|
||||||
@ -83,10 +85,35 @@ export async function IncidentSettingsPanel(props: {
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// PEP-295: whether errors go to work without «Делать» is the owner's decision — shown in both views.
|
||||||
|
const direct = (
|
||||||
|
<div className="flex flex-col gap-1.5 text-sm">
|
||||||
|
<span>
|
||||||
|
{props.direct
|
||||||
|
? t("Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».")
|
||||||
|
: t("Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».")}
|
||||||
|
</span>
|
||||||
|
{props.isOwner && (
|
||||||
|
<form action={setDirectIncidentsAction}>
|
||||||
|
<Hidden fields={{ projectId, back, on: props.direct ? "no" : "yes" }} />
|
||||||
|
<Button size="sm" variant="outline">
|
||||||
|
{props.direct ? t("Ждать моего решения") : t("Брать в работу сразу")}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
// PEP-123: addresses, variables and the policy of incidents are an engineer's settings.
|
// PEP-123: addresses, variables and the policy of incidents are an engineer's settings.
|
||||||
if (w.product) return <p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>;
|
if (w.product)
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-3">
|
||||||
|
<p className="m-0 text-sm text-muted-foreground">{t("Подключено: ошибки вашего продукта приходят во вкладку «Баги» и становятся задачами для агентов.")}</p>
|
||||||
|
{direct}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-3 text-sm">
|
<div className="flex flex-col gap-3 text-sm">
|
||||||
|
{direct}
|
||||||
{props.sources.map((src) => (
|
{props.sources.map((src) => (
|
||||||
<div key={src.id} className="flex flex-col gap-1">
|
<div key={src.id} className="flex flex-col gap-1">
|
||||||
<span className="font-medium">{src.kind === "web" ? t("DSN фронта (web)") : t("DSN бэка (api)")}</span>
|
<span className="font-medium">{src.kind === "web" ? t("DSN фронта (web)") : t("DSN бэка (api)")}</span>
|
||||||
|
|||||||
@ -41,7 +41,7 @@ export async function ProposalList({ items, back }: { items: ProposalItem[]; bac
|
|||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-xs text-muted-foreground">{i.decision === "rejected" ? t("Отклонено") : i.severity === "breakage" ? t("Уже в бэклоге") : t("Взято в бэклог")}</span>
|
<span className="text-xs text-muted-foreground">{i.decision === "rejected" ? t("Отклонено") : t("Взято в бэклог")}</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -0,0 +1,62 @@
|
|||||||
|
# Design — PEP-295
|
||||||
|
|
||||||
|
## Одна точка: `createTask`
|
||||||
|
Правило проверяется там, где задача рождается, а не в каждом вызывающем: `createTask` при
|
||||||
|
`origin` ≠ `human` ставит `proposed = true`, игнорируя переданный `proposed`. Снять флаг при
|
||||||
|
создании могут только:
|
||||||
|
- `decidedByPerson: true` — вызывающий передаёт решение человека, которое уже было (кнопка
|
||||||
|
у ошибки продукта — `decideIncident`, `decidedBy = pm`);
|
||||||
|
- исключение владельца: происхождение есть в `project.direct-origins:<projectId>`
|
||||||
|
(`getDirectOrigins`/`setDirectOrigins` в core/task-origin.ts; без миграции, нет строки = пусто).
|
||||||
|
|
||||||
|
Так новый путь создания задачи не сможет забыть правило — он получает его по умолчанию.
|
||||||
|
|
||||||
|
## Исключение владельца
|
||||||
|
Задача формулирует исключение как «например, ошибки из прода брать сразу». Делаем общий
|
||||||
|
список происхождений в ядре (`incident`, `acceptance`, `analyst`, `agent`), а в вебе
|
||||||
|
показываем владельцу одну галочку — «Ошибки продукта брать в работу сразу» в «⋯ Настройки
|
||||||
|
проекта → Баги» (видна и в «Продакте»: это решение владельца, не техническое). Остальные —
|
||||||
|
через CLI `peppa project direct <KEY> [origin=on|off …]` для суперадмина. Менять может только
|
||||||
|
владелец (или суперадмин) — `isOwner` как у прочих настроек владельца.
|
||||||
|
|
||||||
|
## Предел в сутки — общий
|
||||||
|
`proposalsToday` считает задачи с `origin` ≠ `human` за 24 часа, кроме созданных решением
|
||||||
|
человека (задача ошибки продукта с `decided_by = pm` — подзапрос по `incidents`). Каждый путь
|
||||||
|
сверяется с `proposalRoom` до создания и при нехватке места:
|
||||||
|
- агент разработки — отказ (как в PEP-270);
|
||||||
|
- приёмка — в недельную сводку (как в PEP-270), теперь и поломки;
|
||||||
|
- ошибка продукта — сообщение «решите сами» с кнопками (как при пределе задач из ошибок);
|
||||||
|
- разбивка аналитика — лишние части не заводятся, их названия дописываются к задаче человека
|
||||||
|
заметкой аналитика;
|
||||||
|
- системная задача о ссылке — не заводится в этот тик, повтор следующим тиком;
|
||||||
|
- возврат ошибки (регрессия старше окна) — без новой задачи, сообщение «решите, что делать».
|
||||||
|
Отказ — событие `proposal_limited` с `via`.
|
||||||
|
|
||||||
|
## Ошибки продукта
|
||||||
|
Политика `start` при задаче в «Предложено» агента не запускает. Сообщение владельцу о задаче
|
||||||
|
в «Предложено» несёт кнопки `p:<taskId>:do|no` — их уже понимает бот (`decideProposals`).
|
||||||
|
|
||||||
|
## Разбивка
|
||||||
|
`confirmTaskDecision` для решения `split` одобряет части (`approveProposal`): «Подходит» —
|
||||||
|
это «Делать». `undoSplit` архивирует их, как и раньше.
|
||||||
|
|
||||||
|
## Агент приёмки
|
||||||
|
`fileStories`: поломка тоже в «Предложено» (метка «Поломка» остаётся, «Делать важные» её
|
||||||
|
берёт). Кнопки в сообщении — у всех находок, включая поломки.
|
||||||
|
|
||||||
|
## Ревьюер и агент обратной связи
|
||||||
|
Задач не заводят (ревьюер шлёт замечания агенту, обращение становится задачей только решением
|
||||||
|
суперадмина `fixFeedback`). Закрепляем тестом: структурный тест перечисляет все вызовы
|
||||||
|
`createTask` в packages/core|runner|mcp|apps и требует для каждого известный путь — новый
|
||||||
|
вызов без явной классификации ронять тест.
|
||||||
|
|
||||||
|
## Запрос для приёмки (48 часов)
|
||||||
|
```sql
|
||||||
|
SELECT p.key, t.number, t.origin, e.created_at
|
||||||
|
FROM events e JOIN tasks t ON t.id = e.task_id JOIN projects p ON p.id = t.project_id
|
||||||
|
WHERE e.type = 'task_updated' AND json_extract(e.payload,'$.to') = 'in_progress'
|
||||||
|
AND t.origin <> 'human' AND p.key IN ('BRM','TPTIP','TR','DIK')
|
||||||
|
AND e.created_at > unixepoch('now','-2 days')*1000
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM events a WHERE a.task_id = t.id AND a.type = 'proposal_approved');
|
||||||
|
```
|
||||||
|
Пустой результат после выкатки — приёмка выполнена (выполнить на живой базе после мержа).
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
# PEP-295: Одно правило для всех задач не от человека — в работу только через «Предложено»
|
||||||
|
|
||||||
|
## Why
|
||||||
|
PEP-270 закрыла обход через `create_task` агента, но остались пути, по которым задача не от
|
||||||
|
человека уходит в работу без решения владельца: «поломка» агента приёмки (важность ставит сам
|
||||||
|
агент — за 24–25.11 так ушли 11 из 39 его задач), ошибки из прода (политика `backlog`/`start`),
|
||||||
|
системная задача «Продукт должен открываться по ссылке» (встаёт первой и берётся сама), части
|
||||||
|
разбивки аналитика. Диспетчер за 48 часов взял 8 таких задач без одобрения.
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- `createTask` сам ставит «Предложено» любой задаче с `origin` ≠ `human`; вызывающий не может
|
||||||
|
это обойти. Задача без флага — только если человек уже решил (`decidedByPerson`: кнопка
|
||||||
|
«В бэклог»/«В работу» у ошибки) или владелец включил исключение для этого происхождения.
|
||||||
|
- Исключение — настройка проекта `project.direct-origins:<id>` (список происхождений), по
|
||||||
|
умолчанию пусто. В вебе владелец включает одно: «Ошибки продукта брать в работу сразу».
|
||||||
|
- Предел `perDay` (5) — общий для всех задач не от человека: агент разработки, приёмка (и
|
||||||
|
поломки), ошибки продукта, разбивка аналитика, системная задача о ссылке. Задачи, созданные
|
||||||
|
решением человека, предел не тратят.
|
||||||
|
- Ошибка продукта: по политике `backlog`/`start`/`triage` без исключения задача идёт в
|
||||||
|
«Предложено» с кнопками «Делать»/«Не надо»; политика `start` не запускает агента.
|
||||||
|
- «Подходит» у решения «разбить» = «Делать» для частей.
|
||||||
|
- Тест на каждый путь создания задачи, включая ревьюера и агента обратной связи (они задач не
|
||||||
|
заводят).
|
||||||
|
|
||||||
|
## Impact
|
||||||
|
- core: `tasks.ts` (`createTask`), `task-origin.ts` (исключения, предел), `incidents.ts`.
|
||||||
|
- runner: `incidents.ts`, `product-review.ts`, `product-link.ts`, `intake.ts`, `decisions.ts`.
|
||||||
|
- web: настройка в «⋯ Настройки проекта → Баги»; CLI `peppa project direct`.
|
||||||
|
- Без миграций.
|
||||||
@ -0,0 +1,90 @@
|
|||||||
|
## REMOVED Requirements
|
||||||
|
|
||||||
|
### Requirement: Задачи агентов не берутся в работу сами
|
||||||
|
**Reason**: поломка от агента приёмки больше не идёт в бэклог сама — заменено требованием «Задача не от человека — только через «Предложено»».
|
||||||
|
**Migration**: поломки появляются в «Предложено» с пометкой «Поломка»; «Делать важные» берёт их.
|
||||||
|
|
||||||
|
### Requirement: Не больше N предложений агентов в сутки на проект
|
||||||
|
**Reason**: предел стал общим для всех путей — заменено требованием «Не больше N задач не от человека в сутки на проект».
|
||||||
|
**Migration**: настройка `perDay` прежняя.
|
||||||
|
|
||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Задача не от человека — только через «Предложено»
|
||||||
|
Любая задача с происхождением не «человек» (агент разработки, агент приёмки — в том числе с пометкой «Поломка», ошибка продукта, часть разбивки аналитика, системная задача FORGE) SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец или участник не нажал «Делать». Задача без «Предложено» создаётся только по решению человека или по исключению, которое владелец включил для этого происхождения в своём проекте (по умолчанию исключений нет).
|
||||||
|
|
||||||
|
#### Scenario: Улучшение от агента приёмки
|
||||||
|
- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом
|
||||||
|
- **WHEN** агент приёмки находит улучшение
|
||||||
|
- **THEN** задача появляется в «Предложено»
|
||||||
|
- **AND** диспетчер её не берёт
|
||||||
|
|
||||||
|
#### Scenario: Поломка от агента приёмки
|
||||||
|
- **GIVEN** проект с режимом «Сам берёт»
|
||||||
|
- **WHEN** агент приёмки находит поломку «Кнопка оплаты не работает»
|
||||||
|
- **THEN** задача появляется в «Предложено» с пометкой «Поломка»
|
||||||
|
- **AND** диспетчер её не берёт, пока владелец не нажал «Делать»
|
||||||
|
|
||||||
|
#### Scenario: Ошибка продукта по политике «в работу»
|
||||||
|
- **GIVEN** проект с политикой ошибок «в работу» и без исключения
|
||||||
|
- **WHEN** приходит новая ошибка продукта
|
||||||
|
- **THEN** задача появляется в «Предложено»
|
||||||
|
- **AND** агент не запускается
|
||||||
|
- **AND** владелец получает сообщение с кнопками «Делать» и «Не надо»
|
||||||
|
|
||||||
|
#### Scenario: Владелец разрешил брать ошибки сразу
|
||||||
|
- **GIVEN** владелец включил «Ошибки продукта брать в работу сразу»
|
||||||
|
- **AND** политика ошибок «в работу»
|
||||||
|
- **WHEN** приходит новая ошибка продукта
|
||||||
|
- **THEN** задача создаётся в работе и агент запускается
|
||||||
|
|
||||||
|
#### Scenario: Решение человека по ошибке
|
||||||
|
- **GIVEN** ошибка продукта ждёт решения
|
||||||
|
- **WHEN** владелец нажимает «В бэклог»
|
||||||
|
- **THEN** задача создаётся в бэклоге, не в «Предложено»
|
||||||
|
|
||||||
|
#### Scenario: Системная задача о ссылке
|
||||||
|
- **GIVEN** у проекта есть принятые задачи и нет версии для проверки
|
||||||
|
- **WHEN** FORGE заводит задачу «Продукт должен открываться по ссылке»
|
||||||
|
- **THEN** задача стоит в «Предложено» и диспетчер её не берёт
|
||||||
|
|
||||||
|
#### Scenario: Части разбивки аналитика
|
||||||
|
- **GIVEN** аналитик разбил задачу человека на 3 части
|
||||||
|
- **WHEN** части заведены
|
||||||
|
- **THEN** вторая и третья части стоят в «Предложено»
|
||||||
|
- **AND** «Подходит» у решения «разбить» переводит их в бэклог
|
||||||
|
|
||||||
|
#### Scenario: Ревьюер и агент обратной связи задач не заводят
|
||||||
|
- **GIVEN** ревьюер вернул замечания, агент обратной связи разобрал обращение
|
||||||
|
- **WHEN** их проходы закончились
|
||||||
|
- **THEN** число задач проекта не изменилось
|
||||||
|
|
||||||
|
### Requirement: Не больше N задач не от человека в сутки на проект
|
||||||
|
Проект SHALL получать не больше `perDay` задач не от человека за последние 24 часа (по умолчанию 5, настройка своя у каждого проекта) — общий предел для всех путей: агент разработки, агент приёмки, ошибки продукта, разбивка аналитика, системные задачи FORGE. Задачи, созданные решением человека (кнопка у ошибки продукта), предел не тратят.
|
||||||
|
|
||||||
|
#### Scenario: Шестая задача агента за сутки
|
||||||
|
- **GIVEN** в проекте за последние 24 часа агенты завели 5 задач
|
||||||
|
- **WHEN** агент вызывает `create_task` ещё раз
|
||||||
|
- **THEN** задача не создаётся
|
||||||
|
- **AND** агент получает ответ, что предел предложений на сутки исчерпан
|
||||||
|
|
||||||
|
#### Scenario: Приёмка нашла больше, чем осталось
|
||||||
|
- **GIVEN** за сутки агенты завели 4 задачи
|
||||||
|
- **WHEN** агент приёмки находит 3 улучшения
|
||||||
|
- **THEN** заводится 1 задача, 2 находки ждут недельной сводки
|
||||||
|
|
||||||
|
#### Scenario: Ошибка продукта при исчерпанном пределе
|
||||||
|
- **GIVEN** за сутки заведено 5 задач не от человека
|
||||||
|
- **WHEN** приходит новая ошибка продукта с политикой «в бэклог»
|
||||||
|
- **THEN** задача не создаётся
|
||||||
|
- **AND** владелец получает сообщение с кнопками решения
|
||||||
|
|
||||||
|
#### Scenario: Решение человека не тратит предел
|
||||||
|
- **GIVEN** за сутки заведено 5 задач не от человека
|
||||||
|
- **WHEN** владелец нажимает «В бэклог» у ошибки продукта
|
||||||
|
- **THEN** задача создаётся
|
||||||
|
|
||||||
|
#### Scenario: Свой предел у проекта
|
||||||
|
- **GIVEN** проекту задан предел 2 в сутки
|
||||||
|
- **WHEN** агент заводит третью задачу за сутки
|
||||||
|
- **THEN** задача не создаётся
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
## 1. Ядро
|
||||||
|
- [x] 1.1 `createTask`: `origin` ≠ `human` → «Предложено», кроме `decidedByPerson` и исключения владельца
|
||||||
|
- [x] 1.2 Исключения `project.direct-origins:<id>` (`getDirectOrigins`/`setDirectOrigins`)
|
||||||
|
- [x] 1.3 `proposalsToday` — все задачи не от человека, кроме решений человека по ошибкам
|
||||||
|
|
||||||
|
## 2. Пути создания
|
||||||
|
- [x] 2.1 Ошибки продукта: «Предложено», `start` без исключения не запускает, предел, кнопки «Делать»/«Не надо», регрессия
|
||||||
|
- [x] 2.2 Агент приёмки: поломка тоже в «Предложено», кнопки у всех находок
|
||||||
|
- [x] 2.3 Системная задача о ссылке: «Предложено», предел
|
||||||
|
- [x] 2.4 Разбивка аналитика: части в «Предложено», предел, «Подходит» одобряет части
|
||||||
|
|
||||||
|
## 3. Настройка владельца
|
||||||
|
- [x] 3.1 Веб: «Ошибки продукта брать в работу сразу» в «⋯ Настройки проекта → Баги» (переводы, словарь)
|
||||||
|
- [x] 3.2 CLI `peppa project direct`
|
||||||
|
|
||||||
|
## 4. Тесты и завершение
|
||||||
|
- [x] 4.1 Тест на каждый путь: MCP агента, приёмка (с поломкой), ошибки продукта, разбивка, ссылка, ревьюер, обратная связь
|
||||||
|
- [x] 4.2 Обновить существующие тесты под новое правило; typecheck, lint, тесты
|
||||||
|
- [x] 4.3 AGENTS.md, память, archive, PR
|
||||||
@ -5,20 +5,6 @@ TBD - created by archiving change pep-197-no-task-loop. Update Purpose after arc
|
|||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
### Requirement: Задачи агентов не берутся в работу сами
|
|
||||||
Задача, заведённая агентом приёмки, SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец не нажал «Делать». Поломка SHALL идти в бэклог сразу с пометкой «Поломка».
|
|
||||||
|
|
||||||
#### Scenario: Улучшение от агента приёмки
|
|
||||||
- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом
|
|
||||||
- **WHEN** агент приёмки находит улучшение
|
|
||||||
- **THEN** задача появляется в «Предложено»
|
|
||||||
- **AND** диспетчер её не берёт
|
|
||||||
|
|
||||||
#### Scenario: Поломка критерия задачи человека
|
|
||||||
- **GIVEN** задача человека с критерием приёмки
|
|
||||||
- **WHEN** агент приёмки находит, что критерий не выполнен
|
|
||||||
- **THEN** задача создаётся в бэклоге с пометкой «Поломка»
|
|
||||||
|
|
||||||
### Requirement: Без дублей
|
### Requirement: Без дублей
|
||||||
Перед созданием задачи агентом SHALL выполняться проверка повтора по открытым задачам и сделанным за 60 дней.
|
Перед созданием задачи агентом SHALL выполняться проверка повтора по открытым задачам и сделанным за 60 дней.
|
||||||
|
|
||||||
@ -67,8 +53,57 @@ TBD - created by archiving change pep-197-no-task-loop. Update Purpose after arc
|
|||||||
- **WHEN** владелец нажимает «Делать»
|
- **WHEN** владелец нажимает «Делать»
|
||||||
- **THEN** задача уходит в бэклог и диспетчер может взять её в работу
|
- **THEN** задача уходит в бэклог и диспетчер может взять её в работу
|
||||||
|
|
||||||
### Requirement: Не больше N предложений агентов в сутки на проект
|
### Requirement: Задача не от человека — только через «Предложено»
|
||||||
Проект SHALL получать от агентов (разработки и приёмки) не больше `perDay` задач за последние 24 часа (по умолчанию 5, настройка своя у каждого проекта). Задачи из ошибок продукта и части разбивки задачи человека предел не тратят.
|
Любая задача с происхождением не «человек» (агент разработки, агент приёмки — в том числе с пометкой «Поломка», ошибка продукта, часть разбивки аналитика, системная задача FORGE) SHALL создаваться в «Предложено» и не браться диспетчером, пока владелец или участник не нажал «Делать». Задача без «Предложено» создаётся только по решению человека или по исключению, которое владелец включил для этого происхождения в своём проекте (по умолчанию исключений нет).
|
||||||
|
|
||||||
|
#### Scenario: Улучшение от агента приёмки
|
||||||
|
- **GIVEN** проект с режимом «Сам берёт» и пустым бэклогом
|
||||||
|
- **WHEN** агент приёмки находит улучшение
|
||||||
|
- **THEN** задача появляется в «Предложено»
|
||||||
|
- **AND** диспетчер её не берёт
|
||||||
|
|
||||||
|
#### Scenario: Поломка от агента приёмки
|
||||||
|
- **GIVEN** проект с режимом «Сам берёт»
|
||||||
|
- **WHEN** агент приёмки находит поломку «Кнопка оплаты не работает»
|
||||||
|
- **THEN** задача появляется в «Предложено» с пометкой «Поломка»
|
||||||
|
- **AND** диспетчер её не берёт, пока владелец не нажал «Делать»
|
||||||
|
|
||||||
|
#### Scenario: Ошибка продукта по политике «в работу»
|
||||||
|
- **GIVEN** проект с политикой ошибок «в работу» и без исключения
|
||||||
|
- **WHEN** приходит новая ошибка продукта
|
||||||
|
- **THEN** задача появляется в «Предложено»
|
||||||
|
- **AND** агент не запускается
|
||||||
|
- **AND** владелец получает сообщение с кнопками «Делать» и «Не надо»
|
||||||
|
|
||||||
|
#### Scenario: Владелец разрешил брать ошибки сразу
|
||||||
|
- **GIVEN** владелец включил «Ошибки продукта брать в работу сразу»
|
||||||
|
- **AND** политика ошибок «в работу»
|
||||||
|
- **WHEN** приходит новая ошибка продукта
|
||||||
|
- **THEN** задача создаётся в работе и агент запускается
|
||||||
|
|
||||||
|
#### Scenario: Решение человека по ошибке
|
||||||
|
- **GIVEN** ошибка продукта ждёт решения
|
||||||
|
- **WHEN** владелец нажимает «В бэклог»
|
||||||
|
- **THEN** задача создаётся в бэклоге, не в «Предложено»
|
||||||
|
|
||||||
|
#### Scenario: Системная задача о ссылке
|
||||||
|
- **GIVEN** у проекта есть принятые задачи и нет версии для проверки
|
||||||
|
- **WHEN** FORGE заводит задачу «Продукт должен открываться по ссылке»
|
||||||
|
- **THEN** задача стоит в «Предложено» и диспетчер её не берёт
|
||||||
|
|
||||||
|
#### Scenario: Части разбивки аналитика
|
||||||
|
- **GIVEN** аналитик разбил задачу человека на 3 части
|
||||||
|
- **WHEN** части заведены
|
||||||
|
- **THEN** вторая и третья части стоят в «Предложено»
|
||||||
|
- **AND** «Подходит» у решения «разбить» переводит их в бэклог
|
||||||
|
|
||||||
|
#### Scenario: Ревьюер и агент обратной связи задач не заводят
|
||||||
|
- **GIVEN** ревьюер вернул замечания, агент обратной связи разобрал обращение
|
||||||
|
- **WHEN** их проходы закончились
|
||||||
|
- **THEN** число задач проекта не изменилось
|
||||||
|
|
||||||
|
### Requirement: Не больше N задач не от человека в сутки на проект
|
||||||
|
Проект SHALL получать не больше `perDay` задач не от человека за последние 24 часа (по умолчанию 5, настройка своя у каждого проекта) — общий предел для всех путей: агент разработки, агент приёмки, ошибки продукта, разбивка аналитика, системные задачи FORGE. Задачи, созданные решением человека (кнопка у ошибки продукта), предел не тратят.
|
||||||
|
|
||||||
#### Scenario: Шестая задача агента за сутки
|
#### Scenario: Шестая задача агента за сутки
|
||||||
- **GIVEN** в проекте за последние 24 часа агенты завели 5 задач
|
- **GIVEN** в проекте за последние 24 часа агенты завели 5 задач
|
||||||
@ -81,10 +116,16 @@ TBD - created by archiving change pep-197-no-task-loop. Update Purpose after arc
|
|||||||
- **WHEN** агент приёмки находит 3 улучшения
|
- **WHEN** агент приёмки находит 3 улучшения
|
||||||
- **THEN** заводится 1 задача, 2 находки ждут недельной сводки
|
- **THEN** заводится 1 задача, 2 находки ждут недельной сводки
|
||||||
|
|
||||||
#### Scenario: Ошибка продукта не тратит предел
|
#### Scenario: Ошибка продукта при исчерпанном пределе
|
||||||
- **GIVEN** за сутки агенты завели 5 задач
|
- **GIVEN** за сутки заведено 5 задач не от человека
|
||||||
- **WHEN** из ошибки продукта заводится задача
|
- **WHEN** приходит новая ошибка продукта с политикой «в бэклог»
|
||||||
- **THEN** задача создаётся, а агент снова не может завести задачу до конца окна
|
- **THEN** задача не создаётся
|
||||||
|
- **AND** владелец получает сообщение с кнопками решения
|
||||||
|
|
||||||
|
#### Scenario: Решение человека не тратит предел
|
||||||
|
- **GIVEN** за сутки заведено 5 задач не от человека
|
||||||
|
- **WHEN** владелец нажимает «В бэклог» у ошибки продукта
|
||||||
|
- **THEN** задача создаётся
|
||||||
|
|
||||||
#### Scenario: Свой предел у проекта
|
#### Scenario: Свой предел у проекта
|
||||||
- **GIVEN** проекту задан предел 2 в сутки
|
- **GIVEN** проекту задан предел 2 в сутки
|
||||||
|
|||||||
@ -77,7 +77,7 @@ import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId,
|
|||||||
import { internalHosts, writeInternalHosts, createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
import { internalHosts, writeInternalHosts, createEdgeTunnel, edgeConfig, edgeHosts, formatEdgeSync, syncEdge, isProjectPaused, setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||||
import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner";
|
import { branchProtectionState, connectErrorTrackingFromEnv, ensureBranchProtection, pauseProject, resumeProject } from "@peppa/runner";
|
||||||
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits } from "@peppa/core";
|
import { logoutAllUsers, showWelcomeToEveryone, agentTaskSummary, agentTaskTable, getAgentLimits, setAgentLimits, type AgentLimits, DIRECT_ORIGINS, getDirectOrigins, setDirectOrigins } from "@peppa/core";
|
||||||
import { tidyAgentTasks, findForeignPaths, fixForeignPaths } from "@peppa/runner";
|
import { tidyAgentTasks, findForeignPaths, fixForeignPaths } from "@peppa/runner";
|
||||||
import { installCrashReporting, PROVIDER_LABEL, requestSmoke, smokeStatus, type SmokeRun } from "@peppa/core";
|
import { installCrashReporting, PROVIDER_LABEL, requestSmoke, smokeStatus, type SmokeRun } from "@peppa/core";
|
||||||
import { pushTemplateOrAlert, syncTemplate } from "@peppa/runner";
|
import { pushTemplateOrAlert, syncTemplate } from "@peppa/runner";
|
||||||
@ -96,6 +96,7 @@ const USAGE = `peppa — FORGE software factory CLI
|
|||||||
peppa project agent <KEY|KEY-N|--platform> [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel claudeModel codexModel opencodeModel; value - = inherit)
|
peppa project agent <KEY|KEY-N|--platform> [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel claudeModel codexModel opencodeModel; value - = inherit)
|
||||||
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
|
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
|
||||||
peppa project agent-limits <KEY> [inWork=N perPass=N inRepo=N perDay=N|reset] (PEP-197/270: limits for stories made by agents)
|
peppa project agent-limits <KEY> [inWork=N perPass=N inRepo=N perDay=N|reset] (PEP-197/270: limits for stories made by agents)
|
||||||
|
peppa project direct <KEY> [incident|acceptance|analyst|agent=on|off …] (PEP-295: owner's exceptions to «Предложено»)
|
||||||
peppa agent-tasks report | tidy [KEY] [--dry-run] (PEP-197: people vs agents per project; one-off tidy)
|
peppa agent-tasks report | tidy [KEY] [--dry-run] (PEP-197: people vs agents per project; one-off tidy)
|
||||||
peppa project pause|resume <KEY> (PEP-174: agents stop, nothing is sent; resume continues them)
|
peppa project pause|resume <KEY> (PEP-174: agents stop, nothing is sent; resume continues them)
|
||||||
peppa project transfer <KEY> <owner> (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
|
peppa project transfer <KEY> <owner> (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
|
||||||
@ -475,6 +476,20 @@ async function main(): Promise<void> {
|
|||||||
console.log(`${p.key}: stories of agents in work at once ≤ ${limits.inWork}, proposals per pass ≤ ${limits.perPass}, stories of one repository in work ≤ ${limits.inRepo || "no limit"}, proposals of agents per 24 hours ≤ ${limits.perDay}`);
|
console.log(`${p.key}: stories of agents in work at once ≤ ${limits.inWork}, proposals per pass ≤ ${limits.perPass}, stories of one repository in work ≤ ${limits.inRepo || "no limit"}, proposals of agents per 24 hours ≤ ${limits.perDay}`);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
case "project direct": {
|
||||||
|
// PEP-295: the owner's exceptions — stories of these origins skip «Предложено».
|
||||||
|
if (!args[0]) throw new PeppaError(`usage: peppa project direct <KEY> [origin=on|off …] (origins: ${DIRECT_ORIGINS.join(", ")})`);
|
||||||
|
const p = await getProject(db, args[0]);
|
||||||
|
let list: string[] = await getDirectOrigins(db, p.id);
|
||||||
|
for (const arg of args.slice(1)) {
|
||||||
|
const [k = "", v = ""] = arg.split("=");
|
||||||
|
if (v !== "on" && v !== "off") throw new PeppaError(`expected ${k}=on|off`);
|
||||||
|
list = v === "on" ? [...list.filter((o) => o !== k), k] : list.filter((o) => o !== k);
|
||||||
|
}
|
||||||
|
if (args.length > 1) list = await setDirectOrigins(db, p.id, list);
|
||||||
|
console.log(`${p.key}: straight to work without «Делать»: ${list.length ? list.join(", ") : "nothing (everything not from a person waits in «Предложено»)"}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
case "agent-tasks report":
|
case "agent-tasks report":
|
||||||
console.log(agentTaskTable(await agentTaskSummary(db)));
|
console.log(agentTaskTable(await agentTaskSummary(db)));
|
||||||
break;
|
break;
|
||||||
|
|||||||
@ -274,9 +274,11 @@ export async function createBugTask(
|
|||||||
goalId: settings?.goalId ?? undefined,
|
goalId: settings?.goalId ?? undefined,
|
||||||
title: bugTaskTitle(i),
|
title: bugTaskTitle(i),
|
||||||
description: bugTaskDescription(i, reason),
|
description: bugTaskDescription(i, reason),
|
||||||
// PEP-197: an error of the product's users is a breakage — to the backlog at once, marked.
|
// PEP-197: an error of the product's users is a breakage, marked. PEP-295: not decided by a person
|
||||||
|
// (policy, triage) → «Предложено», unless the owner lets errors go to work at once.
|
||||||
origin: "incident",
|
origin: "incident",
|
||||||
severity: "breakage",
|
severity: "breakage",
|
||||||
|
decidedByPerson: by === "pm",
|
||||||
});
|
});
|
||||||
// PEP-270: the decision lands with the status — a reader never sees «task» without what was decided.
|
// PEP-270: the decision lands with the status — a reader never sees «task» without what was decided.
|
||||||
await updateIncident(db, i.id, { ...decided, taskId: ref.task.id, taskCreatedAt: new Date(), status: "task", decidedBy: by });
|
await updateIncident(db, i.id, { ...decided, taskId: ref.task.id, taskCreatedAt: new Date(), status: "task", decidedBy: by });
|
||||||
@ -289,7 +291,7 @@ const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replac
|
|||||||
|
|
||||||
export type IncidentMessage =
|
export type IncidentMessage =
|
||||||
| { kind: "notify" }
|
| { kind: "notify" }
|
||||||
| { kind: "task"; task: TaskRef; started?: boolean; reason?: string | null }
|
| { kind: "task"; task: TaskRef; started?: boolean; reason?: string | null; proposed?: boolean }
|
||||||
| { kind: "ask"; note?: string | null }
|
| { kind: "ask"; note?: string | null }
|
||||||
| { kind: "regressed"; task?: TaskRef | null };
|
| { kind: "regressed"; task?: TaskRef | null };
|
||||||
|
|
||||||
@ -315,13 +317,27 @@ export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i:
|
|||||||
if (i.url) lines.push(`<a href="${esc(i.url)}">${tr("Подробности ошибки")}</a>`);
|
if (i.url) lines.push(`<a href="${esc(i.url)}">${tr("Подробности ошибки")}</a>`);
|
||||||
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
|
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
|
||||||
if (m.kind === "task") {
|
if (m.kind === "task") {
|
||||||
lines.push("", m.started ? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) }) : tr("📥 Задача в бэклоге: {link}", { link: taskLink(m.task) }));
|
lines.push(
|
||||||
|
"",
|
||||||
|
m.started
|
||||||
|
? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) })
|
||||||
|
: m.proposed
|
||||||
|
? tr("💡 Задача ждёт вашего решения в «Предложено»: {link}", { link: taskLink(m.task) })
|
||||||
|
: tr("📥 Задача в бэклоге: {link}", { link: taskLink(m.task) }),
|
||||||
|
);
|
||||||
if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: asIs(esc(clip(m.reason, 500))) }));
|
if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: asIs(esc(clip(m.reason, 500))) }));
|
||||||
} else if (m.kind === "ask") {
|
} else if (m.kind === "ask") {
|
||||||
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
|
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
|
||||||
lines.push("", tr("Что делаем?"));
|
lines.push("", tr("Что делаем?"));
|
||||||
} else if (m.kind === "regressed") {
|
} else if (m.kind === "regressed") {
|
||||||
lines.push("", m.task ? tr("Задача {link} снова в бэклоге.", { link: taskLink(m.task) }) : tr("Задачи нет — решите, что делать."));
|
lines.push(
|
||||||
|
"",
|
||||||
|
m.task
|
||||||
|
? m.task.task.proposed
|
||||||
|
? tr("💡 Задача ждёт вашего решения в «Предложено»: {link}", { link: taskLink(m.task) })
|
||||||
|
: tr("Задача {link} снова в бэклоге.", { link: taskLink(m.task) })
|
||||||
|
: tr("Задачи нет — решите, что делать."),
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">${tr("Ошибки проекта")}</a>`);
|
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">${tr("Ошибки проекта")}</a>`);
|
||||||
}
|
}
|
||||||
@ -335,8 +351,14 @@ export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessag
|
|||||||
const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId));
|
const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId));
|
||||||
if (!project) return 0;
|
if (!project) return 0;
|
||||||
const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL);
|
const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL);
|
||||||
const markup = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? { inline_keyboard: incidentButtons(i.id) } : undefined;
|
// PEP-295: a proposed story carries «Делать» / «Не надо» (the bot knows `p:<task>:do|no`).
|
||||||
const kind = m.kind === "ask" || markup ? "ask" : m.kind;
|
const markup =
|
||||||
|
m.kind === "ask" || (m.kind === "regressed" && !m.task)
|
||||||
|
? { inline_keyboard: incidentButtons(i.id) }
|
||||||
|
: (m.kind === "task" && m.proposed) || (m.kind === "regressed" && m.task?.task.proposed)
|
||||||
|
? { inline_keyboard: [[{ text: `✅ ${tr("Делать")}`, callback_data: `p:${m.task!.task.id}:do` }, { text: `✖️ ${tr("Не надо")}`, callback_data: `p:${m.task!.task.id}:no` }]] }
|
||||||
|
: undefined;
|
||||||
|
const kind = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? "ask" : m.kind;
|
||||||
const taskKey = m.kind === "task" ? m.task.key : m.kind === "regressed" ? m.task?.key : null;
|
const taskKey = m.kind === "task" ? m.task.key : m.kind === "regressed" ? m.task?.key : null;
|
||||||
let sent = 0;
|
let sent = 0;
|
||||||
for (const u of audience) {
|
for (const u of audience) {
|
||||||
|
|||||||
@ -43,7 +43,7 @@ export interface AgentLimits {
|
|||||||
perPass: number;
|
perPass: number;
|
||||||
/** PEP-205: stories of one repository in work at once, whoever made them (0 — no limit); the rest wait «В очереди». */
|
/** PEP-205: stories of one repository in work at once, whoever made them (0 — no limit); the rest wait «В очереди». */
|
||||||
inRepo: number;
|
inRepo: number;
|
||||||
/** PEP-270: proposals of agents (developing and acceptance) per project in the last 24 hours. */
|
/** PEP-270/295: stories not from a person (every path) per project in the last 24 hours. */
|
||||||
perDay: number;
|
perDay: number;
|
||||||
}
|
}
|
||||||
export const DEFAULT_AGENT_LIMITS: AgentLimits = { inWork: 3, perPass: 5, inRepo: 4, perDay: 5 };
|
export const DEFAULT_AGENT_LIMITS: AgentLimits = { inWork: 3, perPass: 5, inRepo: 4, perDay: 5 };
|
||||||
@ -76,18 +76,48 @@ export async function agentTasksInWork(db: Db, projectId: number): Promise<numbe
|
|||||||
return Number(r?.n ?? 0);
|
return Number(r?.n ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── PEP-270: proposals per day ─────────────────────────────────────────────────
|
// ── PEP-295: exceptions of the owner ───────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Origins whose stories may skip «Предложено» — only by the owner's explicit choice (none by default). */
|
||||||
|
export const DIRECT_ORIGINS = ["incident", "acceptance", "analyst", "agent"] as const;
|
||||||
|
export type DirectOrigin = (typeof DIRECT_ORIGINS)[number];
|
||||||
|
const directKey = (projectId: number) => `project.direct-origins:${projectId}`;
|
||||||
|
|
||||||
|
export async function getDirectOrigins(db: Db, projectId: number): Promise<DirectOrigin[]> {
|
||||||
|
const v = await getSetting<string[]>(db, directKey(projectId));
|
||||||
|
return (v ?? []).filter((o): o is DirectOrigin => (DIRECT_ORIGINS as readonly string[]).includes(o));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setDirectOrigins(db: Db, projectId: number, list: string[]): Promise<DirectOrigin[]> {
|
||||||
|
const bad = list.filter((o) => !(DIRECT_ORIGINS as readonly string[]).includes(o));
|
||||||
|
if (bad.length) throw new PeppaError(tr("Неизвестное происхождение задачи: {name}", { name: bad.join(", ") }));
|
||||||
|
const next = [...new Set(list)] as DirectOrigin[];
|
||||||
|
if (next.length) await setSetting(db, directKey(projectId), next);
|
||||||
|
else await deleteSetting(db, directKey(projectId));
|
||||||
|
await logEvent(db, { projectId, type: "direct_origins_changed", payload: { origins: next } });
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── PEP-270 / PEP-295: stories not from a person, per day ──────────────────────
|
||||||
|
|
||||||
/** Origins that spend the daily limit: what agents thought up themselves (not bugs of users, not parts of a person's story). */
|
|
||||||
export const PROPOSAL_ORIGINS = ["agent", "acceptance"] as const;
|
|
||||||
export const PROPOSAL_WINDOW_MS = 86_400_000;
|
export const PROPOSAL_WINDOW_MS = 86_400_000;
|
||||||
|
|
||||||
/** Stories agents filed in the project during the last 24 hours (archived — declined — ones count too). */
|
/**
|
||||||
|
* Stories not from a person filed in the project during the last 24 hours, by every path (archived —
|
||||||
|
* declined — ones count too). A story a person decided to make (the button under an error) does not.
|
||||||
|
*/
|
||||||
export async function proposalsToday(db: Db, projectId: number, now = new Date()): Promise<number> {
|
export async function proposalsToday(db: Db, projectId: number, now = new Date()): Promise<number> {
|
||||||
const [r] = await db
|
const [r] = await db
|
||||||
.select({ n: sql<number>`count(*)` })
|
.select({ n: sql<number>`count(*)` })
|
||||||
.from(tasks)
|
.from(tasks)
|
||||||
.where(and(eq(tasks.projectId, projectId), inArray(tasks.origin, [...PROPOSAL_ORIGINS]), gte(tasks.createdAt, new Date(now.getTime() - PROPOSAL_WINDOW_MS))));
|
.where(
|
||||||
|
and(
|
||||||
|
eq(tasks.projectId, projectId),
|
||||||
|
ne(tasks.origin, "human"),
|
||||||
|
gte(tasks.createdAt, new Date(now.getTime() - PROPOSAL_WINDOW_MS)),
|
||||||
|
sql`${tasks.id} NOT IN (SELECT task_id FROM incidents WHERE task_id IS NOT NULL AND decided_by = 'pm')`,
|
||||||
|
),
|
||||||
|
);
|
||||||
return Number(r?.n ?? 0);
|
return Number(r?.n ?? 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -20,7 +20,7 @@ import { keepQuestionDetails, messageText, stripServiceBlocks } from "./user-tex
|
|||||||
import { defaultMessageType, type MessageType } from "./questions.ts";
|
import { defaultMessageType, type MessageType } from "./questions.ts";
|
||||||
import { renderMain, type AgentMessage } from "./agent-message.ts";
|
import { renderMain, type AgentMessage } from "./agent-message.ts";
|
||||||
import { insertQuestion, setMessageDetails } from "./message-details.ts";
|
import { insertQuestion, setMessageDetails } from "./message-details.ts";
|
||||||
import { touchVersion } from "./task-origin.ts";
|
import { getDirectOrigins, touchVersion } from "./task-origin.ts";
|
||||||
import { clearRolloutWait, rolloutTracked, setRolloutWait } from "./rollout.ts";
|
import { clearRolloutWait, rolloutTracked, setRolloutWait } from "./rollout.ts";
|
||||||
|
|
||||||
export type Task = typeof tasks.$inferSelect;
|
export type Task = typeof tasks.$inferSelect;
|
||||||
@ -59,14 +59,22 @@ export interface NewTask {
|
|||||||
goalId?: number;
|
goalId?: number;
|
||||||
title: string;
|
title: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
/** PEP-197: who made it (default: a person); agents' stories are «Предложено» unless a breakage. */
|
/** PEP-197: who made it (default: a person). PEP-295: anything not from a person is «Предложено». */
|
||||||
origin?: "human" | "acceptance" | "incident" | "analyst" | "agent";
|
origin?: "human" | "acceptance" | "incident" | "analyst" | "agent";
|
||||||
|
/** Only for a person's story; for the others `createTask` decides (PEP-295). */
|
||||||
proposed?: boolean;
|
proposed?: boolean;
|
||||||
|
/** PEP-295: a person already decided to do it (the button under an error of the product): not a proposal. */
|
||||||
|
decidedByPerson?: boolean;
|
||||||
severity?: "breakage" | "important" | "minor" | null;
|
severity?: "breakage" | "important" | "minor" | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createTask(db: Db, t: NewTask): Promise<TaskRef> {
|
export async function createTask(db: Db, input: NewTask): Promise<TaskRef> {
|
||||||
|
const { decidedByPerson, ...t } = input;
|
||||||
if (t.goalId != null) await getGoal(db, t.projectId, t.goalId);
|
if (t.goalId != null) await getGoal(db, t.projectId, t.goalId);
|
||||||
|
// PEP-295: one rule for every path — a story not from a person waits for «Делать» in «Предложено»,
|
||||||
|
// unless a person already decided or the owner made an exception for its origin in this project.
|
||||||
|
const origin = t.origin ?? "human";
|
||||||
|
if (origin !== "human") t.proposed = !decidedByPerson && !(await getDirectOrigins(db, t.projectId)).includes(origin);
|
||||||
// Hand out the per-project number atomically. SQLite transactions are synchronous: no
|
// Hand out the per-project number atomically. SQLite transactions are synchronous: no
|
||||||
// await inside (the driver refuses an async callback).
|
// await inside (the driver refuses an async callback).
|
||||||
const made = db.transaction(
|
const made = db.transaction(
|
||||||
|
|||||||
@ -5,6 +5,7 @@
|
|||||||
// them back into the first story's description.
|
// them back into the first story's description.
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import {
|
import {
|
||||||
|
approveProposal,
|
||||||
addStoryComment,
|
addStoryComment,
|
||||||
changeDecision,
|
changeDecision,
|
||||||
clearSplitPart,
|
clearSplitPart,
|
||||||
@ -25,7 +26,9 @@ import { resolveTaskById, sendToSession } from "./sessions.ts";
|
|||||||
export type DecisionOutcome = "confirmed" | "refine" | "agent" | "fix" | "noted" | "unsplit";
|
export type DecisionOutcome = "confirmed" | "refine" | "agent" | "fix" | "noted" | "unsplit";
|
||||||
|
|
||||||
export async function confirmTaskDecision(db: Db, ref: TaskRef, id: number, by: { login: string }): Promise<DecisionOutcome> {
|
export async function confirmTaskDecision(db: Db, ref: TaskRef, id: number, by: { login: string }): Promise<DecisionOutcome> {
|
||||||
await confirmDecision(db, ref.task, id, by.login);
|
const d = await confirmDecision(db, ref.task, id, by.login);
|
||||||
|
// PEP-295: «Подходит» on the split is the owner's «Делать» for its parts.
|
||||||
|
if (d.kind === "split") for (const part of d.parts ?? []) await approveProposal(db, part, by.login);
|
||||||
return "confirmed";
|
return "confirmed";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,8 @@ import { bugsinkFromEnv, issueFromEvent, parseWebhook, type BugsinkClient, type
|
|||||||
import {
|
import {
|
||||||
addErrorSource,
|
addErrorSource,
|
||||||
autoIncidentTasksToday,
|
autoIncidentTasksToday,
|
||||||
|
logEvent,
|
||||||
|
proposalRoom,
|
||||||
claimNewIncidents,
|
claimNewIncidents,
|
||||||
closeIncidentAsks,
|
closeIncidentAsks,
|
||||||
createBugTask,
|
createBugTask,
|
||||||
@ -133,10 +135,20 @@ async function execute(
|
|||||||
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
|
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
// PEP-295: the daily limit of stories not from a person is shared by every path.
|
||||||
|
if ((await proposalRoom(db, i.projectId, o.now)).room <= 0) {
|
||||||
|
const limitNote = m("Предел задач без вашего решения на сегодня исчерпан — задача не создана.");
|
||||||
|
await logEvent(db, { projectId: i.projectId, type: "proposal_limited", payload: { title: i.title, via: "incident", incident: i.id } });
|
||||||
|
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
|
||||||
|
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
|
||||||
|
return row;
|
||||||
|
}
|
||||||
const ref = await createBugTask(db, i, by, by === "triage" ? reason : null, { decision: base.decision, decisionReason: base.decisionReason });
|
const ref = await createBugTask(db, i, by, by === "triage" ? reason : null, { decision: base.decision, decisionReason: base.decisionReason });
|
||||||
const started = action === "start" ? await startBugTask(db, ref, o) : false;
|
// PEP-295: a story waiting for «Делать» is never started by the policy.
|
||||||
|
const proposed = ref.task.proposed;
|
||||||
|
const started = action === "start" && !proposed ? await startBugTask(db, ref, o) : false;
|
||||||
const row = await getIncident(db, i.id);
|
const row = await getIncident(db, i.id);
|
||||||
await sendIncidentMessage(db, row, { kind: "task", task: ref, started, reason: by === "triage" ? reason : null });
|
await sendIncidentMessage(db, row, { kind: "task", task: ref, started, proposed, reason: by === "triage" ? reason : null });
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -218,8 +230,15 @@ export async function handleRegression(db: Db, i: Incident, o: IncidentOptions =
|
|||||||
let ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
|
let ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
|
||||||
const stamp = `${(o.now ?? new Date()).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
const stamp = `${(o.now ?? new Date()).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
||||||
if (ref && ref.task.status === "done" && (o.now ?? new Date()).getTime() - ref.task.updatedAt.getTime() > REOPEN_WINDOW_MS) {
|
if (ref && ref.task.status === "done" && (o.now ?? new Date()).getTime() - ref.task.updatedAt.getTime() > REOPEN_WINDOW_MS) {
|
||||||
ref = await createBugTask(db, i, "policy", null);
|
// PEP-295: a new story is a proposal and spends the shared daily limit; without room the people decide.
|
||||||
await updateIncident(db, i.id, { status: "regressed" });
|
if ((await proposalRoom(db, i.projectId, o.now)).room <= 0) {
|
||||||
|
await logEvent(db, { projectId: i.projectId, type: "proposal_limited", payload: { title: i.title, via: "incident", incident: i.id } });
|
||||||
|
ref = null;
|
||||||
|
await updateIncident(db, i.id, { status: "regressed", taskId: null });
|
||||||
|
} else {
|
||||||
|
ref = await createBugTask(db, i, "policy", null);
|
||||||
|
await updateIncident(db, i.id, { status: "regressed" });
|
||||||
|
}
|
||||||
} else if (ref) {
|
} else if (ref) {
|
||||||
await moveTask(db, ref, "backlog");
|
await moveTask(db, ref, "backlog");
|
||||||
ref = await resolveTask(db, ref.key);
|
ref = await resolveTask(db, ref.key);
|
||||||
|
|||||||
@ -21,6 +21,8 @@ import {
|
|||||||
intakePending,
|
intakePending,
|
||||||
intakePrompt,
|
intakePrompt,
|
||||||
listTasks,
|
listTasks,
|
||||||
|
logEvent,
|
||||||
|
proposalRoom,
|
||||||
markSplitPart,
|
markSplitPart,
|
||||||
openDecisions,
|
openDecisions,
|
||||||
parseIntakeNote,
|
parseIntakeNote,
|
||||||
@ -65,14 +67,22 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) =
|
|||||||
const note = parseIntakeNote(out.text, task.title);
|
const note = parseIntakeNote(out.text, task.title);
|
||||||
if (!note) throw new Error(m("аналитик ответил не по формату"));
|
if (!note) throw new Error(m("аналитик ответил не по формату"));
|
||||||
// The parts of the request: each checked for a repeat first (3.5), then filed after this story.
|
// The parts of the request: each checked for a repeat first (3.5), then filed after this story.
|
||||||
|
// PEP-295: the parts are proposals (they wait for «Делать» — or «Подходит» on the split) and spend
|
||||||
|
// the shared daily limit; the parts beyond it stay in this story's text.
|
||||||
const parts: TaskRef[] = [];
|
const parts: TaskRef[] = [];
|
||||||
const repeats: string[] = [];
|
const repeats: string[] = [];
|
||||||
|
const limited: string[] = [];
|
||||||
for (const s of note.split) {
|
for (const s of note.split) {
|
||||||
const dup = await checkDuplicate(db, project, s, { log, origin: "analyst" });
|
const dup = await checkDuplicate(db, project, s, { log, origin: "analyst" });
|
||||||
if (dup.kind !== "none" && dup.task.id !== task.id) {
|
if (dup.kind !== "none" && dup.task.id !== task.id) {
|
||||||
repeats.push(`«${s.title}» — ${dup.key}`);
|
repeats.push(`«${s.title}» — ${dup.key}`);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if ((await proposalRoom(db, project.id)).room <= 0) {
|
||||||
|
limited.push(s.title);
|
||||||
|
await logEvent(db, { projectId: project.id, taskId: task.id, type: "proposal_limited", payload: { title: s.title, via: "analyst" } });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const part = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: `${s.description}\n\n_${m("Из разбивки {key}.", { key: ref.key })}_`, origin: "analyst" });
|
const part = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: `${s.description}\n\n_${m("Из разбивки {key}.", { key: ref.key })}_`, origin: "analyst" });
|
||||||
// Formulated by the analyst already: the part does not go through intake again.
|
// Formulated by the analyst already: the part does not go through intake again.
|
||||||
await setIntakeState(db, part.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: `из разбивки ${ref.key}` });
|
await setIntakeState(db, part.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: `из разбивки ${ref.key}` });
|
||||||
@ -86,6 +96,7 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) =
|
|||||||
const splitText = parts.length ? m("Разделила на {n} задач: {list}", { n: parts.length + 1, list: [ref.key, ...parts.map((p) => p.key)].join(", ") }) : "";
|
const splitText = parts.length ? m("Разделила на {n} задач: {list}", { n: parts.length + 1, list: [ref.key, ...parts.map((p) => p.key)].join(", ") }) : "";
|
||||||
const decisions = await setDecisions(db, task.id, note.decisions, parts.length ? { text: splitText, parts: parts.map((p) => p.task.id), deferred: note.deferred } : undefined);
|
const decisions = await setDecisions(db, task.id, note.decisions, parts.length ? { text: splitText, parts: parts.map((p) => p.task.id), deferred: note.deferred } : undefined);
|
||||||
await addIntakeNote(db, task, "analyst", intakeMessage(ref.key, note, { parts: parts.map((p) => p.key), repeats, decisions: openDecisions(decisions) }));
|
await addIntakeNote(db, task, "analyst", intakeMessage(ref.key, note, { parts: parts.map((p) => p.key), repeats, decisions: openDecisions(decisions) }));
|
||||||
|
if (limited.length) await addIntakeNote(db, task, "analyst", m("Не завела отдельными задачами — на сегодня предел новых задач: {list}. Их можно сделать в этой задаче или завести позже.", { list: limited.map((t) => `«${t}»`).join(", ") }));
|
||||||
return { ...state, stage: "done", product: { goal: note.goal, comment: note.comment, title: note.title, split: note.split }, analyst, attempts: 0 };
|
return { ...state, stage: "done", product: { goal: note.goal, comment: note.comment, title: note.title, split: note.split }, analyst, attempts: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -5,6 +5,7 @@
|
|||||||
// one-time offer of that mode to projects created before it existed.
|
// one-time offer of that mode to projects created before it existed.
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import {
|
import {
|
||||||
|
proposalRoom,
|
||||||
archivedLog,
|
archivedLog,
|
||||||
askPmProject,
|
askPmProject,
|
||||||
createTask,
|
createTask,
|
||||||
@ -84,9 +85,14 @@ export async function ensureProductLinkTask(db: Db, project: Project, o: Product
|
|||||||
const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging;
|
const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging;
|
||||||
if (!failed && (healthy || done.length === 0)) return null;
|
if (!failed && (healthy || done.length === 0)) return null;
|
||||||
|
|
||||||
|
// PEP-295: the system story is a proposal too and spends the shared daily limit; no room — the next tick tries again.
|
||||||
|
if ((await proposalRoom(db, project.id, o.now)).room <= 0) {
|
||||||
|
o.log?.(`product link ${project.key}: daily limit of proposals reached`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail ?? archivedLog("releases", failed.id, failed.updatedAt), runUrl: failed.runUrl } : null });
|
const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail ?? archivedLog("releases", failed.id, failed.updatedAt), runUrl: failed.runUrl } : null });
|
||||||
const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description, origin: "acceptance", severity: "breakage" });
|
const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description, origin: "acceptance", severity: "breakage" });
|
||||||
// Already formulated: «продакт» and «аналитик» of the intake skip it.
|
// Already formulated: the analyst of the intake skips it. It waits for «Делать» in «Предложено» (PEP-295).
|
||||||
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена FORGE: продукт не открывается по ссылке" });
|
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена FORGE: продукт не открывается по ссылке" });
|
||||||
await reorderTask(db, ref, { to: "top" });
|
await reorderTask(db, ref, { to: "top" });
|
||||||
await setProductLinkState(db, project.id, { taskId: ref.task.id, at: now });
|
await setProductLinkState(db, project.id, { taskId: ref.task.id, at: now });
|
||||||
|
|||||||
@ -197,12 +197,13 @@ interface Filed {
|
|||||||
key: string;
|
key: string;
|
||||||
title: string;
|
title: string;
|
||||||
severity: Severity;
|
severity: Severity;
|
||||||
|
proposed: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Files the stories the acceptance agent found: not more than the project's limit per pass,
|
* Files the stories the acceptance agent found: not more than the project's limit per pass,
|
||||||
* never what the owner declined, never a repeat (a remark goes to the open story instead).
|
* never what the owner declined, never a repeat (a remark goes to the open story instead).
|
||||||
* An improvement waits in «Предложено»; a breakage goes to the backlog at once, marked.
|
* Every finding waits in «Предложено» (PEP-295: a breakage too — the agent sets the severity itself), marked.
|
||||||
* After the version's finish only breakages are filed; the rest is kept for the weekly message.
|
* After the version's finish only breakages are filed; the rest is kept for the weekly message.
|
||||||
*/
|
*/
|
||||||
export async function fileStories(db: Db, project: Project, stories: ProductReviewReply["stories"], o: { envLabel: string; url: string; log?: (m: string) => void; ignoreFinish?: boolean }): Promise<{ created: Filed[]; breakage: boolean; kept: number }> {
|
export async function fileStories(db: Db, project: Project, stories: ProductReviewReply["stories"], o: { envLabel: string; url: string; log?: (m: string) => void; ignoreFinish?: boolean }): Promise<{ created: Filed[]; breakage: boolean; kept: number }> {
|
||||||
@ -234,18 +235,18 @@ export async function fileStories(db: Db, project: Project, stories: ProductRevi
|
|||||||
// glossary-user: описание задачи, которое читает владелец
|
// glossary-user: описание задачи, которое читает владелец
|
||||||
let description = `${s.description}\n\n_Заведено агентом приёмки${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`;
|
let description = `${s.description}\n\n_Заведено агентом приёмки${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`;
|
||||||
if (dup.kind === "done") description += `\n\n_${dedupSimilarNote(dup.key, dup.doneAt.toISOString().slice(0, 10))}_`;
|
if (dup.kind === "done") description += `\n\n_${dedupSimilarNote(dup.key, dup.doneAt.toISOString().slice(0, 10))}_`;
|
||||||
const isBreakage = s.severity === "breakage";
|
const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity });
|
||||||
const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity, proposed: !isBreakage });
|
|
||||||
// Already formulated: «продакт» and «аналитик» of the intake skip it.
|
// Already formulated: «продакт» and «аналитик» of the intake skip it.
|
||||||
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена агентом приёмки" });
|
await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена агентом приёмки" });
|
||||||
created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity });
|
created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity, proposed: ref.task.proposed });
|
||||||
}
|
}
|
||||||
return { created, breakage, kept };
|
return { created, breakage, kept };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Telegram buttons under the message: per item «Делать» / «Не надо» (`p:<task>:do|no`), then for all. */
|
/** Telegram buttons under the message: per item «Делать» / «Не надо» (`p:<task>:do|no`), then for all. */
|
||||||
export function proposalButtons(items: Array<{ id: number; key: string; severity: string }>, locale: Locale): Array<Array<{ text: string; callback_data: string }>> {
|
export function proposalButtons(items: Array<{ id: number; key: string; severity: string; proposed?: boolean }>, locale: Locale): Array<Array<{ text: string; callback_data: string }>> {
|
||||||
const open = items.filter((i) => i.severity !== "breakage");
|
// PEP-295: every finding is a proposal unless the owner let them go to work at once.
|
||||||
|
const open = items.filter((i) => i.proposed !== false);
|
||||||
if (!open.length) return [];
|
if (!open.length) return [];
|
||||||
const rows = open.map((i) => [
|
const rows = open.map((i) => [
|
||||||
{ text: `✅ ${t(locale, "Делать")} ${i.key}`, callback_data: `p:${i.id}:do` },
|
{ text: `✅ ${t(locale, "Делать")} ${i.key}`, callback_data: `p:${i.id}:do` },
|
||||||
|
|||||||
@ -41,4 +41,14 @@ export const proposals: Record<string, string> = {
|
|||||||
"Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Once a week: improvements found: {n} (important: {k}).",
|
"Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Once a week: improvements found: {n} (important: {k}).",
|
||||||
"По этим задачам решение уже принято.": "A decision on these tasks has already been made.",
|
"По этим задачам решение уже принято.": "A decision on these tasks has already been made.",
|
||||||
"Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "We tidied up: tasks the factory made itself that wait for your decision: {n}. They are in «Suggested» on the board. Nothing was deleted.",
|
"Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "We tidied up: tasks the factory made itself that wait for your decision: {n}. They are in «Suggested» on the board. Nothing was deleted.",
|
||||||
|
// PEP-295
|
||||||
|
"Это решает владелец проекта.": "This is the project owner's decision.",
|
||||||
|
"Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».": "Agents take tasks from product errors into work right away, without your «Do it».",
|
||||||
|
"Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».": "Tasks from product errors wait for your «Do it» in «Suggested».",
|
||||||
|
"Ждать моего решения": "Wait for my decision",
|
||||||
|
"Брать в работу сразу": "Take into work right away",
|
||||||
|
"💡 Задача ждёт вашего решения в «Предложено»: {link}": "💡 The task waits for your decision in «Suggested»: {link}",
|
||||||
|
"Неизвестное происхождение задачи: {name}": "Unknown task origin: {name}",
|
||||||
|
"Предел задач без вашего решения на сегодня исчерпан — задача не создана.": "Today's limit of tasks without your decision is reached — the task was not created.",
|
||||||
|
"Не завела отдельными задачами — на сегодня предел новых задач: {list}. Их можно сделать в этой задаче или завести позже.": "Not filed as separate tasks — today's limit of new tasks is reached: {list}. They can be done in this task or filed later.",
|
||||||
};
|
};
|
||||||
|
|||||||
@ -41,4 +41,14 @@ export const proposals: Record<string, string> = {
|
|||||||
"Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Аптасына бір рет: табылған жақсартулар: {n} (маңыздысы: {k}).",
|
"Раз в неделю: нашёл улучшений: {n} (важных: {k}).": "Аптасына бір рет: табылған жақсартулар: {n} (маңыздысы: {k}).",
|
||||||
"По этим задачам решение уже принято.": "Бұл тапсырмалар бойынша шешім қабылданған.",
|
"По этим задачам решение уже принято.": "Бұл тапсырмалар бойынша шешім қабылданған.",
|
||||||
"Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "Тәртіпке келтірдік: фабрика өзі қосқан және сіздің шешіміңізді күтетін тапсырмалар: {n}. Олар тақтадағы «Ұсынылған» бөлімінде. Ештеңе жойылған жоқ.",
|
"Навели порядок: задач, которые фабрика завела сама, и которые ждут вашего решения: {n}. Они в «Предложено» на доске. Ничего не удалено.": "Тәртіпке келтірдік: фабрика өзі қосқан және сіздің шешіміңізді күтетін тапсырмалар: {n}. Олар тақтадағы «Ұсынылған» бөлімінде. Ештеңе жойылған жоқ.",
|
||||||
|
// PEP-295
|
||||||
|
"Это решает владелец проекта.": "Мұны жоба иесі шешеді.",
|
||||||
|
"Задачи из ошибок продукта агенты берут в работу сразу, без вашего «Делать».": "Өнім қателерінен туған тапсырмаларды агенттер сіздің «Орындау» батырмаңызсыз бірден жұмысқа алады.",
|
||||||
|
"Задачи из ошибок продукта ждут вашего «Делать» в «Предложено».": "Өнім қателерінен туған тапсырмалар «Ұсынылған» ішінде сіздің «Орындау» батырмаңызды күтеді.",
|
||||||
|
"Ждать моего решения": "Менің шешімімді күту",
|
||||||
|
"Брать в работу сразу": "Бірден жұмысқа алу",
|
||||||
|
"💡 Задача ждёт вашего решения в «Предложено»: {link}": "💡 Тапсырма «Ұсынылған» ішінде сіздің шешіміңізді күтеді: {link}",
|
||||||
|
"Неизвестное происхождение задачи: {name}": "Тапсырманың белгісіз шығу тегі: {name}",
|
||||||
|
"Предел задач без вашего решения на сегодня исчерпан — задача не создана.": "Бүгінге сіздің шешіміңізсіз тапсырмалар шегі таусылды — тапсырма құрылмады.",
|
||||||
|
"Не завела отдельными задачами — на сегодня предел новых задач: {list}. Их можно сделать в этой задаче или завести позже.": "Бөлек тапсырма етіп қоспадым — бүгінге жаңа тапсырмалар шегі таусылды: {list}. Оларды осы тапсырмада жасауға немесе кейін қосуға болады.",
|
||||||
};
|
};
|
||||||
|
|||||||
@ -11,9 +11,15 @@ describe("PEP-197: уборка и сводка", () => {
|
|||||||
test("not started stories of agents go to «Предложено»; started ones stay; repeats are marked; one message; nothing deleted", async () => {
|
test("not started stories of agents go to «Предложено»; started ones stay; repeats are marked; one message; nothing deleted", async () => {
|
||||||
const tp = await project({ turns: [] });
|
const tp = await project({ turns: [] });
|
||||||
const p = await core.getProject(db, tp.key);
|
const p = await core.getProject(db, tp.key);
|
||||||
const idle = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки", origin: "acceptance", severity: "important" });
|
// Stories filed before PEP-295 (no «Предложено» flag): what the tidy is for.
|
||||||
const repeat = await core.createTask(db, { projectId: p.id, title: "Подписать кнопки!", origin: "acceptance", severity: "important" });
|
const legacy = async (t: Parameters<typeof core.createTask>[1]) => {
|
||||||
const going = await core.createTask(db, { projectId: p.id, title: "Другая тема", origin: "acceptance" });
|
const ref = await core.createTask(db, t);
|
||||||
|
await db.update(tasks).set({ proposed: false }).where(eq(tasks.id, ref.task.id));
|
||||||
|
return ref;
|
||||||
|
};
|
||||||
|
const idle = await legacy({ projectId: p.id, title: "Подписать кнопки", origin: "acceptance", severity: "important" });
|
||||||
|
const repeat = await legacy({ projectId: p.id, title: "Подписать кнопки!", origin: "acceptance", severity: "important" });
|
||||||
|
const going = await legacy({ projectId: p.id, title: "Другая тема", origin: "acceptance" });
|
||||||
await core.updateTask(db, going, { status: "in_progress" });
|
await core.updateTask(db, going, { status: "in_progress" });
|
||||||
const mine = await core.createTask(db, { projectId: p.id, title: "Просьба человека" });
|
const mine = await core.createTask(db, { projectId: p.id, title: "Просьба человека" });
|
||||||
|
|
||||||
@ -42,7 +48,7 @@ describe("PEP-197: уборка и сводка", () => {
|
|||||||
await core.createTask(db, { projectId: p.id, title: "Первая от агента", origin: "acceptance", proposed: true });
|
await core.createTask(db, { projectId: p.id, title: "Первая от агента", origin: "acceptance", proposed: true });
|
||||||
await core.createTask(db, { projectId: p.id, title: "Вторая от агента", origin: "incident" });
|
await core.createTask(db, { projectId: p.id, title: "Вторая от агента", origin: "incident" });
|
||||||
const row = (await core.agentTaskSummary(db)).find((r) => r.key === p.key)!;
|
const row = (await core.agentTaskSummary(db)).find((r) => r.key === p.key)!;
|
||||||
assert.deepEqual([row.human, row.agents, row.proposed, row.agentsMoreThanHuman], [1, 2, 1, true]);
|
assert.deepEqual([row.human, row.agents, row.proposed, row.agentsMoreThanHuman], [1, 2, 2, true], "PEP-295: an error's story is a proposal too");
|
||||||
assert.match(core.agentTaskTable([row]), new RegExp(`${p.key} \\| 1 \\| 2 \\| 1 \\|`));
|
assert.match(core.agentTaskTable([row]), new RegExp(`${p.key} \\| 1 \\| 2 \\| 2 \\|`));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -264,6 +264,7 @@ describe("PEP-197: stories of agents in work", () => {
|
|||||||
await core.setAutonomy(db, p.id, { level: "auto", wipLimit: 5, ...NO_QUIET });
|
await core.setAutonomy(db, p.id, { level: "auto", wipLimit: 5, ...NO_QUIET });
|
||||||
const make = async (title: string, status: "backlog" | "in_progress") => {
|
const make = async (title: string, status: "backlog" | "in_progress") => {
|
||||||
const ref = await core.createTask(db, { projectId: p.id, title, origin: "acceptance", severity: "breakage" });
|
const ref = await core.createTask(db, { projectId: p.id, title, origin: "acceptance", severity: "breakage" });
|
||||||
|
await core.approveProposal(db, ref.task.id); // PEP-295: the owner said «Делать»
|
||||||
if (status === "in_progress") await core.updateTask(db, ref, { status });
|
if (status === "in_progress") await core.updateTask(db, ref, { status });
|
||||||
return ref;
|
return ref;
|
||||||
};
|
};
|
||||||
|
|||||||
@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
|
|||||||
import { after, before, describe, test } from "node:test";
|
import { after, before, describe, test } from "node:test";
|
||||||
import { core, db, runner, teardown, waitFor } from "./helpers.ts";
|
import { core, db, runner, teardown, waitFor } from "./helpers.ts";
|
||||||
import { MockTelegram } from "../src/mock-telegram.ts";
|
import { MockTelegram } from "../src/mock-telegram.ts";
|
||||||
import { feedback, telegramOutbox, users } from "@peppa/db";
|
import { feedback, tasks, telegramOutbox, users } from "@peppa/db";
|
||||||
import { eq, like } from "drizzle-orm";
|
import { eq, like } from "drizzle-orm";
|
||||||
import type { Bot } from "@peppa/bot";
|
import type { Bot } from "@peppa/bot";
|
||||||
|
|
||||||
@ -163,7 +163,10 @@ describe("Разбор агентом обратной связи", () => {
|
|||||||
test("Scenario: Разбор с тремя вариантами", async () => {
|
test("Scenario: Разбор с тремя вариантами", async () => {
|
||||||
await db.delete(feedback);
|
await db.delete(feedback);
|
||||||
await db.delete(telegramOutbox);
|
await db.delete(telegramOutbox);
|
||||||
|
const tasksBefore = (await db.select({ id: tasks.id }).from(tasks)).length;
|
||||||
const f = await analysed("Кнопка „Принять“ не нажимается", [PNG]);
|
const f = await analysed("Кнопка „Принять“ не нажимается", [PNG]);
|
||||||
|
// PEP-295: the feedback agent only analyses — a story appears only by the superadmin's decision.
|
||||||
|
assert.equal((await db.select({ id: tasks.id }).from(tasks)).length, tasksBefore, "the feedback agent files no story");
|
||||||
assert.equal(f.status, "analyzed");
|
assert.equal(f.status, "analyzed");
|
||||||
assert.equal(f.analysis?.kind, "bug");
|
assert.equal(f.analysis?.kind, "bug");
|
||||||
assert.equal(f.analysis?.options.length, 3);
|
assert.equal(f.analysis?.options.length, 3);
|
||||||
|
|||||||
@ -94,7 +94,7 @@ interface Connected {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** A fresh project connected to (mock) Bugsink, alerts pointed at FORGE, with this policy. */
|
/** A fresh project connected to (mock) Bugsink, alerts pointed at FORGE, with this policy. */
|
||||||
async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2] = {}, opts: { webhook?: boolean } = {}): Promise<Connected> {
|
async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2] = {}, opts: { webhook?: boolean; direct?: boolean } = {}): Promise<Connected> {
|
||||||
const p = await project({ turns: [[{ say: "смотрю ошибку" }]] });
|
const p = await project({ turns: [[{ say: "смотрю ошибку" }]] });
|
||||||
const proj = await core.getProject(db, p.key);
|
const proj = await core.getProject(db, p.key);
|
||||||
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
|
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
|
||||||
@ -106,6 +106,8 @@ async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2
|
|||||||
bugsink.setWebhook(api, r.webhookUrl);
|
bugsink.setWebhook(api, r.webhookUrl);
|
||||||
}
|
}
|
||||||
if (Object.keys(patch).length) await core.updateIncidentSettings(db, proj.id, patch);
|
if (Object.keys(patch).length) await core.updateIncidentSettings(db, proj.id, patch);
|
||||||
|
// PEP-295: the owner's exception — errors go to work without «Делать».
|
||||||
|
if (opts.direct) await core.setDirectOrigins(db, proj.id, ["incident"]);
|
||||||
return { key: p.key, proj, web, api, secret: r.settings.hookSecret };
|
return { key: p.key, proj, web, api, secret: r.settings.hookSecret };
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -228,7 +230,7 @@ describe("Политика инцидентов проекта", () => {
|
|||||||
assert.equal(buttons(m).length, 0);
|
assert.equal(buttons(m).length, 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("backlog: задача-баг под «Стабильностью» со стеком и ссылкой, PM получает сообщение со ссылкой", async () => {
|
test("backlog: задача-баг под «Стабильностью» со стеком и ссылкой в «Предложено», PM получает сообщение с «Делать» (PEP-295)", async () => {
|
||||||
const c = await connected({ policy: "backlog" });
|
const c = await connected({ policy: "backlog" });
|
||||||
await bugsink.capture(c.api, AMOUNT);
|
await bugsink.capture(c.api, AMOUNT);
|
||||||
const i = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "task");
|
const i = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "task");
|
||||||
@ -240,13 +242,26 @@ describe("Политика инцидентов проекта", () => {
|
|||||||
assert.match(t.description!, /billing\/charge\.ts:42 in charge/);
|
assert.match(t.description!, /billing\/charge\.ts:42 in charge/);
|
||||||
assert.ok(t.description!.includes(i.url!));
|
assert.ok(t.description!.includes(i.url!));
|
||||||
assert.match(t.description!, /Условия готовности/);
|
assert.match(t.description!, /Условия готовности/);
|
||||||
|
assert.equal(t.proposed, true, "not decided by a person — waits for «Делать»");
|
||||||
const m = await waitPm("TypeError: amount is undefined", (x) => x.text.includes(t.key));
|
const m = await waitPm("TypeError: amount is undefined", (x) => x.text.includes(t.key));
|
||||||
assert.match(m.text, /Задача в бэклоге/);
|
assert.match(m.text, /Задача ждёт вашего решения в «Предложено»/);
|
||||||
assert.ok(m.text.includes(`http://peppa.test/t/${t.key}`));
|
assert.ok(m.text.includes(`http://peppa.test/t/${t.key}`));
|
||||||
|
assert.deepEqual(buttons(m).map((b) => b.callback_data), [`p:${t.id}:do`, `p:${t.id}:no`]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("start: задача сразу в работе, раннер запущен, PM знает", async () => {
|
test("start без исключения владельца: задача в «Предложено», агент не запускается (PEP-295)", async () => {
|
||||||
const c = await connected({ policy: "start" });
|
const c = await connected({ policy: "start" });
|
||||||
|
await bugsink.capture(c.api, { ...AMOUNT, value: "start proposed" });
|
||||||
|
const i = await waitIncident(c, "TypeError: start proposed", (x) => x.status === "task");
|
||||||
|
await waitPm("TypeError: start proposed", (m) => /Предложено/.test(m.text));
|
||||||
|
const t = (await tasksOf(c)).find((x) => x.id === i.taskId)!;
|
||||||
|
assert.equal(t.status, "backlog");
|
||||||
|
assert.equal(t.proposed, true);
|
||||||
|
assert.equal((await core.listSessions(db, { taskId: t.id })).length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("start с исключением «Ошибки продукта брать в работу сразу»: задача сразу в работе, раннер запущен, PM знает", async () => {
|
||||||
|
const c = await connected({ policy: "start" }, { direct: true });
|
||||||
await bugsink.capture(c.api, { ...AMOUNT, value: "start now" });
|
await bugsink.capture(c.api, { ...AMOUNT, value: "start now" });
|
||||||
const i = await waitIncident(c, "TypeError: start now", (x) => x.status === "task");
|
const i = await waitIncident(c, "TypeError: start now", (x) => x.status === "task");
|
||||||
// The incident points at its task before the task is moved to work.
|
// The incident points at its task before the task is moved to work.
|
||||||
@ -306,7 +321,7 @@ describe("Политика инцидентов проекта", () => {
|
|||||||
test("triage, триажёр уверен: задача в работе, обоснование в задаче и в сообщении", async () => {
|
test("triage, триажёр уверен: задача в работе, обоснование в задаче и в сообщении", async () => {
|
||||||
const prompt = "падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси";
|
const prompt = "падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси";
|
||||||
triage({ rules: [{ match: "PaymentError", action: "start", confidence: 0.92, reason: "падает оплата — по правилам сразу в работу" }] });
|
triage({ rules: [{ match: "PaymentError", action: "start", confidence: 0.92, reason: "падает оплата — по правилам сразу в работу" }] });
|
||||||
const c = await connected({ policy: "triage", triagePrompt: prompt });
|
const c = await connected({ policy: "triage", triagePrompt: prompt }, { direct: true });
|
||||||
await bugsink.capture(c.api, { type: "PaymentError", value: "card declined handler crashed", environment: "prod", release: "a1b2c3", frames: [{ filename: "billing/pay.ts", function: "pay", lineno: 3 }] });
|
await bugsink.capture(c.api, { type: "PaymentError", value: "card declined handler crashed", environment: "prod", release: "a1b2c3", frames: [{ filename: "billing/pay.ts", function: "pay", lineno: 3 }] });
|
||||||
await waitIncident(c, "PaymentError: card declined handler crashed", (x) => x.status === "task");
|
await waitIncident(c, "PaymentError: card declined handler crashed", (x) => x.status === "task");
|
||||||
// The message is the last step of the decision: after it the incident and the task are final.
|
// The message is the last step of the decision: after it the incident and the task are final.
|
||||||
@ -378,6 +393,9 @@ describe("Политика инцидентов проекта", () => {
|
|||||||
// The PM's own decision isn't capped.
|
// The PM's own decision isn't capped.
|
||||||
const r = await runner.decideIncident(db, i.id, "backlog", "mock-pm");
|
const r = await runner.decideIncident(db, i.id, "backlog", "mock-pm");
|
||||||
assert.equal(r.task?.task.status, "backlog");
|
assert.equal(r.task?.task.status, "backlog");
|
||||||
|
// PEP-295: a person decided — not a proposal, and the shared daily limit is not spent.
|
||||||
|
assert.equal(r.task?.task.proposed, false);
|
||||||
|
assert.equal(await core.proposalsToday(db, c.proj.id), 5);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Смена политики: после выбора triage новые ошибки разбирает триажёр по промпту", async () => {
|
test("Смена политики: после выбора triage новые ошибки разбирает триажёр по промпту", async () => {
|
||||||
@ -451,6 +469,7 @@ describe("Проект-образец SBX: ошибка → инцидент →
|
|||||||
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
|
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
|
||||||
for (const s of r.sources) bugsink.setWebhook(s.bugsinkProjectId, r.webhookUrl);
|
for (const s of r.sources) bugsink.setWebhook(s.bugsinkProjectId, r.webhookUrl);
|
||||||
await core.updateIncidentSettings(db, proj.id, { policy: "start" });
|
await core.updateIncidentSettings(db, proj.id, { policy: "start" });
|
||||||
|
await core.setDirectOrigins(db, proj.id, ["incident"]);
|
||||||
const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
|
const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
|
||||||
await bugsink.capture(web, { type: "TypeError", value: "Cannot read properties of undefined (reading 'total')", environment: "prod", release: "sbx001", frames: [{ filename: "app/checkout/page.tsx", function: "Checkout", lineno: 21 }] });
|
await bugsink.capture(web, { type: "TypeError", value: "Cannot read properties of undefined (reading 'total')", environment: "prod", release: "sbx001", frames: [{ filename: "app/checkout/page.tsx", function: "Checkout", lineno: 21 }] });
|
||||||
const entry = await p.waitLog("agent read the bug task", (e) => e.ev === "mcp" && e.tool === "get_task");
|
const entry = await p.waitLog("agent read the bug task", (e) => e.ev === "mcp" && e.tool === "get_task");
|
||||||
|
|||||||
@ -405,7 +405,7 @@ const asked = (projectId: number) => core.createTask(db, { projectId, title: "П
|
|||||||
const byTitle = async (projectId: number, title: string) => (await core.listTasks(db, { projectId, includeArchived: true })).find((t) => t.title === title);
|
const byTitle = async (projectId: number, title: string) => (await core.listTasks(db, { projectId, includeArchived: true })).find((t) => t.title === title);
|
||||||
|
|
||||||
describe("PEP-197: приёмка предлагает, а не запускает", () => {
|
describe("PEP-197: приёмка предлагает, а не запускает", () => {
|
||||||
test("Scenario: Агент приёмки находит улучшение — задача в «Предложено», диспетчер её не берёт; поломка — в бэклоге с пометкой", async () => {
|
test("Scenario: Агент приёмки находит улучшение — задача в «Предложено», диспетчер её не берёт; поломка — тоже в «Предложено» с пометкой (PEP-295)", async () => {
|
||||||
page = REAL_PAGE;
|
page = REAL_PAGE;
|
||||||
const p = await proj();
|
const p = await proj();
|
||||||
await asked(p.id);
|
await asked(p.id);
|
||||||
@ -414,8 +414,10 @@ describe("PEP-197: приёмка предлагает, а не запускае
|
|||||||
const idea = (await byTitle(p.id, "Подписать кнопку «Подобрать»"))!;
|
const idea = (await byTitle(p.id, "Подписать кнопку «Подобрать»"))!;
|
||||||
assert.deepEqual([idea.origin, idea.proposed, idea.severity, idea.status], ["acceptance", true, "important", "backlog"]);
|
assert.deepEqual([idea.origin, idea.proposed, idea.severity, idea.status], ["acceptance", true, "important", "backlog"]);
|
||||||
const broken = (await byTitle(p.id, "Страница не открывается без токена"))!;
|
const broken = (await byTitle(p.id, "Страница не открывается без токена"))!;
|
||||||
assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", false, "breakage", "backlog"], "a breakage goes to the backlog at once, marked");
|
assert.deepEqual([broken.origin, broken.proposed, broken.severity, broken.status], ["acceptance", true, "breakage", "backlog"], "a breakage waits for «Делать» too, marked");
|
||||||
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [broken.id], "the dispatcher sees the breakage only");
|
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [], "the dispatcher sees none of them");
|
||||||
|
await core.resolveProposals(db, [idea.id, broken.id], "important");
|
||||||
|
assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id).sort(), [idea.id, broken.id].sort(), "«Делать важные» takes both");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Scenario: Повтор открытой задачи не создаётся — к ней дописано замечание; похожая сделанная — в «Предложено» с пометкой", async () => {
|
test("Scenario: Повтор открытой задачи не создаётся — к ней дописано замечание; похожая сделанная — в «Предложено» с пометкой", async () => {
|
||||||
@ -452,10 +454,11 @@ describe("PEP-197: приёмка предлагает, а не запускае
|
|||||||
const msg = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id))[0]!;
|
const msg = (await core.discussionMessages(db, (await core.ensureProjectChat(db, p.id)).id))[0]!;
|
||||||
const offer = (await core.chatOffers(db, [msg.id])).get(msg.id)!;
|
const offer = (await core.chatOffers(db, [msg.id])).get(msg.id)!;
|
||||||
assert.equal(offer.kind, "proposals");
|
assert.equal(offer.kind, "proposals");
|
||||||
assert.deepEqual(offer.items!.map((i) => [i.title, i.open]), [["Починить вход", false], ["Убрать слово «ID» с экрана", true], ["Выровнять отступы в шапке", true]]);
|
assert.deepEqual(offer.items!.map((i) => [i.title, i.open]), [["Починить вход", true], ["Убрать слово «ID» с экрана", true], ["Выровнять отступы в шапке", true]], "PEP-295: a breakage waits for «Делать» too");
|
||||||
|
|
||||||
const idea = (await byTitle(p.id, "Убрать слово «ID» с экрана"))!;
|
const idea = (await byTitle(p.id, "Убрать слово «ID» с экрана"))!;
|
||||||
const minor = (await byTitle(p.id, "Выровнять отступы в шапке"))!;
|
const minor = (await byTitle(p.id, "Выровнять отступы в шапке"))!;
|
||||||
|
await runner.decideProposals(db, pm, [(await byTitle(p.id, "Починить вход"))!.id], "do");
|
||||||
await runner.decideProposals(db, pm, [idea.id], "do");
|
await runner.decideProposals(db, pm, [idea.id], "do");
|
||||||
assert.equal((await byTitle(p.id, idea.title))!.proposed, false, "«Делать» moves it to the backlog");
|
assert.equal((await byTitle(p.id, idea.title))!.proposed, false, "«Делать» moves it to the backlog");
|
||||||
await runner.decideProposals(db, pm, [minor.id], "no");
|
await runner.decideProposals(db, pm, [minor.id], "no");
|
||||||
|
|||||||
@ -56,7 +56,11 @@ describe("PEP-145: системная задача при отсутствии
|
|||||||
const backlog = await core.listTasks(db, { projectId: p.id, statuses: ["backlog"] });
|
const backlog = await core.listTasks(db, { projectId: p.id, statuses: ["backlog"] });
|
||||||
assert.equal(backlog[0]!.title, "Продукт должен открываться по ссылке", "first in the backlog");
|
assert.equal(backlog[0]!.title, "Продукт должен открываться по ссылке", "first in the backlog");
|
||||||
assert.match(backlog[0]!.description ?? "", /принято задач: 2/);
|
assert.match(backlog[0]!.description ?? "", /принято задач: 2/);
|
||||||
assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "the dispatcher takes it before the rest");
|
// PEP-295: a system story waits for «Делать» like any story not from a person.
|
||||||
|
assert.equal(backlog[0]!.proposed, true);
|
||||||
|
assert.ok(!(await runner.readyBacklog(db, p.id)).some((t) => t.id === backlog[0]!.id), "the dispatcher does not take it alone");
|
||||||
|
await core.approveProposal(db, backlog[0]!.id);
|
||||||
|
assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "after «Делать» it goes before the rest");
|
||||||
assert.ok(backlog.some((t) => t.id === waiting.task.id));
|
assert.ok(backlog.some((t) => t.id === waiting.task.id));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -54,7 +54,7 @@ describe("PEP-270: предложения агентов", () => {
|
|||||||
assert.ok(ready2.some((x) => x.id === t.id));
|
assert.ok(ready2.some((x) => x.id === t.id));
|
||||||
});
|
});
|
||||||
|
|
||||||
test("Шестая задача агента за сутки не создаётся, агент получает объяснение; ошибка продукта предел не тратит", async () => {
|
test("Шестая задача агента за сутки не создаётся, агент получает объяснение; предел общий для всех путей (PEP-295)", async () => {
|
||||||
const tp = await project({ turns: [] });
|
const tp = await project({ turns: [] });
|
||||||
const p = await core.getProject(db, tp.key);
|
const p = await core.getProject(db, tp.key);
|
||||||
const call = await agent(tp.key);
|
const call = await agent(tp.key);
|
||||||
@ -67,11 +67,11 @@ describe("PEP-270: предложения агентов", () => {
|
|||||||
assert.equal(await byTitle(p.id, "Идея номер 6"), undefined);
|
assert.equal(await byTitle(p.id, "Идея номер 6"), undefined);
|
||||||
assert.equal((await limited(p.id)).length, 1);
|
assert.equal((await limited(p.id)).length, 1);
|
||||||
|
|
||||||
// An error of the product's users and a part of a person's story don't spend the limit.
|
// PEP-295: an error of the product and a part of a split count too; a person's story does not.
|
||||||
await core.createTask(db, { projectId: p.id, title: "Ошибка: TypeError", origin: "incident", severity: "breakage" });
|
await core.createTask(db, { projectId: p.id, title: "Ошибка: TypeError", origin: "incident", severity: "breakage" });
|
||||||
await core.createTask(db, { projectId: p.id, title: "Часть задачи человека", origin: "analyst" });
|
await core.createTask(db, { projectId: p.id, title: "Часть задачи человека", origin: "analyst" });
|
||||||
await core.createTask(db, { projectId: p.id, title: "Задача человека" });
|
await core.createTask(db, { projectId: p.id, title: "Задача человека" });
|
||||||
assert.equal(await core.proposalsToday(db, p.id), 5);
|
assert.equal(await core.proposalsToday(db, p.id), 7);
|
||||||
|
|
||||||
// The window slides: in 24 hours the room is back.
|
// The window slides: in 24 hours the room is back.
|
||||||
assert.equal((await core.proposalRoom(db, p.id, new Date(Date.now() + 86_400_000 + 1000))).room, 5);
|
assert.equal((await core.proposalRoom(db, p.id, new Date(Date.now() + 86_400_000 + 1000))).room, 5);
|
||||||
|
|||||||
181
packages/testkit/test/proposals-only.test.ts
Normal file
181
packages/testkit/test/proposals-only.test.ts
Normal file
@ -0,0 +1,181 @@
|
|||||||
|
// PEP-295: one rule for every story not from a person — it is created in «Предложено» and goes to
|
||||||
|
// work only after «Делать» of the owner or a member; the only exception is the owner's explicit
|
||||||
|
// choice per project; the limit of 5 a day is shared by every path. Paths covered here: the
|
||||||
|
// developing agent (MCP), the acceptance agent (a breakage too), errors of the product, the split of
|
||||||
|
// the analyst, the system story about the link; the reviewer and the feedback agent file nothing —
|
||||||
|
// reviewer.test.ts / feedback.test.ts; the policies of errors end to end — incidents.test.ts.
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||||
|
import { join, relative, resolve } from "node:path";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { after, describe, test } from "node:test";
|
||||||
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||||
|
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||||
|
import { events, tasks } from "@peppa/db";
|
||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
|
import { core, db, project, runner, teardown } from "./helpers.ts";
|
||||||
|
|
||||||
|
// No model for the repeat check: a failing call means «not a repeat».
|
||||||
|
process.env.PEPPA_INTAKE_BIN = "/nonexistent/mock-intake";
|
||||||
|
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||||||
|
|
||||||
|
after(teardown);
|
||||||
|
|
||||||
|
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||||||
|
|
||||||
|
async function agent(projectKey: string) {
|
||||||
|
const [a, b] = InMemoryTransport.createLinkedPair();
|
||||||
|
await createAgentServer(db, { defaultKey: projectKey }).connect(a);
|
||||||
|
const client = new Client({ name: "mock-agent", version: "0" });
|
||||||
|
await client.connect(b);
|
||||||
|
return async (name: string, args: Record<string, unknown> = {}) => {
|
||||||
|
const r = await client.callTool({ name, arguments: args });
|
||||||
|
return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fresh() {
|
||||||
|
const tp = await project({ turns: [] });
|
||||||
|
const p = await core.getProject(db, tp.key);
|
||||||
|
// «Сам берёт»: the dispatcher would take anything ready — the rule must hold anyway.
|
||||||
|
await core.setAutonomy(db, p.id, { pick: "auto" });
|
||||||
|
return { tp, p };
|
||||||
|
}
|
||||||
|
const byTitle = async (projectId: number, title: string) => (await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.title, title))))[0]!;
|
||||||
|
const ready = async (projectId: number) => (await runner.readyBacklog(db, projectId)).map((t) => t.id);
|
||||||
|
|
||||||
|
describe("PEP-295: задача не от человека — только через «Предложено»", () => {
|
||||||
|
test("Scenario Outline: каждое происхождение не от человека создаётся в «Предложено»; задача человека — нет", async () => {
|
||||||
|
const { p } = await fresh();
|
||||||
|
for (const origin of ["agent", "acceptance", "incident", "analyst"] as const) {
|
||||||
|
// Even when a caller asks for the backlog, the rule wins.
|
||||||
|
const ref = await core.createTask(db, { projectId: p.id, title: `от ${origin}`, origin, proposed: false });
|
||||||
|
assert.equal(ref.task.proposed, true, `${origin}: «Предложено»`);
|
||||||
|
assert.ok(!(await ready(p.id)).includes(ref.task.id), `${origin}: the dispatcher does not see it`);
|
||||||
|
}
|
||||||
|
const mine = await core.createTask(db, { projectId: p.id, title: "от человека" });
|
||||||
|
assert.equal(mine.task.proposed, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: решение человека — задача сразу в бэклоге и не тратит предел", async () => {
|
||||||
|
const { p } = await fresh();
|
||||||
|
const ref = await core.createTask(db, { projectId: p.id, title: "Ошибка: решил человек", origin: "incident", severity: "breakage", decidedByPerson: true });
|
||||||
|
assert.equal(ref.task.proposed, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: исключение владельца — только для своего происхождения и только в своём проекте", async () => {
|
||||||
|
const { p } = await fresh();
|
||||||
|
const { p: other } = await fresh();
|
||||||
|
assert.deepEqual(await core.getDirectOrigins(db, p.id), [], "no exceptions by default");
|
||||||
|
await core.setDirectOrigins(db, p.id, ["incident"]);
|
||||||
|
assert.equal((await core.createTask(db, { projectId: p.id, title: "ошибка напрямую", origin: "incident", severity: "breakage" })).task.proposed, false);
|
||||||
|
assert.equal((await core.createTask(db, { projectId: p.id, title: "находка приёмки", origin: "acceptance", severity: "breakage" })).task.proposed, true, "other origins still wait");
|
||||||
|
assert.equal((await core.createTask(db, { projectId: other.id, title: "ошибка в другом проекте", origin: "incident" })).task.proposed, true, "other projects still wait");
|
||||||
|
await assert.rejects(core.setDirectOrigins(db, p.id, ["human"]), /Неизвестное происхождение/);
|
||||||
|
await core.setDirectOrigins(db, p.id, []);
|
||||||
|
assert.equal((await core.createTask(db, { projectId: p.id, title: "ошибка снова ждёт", origin: "incident" })).task.proposed, true);
|
||||||
|
const log = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "direct_origins_changed")));
|
||||||
|
assert.equal(log.length, 2, "the owner's choice is in the journal");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: агент разработки через MCP — в «Предложено»", async () => {
|
||||||
|
const { tp, p } = await fresh();
|
||||||
|
const call = await agent(tp.key);
|
||||||
|
assert.equal((await call("create_task", { title: "Экспорт в CSV" })).isError, false);
|
||||||
|
const t = await byTitle(p.id, "Экспорт в CSV");
|
||||||
|
assert.deepEqual([t.origin, t.proposed], ["agent", true]);
|
||||||
|
assert.ok(!(await ready(p.id)).includes(t.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: поломка от агента приёмки — в «Предложено» с пометкой, «Делать» отдаёт её в бэклог", async () => {
|
||||||
|
const { p } = await fresh();
|
||||||
|
const filed = await runner.fileStories(db, p, [{ title: "Кнопка оплаты не работает", description: "Оплата падает.", severity: "breakage" }], { envLabel: "staging", url: "", ignoreFinish: true });
|
||||||
|
const t = await byTitle(p.id, "Кнопка оплаты не работает");
|
||||||
|
assert.deepEqual([t.origin, t.severity, t.proposed, t.status], ["acceptance", "breakage", true, "backlog"]);
|
||||||
|
assert.equal(filed.created[0]!.proposed, true);
|
||||||
|
assert.ok(!(await ready(p.id)).includes(t.id));
|
||||||
|
const buttons = runner.proposalButtons(filed.created, "ru").flat().map((b) => b.callback_data);
|
||||||
|
assert.ok(buttons.includes(`p:${t.id}:do`), "the owner gets «Делать» for a breakage too");
|
||||||
|
await core.approveProposal(db, t.id);
|
||||||
|
assert.ok((await ready(p.id)).includes(t.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: системная задача о ссылке — в «Предложено»; без места в пределе не заводится", async () => {
|
||||||
|
const { p } = await fresh();
|
||||||
|
const done = await core.createTask(db, { projectId: p.id, title: "Каталог" });
|
||||||
|
await core.updateTask(db, done, { status: "done" });
|
||||||
|
// The limit is used up: the system story waits for the next tick.
|
||||||
|
for (let i = 0; i < 5; i++) await core.createTask(db, { projectId: p.id, title: `предложение ${i}`, origin: "agent" });
|
||||||
|
assert.equal(await runner.ensureProductLinkTask(db, p), null);
|
||||||
|
// A day later there is room again.
|
||||||
|
const key = await runner.ensureProductLinkTask(db, p, { now: new Date(Date.now() + 86_400_000 + 1000) });
|
||||||
|
assert.ok(key);
|
||||||
|
const t = (await core.resolveTask(db, key)).task;
|
||||||
|
assert.equal(t.title, core.PRODUCT_LINK_TITLE);
|
||||||
|
assert.equal(t.proposed, true);
|
||||||
|
assert.ok(!(await ready(p.id)).includes(t.id));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: части разбивки — в «Предложено»; «Подходит» у разбивки отдаёт их в бэклог", async () => {
|
||||||
|
const { tp, p } = await fresh();
|
||||||
|
const main = await core.resolveTask(db, tp.taskKey);
|
||||||
|
const part = await core.createTask(db, { projectId: p.id, title: "Часть 2", origin: "analyst" });
|
||||||
|
await core.markSplitPart(db, part.task.id, main.task.id);
|
||||||
|
assert.equal(part.task.proposed, true);
|
||||||
|
const [d] = await core.setDecisions(db, main.task.id, [], { text: "Разделила на 2 задачи", parts: [part.task.id], deferred: [] });
|
||||||
|
assert.equal(d!.kind, "split");
|
||||||
|
await runner.confirmTaskDecision(db, main, d!.id, { login: "mock-pm" });
|
||||||
|
assert.equal((await core.resolveTask(db, part.key)).task.proposed, false, "«Подходит» is the owner's «Делать»");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Scenario: предел 5 в сутки — общий для всех путей", async () => {
|
||||||
|
const { tp, p } = await fresh();
|
||||||
|
await core.createTask(db, { projectId: p.id, title: "ошибка", origin: "incident" });
|
||||||
|
await core.createTask(db, { projectId: p.id, title: "часть", origin: "analyst" });
|
||||||
|
await core.createTask(db, { projectId: p.id, title: "находка", origin: "acceptance" });
|
||||||
|
await core.createTask(db, { projectId: p.id, title: "ссылка", origin: "acceptance", severity: "breakage" });
|
||||||
|
await core.createTask(db, { projectId: p.id, title: "задача человека" });
|
||||||
|
assert.deepEqual(await core.proposalRoom(db, p.id), { room: 1, limit: 5, used: 4 });
|
||||||
|
const call = await agent(tp.key);
|
||||||
|
assert.equal((await call("create_task", { title: "пятая" })).isError, false);
|
||||||
|
const sixth = await call("create_task", { title: "шестая" });
|
||||||
|
assert.equal(sixth.isError, true, "the developing agent is refused when other paths used the limit");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("Каждый вызов createTask в коде — известный путь (новый путь создания задачи не обойдёт правило незаметно)", () => {
|
||||||
|
// Path → how the rule holds there. A new call site fails this test until it is classified here.
|
||||||
|
const KNOWN: Record<string, string> = {
|
||||||
|
"packages/core/src/feedback.ts": "human — решение суперадмина по обращению",
|
||||||
|
"packages/core/src/incidents.ts": "incident — «Предложено», кроме решения человека и исключения владельца",
|
||||||
|
"packages/mcp/src/manager.ts": "human — человек через свой ИИ-клиент",
|
||||||
|
"packages/mcp/src/agent.ts": "agent — «Предложено»",
|
||||||
|
"packages/cli/src/index.ts": "human — администратор",
|
||||||
|
"packages/runner/src/product-link.ts": "acceptance — «Предложено»",
|
||||||
|
"packages/runner/src/product-review.ts": "acceptance — «Предложено»",
|
||||||
|
"packages/runner/src/intake.ts": "analyst — «Предложено»",
|
||||||
|
"packages/runner/src/message-intent.ts": "human — кнопка «Создать» в чате",
|
||||||
|
"packages/runner/src/runners.ts": "human — «Оформить стори» из свободного раннера",
|
||||||
|
"packages/runner/src/planner.ts": "human — план эпика применяет человек",
|
||||||
|
"packages/runner/src/gitea-events.ts": "human — issue владельца или участника",
|
||||||
|
"apps/web/app/(app)/actions.ts": "human — «+ Задача»",
|
||||||
|
"apps/bot/src/bot.ts": "human — сообщение в Telegram",
|
||||||
|
};
|
||||||
|
const found = new Set<string>();
|
||||||
|
const walk = (dir: string) => {
|
||||||
|
for (const name of readdirSync(dir)) {
|
||||||
|
if (name === "node_modules" || name === ".next" || name === "test") continue;
|
||||||
|
const path = join(dir, name);
|
||||||
|
if (statSync(path).isDirectory()) walk(path);
|
||||||
|
else if (/\.tsx?$/.test(name) && /\bcreateTask\(db,/.test(readFileSync(path, "utf8"))) found.add(relative(ROOT, path));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (const dir of ["packages/core/src", "packages/runner/src", "packages/mcp/src", "packages/cli/src", "apps/web", "apps/bot/src"]) walk(join(ROOT, dir));
|
||||||
|
assert.deepEqual([...found].sort(), Object.keys(KNOWN).sort());
|
||||||
|
// Paths not from a person pass their origin: the rule in createTask sees them.
|
||||||
|
for (const [file, why] of Object.entries(KNOWN)) {
|
||||||
|
if (why.startsWith("human")) continue;
|
||||||
|
const origin = why.split(" ")[0];
|
||||||
|
assert.match(readFileSync(join(ROOT, file), "utf8"), new RegExp(`createTask\\(db,[^;]*origin: "${origin}"`, "s"), `${file} passes origin ${origin}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -103,6 +103,8 @@ describe("Агент-ревьюер до ревью PM", () => {
|
|||||||
const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task");
|
const tool = await t.p.waitLog("update_task answered", (e) => e.ev === "mcp" && e.tool === "update_task");
|
||||||
assert.match(String(tool.text), /reviewer agent is checking/);
|
assert.match(String(tool.text), /reviewer agent is checking/);
|
||||||
await t.p.waitLog("findings delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("деление на ноль возвращает Infinity") && String(e.prompt).includes("src/divide.ts:1"));
|
await t.p.waitLog("findings delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("деление на ноль возвращает Infinity") && String(e.prompt).includes("src/divide.ts:1"));
|
||||||
|
// PEP-295: the reviewer's remarks go to the agent; no story is filed.
|
||||||
|
assert.deepEqual((await core.listTasks(db, { projectId: t.proj.id, includeArchived: true })).map((x) => x.id), [(await t.ref()).task.id], "the reviewer files no story");
|
||||||
const [call] = calls();
|
const [call] = calls();
|
||||||
assert.equal(call?.story, t.p.taskKey);
|
assert.equal(call?.story, t.p.taskKey);
|
||||||
assert.ok(call?.diff, "the reviewer got the PR diff");
|
assert.ok(call?.diff, "the reviewer got the PR diff");
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user