From 117dc6ea9c1cc8d27e8a70acdb9582ffcfe328af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Mon, 16 Nov 2026 10:35:55 +0500 Subject: [PATCH] =?UTF-8?q?PEP-145:=20product=20placeholder=20in=20the=20t?= =?UTF-8?q?emplate,=20first=20deploy=20of=20a=20new=20project,=20the=20sys?= =?UTF-8?q?tem=20story=20and=20=C2=AB=D0=9F=D0=BE=D0=BA=D0=B0=D0=B7=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=20=D0=B2=D1=81=D0=B5=D0=BC:=20=D1=81?= =?UTF-8?q?=D0=B0=D0=BC=C2=BB=20in=20the=20watchdog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5.2 --- packages/core/src/index.ts | 1 + packages/core/src/product-link.ts | 108 +++++++++++++++++++++++ packages/core/src/product.ts | 49 ++++++++++- packages/core/src/progress.ts | 7 +- packages/runner/src/accept-pending.ts | 4 +- packages/runner/src/autonomy.ts | 8 +- packages/runner/src/deploy.ts | 46 +++++++++- packages/runner/src/index.ts | 1 + packages/runner/src/product-link.ts | 122 ++++++++++++++++++++++++++ packages/runner/src/provision.ts | 32 ++++++- packages/runner/src/watchdog.ts | 4 + template/AGENTS.md | 7 ++ template/Dockerfile | 10 +++ template/RULES.md | 14 +++ template/product/index.html | 26 ++++++ template/product/server.mjs | 16 ++++ 16 files changed, 442 insertions(+), 13 deletions(-) create mode 100644 packages/core/src/product-link.ts create mode 100644 packages/runner/src/product-link.ts create mode 100644 template/Dockerfile create mode 100644 template/product/index.html create mode 100644 template/product/server.mjs diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1d69ab95..d32cfffe 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -32,6 +32,7 @@ export * from "./help-texts.ts"; export * from "./connect-texts.ts"; export * from "./story-product.ts"; export * from "./product.ts"; +export * from "./product-link.ts"; export * from "./story-refine.ts"; export * from "./local-users.ts"; export * from "./new-users.ts"; diff --git a/packages/core/src/product-link.ts b/packages/core/src/product-link.ts new file mode 100644 index 00000000..729fb9f5 --- /dev/null +++ b/packages/core/src/product-link.ts @@ -0,0 +1,108 @@ +// PEP-145: the product of a project always opens by a link. Here: the «Показывать всем» +// setting (auto / by the button), the state of the system story «Продукт должен открываться +// по ссылке» that Peppa files itself, and its text. The watchdog side is runner/product-link.ts. +import { m as tr } from "@peppa/shared/i18n"; +import { tasks, type Db } from "@peppa/db"; +import { eq } from "drizzle-orm"; +import { PeppaError } from "./errors.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +/** "auto": a healthy version to check whose stories are all accepted goes to everyone by itself. */ +export type PublishMode = "auto" | "button"; +export const PUBLISH_MODES: readonly PublishMode[] = ["auto", "button"]; +/** What a newly created project starts with (existing ones keep «по кнопке» until the owner chooses). */ +export const NEW_PROJECT_PUBLISH: PublishMode = "auto"; + +export const PUBLISH_MODE_RU: Record = { + auto: tr("Сам"), + button: tr("По кнопке"), +}; +export const PUBLISH_MODE_HINT: Record = { + auto: tr("Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям."), + button: tr("Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем»."), +}; + +/** Options of the one-time offer to an existing project. */ +export const PUBLISH_AUTO_OPTION = tr("Показывать сразу"); +export const PUBLISH_BUTTON_OPTION = tr("Оставить по кнопке"); + +const modeKey = (projectId: number) => `product.publish:${projectId}`; + +/** The chosen mode; null — nobody chose yet (behaves as "button"). */ +export async function getPublishChoice(db: Db, projectId: number): Promise { + const v = await getSetting(db, modeKey(projectId)); + return v === "auto" || v === "button" ? v : null; +} + +export async function getPublishMode(db: Db, projectId: number): Promise { + return (await getPublishChoice(db, projectId)) ?? "button"; +} + +export async function setPublishMode(db: Db, projectId: number, mode: PublishMode): Promise { + if (!PUBLISH_MODES.includes(mode)) throw new PeppaError(tr("Показывать всем: выберите «Сам» или «По кнопке».")); + await setSetting(db, modeKey(projectId), mode); + return mode; +} + +/** The system story Peppa filed last for a project and when. */ +export interface ProductLinkState { + taskId: number; + at: number; +} + +const linkKey = (projectId: number) => `product.link:${projectId}`; + +export const getProductLinkState = (db: Db, projectId: number) => getSetting(db, linkKey(projectId)); + +export async function setProductLinkState(db: Db, projectId: number, state: ProductLinkState | null): Promise { + if (state) await setSetting(db, linkKey(projectId), state); + else await deleteSetting(db, linkKey(projectId)); +} + +/** The open system story of a project (not accepted, not archived), if any. */ +export async function openProductLinkTask(db: Db, projectId: number): Promise<{ id: number; number: number; status: string } | null> { + const state = await getProductLinkState(db, projectId); + if (!state) return null; + const [t] = await db.select({ id: tasks.id, number: tasks.number, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(eq(tasks.id, state.taskId)); + if (!t || t.projectId !== projectId || t.archivedAt || t.status === "done") return null; + return { id: t.id, number: t.number, status: t.status }; +} + +// glossary-user: название и описание задачи читает владелец проекта +export const PRODUCT_LINK_TITLE = "Продукт должен открываться по ссылке"; + +export interface ProductLinkProblem { + /** Accepted stories of the project. */ + doneStories: number; + /** The last finished update of the version to check, when it did not come up. */ + failed?: { status: string; sha: string; reason: string | null; logTail: string | null; runUrl: string | null } | null; +} + +/** The story text: what happened in plain words, then what the agent has to do. */ +export function productLinkDescription(p: ProductLinkProblem): string { + const what = p.failed + ? // glossary-user: описание задачи читает владелец проекта + `Последнее обновление версии для проверки не запустилось${p.failed.status === "rolled_back" ? " — возвращена прежняя версия" : ""}, поэтому новые изменения нельзя открыть и посмотреть.` + : // glossary-user: описание задачи читает владелец проекта + `В проекте принято задач: ${p.doneStories}, но продукт не открывается по ссылке — посмотреть результат негде.`; + const lines = [ + "## Зачем", + what, + "", + "## Что сделать", + "Продукт открывается по ссылке версии для проверки и показывает результат принятых задач. Вопросов владельцу не задавать: это техническая задача, её заводит сама Peppa FACTORY.", + "", + "## Условия готовности", + "- Обновление версии для проверки проходит, ссылка открывается.", + "- На странице виден продукт; у продукта без сайта — страница продукта: что это, как пользоваться, как проверить.", + "", + "## Для агента", + "- Правила: разделы «Завершение» и «CD: деплой». Нужны `Dockerfile`, `deploy/compose.yml`, `deploy` в `.peppa/project.json`; приложение слушает `$PORT` и отвечает 200 на `GET /healthz`.", + "- Проверь локально: `docker build .`, запуск образа с `PORT=3000`, `curl /healthz`.", + ]; + if (p.failed) { + lines.push(`- Коммит: ${p.failed.sha.slice(0, 12)}; причина: ${p.failed.reason ?? "неизвестна"}${p.failed.runUrl ? `; запуск: ${p.failed.runUrl}` : ""}.`); + if (p.failed.logTail) lines.push("", "### Журнал сбоя", "```", p.failed.logTail.split("\n").slice(-60).join("\n").slice(-4000), "```"); + } + return lines.join("\n"); +} diff --git a/packages/core/src/product.ts b/packages/core/src/product.ts index c8ac1ef6..6242d354 100644 --- a/packages/core/src/product.ts +++ b/packages/core/src/product.ts @@ -1,8 +1,11 @@ // PEP-111: «Ваш продукт» — where the result of the project lives, in words for a product // manager: the working version everyone sees (prod), the version to check (staging), or the // fact that the project is not deployed as a site at all. -import { releases, tasks, type Db } from "@peppa/db"; -import { and, desc, eq, inArray, isNull } from "drizzle-orm"; +import { m as tr } from "@peppa/shared/i18n"; +import { formatTaskKey } from "@peppa/shared"; +import { projects, releases, tasks, type Db } from "@peppa/db"; +import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; +import { openProductLinkTask } from "./product-link.ts"; export interface ProductVersion { url: string; @@ -18,21 +21,59 @@ export interface ProjectProduct { check: ProductVersion | null; /** Stories accepted so far (a product without a site still has results). */ doneStories: number; + /** PEP-145: the open system story «Продукт должен открываться по ссылке». */ + fix: { key: string; working: boolean } | null; + /** PEP-145: the last update of the version to check did not come up (the earlier one still runs). */ + broken: boolean; + /** PEP-145: no link yet, but it is on its way — an update is running or the system story is open. */ + preparing: boolean; + /** PEP-145: a screenshot of the first page (taken on a story's version to check, PEP-44). */ + shot: { releaseId: number; n: number } | null; } +/** An update that reported «начато» and nothing since is not «идёт» for ever. */ +const DEPLOYING_MS = 30 * 60_000; + export async function projectProduct(db: Db, projectId: number): Promise { const latest = async (env: "prod" | "staging") => (await db.select().from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, env), eq(releases.status, "healthy"))).orderBy(desc(releases.id)).limit(1))[0]; const [prod, staging] = [await latest("prod"), await latest("staging")]; const version = (r: NonNullable): ProductVersion | null => (r.host ? { url: `https://${r.host}`, at: r.updatedAt ?? r.createdAt, stories: r.tasks } : null); const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt))); + const live = prod ? version(prod) : null; + const check = staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null; + const recent = await db.select({ status: releases.status, createdAt: releases.createdAt }).from(releases).where(and(eq(releases.projectId, projectId), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(5); + const deploying = recent.some((r) => r.status === "deploying" && Date.now() - r.createdAt.getTime() < DEPLOYING_MS); + const lastFinished = recent.find((r) => r.status !== "deploying" && r.status !== "removed"); + const open = await openProductLinkTask(db, projectId); + const [project] = open ? await db.select({ key: projects.key }).from(projects).where(eq(projects.id, projectId)) : []; + const [shot] = await db + .select({ id: releases.id, screenshots: releases.screenshots }) + .from(releases) + .where(and(eq(releases.projectId, projectId), eq(releases.env, "preview"), sql`json_array_length(${releases.screenshots}) > 0`)) + .orderBy(desc(releases.id)) + .limit(1); + const fix = open && project ? { key: formatTaskKey(project.key, open.number), working: open.status !== "backlog" } : null; return { - live: prod ? version(prod) : null, - check: staging && (!prod || (staging.id > prod.id && staging.sha !== prod.sha)) ? version(staging) : null, + live, + check, doneStories: done.length, + fix, + broken: !!lastFinished && (lastFinished.status === "failed" || lastFinished.status === "rolled_back"), + preparing: !live && !check && (deploying || !!fix), + shot: shot ? { releaseId: shot.id, n: Math.max(0, shot.screenshots.findIndex((s) => s.path === "/")) } : null, }; } +/** + * PEP-145: the «Посмотреть» line for a message about an accepted story — the product link, if + * the project has one ("" otherwise). The new version takes a few minutes to come up. + */ +export async function productLookLine(db: Db, projectId: number): Promise { + const product = (await productUrls(db, [projectId])).get(projectId); + return product ? `\n${tr("Посмотреть: {url} — продукт обновится через несколько минут", { url: product.url })}` : ""; +} + /** Product links of several projects at once (the Home page): projectId → URL of the best version. */ export async function productUrls(db: Db, projectIds: number[]): Promise> { const out = new Map(); diff --git a/packages/core/src/progress.ts b/packages/core/src/progress.ts index ded1ec6b..3fb928b2 100644 --- a/packages/core/src/progress.ts +++ b/packages/core/src/progress.ts @@ -2,6 +2,7 @@ // in work right now (agent, tasks.md progress). import { m as tr } from "@peppa/shared/i18n"; import { productUrls } from "./product.ts"; +import { openProductLinkTask } from "./product-link.ts"; import { projects, tasks, users, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, eq, inArray, isNull } from "drizzle-orm"; @@ -35,6 +36,8 @@ export interface ProjectProgress { reviewKeys: string[]; /** PEP-111: where the product runs (prod, else the version to check), if it is deployed. */ product: { url: string; live: boolean } | null; + /** PEP-145: no link yet — the key of the system story that makes the product open by a link. */ + productFix: string | null; } export interface ProgressOverview { @@ -59,7 +62,9 @@ export async function progressOverview(db: Db, userId: number): Promise t.projectId === p.id); const agentsOf = own.some((t) => column(t.status) === "inProgress") ? await taskAgentNames(db, p.id) : new Map(); for (const t of own) { diff --git a/packages/runner/src/accept-pending.ts b/packages/runner/src/accept-pending.ts index 17cbb081..f56983f1 100644 --- a/packages/runner/src/accept-pending.ts +++ b/packages/runner/src/accept-pending.ts @@ -1,7 +1,7 @@ // PEP-127: «Принять» remembered over a conflict is carried through by the watchdog — the agent // rebases (flow.ts `deferAccept`), and once the story is back in review with green checks the PR // is merged and the story closed. The PM hears when it closed, or once if it could not be done. -import { answerQuestion, askPm, clearPendingAccept, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef } from "@peppa/core"; +import { answerQuestion, askPm, clearPendingAccept, productLookLine, giteaForBot, listPendingAccepts, listSessions, logEvent, prGate, setPendingAccept, taskPrNumber, type GiteaClient, type PendingAccept, type TaskRef } from "@peppa/core"; import { questions, type Db } from "@peppa/db"; import { m } from "@peppa/shared/i18n"; import { and, eq, isNull } from "drizzle-orm"; @@ -85,7 +85,7 @@ async function finish(db: Db, ref: TaskRef, log: (m: string) => void) { for (const s of await listSessions(db, { taskId: ref.task.id })) if (s.workspacePath && ["done", "failed"].includes(s.status)) await cleanupWorktree(db, s).catch(() => {}); await syncWorkspace(db, ref).catch(() => {}); await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "accept_completed", payload: { pr: ref.task.prUrl } }); - await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: ref.task.title })); + await notifyPm(db, ref.project.id, `accept:done:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("✅ {key} «{title}» принята и закрыта: агент обновил изменения, проверки пройдены.", { key: ref.key, title: ref.task.title })}${await productLookLine(db, ref.project.id)}`); log(`${ref.key}: accepted story merged and closed`); } diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index eb5b75d6..f28aca66 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -36,6 +36,8 @@ import { projectAgentWarning, intakePendingTasks, productUrls, + productLookLine, + getProductLinkState, pendingRefinements, } from "@peppa/core"; import { goals, incidents, questions, tasks, type Db } from "@peppa/db"; @@ -156,7 +158,7 @@ async function autoMergeReviews(db: Db, project: Project, a: AutonomySettings, c async function afterMerge(db: Db, ref: TaskRef, a: AutonomySettings, state: MergeState, log: (m: string) => void) { if (a.close === "after_merge") { await closeStory(db, ref, m("✅ Закрыто автоматически: изменения приняты")); - await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: ref.task.title })); + await notifyPm(db, ref.project.id, `auto:closed:${ref.task.id}:${ref.task.prUrl ?? "no-pr"}`, `${m("🤖 {key} «{title}»: изменения приняты, задача закрыта автоматически.", { key: ref.key, title: ref.task.title })}${await productLookLine(db, ref.project.id)}`); log(`${ref.key}: closed after merge`); return; } @@ -310,7 +312,9 @@ export async function readyBacklog(db: const ready = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id)); // PEP-103: fixing errors comes first — bug stories, then the rest, each in board order. const bugs = await bugTaskIds(db, projectId); - return [...ready.filter((t) => bugs.has(t.id)), ...ready.filter((t) => !bugs.has(t.id))]; + // PEP-145: before everything — the system story that makes the product open by a link. + const link = (await getProductLinkState(db, projectId))?.taskId; + return [...ready.filter((t) => t.id === link), ...ready.filter((t) => t.id !== link && bugs.has(t.id)), ...ready.filter((t) => t.id !== link && !bugs.has(t.id))]; } /** Bug stories of a project: made from a production error (PEP-58) or in the «Стабильность» epic. */ diff --git a/packages/runner/src/deploy.ts b/packages/runner/src/deploy.ts index 34e70b38..3e3fd6b2 100644 --- a/packages/runner/src/deploy.ts +++ b/packages/runner/src/deploy.ts @@ -3,7 +3,7 @@ // here; Peppa keeps the releases, tells the PM, and starts prod by the PM's button — a // `deploy-prod-*` tag at the healthy staging commit (Gitea 1.22 has no workflow_dispatch API). import { m } from "@peppa/shared/i18n"; -import { answerQuestion, askPmProject, deleteSetting, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; +import { answerQuestion, askPmProject, deleteSetting, getPublishMode, getSetting, setSetting, resolveTask, giteaForBot, logEvent, markSecretsRestart, needsLine, openNeeds, PeppaError, projectSecretMasker, queueProductReview, runLink, type GiteaClient, type Project, type Question } from "@peppa/core"; import { projects, questions, releases, settings, type Db } from "@peppa/db"; import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; import { deployPlatform, isPlatform } from "./platform-release.ts"; @@ -134,6 +134,8 @@ async function notifyRelease(db: Db, project: Project, rel: Release) { }); } else if (rel.status === "healthy" && rel.env === "staging") { await expireProdOffers(db, project.id); + // PEP-145: «Показывать всем: сам» — the version goes to everyone without a question. + if (await autoPublish(db, project).catch(() => false)) return; await askPmProject(db, project, { kind: "question", options: [PROD_OPTION], @@ -184,6 +186,48 @@ export async function deployProd(db: Db, project: Project, by: string, client?: return rel!; } +const publishedKey = (projectId: number) => `product.published:${projectId}`; +/** A failed automatic start is tried again not sooner than this. */ +const AUTO_PUBLISH_RETRY_MS = 10 * 60_000; + +/** + * PEP-145: «Показывать всем: сам». The healthy version to check, newer than the working one and + * with every story accepted, becomes the working version without anyone pressing a button. + * Called when a staging deploy turns healthy and from the watchdog (stories accepted later). + * Returns true when the update of the working version was started. + */ +export async function autoPublish(db: Db, project: Project, o: { now?: Date; client?: GiteaClient; log?: (m: string) => void } = {}): Promise { + if (isPlatform(project) || (await getPublishMode(db, project.id)) !== "auto") return false; + const { staging, prod } = await currentReleases(db, project.id); + if (!staging || prod?.sha === staging.sha) return false; + const now = (o.now ?? new Date()).getTime(); + const tried = await getSetting<{ sha: string; at: number; ok: boolean }>(db, publishedKey(project.id)); + if (tried?.sha === staging.sha && (tried.ok || now - tried.at < AUTO_PUBLISH_RETRY_MS)) return false; + const [running] = await db.select({ id: releases.id }).from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "prod"), eq(releases.status, "deploying"))).limit(1); + if (running) return false; + // Every story that would reach everyone is accepted: this version and the ones skipped before it. + const since = await db + .select({ tasks: releases.tasks }) + .from(releases) + .where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"), eq(releases.status, "healthy"), prod ? sql`${releases.id} > ${prod.id}` : undefined)); + for (const key of new Set([...since.flatMap((r) => r.tasks), ...staging.tasks])) { + const ref = await resolveTask(db, key, project.key).catch(() => null); + if (ref && ref.project.id === project.id && ref.task.status !== "done" && !ref.task.archivedAt) return false; + } + try { + await deployProd(db, project, "Peppa FACTORY", o.client); + } catch (e) { + await setSetting(db, publishedKey(project.id), { sha: staging.sha, at: now, ok: false }); + o.log?.(`auto publish ${project.key}: ${(e as Error).message}`); + return false; + } + await setSetting(db, publishedKey(project.id), { sha: staging.sha, at: now, ok: true }); + await expireProdOffers(db, project.id, m("(неактуально: Peppa FACTORY сама показывает эту версию всем)")); + await logEvent(db, { projectId: project.id, type: "product_auto_published", payload: { sha: staging.sha, tasks: staging.tasks } }); + o.log?.(`auto publish ${project.key}: ${staging.sha.slice(0, 7)}`); + return true; +} + const REDEPLOY_PREFIX = "product.redeploy:"; /** diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 77cc5cfa..64bb5f6d 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -20,6 +20,7 @@ export * from "./feedback.ts"; export * from "./triage.ts"; export * from "./ci-feedback.ts"; export * from "./deploy.ts"; +export * from "./product-link.ts"; export * from "./platform-release.ts"; export * from "./platform-build.ts"; export * from "./code.ts"; diff --git a/packages/runner/src/product-link.ts b/packages/runner/src/product-link.ts new file mode 100644 index 00000000..507eafcd --- /dev/null +++ b/packages/runner/src/product-link.ts @@ -0,0 +1,122 @@ +// PEP-145: the product of a project always opens by a link — the watchdog side. Per project +// (not Peppa itself): the system story «Продукт должен открываться по ссылке» when accepted +// stories have nowhere to be seen or the last update of the version to check did not come up; +// «Показывать всем: сам» carried through when stories are accepted after the deploy; and the +// one-time offer of that mode to projects created before it existed. +import { m } from "@peppa/shared/i18n"; +import { + askPmProject, + createTask, + getProductLinkState, + getPublishChoice, + getSetting, + listProjects, + logEvent, + openProductLinkTask, + productLinkDescription, + PRODUCT_LINK_TITLE, + PUBLISH_AUTO_OPTION, + PUBLISH_BUTTON_OPTION, + reorderTask, + setIntakeState, + setProductLinkState, + setPublishMode, + setSetting, + type GiteaClient, + type Project, + type Question, +} from "@peppa/core"; +import { projects, releases, tasks, type Db } from "@peppa/db"; +import { and, desc, eq, isNull } from "drizzle-orm"; +import { autoPublish, currentReleases } from "./deploy.ts"; +import { isPlatform } from "./platform-release.ts"; +import { onAnswer } from "./sessions.ts"; + +export interface ProductLinkTickOptions { + now?: Date; + log?: (m: string) => void; + client?: GiteaClient; +} + +/** A deploy that said «начато» and nothing since does not hold the story back for ever. */ +const DEPLOYING_MS = 30 * 60_000; +const minGapMs = () => Math.max(0, Number(process.env.PEPPA_PRODUCT_LINK_HOURS ?? 24)) * 3_600_000; +const offeredKey = (projectId: number) => `product.publish.offered:${projectId}`; + +export async function productLinkTick(db: Db, o: ProductLinkTickOptions = {}): Promise { + if (process.env.PEPPA_PRODUCT_LINK === "off") return; + const log = o.log ?? (() => {}); + for (const project of await listProjects(db)) { + if (isPlatform(project)) continue; + try { + await ensureProductLinkTask(db, project, o); + await offerPublishMode(db, project); + await autoPublish(db, project, o); + } catch (e) { + log(`product link ${project.key}: ${(e as Error).message}`); + } + } +} + +/** + * Files the system story when the project has accepted stories and no healthy version to check, + * or the last finished update failed or was rolled back. One open story per project, not more + * often than once a day. Returns the new story's key, or null. + */ +export async function ensureProductLinkTask(db: Db, project: Project, o: ProductLinkTickOptions = {}): Promise { + const now = (o.now ?? new Date()).getTime(); + if (await openProductLinkTask(db, project.id)) return null; + const state = await getProductLinkState(db, project.id); + if (state && now - state.at < minGapMs()) return null; + const recent = await db.select().from(releases).where(and(eq(releases.projectId, project.id), eq(releases.env, "staging"))).orderBy(desc(releases.id)).limit(10); + // An update is on its way: its result decides. + if (recent.some((r) => r.status === "deploying" && now - r.createdAt.getTime() < DEPLOYING_MS)) return null; + const last = recent.find((r) => r.status !== "deploying" && r.status !== "removed"); + const failed = last && (last.status === "failed" || last.status === "rolled_back") ? last : null; + const done = await db.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.status, "done"), isNull(tasks.archivedAt))); + const healthy = recent.some((r) => r.status === "healthy") || !!(await currentReleases(db, project.id)).staging; + if (!failed && (healthy || done.length === 0)) return null; + + const description = productLinkDescription({ doneStories: done.length, failed: failed ? { status: failed.status, sha: failed.sha, reason: failed.reason, logTail: failed.logTail, runUrl: failed.runUrl } : null }); + const ref = await createTask(db, { projectId: project.id, title: PRODUCT_LINK_TITLE, description }); + // Already formulated: «продакт» and «аналитик» of the intake skip it. + await setIntakeState(db, ref.task.id, { stage: "done", original: { title: PRODUCT_LINK_TITLE, description }, attempts: 0, note: "заведена Peppa FACTORY: продукт не открывается по ссылке" }); + await reorderTask(db, ref, { to: "top" }); + await setProductLinkState(db, project.id, { taskId: ref.task.id, at: now }); + await logEvent(db, { projectId: project.id, taskId: ref.task.id, type: "product_link_task", payload: { key: ref.key, failed: failed ? { sha: failed.sha, status: failed.status, reason: failed.reason } : null, doneStories: done.length } }); + o.log?.(`product link ${project.key}: filed ${ref.key}${failed ? ` (${failed.status} ${failed.sha.slice(0, 7)})` : " (no version to check)"}`); + return ref.key; +} + +/** + * A project created before «Показывать всем» existed stays «по кнопке»; once it has a version + * to check, its people get one message with two buttons. + */ +export async function offerPublishMode(db: Db, project: Project): Promise { + if ((await getPublishChoice(db, project.id)) || (await getSetting(db, offeredKey(project.id)))) return false; + if (!(await currentReleases(db, project.id)).staging) return false; + const q = await askPmProject(db, project, { + kind: "question", + options: [PUBLISH_AUTO_OPTION, PUBLISH_BUTTON_OPTION], + text: [ + m("💡 {project}: показывать новые версии продукта всем пользователям сразу?", { project: project.name }), + m("Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех."), + m("Изменить выбор можно в настройках проекта."), + ].join("\n"), + }); + await setSetting(db, offeredKey(project.id), { questionId: q.id, at: Date.now() }); + return true; +} + +/** The answer to the offer above (`onAnswer` registry). */ +export async function onPublishAnswer(db: Db, q: Question, answer: string): Promise { + if (q.taskId || q.sessionId || !(q.options ?? []).includes(PUBLISH_AUTO_OPTION)) return false; + const a = answer.trim(); + if (a !== PUBLISH_AUTO_OPTION && a !== PUBLISH_BUTTON_OPTION) return false; + const [project] = await db.select().from(projects).where(eq(projects.id, q.projectId)); + if (!project) return false; + await setPublishMode(db, project.id, a === PUBLISH_AUTO_OPTION ? "auto" : "button"); + if (a === PUBLISH_AUTO_OPTION) await autoPublish(db, project).catch(() => false); + return true; +} +onAnswer(onPublishAnswer); diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts index 16ea824a..ce1898e9 100644 --- a/packages/runner/src/provision.ts +++ b/packages/runner/src/provision.ts @@ -5,7 +5,7 @@ import { m } from "@peppa/shared/i18n"; import { cpSync, existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { createProject, NEW_PROJECT_AUTONOMY, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core"; +import { createProject, NEW_PROJECT_AUTONOMY, NEW_PROJECT_PUBLISH, setPublishMode, logEvent, ownPool, setAutonomy, setIntakeSettings, setProjectPool, giteaForBot, giteaForUser, isLocalUser, PeppaError, type GiteaClient, type Project, type User } from "@peppa/core"; import { projects, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { eq, or } from "drizzle-orm"; @@ -34,6 +34,11 @@ export interface ProvisionOptions { // Template files that stay in the template repo (RULES.md is loaded live by the runner). const TEMPLATE_SKIP = new Set([".git", "RULES.md", "README.md"]); +// PEP-145: the product placeholder («Продукт создаётся») — only for a new, empty repository; +// a connected repository keeps its own code and deploy untouched. +const PLACEHOLDER = new Set(["Dockerfile", "product"]); +/** `deploy` of a new project: the placeholder opens by the link before the first story. */ +export const NEW_PROJECT_DEPLOY = { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" }; /** * Where a user's new project goes: their namespace (or an org) with their Gitea client; a local @@ -102,6 +107,8 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise log(`ci: ${(e as Error).message}`)); + const ci = await setupCi(db, project).then(() => true, (e) => (log(`ci: ${(e as Error).message}`), false)); + // PEP-145: new versions reach everyone without a visit to the settings; the bootstrap commit + // was pushed before the runner and the secret existed, so the first deploy of the version to + // check is asked for with a tag (the PEP-112 mechanism). Best effort: the watchdog and the + // first merged story deploy it anyway. + await setPublishMode(db, project.id, NEW_PROJECT_PUBLISH); + if (ci && firstDeploy) { + log("first deploy"); + try { + const { stdout: head } = await git(dest, "rev-parse", "HEAD"); + const tag = `deploy-staging-${new Date().toISOString().replace(/\D/g, "").slice(0, 17)}`; + await o.gitea.createTag(repo.owner.login, repo.name, tag, head.trim(), "Первая версия для проверки: заглушка продукта"); + await logEvent(db, { projectId: project.id, type: "first_deploy_requested", payload: { tag } }); + } catch (e) { + log(`first deploy: ${(e as Error).message}`); + } + } return project; } catch (e) { rmSync(dest, { recursive: true, force: true }); diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 651609c8..2ad0be4c 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -44,6 +44,7 @@ import { analystChatTick } from "./analyst-chat.ts"; import { productReviewTick } from "./product-review.ts"; import { feedbackTick } from "./feedback.ts"; import { productRedeployTick } from "./deploy.ts"; +import { productLinkTick } from "./product-link.ts"; import { budgetTick } from "./budgets.ts"; import { getWatchdogSettings, idleStopTick, onRunnerCrash, patchWatch, remindTick, restartStalled, restartTick, type WatchdogSettings } from "./recovery.ts"; import { serveRunnerCommands, type RunnerService } from "./runner-service.ts"; @@ -104,6 +105,9 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise { await storyRefineTick(db, { now: opts.now, log }).catch(failed(db, log, "story refine")); // PEP-127: accepts remembered over a conflict — merge and close once the agent has rebased. await pendingAcceptTick(db, { now: opts.now, log }).catch(failed(db, log, "pending accepts")); + // PEP-145: a project whose product does not open by a link gets a story for that, first in the + // backlog — before the dispatcher looks; «Показывать всем: сам» is carried through. + await productLinkTick(db, { now: opts.now, log }).catch(failed(db, log, "product link")); await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy")); // PEP-110: the analyst answers people in the projects' discussions. await analystChatTick(db, { log }).catch(failed(db, log, "analyst chat")); diff --git a/template/AGENTS.md b/template/AGENTS.md index 3be88e30..108e53b9 100644 --- a/template/AGENTS.md +++ b/template/AGENTS.md @@ -13,3 +13,10 @@ ## Проект + +## Продукт по ссылке + +Продукт проекта всегда открывается по ссылке (`-staging.telecom.quest`). Сейчас там +заглушка из `product/` и `Dockerfile` — первая стори с настоящим продуктом заменяет её своим +приложением (слушает `$PORT`, отвечает 200 на `GET /healthz`). Подробности — общие правила, +разделы «Завершение» и «CD: деплой». diff --git a/template/Dockerfile b/template/Dockerfile new file mode 100644 index 00000000..32b96e17 --- /dev/null +++ b/template/Dockerfile @@ -0,0 +1,10 @@ +# Заглушка продукта (PEP-145): страница «Продукт создаётся» из product/. Проект открывается +# по ссылке с первого дня. Первая задача с настоящим продуктом заменяет этот файл своим +# (заготовки — deploy/Dockerfile.node, deploy/Dockerfile.python): приложение слушает $PORT +# и отвечает 200 на GET /healthz. +FROM node:22-alpine +WORKDIR /app +COPY product/ ./product/ +ENV NODE_ENV=production PORT=3000 +EXPOSE 3000 +CMD ["node", "product/server.mjs"] diff --git a/template/RULES.md b/template/RULES.md index e3fee551..3736d5a1 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -66,6 +66,14 @@ git, тесты, раннеры — решаешь ты сам и пишешь, `remember` сообщает о пределе — ужми память (`get_memory`, затем `remember` с `replace: true`: объедини похожее, убери устаревшее). Закоммить файл в ветке стори. В сессиях Пеппы память уже в системном промпте (раздел «Память проекта»). +- **Продукт открывается по ссылке (PEP-145).** Стори не готова, пока продукт с её изменениями + не открывается по ссылке версии для проверки (preview PR, после мержа — staging). Проверь + сам: образ собирается, `GET /healthz` отвечает 200, на странице виден результат стори. + Проект ещё не выкладывается (нет `deploy` в `.peppa/project.json`, нет `Dockerfile`, стоит + заглушка «Продукт создаётся») — сначала настрой выкладку (Dockerfile, `deploy/compose.yml`, + health): это часть твоей стори, PM об этом не спрашивай. Продукт без сайта (бот, библиотека, + скрипт) — сделай страницу продукта, которая открывается по той же ссылке: что это, как + пользоваться, как проверить. - `openspec archive <имя>` — delta-специфики вливаются в `openspec/specs/`. - Запушь ветку и открой PR в Gitea (ссылка на стори и резюме change). - `peppa.update_task` → `status: review`, `pr_url: …` и закончи ход. PM получит «готово @@ -122,6 +130,12 @@ git, тесты, раннеры — решаешь ты сам и пишешь, "health": "/healthz", "migrate": "pnpm db:migrate" } } ``` +- Новый проект создаётся с заглушкой: `Dockerfile` + `product/` (страница «Продукт создаётся») + и готовый `deploy` — ссылка работает с первого дня. Первая стори с настоящим продуктом + заменяет заглушку своим приложением (тот же порт и `/healthz`), а не оставляет её рядом. +- Стори «Продукт должен открываться по ссылке» заводит сама Пеппа, когда у проекта нет + здоровой версии для проверки или выкладка упала: причина и хвост журнала — в описании. + Почини причину, доведи до зелёной выкладки; `.gitea/` и проверки не ослабляй. - Приложение слушает `$PORT` и отвечает 200 на `GET /healthz` (`deploy.health`) — без этого деплой считается неудачным и откатывается. - PR получает preview `-pr.telecom.quest`, мерж в main — staging diff --git a/template/product/index.html b/template/product/index.html new file mode 100644 index 00000000..d65b66f9 --- /dev/null +++ b/template/product/index.html @@ -0,0 +1,26 @@ + + + + + + Продукт создаётся + + + +
+

Продукт создаётся

+

Агенты уже работают над первой задачей. Когда она будет готова, результат появится на этой странице — адрес останется тем же.

+

Өнім жасалып жатыр. Бірінші тапсырма дайын болғанда нәтиже осы бетте пайда болады.

+

The product is being built. The result of the first task will appear on this page.

+
+ + diff --git a/template/product/server.mjs b/template/product/server.mjs new file mode 100644 index 00000000..67e22141 --- /dev/null +++ b/template/product/server.mjs @@ -0,0 +1,16 @@ +// Заглушка продукта (PEP-145): пока в проекте нет своего приложения, по ссылке открывается +// страница «Продукт создаётся». Слушает $PORT, отвечает 200 на GET /healthz. Первая задача, +// которая делает настоящий продукт, заменяет этот каталог и Dockerfile своими. +import { createServer } from "node:http"; +import { readFileSync } from "node:fs"; + +const page = readFileSync(new URL("./index.html", import.meta.url)); +const port = Number(process.env.PORT ?? 3000); + +createServer((req, res) => { + if (req.url === "/healthz") { + res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end("ok"); + return; + } + res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }).end(page); +}).listen(port, "0.0.0.0", () => console.log(`product placeholder on :${port}`));