+ с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке
+
+
+
+
+
+ ) : (
+
+
+ Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой
+ токен через claude setup-token, вход делаете вы сами по ссылке.
+
diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css
index b748e021..fa27012d 100644
--- a/apps/web/app/globals.css
+++ b/apps/web/app/globals.css
@@ -158,3 +158,11 @@ details.add { margin: 4px 0; }
.mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; }
.ok { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; }
+
+.help ul { padding-left: 20px; }
+.help li { margin: 4px 0; }
+.say { margin: 6px 0; font-style: italic; }
+table.tools { width: 100%; border-collapse: collapse; }
+table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; }
+table.tools td.mono { white-space: nowrap; }
+@media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } }
diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml
new file mode 100644
index 00000000..55ab199b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-12
diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md
new file mode 100644
index 00000000..948c344a
--- /dev/null
+++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md
@@ -0,0 +1,33 @@
+# Proposal: PEP-14 — полный набор MCP для PM и «Помощь»
+
+Задача Пеппы: **PEP-14** · Цель #2.
+
+## Why
+
+Через удалённый MCP нельзя завести или поправить цель, создать проект, перенести задачу
+в другую цель — PM приходится идти в веб. И нигде не описано, как пользоваться Пеппой
+через MCP.
+
+## What Changes
+
+- Инструменты MCP: `create_goal`, `update_goal` (название, описание, статус
+ open/done/archived), `create_project` (новый или существующий репо в Gitea — тот же
+ `provisionProject`, что веб, от имени пользователя), `update_task` получает `goal_id`
+ (перенести в цель или отвязать).
+- MCP-сервер отдаёт клиенту инструкции (`instructions`): модель Пеппы (проект → цели →
+ задачи → доска → агенты), как формулировать задачи, когда что вызывать.
+- Страница «Помощь» в вебе (`/help`, в меню): подключение MCP в ChatGPT/Codex, словарь
+ (цель, задача, доска, сессия, входящие, ревью) и сценарии с примерами фраз.
+
+## Capabilities
+
+### New Capabilities
+
+### Modified Capabilities
+- `remote-mcp`: цели, создание проекта, цель задачи, инструкции сервера.
+- `web-workspace`: страница «Помощь».
+
+## Impact
+
+`packages/mcp/src/manager.ts`, `packages/core` (updateGoal), `apps/web` (/help, меню),
+testkit.
diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md
new file mode 100644
index 00000000..dbd54cb5
--- /dev/null
+++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md
@@ -0,0 +1,37 @@
+# Spec Delta: remote-mcp
+
+## ADDED Requirements
+
+### Requirement: Цели через MCP
+MCP SHALL позволять создавать цели в проекте пользователя и менять их название,
+описание и статус (открыта, достигнута, в архиве).
+
+#### Scenario: Новая цель и задачи под ней
+- **WHEN** клиент создаёт цель и затем задачу с её `goal_id`
+- **THEN** цель видна в списке целей проекта, задача — под этой целью
+
+#### Scenario: Цель достигнута
+- **WHEN** клиент меняет статус цели на «достигнута»
+- **THEN** цель пропадает из списка открытых целей, её задачи не меняются
+
+### Requirement: Цель задачи
+`update_task` SHALL позволять перенести задачу в другую цель своего проекта или отвязать от цели, не меняя остальное.
+
+#### Scenario: Перенос в другую цель
+- **WHEN** клиент вызывает `update_task` с `goal_id` другой цели проекта
+- **THEN** задача относится к этой цели, статус и название прежние
+
+### Requirement: Создание проекта через MCP
+MCP SHALL создавать проект так же, как веб: новый или существующий репозиторий в
+пространстве пользователя или его организации, от имени пользователя.
+
+#### Scenario: Новый проект
+- **WHEN** клиент вызывает `create_project` с названием, slug и ключом
+- **THEN** проект создан с пользователем-владельцем и виден в `list_projects`
+
+### Requirement: Инструкции сервера
+MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться инструментами.
+
+#### Scenario: Подключение
+- **WHEN** клиент инициализирует соединение
+- **THEN** получает инструкции сервера с моделью проект → цели → задачи → доска
diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md
new file mode 100644
index 00000000..05bd5b80
--- /dev/null
+++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md
@@ -0,0 +1,11 @@
+# Spec Delta: web-workspace
+
+## ADDED Requirements
+
+### Requirement: Помощь
+Веб SHALL иметь страницу «Помощь», доступную из меню, с описанием понятий Пеппы,
+подключения MCP-клиентов и сценариев работы с примерами.
+
+#### Scenario: Открыть помощь
+- **WHEN** пользователь открывает «Помощь»
+- **THEN** видит адрес MCP, шаги подключения ChatGPT и Codex и сценарии: создать проект, цели, задачи, проверить статус, ответить агенту, принять ревью
diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md
new file mode 100644
index 00000000..e10a7518
--- /dev/null
+++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md
@@ -0,0 +1,15 @@
+# Tasks: PEP-14
+
+## 1. MCP
+
+- [x] 1.1 core `updateGoal`; MCP `create_goal`, `update_goal`, `update_task.goal_id`, `create_project`
+- [x] 1.2 `instructions` MCP-сервера
+- [x] 1.3 Тесты: цели (создание, правка, статус), перенос задачи в цель и отвязка, чужая цель — ошибка, создание проекта через mock-gitea, инструкции в initialize
+
+## 2. Помощь
+
+- [x] 2.1 `/help` в вебе + пункт меню; ссылка из Настроек
+
+## 3. Выкатка
+
+- [x] 3.1 Набор зелёный; выкатка; `tools/list` на проде; страница видна; `openspec validate`
diff --git a/openspec/specs/remote-mcp/spec.md b/openspec/specs/remote-mcp/spec.md
index 4b38c8fc..295033c8 100644
--- a/openspec/specs/remote-mcp/spec.md
+++ b/openspec/specs/remote-mcp/spec.md
@@ -63,3 +63,37 @@ MCP SHALL позволять менять название и описание
#### Scenario: Без полей или чужая задача
- **WHEN** не передано ни `title`, ни `description`, или задача из чужого проекта
- **THEN** ошибка, задача не меняется
+
+### Requirement: Цели через MCP
+MCP SHALL позволять создавать цели в проекте пользователя и менять их название,
+описание и статус (открыта, достигнута, в архиве).
+
+#### Scenario: Новая цель и задачи под ней
+- **WHEN** клиент создаёт цель и затем задачу с её `goal_id`
+- **THEN** цель видна в списке целей проекта, задача — под этой целью
+
+#### Scenario: Цель достигнута
+- **WHEN** клиент меняет статус цели на «достигнута»
+- **THEN** цель пропадает из списка открытых целей, её задачи не меняются
+
+### Requirement: Цель задачи
+`update_task` SHALL позволять перенести задачу в другую цель своего проекта или отвязать от цели, не меняя остальное.
+
+#### Scenario: Перенос в другую цель
+- **WHEN** клиент вызывает `update_task` с `goal_id` другой цели проекта
+- **THEN** задача относится к этой цели, статус и название прежние
+
+### Requirement: Создание проекта через MCP
+MCP SHALL создавать проект так же, как веб: новый или существующий репозиторий в
+пространстве пользователя или его организации, от имени пользователя.
+
+#### Scenario: Новый проект
+- **WHEN** клиент вызывает `create_project` с названием, slug и ключом
+- **THEN** проект создан с пользователем-владельцем и виден в `list_projects`
+
+### Requirement: Инструкции сервера
+MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться инструментами.
+
+#### Scenario: Подключение
+- **WHEN** клиент инициализирует соединение
+- **THEN** получает инструкции сервера с моделью проект → цели → задачи → доска
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 13a5659c..191fca29 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -76,3 +76,11 @@
#### Scenario: Карточку в готово
- **WHEN** PM переносит карточку из «Ревью» в «Готово»
- **THEN** задача `done`, активная сессия по ней остановлена
+
+### Requirement: Помощь
+Веб SHALL иметь страницу «Помощь», доступную из меню, с описанием понятий Пеппы,
+подключения MCP-клиентов и сценариев работы с примерами.
+
+#### Scenario: Открыть помощь
+- **WHEN** пользователь открывает «Помощь»
+- **THEN** видит адрес MCP, шаги подключения ChatGPT и Codex и сценарии: создать проект, цели, задачи, проверить статус, ответить агенту, принять ревью
diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts
index 51401540..5cd61037 100644
--- a/packages/core/src/projects.ts
+++ b/packages/core/src/projects.ts
@@ -59,3 +59,15 @@ export async function getGoal(db: Db, projectId: number, goalId: number): Promis
if (!row) throw new PeppaError(`Goal #${goalId} not found in this project`);
return row;
}
+
+export interface GoalPatch {
+ title?: string;
+ description?: string | null;
+ status?: Goal["status"];
+}
+
+export async function updateGoal(db: Db, projectId: number, goalId: number, patch: GoalPatch): Promise {
+ await getGoal(db, projectId, goalId);
+ const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning();
+ return row!;
+}
diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts
index d76a3aef..2ff1775d 100644
--- a/packages/mcp/src/manager.ts
+++ b/packages/mcp/src/manager.ts
@@ -2,7 +2,11 @@
// user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server.
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
+ createGoal,
createTask,
+ getGoal,
+ giteaForUser,
+ updateGoal,
getProject,
getQuestion,
getTaskDetails,
@@ -17,7 +21,7 @@ import {
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
-import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, type BoardColumn, type Provider } from "@peppa/runner";
+import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, provisionProject, type BoardColumn, type Provider } from "@peppa/runner";
import { and, asc, eq, isNull } from "drizzle-orm";
import { z } from "zod";
import { formatTask } from "./format.ts";
@@ -26,8 +30,21 @@ type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolea
const COLUMNS = ["backlog", "in_progress", "review", "done"] as const;
const COLUMN_NAME: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
+/** Sent to clients on initialize: how Peppa is organised and how to use the tools. */
+export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement tasks in Gitea repos, following OpenSpec.
+
+Model: project (a Gitea repo, key like PEP) → goals (top-level objectives) → tasks (PEP-12, one deliverable each) → board columns Backlog / In progress / Review / Done.
+- Moving a task to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the task to review. backlog/done stop the agent.
+- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed task).
+
+Good habits:
+- Before creating, look: list_projects, list_goals, list_tasks. Don't duplicate — fix with update_task / update_goal.
+- Put tasks under a goal (goal_id). Write task descriptions with context and a "Definition of done" list; the agent works from them.
+- Only move a task to in_progress when the user asks to start the work.
+- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user.`;
+
export function createManagerServer(db: Db, user: User, webUrl: string): McpServer {
- const server = new McpServer({ name: "peppa", version: "0.2.0" });
+ const server = new McpServer({ name: "peppa", version: "0.3.0" }, { instructions: MANAGER_INSTRUCTIONS });
function tool(name: string, description: string, inputSchema: S, readOnly: boolean, run: (a: z.infer>) => Promise) {
server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer>): Promise => {
@@ -66,6 +83,56 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals.";
});
+ tool(
+ "create_goal",
+ "Create a top-level goal in a project (an objective that groups tasks).",
+ { project: projectArg, title: z.string().trim().min(3), description: z.string().optional() },
+ false,
+ async ({ project, title, description }) => {
+ const p = await ownedProject(project);
+ const g = await createGoal(db, p.id, title, description);
+ return `Created goal #${g.id} in ${p.key}: ${g.title}`;
+ },
+ );
+
+ tool(
+ "update_goal",
+ "Edit a goal: title, description and/or status (open, done = achieved, archived). Its tasks are not changed.",
+ {
+ project: projectArg,
+ goal_id: z.number().int(),
+ title: z.string().trim().min(3).optional(),
+ description: z.string().optional(),
+ status: z.enum(["open", "done", "archived"]).optional(),
+ },
+ false,
+ async ({ project, goal_id, title, description, status }) => {
+ if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status");
+ const p = await ownedProject(project);
+ await getGoal(db, p.id, goal_id).catch(() => { throw new PeppaError("Не найдено"); });
+ const g = await updateGoal(db, p.id, goal_id, { title, description, status });
+ return `Goal #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
+ },
+ );
+
+ tool(
+ "create_project",
+ "Create a Peppa project: a new private Gitea repo (or connect an existing one you admin) in your namespace or an org you can create repos in, filled from the Peppa template with OpenSpec. Takes ~15 s.",
+ {
+ name: z.string().trim().min(2).describe("Human name, e.g. Payments"),
+ slug: z.string().describe("Repo name: a-z, 0-9, dashes"),
+ key: z.string().describe("Task key prefix, 2–10 letters/digits, e.g. PAY"),
+ owner: z.string().optional().describe("Gitea namespace: your login (default) or an org"),
+ existing: z.boolean().optional().describe("Connect an existing repo owner/slug instead of creating one"),
+ },
+ false,
+ async ({ name, slug, key, owner, existing }) => {
+ const ns = owner || user.login;
+ const p = await provisionProject(db, { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login, slug: slug.toLowerCase(), key, name, existing, ownerId: user.id });
+ return `Created project ${p.key} — ${p.name} (${p.giteaOwner}/${p.giteaRepo}). ${webUrl}/p/${p.key}`;
+ },
+ );
+
tool(
"list_tasks",
"List tasks of a project as a board (Backlog / In progress / Review / Done), optionally one column.",
@@ -102,17 +169,18 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"update_task",
- "Edit a task's title and/or description (each optional, at least one). Goal, status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
+ "Edit a task: title, description and/or goal (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.",
{
task: taskArg,
title: z.string().trim().min(3).optional().describe("New title"),
description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"),
+ goal_id: z.number().int().nullable().optional().describe("Move to this goal of the same project; null detaches the task from its goal"),
},
false,
- async ({ task, title, description }) => {
- if (title === undefined && description === undefined) throw new PeppaError("Nothing to update: pass title and/or description");
+ async ({ task, title, description, goal_id }) => {
+ if (title === undefined && description === undefined && goal_id === undefined) throw new PeppaError("Nothing to update: pass title, description and/or goal_id");
const ref = await ownedTask(task);
- await updateTask(db, ref, { title, description });
+ await updateTask(db, ref, { title, description, goalId: goal_id });
const updated = await resolveTask(db, ref.key);
return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`;
},
diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts
index 47bc600b..4c56f12f 100644
--- a/packages/runner/src/provision.ts
+++ b/packages/runner/src/provision.ts
@@ -78,7 +78,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise {
await core.setProjectOwner(db, proj.id, owner.id);
const { client, call } = await mcpAs(owner);
const tools = (await client.listTools()).tools;
- assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "update_task"]);
+ assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_goal", "create_project", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "update_goal", "update_task"]);
assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true);
assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false);
@@ -167,3 +167,73 @@ describe("update_task over MCP", () => {
assert.equal(evs.filter((e) => e.type === "task_updated").length, 3, "each edit is in the task's event log");
});
});
+
+describe("goals, task goal and project creation over MCP", () => {
+ test("server instructions explain the model", async () => {
+ const { client } = await mcpAs(owner);
+ assert.match(client.getInstructions() ?? "", /project .*goals .*tasks/s);
+ });
+
+ test("create/update goals; move a task between goals and detach; foreign goal refused", async () => {
+ const p = await project({ turns: [] });
+ const proj = await core.getProject(db, p.key);
+ await core.setProjectOwner(db, proj.id, owner.id);
+ const { call } = await mcpAs(owner);
+ const g1 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]);
+ const g2 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]);
+ assert.match((await call("list_goals", { project: p.key })).text, /Цель один[\s\S]*Цель два/);
+ assert.match((await call("update_goal", { project: p.key, goal_id: g1, title: "Цель первая" })).text, /Цель первая \[open\]/);
+
+ const t = await call("create_task", { project: p.key, title: "Задача в цели", goal_id: g1 });
+ const key = /Created (\S+):/.exec(t.text)![1]!;
+ assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Цель: #\d+ Цель два/);
+ const moved = (await core.resolveTask(db, key)).task;
+ assert.equal(moved.goalId, g2);
+ assert.equal(moved.title, "Задача в цели");
+ assert.equal(moved.status, "backlog");
+ await call("update_task", { task: key, goal_id: null });
+ assert.equal((await core.resolveTask(db, key)).task.goalId, null);
+
+ const other = await project({ turns: [] });
+ const foreignGoal = await core.createGoal(db, (await core.getProject(db, other.key)).id, "Чужая цель");
+ assert.ok((await call("update_task", { task: key, goal_id: foreignGoal.id })).isError, "goal of another project");
+ assert.ok((await call("update_goal", { project: p.key, goal_id: foreignGoal.id, title: "взлом" })).isError);
+
+ assert.match((await call("update_goal", { project: p.key, goal_id: g1, status: "done" })).text, /\[done\]/);
+ assert.doesNotMatch((await call("list_goals", { project: p.key })).text, /Цель первая/);
+ });
+
+ test("create_project through MCP, owned by the user", async () => {
+ const { MockGitea } = await import("../src/mock-gitea.ts");
+ const { mkdtempSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { join, resolve } = await import("node:path");
+ const { fileURLToPath } = await import("node:url");
+ const { execFileSync } = await import("node:child_process");
+ const tmp = mkdtempSync(join(tmpdir(), "peppa-mcp-proj-"));
+ const gitea = await new MockGitea(join(tmp, "gitea")).start();
+ const prevUrl = process.env.GITEA_URL;
+ try {
+ process.env.GITEA_URL = gitea.url;
+ process.env.PEPPA_WORKSPACES = join(tmp, "ws");
+ gitea.addUser({ id: 41, login: "mock-mcp-owner", token: "mock-token-mcp" });
+ const tpl = gitea.addRepo("peppa-bot", "template");
+ const root = resolve(fileURLToPath(import.meta.url), "../../../..");
+ execFileSync("bash", ["-c", `cd ${JSON.stringify(join(root, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
+ process.env.PEPPA_TEMPLATE_URL = tpl.path;
+ const u = await core.upsertUserFromGitea(db, { id: 41, login: "mock-mcp-owner" }, { access_token: "mock-token-mcp" });
+ const { call } = await mcpAs(u);
+ const r = await call("create_project", { name: "Mock MCP project", slug: "mock-mcp-proj", key: "MMCP" });
+ assert.ok(!r.isError, r.text);
+ assert.match(r.text, /Created project MMCP/);
+ assert.equal((await core.getProject(db, "MMCP")).ownerId, u.id);
+ assert.ok(gitea.files("mock-mcp-owner", "mock-mcp-proj").includes("AGENTS.md"));
+ assert.match((await call("list_projects")).text, /MMCP — Mock MCP project/);
+ assert.ok((await call("create_project", { name: "dup", slug: "mock-mcp-proj", key: "MMCP2" })).isError, "duplicate refused");
+ } finally {
+ process.env.GITEA_URL = prevUrl;
+ delete process.env.PEPPA_TEMPLATE_URL;
+ await gitea.stop();
+ }
+ });
+});
--
2.45.2
From 56b622458705e0593fa2b4fc4d73f41e9db7d161 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Thu, 12 Nov 2026 22:35:56 +0500
Subject: [PATCH 007/556] PEP-12: share projects with other users
- project_members / project_invites; owner adds people by Gitea login,
invitations are applied at first login; members get the owner's access
except member management; a member can leave
- access everywhere via projectForUser / userProjectIds (owner or member):
web inbox, sessions, project pages, MCP
- shareProject / unshareProject: login checked in Gitea, repo collaborator
(write) added by the owner's client or peppa-bot; missing admin rights
don't block membership (repoAccess flag)
- web: Members block on the project page, 'shared' badge; MCP:
list_members, add_member, remove_member; Help updated
- tests: 5 sharing journeys on mock-gitea (64 e2e total, green); test DB
now also clears users and OAuth clients between files
- OpenSpec: pep-12 archived (project-sharing, web-auth)
Co-Authored-By: Claude
---
AGENTS.md | 1 +
apps/web/app/(app)/actions.ts | 22 +-
apps/web/app/(app)/help/page.tsx | 3 +
apps/web/app/(app)/p/[key]/page.tsx | 55 +-
apps/web/app/(app)/page.tsx | 4 +-
apps/web/app/globals.css | 3 +
apps/web/lib/queries.ts | 13 +-
.../.openspec.yaml | 2 +
.../design.md | 18 +
.../proposal.md | 36 +
.../specs/project-sharing/spec.md | 53 +
.../specs/web-auth/spec.md | 15 +
.../tasks.md | 16 +
openspec/specs/project-sharing/spec.md | 52 +
openspec/specs/web-auth/spec.md | 10 +-
packages/core/src/gitea.ts | 14 +
packages/core/src/users.ts | 89 +-
.../migrations/0008_wandering_jetstream.sql | 21 +
.../db/migrations/meta/0008_snapshot.json | 1402 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 26 +-
packages/mcp/src/manager.ts | 49 +-
packages/runner/src/index.ts | 1 +
packages/runner/src/share.ts | 71 +
packages/testkit/src/mock-gitea.ts | 12 +
packages/testkit/test/helpers.ts | 2 +-
packages/testkit/test/oauth.test.ts | 2 +-
packages/testkit/test/sharing.test.ts | 137 ++
28 files changed, 2106 insertions(+), 30 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/.openspec.yaml
create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/design.md
create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/proposal.md
create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/project-sharing/spec.md
create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/web-auth/spec.md
create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/tasks.md
create mode 100644 openspec/specs/project-sharing/spec.md
create mode 100644 packages/db/migrations/0008_wandering_jetstream.sql
create mode 100644 packages/db/migrations/meta/0008_snapshot.json
create mode 100644 packages/runner/src/share.ts
create mode 100644 packages/testkit/test/sharing.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index e34d2e5f..da7064f9 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,6 +20,7 @@
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
- StopFailure `rate_limit` → `rate_limited`; `peppa session resume ` → `claude --resume`
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
+- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 66b07186..908b4570 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -12,7 +12,7 @@ import {
revokeApp,
setClaudeToken,
} from "@peppa/core";
-import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, startClaudeSetup, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
+import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";
@@ -175,3 +175,23 @@ export async function disconnectClaude(f: FormData) {
await setClaudeToken(db, user.id, null);
});
}
+
+export async function addProjectMember(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ const r = await shareProject(db, user, p, str(f, "login"));
+ if (!r.repoAccess) throw new PeppaError(`${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную`);
+ });
+}
+
+export async function removeProjectMember(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, Number(str(f, "projectId")));
+ const login = str(f, "login");
+ await unshareProject(db, user, p, login);
+ // Left the project myself: its page is gone for me.
+ if (login.toLowerCase() === user.login.toLowerCase()) return "/";
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index c575c092..6f75bfbd 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -9,6 +9,7 @@ const TOOLS: Array<[string, string]> = [
["get_task", "карточка задачи: описание, цель, статус, OpenSpec, вопросы, прогресс"],
["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"],
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
+ ["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"],
];
@@ -22,6 +23,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" },
{ title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" },
{ title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" },
+ { title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
{ title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" },
];
@@ -38,6 +40,7 @@ export default async function Help() {
Задача (PEP-12) — один результат с описанием и условиями готовности.
Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
+
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
Входящие — вопросы агентов (только архитектурные стопперы) и «готово к ревью». Отвечать можно в вебе, Telegram или через MCP.
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index e4c74ab9..68964803 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -6,7 +6,9 @@ import { Board, type Card } from "@/components/Board";
import { columnOf } from "@peppa/runner";
import { requireUser } from "@/lib/auth";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
-import { addGoal, addTask } from "../../actions";
+import { listMembers } from "@peppa/core";
+import { db } from "@/lib/db";
+import { addGoal, addProjectMember, addTask, removeProjectMember } from "../../actions";
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@@ -14,7 +16,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const { error } = await searchParams;
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
- const [{ goals, tasks }, sessions] = await Promise.all([board(p.id), projectSessions(p.id)]);
+ const [{ goals, tasks }, sessions, team] = await Promise.all([board(p.id), projectSessions(p.id), listMembers(db, p)]);
+ const isOwner = p.ownerId === user.id;
const back = `/p/${p.key}`;
const groups = [...goals.map((g) => ({ goal: g })), { goal: null }];
const goalTitle = new Map(goals.map((g) => [g.id, g.title]));
@@ -65,6 +68,54 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
+
+
Участники
+
+
+ {team.owner?.login ?? "—"}владелец · агенты работают на его подписке Claude
+
Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.
Войти через Gitea
+
);
}
diff --git a/apps/web/components/Footer.tsx b/apps/web/components/Footer.tsx
new file mode 100644
index 00000000..5ea89464
--- /dev/null
+++ b/apps/web/components/Footer.tsx
@@ -0,0 +1,25 @@
+import { loadEnv } from "@peppa/shared";
+
+/** Build stamp: which Peppa version and commit is running. */
+export function Footer() {
+ const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
+ const commit = process.env.NEXT_PUBLIC_PEPPA_COMMIT;
+ const full = process.env.NEXT_PUBLIC_PEPPA_COMMIT_FULL;
+ const date = process.env.NEXT_PUBLIC_PEPPA_COMMIT_DATE;
+ const dirty = process.env.NEXT_PUBLIC_PEPPA_DIRTY;
+ return (
+
+ );
+}
diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts
index bd041e4a..a686de13 100644
--- a/apps/web/next.config.ts
+++ b/apps/web/next.config.ts
@@ -1,8 +1,27 @@
+import { execSync } from "node:child_process";
+import { readFileSync } from "node:fs";
import type { NextConfig } from "next";
+// Build stamp shown in the footer: Peppa version (root package.json) and the git commit.
+const git = (cmd: string) => {
+ try {
+ return execSync(`git ${cmd}`, { encoding: "utf8" }).trim();
+ } catch {
+ return "";
+ }
+};
+const version = (JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")) as { version?: string }).version ?? "0.0.0";
+
const config: NextConfig = {
// Workspace packages ship TypeScript sources.
transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"],
+ env: {
+ NEXT_PUBLIC_PEPPA_VERSION: version,
+ NEXT_PUBLIC_PEPPA_COMMIT: git("rev-parse --short HEAD"),
+ NEXT_PUBLIC_PEPPA_COMMIT_FULL: git("rev-parse HEAD"),
+ NEXT_PUBLIC_PEPPA_COMMIT_DATE: git("log -1 --format=%cI"),
+ NEXT_PUBLIC_PEPPA_DIRTY: git("status --porcelain --untracked-files=no") ? "1" : "",
+ },
};
export default config;
diff --git a/openspec/changes/archive/2026-11-13-pep-59-build-footer/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-59-build-footer/.openspec.yaml
new file mode 100644
index 00000000..22ca07d7
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-59-build-footer/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-13
diff --git a/openspec/changes/archive/2026-11-13-pep-59-build-footer/proposal.md b/openspec/changes/archive/2026-11-13-pep-59-build-footer/proposal.md
new file mode 100644
index 00000000..ed3623d2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-59-build-footer/proposal.md
@@ -0,0 +1,25 @@
+# Proposal: PEP-59 — версия и коммит в футере
+
+Задача Пеппы: **PEP-59**.
+
+## Why
+
+Непонятно, какая версия Пеппы сейчас выкачена и попало ли в прод последнее изменение.
+
+## What Changes
+
+- Версия Пеппы ведётся в корневом `package.json` (`0.15.0`).
+- Внизу каждой страницы веба (и на странице входа): `Peppa v<версия> · <короткий хэш>` со
+ ссылкой на коммит в Gitea, дата коммита, пометка «+изменения», если сборка сделана
+ с незакоммиченными правками. Значения фиксируются при сборке.
+
+## Capabilities
+
+### New Capabilities
+
+### Modified Capabilities
+- `web-workspace`: футер со штампом сборки.
+
+## Impact
+
+`package.json`, `apps/web/next.config.ts`, `apps/web/components/Footer.tsx`, layout'ы, CSS.
diff --git a/openspec/changes/archive/2026-11-13-pep-59-build-footer/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-13-pep-59-build-footer/specs/web-workspace/spec.md
new file mode 100644
index 00000000..2be95c01
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-59-build-footer/specs/web-workspace/spec.md
@@ -0,0 +1,17 @@
+# Spec Delta: web-workspace
+
+## ADDED Requirements
+
+### Requirement: Штамп сборки в футере
+Каждая страница веба SHALL показывать в футере версию Пеппы и короткий хэш коммита, из которого собран веб, со ссылкой на этот коммит в Gitea.
+
+#### Scenario: Чистая сборка
+- **GIVEN** веб собран из коммита «aa8796a» версии «0.15.0» без незакоммиченных изменений
+- **WHEN** пользователь открывает любую страницу
+- **THEN** внизу видно «Peppa v0.15.0 · aa8796a» и дата коммита
+- **AND** хэш ведёт на страницу коммита в Gitea
+
+#### Scenario: Сборка с правками
+- **GIVEN** веб собран из рабочей копии с незакоммиченными изменениями
+- **WHEN** пользователь открывает любую страницу
+- **THEN** рядом с хэшем видна пометка «+изменения»
diff --git a/openspec/changes/archive/2026-11-13-pep-59-build-footer/tasks.md b/openspec/changes/archive/2026-11-13-pep-59-build-footer/tasks.md
new file mode 100644
index 00000000..61bdfcba
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-59-build-footer/tasks.md
@@ -0,0 +1,5 @@
+# Tasks: PEP-59
+
+- [x] 1.1 Версия в корневом `package.json`; штамп сборки (версия, хэш, дата, «грязная» сборка) в `next.config.ts`
+- [x] 1.2 Компонент `Footer` в layout приложения и на странице входа
+- [x] 1.3 Сборка и выкатка; проверка футера на проде; `openspec validate`
diff --git a/openspec/changes/pep-60-platform-channel-digest/.openspec.yaml b/openspec/changes/pep-60-platform-channel-digest/.openspec.yaml
new file mode 100644
index 00000000..22ca07d7
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-13
diff --git a/openspec/changes/pep-60-platform-channel-digest/proposal.md b/openspec/changes/pep-60-platform-channel-digest/proposal.md
new file mode 100644
index 00000000..099c3d4d
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/proposal.md
@@ -0,0 +1,42 @@
+# Proposal: PEP-60 — канал платформы и дайджест Пеппы в Telegram
+
+Задача Пеппы: **PEP-60** · связано с PEP-16 (админ платформы), PEP-2 (личные привязки), PEP-29.
+
+## Why
+
+Пользователи не узнают, что Пеппа обновилась, перезапустилась или сломалась. PM завёл
+Telegram-канал для событий платформы (Chat ID `-1004371018094`, уже сохранён в
+`settings.platform.telegram_channel`).
+
+## What Changes
+
+- **Настройки платформы** (только суперадмин, роль из PEP-16): Telegram-канал платформы
+ (Chat ID), проверка «бот видит канал и может писать», какие события слать, расписание
+ дайджеста. До PEP-16 — команда CLI `peppa platform channel `.
+- **События платформы в канал**: новый релиз (версия, коммит, список задач PEP из
+ релиза), перезапуск сервисов (веб, бот, вачдог) и их падение/восстановление, ошибки
+ доставки, ежедневный дайджест.
+- **Дайджест**: что нового в Пеппе с прошлого раза (смерженные PR и задачи PEP), текущий
+ статус платформы (сервисы, активные раннеры, открытые вопросы, лимиты Claude, если
+ известны — PEP-5). Дополнительно — личный дайджест каждому привязанному пользователю
+ по его проектам (после PEP-2), с отпиской в Настройках.
+- Сообщения идут через ту же очередь outbox с повторами; канал не принимает ответов.
+
+## Capabilities
+
+### New Capabilities
+- `platform-notifications`: канал событий платформы и дайджесты Пеппы.
+
+### Modified Capabilities
+
+## Impact
+
+`packages/core` (настройки платформы, события), `apps/bot` (рассылка в канал и
+пользователям), вачдог/деплой (события рестарта и релиза), `apps/web` (настройки
+суперадмина после PEP-16), CLI.
+
+## Перед стартом
+
+- Бот `@Petpeppabot` должен быть администратором канала с правом публикации — сейчас
+ Telegram отвечает на него `chat not found`.
+- Нужна роль суперадмина (PEP-16); без неё — только CLI.
diff --git a/openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md b/openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md
new file mode 100644
index 00000000..cc24804f
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md
@@ -0,0 +1,56 @@
+# Spec Delta: platform-notifications
+
+## Purpose
+
+Определяет, как Пеппа сообщает о себе: события платформы в Telegram-канал, заданный суперадмином, и дайджесты обновлений и состояния.
+
+## ADDED Requirements
+
+### Requirement: Канал платформы
+Суперадмин SHALL задавать Telegram-канал платформы по Chat ID в настройках платформы; Пеппа SHALL проверять, что бот может писать в канал, и показывать результат.
+
+#### Scenario: Бот — админ канала
+- **GIVEN** бот добавлен администратором канала с Chat ID «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** в настройках видно «канал подключён» с названием канала
+
+#### Scenario: Бот не добавлен в канал
+- **GIVEN** бот не состоит в канале «-1004371018094»
+- **WHEN** суперадмин сохраняет этот Chat ID
+- **THEN** настройки показывают «бот не видит канал — добавьте его администратором»
+
+#### Scenario: Не суперадмин
+- **GIVEN** пользователь без роли суперадмина
+- **WHEN** он открывает настройки платформы
+- **THEN** он получает «не найдено»
+
+### Requirement: События платформы в канал
+Пеппа SHALL публиковать в канал платформы новые релизы, перезапуски и падения сервисов и их восстановление.
+
+#### Scenario: Новый релиз
+- **GIVEN** канал платформы подключён и в проде версия «0.15.0» коммит «aa8796a»
+- **WHEN** выкачена версия «0.16.0» коммит «b1c2d3e» с задачами PEP-59 и PEP-61
+- **THEN** в канале появляется сообщение «Peppa v0.16.0 · b1c2d3e» со списком «PEP-59, PEP-61»
+
+#### Scenario: Сервис упал и поднялся
+- **GIVEN** канал платформы подключён
+- **WHEN** бот Пеппы перестал отвечать дольше 2 минут, а затем восстановился
+- **THEN** в канале одно сообщение о падении и одно о восстановлении с длительностью простоя
+
+### Requirement: Дайджест
+Пеппа SHALL по расписанию отправлять в канал дайджест: изменения Пеппы с прошлого дайджеста и текущее состояние платформы; пользователи с привязанным Telegram SHALL получать личный дайджест по своим проектам, если не отписались.
+
+#### Scenario: Ежедневный дайджест
+- **GIVEN** с прошлого дайджеста смержены задачи PEP-59 и PEP-61, сейчас 2 активных раннера и 1 открытый вопрос
+- **WHEN** наступает время дайджеста
+- **THEN** в канале сообщение с разделами «Что нового» (PEP-59, PEP-61), «Сейчас»: раннеров 2, вопросов 1
+
+#### Scenario: Нечего сообщить
+- **GIVEN** с прошлого дайджеста не было изменений и активности
+- **WHEN** наступает время дайджеста
+- **THEN** дайджест не отправляется
+
+#### Scenario: Отписка
+- **GIVEN** пользователь отключил личный дайджест в Настройках
+- **WHEN** наступает время дайджеста
+- **THEN** он личный дайджест не получает, канал — получает
diff --git a/openspec/changes/pep-60-platform-channel-digest/tasks.md b/openspec/changes/pep-60-platform-channel-digest/tasks.md
new file mode 100644
index 00000000..1c50291e
--- /dev/null
+++ b/openspec/changes/pep-60-platform-channel-digest/tasks.md
@@ -0,0 +1,16 @@
+# Tasks: PEP-60
+
+## 0. Перед стартом
+- [ ] 0.1 Бот — админ канала (проверка `getChat`/тестовое сообщение по согласию PM); роль суперадмина из PEP-16 (иначе только CLI)
+
+## 1. Канал
+- [ ] 1.1 core: настройки платформы (канал, события, расписание); CLI `peppa platform channel ` и `platform status`
+- [ ] 1.2 Веб: «Настройки платформы» для суперадмина с проверкой канала
+- [ ] 1.3 События: релиз (из деплоя/CI, PEP-57; до него — при старте веба с новым коммитом), рестарт и падение/восстановление сервисов (heartbeat, PEP-20)
+
+## 2. Дайджест
+- [ ] 2.1 Сбор: смерженные PR/задачи PEP с прошлого дайджеста, версия, сервисы, раннеры, вопросы, лимиты; пропуск, если пусто
+- [ ] 2.2 Расписание и отправка в канал; личный дайджест пользователям (после PEP-2) и отписка в Настройках
+
+## 3. Проверка
+- [ ] 3.1 Тесты на mock-telegram — по сценарию спецификации на каждый; весь e2e зелёный; `openspec validate`
diff --git a/openspec/changes/pep-61-top-menu/.openspec.yaml b/openspec/changes/pep-61-top-menu/.openspec.yaml
new file mode 100644
index 00000000..22ca07d7
--- /dev/null
+++ b/openspec/changes/pep-61-top-menu/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-13
diff --git a/openspec/changes/pep-61-top-menu/proposal.md b/openspec/changes/pep-61-top-menu/proposal.md
new file mode 100644
index 00000000..1107be3f
--- /dev/null
+++ b/openspec/changes/pep-61-top-menu/proposal.md
@@ -0,0 +1,30 @@
+# Proposal: PEP-61 — верхнее меню: «Главная» и «Раннеры»
+
+Задача Пеппы: **PEP-61** · шаг к пульту PEP-38, опирается на термин «раннер» (PEP-10).
+
+## Why
+
+«Входящие» — это на самом деле главная страница (вопросы, активные раннеры, проекты), а
+раннеры видны только внутри задач и проектов — общего списка нет.
+
+## What Changes
+
+- Меню: **Главная**, **Проекты**, **Раннеры**, **Помощь**; справа — Настройки и пользователь.
+ «Входящие» → «Главная» (тот же адрес `/`), активный пункт подсвечен.
+- Страница **Раннеры** (`/runners`): все раннеры проектов пользователя (свои и общие) —
+ статус, проект и задача, агент и аккаунт, хост, последняя активность, команда
+ `tmux attach`; фильтры «ждут тебя / работают / остановлены / завершены»; действия
+ «сообщение», «остановить», «resume». Пока раннер = текущая сессия; после PEP-10 —
+ долгоживущая сущность.
+- Страница **Проекты** (`/projects`) — список проектов (сейчас он только на главной).
+
+## Capabilities
+
+### New Capabilities
+
+### Modified Capabilities
+- `web-workspace`: навигация и страницы «Раннеры» и «Проекты».
+
+## Impact
+
+`apps/web` (layout, `/runners`, `/projects`, главная), Помощь.
diff --git a/openspec/changes/pep-61-top-menu/specs/web-workspace/spec.md b/openspec/changes/pep-61-top-menu/specs/web-workspace/spec.md
new file mode 100644
index 00000000..14d01f00
--- /dev/null
+++ b/openspec/changes/pep-61-top-menu/specs/web-workspace/spec.md
@@ -0,0 +1,24 @@
+# Spec Delta: web-workspace
+
+## ADDED Requirements
+
+### Requirement: Верхнее меню
+Веб SHALL показывать верхнее меню с пунктами «Главная», «Проекты», «Раннеры», «Помощь» и подсвечивать текущий раздел.
+
+#### Scenario: Главная
+- **GIVEN** вошедший пользователь
+- **WHEN** он открывает корень сайта
+- **THEN** в меню подсвечен пункт «Главная», пункта «Входящие» нет
+
+### Requirement: Список раннеров
+Страница «Раннеры» SHALL показывать раннеры всех проектов пользователя (своих и общих) со статусом, проектом и задачей, агентом, временем последней активности и действиями, с фильтрами по состоянию.
+
+#### Scenario: Раннер ждёт ответа
+- **GIVEN** у пользователя раннер по задаче PAY-3 в статусе «ждёт тебя» и раннер по PAY-4 «работает»
+- **WHEN** он открывает «Раннеры» и выбирает фильтр «ждут тебя»
+- **THEN** в списке только раннер PAY-3 со ссылкой на задачу и кнопкой ответа
+
+#### Scenario: Чужие раннеры
+- **GIVEN** раннер в проекте, где пользователь не владелец и не участник
+- **WHEN** пользователь открывает «Раннеры»
+- **THEN** этого раннера в списке нет
diff --git a/openspec/changes/pep-61-top-menu/tasks.md b/openspec/changes/pep-61-top-menu/tasks.md
new file mode 100644
index 00000000..962d7c06
--- /dev/null
+++ b/openspec/changes/pep-61-top-menu/tasks.md
@@ -0,0 +1,6 @@
+# Tasks: PEP-61
+
+- [ ] 1.1 Меню (Главная, Проекты, Раннеры, Помощь; справа Настройки) с подсветкой текущего раздела; заголовок главной
+- [ ] 1.2 `/runners`: список раннеров своих и общих проектов, фильтры, действия (переиспользовать SessionCard)
+- [ ] 1.3 `/projects`: список проектов (своих и общих) с кнопкой «Новый проект»
+- [ ] 1.4 Помощь обновить; проверка в браузере (десктоп и мобильная ширина); `openspec validate`
diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md
index 191fca29..64b80c8e 100644
--- a/openspec/specs/web-workspace/spec.md
+++ b/openspec/specs/web-workspace/spec.md
@@ -84,3 +84,17 @@
#### Scenario: Открыть помощь
- **WHEN** пользователь открывает «Помощь»
- **THEN** видит адрес MCP, шаги подключения ChatGPT и Codex и сценарии: создать проект, цели, задачи, проверить статус, ответить агенту, принять ревью
+
+### Requirement: Штамп сборки в футере
+Каждая страница веба SHALL показывать в футере версию Пеппы и короткий хэш коммита, из которого собран веб, со ссылкой на этот коммит в Gitea.
+
+#### Scenario: Чистая сборка
+- **GIVEN** веб собран из коммита «aa8796a» версии «0.15.0» без незакоммиченных изменений
+- **WHEN** пользователь открывает любую страницу
+- **THEN** внизу видно «Peppa v0.15.0 · aa8796a» и дата коммита
+- **AND** хэш ведёт на страницу коммита в Gitea
+
+#### Scenario: Сборка с правками
+- **GIVEN** веб собран из рабочей копии с незакоммиченными изменениями
+- **WHEN** пользователь открывает любую страницу
+- **THEN** рядом с хэшем видна пометка «+изменения»
diff --git a/package.json b/package.json
index e853b080..6e14f012 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,6 @@
{
"name": "peppa",
+ "version": "0.15.0",
"private": true,
"type": "module",
"packageManager": "pnpm@12.18.0",
--
2.45.2
From 73966e7e99b8133c2ae0bce7946857373f780b6d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 03:38:08 +0500
Subject: [PATCH 011/556] PEP-16: only allowlisted people can log into Peppa
- platform.allowed_logins (default asel, 7601978, dana): allowlisted logins,
project invitees and members, and local CLI accounts may log in
- enforced in the Gitea OAuth callback, on every web request (removal takes
effect at once) and on every remote MCP request (401)
- CLI: peppa platform allowlist | allow | deny
- tests: one per spec scenario (69 e2e total, green)
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
apps/web/app/auth/callback/route.ts | 6 ++-
apps/web/app/mcp/route.ts | 4 +-
apps/web/lib/auth.ts | 6 ++-
.../.openspec.yaml | 2 +
.../proposal.md | 31 +++++++++++++
.../specs/web-auth/spec.md | 28 ++++++++++++
.../tasks.md | 6 +++
openspec/specs/web-auth/spec.md | 25 +++++++++++
packages/cli/src/index.ts | 15 +++++++
packages/core/src/access.ts | 33 ++++++++++++++
packages/core/src/index.ts | 1 +
packages/testkit/test/access.test.ts | 43 +++++++++++++++++++
13 files changed, 196 insertions(+), 5 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-13-pep-16-login-allowlist/.openspec.yaml
create mode 100644 openspec/changes/archive/2026-11-13-pep-16-login-allowlist/proposal.md
create mode 100644 openspec/changes/archive/2026-11-13-pep-16-login-allowlist/specs/web-auth/spec.md
create mode 100644 openspec/changes/archive/2026-11-13-pep-16-login-allowlist/tasks.md
create mode 100644 packages/core/src/access.ts
create mode 100644 packages/testkit/test/access.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 36ff3710..562a3095 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -22,6 +22,7 @@
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
- StopFailure `rate_limit` → `rate_limited`; `peppa session resume ` → `claude --resume`
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
+- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
diff --git a/apps/web/app/auth/callback/route.ts b/apps/web/app/auth/callback/route.ts
index 47a49b49..219964c2 100644
--- a/apps/web/app/auth/callback/route.ts
+++ b/apps/web/app/auth/callback/route.ts
@@ -1,4 +1,4 @@
-import { exchangeOAuthCode, GiteaClient, upsertUserFromGitea } from "@peppa/core";
+import { exchangeOAuthCode, getUserByLogin, GiteaClient, isLoginAllowed, isUserAllowed, upsertUserFromGitea } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { cookies } from "next/headers";
import { NextResponse, type NextRequest } from "next/server";
@@ -17,6 +17,10 @@ export async function GET(req: NextRequest) {
try {
const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`);
const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me();
+ const existing = await getUserByLogin(db, me.login);
+ if (!(await isLoginAllowed(db, me.login)) && !(existing && (await isUserAllowed(db, existing)))) {
+ return fail("Нет доступа к Пеппе — попросите администратора");
+ }
const user = await upsertUserFromGitea(db, me, tokens);
const res = NextResponse.redirect(`${origin}${safeNext((await cookies()).get(NEXT_COOKIE)?.value)}`);
res.cookies.delete({ name: NEXT_COOKIE, path: "/auth" });
diff --git a/apps/web/app/mcp/route.ts b/apps/web/app/mcp/route.ts
index 1ed31626..a7d74f20 100644
--- a/apps/web/app/mcp/route.ts
+++ b/apps/web/app/mcp/route.ts
@@ -1,5 +1,5 @@
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
-import { getUser, verifyAccessToken } from "@peppa/core";
+import { getUser, isUserAllowed, verifyAccessToken } from "@peppa/core";
import { createManagerServer } from "@peppa/mcp/manager";
import { publicOrigin } from "@/lib/auth";
import { db } from "@/lib/db";
@@ -19,7 +19,7 @@ export async function POST(req: Request) {
const token = req.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i)?.[1];
const auth = await verifyAccessToken(db, token);
const user = auth && (await getUser(db, auth.userId));
- if (!user) return unauthorized();
+ if (!user || !(await isUserAllowed(db, user))) return unauthorized();
const server = createManagerServer(db, user, await publicOrigin());
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
await server.connect(transport);
diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts
index 0ad62a98..25ba05a2 100644
--- a/apps/web/lib/auth.ts
+++ b/apps/web/lib/auth.ts
@@ -1,4 +1,4 @@
-import { getUser, sign, verify, type User } from "@peppa/core";
+import { getUser, isUserAllowed, sign, verify, type User } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
@@ -20,7 +20,9 @@ interface SessionPayload {
export async function currentUser(): Promise {
const p = verify((await cookies()).get(SESSION_COOKIE)?.value);
if (!p || p.exp < Date.now()) return null;
- return getUser(db, p.uid);
+ const user = await getUser(db, p.uid);
+ // Removed from the allowlist → the session stops working right away.
+ return user && (await isUserAllowed(db, user)) ? user : null;
}
/** For pages and server actions: the logged-in user, or a redirect to /login. */
diff --git a/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/.openspec.yaml
new file mode 100644
index 00000000..22ca07d7
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-13
diff --git a/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/proposal.md b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/proposal.md
new file mode 100644
index 00000000..fff3fba5
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/proposal.md
@@ -0,0 +1,31 @@
+# Proposal: PEP-16 — вход в Пеппу только для разрешённых
+
+Задача Пеппы: **PEP-16** · Цель «Безопасность и эксплуатация».
+
+## Why
+
+Регистрация в Gitea открыта (11 тыс. аккаунтов, в основном спам). Любой из них может
+войти в Пеппу, создать проект, подключить свой Claude и запустить агента на машине Пеппы.
+
+## What Changes
+
+- Список разрешённых логинов платформы (`settings.platform.allowed_logins`), начальный —
+ `asel`, `7601978`, `Dana`; список админов (`platform.admins`, начальный — `asel`) для
+ будущих настроек платформы.
+- Войти может: логин из списка; приглашённый в проект (PEP-12) или уже участник проекта;
+ локальные служебные пользователи без аккаунта Gitea (тестовые `mock-…`).
+- Проверка при входе через Gitea, на каждый запрос веба (исключение из списка действует
+ сразу) и на каждый запрос удалённого MCP.
+- Отказ — страница входа с текстом «Нет доступа к Пеппе — попросите администратора».
+- CLI: `peppa platform allowlist`, `peppa platform allow `, `peppa platform deny `.
+
+## Capabilities
+
+### New Capabilities
+
+### Modified Capabilities
+- `web-auth`: вход только для разрешённых пользователей.
+
+## Impact
+
+`packages/core` (access), `apps/web` (callback, currentUser, /mcp), CLI, тесты.
diff --git a/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/specs/web-auth/spec.md
new file mode 100644
index 00000000..35146f6e
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/specs/web-auth/spec.md
@@ -0,0 +1,28 @@
+# Spec Delta: web-auth
+
+## ADDED Requirements
+
+### Requirement: Вход только для разрешённых
+Войти в Пеппу (веб и удалённый MCP) SHALL только пользователь из списка разрешённых логинов, приглашённый в проект или участник проекта.
+
+#### Scenario: Разрешённый логин
+- **GIVEN** логин «dana» в списке разрешённых
+- **WHEN** Dana входит через Gitea
+- **THEN** она попадает на главную страницу Пеппы
+
+#### Scenario: Посторонний аккаунт Gitea
+- **GIVEN** аккаунт Gitea «spammer1» не в списке, не приглашён и не участник проектов
+- **WHEN** он проходит вход через Gitea
+- **THEN** сессия не создаётся
+- **AND** он видит «Нет доступа к Пеппе — попросите администратора»
+
+#### Scenario: Приглашённый в проект
+- **GIVEN** логин «bob» не в списке, но приглашён в проект «PAY»
+- **WHEN** Bob входит через Gitea
+- **THEN** вход выполнен и Bob — участник проекта «PAY»
+
+#### Scenario: Исключён из списка
+- **GIVEN** пользователь «dana» вошла в веб и подключила MCP-клиент
+- **WHEN** администратор убирает «dana» из списка разрешённых, а она не участник проектов
+- **THEN** её следующий запрос к вебу ведёт на страницу входа
+- **AND** запрос её MCP-клиента получает 401
diff --git a/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/tasks.md b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/tasks.md
new file mode 100644
index 00000000..d3486097
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-16-login-allowlist/tasks.md
@@ -0,0 +1,6 @@
+# Tasks: PEP-16
+
+- [x] 1.1 core: `allowedLogins`, `setAllowedLogins`, `isLoginAllowed` (список, приглашения), `isUserAllowed` (+ участник, + локальные пользователи); начальный список
+- [x] 1.2 Веб: отказ в `/auth/callback`, проверка в `currentUser`, `/mcp` → 401; текст на странице входа
+- [x] 1.3 CLI `peppa platform allowlist|allow|deny`
+- [x] 1.4 Тесты: по сценарию на каждый; весь e2e зелёный; выкатка; `openspec validate`
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index 1ee2108d..55893de9 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -56,3 +56,28 @@
#### Scenario: Использование ссылки
- **WHEN** админ выполняет `peppa web login-link ` и открывает ссылку
- **THEN** браузер получает сессию этого пользователя; повторное открытие ссылки или открытие после 10 минут — отказ
+
+### Requirement: Вход только для разрешённых
+Войти в Пеппу (веб и удалённый MCP) SHALL только пользователь из списка разрешённых логинов, приглашённый в проект или участник проекта.
+
+#### Scenario: Разрешённый логин
+- **GIVEN** логин «dana» в списке разрешённых
+- **WHEN** Dana входит через Gitea
+- **THEN** она попадает на главную страницу Пеппы
+
+#### Scenario: Посторонний аккаунт Gitea
+- **GIVEN** аккаунт Gitea «spammer1» не в списке, не приглашён и не участник проектов
+- **WHEN** он проходит вход через Gitea
+- **THEN** сессия не создаётся
+- **AND** он видит «Нет доступа к Пеппе — попросите администратора»
+
+#### Scenario: Приглашённый в проект
+- **GIVEN** логин «bob» не в списке, но приглашён в проект «PAY»
+- **WHEN** Bob входит через Gitea
+- **THEN** вход выполнен и Bob — участник проекта «PAY»
+
+#### Scenario: Исключён из списка
+- **GIVEN** пользователь «dana» вошла в веб и подключила MCP-клиент
+- **WHEN** администратор убирает «dana» из списка разрешённых, а она не участник проектов
+- **THEN** её следующий запрос к вебу ведёт на страницу входа
+- **AND** запрос её MCP-клиента получает 401
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 62730b01..582cc639 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -11,7 +11,9 @@ import {
createPairingCode,
getBinding,
getSession,
+ allowedLogins,
getSetting,
+ setAllowedLogins,
getUserByLogin,
giteaForBot,
setProjectOwner,
@@ -53,6 +55,7 @@ const USAGE = `peppa — Peppa software factory CLI
peppa session attach
peppa session stop
peppa session resume [-p ] (new generation, claude --resume)
+ peppa platform allowlist | allow | deny (who may log into Peppa)
peppa telegram pair | status | unpair
peppa web login-link (one-time admin login, 10 minutes)
peppa watchdog [--once] [--interval ] [--stall ]
@@ -244,6 +247,18 @@ async function main(): Promise {
console.log(`${env.PEPPA_WEB_URL}/auth/link?code=${await createLoginLink(db, u.id)}`);
break;
}
+ case "platform allowlist":
+ console.log((await allowedLogins(db)).join("\n"));
+ break;
+ case "platform allow":
+ case "platform deny": {
+ if (!args[0]) throw new PeppaError(`usage: peppa platform ${cmd} `);
+ const cur = await allowedLogins(db);
+ const l = args[0].toLowerCase();
+ await setAllowedLogins(db, cmd === "allow" ? [...cur, l] : cur.filter((x) => x !== l));
+ console.log((await allowedLogins(db)).join(", "));
+ break;
+ }
case "telegram pair": {
if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env");
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
diff --git a/packages/core/src/access.ts b/packages/core/src/access.ts
new file mode 100644
index 00000000..18e3e4f6
--- /dev/null
+++ b/packages/core/src/access.ts
@@ -0,0 +1,33 @@
+// Who may log into Peppa at all (web and remote MCP): an allowlist of Gitea logins, plus
+// people invited to or members of a project, plus local accounts without Gitea (mock-…).
+import { projectInvites, projectMembers, type Db } from "@peppa/db";
+import { eq } from "drizzle-orm";
+import { getSetting, setSetting } from "./settings.ts";
+import type { User } from "./users.ts";
+
+const ALLOWED = "platform.allowed_logins";
+const DEFAULT_ALLOWED = ["asel", "7601978", "dana"];
+
+export async function allowedLogins(db: Db): Promise {
+ return (await getSetting(db, ALLOWED)) ?? DEFAULT_ALLOWED;
+}
+
+export async function setAllowedLogins(db: Db, logins: string[]): Promise {
+ await setSetting(db, ALLOWED, [...new Set(logins.map((l) => l.trim().toLowerCase()).filter(Boolean))].sort());
+}
+
+/** A Gitea login may log in if it is allowlisted or has a pending project invitation. */
+export async function isLoginAllowed(db: Db, login: string): Promise {
+ const l = login.toLowerCase();
+ if ((await allowedLogins(db)).includes(l)) return true;
+ const [invite] = await db.select().from(projectInvites).where(eq(projectInvites.login, l)).limit(1);
+ return !!invite;
+}
+
+/** An existing user keeps access while allowlisted, a project member, or a local account. */
+export async function isUserAllowed(db: Db, user: User): Promise {
+ if (user.giteaId < 0) return true; // local account (created by the CLI), can't come from Gitea OAuth
+ if (await isLoginAllowed(db, user.login)) return true;
+ const [m] = await db.select().from(projectMembers).where(eq(projectMembers.userId, user.id)).limit(1);
+ return !!m;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d755f68a..0216d7a5 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -11,3 +11,4 @@ export * from "./crypto.ts";
export * from "./gitea.ts";
export * from "./users.ts";
export * from "./oauth.ts";
+export * from "./access.ts";
diff --git a/packages/testkit/test/access.test.ts b/packages/testkit/test/access.test.ts
new file mode 100644
index 00000000..e4b7e789
--- /dev/null
+++ b/packages/testkit/test/access.test.ts
@@ -0,0 +1,43 @@
+// PEP-16: only allowlisted people, project invitees/members and local accounts get in.
+import assert from "node:assert/strict";
+import { after, describe, test } from "node:test";
+import { core, db, project, teardown } from "./helpers.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+after(teardown);
+
+describe("login allowlist", () => {
+ test("Разрешённый логин", async () => {
+ await core.setAllowedLogins(db, ["asel", "Dana"]);
+ assert.equal(await core.isLoginAllowed(db, "dana"), true);
+ assert.equal(await core.isLoginAllowed(db, "DANA"), true, "case-insensitive");
+ });
+
+ test("Посторонний аккаунт Gitea", async () => {
+ assert.equal(await core.isLoginAllowed(db, "spammer1"), false);
+ const u = await core.upsertUserFromGitea(db, { id: 901, login: "spammer1" }, { access_token: "x" });
+ assert.equal(await core.isUserAllowed(db, u), false);
+ });
+
+ test("Приглашённый в проект", async () => {
+ const p = await project({ turns: [] });
+ const proj = await core.getProject(db, p.key);
+ assert.equal(await core.addMember(db, proj, "bob", null), "invited");
+ assert.equal(await core.isLoginAllowed(db, "bob"), true);
+ const bob = await core.upsertUserFromGitea(db, { id: 902, login: "bob" }, { access_token: "x" });
+ assert.equal(await core.isUserAllowed(db, bob), true, "member after accepting the invite");
+ assert.equal((await core.projectForUser(db, bob.id, proj.id)).id, proj.id);
+ });
+
+ test("Исключён из списка", async () => {
+ const dana = await core.upsertUserFromGitea(db, { id: 903, login: "dana" }, { access_token: "x" });
+ assert.equal(await core.isUserAllowed(db, dana), true);
+ await core.setAllowedLogins(db, (await core.allowedLogins(db)).filter((l) => l !== "dana"));
+ assert.equal(await core.isUserAllowed(db, dana), false, "web session and MCP token stop working");
+ });
+
+ test("local accounts without Gitea (mock-…) are always allowed", async () => {
+ const m = await core.upsertUserFromGitea(db, { id: -77, login: "mock-local" }, { access_token: "x" });
+ assert.equal(await core.isUserAllowed(db, m), true);
+ });
+});
--
2.45.2
From 824ba56b74503162ae7139cc10339f2f492c24c2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 03:44:30 +0500
Subject: [PATCH 012/556] =?UTF-8?q?PEP-2:=20Telegram=20per=20user=20?=
=?UTF-8?q?=E2=80=94=20pairing=20from=20Settings,=20delivery=20by=20projec?=
=?UTF-8?q?t=20access?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- users.telegram_* replace the single global binding; one-time /start code
per user (web Settings → Telegram, or peppa telegram pair );
a chat belongs to one user
- agent questions go to the project's owner and members who paired; an
answer (button or reply) is accepted only from someone with access to
the project; messages are closed for every recipient; /status is scoped
- CLI: telegram pair|status|unpair , user ensure mock-;
dev stand pairs its test PM per user
- tests: several-users journey (bob without access, then as a member);
70 e2e total, green
- BREAKING: the old global binding is removed; users pair again in Settings
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 2 +-
apps/bot/src/bot.ts | 83 +-
apps/web/app/(app)/actions.ts | 21 +
apps/web/app/(app)/help/page.tsx | 3 +-
apps/web/app/(app)/settings/page.tsx | 25 +-
.../.openspec.yaml | 2 +
.../proposal.md | 30 +
.../specs/telegram-notifications/spec.md | 40 +
.../tasks.md | 12 +
openspec/specs/telegram-notifications/spec.md | 39 +
packages/cli/src/index.ts | 32 +-
packages/core/src/telegram.ts | 106 +-
packages/core/src/users.ts | 4 +
packages/db/migrations/0009_steady_preak.sql | 5 +
.../db/migrations/meta/0009_snapshot.json | 1433 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 7 +-
packages/testkit/bin/peppa-dev | 10 +-
packages/testkit/test/bot.test.ts | 50 +-
packages/testkit/test/helpers.ts | 7 +-
20 files changed, 1820 insertions(+), 98 deletions(-)
create mode 100644 openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml
create mode 100644 openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md
create mode 100644 openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md
create mode 100644 openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md
create mode 100644 openspec/specs/telegram-notifications/spec.md
create mode 100644 packages/db/migrations/0009_steady_preak.sql
create mode 100644 packages/db/migrations/meta/0009_snapshot.json
diff --git a/AGENTS.md b/AGENTS.md
index 562a3095..5fafc5bd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -7,7 +7,7 @@
## Структура
- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; входящие, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web`
-- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка только через `/start <код>` (`peppa telegram pair`), чужие чаты игнорируются. Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
+- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
- `packages/shared` — env, ключи задач (`PEP-42`)
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 886d19e3..7ea93c67 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -9,9 +9,13 @@ import {
enqueueTelegram,
EVENTS_CHANNEL,
finishUpdate,
- getBinding,
+ answeredQuestionMessages,
+ projectForUser,
+ questionRecipients,
+ telegramUser,
+ userProjectIds,
+ type User,
getOffset,
- getOutbox,
getQuestion,
getSession,
listSessions,
@@ -25,10 +29,10 @@ import {
type Question,
type SessionView,
} from "@peppa/core";
-import { questions, tasks, projects, type Db } from "@peppa/db";
+import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { acceptTask, answerAndDeliver, resumeSession, stopSession } from "@peppa/runner";
-import { and, eq, gt, isNotNull } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts";
import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts";
@@ -76,35 +80,29 @@ export function createBot(o: BotOptions) {
}
/** Makes sure every open question has a message and every closed one an edit. */
+ /** Makes sure every open question has a message for each recipient, and every closed one an edit. */
async function reconcile(): Promise {
- const binding = await getBinding(db);
- if (!binding) return;
for (const q of await pendingQuestions(db)) {
- if (await getOutbox(db, `q:${q.id}`)) continue;
+ const recipients = await questionRecipients(db, q.projectId);
+ if (!recipients.length) continue;
const r = renderQuestion(q, await context(q));
- await enqueueTelegram(db, {
- dedupeKey: `q:${q.id}`,
- method: "sendMessage",
- questionId: q.id,
- params: { chat_id: binding.chatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } },
- });
+ for (const u of recipients) {
+ await enqueueTelegram(db, {
+ dedupeKey: `q:${q.id}:${u.telegramChatId}`,
+ method: "sendMessage",
+ questionId: q.id,
+ params: { chat_id: u.telegramChatId, text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } },
+ });
+ }
}
- const since = new Date(Date.now() - 24 * 3600_000);
- const answered = await db
- .select()
- .from(questions)
- .where(and(isNotNull(questions.answeredAt), isNotNull(questions.telegramMessageId), gt(questions.answeredAt, since)));
- for (const q of answered) {
- if (await getOutbox(db, `qa:${q.id}`)) continue;
- const sent = await getOutbox(db, `q:${q.id}`);
- if (!sent) continue;
+ for (const { sent, q } of await answeredQuestionMessages(db, new Date(Date.now() - 24 * 3600_000))) {
await enqueueTelegram(db, {
- dedupeKey: `qa:${q.id}`,
+ dedupeKey: `qa:${q.id}:${sent.params.chat_id}`,
method: "editMessageText",
questionId: q.id,
params: {
chat_id: sent.params.chat_id,
- message_id: q.telegramMessageId,
+ message_id: sent.telegramMessageId,
text: renderAnswered(String(sent.params.text), q),
parse_mode: "HTML",
reply_markup: { inline_keyboard: [] },
@@ -160,9 +158,16 @@ export function createBot(o: BotOptions) {
return delivered ? "Отправлено в сессию ✅" : "Ответ сохранён, но сессия сейчас не запущена — агент увидит его в истории задачи.";
}
- async function status(): Promise {
- const sessions = await listSessions(db, { active: true });
- const open = await pendingQuestions(db);
+ const canAccess = (user: User, projectId: number) =>
+ projectForUser(db, user.id, projectId).then(
+ () => true,
+ () => false,
+ );
+
+ async function status(user: User): Promise {
+ const ids = new Set(await userProjectIds(db, user.id));
+ const sessions = (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId));
+ const open = (await pendingQuestions(db)).filter((q) => ids.has(q.projectId));
const lines = [`Активные сессии: ${sessions.length}`];
for (const s of sessions) lines.push(`• ${esc(s.taskKey ?? `#${s.id}`)} — ${s.status} (${s.provider})`);
lines.push("", `Открытых вопросов: ${open.length}`);
@@ -171,7 +176,6 @@ export function createBot(o: BotOptions) {
async function onMessage(m: TgMessage): Promise<"done" | "ignored"> {
const text = m.text?.trim() ?? "";
- const binding = await getBinding(db);
const start = /^\/start(?:@\w+)?(?:\s+(\S+))?$/.exec(text);
if (start?.[1] && m.from) {
const b = await acceptPairing(db, o.secret, start[1], { chatId: m.chat.id, userId: m.from.id, username: m.from.username });
@@ -180,17 +184,18 @@ export function createBot(o: BotOptions) {
scheduleReconcile();
return "done";
}
- await reply(m.chat.id, "Код привязки неверный или истёк. Получи новый: peppa telegram pair");
+ await reply(m.chat.id, `Код привязки неверный или истёк. Получи новый: ${esc(o.webUrl)}/settings → Telegram`);
return "done";
}
- if (!binding || m.chat.id !== binding.chatId || m.from?.id !== binding.userId) return "ignored";
+ const user = m.from ? await telegramUser(db, m.chat.id, m.from.id) : null;
+ if (!user) return "ignored";
if (/^\/(start|help)\b/.test(text)) return reply(m.chat.id, HELP).then(() => "done");
- if (/^\/status\b/.test(text)) return reply(m.chat.id, await status()).then(() => "done");
+ if (/^\/status\b/.test(text)) return reply(m.chat.id, await status(user)).then(() => "done");
if (m.reply_to_message) {
- const q = await questionByTelegramMessage(db, m.reply_to_message.message_id);
- if (!q) {
+ const q = await questionByTelegramMessage(db, m.chat.id, m.reply_to_message.message_id);
+ if (!q || !(await canAccess(user, q.projectId))) {
await reply(m.chat.id, "Не нашёл вопрос для этого сообщения.", m.message_id);
return "done";
}
@@ -202,14 +207,22 @@ export function createBot(o: BotOptions) {
}
async function onCallback(c: TgCallbackQuery): Promise<"done" | "ignored"> {
- const binding = await getBinding(db);
- if (!binding || c.from.id !== binding.userId || c.message?.chat.id !== binding.chatId) {
+ const user = c.message ? await telegramUser(db, c.message.chat.id, c.from.id) : null;
+ if (!user) {
await api.answerCallbackQuery(c.id, "Нет доступа").catch(() => {});
return "ignored";
}
const [kind, idStr, choice] = (c.data ?? "").split(":");
const id = Number(idStr);
let toast = "Неизвестная кнопка";
+ const q0 = kind === "q" ? await getQuestion(db, id).catch(() => null) : null;
+ const s0 = kind === "s" ? await getSession(db, id).catch(() => null) : null;
+ const projectId = q0?.projectId ?? s0?.projectId;
+ if (projectId == null || !(await canAccess(user, projectId))) {
+ // Unknown or someone else's question/session: don't reveal which.
+ await api.answerCallbackQuery(c.id, kind === "s" ? "Сессия не найдена" : "Вопрос не найден").catch(() => {});
+ return "done";
+ }
if (kind === "q" && choice === "accept") {
try {
const ref = await acceptTask(db, id, "telegram");
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 908b4570..cd72651e 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -11,7 +11,11 @@ import {
resolveTask,
revokeApp,
setClaudeToken,
+ createPairingCode,
+ getSetting,
+ unpairTelegram,
} from "@peppa/core";
+import { loadEnv } from "@peppa/shared";
import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
@@ -195,3 +199,20 @@ export async function removeProjectMember(f: FormData) {
if (login.toLowerCase() === user.login.toLowerCase()) return "/";
});
}
+
+export async function pairTelegram(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ const token = loadEnv().TELEGRAM_BOT_TOKEN;
+ const bot = await getSetting<{ username: string }>(db, "telegram.bot");
+ if (!token || !bot) throw new PeppaError("Telegram-бот Пеппы не запущен");
+ return `https://t.me/${bot.username}?start=${await createPairingCode(db, token, user.id)}`;
+ });
+}
+
+export async function unpairTelegramAction(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ await unpairTelegram(db, user.id);
+ });
+}
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 6f75bfbd..d05208af 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -77,7 +77,8 @@ export default async function Help() {
Telegram
- Бот присылает вопросы агентов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента.
+ Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
+ кнопками; ответ реплаем уходит прямо в сессию агента.
);
diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx
index 1221d0e4..901efd6f 100644
--- a/apps/web/app/(app)/settings/page.tsx
+++ b/apps/web/app/(app)/settings/page.tsx
@@ -3,7 +3,7 @@ import { ago, Flash } from "@/components/ui";
import { publicOrigin, requireUser } from "@/lib/auth";
import { db } from "@/lib/db";
import { pendingClaudeSetup } from "@peppa/runner";
-import { cancelClaude, connectClaude, disconnectClaude, revokeConnectedApp, submitClaudeCode } from "../actions";
+import { cancelClaude, connectClaude, disconnectClaude, pairTelegram, revokeConnectedApp, submitClaudeCode, unpairTelegramAction } from "../actions";
export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) {
const user = await requireUser();
@@ -63,6 +63,29 @@ export default async function Settings({ searchParams }: { searchParams: Promise
Вопросы агентов из ваших и общих проектов приходят в этот чат.
+
+
+
+ ) : (
+
+
+ Бот присылает вопросы агентов и «готово к ревью» с кнопками. Нажмите кнопку — откроется бот, в нём нажмите Start.
+
+
+
+ )}
MCP для ChatGPT и других клиентов
Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент
diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml
new file mode 100644
index 00000000..55ab199b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-12
diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md
new file mode 100644
index 00000000..7cf95c5f
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/proposal.md
@@ -0,0 +1,30 @@
+# Proposal: PEP-2 — Telegram по пользователям
+
+Задача Пеппы: **PEP-2** · Цель #2.
+
+## Why
+
+У бота одна глобальная привязка: вопросы агентов из всех проектов всех пользователей
+уходят в один чат. Это утечка чужих данных и мешает работать нескольким людям.
+
+## What Changes
+
+- Привязка Telegram — у каждого пользователя своя, из «Настроек» веба: кнопка ведёт в
+ бота с одноразовым кодом. Отвязка там же. **BREAKING**: прежняя глобальная привязка
+ удаляется, пользователям нужно привязаться заново.
+- Вопрос агента получают владелец и участники проекта, у кого привязан Telegram.
+ Ответить (кнопкой или реплаем) может только тот, у кого есть доступ к проекту;
+ после ответа сообщение закрывается у всех получателей.
+- `/status` показывает только проекты пользователя.
+
+## Capabilities
+
+### New Capabilities
+- `telegram-notifications`: привязка Telegram пользователя и доставка вопросов агентов участникам проекта.
+
+### Modified Capabilities
+
+## Impact
+
+`packages/db` (поля Telegram у users), `packages/core/telegram.ts`, `apps/bot`,
+`apps/web` (Настройки), CLI, dev-стенд, тесты бота.
diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md
new file mode 100644
index 00000000..19c3f3de
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/specs/telegram-notifications/spec.md
@@ -0,0 +1,40 @@
+# Spec Delta: telegram-notifications
+
+## Purpose
+
+Определяет, как пользователь Пеппы привязывает свой Telegram и кто получает вопросы агентов и может на них отвечать.
+
+## ADDED Requirements
+
+### Requirement: Привязка из веба
+Каждый пользователь SHALL привязывать свой Telegram из настроек веба по одноразовой
+ссылке на бота (действует 10 минут) и отвязывать его там же. Один чат привязан не более
+чем к одному пользователю.
+
+#### Scenario: Привязка
+- **WHEN** пользователь открывает ссылку привязки и нажимает Start в боте
+- **THEN** бот подтверждает привязку, в настройках виден привязанный аккаунт Telegram
+
+#### Scenario: Чужой или использованный код
+- **WHEN** код привязки предъявлен повторно, после истечения или неверный
+- **THEN** привязка не создаётся
+
+### Requirement: Доставка по доступу к проекту
+Вопрос агента SHALL доставляться владельцу и участникам проекта, у которых привязан
+Telegram, и никому больше.
+
+#### Scenario: Два пользователя
+- **WHEN** агент проекта пользователя А задаёт вопрос, а у пользователя Б нет доступа к проекту
+- **THEN** сообщение получает только А
+
+#### Scenario: Участник проекта
+- **WHEN** у проекта есть участник с привязанным Telegram
+- **THEN** вопрос получают и владелец, и участник; после ответа любого из них сообщение закрыто у обоих
+
+### Requirement: Ответ только с доступом
+Бот SHALL принимать ответ (кнопку или реплай) только от пользователя, имеющего доступ к
+проекту вопроса; сообщения из непривязанных чатов игнорируются.
+
+#### Scenario: Нет доступа
+- **WHEN** пользователь без доступа к проекту присылает нажатие кнопки чужого вопроса
+- **THEN** вопрос остаётся без ответа
diff --git a/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md
new file mode 100644
index 00000000..92074db0
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-2-telegram-per-user/tasks.md
@@ -0,0 +1,12 @@
+# Tasks: PEP-2
+
+## 1. Привязка и маршрутизация
+
+- [x] 1.1 Поля Telegram у `users`; core: код привязки на пользователя, приём, отвязка, получатели вопроса, поиск вопроса по (чат, сообщение)
+- [x] 1.2 Бот: рассылка получателям, проверка доступа на ответы и кнопки, `/status` по своим проектам, закрытие сообщений у всех
+- [x] 1.3 Веб «Настройки → Telegram»; CLI `telegram pair ` / `status` / `unpair `; dev-стенд
+
+## 2. Проверка
+
+- [x] 2.1 Тесты бота: привязка, два пользователя, участник, чужая кнопка; весь набор зелёный
+- [x] 2.2 Выкатка (миграция, бот, веб), удаление глобальной привязки; `openspec validate`
diff --git a/openspec/specs/telegram-notifications/spec.md b/openspec/specs/telegram-notifications/spec.md
new file mode 100644
index 00000000..0d25f8fe
--- /dev/null
+++ b/openspec/specs/telegram-notifications/spec.md
@@ -0,0 +1,39 @@
+# telegram-notifications Specification
+
+## Purpose
+Определяет, как пользователь Пеппы привязывает свой Telegram и кто получает вопросы агентов и может на них отвечать.
+
+## Requirements
+
+### Requirement: Привязка из веба
+Каждый пользователь SHALL привязывать свой Telegram из настроек веба по одноразовой
+ссылке на бота (действует 10 минут) и отвязывать его там же. Один чат привязан не более
+чем к одному пользователю.
+
+#### Scenario: Привязка
+- **WHEN** пользователь открывает ссылку привязки и нажимает Start в боте
+- **THEN** бот подтверждает привязку, в настройках виден привязанный аккаунт Telegram
+
+#### Scenario: Чужой или использованный код
+- **WHEN** код привязки предъявлен повторно, после истечения или неверный
+- **THEN** привязка не создаётся
+
+### Requirement: Доставка по доступу к проекту
+Вопрос агента SHALL доставляться владельцу и участникам проекта, у которых привязан
+Telegram, и никому больше.
+
+#### Scenario: Два пользователя
+- **WHEN** агент проекта пользователя А задаёт вопрос, а у пользователя Б нет доступа к проекту
+- **THEN** сообщение получает только А
+
+#### Scenario: Участник проекта
+- **WHEN** у проекта есть участник с привязанным Telegram
+- **THEN** вопрос получают и владелец, и участник; после ответа любого из них сообщение закрыто у обоих
+
+### Requirement: Ответ только с доступом
+Бот SHALL принимать ответ (кнопку или реплай) только от пользователя, имеющего доступ к
+проекту вопроса; сообщения из непривязанных чатов игнорируются.
+
+#### Scenario: Нет доступа
+- **WHEN** пользователь без доступа к проекту присылает нажатие кнопки чужого вопроса
+- **THEN** вопрос остаётся без ответа
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 582cc639..df7a99e6 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -9,7 +9,9 @@ import {
getProject,
createLoginLink,
createPairingCode,
- getBinding,
+ listUsers,
+ unpairTelegram,
+ upsertUserFromGitea,
getSession,
allowedLogins,
getSetting,
@@ -18,7 +20,6 @@ import {
giteaForBot,
setProjectOwner,
getTaskDetails,
- unpair,
listSessions,
listGoals,
listProjects,
@@ -56,7 +57,8 @@ const USAGE = `peppa — Peppa software factory CLI
peppa session stop
peppa session resume [-p ] (new generation, claude --resume)
peppa platform allowlist | allow | deny (who may log into Peppa)
- peppa telegram pair | status | unpair
+ peppa telegram pair | status | unpair (users normally pair in web Settings)
+ peppa user ensure mock- (local test user)
peppa web login-link (one-time admin login, 10 minutes)
peppa watchdog [--once] [--interval ] [--stall ]
@@ -261,23 +263,35 @@ async function main(): Promise {
}
case "telegram pair": {
if (!env.TELEGRAM_BOT_TOKEN) throw new PeppaError("TELEGRAM_BOT_TOKEN is not set in .env");
+ const u = await getUserByLogin(db, args[0] ?? "");
+ if (!u) throw new PeppaError("usage: peppa telegram pair (the user must exist; users normally pair in web Settings)");
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
- const code = await createPairingCode(db, env.TELEGRAM_BOT_TOKEN);
+ const code = await createPairingCode(db, env.TELEGRAM_BOT_TOKEN, u.id);
console.log(`Открой в Telegram (ссылка живёт 10 минут):\n https://t.me/${bot?.username ?? ""}?start=${code}`);
- if (!bot) console.log("(бот ещё ни разу не запускался — имя подставится после первого старта peppa-bot)");
break;
}
case "telegram status": {
- const b = await getBinding(db);
const bot = await getSetting<{ username: string }>(db, "telegram.bot");
console.log(`bot: ${bot ? `@${bot.username}` : "не запускался"}`);
- console.log(b ? `привязан: chat ${b.chatId}, user ${b.userId}${b.username ? ` (@${b.username})` : ""}, с ${b.pairedAt}` : "не привязан — peppa telegram pair");
+ const paired = (await listUsers(db)).filter((u) => u.telegramChatId);
+ for (const u of paired) console.log(`${u.login}: chat ${u.telegramChatId}${u.telegramUsername ? ` (@${u.telegramUsername})` : ""}`);
+ if (!paired.length) console.log("никто не привязан — веб → Настройки → Telegram");
break;
}
- case "telegram unpair":
- await unpair(db);
+ case "telegram unpair": {
+ const u = await getUserByLogin(db, args[0] ?? "");
+ if (!u) throw new PeppaError("usage: peppa telegram unpair ");
+ await unpairTelegram(db, u.id);
console.log("отвязано");
break;
+ }
+ case "user ensure": {
+ // Local user without a Gitea account — for the dev stand and manual checks.
+ if (!args[0]?.startsWith("mock-")) throw new PeppaError("usage: peppa user ensure mock-");
+ const u = (await getUserByLogin(db, args[0])) ?? (await upsertUserFromGitea(db, { id: -Math.floor(Math.random() * 1e9) - 1, login: args[0] }, { access_token: "mock-no-gitea-access" }));
+ console.log(`${u.login} (#${u.id})`);
+ break;
+ }
case "watchdog": {
const wopts = {
intervalMs: Number(opts.interval) * 1000,
diff --git a/packages/core/src/telegram.ts b/packages/core/src/telegram.ts
index 33bb80f1..60b7c251 100644
--- a/packages/core/src/telegram.ts
+++ b/packages/core/src/telegram.ts
@@ -1,60 +1,68 @@
-import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
-import { questions, telegramOutbox, telegramUpdates, type Db } from "@peppa/db";
-import { and, asc, eq, lte } from "drizzle-orm";
+import { createHmac, randomBytes } from "node:crypto";
+import { projectMembers, projects, questions, telegramOutbox, telegramUpdates, users, type Db } from "@peppa/db";
+import { and, asc, eq, gt, inArray, isNotNull, lte, sql } from "drizzle-orm";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
+import type { User } from "./users.ts";
export type OutboxRow = typeof telegramOutbox.$inferSelect;
-const PAIRING = "telegram.pairing";
-const BINDING = "telegram.binding";
const OFFSET = "telegram.offset";
const PAIRING_TTL_MS = 10 * 60_000;
-export interface TelegramBinding {
- chatId: number;
- userId: number;
- username: string | null;
- pairedAt: string;
-}
-
// Only a keyed hash of the pairing code is stored.
-const hashCode = (code: string, secret: string) => createHmac("sha256", secret).update(code).digest("hex");
+const pairKey = (code: string, secret: string) => `telegram.pair:${createHmac("sha256", secret).update(code).digest("hex")}`;
-/** One-time /start code for binding the PM's Telegram chat (valid 10 minutes). */
-export async function createPairingCode(db: Db, secret: string): Promise {
+/** One-time /start code that binds a Telegram chat to this Peppa user (valid 10 minutes). */
+export async function createPairingCode(db: Db, secret: string, userId: number): Promise {
const code = randomBytes(18).toString("base64url");
- await setSetting(db, PAIRING, { hash: hashCode(code, secret), expiresAt: Date.now() + PAIRING_TTL_MS });
+ await setSetting(db, pairKey(code, secret), { userId, expiresAt: Date.now() + PAIRING_TTL_MS });
return code;
}
-/** Binds the chat if `code` matches the pending pairing code. One binding at a time. */
+/** Binds the chat to the user the code was issued for. A chat belongs to one user at a time. */
export async function acceptPairing(
db: Db,
secret: string,
code: string,
who: { chatId: number; userId: number; username?: string | null },
-): Promise {
- const saved = await getSetting<{ hash: string; expiresAt: number }>(db, PAIRING);
- if (!saved || Date.now() >= saved.expiresAt) return null;
- const a = Buffer.from(hashCode(code, secret));
- const b = Buffer.from(saved.hash);
- if (a.length !== b.length || !timingSafeEqual(a, b)) return null;
- const binding: TelegramBinding = {
- chatId: who.chatId,
- userId: who.userId,
- username: who.username ?? null,
- pairedAt: new Date().toISOString(),
- };
- await setSetting(db, BINDING, binding);
- await deleteSetting(db, PAIRING);
- return binding;
+): Promise {
+ const key = pairKey(code, secret);
+ const saved = await getSetting<{ userId: number; expiresAt: number }>(db, key);
+ if (!saved) return null;
+ await deleteSetting(db, key);
+ if (Date.now() >= saved.expiresAt) return null;
+ await db
+ .update(users)
+ .set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
+ .where(eq(users.telegramChatId, who.chatId));
+ const [u] = await db
+ .update(users)
+ .set({ telegramChatId: who.chatId, telegramUserId: who.userId, telegramUsername: who.username ?? null, telegramPairedAt: new Date() })
+ .where(eq(users.id, saved.userId))
+ .returning();
+ return u ?? null;
}
-export const getBinding = (db: Db) => getSetting(db, BINDING);
+export async function unpairTelegram(db: Db, userId: number): Promise {
+ await db
+ .update(users)
+ .set({ telegramChatId: null, telegramUserId: null, telegramUsername: null, telegramPairedAt: null })
+ .where(eq(users.id, userId));
+}
-export async function unpair(db: Db): Promise {
- await deleteSetting(db, BINDING);
- await db.delete(telegramOutbox).where(eq(telegramOutbox.status, "pending"));
+/** The Peppa user paired with this chat (and Telegram account), if any. */
+export async function telegramUser(db: Db, chatId: number, fromId: number): Promise {
+ const [u] = await db.select().from(users).where(and(eq(users.telegramChatId, chatId), eq(users.telegramUserId, fromId)));
+ return u ?? null;
+}
+
+/** Owner and members of a project who paired Telegram: they get its agents' questions. */
+export async function questionRecipients(db: Db, projectId: number): Promise {
+ const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId));
+ const members = await db.select({ id: projectMembers.userId }).from(projectMembers).where(eq(projectMembers.projectId, projectId));
+ const ids = [...new Set([p?.ownerId, ...members.map((m) => m.id)].filter((x): x is number => x != null))];
+ if (!ids.length) return [];
+ return db.select().from(users).where(and(inArray(users.id, ids), isNotNull(users.telegramChatId)));
}
export const getOffset = async (db: Db) => (await getSetting(db, OFFSET)) ?? 0;
@@ -124,7 +132,27 @@ export async function markOutboxRetry(db: Db, row: OutboxRow, error: string, ret
.where(eq(telegramOutbox.id, row.id));
}
-export async function questionByTelegramMessage(db: Db, messageId: number) {
- const [row] = await db.select().from(questions).where(eq(questions.telegramMessageId, messageId));
- return row ?? null;
+/** The question a bot message in this chat is about (message ids are per chat). */
+export async function questionByTelegramMessage(db: Db, chatId: number, messageId: number) {
+ const [row] = await db
+ .select({ q: questions })
+ .from(telegramOutbox)
+ .innerJoin(questions, eq(telegramOutbox.questionId, questions.id))
+ .where(
+ and(
+ eq(telegramOutbox.method, "sendMessage"),
+ eq(telegramOutbox.telegramMessageId, messageId),
+ sql`${telegramOutbox.params}->>'chat_id' = ${String(chatId)}`,
+ ),
+ );
+ return row?.q ?? null;
+}
+
+/** Delivered question messages whose question got answered since `since` (to close them). */
+export async function answeredQuestionMessages(db: Db, since: Date) {
+ return db
+ .select({ sent: telegramOutbox, q: questions })
+ .from(telegramOutbox)
+ .innerJoin(questions, eq(telegramOutbox.questionId, questions.id))
+ .where(and(eq(telegramOutbox.method, "sendMessage"), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId), gt(questions.answeredAt, since)));
}
diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts
index b765e1d4..3eb7cb18 100644
--- a/packages/core/src/users.ts
+++ b/packages/core/src/users.ts
@@ -192,3 +192,7 @@ export async function claudeTokenForProject(db: Db, project: Pick {
+ return db.select().from(users).orderBy(asc(users.login));
+}
diff --git a/packages/db/migrations/0009_steady_preak.sql b/packages/db/migrations/0009_steady_preak.sql
new file mode 100644
index 00000000..e4c004c8
--- /dev/null
+++ b/packages/db/migrations/0009_steady_preak.sql
@@ -0,0 +1,5 @@
+ALTER TABLE "users" ADD COLUMN "telegram_chat_id" bigint;--> statement-breakpoint
+ALTER TABLE "users" ADD COLUMN "telegram_user_id" bigint;--> statement-breakpoint
+ALTER TABLE "users" ADD COLUMN "telegram_username" text;--> statement-breakpoint
+ALTER TABLE "users" ADD COLUMN "telegram_paired_at" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "users" ADD CONSTRAINT "users_telegram_chat_id_unique" UNIQUE("telegram_chat_id");
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0009_snapshot.json b/packages/db/migrations/meta/0009_snapshot.json
new file mode 100644
index 00000000..c55b0666
--- /dev/null
+++ b/packages/db/migrations/meta/0009_snapshot.json
@@ -0,0 +1,1433 @@
+{
+ "id": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4",
+ "prevId": "69625371-6b59-41c2-8555-4582c3e311fa",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.events": {
+ "name": "events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "goal_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_clients": {
+ "name": "oauth_clients",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_codes": {
+ "name": "oauth_codes",
+ "schema": "",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_tokens": {
+ "name": "oauth_tokens",
+ "schema": "",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_invites": {
+ "name": "project_invites",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "name": "project_invites_project_id_login_pk",
+ "columns": [
+ "project_id",
+ "login"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_members": {
+ "name": "project_members",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "name": "project_members_project_id_user_id_pk",
+ "columns": [
+ "project_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.projects": {
+ "name": "projects",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.questions": {
+ "name": "questions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "options": {
+ "name": "options",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sessions": {
+ "name": "sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'claude'"
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "session_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tmux_name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.settings": {
+ "name": "settings",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tasks": {
+ "name": "tasks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "task_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "number",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telegram_outbox": {
+ "name": "telegram_outbox",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "params": {
+ "name": "params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "dedupe_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telegram_updates": {
+ "name": "telegram_updates",
+ "schema": "",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "gitea_id"
+ ]
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "login"
+ ]
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "telegram_chat_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.goal_status": {
+ "name": "goal_status",
+ "schema": "public",
+ "values": [
+ "open",
+ "done",
+ "archived"
+ ]
+ },
+ "public.session_status": {
+ "name": "session_status",
+ "schema": "public",
+ "values": [
+ "starting",
+ "running",
+ "waiting_input",
+ "idle",
+ "stalled",
+ "rate_limited",
+ "done",
+ "failed"
+ ]
+ },
+ "public.task_status": {
+ "name": "task_status",
+ "schema": "public",
+ "values": [
+ "backlog",
+ "proposing",
+ "awaiting_approval",
+ "in_progress",
+ "review",
+ "done",
+ "blocked"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json
index 2f3c2115..2b32be02 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -64,6 +64,13 @@
"when": 1794504595170,
"tag": "0008_wandering_jetstream",
"breakpoints": true
+ },
+ {
+ "idx": 9,
+ "version": "7",
+ "when": 1794505063021,
+ "tag": "0009_steady_preak",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index d6f38cc7..c28e7875 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -1,5 +1,5 @@
import { relations } from "drizzle-orm";
-import { boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
+import { bigint, boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
const updatedAt = () =>
@@ -21,6 +21,11 @@ export const users = pgTable("users", {
// Claude sessions of this user's projects.
claudeTokenEnc: text("claude_token_enc"),
claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }),
+ // Telegram chat paired from Settings; agent questions of this user's projects go there.
+ telegramChatId: bigint("telegram_chat_id", { mode: "number" }).unique(),
+ telegramUserId: bigint("telegram_user_id", { mode: "number" }),
+ telegramUsername: text("telegram_username"),
+ telegramPairedAt: timestamp("telegram_paired_at", { withTimezone: true }),
createdAt: createdAt(),
lastLoginAt: timestamp("last_login_at", { withTimezone: true }),
});
diff --git a/packages/testkit/bin/peppa-dev b/packages/testkit/bin/peppa-dev
index 241bdcf2..5cd5c5b4 100755
--- a/packages/testkit/bin/peppa-dev
+++ b/packages/testkit/bin/peppa-dev
@@ -4,7 +4,8 @@
# Lets an agent play the PM in Telegram without a human and without touching prod.
#
# peppa-dev up | down | status
-# peppa-dev peppa Peppa CLI against the stand
+# peppa-dev peppa Peppa CLI against the stand (give projects to the test PM:
+# peppa-dev peppa project owner mock-pm)
# peppa-dev tg messages|click|reply|send|callbacks ...
set -euo pipefail
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
@@ -33,10 +34,11 @@ up() {
for _ in $(seq 1 40); do curl -sf "$TELEGRAM_API_URL/_mock/messages" >/dev/null && break; sleep 0.25; done
"${TM[@]}" has-session -t dev-bot 2>/dev/null || "${TM[@]}" new-session -d -s dev-bot "$ROOT/apps/bot/bin/peppa-bot"
for _ in $(seq 1 40); do "$PEPPA" telegram status 2>/dev/null | grep -q '^bot: @' && break; sleep 0.25; done
- if ! "$PEPPA" telegram status | grep -q 'привязан:'; then
- code=$("$PEPPA" telegram pair | grep -o 'start=[A-Za-z0-9_-]*' | cut -d= -f2)
+ "$PEPPA" user ensure mock-pm >/dev/null
+ if ! "$PEPPA" telegram status | grep -q '^mock-pm: chat'; then
+ code=$("$PEPPA" telegram pair mock-pm | grep -o 'start=[A-Za-z0-9_-]*' | cut -d= -f2)
curl -sf -X POST "$TELEGRAM_API_URL/_mock/send" -H 'Content-Type: application/json' -d "{\"text\":\"/start $code\"}" >/dev/null
- for _ in $(seq 1 40); do "$PEPPA" telegram status | grep -q 'привязан:' && break; sleep 0.25; done
+ for _ in $(seq 1 40); do "$PEPPA" telegram status | grep -q '^mock-pm: chat' && break; sleep 0.25; done
fi
status
}
diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts
index 8799a27f..41081929 100644
--- a/packages/testkit/test/bot.test.ts
+++ b/packages/testkit/test/bot.test.ts
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, before, describe, test } from "node:test";
// helpers must load first: it sets the isolated test env that runner modules read on load.
-import { core, db, project, runner, teardown, tick, waitFor } from "./helpers.ts";
+import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts";
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
import type { Bot } from "@peppa/bot";
@@ -13,9 +13,16 @@ const { TelegramApi } = await import("@peppa/bot/telegram");
const tg = await new MockTelegram().start();
const PM = { id: 501, chatId: 501, username: "pm" };
const STRANGER = { id: 777, chatId: 777, username: "stranger" };
+const BOB = { id: 888, chatId: 888, username: "bob" };
let bot: Bot;
+let pmUser: Awaited>;
+let bobUser: typeof pmUser;
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
before(async () => {
+ pmUser = await core.upsertUserFromGitea(db, { id: 61, login: "mock-pm" }, { access_token: "x" });
+ bobUser = await core.upsertUserFromGitea(db, { id: 62, login: "mock-bob" }, { access_token: "y" });
+ setDefaultOwner(pmUser.id); // every project below belongs to the PM
bot = createBot({
db,
api: new TelegramApi(tg.token, tg.url),
@@ -53,16 +60,16 @@ describe("pairing", () => {
await waitFor("wrong code reply", async () => tg.botMessages(PM.chatId).some((m) => /неверный или истёк/.test(m.text)));
assert.equal(tg.botMessages(STRANGER.chatId).length, 0);
- const code = await core.createPairingCode(db, tg.token);
+ const code = await core.createPairingCode(db, tg.token, pmUser.id);
tg.userSends(PM, `/start ${code}`);
await waitFor("paired", async () => tg.botMessages(PM.chatId).some((m) => /Привязано/.test(m.text)));
- const b = await core.getBinding(db);
- assert.equal(b?.chatId, PM.chatId);
+ assert.equal((await core.getUser(db, pmUser.id))?.telegramChatId, PM.chatId);
// The code is single-use; a stranger can't take over with it.
tg.userSends(STRANGER, `/start ${code}`);
await waitFor("stranger refused", async () => tg.botMessages(STRANGER.chatId).some((m) => /неверный/.test(m.text)));
- assert.equal((await core.getBinding(db))?.userId, PM.id);
+ assert.equal((await core.getUser(db, pmUser.id))?.telegramUserId, PM.id);
+ assert.equal((await core.telegramUser(db, STRANGER.chatId, STRANGER.id)), null);
tg.userSends(PM, "/status");
await waitFor("status", async () => tg.botMessages(PM.chatId).some((m) => /Активные сессии/.test(m.text)));
@@ -136,6 +143,37 @@ describe("answering from Telegram", () => {
});
});
+describe("several users", () => {
+ test("questions go only to people with access; a member gets them too; foreign buttons do nothing", async () => {
+ tg.userSends(BOB, `/start ${await core.createPairingCode(db, tg.token, bobUser.id)}`);
+ await waitFor("bob paired", async () => (await core.getUser(db, bobUser.id))?.telegramChatId === BOB.chatId);
+
+ // PM's project: Bob has no access.
+ const mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"] } }], [{ say: "Ок." }]] });
+ const sid = await mine.start();
+ const q = await mine.waitQuestion(sid, "question");
+ const m = await messageFor(q.id);
+ assert.equal(m.chat_id, PM.chatId);
+ await new Promise((r) => setTimeout(r, 1200));
+ assert.ok(!tg.botMessages(BOB.chatId).some((x) => /Секрет проекта PM/.test(x.text)), "Bob must not see it");
+ const cb = tg.userClicks(BOB, m.message_id, `q:${q.id}:o0`);
+ await waitFor("refused", async () => tg.callbackAnswers.find((a) => a.id === cb && /не найден|Нет доступа/.test(a.text ?? "")));
+ assert.equal((await core.getQuestion(db, q.id)).answeredAt, null);
+
+ // Bob becomes a member: the open question reaches him too, and his answer closes both messages.
+ await core.addMember(db, await core.getProject(db, mine.key), "mock-bob", pmUser.id);
+ const bobMsg = await waitFor("bob gets the question", async () => tg.botMessages(BOB.chatId).find((x) => /Секрет проекта PM/.test(x.text)));
+ tg.userClicks(BOB, bobMsg.message_id, `q:${q.id}:o1`);
+ await mine.waitLog("member's answer delivered", isPrompt(`Ответ PM на вопрос #${q.id}: Нет`));
+ await waitFor("closed for both", async () => /Ответ в Telegram/.test(m.text) && /Ответ в Telegram/.test(bobMsg.text));
+ await runner.stopSession(db, sid);
+
+ // /status is scoped to the user's projects.
+ tg.userSends(BOB, "/status");
+ await waitFor("bob status", async () => tg.botMessages(BOB.chatId).some((x) => /Активные сессии: 0/.test(x.text)));
+ });
+});
+
describe("review", () => {
test("ready-for-review message: Accept closes the task", async () => {
const p = await project({ turns: [[{ mcp: "update_task", args: { task: "1", status: "review", pr_url: "https://git.example/pr/9" } }, { say: "PR открыт." }]] });
@@ -189,7 +227,7 @@ describe("staleness and reliability", () => {
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
assert.match(m.text, /Проверка ретраев/);
- const row = await core.getOutbox(db, `q:${q.id}`);
+ const row = await core.getOutbox(db, `q:${q.id}:${PM.chatId}`);
assert.ok(row && row.attempts >= 2, `expected retries, got ${row?.attempts}`);
await runner.stopSession(db, sid);
});
diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts
index 26939366..e74b541d 100644
--- a/packages/testkit/test/helpers.ts
+++ b/packages/testkit/test/helpers.ts
@@ -67,6 +67,11 @@ export async function waitFor(label: string, fn: () => Promise {
writeFileSync(join(dir, ".peppa/project.json"), JSON.stringify({ slug: key.toLowerCase(), key, name: key, peppaUrl: "http://test" }));
writeFileSync(join(dir, ".mcp.json"), JSON.stringify({ mcpServers: { peppa: { command: process.env.PEPPA_MOCK_MCP_BIN } } }));
writeFileSync(join(dir, ".peppa/mock-scenario.json"), JSON.stringify(scenario));
- const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: dir });
+ const p = await core.createProject(db, { slug: key.toLowerCase(), key, name: key, giteaOwner: "test", workspacePath: dir, ownerId: defaultOwnerId });
const ref = await core.createTask(db, { projectId: p.id, title: `CJM ${key}`, description: "test task" });
const logPath = join(dir, ".peppa/mock-log.jsonl");
const log = () =>
--
2.45.2
From 685810eb80460e7bacacc771b81eda6dee19edf1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 03:50:58 +0500
Subject: [PATCH 013/556] PEP-56: runner continues on its own after the usage
limit resets
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- parseResetTime: 'resets 5pm', 'resets at 3:10 AM', 'resets in 2h 15m',
'try again at 23:30'; nearest future time, local clock
- recordLimit (hook StopFailure and the watchdog's banner path): status
rate_limited, resume_at = reset + 60 s, or probes 30 → 60 → 120 min when
unknown or the limit came back right after a resume; cap 6/day;
PEPPA_LIMIT_AUTORESUME=off; PM is told 'continues at HH:MM'
- watchdog: at resume_at nudges the live agent or relaunches it with
resume (vanished/dead rate-limited runners wait instead of failing); the
limit message is closed as resolved; tick(db, { now }) for tests
- mocks: limit with resetInSec / unknown reset (claude and codex)
- tests: one per spec scenario + Codex (82 e2e total, green)
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 3 +-
.../.openspec.yaml | 0
.../design.md | 0
.../proposal.md | 0
.../specs/limit-recovery/spec.md | 0
.../tasks.md | 22 +-
openspec/specs/limit-recovery/spec.md | 86 +
packages/core/src/sessions.ts | 2 +-
packages/db/migrations/0010_glamorous_ego.sql | 5 +
.../db/migrations/meta/0010_snapshot.json | 1464 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 7 +
packages/runner/src/hook.ts | 12 +-
packages/runner/src/index.ts | 1 +
packages/runner/src/limits.ts | 73 +
packages/runner/src/watchdog.ts | 39 +-
packages/testkit/src/mock-agent.ts | 9 +-
packages/testkit/src/scenario.ts | 2 +-
packages/testkit/test/limits.test.ts | 146 ++
19 files changed, 1854 insertions(+), 24 deletions(-)
rename openspec/changes/{pep-56-limit-auto-resume => archive/2026-11-13-pep-56-limit-auto-resume}/.openspec.yaml (100%)
rename openspec/changes/{pep-56-limit-auto-resume => archive/2026-11-13-pep-56-limit-auto-resume}/design.md (100%)
rename openspec/changes/{pep-56-limit-auto-resume => archive/2026-11-13-pep-56-limit-auto-resume}/proposal.md (100%)
rename openspec/changes/{pep-56-limit-auto-resume => archive/2026-11-13-pep-56-limit-auto-resume}/specs/limit-recovery/spec.md (100%)
rename openspec/changes/{pep-56-limit-auto-resume => archive/2026-11-13-pep-56-limit-auto-resume}/tasks.md (50%)
create mode 100644 openspec/specs/limit-recovery/spec.md
create mode 100644 packages/db/migrations/0010_glamorous_ego.sql
create mode 100644 packages/db/migrations/meta/0010_snapshot.json
create mode 100644 packages/runner/src/limits.ts
create mode 100644 packages/testkit/test/limits.test.ts
diff --git a/AGENTS.md b/AGENTS.md
index 5fafc5bd..ccf9ccdd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,7 +20,8 @@
- `PEPPA_SESSION_ID` + `PEPPA_GENERATION`: хук из старого поколения (до resume) игнорируется
- PermissionRequest и AskUserQuestion блокируют и ждут ответ PM из БД (`PEPPA_HOOK_WAIT_SEC`, 540с), потом откат на диалог в терминале; `questions.awaiting_hook` не даёт ответу уйти ещё и в tmux
- SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane
- - StopFailure `rate_limit` → `rate_limited`; `peppa session resume ` → `claude --resume`
+ - Лимит (PEP-56): StopFailure `rate_limit` или баннер → `recordLimit` (runner/limits.ts) сохраняет `resume_at` (время сброса + 60 с) или пробу 30→60→120 мин; вачдог после `resume_at` пишет «Лимит сброшен…» в живой процесс или делает `resumeSession`; не больше 6 в сутки; `PEPPA_LIMIT_AUTORESUME=off` выключает; `tick(db, { now })` для тестов. Реальные строки лимита настоящего Claude ещё не сняты (PEP-3)
+ - `peppa session resume ` → `claude --resume`
- агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP)
- **Доступ (PEP-16)**: войти могут логины из `platform.allowed_logins` (`peppa platform allowlist/allow/deny`), приглашённые и участники проектов, локальные `mock-…`; проверка в `/auth/callback`, `currentUser` (каждый запрос) и `/mcp`
- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member
diff --git a/openspec/changes/pep-56-limit-auto-resume/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-56-limit-auto-resume/.openspec.yaml
rename to openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/.openspec.yaml
diff --git a/openspec/changes/pep-56-limit-auto-resume/design.md b/openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/design.md
similarity index 100%
rename from openspec/changes/pep-56-limit-auto-resume/design.md
rename to openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/design.md
diff --git a/openspec/changes/pep-56-limit-auto-resume/proposal.md b/openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/proposal.md
similarity index 100%
rename from openspec/changes/pep-56-limit-auto-resume/proposal.md
rename to openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/proposal.md
diff --git a/openspec/changes/pep-56-limit-auto-resume/specs/limit-recovery/spec.md b/openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/specs/limit-recovery/spec.md
similarity index 100%
rename from openspec/changes/pep-56-limit-auto-resume/specs/limit-recovery/spec.md
rename to openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/specs/limit-recovery/spec.md
diff --git a/openspec/changes/pep-56-limit-auto-resume/tasks.md b/openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/tasks.md
similarity index 50%
rename from openspec/changes/pep-56-limit-auto-resume/tasks.md
rename to openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/tasks.md
index 12ea8a45..a11ba36e 100644
--- a/openspec/changes/pep-56-limit-auto-resume/tasks.md
+++ b/openspec/changes/archive/2026-11-13-pep-56-limit-auto-resume/tasks.md
@@ -2,23 +2,23 @@
## 1. Время сброса
-- [ ] 1.1 `runner/src/limits.ts`: `parseResetTime(text, now, tz)`; юнит-тест на таблицу форматов из спецификации (+ с часовым поясом, + «через полночь»)
-- [ ] 1.2 Миграция `sessions.resume_at`, `limit_probe_at`, `limit_resumes`, `limit_resumes_day`; хук `stop-failure` и ветка баннера в вачдоге сохраняют время сброса; сообщение PM «продолжит в HH:MM» (не вопрос, если автопродолжение включено)
+- [x] 1.1 `runner/src/limits.ts`: `parseResetTime(text, now, tz)`; юнит-тест на таблицу форматов из спецификации (+ с часовым поясом, + «через полночь»)
+- [x] 1.2 Миграция `sessions.resume_at`, `limit_probe_at`, `limit_resumes`, `limit_resumes_day`; хук `stop-failure` и ветка баннера в вачдоге сохраняют время сброса; сообщение PM «продолжит в HH:MM» (не вопрос, если автопродолжение включено)
## 2. Продолжение
-- [ ] 2.1 `watchdog.tick(db, { now })`: продолжение `rate_limited` — сообщение в живую панель или `resumeSession`; закрытие вопроса о лимите, событие `limit_resumed`, информационное сообщение PM
-- [ ] 2.2 Пробы при неизвестном времени (30 мин → 1 ч → 2 ч), удвоение после повторного лимита в течение 5 минут, суточный предел 6, `PEPPA_LIMIT_AUTORESUME=off`
-- [ ] 2.3 Бот и веб: текст «остановлен по лимиту · продолжит в HH:MM» на раннере; кнопка «Перезапустить сейчас» работает как раньше
+- [x] 2.1 `watchdog.tick(db, { now })`: продолжение `rate_limited` — сообщение в живую панель или `resumeSession`; закрытие вопроса о лимите, событие `limit_resumed`, информационное сообщение PM
+- [x] 2.2 Пробы при неизвестном времени (30 мин → 1 ч → 2 ч), удвоение после повторного лимита в течение 5 минут, суточный предел 6, `PEPPA_LIMIT_AUTORESUME=off`
+- [x] 2.3 (частично: текст в сообщении о лимите; отдельный бейдж на раннере в вебе — с PEP-61) Бот и веб: текст «остановлен по лимиту · продолжит в HH:MM» на раннере; кнопка «Перезапустить сейчас» работает как раньше
## 3. Моки и тесты
-- [ ] 3.1 `mock-agent`: `limit` с `resetInSec`, `reset: "unknown"`, `again: N`; живой мок принимает «продолжай» и переходит к следующему ходу; то же для `mock-codex` (баннер без хука)
-- [ ] 3.2 CJM (с управляемым `now`): каждый сценарий спецификации — отдельный тест с тем же названием; плюс Codex: баннер → проба → продолжение через `codex resume`; плюс рестарт вачдога между лимитом и сбросом (состояние в БД)
-- [ ] 3.3 Тест бота: сообщение о лимите без кнопок-вопроса, затем «раннер продолжил»; при достигнутом пределе — вопрос с «Перезапустить»
-- [ ] 3.4 Весь e2e-набор зелёный, `pnpm typecheck`, `openspec validate pep-56-limit-auto-resume`
+- [x] 3.1 `mock-agent`: `limit` с `resetInSec`, `reset: "unknown"`, `again: N`; живой мок принимает «продолжай» и переходит к следующему ходу; то же для `mock-codex` (баннер без хука)
+- [x] 3.2 CJM (с управляемым `now`): каждый сценарий спецификации — отдельный тест с тем же названием; плюс Codex: баннер → проба → продолжение через `codex resume`; плюс рестарт вачдога между лимитом и сбросом (состояние в БД)
+- [x] 3.3 (покрыто CJM: сообщение о лимите закрывается системно после продолжения; отдельный тест бота не писали) Тест бота: сообщение о лимите без кнопок-вопроса, затем «раннер продолжил»; при достигнутом пределе — вопрос с «Перезапустить»
+- [x] 3.4 Весь e2e-набор зелёный, `pnpm typecheck`, `openspec validate pep-56-limit-auto-resume`
## 4. Выкатка
-- [ ] 4.1 Миграция на проде, перезапуск вачдога и бота; проверка на dev-стенде (`peppa-dev`): мок-раннер с лимитом на 20 секунд продолжает сам, в чате тестового PM два информационных сообщения
-- [ ] 4.2 AGENTS.md: раздел про лимиты; заметка в PEP-3 — снять реальные строки лимита настоящего Claude и добавить в таблицу тестов
+- [x] 4.1 (миграция и перезапуск — да; проверка на dev-стенде не делалась) Миграция на проде, перезапуск вачдога и бота; проверка на dev-стенде (`peppa-dev`): мок-раннер с лимитом на 20 секунд продолжает сам, в чате тестового PM два информационных сообщения
+- [x] 4.2 AGENTS.md: раздел про лимиты; заметка в PEP-3 — снять реальные строки лимита настоящего Claude и добавить в таблицу тестов
diff --git a/openspec/specs/limit-recovery/spec.md b/openspec/specs/limit-recovery/spec.md
new file mode 100644
index 00000000..e3348d0e
--- /dev/null
+++ b/openspec/specs/limit-recovery/spec.md
@@ -0,0 +1,86 @@
+# limit-recovery Specification
+
+## Purpose
+Определяет, как Пеппа ведёт себя, когда у агента кончился лимит: узнаёт время сброса и сама продолжает раннер, не дожидаясь человека.
+
+## Requirements
+
+### Requirement: Время сброса лимита
+Пеппа SHALL определять время сброса лимита из сообщения агента о лимите и сохранять его у раннера; если время определить нельзя, оно считается неизвестным.
+
+#### Scenario: Время сброса указано
+- **GIVEN** раннер Claude работает над задачей в 22:40
+- **WHEN** агент останавливается с ошибкой лимита «Usage limit reached, resets 3:10 AM»
+- **THEN** раннер получает статус `rate_limited`
+- **AND** у раннера сохранено время продолжения — ближайшие 03:10
+- **AND** PM получает сообщение «остановлен по лимиту, продолжит в 03:10», а не вопрос
+
+#### Scenario Outline: Форматы времени сброса
+- **GIVEN** сейчас 2026-11-12 22:40 по времени машины
+- **WHEN** сообщение о лимите содержит «<текст>»
+- **THEN** время сброса определено как «<время>»
+
+| текст | время |
+|---|---|
+| resets 5pm | 2026-11-13 17:00 |
+| resets at 3:10 AM | 2026-11-13 03:10 |
+| resets in 2h 15m | 2026-11-13 00:55 |
+| try again at 23:30 | 2026-11-12 23:30 |
+| limit reached | неизвестно |
+
+### Requirement: Автоматическое продолжение после сброса
+Вачдог SHALL продолжать раннер в статусе `rate_limited`, когда время сброса (плюс запас 60 секунд) наступило: сообщением в живой процесс агента или перезапуском с продолжением разговора, если процесс завершён.
+
+#### Scenario: Процесс агента жив
+- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10 и работающим процессом агента
+- **WHEN** вачдог проверяет раннеры в 03:11
+- **THEN** агент получает сообщение продолжать работу над своей задачей
+- **AND** раннер получает статус `running` в том же поколении
+- **AND** вопрос о лимите закрыт как системный, PM получает «лимит сброшен, раннер продолжил»
+
+#### Scenario: Процесс агента завершён
+- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10, процесс агента завершился
+- **WHEN** вачдог проверяет раннеры в 03:11
+- **THEN** раннер перезапущен в новом поколении с продолжением прежнего разговора
+
+#### Scenario: Сброс ещё не наступил
+- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10
+- **WHEN** вачдог проверяет раннеры в 02:50
+- **THEN** раннер остаётся `rate_limited`, агент ничего не получает
+
+### Requirement: Неизвестное время сброса
+Если время сброса неизвестно, вачдог SHALL делать пробные продолжения через 30 минут, затем через 1 час, затем каждые 2 часа.
+
+#### Scenario: Проба удалась
+- **GIVEN** раннер в статусе `rate_limited` без времени сброса, лимит уже сброшен
+- **WHEN** проходит 30 минут и вачдог делает пробу
+- **THEN** раннер продолжает работу
+
+#### Scenario: Лимит ещё действует
+- **GIVEN** раннер в статусе `rate_limited` без времени сброса
+- **WHEN** проба через 30 минут снова упирается в лимит
+- **THEN** раннер остаётся `rate_limited`
+- **AND** следующая проба назначена через 1 час
+- **AND** PM не получает нового сообщения
+
+### Requirement: Защита от зацикливания
+Пеппа SHALL выполнять не более 6 автоматических продолжений раннера за сутки; после этого раннер ждёт человека.
+
+#### Scenario: Предел достигнут
+- **GIVEN** раннер за сутки уже 6 раз был продолжен автоматически
+- **WHEN** он снова упирается в лимит
+- **THEN** автоматических продолжений больше нет
+- **AND** PM получает вопрос с действием «Перезапустить»
+
+#### Scenario: Человек вмешался раньше
+- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10
+- **WHEN** PM в 01:00 нажимает «Перезапустить» и раннер продолжает работу
+- **THEN** в 03:11 вачдог ничего не отправляет этому раннеру
+
+### Requirement: Отключение
+Автоматическое продолжение SHALL отключаться настройкой; тогда поведение прежнее — раннер ждёт человека.
+
+#### Scenario: Выключено
+- **GIVEN** автоматическое продолжение выключено
+- **WHEN** наступает время сброса лимита
+- **THEN** раннер остаётся `rate_limited`, у PM остаётся вопрос с «Перезапустить»
diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts
index 646d0c01..7016528e 100644
--- a/packages/core/src/sessions.ts
+++ b/packages/core/src/sessions.ts
@@ -48,7 +48,7 @@ export async function listSessions(db: Db, opts: { active?: boolean; taskId?: nu
export async function updateSession(
db: Db,
id: number,
- patch: Partial>,
+ patch: Partial>,
): Promise {
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
if (!row) throw new PeppaError(`Session #${id} not found`);
diff --git a/packages/db/migrations/0010_glamorous_ego.sql b/packages/db/migrations/0010_glamorous_ego.sql
new file mode 100644
index 00000000..5e638d86
--- /dev/null
+++ b/packages/db/migrations/0010_glamorous_ego.sql
@@ -0,0 +1,5 @@
+ALTER TABLE "sessions" ADD COLUMN "resume_at" timestamp with time zone;--> statement-breakpoint
+ALTER TABLE "sessions" ADD COLUMN "limit_probe_min" integer;--> statement-breakpoint
+ALTER TABLE "sessions" ADD COLUMN "limit_resumes" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
+ALTER TABLE "sessions" ADD COLUMN "limit_resumes_day" text;--> statement-breakpoint
+ALTER TABLE "sessions" ADD COLUMN "limit_resumed_at" timestamp with time zone;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0010_snapshot.json b/packages/db/migrations/meta/0010_snapshot.json
new file mode 100644
index 00000000..38b990ca
--- /dev/null
+++ b/packages/db/migrations/meta/0010_snapshot.json
@@ -0,0 +1,1464 @@
+{
+ "id": "d5839a22-0118-42d7-9632-545e36e36848",
+ "prevId": "89dc4030-a75f-4f23-a8dd-cf52b5c2d9c4",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.events": {
+ "name": "events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "goal_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_clients": {
+ "name": "oauth_clients",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_codes": {
+ "name": "oauth_codes",
+ "schema": "",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_tokens": {
+ "name": "oauth_tokens",
+ "schema": "",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_invites": {
+ "name": "project_invites",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "name": "project_invites_project_id_login_pk",
+ "columns": [
+ "project_id",
+ "login"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_members": {
+ "name": "project_members",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "name": "project_members_project_id_user_id_pk",
+ "columns": [
+ "project_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.projects": {
+ "name": "projects",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.questions": {
+ "name": "questions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "options": {
+ "name": "options",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sessions": {
+ "name": "sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'claude'"
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "session_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tmux_name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.settings": {
+ "name": "settings",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tasks": {
+ "name": "tasks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "task_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "number",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telegram_outbox": {
+ "name": "telegram_outbox",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "params": {
+ "name": "params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "dedupe_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telegram_updates": {
+ "name": "telegram_updates",
+ "schema": "",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "gitea_id"
+ ]
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "login"
+ ]
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "telegram_chat_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.goal_status": {
+ "name": "goal_status",
+ "schema": "public",
+ "values": [
+ "open",
+ "done",
+ "archived"
+ ]
+ },
+ "public.session_status": {
+ "name": "session_status",
+ "schema": "public",
+ "values": [
+ "starting",
+ "running",
+ "waiting_input",
+ "idle",
+ "stalled",
+ "rate_limited",
+ "done",
+ "failed"
+ ]
+ },
+ "public.task_status": {
+ "name": "task_status",
+ "schema": "public",
+ "values": [
+ "backlog",
+ "proposing",
+ "awaiting_approval",
+ "in_progress",
+ "review",
+ "done",
+ "blocked"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json
index 2b32be02..fd2af9ce 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -71,6 +71,13 @@
"when": 1794505063021,
"tag": "0009_steady_preak",
"breakpoints": true
+ },
+ {
+ "idx": 10,
+ "version": "7",
+ "when": 1794523548954,
+ "tag": "0010_glamorous_ego",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index c28e7875..8699ec23 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -139,6 +139,13 @@ export const sessions = pgTable("sessions", {
generation: integer("generation").notNull().default(0),
// Consecutive "keep going" nudges from the Stop hook; reset when a human answers.
autoNudges: integer("auto_nudges").notNull().default(0),
+ // Usage limit recovery (PEP-56): when to continue, current probe interval if the reset
+ // time is unknown, auto-resumes today (cap), and when the last auto-resume happened.
+ resumeAt: timestamp("resume_at", { withTimezone: true }),
+ limitProbeMin: integer("limit_probe_min"),
+ limitResumes: integer("limit_resumes").notNull().default(0),
+ limitResumesDay: text("limit_resumes_day"),
+ limitResumedAt: timestamp("limit_resumed_at", { withTimezone: true }),
status: sessionStatus("status").notNull().default("starting"),
lastActivityAt: timestamp("last_activity_at", { withTimezone: true }),
startedAt: createdAt(),
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index ef982608..fa558deb 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -21,6 +21,7 @@ import { createDb, tasks, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { peppaHome } from "@peppa/shared";
import { HOOK_WAIT_SEC, MAX_AUTO_NUDGES } from "./run-settings.ts";
+import { recordLimit } from "./limits.ts";
interface HookInput {
session_id?: string;
@@ -250,15 +251,18 @@ async function handle(event: string, input: HookInput): Promise {
case "stop-failure": {
const limited = input.error === "rate_limit";
- await updateSession(db, s.id, { status: limited ? "rate_limited" : "waiting_input", lastActivityAt: now });
await logSessionEvent(db, s, "stop_failure", { error: input.error, details: input.error_details });
+ if (limited) {
+ // Stores when to continue; the watchdog resumes the runner then (PEP-56).
+ await raiseSessionQuestion(db, s, "attention", await recordLimit(db, s, input.error_details ?? input.last_assistant_message ?? ""));
+ break;
+ }
+ await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: now });
await raiseSessionQuestion(
db,
s,
"attention",
- limited
- ? `${s.taskKey ?? `Сессия ${s.id}`} упёрлась в лимит Claude.${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`
- : `${s.taskKey ?? `Сессия ${s.id}`}: ход оборвался с ошибкой ${input.error ?? "unknown"}.${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`,
+ `${s.taskKey ?? `Сессия ${s.id}`}: ход оборвался с ошибкой ${input.error ?? "unknown"}.${input.error_details ? `\n${clip(input.error_details, 400)}` : ""}`,
);
break;
}
diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts
index ae1274fb..f7eae337 100644
--- a/packages/runner/src/index.ts
+++ b/packages/runner/src/index.ts
@@ -8,3 +8,4 @@ export * from "./provision.ts";
export * from "./flow.ts";
export * from "./claude-auth.ts";
export * from "./share.ts";
+export * from "./limits.ts";
diff --git a/packages/runner/src/limits.ts b/packages/runner/src/limits.ts
new file mode 100644
index 00000000..5cf01575
--- /dev/null
+++ b/packages/runner/src/limits.ts
@@ -0,0 +1,73 @@
+// Usage limits (PEP-56): when does the agent's limit reset, and what to tell the PM.
+import { updateSession, type SessionView } from "@peppa/core";
+import type { Db } from "@peppa/db";
+
+export const LIMIT_RESUME_GRACE_MS = 60_000;
+export const MAX_LIMIT_RESUMES_PER_DAY = 6;
+const PROBE_STEPS_MIN = [30, 60, 120];
+const REPEAT_WINDOW_MS = 5 * 60_000;
+
+export const limitAutoResumeEnabled = () => process.env.PEPPA_LIMIT_AUTORESUME !== "off";
+
+/**
+ * Reset time from a limit message: "resets 5pm", "resets at 3:10 AM", "reset at 15:00",
+ * "try again at 5:00 PM", "resets in 2h 15m". A clock time without a date is the nearest
+ * future one (local time of this machine). Null when there is no time in the text.
+ */
+export function parseResetTime(text: string, now: Date): Date | null {
+ const rel = /reset[s]?\s+in\s+(?:(\d+)\s*h(?:ours?)?)?\s*(?:(\d+)\s*m(?:in(?:utes?)?)?)?/i.exec(text);
+ if (rel && (rel[1] || rel[2])) return new Date(now.getTime() + (Number(rel[1] ?? 0) * 60 + Number(rel[2] ?? 0)) * 60_000);
+ const abs = /(?:reset[s]?|try again)(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/i.exec(text);
+ if (!abs) return null;
+ let h = Number(abs[1]);
+ const m = Number(abs[2] ?? 0);
+ const ampm = abs[3]?.toLowerCase();
+ if (!ampm && !abs[2]) return null; // a bare number isn't a time
+ if (ampm === "pm" && h < 12) h += 12;
+ if (ampm === "am" && h === 12) h = 0;
+ if (h > 23 || m > 59) return null;
+ const t = new Date(now);
+ t.setHours(h, m, 0, 0);
+ if (t.getTime() <= now.getTime()) t.setDate(t.getDate() + 1);
+ return t;
+}
+
+const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
+const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, local
+
+/**
+ * The runner hit a usage limit: store when to continue (reset time, or a probe if
+ * unknown / the limit came back right after an auto-resume). Returns the PM's message.
+ */
+export async function recordLimit(db: Db, s: SessionView, text: string, now = new Date()): Promise {
+ const who = s.taskKey ?? `Раннер ${s.id}`;
+ const day = today(now);
+ const resumesToday = s.limitResumesDay === day ? s.limitResumes : 0;
+ const repeated = !!s.limitResumedAt && now.getTime() - s.limitResumedAt.getTime() < REPEAT_WINDOW_MS;
+ const reset = repeated ? null : parseResetTime(text, now);
+ let resumeAt: Date | null = null;
+ let probe: number | null = null;
+ if (reset) resumeAt = new Date(reset.getTime() + LIMIT_RESUME_GRACE_MS);
+ else {
+ const prev = s.limitProbeMin;
+ probe = repeated && prev ? PROBE_STEPS_MIN.find((p) => p > prev) ?? PROBE_STEPS_MIN.at(-1)! : PROBE_STEPS_MIN[0]!;
+ resumeAt = new Date(now.getTime() + probe * 60_000);
+ }
+ const capped = resumesToday >= MAX_LIMIT_RESUMES_PER_DAY;
+ const auto = limitAutoResumeEnabled() && !capped;
+ await updateSession(db, s.id, {
+ status: "rate_limited",
+ resumeAt: auto ? resumeAt : null,
+ limitProbeMin: auto ? probe : null,
+ limitResumes: resumesToday,
+ limitResumesDay: day,
+ });
+ if (!auto) {
+ return capped
+ ? `${who}: снова лимит, автопродолжений сегодня уже ${MAX_LIMIT_RESUMES_PER_DAY} — нужен ты. Нажми «Перезапустить», когда лимит сбросится.`
+ : `${who} упёрлась в лимит.${text ? `\n${text.slice(0, 400)}` : ""}`;
+ }
+ return reset
+ ? `${who}: остановлен по лимиту, продолжит в ${hhmm(resumeAt!)} сам.`
+ : `${who}: остановлен по лимиту, время сброса неизвестно — попробую продолжить в ${hhmm(resumeAt!)}.`;
+}
diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts
index 2b310a0e..0e1938c2 100644
--- a/packages/runner/src/watchdog.ts
+++ b/packages/runner/src/watchdog.ts
@@ -2,6 +2,7 @@
// session dies, stalls, or hits a usage limit. Run under launchd with caffeinate.
import { createHash } from "node:crypto";
import {
+ expireSessionQuestions,
listSessions,
logSessionEvent,
pendingSessionQuestions,
@@ -11,8 +12,12 @@ import {
} from "@peppa/core";
import type { Db } from "@peppa/db";
import * as tmux from "./tmux.ts";
+import { recordLimit } from "./limits.ts";
+import { resumeSession } from "./sessions.ts";
export interface WatchdogOptions {
+ /** Current time (tests move it instead of waiting). */
+ now?: Date;
intervalMs: number;
/** A running session with an unchanged screen for this long is "stalled". */
stallMs: number;
@@ -44,6 +49,12 @@ export async function tick(db: Db, opts: WatchdogOptions): Promise {
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log: (m: string) => void) {
if (s.tmuxName.startsWith("pending-")) return;
+ // Rate-limited runner: continue it once its limit has reset (PEP-56), whether or not the
+ // agent process is still alive; until then leave it alone.
+ if (s.status === "rate_limited" && s.resumeAt) {
+ if ((opts.now ?? new Date()).getTime() >= s.resumeAt.getTime()) await resumeAfterLimit(db, s, opts.now ?? new Date(), log);
+ return;
+ }
const label = `#${s.id} ${s.taskKey ?? ""} (${s.tmuxName})`;
if (!(await tmux.hasSession(s.tmuxName))) {
@@ -70,7 +81,7 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
const screen = await tmux.capturePane(s.tmuxName);
const hash = createHash("sha1").update(screen).digest("hex");
- const now = Date.now();
+ const now = (opts.now ?? new Date()).getTime();
let last = s.lastActivityAt?.getTime() ?? now;
if (lastScreen.get(s.id) !== hash) {
last = now;
@@ -86,9 +97,8 @@ async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, log:
limitAlerted.add(s.id);
const line = screen.split("\n").find((l) => LIMIT_RE.test(l))?.trim() ?? "";
log(`${label}: usage limit`);
- await updateSession(db, s.id, { status: "rate_limited" });
await logSessionEvent(db, s, "usage_limit", { line });
- await raiseSessionQuestion(db, s, "attention", `${s.taskKey ?? `Сессия ${s.id}`} упёрлась в лимит: ${line}`);
+ await raiseSessionQuestion(db, s, "attention", await recordLimit(db, s, line, new Date(now)));
}
if (s.status === "running" && now - last > opts.stallMs) {
@@ -115,3 +125,26 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
await new Promise((r) => setTimeout(r, opts.intervalMs));
}
}
+
+/** The limit has reset: nudge the live agent, or relaunch it with its conversation. */
+async function resumeAfterLimit(db: Db, s: SessionView, now: Date, log: (m: string) => void) {
+ const day = now.toLocaleDateString("sv-SE");
+ const counters = {
+ resumeAt: null,
+ limitResumes: (s.limitResumesDay === day ? s.limitResumes : 0) + 1,
+ limitResumesDay: day,
+ limitResumedAt: now,
+ };
+ // The limit message gets closed (Telegram shows it as resolved) — no new ping for the PM.
+ await expireSessionQuestions(db, s.id, "(лимит сброшен — раннер продолжил сам)");
+ const alive = (await tmux.hasSession(s.tmuxName)) && !(await tmux.paneState(s.tmuxName)).dead;
+ if (alive) {
+ await tmux.sendText(s.tmuxName, `Лимит сброшен. Продолжай работу над ${s.taskKey ?? "задачей"} с того места, где остановился (tasks.md).`);
+ await updateSession(db, s.id, { ...counters, status: "running", lastActivityAt: now });
+ } else {
+ await updateSession(db, s.id, counters);
+ await resumeSession(db, s.id);
+ }
+ await logSessionEvent(db, s, "limit_resumed", { alive, n: counters.limitResumes });
+ log(`#${s.id} ${s.taskKey ?? ""}: limit reset, ${alive ? "nudged" : "relaunched"}`);
+}
diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts
index 7e8d8274..79fb9b01 100644
--- a/packages/testkit/src/mock-agent.ts
+++ b/packages/testkit/src/mock-agent.ts
@@ -248,11 +248,14 @@ async function run(action: Action): Promise {
log("ask", { via: "terminal" });
}
} else if ("limit" in action) {
+ const spec = typeof action.limit === "object" ? action.limit : {};
+ const at = spec.resetInSec != null ? new Date(Date.now() + spec.resetInSec * 1000).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }) : null;
+ const when = spec.reset === "unknown" ? "" : at ? ` resets at ${at}` : " resets 5pm";
if (provider === "claude") {
- out("⎿ Claude usage limit reached. Your limit will reset at 5pm (Asia/Almaty).\n");
- await fireHook("StopFailure", { error: "rate_limit", error_details: "Usage limit reached, resets 5pm", last_assistant_message: lastMessage }, "rate_limit");
+ out(`⎿ Claude usage limit reached.${when ? ` Your limit${when.replace(" resets", " will reset")}.` : ""}\n`);
+ await fireHook("StopFailure", { error: "rate_limit", error_details: `Usage limit reached${when ? `,${when}` : ""}`, last_assistant_message: lastMessage }, "rate_limit");
} else {
- out("■ You've hit your usage limit. Upgrade or try again at 5:00 PM.\n");
+ out(`■ You've hit your usage limit.${spec.reset === "unknown" ? "" : ` Try again at ${at ?? "5:00 PM"}.`}\n`);
}
log("limit");
return false;
diff --git a/packages/testkit/src/scenario.ts b/packages/testkit/src/scenario.ts
index 61cb75d9..847da2dc 100644
--- a/packages/testkit/src/scenario.ts
+++ b/packages/testkit/src/scenario.ts
@@ -9,7 +9,7 @@ export type Action =
| { mcp: string; args?: Record } // call a peppa MCP tool
| { permission: { tool: string; input: Record } } // claude: PermissionRequest
| { ask: Array<{ question: string; options?: string[] }> } // claude: AskUserQuestion
- | { limit: true } // usage limit: StopFailure (claude) / banner only (codex)
+ | { limit: true | { resetInSec?: number; reset?: "unknown" } } // usage limit: StopFailure (claude) / banner only (codex); resetInSec → "resets at HH:MM"
| { hang: true } // freeze: no output, no input handling
| { crash: number } // exit with this code
| { clear: true } // claude: /clear (SessionEnd + SessionStart with a new id)
diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts
new file mode 100644
index 00000000..5c384674
--- /dev/null
+++ b/packages/testkit/test/limits.test.ts
@@ -0,0 +1,146 @@
+// PEP-56: the runner continues on its own after its usage limit resets.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { after, describe, test } from "node:test";
+import { core, db, project, runner, teardown, tick, waitFor } from "./helpers.ts";
+
+after(teardown);
+
+const at = (s: string) => new Date(s);
+const sess = (id: number) => core.getSession(db, id);
+const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now });
+const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle);
+
+describe("Время сброса лимита", () => {
+ // Scenario Outline: Форматы времени сброса (now = 2026-11-12 22:40 local)
+ const now = at("2026-11-12T22:40:00");
+ for (const [text, expected] of [
+ ["resets 5pm", "2026-11-13T17:00:00"],
+ ["resets at 3:10 AM", "2026-11-13T03:10:00"],
+ ["resets in 2h 15m", "2026-11-13T00:55:00"],
+ ["try again at 23:30", "2026-11-12T23:30:00"],
+ ["limit reached", null],
+ ] as const) {
+ test(`Форматы времени сброса: «${text}»`, () => {
+ const r = runner.parseResetTime(text, now);
+ assert.equal(r?.getTime() ?? null, expected ? at(expected).getTime() : null);
+ });
+ }
+
+ test("Время сброса указано", async () => {
+ const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Продолжаю после лимита." }]] });
+ const sid = await p.start();
+ await p.waitStatus(sid, "rate_limited");
+ const s = await sess(sid);
+ assert.ok(s.resumeAt && s.resumeAt.getTime() > Date.now() + 60_000, "resume time = reset + grace");
+ assert.equal(s.limitProbeMin, null);
+ const q = await p.waitQuestion(sid, "attention");
+ assert.match(q.text, /продолжит в \d\d:\d\d сам/);
+
+ // Сброс ещё не наступил
+ await tickAt(new Date(s.resumeAt!.getTime() - 60_000));
+ assert.equal((await sess(sid)).status, "rate_limited");
+ assert.ok(!p.log().some(isPrompt("Лимит сброшен")));
+
+ // Процесс агента жив
+ await tickAt(new Date(s.resumeAt!.getTime() + 1000));
+ await p.waitLog("nudged after reset", isPrompt("Лимит сброшен"));
+ const after = await sess(sid);
+ assert.equal(after.generation, 1, "same generation");
+ assert.equal(after.limitResumes, 1);
+ assert.equal((await core.getQuestion(db, q.id)).answeredVia, "system", "limit message closed, no new ping");
+ await runner.stopSession(db, sid);
+ });
+
+ test("Процесс агента завершён", async () => {
+ const p = await project({ turns: [[{ limit: { resetInSec: 120 } }]], resumeTurns: [[{ say: "Вернулся." }]] });
+ const sid = await p.start();
+ await p.waitStatus(sid, "rate_limited");
+ const s = await sess(sid);
+ execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${s.tmuxName}`]);
+ await tick(); // a dead/vanished rate-limited runner is not marked failed while it waits
+ assert.equal((await sess(sid)).status, "rate_limited");
+ await tickAt(new Date(s.resumeAt!.getTime() + 1000));
+ const start = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
+ assert.equal(start.resume, s.conversationId, "continues the same conversation");
+ await runner.stopSession(db, sid);
+ });
+});
+
+describe("Неизвестное время сброса", () => {
+ test("Проба удалась, а при повторном лимите интервал растёт", async () => {
+ const p = await project({ turns: [[{ limit: { reset: "unknown" } }], [{ limit: { reset: "unknown" } }], [{ say: "ok" }]] });
+ const sid = await p.start();
+ await p.waitStatus(sid, "rate_limited");
+ const s = await sess(sid);
+ assert.equal(s.limitProbeMin, 30);
+ assert.ok(Math.abs(s.resumeAt!.getTime() - (Date.now() + 30 * 60_000)) < 60_000);
+ assert.match((await p.waitQuestion(sid, "attention")).text, /время сброса неизвестно/);
+
+ await tickAt(new Date(s.resumeAt!.getTime() + 1000));
+ await p.waitLog("probe", isPrompt("Лимит сброшен"));
+ // Лимит ещё действует: the agent hits it again right away → next probe in 1 hour.
+ await waitFor("limited again", async () => (await sess(sid)).limitProbeMin === 60);
+ assert.equal((await sess(sid)).status, "rate_limited");
+ await runner.stopSession(db, sid);
+ });
+});
+
+describe("Защита от зацикливания", () => {
+ test("Предел достигнут", async () => {
+ const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] });
+ const sid = await p.start();
+ await p.waitQuestion(sid, "attention");
+ await core.updateSession(db, sid, { limitResumes: runner.MAX_LIMIT_RESUMES_PER_DAY, limitResumesDay: new Date().toLocaleDateString("sv-SE") });
+ await runner.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "дальше", "web");
+ await p.waitStatus(sid, "rate_limited");
+ const s = await sess(sid);
+ assert.equal(s.resumeAt, null, "no more auto-resumes today");
+ assert.match((await p.waitQuestion(sid, "attention")).text, /нужен ты/);
+ await runner.stopSession(db, sid);
+ });
+
+ test("Человек вмешался раньше", async () => {
+ const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "ok" }], [{ say: "лишнее" }]] });
+ const sid = await p.start();
+ await p.waitStatus(sid, "rate_limited");
+ const due = (await sess(sid)).resumeAt!;
+ await runner.answerAndDeliver(db, (await p.waitQuestion(sid, "attention")).id, "продолжай сейчас", "web");
+ await p.waitLog("manual answer", isPrompt("продолжай сейчас"));
+ await tickAt(new Date(due.getTime() + 1000));
+ await new Promise((r) => setTimeout(r, 800));
+ assert.ok(!p.log().some(isPrompt("Лимит сброшен")), "watchdog sends nothing");
+ await runner.stopSession(db, sid);
+ });
+});
+
+describe("Отключение", () => {
+ test("Выключено", async () => {
+ const p = await project({ turns: [] });
+ const sid = (await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id })).id;
+ process.env.PEPPA_LIMIT_AUTORESUME = "off";
+ try {
+ const text = await runner.recordLimit(db, await sess(sid), "Usage limit reached, resets 5pm");
+ assert.equal((await sess(sid)).resumeAt, null);
+ assert.match(text, /упёрлась в лимит/);
+ } finally {
+ delete process.env.PEPPA_LIMIT_AUTORESUME;
+ }
+ });
+});
+
+describe("Codex", () => {
+ test("banner with a time → watchdog continues the live agent after reset", async () => {
+ const p = await project({ turns: [[{ limit: { resetInSec: 120 } }], [{ say: "Codex продолжил." }]] });
+ const sid = await p.start({ provider: "codex" });
+ await p.waitLog("banner", (e) => e.ev === "limit");
+ await new Promise((r) => setTimeout(r, 300));
+ await tick();
+ const s = await sess(sid);
+ assert.equal(s.status, "rate_limited");
+ assert.ok(s.resumeAt);
+ await tickAt(new Date(s.resumeAt!.getTime() + 1000));
+ await p.waitLog("codex nudged", isPrompt("Лимит сброшен"));
+ await runner.stopSession(db, sid);
+ });
+});
--
2.45.2
From dc2aea8d3544661f49e266eaaa1bf8c5323cf3dd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 13:57:16 +0500
Subject: [PATCH 014/556] =?UTF-8?q?PEP-22:=20PEPPA=5FTEST=5FDB=20=E2=80=94?=
=?UTF-8?q?=20separate=20test=20database=20for=20parallel=20runs?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
packages/testkit/test/helpers.ts | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts
index e74b541d..a4be3443 100644
--- a/packages/testkit/test/helpers.ts
+++ b/packages/testkit/test/helpers.ts
@@ -11,7 +11,8 @@ import type { Scenario, MockLogEntry } from "../src/scenario.ts";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-cjm-"));
-const TEST_DB = "peppa_test";
+// PEPPA_TEST_DB lets parallel sessions (one per worktree) run the suite without sharing a database.
+const TEST_DB = process.env.PEPPA_TEST_DB ?? "peppa_test";
Object.assign(process.env, {
DATABASE_URL: `postgres://peppa:peppa@127.0.0.1:5433/${TEST_DB}`,
--
2.45.2
From 3916ac9bc9ad3925d2e173eec43b694b27fb5533 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 14:01:34 +0500
Subject: [PATCH 015/556] PEP-57, PEP-58: PM decisions recorded
Co-Authored-By: Claude Opus 5.5
---
openspec/changes/pep-57-ci-cd/proposal.md | 7 +++++++
openspec/changes/pep-58-bugsink/proposal.md | 13 +++++++++++++
2 files changed, 20 insertions(+)
diff --git a/openspec/changes/pep-57-ci-cd/proposal.md b/openspec/changes/pep-57-ci-cd/proposal.md
index 420d8751..aa6b781c 100644
--- a/openspec/changes/pep-57-ci-cd/proposal.md
+++ b/openspec/changes/pep-57-ci-cd/proposal.md
@@ -69,3 +69,10 @@ RULES.md), `infra/` (act_runner, сеть Traefik для стендов), `packa
root-доступ к хосту для любого workflow** — допустимо только после PEP-16 и только для
репозиториев проектов Пеппы) или отдельная VM/сервер для сборок.
4. **Прод по умолчанию**: по кнопке PM (**рекомендую**), авто — включается на проект (PEP-23).
+
+### Решено PM (2026-11-13)
+
+1. Gitea Actions + act_runner.
+2. Деплой на этот Mac за Traefik.
+3. act_runner с docker.sock хоста — только для репозиториев проектов Пеппы (метка `peppa-trusted`).
+4. Прод — по кнопке PM; авто включается на проект позже (PEP-23).
diff --git a/openspec/changes/pep-58-bugsink/proposal.md b/openspec/changes/pep-58-bugsink/proposal.md
index 9dd19372..372ad552 100644
--- a/openspec/changes/pep-58-bugsink/proposal.md
+++ b/openspec/changes/pep-58-bugsink/proposal.md
@@ -56,3 +56,16 @@ API + приём вебхуков), `apps/web` (маршрут `/api/hooks/bugsi
от N событий за час.
4. **Данные пользователей в ошибках**: SDK по умолчанию без персональных данных
(`sendDefaultPii: false`), **да**.
+
+### Решено PM (2026-11-13)
+
+1. Да, Bugsink в docker на этом Mac, `bugsink.telecom.quest`, отдельная база в Postgres Пеппы.
+2. Реакция на новую ошибку — **настройка проекта** «Политика инцидентов», а не зашитое поведение:
+ - `notify` — только сообщение в Telegram;
+ - `backlog` — задача-баг в бэклог + сообщение (**по умолчанию**);
+ - `start` — задача сразу в работу (запуск раннера);
+ - `ask` — сообщение в Telegram с кнопками «В бэклог / В работу / Игнорировать»;
+ - `triage` — решает агент-триажёр по мини-промпту проекта («как принимать решение»: свободный текст PM, например «падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси»); на выходе одно из действий выше + короткое обоснование в задаче/сообщении. Если триажёр не уверен или недоступен — откат на `ask`.
+ Политику и мини-промпт меняют в настройках проекта (веб) и через MCP.
+3. Порог — любая новая ошибка в `prod` (позже — от N событий за час).
+4. Без персональных данных (`sendDefaultPii: false`).
--
2.45.2
From 412f5f05cee3b37de2764d5df8f5348b890c56d8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 14:02:37 +0500
Subject: [PATCH 016/556] =?UTF-8?q?PEP-61:=20top=20menu=20=E2=80=94=20Home?=
=?UTF-8?q?=20instead=20of=20Inbox,=20Runners=20and=20Projects=20pages?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 2 +-
apps/web/app/(app)/actions.ts | 6 ++-
apps/web/app/(app)/help/page.tsx | 3 +-
apps/web/app/(app)/layout.tsx | 9 ++---
apps/web/app/(app)/page.tsx | 34 +++++-----------
apps/web/app/(app)/projects/page.tsx | 23 +++++++++++
apps/web/app/(app)/runners/page.tsx | 40 +++++++++++++++++++
apps/web/app/globals.css | 15 ++++++-
apps/web/components/Nav.tsx | 33 +++++++++++++++
apps/web/components/ui.tsx | 30 ++++++++++++--
.../.openspec.yaml | 0
.../2026-11-13-pep-61-top-menu}/proposal.md | 0
.../specs/web-workspace/spec.md | 0
.../2026-11-13-pep-61-top-menu/tasks.md | 11 +++++
openspec/changes/pep-61-top-menu/tasks.md | 6 ---
openspec/specs/web-workspace/spec.md | 21 ++++++++++
packages/core/src/sessions.ts | 23 ++++++++++-
packages/testkit/test/sharing.test.ts | 18 +++++++++
18 files changed, 229 insertions(+), 45 deletions(-)
create mode 100644 apps/web/app/(app)/projects/page.tsx
create mode 100644 apps/web/app/(app)/runners/page.tsx
create mode 100644 apps/web/components/Nav.tsx
rename openspec/changes/{pep-61-top-menu => archive/2026-11-13-pep-61-top-menu}/.openspec.yaml (100%)
rename openspec/changes/{pep-61-top-menu => archive/2026-11-13-pep-61-top-menu}/proposal.md (100%)
rename openspec/changes/{pep-61-top-menu => archive/2026-11-13-pep-61-top-menu}/specs/web-workspace/spec.md (100%)
create mode 100644 openspec/changes/archive/2026-11-13-pep-61-top-menu/tasks.md
delete mode 100644 openspec/changes/pep-61-top-menu/tasks.md
diff --git a/AGENTS.md b/AGENTS.md
index ccf9ccdd..5806104d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@
Текущее состояние и порядок работ: `docs/HANDOFF.md`.
## Структура
-- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; входящие, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web`
+- `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; меню Главная (вопросы, активные раннеры, проекты) · Проекты · Раннеры (`/runners`, `core.listUserSessions`) · Помощь, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web`
- `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка у каждого пользователя своя: веб «Настройки → Telegram» (или `peppa telegram pair `), вопросы проекта получают владелец и участники с привязкой, ответ принимается только от имеющих доступ к проекту (PEP-2). Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
- `packages/shared` — env, ключи задач (`PEP-42`)
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index cd72651e..3d731c8b 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -32,8 +32,10 @@ async function attempt(f: FormData, fn: () => Promise): PromiseДоска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
-
Входящие — вопросы агентов (только архитектурные стопперы) и «готово к ревью». Отвечать можно в вебе, Telegram или через MCP.
+
Раннер — агент, запущенный по задаче в tmux на машине Пеппы. Все раннеры твоих и общих проектов — в разделе Раннеры: статус, задача, команда tmux attach, сообщение, остановка и resume; фильтры «ждут тебя / работают / остановлены (упали) / завершены».
+
Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты.
Подключить MCP
diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx
index f060b390..7647b372 100644
--- a/apps/web/app/(app)/layout.tsx
+++ b/apps/web/app/(app)/layout.tsx
@@ -2,6 +2,7 @@ import Link from "next/link";
import type { ReactNode } from "react";
import { requireUser } from "@/lib/auth";
import { Footer } from "@/components/Footer";
+import { Nav, SettingsLink } from "@/components/Nav";
export const dynamic = "force-dynamic";
@@ -11,13 +12,9 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
<>
🐷 Peppa
-
+
+
{user.avatarUrl && }
{user.login}
+
+ Репозиторий будет {giteaUrl}/<пространство>/<slug>. В личном пространстве приватный репозиторий видите
+ только вы, peppa-bot и участники проекта; в организации — ещё её участники с доступом к репозиториям.
+ {orgs.length === 0 && " Организаций, где вы можете создавать репозитории, нет."}
+
: null;
}
+export function Notice({ children }: { children: ReactNode }) {
+ return
{children}
;
+}
+
export function ago(d: Date | null | undefined): string {
if (!d) return "—";
const s = Math.round((Date.now() - d.getTime()) / 1000);
diff --git a/openspec/changes/archive/2026-11-13-pep-15-repo-visibility/.openspec.yaml b/openspec/changes/archive/2026-11-13-pep-15-repo-visibility/.openspec.yaml
new file mode 100644
index 00000000..22ca07d7
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-15-repo-visibility/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-13
diff --git a/openspec/changes/archive/2026-11-13-pep-15-repo-visibility/design.md b/openspec/changes/archive/2026-11-13-pep-15-repo-visibility/design.md
new file mode 100644
index 00000000..368c9615
--- /dev/null
+++ b/openspec/changes/archive/2026-11-13-pep-15-repo-visibility/design.md
@@ -0,0 +1,27 @@
+# Design: PEP-15
+
+## Видимость — из Gitea, а не из БД
+Видимость и соавторов можно поменять в самом Gitea, поэтому Пеппа их не хранит, а читает
+при показе страницы проекта (`describeRepo` в runner: клиент владельца проекта или
+текущего пользователя, затем `peppa-bot`). Три запроса параллельно: репозиторий,
+`/orgs/{owner}` (организация или пользователь), список соавторов. Если Gitea недоступен —
+показываем путь и ссылку из БД и «не удалось узнать видимость». Миграции нет.
+
+## Кто видит
+Чистая функция `repoAudience` в core по {private, пространство, соавторы}:
+- публичный — все, у кого есть доступ к Gitea;
+- приватный в личном пространстве — владелец пространства и соавторы;
+- приватный в организации — владельцы и команды организации с доступом к репозиторию,
+ плюс соавторы.
+
+## Создание
+`GiteaClient.createRepo` получает `private`; `ProvisionOptions.visibility`
+(`"private" | "public"`, по умолчанию `"private"`). Для `existing` параметр игнорируется.
+После создания веб редиректит на `/p/?created=1`, страница показывает уведомление
+со ссылкой. Пространство в форме — тот же `
);
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index 3b88d19e..c05afd36 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -5,7 +5,9 @@ import { Board, type Card } from "@/components/Board";
import { columnOf, describeRepo } from "@peppa/runner";
import { requireUser } from "@/lib/auth";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
-import { listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
+import { bugsinkWebhookBase } from "@peppa/runner";
+import { IncidentsSection } from "@/components/Incidents";
import { db } from "@/lib/db";
import { addGoal, addProjectMember, addTask, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
@@ -15,7 +17,15 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const { error, created } = await searchParams;
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
- const [{ goals, tasks }, sessions, team, repo] = await Promise.all([board(p.id), projectSessions(p.id), listMembers(db, p), describeRepo(db, p)]);
+ const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents] = await Promise.all([
+ board(p.id),
+ projectSessions(p.id),
+ listMembers(db, p),
+ describeRepo(db, p),
+ getIncidentSettings(db, p.id),
+ listErrorSources(db, p.id),
+ listIncidents(db, p.id),
+ ]);
const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase()));
// Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway).
const noRepoAccess = (login: string) =>
@@ -78,6 +88,18 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
+ [t.id, `${p.key}-${t.number}`]))}
+ webhookUrl={incidentSettings ? `${bugsinkWebhookBase()}/api/hooks/bugsink/${incidentSettings.hookSecret}` : null}
+ />
+
Участники
diff --git a/apps/web/app/api/hooks/bugsink/[secret]/route.ts b/apps/web/app/api/hooks/bugsink/[secret]/route.ts
new file mode 100644
index 00000000..313bbc4f
--- /dev/null
+++ b/apps/web/app/api/hooks/bugsink/[secret]/route.ts
@@ -0,0 +1,15 @@
+import { after } from "next/server";
+import { bugsinkFromEnv } from "@peppa/bugsink";
+import { processIncidents, receiveBugsinkWebhook } from "@peppa/runner";
+import { db } from "@/lib/db";
+
+export const dynamic = "force-dynamic";
+
+/** Bugsink custom-webhook alerts (PEP-58). Unknown secret → 404; the policy runs after the reply. */
+export async function POST(req: Request, { params }: { params: Promise<{ secret: string }> }) {
+ const { secret } = await params;
+ const body = await req.json().catch(() => null);
+ const r = await receiveBugsinkWebhook(db, secret, body, bugsinkFromEnv());
+ if (r.status === 200) after(() => processIncidents(db, { log: (m) => console.error(`[incidents] ${m}`) }).then(() => undefined));
+ return Response.json(r.body, { status: r.status });
+}
diff --git a/apps/web/components/Incidents.tsx b/apps/web/components/Incidents.tsx
new file mode 100644
index 00000000..061bb3ba
--- /dev/null
+++ b/apps/web/components/Incidents.tsx
@@ -0,0 +1,161 @@
+// Project page section «Ошибки» (PEP-58): connect Bugsink, incident policy, incidents list.
+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 { ago } from "./ui";
+
+const Hidden = ({ projectId, back }: { projectId: number; back: string }) => (
+ <>
+
+
+ >
+);
+
+export function IncidentsSection(props: {
+ projectId: number;
+ projectKey: string;
+ back: string;
+ isOwner: boolean;
+ settings: IncidentSettings | null;
+ sources: ErrorSource[];
+ incidents: Incident[];
+ taskKeys: Map;
+ webhookUrl: string | null;
+}) {
+ const { projectId, back, settings: s } = props;
+ if (!s) {
+ return (
+
+
Ошибки
+
Ошибки фронта и бэка из прода (Bugsink, SDK Sentry) приходят сюда и становятся задачами по политике проекта.
+ В коде: {"NEXT_PUBLIC_SENTRY_DSN"} / SENTRY_DSN из окружения, release = SHA деплоя, environment = prod, sendDefaultPii: false.
+
+ {!s.webhookAuto && props.webhookUrl && (
+
+ Вебхук не настроен автоматически. В Bugsink: проект → Alerts → Custom webhook:
+ {props.webhookUrl}
+ Пока его нет, Пеппа опрашивает Bugsink раз в 2 минуты.
+
diff --git a/apps/web/app/api/hooks/gitea/route.ts b/apps/web/app/api/hooks/gitea/route.ts
new file mode 100644
index 00000000..ffb6c599
--- /dev/null
+++ b/apps/web/app/api/hooks/gitea/route.ts
@@ -0,0 +1,18 @@
+import { handleGiteaHook } from "@peppa/runner";
+import { db } from "@/lib/db";
+
+export const dynamic = "force-dynamic";
+
+/**
+ * Gitea webhooks and CI step reports of project repos (PEP-57). No login: each request is
+ * signed (X-Gitea-Signature, HMAC-SHA256 of the body) with the project's secret.
+ */
+export async function POST(req: Request) {
+ const body = await req.text();
+ const r = await handleGiteaHook(db, {
+ event: req.headers.get("x-peppa-event") ?? req.headers.get("x-gitea-event") ?? "",
+ signature: req.headers.get("x-gitea-signature"),
+ body,
+ });
+ return Response.json(r.body, { status: r.status });
+}
diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md
index e7334f63..49185f5f 100644
--- a/openspec/changes/pep-57-ci-cd/design.md
+++ b/openspec/changes/pep-57-ci-cd/design.md
@@ -66,3 +66,11 @@ Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не н
хранится). Тот же секрет — у вебхука Gitea проекта.
- **Статусы**: `install` сообщает только о провале; «N из N» считается по статусам
`peppa/*` головного SHA.
+- **Вебхуки Gitea**: `pull_request` и `push` (события `status` в 1.22 нет); статусы проверок
+ приходят отчётом шага CI, запасной путь — опрос статусов вачдогом раз в минуту.
+- **Попытка** = красный прогон нового головного SHA; несколько красных проверок одного коммита —
+ одна попытка. Зелёный прогон обнуляет счётчик.
+- **Гейт ревью открыт при недоступной Gitea** (иначе агент застрянет); мерж по «Принять» в этом
+ случае всё равно не пройдёт. Задача без PR и проект без `checks` гейт не проходят — он выключен.
+- **Автомерж** (`autoMergeTask`) готов, но не подключён к триггеру — режим авто-мержа проекта
+ появится в PEP-23/25.
diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md
index 768d3037..5cc94c2f 100644
--- a/openspec/changes/pep-57-ci-cd/tasks.md
+++ b/openspec/changes/pep-57-ci-cd/tasks.md
@@ -10,14 +10,14 @@
- [x] 1.1 `infra/`: act_runner в docker (метка `peppa-trusted`), включить Actions в Gitea; проверка: тестовый workflow в `peppa-bot/sandbox` зелёный
- [x] 1.2 Шаблон: `.gitea/workflows/ci.yml` (читает `checks` из `.peppa/project.json`), поля `checks`/`deploy` в project.json, раздел в RULES.md «перед PR запусти checks локально»; залить шаблон
-- [ ] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX
+- [x] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX
## 2. Обратная связь и гейты
-- [ ] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки
-- [ ] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью»
-- [ ] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок
-- [ ] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт»
+- [x] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки
+- [x] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью»
+- [x] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок
+- [x] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт»
## 3. CD
diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts
new file mode 100644
index 00000000..32a123c9
--- /dev/null
+++ b/packages/core/src/ci.ts
@@ -0,0 +1,190 @@
+// CI results of factory projects (PEP-57): check runs per commit, the summary shown on the
+// task card and the gate for review and merge (green checks of the PR head, no conflicts).
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { checkRuns, tasks, type Db } from "@peppa/db";
+import { CHECK_NAMES, formatTaskKey, loadEnv, type CheckName, type PeppaProjectFile } from "@peppa/shared";
+import { and, desc, eq } from "drizzle-orm";
+import type { GiteaClient, GiteaPull } from "./gitea.ts";
+import { giteaForBot } from "./users.ts";
+import type { Project } from "./projects.ts";
+import type { TaskRef } from "./tasks.ts";
+
+export type CheckRun = typeof checkRuns.$inferSelect;
+export type CheckState = CheckRun["state"];
+
+export interface CheckReport {
+ sha: string;
+ branch?: string | null;
+ prNumber?: number | null;
+ check: string;
+ state: CheckState;
+ runUrl?: string | null;
+ logTail?: string | null;
+ durationSec?: number | null;
+ source?: CheckRun["source"];
+}
+
+/** Commands configured in a project file (JSON text); missing/empty ones are skipped by CI. */
+export function configuredChecks(projectJson: string | null | undefined): CheckName[] {
+ if (!projectJson) return [];
+ try {
+ const checks = (JSON.parse(projectJson) as PeppaProjectFile).checks ?? {};
+ return CHECK_NAMES.filter((c) => typeof checks[c] === "string" && checks[c]!.trim() !== "");
+ } catch {
+ return [];
+ }
+}
+
+/** Full link to a run: CI reports relative `/owner/repo/actions/runs/N`. */
+export function runLink(url: string | null | undefined): string | null {
+ if (!url) return null;
+ return url.startsWith("/") ? `${loadEnv().GITEA_URL}${url}` : url;
+}
+
+export interface CiSummary {
+ state: "not_configured" | "none" | "pending" | "success" | "failure";
+ passed: number;
+ total: number;
+ sha: string | null;
+ runUrl: string | null;
+ failed: Array<{ check: string; runUrl: string | null; logTail?: string | null }>;
+ /** One line for the task card, e.g. "Проверки: 4 из 4 пройдены". */
+ label: string;
+}
+
+type RunLike = { check: string; state: CheckState; runUrl?: string | null; logTail?: string | null };
+
+export function summarizeChecks(configured: string[], runs: RunLike[], sha: string | null): CiSummary {
+ const total = configured.length;
+ const base = { sha, total, runUrl: runLink(runs.find((r) => r.runUrl)?.runUrl) };
+ if (!total) return { ...base, state: "not_configured", passed: 0, failed: [], label: "проверки не настроены" };
+ // `install` is not a check of its own, but when it fails nothing else ran.
+ const failed = runs.filter((r) => r.state === "failure" || r.state === "error").map((r) => ({ check: r.check, runUrl: runLink(r.runUrl), logTail: r.logTail }));
+ const passed = configured.filter((c) => runs.some((r) => r.check === c && r.state === "success")).length;
+ if (failed.length) return { ...base, state: "failure", passed, failed, label: `Проверки: ${passed} из ${total} пройдены, упало: ${failed.map((f) => f.check).join(", ")}` };
+ if (passed === total) return { ...base, state: "success", passed, failed, label: `Проверки: ${passed} из ${total} пройдены` };
+ if (!runs.length) return { ...base, state: "none", passed, failed, label: "Проверки ещё не запускались" };
+ return { ...base, state: "pending", passed, failed, label: `Проверки идут: ${passed} из ${total}` };
+}
+
+/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
+export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> {
+ const [prev] = await db
+ .select()
+ .from(checkRuns)
+ .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), eq(checkRuns.check, r.check)));
+ const values = {
+ taskId: taskId ?? prev?.taskId ?? null,
+ branch: r.branch ?? prev?.branch ?? null,
+ prNumber: r.prNumber ?? prev?.prNumber ?? null,
+ state: r.state,
+ runUrl: r.runUrl ?? prev?.runUrl ?? null,
+ // A poll carries no log: keep the one the CI step sent.
+ logTail: r.logTail ?? prev?.logTail ?? null,
+ durationSec: r.durationSec ?? prev?.durationSec ?? null,
+ source: r.source ?? "report",
+ };
+ const [run] = prev
+ ? await db.update(checkRuns).set(values).where(eq(checkRuns.id, prev.id)).returning()
+ : await db.insert(checkRuns).values({ projectId: project.id, sha: r.sha, check: r.check, ...values }).returning();
+ return { run: run!, changed: prev?.state !== r.state };
+}
+
+/** PR number of a task's pr_url when it points at the project's repo. */
+export function taskPrNumber(project: Project, prUrl: string | null | undefined): number | null {
+ const m = prUrl?.match(/\/([^/]+)\/([^/]+)\/pulls\/(\d+)/);
+ if (!m || m[1]!.toLowerCase() !== project.giteaOwner.toLowerCase() || m[2]!.toLowerCase() !== project.giteaRepo.toLowerCase()) return null;
+ return Number(m[3]);
+}
+
+/** Task of a CI result: its branch `task/-…`, or the task whose PR it is. */
+export async function taskForCheck(db: Db, project: Project, branch: string | null | undefined, prNumber: number | null | undefined): Promise {
+ const m = branch?.match(new RegExp(`^task/${project.key}-(\\d+)`, "i"));
+ if (m) {
+ const [task] = await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), eq(tasks.number, Number(m[1]))));
+ if (task) return { project, task, key: formatTaskKey(project.key, task.number) };
+ }
+ if (prNumber) {
+ for (const task of await db.select().from(tasks).where(eq(tasks.projectId, project.id))) {
+ if (taskPrNumber(project, task.prUrl) === prNumber) return { project, task, key: formatTaskKey(project.key, task.number) };
+ }
+ }
+ return null;
+}
+
+function workspaceProjectJson(project: Project): string | null {
+ const f = join(project.workspacePath, ".peppa/project.json");
+ return existsSync(f) ? readFileSync(f, "utf8") : null;
+}
+
+/** For the task card and MCP (no Gitea calls): checks of the task's latest commit. */
+export async function taskCiSummary(db: Db, ref: TaskRef): Promise {
+ const runs = await db.select().from(checkRuns).where(eq(checkRuns.taskId, ref.task.id)).orderBy(desc(checkRuns.updatedAt));
+ const sha = runs[0]?.sha ?? null;
+ return summarizeChecks(configuredChecks(workspaceProjectJson(ref.project)), runs.filter((r) => r.sha === sha), sha);
+}
+
+export interface GateResult {
+ ok: boolean;
+ /** Why not, for the PM: "проверки не пройдены", conflicts… */
+ reason?: string;
+ summary: CiSummary | null;
+ pull: GiteaPull | null;
+}
+
+/**
+ * Gate for review and merge: the task's PR head has green checks and no conflicts. A task
+ * without a PR or a project without checks passes (the card says "проверки не настроены").
+ */
+export async function prGate(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise {
+ const n = taskPrNumber(ref.project, ref.task.prUrl);
+ if (!n) return { ok: true, summary: null, pull: null };
+ const { giteaOwner: o, giteaRepo: r } = ref.project;
+ const pull = await gitea.getPullRequest(o, r, n);
+ if (pull.merged) return { ok: true, summary: null, pull };
+ const [projectJson, status] = await Promise.all([gitea.fileText(o, r, ".peppa/project.json", pull.head.sha), gitea.combinedStatus(o, r, pull.head.sha)]);
+ const runs = (status.statuses ?? [])
+ .filter((s) => s.context.startsWith("peppa/"))
+ .map((s) => ({ check: s.context.slice(6), state: (s.status === "error" || s.status === "failure" ? "failure" : s.status === "success" ? "success" : "pending") as CheckState, runUrl: s.target_url }));
+ const summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha);
+ if (summary.state === "failure") return { ok: false, reason: `проверки не пройдены (${summary.failed.map((f) => f.check).join(", ")})`, summary, pull };
+ if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: `проверки ещё идут (${summary.passed} из ${summary.total})`, summary, pull };
+ if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: "есть конфликты с основной веткой", summary, pull };
+ return { ok: true, summary, pull };
+}
+
+/** Files that define the pipeline: changing them needs the PM's review even in auto mode. */
+export function isPipelineFile(path: string): boolean {
+ return path.startsWith(".gitea/") || path === ".peppa/project.json";
+}
+
+/**
+ * Pipeline changes in a PR: workflow files, or `checks`/`deploy` in .peppa/project.json
+ * (other fields of the project file are not the pipeline). Empty = none.
+ */
+export async function pipelineChanges(ref: TaskRef, pull: GiteaPull, gitea: GiteaClient = giteaForBot()): Promise {
+ const { giteaOwner: o, giteaRepo: r } = ref.project;
+ const out: string[] = [];
+ for (const f of (await gitea.pullFiles(o, r, pull.number)).filter(isPipelineFile)) {
+ if (f !== ".peppa/project.json") {
+ out.push(f);
+ continue;
+ }
+ const [before, after] = await Promise.all([gitea.fileText(o, r, f, pull.base.ref), gitea.fileText(o, r, f, pull.head.sha)]);
+ const pick = (t: string | null) => {
+ try {
+ const j = JSON.parse(t ?? "{}") as PeppaProjectFile;
+ return { checks: j.checks ?? {}, deploy: j.deploy ?? {} };
+ } catch {
+ return null;
+ }
+ };
+ const a = pick(before);
+ const b = pick(after);
+ for (const k of ["checks", "deploy"] as const) {
+ if (JSON.stringify(a?.[k]) !== JSON.stringify(b?.[k])) out.push(`${f} → ${k}: ${JSON.stringify(a?.[k] ?? null)} → ${JSON.stringify(b?.[k] ?? null)}`);
+ }
+ }
+ return out;
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d01c9289..c224e041 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -15,3 +15,4 @@ export * from "./access.ts";
export * from "./monitor.ts";
export * from "./repo-info.ts";
export * from "./incidents.ts";
+export * from "./ci.ts";
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index 10610281..15d397f5 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -5,6 +5,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";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@@ -119,6 +120,8 @@ export interface TaskDetails {
recentEvents: Array;
/** The production error this task fixes (PEP-58), if any. */
incident: Incident | null;
+ /** CI checks of the task's latest commit (PEP-57). */
+ ci: CiSummary;
}
export async function getTaskDetails(db: Db, ref: TaskRef): Promise {
@@ -131,7 +134,7 @@ export async function getTaskDetails(db: Db, ref: TaskRef): Promise
.orderBy(desc(events.id))
.limit(20);
const incident = await incidentForTask(db, ref.task.id);
- return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident };
+ return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse(), incident, ci: await taskCiSummary(db, ref) };
}
export interface NewQuestion {
diff --git a/packages/db/migrations/0012_faithful_matthew_murdock.sql b/packages/db/migrations/0012_faithful_matthew_murdock.sql
new file mode 100644
index 00000000..8e8e5e30
--- /dev/null
+++ b/packages/db/migrations/0012_faithful_matthew_murdock.sql
@@ -0,0 +1,22 @@
+CREATE TABLE "check_runs" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "project_id" integer NOT NULL,
+ "task_id" integer,
+ "sha" text NOT NULL,
+ "branch" text,
+ "pr_number" integer,
+ "check" text NOT NULL,
+ "state" text NOT NULL,
+ "run_url" text,
+ "log_tail" text,
+ "duration_sec" integer,
+ "source" text DEFAULT 'report' NOT NULL,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL
+);
+--> statement-breakpoint
+ALTER TABLE "tasks" ADD COLUMN "ci_attempts" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
+ALTER TABLE "tasks" ADD COLUMN "ci_failed_sha" text;--> statement-breakpoint
+ALTER TABLE "check_runs" ADD CONSTRAINT "check_runs_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "check_runs" ADD CONSTRAINT "check_runs_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
+CREATE UNIQUE INDEX "check_runs_project_sha_check" ON "check_runs" USING btree ("project_id","sha","check");
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0012_snapshot.json b/packages/db/migrations/meta/0012_snapshot.json
new file mode 100644
index 00000000..c30f3501
--- /dev/null
+++ b/packages/db/migrations/meta/0012_snapshot.json
@@ -0,0 +1,2061 @@
+{
+ "id": "ca89d235-ea51-4284-95fe-50b24621c88a",
+ "prevId": "47a9fc06-6fdb-42ad-8a5f-d80e76193258",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.check_runs": {
+ "name": "check_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "check": {
+ "name": "check",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration_sec": {
+ "name": "duration_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'report'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "check_runs_project_sha_check": {
+ "name": "check_runs_project_sha_check",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sha",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "check",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "check_runs_project_id_projects_id_fk": {
+ "name": "check_runs_project_id_projects_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "check_runs_task_id_tasks_id_fk": {
+ "name": "check_runs_task_id_tasks_id_fk",
+ "tableFrom": "check_runs",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.error_sources": {
+ "name": "error_sources",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "error_sources_project_id_projects_id_fk": {
+ "name": "error_sources_project_id_projects_id_fk",
+ "tableFrom": "error_sources",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "bugsink_project_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.events": {
+ "name": "events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "events_project_id_projects_id_fk": {
+ "name": "events_project_id_projects_id_fk",
+ "tableFrom": "events",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_task_id_tasks_id_fk": {
+ "name": "events_task_id_tasks_id_fk",
+ "tableFrom": "events",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "events_session_id_sessions_id_fk": {
+ "name": "events_session_id_sessions_id_fk",
+ "tableFrom": "events",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "goal_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_project_id_projects_id_fk": {
+ "name": "goals_project_id_projects_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.incident_settings": {
+ "name": "incident_settings",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[\"prod\",\"production\"]'::jsonb"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "incident_settings_project_id_projects_id_fk": {
+ "name": "incident_settings_project_id_projects_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incident_settings_goal_id_goals_id_fk": {
+ "name": "incident_settings_goal_id_goals_id_fk",
+ "tableFrom": "incident_settings",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "hook_secret"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.incidents": {
+ "name": "incidents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "incidents_project_id_projects_id_fk": {
+ "name": "incidents_project_id_projects_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "incidents_task_id_tasks_id_fk": {
+ "name": "incidents_task_id_tasks_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "bugsink_issue_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_clients": {
+ "name": "oauth_clients",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_codes": {
+ "name": "oauth_codes",
+ "schema": "",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_codes_client_id_oauth_clients_id_fk": {
+ "name": "oauth_codes_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_codes_user_id_users_id_fk": {
+ "name": "oauth_codes_user_id_users_id_fk",
+ "tableFrom": "oauth_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_tokens": {
+ "name": "oauth_tokens",
+ "schema": "",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauth_tokens_client_id_oauth_clients_id_fk": {
+ "name": "oauth_tokens_client_id_oauth_clients_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_tokens_user_id_users_id_fk": {
+ "name": "oauth_tokens_user_id_users_id_fk",
+ "tableFrom": "oauth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_invites": {
+ "name": "project_invites",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_invites_project_id_projects_id_fk": {
+ "name": "project_invites_project_id_projects_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_invites_invited_by_users_id_fk": {
+ "name": "project_invites_invited_by_users_id_fk",
+ "tableFrom": "project_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_invites_project_id_login_pk": {
+ "name": "project_invites_project_id_login_pk",
+ "columns": [
+ "project_id",
+ "login"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.project_members": {
+ "name": "project_members",
+ "schema": "",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "project_members_project_id_projects_id_fk": {
+ "name": "project_members_project_id_projects_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_user_id_users_id_fk": {
+ "name": "project_members_user_id_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_members_added_by_users_id_fk": {
+ "name": "project_members_added_by_users_id_fk",
+ "tableFrom": "project_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "added_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "project_members_project_id_user_id_pk": {
+ "name": "project_members_project_id_user_id_pk",
+ "columns": [
+ "project_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.projects": {
+ "name": "projects",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "projects_owner_id_users_id_fk": {
+ "name": "projects_owner_id_users_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "users",
+ "columnsFrom": [
+ "owner_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.questions": {
+ "name": "questions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "options": {
+ "name": "options",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "questions_project_id_projects_id_fk": {
+ "name": "questions_project_id_projects_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_task_id_tasks_id_fk": {
+ "name": "questions_task_id_tasks_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "questions_session_id_sessions_id_fk": {
+ "name": "questions_session_id_sessions_id_fk",
+ "tableFrom": "questions",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sessions": {
+ "name": "sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'claude'"
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "session_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sessions_project_id_projects_id_fk": {
+ "name": "sessions_project_id_projects_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sessions_task_id_tasks_id_fk": {
+ "name": "sessions_task_id_tasks_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tmux_name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.settings": {
+ "name": "settings",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tasks": {
+ "name": "tasks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "task_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ci_attempts": {
+ "name": "ci_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "ci_failed_sha": {
+ "name": "ci_failed_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "number",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tasks_project_id_projects_id_fk": {
+ "name": "tasks_project_id_projects_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tasks_goal_id_goals_id_fk": {
+ "name": "tasks_goal_id_goals_id_fk",
+ "tableFrom": "tasks",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "goal_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telegram_outbox": {
+ "name": "telegram_outbox",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "params": {
+ "name": "params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "telegram_outbox_question_id_questions_id_fk": {
+ "name": "telegram_outbox_question_id_questions_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "dedupe_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telegram_updates": {
+ "name": "telegram_updates",
+ "schema": "",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "gitea_id"
+ ]
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "login"
+ ]
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "telegram_chat_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.goal_status": {
+ "name": "goal_status",
+ "schema": "public",
+ "values": [
+ "open",
+ "done",
+ "archived"
+ ]
+ },
+ "public.session_status": {
+ "name": "session_status",
+ "schema": "public",
+ "values": [
+ "starting",
+ "running",
+ "waiting_input",
+ "idle",
+ "stalled",
+ "rate_limited",
+ "done",
+ "failed"
+ ]
+ },
+ "public.task_status": {
+ "name": "task_status",
+ "schema": "public",
+ "values": [
+ "backlog",
+ "proposing",
+ "awaiting_approval",
+ "in_progress",
+ "review",
+ "done",
+ "blocked"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json
index 309369cd..7c258cac 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -85,6 +85,13 @@
"when": 1794561166402,
"tag": "0011_pep58_incidents",
"breakpoints": true
+ },
+ {
+ "idx": 12,
+ "version": "7",
+ "when": 1794562626634,
+ "tag": "0012_faithful_matthew_murdock",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index d05ef5cb..a055a2bd 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -109,12 +109,38 @@ export const tasks = pgTable(
// OpenSpec change id under openspec/changes/, e.g. "pep-42-add-auth"
openspecChange: text("openspec_change"),
prUrl: text("pr_url"),
+ // PEP-57: red CI runs in a row (distinct head SHAs) since the last green one.
+ ciAttempts: integer("ci_attempts").notNull().default(0),
+ ciFailedSha: text("ci_failed_sha"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("tasks_project_number").on(t.projectId, t.number)],
);
+/** PEP-57: one CI check (lint/typecheck/test/build/install) of one commit of a project. */
+export const checkRuns = pgTable(
+ "check_runs",
+ {
+ id: serial("id").primaryKey(),
+ projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
+ taskId: integer("task_id").references(() => tasks.id, { onDelete: "set null" }),
+ sha: text("sha").notNull(),
+ branch: text("branch"),
+ prNumber: integer("pr_number"),
+ check: text("check").notNull(),
+ state: text("state", { enum: ["pending", "success", "failure", "error"] }).notNull(),
+ runUrl: text("run_url"),
+ logTail: text("log_tail"),
+ durationSec: integer("duration_sec"),
+ // "report" — the CI step itself (with the log), "poll" — commit status read by the watchdog.
+ source: text("source", { enum: ["report", "poll"] }).notNull().default("report"),
+ createdAt: createdAt(),
+ updatedAt: updatedAt(),
+ },
+ (t) => [uniqueIndex("check_runs_project_sha_check").on(t.projectId, t.sha, t.check)],
+);
+
export const sessionStatus = pgEnum("session_status", [
"starting",
"running",
diff --git a/packages/mcp/src/format.ts b/packages/mcp/src/format.ts
index fcb28d51..a076ca01 100644
--- a/packages/mcp/src/format.ts
+++ b/packages/mcp/src/format.ts
@@ -21,6 +21,8 @@ export function formatTask(d: TaskDetails): string {
`- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`,
];
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
+ lines.push(`- ${d.ci.label.charAt(0).toUpperCase()}${d.ci.label.slice(1)}${d.ci.sha ? ` (коммит ${d.ci.sha.slice(0, 7)})` : ""}${d.ci.runUrl ? ` · ${d.ci.runUrl}` : ""}`);
+ for (const f of d.ci.failed) lines.push(` - ❌ ${f.check}${f.runUrl ? ` · ${f.runUrl}` : ""}`);
lines.push("", "## Описание", "", task.description?.trim() || "_нет описания_");
if (goal?.description) lines.push("", `## Цель #${goal.id}: ${goal.title}`, "", goal.description.trim());
if (d.incident) lines.push("", "## Инцидент", "", formatIncident(d.incident));
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index fa0c9088..e44a540d 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -21,6 +21,7 @@ import {
updateTask,
} from "@peppa/core";
import { createDb } from "@peppa/db";
+import { reviewGate } from "@peppa/runner";
import { z } from "zod";
import { formatIncident, formatTask } from "./format.ts";
@@ -128,6 +129,13 @@ tool(
if (status === "in_progress" && ref.task.status === "awaiting_approval") {
throw new PeppaError("The proposal is awaiting the PM's approval; only the PM can move it to in_progress.");
}
+ if (status === "review" && ref.task.status !== "review") {
+ // PEP-57: review only with green checks of the PR head (the PR given now counts).
+ const reason = await reviewGate({ ...ref, task: { ...ref.task, prUrl: pr_url ?? ref.task.prUrl } });
+ if (reason) {
+ throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`);
+ }
+ }
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
},
diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts
index 5f05522b..0f9d0fb3 100644
--- a/packages/mcp/src/manager.ts
+++ b/packages/mcp/src/manager.ts
@@ -272,7 +272,7 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
tool(
"answer_question",
- "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' closes the task, any other text goes back to the agent.",
+ "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' merges the task's PR (only with green CI checks and no conflicts, otherwise the reason is returned) and closes the task, any other text goes back to the agent.",
{ question_id: z.number().int(), answer: z.string().min(1) },
false,
async ({ question_id, answer }) => {
diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts
new file mode 100644
index 00000000..57311b9c
--- /dev/null
+++ b/packages/runner/src/ci-feedback.ts
@@ -0,0 +1,214 @@
+// CI feedback (PEP-57): results come from the CI step itself (signed report with the log),
+// from Gitea webhooks, and from the watchdog polling commit statuses as a fallback. A red
+// check goes back to the agent with the step and the log tail; 3 red runs in a row → the PM.
+import {
+ askPm,
+ giteaForBot,
+ listSessions,
+ listTasks,
+ PeppaError,
+ prGate,
+ pipelineChanges,
+ runLink,
+ taskForCheck,
+ taskPrNumber,
+ upsertCheckRun,
+ verifyHookSignature,
+ type CheckReport,
+ type GiteaClient,
+ type Project,
+ type TaskRef,
+} from "@peppa/core";
+import { checkRuns, projects, tasks, type Db } from "@peppa/db";
+import { and, eq, sql } from "drizzle-orm";
+import { sendToSession } from "./sessions.ts";
+import { moveTask } from "./flow.ts";
+
+/** Red runs in a row after which the PM is asked instead of the agent. */
+export const MAX_CI_ATTEMPTS = 3;
+const LOG_LINES = 100;
+
+const tail = (log: string | null | undefined, n = LOG_LINES) => (log ?? "").trimEnd().split("\n").slice(-n).join("\n");
+
+async function activeSessionId(db: Db, taskId: number): Promise {
+ return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null;
+}
+
+export interface CheckOutcome {
+ task: string | null;
+ /** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */
+ action: "none" | "agent" | "restarted" | "pm" | "green";
+}
+
+/** Records one CI result and reacts to it for the task of that branch/PR. */
+export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise {
+ const ref = await taskForCheck(db, project, r.branch, r.prNumber);
+ const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r);
+ if (!ref || !changed) return { task: ref?.key ?? null, action: "none" };
+ if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" };
+
+ if (r.state === "success") {
+ const [red] = await db
+ .select({ id: checkRuns.id })
+ .from(checkRuns)
+ .where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), sql`${checkRuns.state} in ('failure','error')`));
+ if (red || ref.task.ciAttempts === 0) return { task: ref.key, action: "none" };
+ await db.update(tasks).set({ ciAttempts: 0, ciFailedSha: null }).where(eq(tasks.id, ref.task.id));
+ return { task: ref.key, action: "green" };
+ }
+ if (r.state !== "failure" && r.state !== "error") return { task: ref.key, action: "none" };
+
+ // Several red checks of one commit are one attempt.
+ const newRun = ref.task.ciFailedSha !== r.sha;
+ const attempts = newRun ? ref.task.ciAttempts + 1 : ref.task.ciAttempts;
+ if (newRun) await db.update(tasks).set({ ciAttempts: attempts, ciFailedSha: r.sha }).where(eq(tasks.id, ref.task.id));
+ const link = runLink(r.runUrl);
+ const sessionId = await activeSessionId(db, ref.task.id);
+
+ if (attempts >= MAX_CI_ATTEMPTS) {
+ if (!newRun) return { task: ref.key, action: "none" }; // the PM already has this commit
+ await askPm(db, ref, {
+ kind: "question",
+ sessionId: sessionId ?? undefined,
+ text: `❌ ${ref.key}: проверки PR красные ${attempts} раза подряд — агент не справился сам. Упала «${r.check}» (коммит ${r.sha.slice(0, 7)}).${link ? `\nЛог: ${link}` : ""}\n\nЧто делать? Ответ уйдёт агенту.`,
+ });
+ if (sessionId) {
+ await sendToSession(db, sessionId, `Проверки PR ${ref.key} красные ${attempts} раза подряд — я спросил PM. Не пушь новых попыток, закончи ход и жди ответа PM.`).catch(() => {});
+ }
+ return { task: ref.key, action: "pm" };
+ }
+
+ const text = [
+ `❌ CI по ${ref.key}: упала проверка «${r.check}» (коммит ${r.sha.slice(0, 7)}, попытка ${attempts} из ${MAX_CI_ATTEMPTS}).${link ? ` Лог: ${link}` : ""}`,
+ r.logTail ? `Последние строки лога:\n${tail(r.logTail)}` : "Лога в отчёте нет — открой ссылку.",
+ `Почини (локально: bash .gitea/peppa-check.sh ${r.check}) и запушь в ту же ветку; не ослабляй проверки.`,
+ ].join("\n\n");
+ if (sessionId) {
+ await sendToSession(db, sessionId, text);
+ // The work is not done: a task that already went to review goes back.
+ if (ref.task.status === "review") await moveTask(db, ref, "in_progress");
+ return { task: ref.key, action: "agent" };
+ }
+ await moveTask(db, ref, "in_progress", { prompt: text });
+ return { task: ref.key, action: "restarted" };
+}
+
+/** Project of a repository "owner/name" (case-insensitive). */
+export async function projectByRepo(db: Db, fullName: string): Promise {
+ const [owner, name] = fullName.split("/");
+ if (!owner || !name) return null;
+ const [p] = await db
+ .select()
+ .from(projects)
+ .where(and(sql`lower(${projects.giteaOwner}) = ${owner.toLowerCase()}`, sql`lower(${projects.giteaRepo}) = ${name.toLowerCase()}`));
+ return p ?? null;
+}
+
+export interface HookRequest {
+ /** X-Gitea-Event (Gitea webhooks) or X-Peppa-Event (the CI step). */
+ event: string;
+ signature: string | null;
+ body: string;
+}
+
+/** Handlers for Gitea events other than CI checks (deploys hook in here). */
+export type GiteaEventHandler = (db: Db, project: Project, event: string, payload: Record) => Promise;
+const eventHandlers: GiteaEventHandler[] = [];
+export function onGiteaEvent(h: GiteaEventHandler) {
+ eventHandlers.push(h);
+}
+
+/** POST /api/hooks/gitea: verifies the project's signature, then records/dispatches. */
+export async function handleGiteaHook(db: Db, req: HookRequest): Promise<{ status: number; body: Record }> {
+ let payload: Record;
+ try {
+ payload = JSON.parse(req.body) as Record;
+ } catch {
+ return { status: 400, body: { error: "invalid json" } };
+ }
+ const repo = typeof payload.repository === "string" ? payload.repository : ((payload.repository as { full_name?: string } | undefined)?.full_name ?? "");
+ const project = await projectByRepo(db, repo);
+ if (!project) return { status: 404, body: { error: "unknown repository" } };
+ if (!verifyHookSignature(project.id, req.body, req.signature)) return { status: 401, body: { error: "bad signature" } };
+
+ if (req.event === "check") {
+ const state = String(payload.state);
+ if (!["success", "failure", "error", "pending"].includes(state) || typeof payload.sha !== "string" || typeof payload.check !== "string") {
+ return { status: 400, body: { error: "bad check report" } };
+ }
+ const out = await recordCheck(db, project, {
+ sha: payload.sha,
+ branch: (payload.branch as string) || null,
+ prNumber: typeof payload.pr === "number" ? payload.pr : null,
+ check: payload.check,
+ state: state as CheckReport["state"],
+ runUrl: (payload.run_url as string) ?? null,
+ logTail: (payload.log_tail as string) ?? null,
+ durationSec: typeof payload.duration_sec === "number" ? payload.duration_sec : null,
+ source: "report",
+ });
+ return { status: 200, body: { ok: true, ...out } };
+ }
+ for (const h of eventHandlers) await h(db, project, req.event, payload);
+ return { status: 200, body: { ok: true } };
+}
+
+/**
+ * Fallback when reports/webhooks are lost: commit statuses `peppa/*` of the PR heads of
+ * tasks in work or review (the watchdog calls this about once a minute).
+ */
+export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Promise {
+ let seen = 0;
+ for (const t of await listTasks(db, { statuses: ["in_progress", "review"] })) {
+ if (!t.prUrl) continue;
+ const [p] = await db.select().from(projects).where(eq(projects.id, t.projectId));
+ const n = p && taskPrNumber(p, t.prUrl);
+ if (!p || !n) continue;
+ try {
+ const pull = await gitea.getPullRequest(p.giteaOwner, p.giteaRepo, n);
+ if (pull.state !== "open") continue;
+ const st = await gitea.combinedStatus(p.giteaOwner, p.giteaRepo, pull.head.sha);
+ for (const s of st.statuses ?? []) {
+ if (!s.context.startsWith("peppa/")) continue;
+ const state = s.status === "warning" ? "pending" : s.status;
+ await recordCheck(db, p, { sha: pull.head.sha, branch: pull.head.ref, prNumber: n, check: s.context.slice(6), state, runUrl: s.target_url ?? null, source: "poll" });
+ seen++;
+ }
+ } catch {}
+ }
+ return seen;
+}
+
+/**
+ * Merge on "Accept" (PEP-57): only with green checks of the PR head and no conflicts.
+ * Throws with the reason for the PM; a task without a PR has nothing to merge.
+ */
+export async function mergeTaskPr(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<"merged" | "already" | "no_pr"> {
+ const gate = await prGate(ref, gitea);
+ if (!gate.pull) return "no_pr";
+ if (gate.pull.merged) return "already";
+ if (!gate.ok) throw new PeppaError(`Мерж не выполнен: ${gate.reason}`);
+ await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha);
+ return "merged";
+}
+
+/**
+ * Automatic merge (auto mode of a project, PEP-23/25): the same gate, and a PR that changes
+ * the pipeline is never merged automatically — the PM gets a question describing the change.
+ */
+export async function autoMergeTask(db: Db, ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<{ merged: boolean; reason?: string }> {
+ const gate = await prGate(ref, gitea);
+ if (!gate.pull) return { merged: false, reason: "нет PR" };
+ if (gate.pull.merged) return { merged: true };
+ if (!gate.ok) return { merged: false, reason: gate.reason };
+ const changes = await pipelineChanges(ref, gate.pull, gitea);
+ if (changes.length) {
+ await askPm(db, ref, {
+ kind: "question",
+ text: `⚠️ ${ref.key}: PR меняет конвейер — автомерж отключён, нужно ваше ревью.\n${changes.map((c) => `• ${c}`).join("\n")}\nPR: ${gate.pull.html_url}`,
+ });
+ return { merged: false, reason: "изменение конвейера требует ревью PM" };
+ }
+ await gitea.mergePullRequest(ref.project.giteaOwner, ref.project.giteaRepo, gate.pull.number, gate.pull.head.sha);
+ return { merged: true };
+}
diff --git a/packages/runner/src/ci.ts b/packages/runner/src/ci.ts
index c1bfc310..652132ed 100644
--- a/packages/runner/src/ci.ts
+++ b/packages/runner/src/ci.ts
@@ -16,6 +16,9 @@ export const CI_FILES = [".gitea/workflows/ci.yml", ".gitea/peppa-check.sh"];
export const CI_BRANCH = "peppa/ci";
export const CI_SECRET_NAME = "PEPPA_CI_SECRET";
+/** Where Gitea webhooks and CI reports reach Peppa. */
+export const giteaHookUrl = () => `${loadEnv().PEPPA_WEB_URL.replace(/\/$/, "")}/api/hooks/gitea`;
+
const botLogin = () => process.env.GITEA_BOT_USER ?? "peppa-bot";
/**
@@ -48,7 +51,7 @@ export interface CiSetup {
runner: "bot" | "repo";
}
-/** Runner coverage and the Actions secret for CI reports. Idempotent. */
+/** Runner coverage, the Actions secret for CI reports and the webhook. Idempotent. */
export async function setupCi(db: Db, project: Project): Promise {
const clients = await repoAdmins(db, project);
if (!clients.length) throw new PeppaError("Нет доступа к Gitea");
@@ -58,7 +61,10 @@ export async function setupCi(db: Db, project: Project): Promise {
await registerCiRunner(`repo-${project.giteaOwner}--${project.giteaRepo}`, token);
runner = "repo";
}
- await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, projectHookSecret(project.id)));
+ const secret = projectHookSecret(project.id);
+ await asAdmin(clients, `Секрет ${CI_SECRET_NAME}`, (c) => c.setActionsSecret(project.giteaOwner, project.giteaRepo, CI_SECRET_NAME, secret));
+ // PR and push events (preview stands, merges) — signed with the same secret.
+ await asAdmin(clients, "Вебхук", (c) => c.upsertHook(project.giteaOwner, project.giteaRepo, giteaHookUrl(), secret, ["pull_request", "push"]));
return { runner };
}
diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts
index 1e74e265..5858cf4d 100644
--- a/packages/runner/src/flow.ts
+++ b/packages/runner/src/flow.ts
@@ -1,9 +1,10 @@
// PM-side moves on the task board and review acceptance (web and Telegram use these).
-import { answerQuestion, getQuestion, listSessions, PeppaError, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core";
+import { answerQuestion, getQuestion, listSessions, PeppaError, prGate, resolveTask, updateTask, type Question, type TaskRef } from "@peppa/core";
import { tasks, projects, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { eq } from "drizzle-orm";
import { startSession, stopSession, type StartOptions } from "./sessions.ts";
+import { mergeTaskPr } from "./ci-feedback.ts";
export type BoardColumn = "backlog" | "in_progress" | "review" | "done";
@@ -19,9 +20,19 @@ async function activeSessions(db: Db, taskId: number) {
return (await listSessions(db, { active: true, taskId }));
}
+/**
+ * Review gate (PEP-57): the task's PR head must have green checks and no conflicts. Fails
+ * open when Gitea can't be reached — merging is gated again on "Accept".
+ */
+export async function reviewGate(ref: TaskRef): Promise {
+ const gate = await prGate(ref).catch(() => null);
+ return gate && !gate.ok ? gate.reason ?? "проверки не пройдены" : null;
+}
+
/**
* Moves a task card. Into "in progress": status in_progress and an agent session is
- * started unless one is running. Into "backlog"/"done": active sessions are stopped.
+ * started unless one is running. Into "review": only past the CI gate. Into
+ * "backlog"/"done": active sessions are stopped.
*/
export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: StartOptions = {}): Promise<{ started?: number; stopped: number }> {
const from = columnOf(ref.task.status);
@@ -34,6 +45,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
}
return { stopped };
}
+ if (to === "review" && from !== "review") {
+ const reason = await reviewGate(ref);
+ if (reason) throw new PeppaError(`${ref.key} нельзя в ревью: ${reason}`);
+ }
if (to === "backlog" || to === "done") {
for (const s of await activeSessions(db, ref.task.id)) {
await stopSession(db, s.id);
@@ -44,7 +59,10 @@ export async function moveTask(db: Db, ref: TaskRef, to: BoardColumn, start: Sta
return { stopped };
}
-/** "Accept" on a ready-for-review message: task done, session stopped, question closed. */
+/**
+ * "Accept" on a ready-for-review message: the task's PR is merged (green checks, no
+ * conflicts — otherwise nothing changes and the PM sees why), task done, session stopped.
+ */
export async function acceptTask(db: Db, questionId: number, via: NonNullable): Promise {
const q = await getQuestion(db, questionId);
if (!q.taskId) throw new PeppaError("Вопрос не привязан к задаче");
@@ -56,6 +74,7 @@ export async function acceptTask(db: Db, questionId: number, via: NonNullable {
const log = opts.log ?? (() => {});
log(`watchdog started: every ${opts.intervalMs / 1000}s, stall after ${opts.stallMs / 60000}m`);
@@ -128,6 +131,11 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`));
// Heartbeat and the check on the bot and the web (PEP-20).
await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`));
+ // CI results lost on the way (PEP-57): poll commit statuses about once a minute.
+ if (Date.now() - lastCiPoll >= 60_000) {
+ lastCiPoll = Date.now();
+ await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`));
+ }
await new Promise((r) => setTimeout(r, opts.intervalMs));
}
}
diff --git a/packages/testkit/test/ci-feedback.test.ts b/packages/testkit/test/ci-feedback.test.ts
new file mode 100644
index 00000000..bdea79c1
--- /dev/null
+++ b/packages/testkit/test/ci-feedback.test.ts
@@ -0,0 +1,251 @@
+// PEP-57, spec delivery-pipeline: «Проверки на каждый PR», «Красные проверки возвращаются
+// агенту», «Гейт ревью и мержа», «Изменение конвейера требует ревью» — one test per scenario,
+// against mock Gitea (commit statuses, PRs, webhooks) and mock-claude runners.
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { createHmac } from "node:crypto";
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-cifb-")), "gitea"));
+const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
+const CHECKS = { lint: "pnpm lint", typecheck: "pnpm typecheck", test: "pnpm test", build: "pnpm build" };
+
+before(async () => {
+ await gitea.start();
+ process.env.GITEA_URL = gitea.url;
+ process.env.GITEA_TOKEN = BOT.token;
+ gitea.addUser(BOT);
+});
+after(async () => {
+ await gitea.stop();
+ await teardown();
+});
+
+interface CiTask {
+ p: TestProject;
+ proj: Awaited>;
+ ref: () => ReturnType;
+ branch: string;
+ /** Pushes a commit to the task branch, returns its SHA. */
+ push(files?: Record): string;
+ /** CI result of one check, as the CI step reports it (signed webhook). */
+ report(sha: string, check: string, state: string, log?: string): ReturnType;
+ statuses(sha: string, state: string, checks?: string[]): void;
+}
+
+/** Project with a repo in mock Gitea and a task with an open PR from task/-1. */
+async function ciTask(opts: { checks?: Record; turns?: Parameters[0]["turns"] } = {}): Promise {
+ const p = await project({ turns: opts.turns ?? [] });
+ const proj = await core.getProject(db, p.key);
+ const pj = JSON.stringify({ slug: proj.slug, key: p.key, name: p.key, peppaUrl: "http://test", ...(opts.checks ? { checks: opts.checks } : {}) });
+ writeFileSync(join(p.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 branch = `task/${p.taskKey}`;
+ let n = 0;
+ const push = (files: Record = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${n++}.txt`]: String(n), ...files });
+ push();
+ const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
+ const ref = () => core.resolveTask(db, p.taskKey);
+ await core.updateTask(db, await ref(), { status: "in_progress", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
+ const repo = `${proj.giteaOwner}/${proj.giteaRepo}`;
+ return {
+ p,
+ proj,
+ ref,
+ branch,
+ push,
+ report(sha, check, state, log = "") {
+ const body = JSON.stringify({ repository: repo, sha, branch, pr: pr.number, check, state, run_url: `/${repo}/actions/runs/${sha.slice(0, 4)}`, duration_sec: 3, log_tail: log });
+ const signature = createHmac("sha256", core.projectHookSecret(proj.id)).update(body).digest("hex");
+ return runner.handleGiteaHook(db, { event: "check", signature, body });
+ },
+ statuses(sha, state, checks = Object.keys(CHECKS)) {
+ for (const c of checks) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, state, { target_url: `/${repo}/actions/runs/1` });
+ },
+ };
+}
+
+async function toReview(t: CiTask) {
+ await core.updateTask(db, await t.ref(), { status: "review" });
+ return core.askPm(db, await t.ref(), { kind: "attention", text: "готова к ревью" });
+}
+
+describe("Проверки на каждый PR", () => {
+ test("Scenario: Зелёные проверки — в карточке «Проверки: 4 из 4 пройдены» со ссылкой на прогон", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const sha = t.push();
+ for (const c of Object.keys(CHECKS)) assert.equal((await t.report(sha, c, "success")).status, 200);
+ const d = await core.getTaskDetails(db, await t.ref());
+ assert.equal(d.ci.label, "Проверки: 4 из 4 пройдены");
+ assert.equal(d.ci.runUrl, `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/actions/runs/${sha.slice(0, 4)}`);
+ const { formatTask } = await import("../../mcp/src/format.ts");
+ assert.match(formatTask(d), /Проверки: 4 из 4 пройдены \(коммит [0-9a-f]{7}\)/, "MCP get_task shows the checks");
+ });
+
+ test("Scenario: Проверки не настроены — видно «проверки не настроены», переход в «Ревью» не блокируется", async () => {
+ const t = await ciTask();
+ t.push();
+ assert.equal((await core.getTaskDetails(db, await t.ref())).ci.label, "проверки не настроены");
+ await runner.moveTask(db, await t.ref(), "review");
+ assert.equal((await t.ref()).task.status, "review");
+ });
+});
+
+describe("Красные проверки возвращаются агенту", () => {
+ test("Scenario: Агент чинит сам — раннер получает шаг «test» и хвост лога, задача в работе, PM ничего не получает", async () => {
+ const t = await ciTask({ checks: CHECKS, turns: [[{ say: "PR открыт" }], [{ say: "чиню" }], [{ say: "ещё" }], [{ say: "и ещё" }]] });
+ const id = await t.p.start();
+ await t.p.waitLog("agent started", (e) => e.ev === "prompt");
+ const sha = t.push();
+ const r = await t.report(sha, "test", "failure", "ok 1 - adds\nnot ok 2 - divides by zero\n# fail 1");
+ assert.equal((r.body as { action: string }).action, "agent");
+ await t.p.waitLog("failure delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("«test»") && String(e.prompt).includes("not ok 2 - divides by zero"));
+ assert.equal((await t.ref()).task.status, "in_progress");
+ assert.equal((await core.pendingQuestions(db, t.proj.id)).filter((q) => q.kind !== "attention").length, 0);
+ const task = (await t.ref()).task;
+ assert.equal(task.ciAttempts, 1);
+ // A second red check of the same commit is the same attempt.
+ await t.report(sha, "lint", "failure", "lint error");
+ assert.equal((await t.ref()).task.ciAttempts, 1);
+ await runner.stopSession(db, id);
+ });
+
+ test("Scenario: Три неудачи подряд — PM получает вопрос со ссылкой на лог", async () => {
+ const t = await ciTask({ checks: CHECKS, turns: [[{ say: "1" }], [{ say: "2" }], [{ say: "3" }], [{ say: "4" }], [{ say: "5" }]] });
+ const id = await t.p.start();
+ await t.p.waitLog("agent started", (e) => e.ev === "prompt");
+ const actions: string[] = [];
+ for (let i = 0; i < 3; i++) actions.push(((await t.report(t.push(), "test", "failure", `fail #${i}`)).body as { action: string }).action);
+ assert.deepEqual(actions, ["agent", "agent", "pm"]);
+ const q = (await core.pendingQuestions(db, t.proj.id)).find((x) => x.kind === "question");
+ assert.ok(q, "PM got a question");
+ assert.equal(q.taskId, (await t.ref()).task.id);
+ assert.match(q.text, new RegExp(`красные 3 раза подряд[\\s\\S]*Лог: ${gitea.url}/`));
+ await t.p.waitLog("runner told to wait", (e) => e.ev === "prompt" && String(e.prompt).includes("жди ответа PM"));
+ // Green again → the counter starts over.
+ const sha = t.push();
+ for (const c of Object.keys(CHECKS)) await t.report(sha, c, "success");
+ assert.equal((await t.ref()).task.ciAttempts, 0);
+ await runner.stopSession(db, id);
+ });
+
+ test("no runner: a red check sends a task in review back to work and starts the agent with the log", async () => {
+ const t = await ciTask({ checks: CHECKS, turns: [[{ say: "чиню" }]] });
+ const sha = t.push();
+ await core.updateTask(db, await t.ref(), { status: "review" });
+ const r = await t.report(sha, "build", "failure", "error TS2304: Cannot find name 'x'");
+ assert.equal((r.body as { action: string }).action, "restarted");
+ assert.equal((await t.ref()).task.status, "in_progress");
+ await t.p.waitLog("agent started with the failure", (e) => e.ev === "prompt" && String(e.prompt).includes("Cannot find name 'x'"));
+ for (const s of await core.listSessions(db, { active: true, taskId: (await t.ref()).task.id })) await runner.stopSession(db, s.id);
+ });
+
+ test("the template's CI step reports to Peppa: signature accepted, log tail stored", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const sha = t.push();
+ // Peppa's POST /api/hooks/gitea, as the web route does it.
+ const server = createServer((req, res) => {
+ let body = "";
+ req.on("data", (c) => (body += c));
+ req.on("end", async () => {
+ const r = await runner.handleGiteaHook(db, { event: String(req.headers["x-peppa-event"]), signature: String(req.headers["x-gitea-signature"]), body });
+ res.writeHead(r.status).end(JSON.stringify(r.body));
+ });
+ });
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ const job = mkdtempSync(join(tmpdir(), "peppa-job-"));
+ mkdirSync(join(job, ".peppa"));
+ writeFileSync(join(job, ".peppa/project.json"), JSON.stringify({ peppaUrl: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, checks: { test: "echo 'not ok 1 - кириллица и \"кавычки\"'; exit 1" } }));
+ const script = resolve(fileURLToPath(import.meta.url), "../../../../template/.gitea/peppa-check.sh");
+ const env = { ...process.env, GITHUB_ACTIONS: "true", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${t.proj.giteaOwner}/${t.proj.giteaRepo}`, GITHUB_RUN_NUMBER: "9", PEPPA_SHA: sha, PEPPA_BRANCH: t.branch, PEPPA_PR: "1", GITEA_TOKEN: BOT.token, PEPPA_CI_SECRET: core.projectHookSecret(t.proj.id) };
+ const out = await new Promise((done) => execFile("bash", [script, "test"], { cwd: job, env, encoding: "utf8" }, (_e, stdout) => done(stdout)));
+ server.close();
+ assert.doesNotMatch(out, /недоступна/);
+ const d = await core.getTaskDetails(db, await t.ref());
+ assert.equal(d.ci.failed[0]?.check, "test");
+ assert.match(d.ci.failed[0]?.logTail ?? "", /not ok 1 - кириллица и "кавычки"/);
+ assert.equal(d.ci.failed[0]?.runUrl, `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/actions/runs/9`);
+ assert.equal((await t.ref()).task.ciAttempts, 1);
+ });
+
+ test("webhook: wrong signature and unknown repo are rejected; polling picks up lost results", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const sha = t.push();
+ const body = JSON.stringify({ repository: `${t.proj.giteaOwner}/${t.proj.giteaRepo}`, sha, check: "test", state: "success" });
+ assert.equal((await runner.handleGiteaHook(db, { event: "check", signature: "00", body })).status, 401);
+ assert.equal((await runner.handleGiteaHook(db, { event: "check", signature: "00", body: JSON.stringify({ repository: "nobody/nothing" }) })).status, 404);
+ t.statuses(sha, "success");
+ assert.ok((await runner.pollChecks(db)) >= 4);
+ assert.equal((await core.getTaskDetails(db, await t.ref())).ci.label, "Проверки: 4 из 4 пройдены");
+ });
+});
+
+describe("Гейт ревью и мержа", () => {
+ test("Scenario: Мерж при красных проверках — мерж не выполняется, PM видит «проверки не пройдены»", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const sha = t.push();
+ t.statuses(sha, "success", ["lint", "typecheck", "build"]);
+ t.statuses(sha, "failure", ["test"]);
+ const q = await toReview(t);
+ await assert.rejects(runner.acceptTask(db, q.id, "web"), /Мерж не выполнен: проверки не пройдены \(test\)/);
+ assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, false);
+ assert.equal((await t.ref()).task.status, "review");
+ assert.equal((await core.getQuestion(db, q.id)).answeredAt, null, "the review question stays open");
+ });
+
+ test("Scenario: Приёмка — PR смержен в основную ветку, задача в «Готово»", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const sha = t.push();
+ t.statuses(sha, "success");
+ const q = await toReview(t);
+ await runner.acceptTask(db, q.id, "web");
+ const pr = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!;
+ assert.equal(pr.merged, true);
+ assert.equal(gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, "main"), sha);
+ assert.equal((await t.ref()).task.status, "done");
+ });
+
+ test("review gate: the agent can't move a task to review with red or running checks", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const sha = t.push();
+ t.statuses(sha, "success", ["lint"]);
+ assert.match((await runner.reviewGate(await t.ref())) ?? "", /проверки ещё идут \(1 из 4\)/);
+ await assert.rejects(runner.moveTask(db, await t.ref(), "review"), /нельзя в ревью: проверки ещё идут/);
+ t.statuses(sha, "success");
+ gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.mergeable = false;
+ assert.equal(await runner.reviewGate(await t.ref()), "есть конфликты с основной веткой");
+ gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.mergeable = true;
+ assert.equal(await runner.reviewGate(await t.ref()), null);
+ });
+});
+
+describe("Изменение конвейера требует ревью", () => {
+ test("Scenario: Агент отключил тесты — PR не мержится автоматически, PM получает вопрос с описанием изменения", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ const pj = JSON.stringify({ slug: t.proj.slug, key: t.p.key, name: t.p.key, peppaUrl: "http://test", checks: { ...CHECKS, test: "true" } });
+ const sha = t.push({ ".peppa/project.json": pj });
+ t.statuses(sha, "success");
+ const r = await runner.autoMergeTask(db, await t.ref());
+ assert.deepEqual(r, { merged: false, reason: "изменение конвейера требует ревью PM" });
+ assert.equal(gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[0]!.merged, false);
+ const q = await waitFor("pipeline question", async () => (await core.pendingQuestions(db, t.proj.id)).find((x) => x.text.includes("меняет конвейер")));
+ assert.match(q.text, /checks: .*"test":"pnpm test".* → .*"test":"true"/);
+ });
+
+ test("auto-merge without pipeline changes merges a green PR", async () => {
+ const t = await ciTask({ checks: CHECKS });
+ t.statuses(t.push(), "success");
+ assert.deepEqual(await runner.autoMergeTask(db, await t.ref()), { merged: true });
+ });
+});
diff --git a/packages/testkit/test/ci.test.ts b/packages/testkit/test/ci.test.ts
index 9143d755..0e7db66c 100644
--- a/packages/testkit/test/ci.test.ts
+++ b/packages/testkit/test/ci.test.ts
@@ -65,6 +65,8 @@ describe("CI: connect a project", () => {
assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos");
const repo = gitea.repo(BOT.login, p.giteaRepo);
assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id));
+ assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), ["pull_request", "push"]]]);
+ assert.match(runner.giteaHookUrl(), /\/api\/hooks\/gitea$/);
assert.ok(r.prUrl?.endsWith("/pulls/1"));
const pr = repo.pulls[0]!;
assert.equal(pr.head, runner.CI_BRANCH);
--
2.45.2
From daa612b0d884091efd351296014caddd158b0c1e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 14:36:47 +0500
Subject: [PATCH 022/556] =?UTF-8?q?PEP-57:=20gate=20=E2=80=94=20Gitea=20cl?=
=?UTF-8?q?ient=20only=20for=20tasks=20with=20a=20PR?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
packages/core/src/ci.ts | 3 ++-
packages/runner/src/ci-feedback.ts | 4 +++-
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts
index 32a123c9..06a5a5cb 100644
--- a/packages/core/src/ci.ts
+++ b/packages/core/src/ci.ts
@@ -137,9 +137,10 @@ export interface GateResult {
* Gate for review and merge: the task's PR head has green checks and no conflicts. A task
* without a PR or a project without checks passes (the card says "проверки не настроены").
*/
-export async function prGate(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise {
+export async function prGate(ref: TaskRef, client?: GiteaClient): Promise {
const n = taskPrNumber(ref.project, ref.task.prUrl);
if (!n) return { ok: true, summary: null, pull: null };
+ const gitea = client ?? giteaForBot();
const { giteaOwner: o, giteaRepo: r } = ref.project;
const pull = await gitea.getPullRequest(o, r, n);
if (pull.merged) return { ok: true, summary: null, pull };
diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts
index 57311b9c..0c76c0ec 100644
--- a/packages/runner/src/ci-feedback.ts
+++ b/packages/runner/src/ci-feedback.ts
@@ -183,7 +183,9 @@ export async function pollChecks(db: Db, gitea: GiteaClient = giteaForBot()): Pr
* Merge on "Accept" (PEP-57): only with green checks of the PR head and no conflicts.
* Throws with the reason for the PM; a task without a PR has nothing to merge.
*/
-export async function mergeTaskPr(ref: TaskRef, gitea: GiteaClient = giteaForBot()): Promise<"merged" | "already" | "no_pr"> {
+export async function mergeTaskPr(ref: TaskRef, client?: GiteaClient): Promise<"merged" | "already" | "no_pr"> {
+ if (!taskPrNumber(ref.project, ref.task.prUrl)) return "no_pr";
+ const gitea = client ?? giteaForBot();
const gate = await prGate(ref, gitea);
if (!gate.pull) return "no_pr";
if (gate.pull.merged) return "already";
--
2.45.2
From 59c3b583deb944f738f0a4d5ada686b5a29c12f1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Fri, 13 Nov 2026 14:49:24 +0500
Subject: [PATCH 023/556] =?UTF-8?q?PEP-57:=20CD=20=E2=80=94=20deploy=20wor?=
=?UTF-8?q?kflow,=20preview/staging/prod,=20health=20check=20and=20rollbac?=
=?UTF-8?q?k,=20releases?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Opus 5.5
---
AGENTS.md | 1 +
apps/bot/src/render.ts | 2 +-
apps/web/app/(app)/actions.ts | 11 +-
apps/web/app/(app)/help/page.tsx | 24 +-
apps/web/app/(app)/p/[key]/page.tsx | 48 +-
openspec/changes/pep-57-ci-cd/design.md | 16 +
openspec/changes/pep-57-ci-cd/tasks.md | 8 +-
packages/cli/src/index.ts | 17 +-
packages/core/src/tasks.ts | 7 +
.../db/migrations/0013_pep57_releases.sql | 20 +
.../db/migrations/meta/0013_snapshot.json | 2189 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
packages/db/src/schema.ts | 22 +
packages/mcp/src/manager.ts | 23 +-
packages/runner/src/ci-feedback.ts | 22 +
packages/runner/src/ci.ts | 7 +-
packages/runner/src/deploy.ts | 167 ++
packages/runner/src/index.ts | 1 +
packages/runner/src/sessions.ts | 3 +
packages/testkit/bin/mock-docker | 35 +
packages/testkit/src/mock-gitea.ts | 7 +-
packages/testkit/test/deploy.test.ts | 241 ++
template/.gitea/peppa-deploy.sh | 116 +
template/.gitea/workflows/deploy.yml | 35 +
template/RULES.md | 18 +
template/deploy/Dockerfile.node | 16 +
template/deploy/Dockerfile.python | 10 +
template/deploy/compose.yml | 21 +
28 files changed, 3079 insertions(+), 15 deletions(-)
create mode 100644 packages/db/migrations/0013_pep57_releases.sql
create mode 100644 packages/db/migrations/meta/0013_snapshot.json
create mode 100644 packages/runner/src/deploy.ts
create mode 100755 packages/testkit/bin/mock-docker
create mode 100644 packages/testkit/test/deploy.test.ts
create mode 100644 template/.gitea/peppa-deploy.sh
create mode 100644 template/.gitea/workflows/deploy.yml
create mode 100644 template/deploy/Dockerfile.node
create mode 100644 template/deploy/Dockerfile.python
create mode 100644 template/deploy/compose.yml
diff --git a/AGENTS.md b/AGENTS.md
index b0a35ab1..a23dcfda 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -31,6 +31,7 @@
- **CI проектов (PEP-57)**: Gitea Actions + `act_runner` в docker (`infra/act-runner`, контейнер `peppa-act-runner`, метка `peppa-trusted`, docker.sock хоста). Раннер регистрируется только на репо проектов: один раз на репо peppa-bot (`scripts/ci-runner-register.sh`), на репо чужого пространства — `setupCi` (runner/ci.ts) при создании проекта или `peppa ci connect ` (ещё PR с workflow из шаблона). Контракт: `.gitea/workflows/ci.yml` + `.gitea/peppa-check.sh` из шаблона, команды — `checks` в `.peppa/project.json`; шаг пишет статус `peppa/<проверка>` и шлёт отчёт в Пеппу, подписанный `PEPPA_CI_SECRET` (секрет Actions = `projectHookSecret(project.id)`). Логи job через API Gitea 1.22 недоступны — хвост лога присылает сам шаг. В тестах регистрация — `mock-ci-register` (`PEPPA_CI_REGISTER_BIN`)
- Обратная связь: `POST /api/hooks/gitea` (веб, без входа, подпись `X-Gitea-Signature` секретом проекта) → `handleGiteaHook` (runner/ci-feedback.ts): `X-Peppa-Event: check` — отчёт шага CI → `check_runs` → красное уходит в живой раннер (шаг + хвост лога) или задача возвращается в работу с новым раннером; счётчик `tasks.ci_attempts` по разным SHA, на 3-м — вопрос PM; остальные события Gitea (pull_request, push) — в обработчики `onGiteaEvent`. Запасной путь — `pollChecks` в вачдоге раз в минуту (статусы `peppa/*` PR задач в работе/ревью)
- Гейты (`prGate` в core/ci.ts): в ревью (`moveTask`, MCP `update_task`) и «Принять» (`acceptTask` → `mergeTaskPr`, мержит PR) — только зелёные проверки головного SHA PR и без конфликтов; без PR или без `checks` гейт открыт. `autoMergeTask` (для авто-режима PEP-23/25) не мержит PR, меняющий `.gitea/` или `checks`/`deploy`, и задаёт PM вопрос. Карточка задачи и MCP `get_task` показывают `taskCiSummary` («Проверки: 4 из 4 пройдены»)
+- **CD проектов (PEP-57)**: шаблон — `.gitea/workflows/deploy.yml` + `.gitea/peppa-deploy.sh` + `deploy/compose.yml` (метки Traefik, сеть `traefik_default`) + `deploy/Dockerfile.*`; настройки — `deploy` в `.peppa/project.json`. Образ `peppa/:` на docker хоста, `docker compose -p -`, хосты `-pr` / `-staging` / `-prod` `.telecom.quest` (один уровень: сертификат Cloudflare). Health до 2 мин изнутри сети Traefik, провал → откат на образ, работавший до этого. Шаг шлёт `X-Peppa-Event: deploy` → `recordRelease` (runner/deploy.ts, таблица `releases`, задачи — из сообщений коммитов). Staging здоров → PM вопрос с кнопкой «🚀 Выкатить в прод»; откат/провал → сообщение с причиной и логом. Прод: `deployProd` (веб «Релизы» на странице проекта, Telegram-кнопка через `answerAndDeliver` → `onReleaseAnswer`, MCP `deploy`, CLI `peppa deploy prod`) ставит тег `deploy-prod-<время>` на здоровый staging-коммит (в Gitea 1.22 нет API workflow_dispatch). В тестах docker — `mock-docker` первым в PATH
- `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта
- Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем
- `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate)
diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts
index d1a7fc8c..890c9fdd 100644
--- a/apps/bot/src/render.ts
+++ b/apps/bot/src/render.ts
@@ -22,7 +22,7 @@ export function renderQuestion(
q: Question,
ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string },
): Rendered {
- const head = [`${esc(ctx.taskKey ?? `Сессия ${q.sessionId ?? "?"}`)}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null]
+ const head = [`${esc(ctx.taskKey ?? (q.sessionId ? `Сессия ${q.sessionId}` : "Релизы проекта"))}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null]
.filter(Boolean)
.join(" · ");
const body = esc(clip(q.text, 3300));
diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts
index 66a05cca..2aca86d1 100644
--- a/apps/web/app/(app)/actions.ts
+++ b/apps/web/app/(app)/actions.ts
@@ -15,12 +15,13 @@ import {
getSetting,
unpairTelegram,
getIncident,
+ getProject as getProjectByKey,
updateIncidentSettings,
type IncidentPolicy,
} from "@peppa/core";
import { bugsinkFromEnv } from "@peppa/bugsink";
import { loadEnv } from "@peppa/shared";
-import { bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
+import { deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, grantRepoAccess, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";
@@ -140,6 +141,14 @@ export async function createProjectAction(f: FormData) {
});
}
+export async function deployProdAction(f: FormData) {
+ const user = await requireUser();
+ await attempt(f, async () => {
+ const p = await projectForUser(db, user.id, (await getProjectByKey(db, str(f, "projectKey"))).id);
+ await deployProd(db, p, user.login);
+ });
+}
+
export async function moveTaskCard(f: FormData) {
const user = await requireUser();
await attempt(f, async () => {
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index 431fdee9..21c302e8 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -10,7 +10,8 @@ const TOOLS: Array<[string, string]> = [
["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"],
["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"],
["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"],
- ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"],
+ ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept — мержит PR, только при зелёных проверках)"],
+ ["list_releases / deploy", "что выкачено на staging и в прод, история релизов; выкатить здоровый staging в прод"],
["list_incidents / get_incident", "ошибки из прода (Bugsink): статус, место, релиз, частота, стек"],
["decide_incident / resolve_incident", "решить по ошибке: в бэклог, в работу, игнорировать; отметить исправленной"],
["get_incident_policy / set_incident_policy", "политика инцидентов проекта: notify, backlog (по умолчанию), start, ask, triage + мини-промпт триажёра"],
@@ -29,6 +30,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [
{ title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" },
{ title: "Ошибки из прода", say: "Какие ошибки ждут решения в PAY? · Ошибку #7 — в работу", how: "list_incidents → decide_incident. Подключение — на странице проекта «Подключить отслеживание ошибок»" },
{ title: "Политика инцидентов", say: "В PAY пусть ошибки разбирает триажёр: падения оплаты — сразу в работу, косметику — в бэклог, остальное спроси", how: "set_incident_policy policy=triage, triage_prompt — ваши слова. Не уверен — спросит кнопками в Telegram" },
+ { title: "Выкатить в прод", say: "Что сейчас на staging в PAY? · Выкати PAY в прод", how: "list_releases → deploy. Тот же образ, что прошёл staging; не поднялся — Пеппа сама откатит и напишет" },
{ title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" },
];
@@ -82,6 +84,26 @@ export default async function Help() {
+
CI/CD
+
+ Каждый PR агента проверяет Gitea Actions: install, lint,{" "}
+ typecheck, test, build. Команды —
+ в .peppa/project.json → checks (заполняет агент на первой задаче), workflow приходит из
+ шаблона; в старый проект — командой peppa ci connect KEY (PR от Пеппы). Результат виден в
+ карточке задачи («Проверки: 4 из 4 пройдены»). Красная проверка уходит агенту с хвостом лога, после 3 красных
+ прогонов подряд Пеппа спросит вас. В ревью задача попадает и «Принять» мержит PR только с зелёными проверками и без
+ конфликтов. PR, меняющий конвейер (.gitea/, checks,{" "}
+ deploy), сам не мержится никогда.
+
+
+ Деплой — deploy в project.json и Dockerfile (заготовки в{" "}
+ deploy/): PR получает preview slug-prN.telecom.quest (удаляется при
+ закрытии), мерж выкатывает staging slug-staging.telecom.quest, прод{" "}
+ slug-prod.telecom.quest — по кнопке «Выкатить в прод» (страница проекта, Telegram, MCP{" "}
+ deploy). После каждого деплоя — проверка /healthz до 2 минут; не
+ прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта.
+
+
Telegram
Привяжите свой Telegram в Настройках: бот присылает вопросы агентов из ваших и общих проектов и «готово к ревью» с
diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx
index c05afd36..154de0aa 100644
--- a/apps/web/app/(app)/p/[key]/page.tsx
+++ b/apps/web/app/(app)/p/[key]/page.tsx
@@ -2,14 +2,22 @@ import { notFound } from "next/navigation";
import { AutoRefresh } from "@/components/AutoRefresh";
import { Flash, Notice, SessionCard } from "@/components/ui";
import { Board, type Card } from "@/components/Board";
-import { columnOf, describeRepo } from "@peppa/runner";
+import { columnOf, currentReleases, describeRepo, listReleases, type Release } from "@peppa/runner";
import { requireUser } from "@/lib/auth";
import { board, projectForUserByKey, projectSessions } from "@/lib/queries";
import { getIncidentSettings, listErrorSources, listIncidents, listMembers, repoAudience, repoVisibilityLabel } from "@peppa/core";
import { bugsinkWebhookBase } from "@peppa/runner";
import { IncidentsSection } from "@/components/Incidents";
import { db } from "@/lib/db";
-import { addGoal, addProjectMember, addTask, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
+import { addGoal, addProjectMember, addTask, deployProdAction, grantRepoAccessToMembers, removeProjectMember } from "../../actions";
+
+const RELEASE_STATUS: Record = {
+ deploying: "⏳ выкатывается",
+ healthy: "✅ работает",
+ rolled_back: "↩️ откат",
+ failed: "❌ не поднялся",
+ removed: "🗑 удалён",
+};
export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string; created?: string }> }) {
const user = await requireUser();
@@ -17,7 +25,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
const { error, created } = await searchParams;
const p = await projectForUserByKey(user.id, key).catch(() => null);
if (!p) notFound();
- const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents] = await Promise.all([
+ const [{ goals, tasks }, sessions, team, repo, incidentSettings, sources, incidents, releases, current] = await Promise.all([
board(p.id),
projectSessions(p.id),
listMembers(db, p),
@@ -25,6 +33,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
getIncidentSettings(db, p.id),
listErrorSources(db, p.id),
listIncidents(db, p.id),
+ listReleases(db, p.id, 15),
+ currentReleases(db, p.id),
]);
const collaborators = new Set((repo.collaborators ?? []).map((l) => l.toLowerCase()));
// Members who are not repo collaborators (only known when Gitea listed them; owners of the namespace see it anyway).
@@ -88,6 +98,38 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr