PEP-278: принятая задача «ждёт обновления», пока её коммит не работает

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-26 08:03:48 +00:00
parent 1143d10fa8
commit 4ba532afc8
26 changed files with 497 additions and 13 deletions

View File

@ -41,7 +41,7 @@ import { setProjectPoolAction } from "../../subscriptions/actions";
import { JournalFilters, JournalList, MetricsTab, ProjectBudgetPanel } from "@/components/Accounting";
import { saveProjectBudgetAction } from "../../actions";
// PEP-127: on its own line — the long @peppa/core import above is edited by every story.
import { delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
import { awaitingRollout, ROLLOUT_LABEL, delayedTaskIds, taskDelayLine, pendingQuestions, listPendingAccepts, PENDING_ACCEPT_LABEL, PLATFORM_DELAY_LABEL } from "@peppa/core";
import { trashDaysLeft } from "@peppa/core";
import { queuePositions, workLine } from "@peppa/core";
import { WorkLine } from "@/components/WorkLine";
@ -157,6 +157,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const epicTitle = new Map(epics.map((e) => [e.id, e.title]));
const agentNames = await taskAgentNames(db, p.id);
const accepted = await listPendingAccepts(db);
// PEP-278: accepted stories whose changes do not run yet.
const rollout = await awaitingRollout(db, tasks.filter((x) => x.status === "done").map((x) => x.id));
// PEP-150: the delay line — not on a story whose question waits for the owner.
// PEP-209: the acceptance page — every story in review on one screen.
const toAccept = tasks.filter((x) => x.status === "review" && !x.archivedAt).length;
@ -189,6 +191,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
blocked: x.status === "backlog" ? blockedLabel(deps.get(x.id)) : null,
agent: agentNames.get(x.id) ?? null,
accepted: accepted.has(x.id) ? t.text(PENDING_ACCEPT_LABEL) : null,
rollout: rollout.has(x.id) ? t.text(ROLLOUT_LABEL) : null,
delayed: delayed.has(x.id) && x.status !== "done" ? t.text(delayLines.get(x.id) ?? PLATFORM_DELAY_LABEL) : null,
queued: queued.get(x.id) ?? null,
hold: holds.has(x.id) ? t.text(holds.get(x.id)!.text) : null,

View File

@ -28,6 +28,7 @@ import {
parseTasks,
prGate,
getPendingAccept,
getRolloutWait,
PENDING_ACCEPT_LABEL,
PLATFORM_DELAY_LABEL,
taskDelayed,
@ -136,6 +137,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
.map((r) => (r.logTail || r.state === "success" || r.state === "pending" ? r : { ...r, logTail: archivedLog("checks", r.id, r.updatedAt) }))
: [];
const pendingAccept = await getPendingAccept(db, task.id);
// PEP-278: accepted, but the version with the changes is not running yet.
const rollout = task.status === "done" && !!(await getRolloutWait(db, task.id));
// PEP-150: a delay on the platform's side — one line instead of a message to the owner.
// Not while a question waits for the owner: «от вас ничего не нужно» would not be true.
const delayed = !task.archivedAt && task.status !== "done" && !questions.some((q) => !q.answeredAt) && (await taskDelayed(db, task.id));
@ -271,6 +274,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
refining,
waitsFor: blockers.filter((b) => b.open).map((b) => b.title),
accepted: !!pendingAccept,
rollout,
delayed,
delayLine,
// PEP-182: no agent yet because all are busy — the place in the queue.
@ -441,7 +445,7 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
}
title={
<>
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <LiveTaskStatus taskId={task.id} status={task.status} />}
<span className="font-mono text-primary">{ref.key}</span> {task.title} {engineer && <LiveTaskStatus taskId={task.id} status={task.status} rollout={rollout} />}
{pendingAccept && <Badge variant="ok" className="ml-1.5 align-middle whitespace-normal">{t.text(PENDING_ACCEPT_LABEL)}</Badge>}
{engineer && hold && <Badge variant="warn" className="ml-1.5 align-middle whitespace-normal">{t.text(hold.text)}</Badge>}
{engineer && delayed && <Badge variant="muted" className="ml-1.5 align-middle whitespace-normal">{t.text(delayLine ?? PLATFORM_DELAY_LABEL)}</Badge>}

View File

@ -35,6 +35,8 @@ export interface Card {
refining?: string | null;
/** PEP-127: accepted over a conflict — the agent updates the changes, the story closes by itself. */
accepted?: string | null;
/** PEP-278: accepted, the version with the changes is not running yet. */
rollout?: string | null;
/** PEP-150: a delay on the platform's side — nothing is needed from the owner. */
delayed?: string | null;
/** PEP-247: in work without an agent for a lawful reason (pause, no subscription, budget). */
@ -242,6 +244,11 @@ export function Board({ cards: server, back }: { cards: Card[]; back: string })
{card.accepted}
</Badge>
)}
{card.rollout && (
<Badge variant="info" className="self-start whitespace-normal text-left" data-rollout>
{card.rollout}
</Badge>
)}
{card.delayed && (
<Badge variant="muted" className="self-start whitespace-normal text-left">
{card.delayed}

View File

@ -7,7 +7,7 @@ import { useT } from "@/components/I18n";
import { useLiveIsland } from "@/lib/live";
import { TASK_STATUS } from "@/lib/status";
export function LiveTaskStatus({ taskId, status: initial }: { taskId: number; status: string }) {
export function LiveTaskStatus({ taskId, status: initial, rollout = false }: { taskId: number; status: string; /** PEP-278: done, the version with the changes is not running yet. */ rollout?: boolean }) {
const t = useT();
const [status, setStatus] = useState(initial);
useEffect(() => setStatus(initial), [initial]);
@ -16,9 +16,10 @@ export function LiveTaskStatus({ taskId, status: initial }: { taskId: number; st
if (row) setStatus(row.status);
return []; // the page around depends on the status too
});
const s = TASK_STATUS[status] ?? { label: status, tone: "muted" as const };
const shown = status === "done" && rollout ? "rollout" : status;
const s = TASK_STATUS[shown] ?? { label: shown, tone: "muted" as const };
return (
<Badge variant={s.tone} data-live-status={status}>
<Badge variant={s.tone} data-live-status={shown}>
{t.text(s.label)}
</Badge>
);

View File

@ -11,6 +11,8 @@ export const TASK_STATUS: Record<string, { label: string; tone: Tone }> = {
in_progress: { label: m("В работе"), tone: "info" },
review: { label: m("Ревью"), tone: "ok" },
done: { label: m("Готово"), tone: "ok" },
// PEP-278: not a status of its own — `done` whose changes do not run yet (`rollout.wait`).
rollout: { label: m("Принято, ждёт обновления"), tone: "info" },
blocked: { label: m("Блок"), tone: "danger" },
};

View File

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-26

View File

@ -0,0 +1,34 @@
## Context
Статус `done` читают десятки мест: автопубликация (`autoPublish` ждёт, что все задачи версии `done`),
версия проекта (PEP-197), метрики, дайджесты, доска, «Готово» в Telegram. Новый статус в enum задачи
сломал бы их все и потребовал бы миграции.
## Decisions
1. **Не новый статус, а отметка поверх `done`.** `settings` `rollout.wait:<taskId>` `{at, key, sha?}`
(без миграции, как `accept.pending`). Ставит `updateTask` при переходе в `done`, снимает — при уходе из `done`
или когда изменения заработали. Всё, что смотрит на `done`, работает как раньше; показ «ждёт обновления»
— только на экранах.
2. **Кого касается.** Задача с результатом в коде проекта (`prUrl`) и проект, у которого изменения
выкладываются: платформа (`PEPPA_PLATFORM_KEY`) или проект, у которого уже была здоровая версия
staging/prod. Проект без выкладки (нет ни одной здоровой версии) — сразу «Готово», как раньше: ждать нечего.
3. **Коммит мержа.** Тик берёт PR у Gitea: `merge_commit_sha`, а у PR, закрытого без мержа (PEP-93: всё уже в
main) — голову PR. Gitea недоступна — попытка в следующую минуту.
4. **Платформа.** Работает = коммит мержа — предок (или равен) коммита живого веба. Коммит живого веба —
`heartbeat:web`.commit (тот же `NEXT_PUBLIC_PEPPA_COMMIT_FULL`, что отдаёт `/api/health`), без сетевого запроса.
Предок — `git merge-base --is-ancestor` в корне платформы (`PEPPA_ROOT`); коммита ещё нет в копии — значит,
не выкачен (выкатка приносит его). Здоровая версия prod платформы (`releases`) тоже считается.
5. **Проекты пользователей.** Работает = здоровая версия staging **или** prod, в задачах которой есть ключ
задачи или чей коммит равен коммиту мержа. Staging — «версия для проверки», её владелец открывает первой;
ждать prod при режиме «по кнопке» значило бы держать задачу незакрытой до решения владельца — это ломает
текущий путь (решение по описанию стори: «если это не ломает путь приёмки»).
6. **Слова.** В описании стори — «ждёт выкатки», но «выкатка» в колонке «Нельзя» словаря. На экране:
«Принято, ждёт обновления»; в чате: «✅ Задача принята — изменения заработают после обновления версии» и
«🚀 Изменения задачи уже работают — задача готова».
7. **Старые задачи** (`done` до выкатки этой версии) отметки не имеют — «Готово», как было.
## Risks
- В контейнере нет git-копии платформы → коммит не проверить, задача висит «ждёт обновления». Тот же корень
использует `platformBuildTick`; на сервере он есть. Отметку не снимаем по таймеру: лучше честно ждать.

View File

@ -0,0 +1,32 @@
## Why
После «Принять» задача сразу показывается «Готово», хотя её изменения ещё не работают у пользователей:
у платформы (PEP) смерженный коммит живёт в `main`, пока его не выкатили (`scripts/platform-deploy.sh`),
у проектов — пока выкладка не стала здоровой. Владелец видит «Готово», открывает продукт — а изменений нет.
План «FORGE после переезда» (24.11.2026, шаг 1.4): готово — только когда коммит на проде.
## What Changes
- Принятая задача с результатом в коде проекта, чьи версии выкладываются, получает отметку «ждёт обновления»
(`settings` `rollout.wait:<taskId>`) — статус задачи остаётся `done`, весь путь приёмки (мерж, автомерж,
автозакрытие, «Показать всем», версия проекта) не меняется.
- Вачдог (`rolloutTick`, раз в минуту) снимает отметку, когда коммит мержа работает:
платформа — входит в коммит живого веба (`heartbeat:web`.commit = `/api/health`), проект — есть здоровая
версия staging или prod с этой задачей/коммитом. Событие `task_rolled_out` → строка в чате задачи.
- Экран: доска (плашка на карточке «Готово»), страница задачи (значок статуса и карточка «Продакта»),
чат (значок треда, строка «принята — появится после обновления», затем «изменения уже работают»).
## Capabilities
### New Capabilities
### Modified Capabilities
- `delivery-pipeline`: «Готово» после принятия — только когда изменения работают.
## Impact
- `packages/core/src/rollout.ts` (новый), `tasks.ts` (`updateTask` ставит/снимает отметку), `chats.ts` (тексты),
`story-product.ts`, `gitea.ts` (`merge_commit_sha`).
- `packages/runner/src/rollout.ts` (новый), `watchdog.ts` (тик).
- Веб: `lib/status.ts`, `LiveTaskStatus`, `Board`, страница проекта, страница задачи, чаты.
- Мок `mock-gitea`: `merge_commit_sha` у смерженного PR.

View File

@ -0,0 +1,38 @@
## ADDED Requirements
### Requirement: «Готово» — когда изменения работают
Принятая задача (статус `done`) с результатом в коде проекта, чьи версии выкладываются (платформа или проект
с хотя бы одной здоровой версией staging/prod), SHALL показываться «Принято, ждёт обновления» на доске,
странице задачи и в чате, пока коммит её мержа не работает: для платформы — пока он не входит в коммит живого
веба (`/api/health`), для проекта — пока нет здоровой версии staging или prod с этой задачей. После этого
задача SHALL показываться «Готово», а в чат задачи SHALL прийти одна строка «изменения уже работают».
Статус задачи SHALL оставаться `done`: путь приёмки не меняется.
#### Scenario: Платформа: принята, но не выкачена
- **GIVEN** задача платформы PEP-7 принята, её PR смержен коммитом «m1»
- **AND** живой веб работает на коммите, в который «m1» не входит
- **WHEN** вачдог проверяет принятые задачи
- **THEN** на доске у PEP-7 плашка «Принято, ждёт обновления»
- **AND** в чате задачи строка «Задача принята — изменения заработают после обновления версии»
#### Scenario: Платформа: выкачена
- **GIVEN** задача PEP-7 ждёт обновления, коммит мержа «m1»
- **WHEN** живой веб перезапущен на коммите, потомке «m1», и вачдог проверяет принятые задачи
- **THEN** плашки нет, задача «Готово»
- **AND** в чате задачи одна строка «Изменения задачи уже работают — задача готова»
#### Scenario: Проект: здоровая версия для проверки
- **GIVEN** у проекта SHOP была здоровая версия staging, задача SHOP-3 принята и ждёт обновления
- **WHEN** приходит отчёт о здоровой версии staging с задачей SHOP-3
- **THEN** после проверки вачдога SHOP-3 показывается «Готово»
#### Scenario: Проект без выкладки
- **GIVEN** у проекта NOD не было ни одной версии staging или prod
- **WHEN** задачу NOD-1 принимают
- **THEN** NOD-1 сразу «Готово», отметки ожидания нет
#### Scenario: Сломанная версия не считается
- **GIVEN** задача SHOP-3 ждёт обновления
- **WHEN** версия staging с SHOP-3 откатилась (`rolled_back`)
- **THEN** SHOP-3 по-прежнему «Принято, ждёт обновления»

View File

@ -0,0 +1,20 @@
## 1. Ядро
- [ ] 1.1 `core/rollout.ts`: отметка `rollout.wait:<taskId>`, `rolloutTracked`, `markRollout`/`clearRollout`, `awaitingRollout`, проверка «работает» для платформы и проекта
- [ ] 1.2 `updateTask`: ставит отметку при переходе в `done` (и `rollout: true` в событии), снимает при уходе из `done`
- [ ] 1.3 `GiteaPull.merge_commit_sha`, мок `mock-gitea` отдаёт его у смерженного PR
- [ ] 1.4 Чат: текст `done` с ожиданием и событие `task_rolled_out`; i18n en/kk
## 2. Вачдог
- [ ] 2.1 `runner/rollout.ts` `rolloutTick`: коммит мержа из Gitea, проверка, снятие отметки, событие `task_rolled_out`
- [ ] 2.2 Подключить тик в вачдог (раз в минуту, `PEPPA_ROLLOUT=off`)
## 3. Экраны
- [ ] 3.1 `TASK_STATUS.rollout` «Принято, ждёт обновления»; доска — плашка; страница задачи (значок и карточка «Продакта»); чат (значок треда)
## 4. Проверка
- [ ] 4.1 Тест `rollout.test.ts` по сценариям спеки (падает без изменения)
- [ ] 4.2 lint, typecheck, тесты

View File

@ -7,6 +7,7 @@ import { formatTaskKey } from "@peppa/shared";
import { and, asc, desc, eq, inArray, isNotNull, isNull, sql } from "drizzle-orm";
import { listPendingAccepts } from "./accept-pending.ts";
import { delayedTaskIds } from "./platform-delay.ts";
import { awaitingRollout } from "./rollout.ts";
import { threadTitle, type Chat } from "./chats.ts";
import { questionType } from "./questions.ts";
import { getSetting, setSetting } from "./settings.ts";
@ -52,7 +53,7 @@ const LINE = 140;
/** Which group a story thread belongs to. */
export function threadGroup(t: { status: string | null; archived?: boolean; accepted?: boolean; open: number }): ThreadGroup {
if (t.open > 0) return "waiting";
if (t.status === "done" || t.archived) return "done";
if (t.status === "done" || t.status === "rollout" || t.archived) return "done";
if (t.status === "awaiting_approval" || (t.status === "review" && !t.accepted)) return "waiting";
return "working";
}
@ -148,6 +149,8 @@ export async function projectThreadList(db: Db, user: Pick<User, "id">, chat: Pi
if (live || !agentByTask.get(r.taskId!)?.live) agentByTask.set(r.taskId!, { name: r.name, live });
}
const accepted = await listPendingAccepts(db);
// PEP-278: accepted, the version with the changes is not running yet — the badge says so.
const rollout = await awaitingRollout(db);
// The newest messages of the threads: the last readable line, the unread count, the search.
const msgs = await db
@ -196,7 +199,7 @@ export async function projectThreadList(db: Db, user: Pick<User, "id">, chat: Pi
if (!found.has(key) && !taskKey.toLocaleLowerCase().includes(q) && !t.title.toLocaleLowerCase().includes(q)) continue;
} else if (open === 0 && (archived || (!lastAt && !ACTIVE.has(t.status)))) continue;
add(
{ key, taskKey, title: t.title, status: t.status, archived, accepted: accepted.has(t.id), agentName: agentByTask.get(t.id)?.name ?? null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open },
{ key, taskKey, title: t.title, status: t.status === "done" && rollout.has(t.id) ? "rollout" : t.status, archived, accepted: accepted.has(t.id), agentName: agentByTask.get(t.id)?.name ?? null, last: found.get(key) ?? lastLine.get(key) ?? null, lastAt, unread: unread.get(key) ?? 0, open },
(lastAt ?? t.updatedAt).getTime(),
);
}

View File

@ -439,7 +439,8 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
awaiting_approval: tr("⏸ План готов и ждёт вашего одобрения"),
in_progress: from === "review" ? tr("🔧 Задача вернулась агенту на доработку") : TOOK_TEXT,
review: tr("👀 Задача готова — посмотрите результат и примите"),
done: tr("✅ Задача принята и закрыта"),
// PEP-278: accepted, but the version with the changes is not running yet.
done: p.rollout ? tr("✅ Задача принята — изменения заработают после обновления версии") : tr("✅ Задача принята и закрыта"),
blocked: tr("⛔ Задача заблокирована — агент не может продолжать"),
backlog: tr("↩️ Задача вернулась в бэклог"),
};
@ -457,6 +458,8 @@ const EVENT_TEXT: Record<string, (p: P) => { text: string; important?: boolean;
// PEP-84 / PEP-198: the analyst talks to the PM in the story's thread (the acceptance agent's remark — by its name).
// PEP-156: the role is the author of the line, not a prefix of its text (free text, PEP-139).
intake_note: (p) => ({ text: asIs(cut(s(p.text), 3000)), important: true, author: "agent", role: p.role === "acceptance" ? ACCEPTANCE_AGENT_NAME : ANALYST_NAME }),
// PEP-278: the version with the story's changes runs — the story is done for real.
task_rolled_out: () => ({ text: tr("🚀 Изменения задачи уже работают — задача готова"), important: true }),
pr_merged_in_gitea: (p) => ({ text: p.by ? tr("🔀 Изменения задачи приняты в код проекта ({by})", { by: s(p.by) }) : tr("🔀 Изменения задачи приняты в код проекта") }),
// PEP-174: the project's pause — one line each; what happened inside it is not sent later.
project_paused: () => ({ text: tr("⏸ Проект поставлен на паузу: агенты остановлены, уведомлений нет"), important: true }),

View File

@ -38,6 +38,8 @@ export interface GiteaPull {
base: { ref: string; sha?: string };
/** Common ancestor of the head and the base branch; ≠ base.sha — the branch is behind the base. */
merge_base?: string;
/** PEP-278: the commit the merge put on the base branch (merged PRs only). */
merge_commit_sha?: string | null;
}
export interface GiteaBranch {
name: string;

View File

@ -66,6 +66,7 @@ export * from "./platform-channel.ts";
export * from "./night-quiet.ts";
export * from "./autonomy.ts";
export * from "./accept-pending.ts";
export * from "./rollout.ts";
export * from "./platform-delay.ts";
export * from "./platform-status.ts";
export * from "./agent-versions.ts";

View File

@ -0,0 +1,101 @@
// PEP-278: «Готово» only when the changes work. An accepted story (status `done`) whose result is
// in the project's code waits for the version that carries it: the mark `rollout.wait:<taskId>`
// sits on top of `done` (the status itself stays — everything that reads `done` works as before),
// screens say «Принято, ждёт обновления», and the watchdog (runner/rollout.ts) lifts the mark
// once the merge commit runs — the platform: it is in the live web's commit (`/api/health`);
// a project: a healthy staging or prod version has the story or the commit.
import { execFileSync } from "node:child_process";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { keyPrefix, releases, settings, type Db } from "@peppa/db";
import { m } from "@peppa/shared/i18n";
import { and, eq, gte, inArray } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
export interface RolloutWait {
/** When the story became done (ms). */
at: number;
/** The story's key («PEP-7»): release task lists carry keys. */
key: string;
/** Commit that brought the story into the main branch; null until the watchdog has asked Gitea. */
sha?: string | null;
}
const PREFIX = "rollout.wait:";
const waitKey = (taskId: number) => `${PREFIX}${taskId}`;
/** What the owner sees on an accepted story that does not work yet. */
export const ROLLOUT_LABEL = m("Принято, ждёт обновления");
const platformKey = () => process.env.PEPPA_PLATFORM_KEY || "PEP";
export const getRolloutWait = (db: Db, taskId: number) => getSetting<RolloutWait>(db, waitKey(taskId));
export const setRolloutWait = (db: Db, taskId: number, w: RolloutWait) => setSetting(db, waitKey(taskId), w);
export const clearRolloutWait = (db: Db, taskId: number) => deleteSetting(db, waitKey(taskId));
/** All waiting stories: task id → wait. */
export async function listRolloutWaits(db: Db): Promise<Map<number, RolloutWait>> {
const rows = await db.select().from(settings).where(keyPrefix(settings.key, PREFIX));
return new Map(rows.map((r) => [Number(r.key.slice(PREFIX.length)), r.value as RolloutWait]));
}
/** Ids of the stories (of `ids`, or all) that are accepted but do not work yet. */
export async function awaitingRollout(db: Db, ids?: number[]): Promise<Set<number>> {
const all = await listRolloutWaits(db);
return new Set(ids ? ids.filter((id) => all.has(id)) : all.keys());
}
/**
* Are the project's changes rolled out at all? The platform — always; a project — once it has had a
* healthy staging or prod version. A project without one has nothing to wait for: done is done.
*/
export async function rolloutTracked(db: Db, project: { id: number; key: string }): Promise<boolean> {
if (project.key === platformKey()) return true;
const [r] = await db
.select({ id: releases.id })
.from(releases)
.where(and(eq(releases.projectId, project.id), inArray(releases.env, ["staging", "prod"]), eq(releases.status, "healthy")))
.limit(1);
return !!r;
}
/** Is `commit` in `live` (equal or an ancestor) in the git checkout `root`? Unknown commit — no. */
export function commitIn(root: string, commit: string, live: string): boolean {
if (commit === live) return true;
try {
execFileSync("git", ["merge-base", "--is-ancestor", commit, live], { cwd: root, stdio: "ignore" });
return true;
} catch {
return false;
}
}
// A version reported a little before the accept may carry the story (merged by hand, webhook late).
const EARLY_MS = 6 * 3600_000;
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../..");
export const platformRoot = () => process.env.PEPPA_ROOT || ROOT;
/** Commit the live web runs (its heartbeat; the same commit `/api/health` reports). */
export async function liveWebCommit(db: Db): Promise<string | null> {
const hb = await getSetting<{ commit?: string | null }>(db, "heartbeat:web");
return hb?.commit || null;
}
/**
* Does the waiting story work now? A healthy staging/prod version created after the accept carries
* its key or its commit; for the platform also — the live web's commit contains the merge commit.
* Returns where it works («live», «staging», «prod») or null.
*/
export async function rolledOutWhere(db: Db, project: { id: number; key: string }, w: RolloutWait, o: { root?: string } = {}): Promise<string | null> {
const rows = await db
.select({ env: releases.env, sha: releases.sha, tasks: releases.tasks })
.from(releases)
.where(and(eq(releases.projectId, project.id), inArray(releases.env, ["staging", "prod"]), eq(releases.status, "healthy"), gte(releases.createdAt, new Date(w.at - EARLY_MS))));
for (const r of rows) if ((r.tasks ?? []).includes(w.key) || (w.sha && r.sha === w.sha)) return r.env;
if (project.key === platformKey() && w.sha) {
const live = await liveWebCommit(db);
if (live && commitIn(o.root ?? platformRoot(), w.sha, live)) return "live";
}
return null;
}

View File

@ -28,6 +28,8 @@ export interface StoryProductInput {
queued?: number | null;
/** PEP-247: no agent for a lawful reason (`taskHoldReason`). */
hold?: "paused" | "subscription" | "budget" | null;
/** PEP-278: accepted, the version with the changes is not running yet (`rollout.wait`). */
rollout?: boolean;
}
export interface StoryProductView {
@ -66,6 +68,7 @@ export const STORY_PRODUCT_TEXT = {
},
paused: { now: m("Агент сейчас не работает над задачей"), next: m("FORGE запустит агента снова. Если работа долго не продолжается, напишите в чат проекта.") },
review: { now: m("Работа готова — посмотрите результат"), need: m("Посмотрите результат и нажмите «Принять» или «Поправить»."), next: m("«Принять» — задача закроется, изменения войдут в ваш продукт. «Поправить» — агент доработает по вашему замечанию.") },
rollout: { now: m("Задача принята — изменения скоро заработают"), next: m("Изменения приняты. Как только обновится версия с ними, задача станет «Готово». Делать ничего не нужно.") },
done: { now: m("Задача готова"), next: m("Изменения приняты. Делать ничего не нужно.") },
blocked: { now: m("Работа остановилась"), need: m("Напишите в чат проекта, что делать с задачей."), next: m("Агент продолжит, когда задача вернётся в работу.") },
fixEmpty: m("Напишите, что поправить"),
@ -93,7 +96,7 @@ export function storyProductView(i: StoryProductInput): StoryProductView {
const base = { step: null, stepText: null, need: null, canAccept: false, canFix: false };
const asked = i.openQuestions > 0;
if (i.archived) return { ...base, ...T.archived };
if (i.status === "done") return { ...base, ...T.done };
if (i.status === "done") return { ...base, ...(i.rollout ? T.rollout : T.done) };
// PEP-127: accepted already, Peppa carries it to the end itself — nothing to press again.
if (i.accepted && i.status !== "backlog" && i.status !== "blocked") return { ...base, ...T.accepted };
if (i.status === "review") return { ...base, ...T.review, canAccept: true, canFix: true };

View File

@ -7,7 +7,7 @@ import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import { getGoal, getProject, type Goal, type Project } from "./projects.ts";
import { incidentForTask, type Incident } from "./incidents.ts";
import { taskCiSummary, type CiSummary } from "./ci.ts";
import { taskCiSummary, taskPrNumber, type CiSummary } from "./ci.ts";
import { latestReview, type CodeReview } from "./reviews.ts";
import { getAutonomy, type AutonomySettings } from "./autonomy.ts";
import { reviewPreview, type ReviewPreview } from "./preview.ts";
@ -21,6 +21,7 @@ import { defaultMessageType, type MessageType } from "./questions.ts";
import { renderMain, type AgentMessage } from "./agent-message.ts";
import { insertQuestion, setMessageDetails } from "./message-details.ts";
import { touchVersion } from "./task-origin.ts";
import { clearRolloutWait, rolloutTracked, setRolloutWait } from "./rollout.ts";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@ -230,13 +231,19 @@ export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, session
const changed = Object.fromEntries(
Object.entries(patch).filter(([k, v]) => v !== undefined && ref.task[k as keyof Task] !== v),
);
// PEP-278: an accepted story with a result in the code waits for the version that carries it.
let rollout = false;
if (changed.status === "done" && taskPrNumber(ref.project, task!.prUrl) && (await rolloutTracked(db, ref.project))) {
await setRolloutWait(db, ref.task.id, { at: Date.now(), key: ref.key, sha: null });
rollout = true;
} else if (changed.status && ref.task.status === "done") await clearRolloutWait(db, ref.task.id);
if (Object.keys(changed).length) {
await db.insert(events).values({
projectId: ref.project.id,
taskId: ref.task.id,
sessionId,
type: "task_updated",
payload: { from: pick(ref.task, Object.keys(changed)), to: changed, ...(login ? { login } : {}) },
payload: { from: pick(ref.task, Object.keys(changed)), to: changed, ...(login ? { login } : {}), ...(rollout ? { rollout: true } : {}) },
...actorColumns(sessionId),
});
await notify(db, { type: "task_updated", taskId: ref.task.id });

View File

@ -38,6 +38,7 @@ export * from "./decisions.ts";
export * from "./question-relay.ts";
export * from "./ready-digest.ts";
export * from "./stuck-tasks.ts";
export * from "./rollout.ts";
export * from "./project-trash.ts";
export * from "./branch-protection.ts";
export * from "./template-sync.ts";

View File

@ -0,0 +1,70 @@
// PEP-278: accepted stories wait for the version that carries them (core/rollout.ts). Once a minute
// the watchdog learns each waiting story's merge commit from Gitea and lifts the mark when that
// commit runs — the story is «Готово» for real, one line goes to its chat thread.
import {
clearRolloutWait,
giteaForBot,
listRolloutWaits,
logEvent,
notify,
rolledOutWhere,
setRolloutWait,
taskPrNumber,
type GiteaClient,
type RolloutWait,
} from "@peppa/core";
import { projects, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
/** The commit that brought the story into the main branch; null — not known (yet), "none" — nothing was merged. */
async function mergeCommit(gitea: GiteaClient, project: { giteaOwner: string; giteaRepo: string }, n: number): Promise<string | "none"> {
const pull = await gitea.getPullRequest(project.giteaOwner, project.giteaRepo, n);
if (pull.merged) return pull.merge_commit_sha || pull.head.sha;
// PEP-93: closed without a merge because all its commits were in the base already.
if (pull.state === "closed") return pull.head.sha;
return "none";
}
export async function rolloutTick(db: Db, o: { gitea?: GiteaClient; root?: string; log?: (m: string) => void } = {}): Promise<number> {
if (process.env.PEPPA_ROLLOUT === "off") return 0;
const waits = await listRolloutWaits(db);
let done = 0;
for (const [taskId, w0] of waits) {
let w: RolloutWait = w0;
const [task] = await db.select().from(tasks).where(eq(tasks.id, taskId));
// The story left «Готово» (or is archived, or gone): nothing to wait for.
if (!task || task.status !== "done" || task.archivedAt) {
await clearRolloutWait(db, taskId);
continue;
}
const [project] = await db.select().from(projects).where(eq(projects.id, task.projectId));
if (!project) continue;
if (!w.sha) {
const n = taskPrNumber(project, task.prUrl);
let sha: string | "none" | null = n ? null : "none";
if (n) {
try {
sha = await mergeCommit(o.gitea ?? giteaForBot(), project, n);
} catch {
continue; // Gitea is down — the next minute
}
}
if (sha === "none") {
// Moved to «Готово» by hand with an unmerged result: there is no commit to wait for.
await clearRolloutWait(db, taskId);
await notify(db, { type: "task_updated", taskId });
continue;
}
w = { ...w, sha };
await setRolloutWait(db, taskId, w);
}
const where = await rolledOutWhere(db, project, w, { root: o.root });
if (!where) continue;
await clearRolloutWait(db, taskId);
await logEvent(db, { projectId: project.id, taskId, type: "task_rolled_out", payload: { env: where, sha: w.sha } });
await notify(db, { type: "task_updated", taskId });
o.log?.(`rollout: ${w.key} runs (${where}, ${w.sha?.slice(0, 7)})`);
done++;
}
return done;
}

View File

@ -40,6 +40,7 @@ import { limitDelay, limitOver } from "./limit-delay.ts";
import { checksQueueTick, platformDelayTick } from "./platform-delays.ts";
import { readyDigestTick } from "./ready-digest.ts";
import { stuckTaskTick } from "./stuck-tasks.ts";
import { rolloutTick } from "./rollout.ts";
import { connectionCheckTick, connectionJournalTick, grantExpiryTick } from "@peppa/core";
import { domainGuardTick } from "./domain-guard.ts";
import { orphanContainersTick } from "./orphan-containers.ts";
@ -462,6 +463,8 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
// PEP-198: the analyst's evening digest of finished stories nobody waited for; stuck stories.
await readyDigestTick(db, { log }).catch(failed(db, log, "ready digest failed"));
await stuckTaskTick(db, { log }).catch(failed(db, log, "stuck tasks failed"));
// PEP-278: accepted stories become «Готово» once the version with their changes runs.
await rolloutTick(db, { log }).catch(failed(db, log, "rollout failed"));
// PEP-249: each connection's key is checked once a day; a key that stopped working — one message to its owner.
await connectionCheckTick(db).catch(failed(db, log, "connection check failed"));
// PEP-254: hourly — the connections journal chain is checked, a daily checkpoint goes outside the table.

View File

@ -34,5 +34,6 @@ import { secretMoves } from "./secret-moves.ts";
import { errors } from "./errors.ts";
import { features } from "./features.ts";
import { launchSmoke } from "./launch-smoke.ts";
import { rollout } from "./rollout.ts";
export const en: Dict = { ...errors, ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...sessions, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke };
export const en: Dict = { ...errors, ...common, ...story, ...project, ...admin, ...settings, ...help, ...runner, ...bot, ...merge, ...merge_a, ...merge_b, ...merge_c, ...merge_d, ...feedback, ...attachments, ...capacity, ...sessions, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke, ...rollout };

View File

@ -0,0 +1,10 @@
import type { Dict } from "../index.ts";
// PEP-278: an accepted story waits for the version that carries its changes.
export const rollout: Dict = {
"Принято, ждёт обновления": "Accepted, waiting for the update",
"✅ Задача принята — изменения заработают после обновления версии": "✅ The task is accepted — the changes will work after the version is updated",
"🚀 Изменения задачи уже работают — задача готова": "🚀 The task's changes are live — the task is done",
"Задача принята — изменения скоро заработают": "The task is accepted — the changes will work soon",
"Изменения приняты. Как только обновится версия с ними, задача станет «Готово». Делать ничего не нужно.": "The changes are accepted. As soon as the version with them is updated, the task becomes «Done». Nothing is needed from you.",
};

View File

@ -34,5 +34,6 @@ import { secretMoves } from "./secret-moves.ts";
import { errors } from "./errors.ts";
import { features } from "./features.ts";
import { launchSmoke } from "./launch-smoke.ts";
import { rollout } from "./rollout.ts";
export const kk: Dict = { ...errors, ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...sessions, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke };
export const kk: Dict = { ...errors, ...admin, ...bot, ...common, ...help, ...mergeA, ...mergeB, ...mergeC, ...mergeD, ...merge, ...project, ...runner, ...settings, ...story, ...feedback, ...attachments, ...capacity, ...sessions, ...untrusted, ...mcpGuide, ...subscriptionRequest, ...domainGuard, ...observe, ...intent, ...proposals, ...analyst, ...chatsUx, ...accountMerge, ...acceptScreen, ...accessHub, ...secretMoves, ...features, ...launchSmoke, ...rollout };

View File

@ -0,0 +1,10 @@
import type { Dict } from "../index.ts";
// PEP-278: қабылданған тапсырма өзгерістері бар нұсқаны күтеді.
export const rollout: Dict = {
"Принято, ждёт обновления": "Қабылданды, жаңартуды күтуде",
"✅ Задача принята — изменения заработают после обновления версии": "✅ Тапсырма қабылданды — өзгерістер нұсқа жаңартылғаннан кейін іске қосылады",
"🚀 Изменения задачи уже работают — задача готова": "🚀 Тапсырманың өзгерістері іске қосылды — тапсырма дайын",
"Задача принята — изменения скоро заработают": "Тапсырма қабылданды — өзгерістер жақында іске қосылады",
"Изменения приняты. Как только обновится версия с ними, задача станет «Готово». Делать ничего не нужно.": "Өзгерістер қабылданды. Олар бар нұсқа жаңартылғанда, тапсырма «Дайын» болады. Сізден ештеңе қажет емес.",
};

View File

@ -59,6 +59,8 @@ export interface MockPull {
state: "open" | "closed";
merged: boolean;
mergeable: boolean;
/** PEP-278: the commit the merge put on the base branch. */
mergeSha?: string;
}
export interface MockGiteaUser {
@ -283,6 +285,7 @@ export class MockGitea {
head: { ref: p.head, sha, repo: { full_name: `${r.owner}/${r.name}` } },
base: { ref: p.base, sha: this.tryGit(r, ["rev-parse", p.base]) },
merge_base: this.tryGit(r, ["merge-base", p.base, p.head]),
merge_commit_sha: p.mergeSha ?? null,
};
}
@ -316,6 +319,7 @@ export class MockGitea {
}
const target = isAncestor ? head : g("-c", "user.name=t", "-c", "user.email=t@t", "commit-tree", `${head}^{tree}`, "-p", base, "-p", head, "-m", `Merge pull request #${p.number}`);
g("update-ref", `refs/heads/${p.base}`, target);
p.mergeSha = target;
p.merged = true;
p.state = "closed";
}

View File

@ -0,0 +1,121 @@
// PEP-278, spec delivery-pipeline «"Готово" — когда изменения работают»: an accepted story is
// «Принято, ждёт обновления» until its merge commit runs (platform: the live web's commit;
// a project: a healthy staging/prod version). Mock Gitea, no agents.
import assert from "node:assert/strict";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { core, db, project, runner, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { chatMessages, events, releases } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-rollout-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { test: "pnpm test" };
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
});
after(async () => {
delete process.env.PEPPA_PLATFORM_KEY;
await gitea.stop();
await teardown();
});
/** A story in review with a green PR in mock Gitea; `platform` — the project is the platform's. */
async function storyInReview(o: { platform?: boolean } = {}) {
const tp = await project({ turns: [] });
if (o.platform) process.env.PEPPA_PLATFORM_KEY = tp.key;
const proj = await core.getProject(db, tp.key);
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS });
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
const head = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" }, `${tp.taskKey}: change`);
gitea.setStatus(proj.giteaOwner, proj.giteaRepo, head, "peppa/test", "success");
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
const ref = () => core.resolveTask(db, tp.taskKey);
await core.updateTask(db, await ref(), { status: "review", prUrl });
const oldMain = gitea.sha(proj.giteaOwner, proj.giteaRepo, "main");
const repoPath = gitea.repo(proj.giteaOwner, proj.giteaRepo).path;
const waiting = async () => (await core.awaitingRollout(db)).has((await ref()).task.id);
const taskEvents = async (type: string) => db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type)));
const thread = async () => {
await core.syncChats(db);
const rows = await db.select().from(chatMessages).where(eq(chatMessages.threadKey, `task:${(await ref()).task.id}`));
return rows.map((r) => stripAsIs(r.text));
};
const release = (env: "staging" | "prod", status: "healthy" | "rolled_back", tasks: string[], sha = "f".repeat(40)) =>
db.insert(releases).values({ projectId: proj.id, env, sha, tasks, status });
return { tp, proj, ref, oldMain, repoPath, waiting, taskEvents, thread, release, main: () => gitea.sha(proj.giteaOwner, proj.giteaRepo, "main") };
}
const liveWeb = (commit: string) => core.setSetting(db, "heartbeat:web", { at: new Date().toISOString(), commit });
describe("«Готово» только когда изменения работают", () => {
test("Платформа: принята, но не выкачена", async () => {
const s = await storyInReview({ platform: true });
await liveWeb(s.oldMain);
await runner.acceptStory(db, await s.ref());
assert.equal((await s.ref()).task.status, "done", "the status machine is unchanged");
assert.equal(await s.waiting(), true);
await runner.rolloutTick(db, { root: s.repoPath });
assert.equal(await s.waiting(), true, "the live web runs a commit without the merge");
assert.ok((await s.thread()).some((t) => t.includes("Задача принята — изменения заработают после обновления версии")));
// Платформа: выкачена — the web restarts on the merge commit.
await liveWeb(s.main());
await runner.rolloutTick(db, { root: s.repoPath });
assert.equal(await s.waiting(), false);
assert.equal((await s.taskEvents("task_rolled_out")).length, 1);
await runner.rolloutTick(db, { root: s.repoPath });
assert.equal((await s.taskEvents("task_rolled_out")).length, 1, "said once");
assert.equal((await s.thread()).filter((t) => t.includes("Изменения задачи уже работают — задача готова")).length, 1);
delete process.env.PEPPA_PLATFORM_KEY;
});
test("Проект: здоровая версия для проверки; сломанная версия не считается", async () => {
const s = await storyInReview();
await s.release("staging", "healthy", []);
await runner.acceptStory(db, await s.ref());
assert.equal(await s.waiting(), true);
await s.release("staging", "rolled_back", [s.tp.taskKey]);
await runner.rolloutTick(db);
assert.equal(await s.waiting(), true, "a rolled back version does not count");
await s.release("staging", "healthy", [s.tp.taskKey]);
await runner.rolloutTick(db);
assert.equal(await s.waiting(), false);
assert.equal((await s.taskEvents("task_rolled_out"))[0]?.payload && ((await s.taskEvents("task_rolled_out"))[0]!.payload as { env: string }).env, "staging");
});
test("Проект без выкладки — сразу «Готово»", async () => {
const s = await storyInReview();
await runner.acceptStory(db, await s.ref());
assert.equal((await s.ref()).task.status, "done");
assert.equal(await s.waiting(), false);
assert.ok((await s.thread()).some((t) => t.includes("Задача принята и закрыта")));
});
test("Задача ушла из «Готово» — ожидание снято", async () => {
const s = await storyInReview();
await s.release("prod", "healthy", []);
await runner.acceptStory(db, await s.ref());
assert.equal(await s.waiting(), true);
await core.updateTask(db, await s.ref(), { status: "in_progress" });
assert.equal(await s.waiting(), false);
});
test("Карточка «Продакта» говорит, что изменения скоро заработают", () => {
const v = core.storyProductView({ status: "done", rollout: true, agentWorking: false, openQuestions: 0 });
assert.equal(v.now, core.STORY_PRODUCT_TEXT.rollout.now);
assert.equal(core.storyProductView({ status: "done", agentWorking: false, openQuestions: 0 }).now, core.STORY_PRODUCT_TEXT.done.now);
});
});