- {t("Версия для проверки готова")}
-
- {t("Пока её видите только вы:")} {host(check.url)} · {t("обновлена {when}.", { when: ago(check.at, t) })} {t("Посмотрите — и, если всё хорошо,")} {showAll}
-
-
+
+ {t("Готовим ссылку на продукт")}
+
- {engineer
- ? t("Этот проект пока не открывается по ссылке как сайт. Что получилось — на странице каждой готовой {task}, вкладка «Результат», и во вкладке «Код». Хотите открывать продукт по ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».", { task: task("gen") })
- : t("Этот проект пока не открывается по ссылке как сайт. Что получилось — на странице каждой готовой {task}, вкладка «Результат». Хотите открывать продукт по ссылке — попросите аналитика в чате: «сделай, чтобы продукт открывался по ссылке».", { task: task("gen") })}
+ {product.fix ? (
+ <>
+ {product.fix.working ? t("Агент уже этим занят:") : t("Это первая в очереди — агент возьмёт её сам:")} {t("{task} {key}", { task: task("nom"), key: product.fix.key })}. {t("Ссылка появится здесь, делать ничего не нужно.")}
+ >
+ ) : product.preparing ? (
+ t("Продукт запускается — ссылка появится здесь через несколько минут.")
+ ) : (
+ t("Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.", { task: task("gen") })
+ )}
{t("Откроется продукт проекта — в нём уже есть эта задача.")}
+
+ )}
{preview.previewUrl && (
diff --git a/packages/core/src/help-texts.ts b/packages/core/src/help-texts.ts
index e2c7374f..40c18d20 100644
--- a/packages/core/src/help-texts.ts
+++ b/packages/core/src/help-texts.ts
@@ -16,6 +16,8 @@ export interface ProductHelpText {
question: string;
/** PEP-143: what to do when Peppa itself misbehaves. */
problem: string;
+ /** PEP-145: where the product is. */
+ product: string;
more: string;
moreLink: string;
}
@@ -59,6 +61,7 @@ export const PRODUCT_HELP: Record = {
],
question: "Агент задал вопрос? Он появится на Главной и в Telegram. Ответьте кнопкой или своими словами — агент продолжит работу.",
problem: "Что-то не работает в самой Peppa FACTORY? Нажмите «Сообщить о проблеме» внизу любой страницы: напишите, что случилось, и приложите скриншот. В Telegram то же самое — отправьте боту /problem. Что стало с обращением, видно в разделе «Обращения».",
+ product: "Где посмотреть продукт? На странице проекта и на Главной есть кнопка «Открыть продукт». Ссылка появляется сама, в первый же день проекта; если её пока нет, на её месте написано, что происходит, — делать ничего не нужно.",
more: "Хотите видеть всё, что делают агенты, и полный справочник? Включите вид «Инженер».",
moreLink: "Открыть Настройки",
},
@@ -97,6 +100,7 @@ export const PRODUCT_HELP: Record = {
],
question: "Агент сұрақ қойды ма? Ол Басты бетте және Telegram-да пайда болады. Батырмамен немесе өз сөзіңізбен жауап беріңіз — агент жұмысын жалғастырады.",
problem: "Peppa FACTORY-дің өзінде бірдеңе жұмыс істемей тұр ма? Кез келген беттің төменгі жағындағы «Мәселе туралы хабарлау» батырмасын басыңыз: не болғанын жазып, скриншот тіркеңіз. Telegram-да да солай — ботқа /problem жіберіңіз. Өтінішіңіздің не болғаны «Өтініштер» бөлімінде көрінеді.",
+ product: "Өнімді қайдан көруге болады? Жоба бетінде және Басты бетте «Өнімді ашу» батырмасы бар. Сілтеме жобаның бірінші күнінде-ақ өзі пайда болады; әзірге жоқ болса, оның орнында не болып жатқаны жазылған — ештеңе істеудің қажеті жоқ.",
more: "Агенттердің барлық іс-әрекетін және толық анықтамалықты көргіңіз келе ме? «Инженер» көрінісін қосыңыз.",
moreLink: "Баптауларды ашу",
},
@@ -135,6 +139,7 @@ export const PRODUCT_HELP: Record = {
],
question: "Did an agent ask a question? It appears on Home and in Telegram. Answer with a button or in your own words — the agent carries on.",
problem: "Is something not working in Peppa FACTORY itself? Press “Report a problem” at the bottom of any page: write what happened and attach a screenshot. In Telegram it is the same — send /problem to the bot. What became of your report is shown in “Reports”.",
+ product: "Where is the product? The project page and Home have an «Open product» button. The link appears by itself on the project's first day; if it is not there yet, the same place says what is happening — you don't need to do anything.",
more: "Want to see everything the agents do and the full reference? Turn on the “Engineer” view.",
moreLink: "Open Settings",
},
diff --git a/packages/core/src/product.ts b/packages/core/src/product.ts
index 6242d354..f2ee6573 100644
--- a/packages/core/src/product.ts
+++ b/packages/core/src/product.ts
@@ -71,7 +71,7 @@ export async function projectProduct(db: Db, projectId: number): Promise {
const product = (await productUrls(db, [projectId])).get(projectId);
- return product ? `\n${tr("Посмотреть: {url} — продукт обновится через несколько минут", { url: product.url })}` : "";
+ return product ? `\n${tr("Продукт обновится через несколько минут: {url}", { url: product.url })}` : "";
}
/** Product links of several projects at once (the Home page): projectId → URL of the best version. */
diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts
index bb1d263b..edb59da9 100644
--- a/packages/shared/src/i18n/en/project.ts
+++ b/packages/shared/src/i18n/en/project.ts
@@ -392,4 +392,32 @@ export const project: Dict = {
"Стори без эпика": "Stories without an epic",
"Переименовать эпик, изменить описание или убрать в архив — «⋯ Настройки проекта → Эпики». Эпик стори меняется кнопкой «Изменить» на её странице.":
"Rename an epic, change its description or archive it in «⋯ Project settings → Epics». A story's epic is changed with the «Edit» button on its page.",
+ // PEP-145: the product always opens by a link
+ "Показывать всем": "Show to everyone",
+ "Ваш продукт готов — пока его видите только вы": "Your product is ready — only you can see it for now",
+ "Адрес:": "Address:",
+ "Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.": "Once the tasks of this version are accepted, Peppa FACTORY will show it to everyone by itself.",
+ "Готовим ссылку на продукт": "Preparing the link to your product",
+ "Агент уже этим занят:": "An agent is already on it:",
+ "Это первая в очереди — агент возьмёт её сам:": "It is first in line — an agent will take it by itself:",
+ "Ссылка появится здесь, делать ничего не нужно.": "The link will appear here; you don't need to do anything.",
+ "Продукт запускается — ссылка появится здесь через несколько минут.": "The product is starting — the link will appear here in a few minutes.",
+ "Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.": "The link will appear here by itself — you don't need to do anything. What is already done is on the page of each finished {task}.",
+ "Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.": "The latest update did not start — the link opens the previous version. We are fixing it.",
+ "Peppa FACTORY покажет её всем сама, когда задачи будут приняты.": "Peppa FACTORY will show it to everyone by itself once the tasks are accepted.",
+ "Версия для проверки — пока её видите только вы": "A version to check — only you can see it for now",
+ "Посмотреть результат": "See the result",
+ "Откроется продукт проекта — в нём уже есть эта задача.": "The project's product will open — this task is already in it.",
+ "Сам": "Automatically",
+ "По кнопке": "By the button",
+ "Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям.": "When all tasks of a new version are accepted, Peppa FACTORY shows it to all users by itself.",
+ "Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем».": "Only you see a new version at first; it opens to everyone with the «Show to everyone» button.",
+ "Показывать сразу": "Show right away",
+ "Оставить по кнопке": "Keep the button",
+ "Показывать всем: выберите «Сам» или «По кнопке».": "Show to everyone: choose «Automatically» or «By the button».",
+ "Продукт обновится через несколько минут: {url}": "The product will update in a few minutes: {url}",
+ "(неактуально: Peppa FACTORY сама показывает эту версию всем)": "(no longer relevant: Peppa FACTORY is showing this version to everyone by itself)",
+ "💡 {project}: показывать новые версии продукта всем пользователям сразу?": "💡 {project}: show new versions of the product to all users right away?",
+ "Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех.": "Right now only you see a new version at first, and it opens to everyone with the «Show to everyone» button. It can work differently: as soon as the tasks are accepted, Peppa FACTORY updates the product for everyone by itself.",
+ "Изменить выбор можно в настройках проекта.": "You can change this in the project settings.",
};
diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts
index f5caee0d..8621d1de 100644
--- a/packages/shared/src/i18n/kk/project.ts
+++ b/packages/shared/src/i18n/kk/project.ts
@@ -337,4 +337,32 @@ export const project: Dict = {
"На доске": "Тақтада",
"Стори без эпика": "Эпиксіз сторилер",
"Переименовать эпик, изменить описание или убрать в архив — «⋯ Настройки проекта → Эпики». Эпик стори меняется кнопкой «Изменить» на её странице.": "Эпиктің атын, сипаттамасын өзгерту немесе архивке жіберу — «⋯ Жоба баптаулары → Эпиктер». Сторидің эпигі оның бетіндегі «Өзгерту» батырмасымен өзгертіледі.",
+ // PEP-145: the product always opens by a link
+ "Показывать всем": "Барлығына көрсету",
+ "Ваш продукт готов — пока его видите только вы": "Өніміңіз дайын — әзірге оны тек сіз көресіз",
+ "Адрес:": "Мекенжайы:",
+ "Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.": "Осы нұсқаның тапсырмалары қабылданғанда, Peppa FACTORY оны барлығына өзі көрсетеді.",
+ "Готовим ссылку на продукт": "Өнімге сілтеме дайындалып жатыр",
+ "Агент уже этим занят:": "Агент осымен айналысып жатыр:",
+ "Это первая в очереди — агент возьмёт её сам:": "Ол кезекте бірінші — агент оны өзі алады:",
+ "Ссылка появится здесь, делать ничего не нужно.": "Сілтеме осы жерде пайда болады, ештеңе істеудің қажеті жоқ.",
+ "Продукт запускается — ссылка появится здесь через несколько минут.": "Өнім іске қосылып жатыр — сілтеме осы жерде бірнеше минуттан кейін пайда болады.",
+ "Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.": "Сілтеме осы жерде өзі пайда болады — ештеңе істеудің қажеті жоқ. Дайын нәтиже — әр дайын {task} бетінде.",
+ "Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.": "Соңғы жаңарту іске қосылмады — сілтеме бойынша алдыңғы нұсқа ашылады. Жөндеп жатырмыз.",
+ "Peppa FACTORY покажет её всем сама, когда задачи будут приняты.": "Тапсырмалар қабылданғанда, Peppa FACTORY оны барлығына өзі көрсетеді.",
+ "Версия для проверки — пока её видите только вы": "Тексеруге арналған нұсқа — әзірге оны тек сіз көресіз",
+ "Посмотреть результат": "Нәтижені қарау",
+ "Откроется продукт проекта — в нём уже есть эта задача.": "Жобаның өнімі ашылады — бұл тапсырма онда бар.",
+ "Сам": "Өзі",
+ "По кнопке": "Батырмамен",
+ "Когда все задачи новой версии приняты, Peppa FACTORY сама показывает её всем пользователям.": "Жаңа нұсқаның барлық тапсырмалары қабылданғанда, Peppa FACTORY оны барлық пайдаланушыларға өзі көрсетеді.",
+ "Новую версию сначала видите только вы; всем она открывается по кнопке «Показать всем».": "Жаңа нұсқаны алдымен тек сіз көресіз; барлығына ол «Барлығына көрсету» батырмасымен ашылады.",
+ "Показывать сразу": "Бірден көрсету",
+ "Оставить по кнопке": "Батырмамен қалдыру",
+ "Показывать всем: выберите «Сам» или «По кнопке».": "Барлығына көрсету: «Өзі» немесе «Батырмамен» дегенді таңдаңыз.",
+ "Продукт обновится через несколько минут: {url}": "Өнім бірнеше минутта жаңарады: {url}",
+ "(неактуально: Peppa FACTORY сама показывает эту версию всем)": "(өзекті емес: Peppa FACTORY бұл нұсқаны барлығына өзі көрсетіп жатыр)",
+ "💡 {project}: показывать новые версии продукта всем пользователям сразу?": "💡 {project}: өнімнің жаңа нұсқаларын барлық пайдаланушыларға бірден көрсету керек пе?",
+ "Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех.": "Қазір жаңа нұсқаны алдымен тек сіз көресіз, ал барлығына ол «Барлығына көрсету» батырмасымен ашылады. Басқаша да болады: тапсырмалар қабылданған бойда Peppa FACTORY өнімді барлығы үшін өзі жаңартады.",
+ "Изменить выбор можно в настройках проекта.": "Таңдауды жоба баптауларында өзгертуге болады.",
};
diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts
index ca57c2c0..e500b1d5 100644
--- a/packages/testkit/test/helpers.ts
+++ b/packages/testkit/test/helpers.ts
@@ -28,6 +28,9 @@ Object.assign(process.env, {
// Unreachable on purpose: rules come from the cache/local template fallback.
GITEA_URL: "http://127.0.0.1:9",
GITEA_TOKEN: "",
+ // PEP-145: the watchdog files «Продукт должен открываться по ссылке» for any project with
+ // accepted stories and no deploy — every suite's projects. product-link.test.ts turns it on.
+ PEPPA_PRODUCT_LINK: "off",
});
mkdirSync(process.env.PEPPA_HOME!, { recursive: true });
diff --git a/packages/testkit/test/product-help.test.ts b/packages/testkit/test/product-help.test.ts
index 90e2c086..d5f121c4 100644
--- a/packages/testkit/test/product-help.test.ts
+++ b/packages/testkit/test/product-help.test.ts
@@ -4,7 +4,7 @@ import { readFileSync } from "node:fs";
import { describe, test } from "node:test";
import { HELP_LANGS, PRODUCT_HELP, type ProductHelpText } from "@peppa/core";
-const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
+const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
/** «Нельзя» column of docs/glossary.md. */
function forbidden(): string[] {
diff --git a/packages/testkit/test/product-link.test.ts b/packages/testkit/test/product-link.test.ts
new file mode 100644
index 00000000..a28bc036
--- /dev/null
+++ b/packages/testkit/test/product-link.test.ts
@@ -0,0 +1,241 @@
+// PEP-145, spec product-link: the product of a project always opens by a link — the system
+// story when there is no link, «Показывать всем: сам / по кнопке», the card's honest status and
+// the link in the message about an accepted story. Provisioning scenarios — web.test.ts.
+import assert from "node:assert/strict";
+import { mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { questions, releases } from "@peppa/db";
+import { and, eq, isNull } from "drizzle-orm";
+import { core, db, runner, teardown } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+delete process.env.PEPPA_PRODUCT_LINK;
+const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-plink-")), "gitea"));
+const BOT = { id: 81, login: "peppa-bot", token: "mock-token-bot" };
+
+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();
+});
+
+let n = 0;
+async function proj() {
+ n++;
+ const slug = `mock-shop-${n}`;
+ const p = await core.createProject(db, { slug, key: `SH${String.fromCharCode(64 + n)}`, name: `Магазин ${n}`, giteaOwner: BOT.login, giteaRepo: slug, workspacePath: `/tmp/${slug}` });
+ gitea.addRepo(BOT.login, slug, { files: { "README.md": "# shop\n" } });
+ return p;
+}
+const story = async (projectId: number, title: string, status?: "done" | "review") => {
+ const ref = await core.createTask(db, { projectId, title });
+ if (status) await core.updateTask(db, ref, { status });
+ return ref;
+};
+const rel = (projectId: number, env: "preview" | "staging" | "prod", sha: string, status: "healthy" | "failed" | "rolled_back" | "deploying" = "healthy", extra: Partial = {}) =>
+ db.insert(releases).values({ projectId, env, sha, status, host: `shop-${env}.mock.test`, ...extra }).returning().then((r) => r[0]!);
+const linkTasks = async (projectId: number) => (await core.listTasks(db, { projectId })).filter((t) => t.title === core.PRODUCT_LINK_TITLE);
+const openQuestions = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt)));
+const HOUR = 3_600_000;
+
+describe("PEP-145: системная задача при отсутствии ссылки", () => {
+ test("Принятые задачи без выкладки", async () => {
+ const p = await proj();
+ await story(p.id, "Каталог", "done");
+ await story(p.id, "Корзина", "done");
+ const waiting = await story(p.id, "Оплата");
+ await runner.productLinkTick(db);
+ const backlog = await core.listTasks(db, { projectId: p.id, statuses: ["backlog"] });
+ assert.equal(backlog[0]!.title, "Продукт должен открываться по ссылке", "first in the backlog");
+ assert.match(backlog[0]!.description ?? "", /принято задач: 2/);
+ assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "the dispatcher takes it before the rest");
+ assert.ok(backlog.some((t) => t.id === waiting.task.id));
+ });
+
+ test("Упавшая выкладка", async () => {
+ const p = await proj();
+ await rel(p.id, "staging", "aaa1111", "failed", { reason: "сборка образа не удалась", logTail: "step 3/7: npm ERR! missing script: build" });
+ await runner.productLinkTick(db);
+ const [t] = await linkTasks(p.id);
+ assert.ok(t, "filed without any accepted story: the deploy itself failed");
+ assert.match(t.description ?? "", /сборка образа не удалась/);
+ assert.match(t.description ?? "", /missing script: build/, "the log of the failure is in the story");
+ });
+
+ test("Вторая задача не заводится", async () => {
+ const p = await proj();
+ await story(p.id, "Каталог", "done");
+ await runner.productLinkTick(db);
+ await runner.productLinkTick(db);
+ await runner.productLinkTick(db, { now: new Date(Date.now() + 30 * HOUR) });
+ assert.equal((await linkTasks(p.id)).length, 1, "one open story, however much time passes");
+ });
+
+ test("Не чаще раза в сутки", async () => {
+ const p = await proj();
+ await story(p.id, "Каталог", "done");
+ await runner.productLinkTick(db);
+ const [t] = await linkTasks(p.id);
+ await core.updateTask(db, await core.resolveTask(db, `${p.key}-${t!.number}`), { status: "done" });
+ await rel(p.id, "staging", "bbb2222", "rolled_back", { reason: "проверка /healthz не прошла за 120 с" });
+ await runner.productLinkTick(db, { now: new Date(Date.now() + 2 * HOUR) });
+ assert.equal((await linkTasks(p.id)).length, 1, "2 hours after the first: nothing new");
+ await runner.productLinkTick(db, { now: new Date(Date.now() + 25 * HOUR) });
+ assert.equal((await linkTasks(p.id)).length, 2, "a day later the product still has no healthy update");
+ });
+
+ test("Здоровая версия или идущее обновление: задача не нужна", async () => {
+ const healthy = await proj();
+ await story(healthy.id, "Каталог", "done");
+ await rel(healthy.id, "staging", "ccc3333");
+ const starting = await proj();
+ await story(starting.id, "Каталог", "done");
+ await rel(starting.id, "staging", "ddd4444", "deploying");
+ const empty = await proj();
+ await story(empty.id, "Каталог");
+ await runner.productLinkTick(db);
+ for (const p of [healthy, starting, empty]) assert.equal((await linkTasks(p.id)).length, 0, p.key);
+ });
+});
+
+/** The commit a version of the project runs: the head of its repository in mock-gitea. */
+const head = (p: { giteaOwner: string; giteaRepo: string }) => gitea.sha(p.giteaOwner, p.giteaRepo, "main");
+
+describe("PEP-145: показ всем без нажатий", () => {
+ const stagingHealthy = (p: Awaited>, sha: string, commits: string[]) =>
+ runner.recordRelease(db, p, { env: "staging", sha, status: "healthy", host: "shop-staging.mock.test", commits });
+
+ test("Режим «сам»", async () => {
+ const p = await proj();
+ await core.setPublishMode(db, p.id, "auto");
+ const t = await story(p.id, "Каталог", "done");
+ await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
+ const [prod] = await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
+ assert.equal(prod?.status, "deploying");
+ assert.equal(prod?.sha, head(p), "the same commit goes to everyone");
+ assert.equal(prod?.deployedBy, "Peppa FACTORY");
+ const tag = gitea.repo(p.giteaOwner, p.giteaRepo).tags.at(-1)!;
+ assert.match(tag.name, /^deploy-prod-/);
+ assert.ok(!(await openQuestions(p.id)).some((q) => /Показать её всем/.test(q.text)), "no question about it");
+ });
+
+ test("Режим «по кнопке»", async () => {
+ const p = await proj();
+ await core.setPublishMode(db, p.id, "button");
+ const t = await story(p.id, "Каталог", "done");
+ await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
+ await runner.productLinkTick(db);
+ assert.equal((await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")))).length, 0);
+ const [q] = await openQuestions(p.id);
+ assert.deepEqual(q?.options, [runner.PROD_OPTION]);
+ assert.equal(runner.PROD_OPTION, "🚀 Показать всем");
+ });
+
+ test("Не все задачи приняты", async () => {
+ const p = await proj();
+ await core.setPublishMode(db, p.id, "auto");
+ const t = await story(p.id, "Оплата", "review");
+ await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
+ await runner.productLinkTick(db);
+ const prods = () => db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
+ assert.equal((await prods()).length, 0, "the story is still in review");
+ await core.updateTask(db, t, { status: "done" });
+ await runner.productLinkTick(db);
+ assert.equal((await prods())[0]?.sha, head(p), "accepted later: the watchdog carries it through");
+ await runner.productLinkTick(db);
+ assert.equal((await prods()).length, 1, "once per version");
+ });
+
+ test("Существующему проекту — предложение один раз", async () => {
+ const p = await proj();
+ await rel(p.id, "staging", head(p));
+ await runner.productLinkTick(db);
+ await runner.productLinkTick(db);
+ const offers = (await openQuestions(p.id)).filter((q) => (q.options ?? []).includes(core.PUBLISH_AUTO_OPTION));
+ assert.equal(offers.length, 1);
+ assert.deepEqual(offers[0]!.options, ["Показывать сразу", "Оставить по кнопке"]);
+ assert.equal(await core.getPublishMode(db, p.id), "button", "nothing changes until the owner chooses");
+ await runner.answerAndDeliver(db, offers[0]!.id, "Показывать сразу", "web");
+ assert.equal(await core.getPublishChoice(db, p.id), "auto");
+ const [prod] = await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
+ assert.equal(prod?.sha, head(p), "the waiting version goes to everyone right away");
+ });
+
+ test("Проект без версии для проверки предложения не получает", async () => {
+ const p = await proj();
+ await runner.productLinkTick(db);
+ assert.equal((await openQuestions(p.id)).length, 0);
+ });
+});
+
+describe("PEP-145: карточка «Ваш продукт» с честным статусом", () => {
+ test("Ссылка есть", async () => {
+ const p = await proj();
+ await rel(p.id, "staging", "5555555eeee", "healthy", { tasks: [`${p.key}-1`] });
+ await rel(p.id, "preview", "5555555eeee", "healthy", { prNumber: 1, screenshots: [{ path: "/about", file: "r1-0.png" }, { path: "/", file: "r1-1.png" }] });
+ const v = await core.projectProduct(db, p.id);
+ assert.equal((v.live ?? v.check)?.url, "https://shop-staging.mock.test");
+ assert.equal(v.preparing, false);
+ assert.equal(v.broken, false);
+ assert.equal(v.shot?.n, 1, "the screenshot of the first page");
+ });
+
+ test("Ссылки нет", async () => {
+ const p = await proj();
+ await story(p.id, "Каталог", "done");
+ await runner.productLinkTick(db);
+ const v = await core.projectProduct(db, p.id);
+ assert.equal(v.live ?? v.check, null);
+ assert.equal(v.preparing, true);
+ assert.deepEqual(v.fix, { key: `${p.key}-2`, working: false });
+ const row = (await core.progressOverview(db, -1)).mine.concat((await core.progressOverview(db, -1)).others).find((r) => r.key === p.key);
+ assert.ok(!row || row.productFix === `${p.key}-2`);
+ });
+
+ test("Выкладка упала, прошлая версия работает", async () => {
+ const p = await proj();
+ await rel(p.id, "staging", "6666666ffff");
+ await rel(p.id, "staging", "7777777aaaa", "rolled_back", { reason: "проверка /healthz не прошла за 120 с" });
+ await runner.productLinkTick(db);
+ const v = await core.projectProduct(db, p.id);
+ assert.equal(v.check?.url, "https://shop-staging.mock.test", "the earlier version still opens");
+ assert.equal(v.broken, true);
+ assert.equal(v.fix?.key, `${p.key}-1`, "and the fix is on its way");
+ });
+
+ test("Новый проект: выкладка заглушки идёт — «Готовим ссылку»", async () => {
+ const p = await proj();
+ await rel(p.id, "staging", "8888888bbbb", "deploying");
+ const v = await core.projectProduct(db, p.id);
+ assert.equal(v.preparing, true);
+ assert.equal(v.fix, null);
+ });
+});
+
+describe("PEP-145: ссылка на продукт у принятой задачи", () => {
+ test("Сообщение о принятой задаче", async () => {
+ const p = await proj();
+ await rel(p.id, "prod", "9999999cccc", "healthy", { host: "shop-prod.mock.test" });
+ assert.match(await core.productLookLine(db, p.id), /https:\/\/shop-prod\.mock\.test/);
+ });
+
+ test("Ссылки нет", async () => {
+ const p = await proj();
+ assert.equal(await core.productLookLine(db, p.id), "");
+ });
+});
+
+describe("PEP-145: тексты", () => {
+ test("описание системной задачи — без слов из «Нельзя» в части для владельца", () => {
+ const text = core.productLinkDescription({ doneStories: 3 }).split("## Для агента")[0]!;
+ for (const word of ["деплой", "выкат", "релиз", "staging", "прод ", "репозитор"]) assert.ok(!text.toLowerCase().includes(word), word);
+ });
+});
diff --git a/packages/testkit/test/product.test.ts b/packages/testkit/test/product.test.ts
index 05195b0a..e898ba1d 100644
--- a/packages/testkit/test/product.test.ts
+++ b/packages/testkit/test/product.test.ts
@@ -17,7 +17,7 @@ describe("PEP-111: the project's product", () => {
test("nothing deployed: no versions, only the count of accepted stories", async () => {
const p = await proj();
const t = await core.createTask(db, { projectId: p.id, title: "Первая" });
- assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0 });
+ assert.deepEqual(await core.projectProduct(db, p.id), { live: null, check: null, doneStories: 0, fix: null, broken: false, preparing: false, shot: null });
await core.updateTask(db, t, { status: "done" });
assert.equal((await core.projectProduct(db, p.id)).doneStories, 1);
assert.equal((await core.productUrls(db, [p.id])).size, 0);
diff --git a/packages/testkit/test/web.test.ts b/packages/testkit/test/web.test.ts
index 6e9dc35e..1d657cd9 100644
--- a/packages/testkit/test/web.test.ts
+++ b/packages/testkit/test/web.test.ts
@@ -102,6 +102,21 @@ describe("project provisioning", () => {
assert.match(execFileSync("git", ["-C", p.workspacePath, "config", "--get-all", "credential.helper"], { encoding: "utf8" }), /git-credential-peppa/);
});
+ // PEP-145, spec product-link: «Новый проект получает заглушку и первую выкладку».
+ test("new repo: the product placeholder, deploy settings and the tag of the first deploy", async () => {
+ const p = await core.getProject(db, "MDEMO");
+ const files = gitea.files(ALICE.login, "mock-demo");
+ for (const f of ["Dockerfile", "product/server.mjs", "product/index.html", "deploy/compose.yml"]) assert.ok(files.includes(f), `${f} pushed`);
+ assert.match(gitea.show(ALICE.login, "mock-demo", "product/index.html"), /Продукт создаётся/);
+ const cfg = JSON.parse(gitea.show(ALICE.login, "mock-demo", ".peppa/project.json"));
+ assert.deepEqual(cfg.deploy, { compose: "deploy/compose.yml", service: "web", port: 3000, health: "/healthz" });
+ const tags = gitea.repo(ALICE.login, "mock-demo").tags;
+ assert.equal(tags.length, 1);
+ assert.match(tags[0]!.name, /^deploy-staging-\d+$/);
+ assert.equal(tags[0]!.target, execFileSync("git", ["-C", p.workspacePath, "rev-parse", "HEAD"], { encoding: "utf8" }).trim(), "the head of the default branch");
+ assert.equal(await core.getPublishChoice(db, p.id), "auto", "a new project shows accepted versions to everyone by itself");
+ });
+
test("PEP-142: the same form sent twice leads to the project just created, not to «slug is taken»", async () => {
const again = await runner.justCreatedProject(db, { slug: "Mock-Demo", key: "mdemo", ownerId: alice.id });
assert.equal(again?.key, "MDEMO", "the owner's second click finds the project made a moment ago");
@@ -147,6 +162,10 @@ describe("project provisioning", () => {
for (const f of ["src/app.ts", ".peppa/project.json", ".mcp.json", "openspec/config.yaml"]) assert.ok(files.includes(f), f);
assert.ok(files.some((f) => f.startsWith(".agents/skills/openspec-")), "openspec init ran");
assert.ok(readFileSync(join(p.workspacePath, "src/app.ts"), "utf8"));
+ // PEP-145, spec product-link: «Существующий репозиторий не получает заглушку».
+ assert.ok(!files.includes("Dockerfile") && !files.some((f) => f.startsWith("product/")), "no placeholder in a repository with its own code");
+ assert.equal(JSON.parse(gitea.show(ALICE.login, "mock-legacy", ".peppa/project.json")).deploy, undefined);
+ assert.deepEqual(gitea.repo(ALICE.login, "mock-legacy").tags, []);
});
test("existing repo without admin rights is refused", async () => {
--
2.45.2
From dc97e718aa8b973d7399553a0d4889578c96d0fc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 10:40:00 +0500
Subject: [PATCH 006/215] PEP-145: help, glossary and AGENTS.md
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/help/page.tsx | 4 ++++
docs/glossary.md | 2 ++
packages/shared/src/i18n/en/project.ts | 2 ++
packages/shared/src/i18n/kk/project.ts | 2 ++
5 files changed, 11 insertions(+)
diff --git a/AGENTS.md b/AGENTS.md
index fbb085b2..577e31f0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -54,6 +54,7 @@
- **Стори берутся сами (PEP-79)**: уровень автономности `self` «Сам берёт» (pick=auto, приёмка за PM); `provisionProject` ставит новому проекту `NEW_PROJECT_AUTONOMY`; диспетчер (`autonomyTick`) не запускает и не пингует, пока есть `projectAgentWarning`
- **Продакту — без технических вопросов (PEP-94)**: правила `template/RULES.md` — технику агент решает сам (`design.md`, `remember`), `ask_pm` — только продуктовое, простыми словами, рекомендация первой, ответа не ждёт; MCP `request_approval` отклоняется, если `proposal !== "pm"`; аналитик не спрашивает (вопросы → «Допущения» сразу); `NEW_PROJECT_AUTONOMY` = `auto`; в вебе Proposal → «План», вкладки стори по-русски (id прежние)
- **Выбор подписки с подтверждением (PEP-116)**: при заданном `platform.shared_pool` мастер `SubscriptionSetup` и панель «Подписки» предлагают «Свою» и «Подписку Peppa FACTORY». `chooseSharedSubscription` (runner/project-subscription.ts): суперадмин → `"switched"`; владелец → `"requested"` — вопрос с опциями `SHARED_APPROVE`/`SHARED_DENY` в платформенном проекте (`PEPPA_PLATFORM_KEY`; суперадмину на Главную и в Telegram), `settings` `shared.request:` + `shared.question:`; `onSharedAnswer` (обработчик `onAnswer`) переключает пул или отказывает и пишет владельцу `attention`. На подписке фабрики пользователь не видит учётки пула
+- **Продукт всегда по ссылке (PEP-145)**: новый проект (`provisionProject`, только пустой репозиторий) получает заглушку из шаблона (`Dockerfile` + `product/` — страница «Продукт создаётся», `/healthz`), `deploy` (`NEW_PROJECT_DEPLOY`) в `.peppa/project.json`, режим показа «сам» и после `setupCi` — тег `deploy-staging-*` на голове основной ветки (первая выкладка; событие `first_deploy_requested`); подключённому репозиторию заглушка не копируется. `productLinkTick` (runner/product-link.ts, тик вачдога перед `autonomyTick`; `PEPPA_PRODUCT_LINK=off`, в тестах выключен в `helpers.ts`; платформа пропускается): есть принятые стори и нет здоровой staging, либо последняя завершённая выкладка staging `failed`/`rolled_back`, и ничего не выкладывается сейчас → системная стори `PRODUCT_LINK_TITLE` «Продукт должен открываться по ссылке» (`productLinkDescription`: причина и хвост журнала; intake `done`; первая в бэклоге — `reorderTask top` и `readyBacklog` ставит её перед багами), состояние `settings` `product.link:` `{taskId, at}` — одна открытая на проект, новая не раньше `PEPPA_PRODUCT_LINK_HOURS` (24), событие `product_link_task`. **«Показывать всем: сам / по кнопке»** — `core/product-link.ts` (`settings` `product.publish:`; нет строки = «по кнопке»; `getPublishChoice`/`getPublishMode`/`setPublishMode`), `autoPublish` (runner/deploy.ts): режим `auto`, здоровая staging с другим коммитом, чем prod, все её стори (и пропущенных версий) `done`, prod не обновляется → `deployProd` от имени «Peppa FACTORY», отметка `product.published:` (повтор после сбоя через 10 мин), вопрос «Показать всем?» не шлётся/закрывается; зовут `recordRelease`, тик и выбор режима. Существующему проекту со staging — один вопрос с кнопками `PUBLISH_AUTO_OPTION`/`PUBLISH_BUTTON_OPTION` (`offerPublishMode`, `product.publish.offered:`, ответ — `onPublishAnswer`). Веб: «⋯ Настройки проекта → Показывать всем» (`PublishPanel`, `setPublishModeAction`). `projectProduct` отдаёт ещё `fix` (открытая системная стори), `broken` (последняя выкладка упала), `preparing`, `shot` (последний скриншот «/» превью проекта); `ProductCard` — одна кнопка «Открыть продукт» (prod, иначе staging), без ссылки — «Готовим ссылку на продукт» со ссылкой на стори, при `broken` — «чиним»; Главная (`ProgressOverview`: `product` / `productFix`); страница принятой задачи — «Посмотреть результат» (`productUrls`); сообщения об автозакрытии и отложенном «Принять» — `productLookLine`. Правило агентам — «Завершение» и «CD» в `template/RULES.md`. После мержа: `scripts/push-template.sh`. Тест `product-link.test.ts`, сценарии создания — `web.test.ts`
- **Продукт работает по-настоящему (PEP-112)**: список «чтобы заработало по-настоящему» — `core/product-needs.ts` (`settings` `product.needs:`; пункт с `secret` закрыт, пока такой секрет заведён, остальные — «Сделано» владельца; `declareNeeds` сливает по имени секрета/названию, пункты продакт-агента без секрета заменяются при каждой приёмке; `demoNote` — строка в «готово к ревью»). MCP агента `declare_needs` → сообщение в обсуждение проекта (`sayInDiscussion` в runner/analyst-chat.ts — общий для «Аналитика», «Продакта» и агентов), список виден в `get_task`. **Секреты → выкатка**: `peppa-deploy.sh` шаблона спрашивает `POST /api/hooks/gitea` `X-Peppa-Event: deploy-env` (подпись `PEPPA_CI_SECRET`, `ts` не старше 10 мин) → `projectSecretEnv(…, "deploy")` → compose-override JSON с `environment` сервиса (`$` → `$$`), значения не в логе; `ANTHROPIC_*`/`CLAUDE_*`/`OPENCODE_*` — только в продукт, не агентам (`productOnlySecret`); хвост лога релиза маскируется. Смена секрета → отметка `product.redeploy:` → `productRedeployTick` (вачдог, тишина `PEPPA_SECRETS_REDEPLOY_DELAY_SEC` 120, `PEPPA_SECRETS_REDEPLOY=off`) ставит теги `deploy-staging-*`/`deploy-prod-*` на коммиты здоровых версий; релиз с `previousSha === sha` — сообщение «перезапущен с новыми настройками» вместо «Показать всем?». Существующим проектам новые `peppa-deploy.sh`/`deploy.yml` приносит `peppa ci connect `. **Продакт-агент на приёмке**: `recordRelease` (здоровый staging/prod, не платформа) → `queueProductReview` (раз на коммит и окружение; после перезапуска из-за секретов — ещё раз) → `productReviewTick` в вачдоге (runner/product-review.ts; только при включённых ролях PEP-84, `claudePrint` на подписке проекта, `PEPPA_PRODUCT_REVIEW_MODEL`, `PEPPA_PRODUCT_REVIEW=off`): текст страниц (`pageText`/`pageLinks`, до 4 страниц; база запроса `PEPPA_PRODUCT_FETCH_BASE` для тестов), скриншоты превью стори релиза (файлы в cwd вызова, `--allowedTools Read`), описания стори, потребности → JSON `{summary, howto, not_real, needs, stories}` → сообщение «Продакта» в обсуждение, потребности (source product), до 3 стори в бэклог (intake `done`, дубль по названию не заводится), `product.review:` — «Как пользоваться» в карточке; 2 неудачи — молча в лог. Карточка `ProductCard`: «Работает в демо-режиме» с полем ключа (`saveProjectSecretAction`), «Сделано»/«убрать» (`setNeedDoneAction`/`removeNeedAction`). Мок — роль `accept` в `mock-intake`; тесты `product-acceptance.test.ts`, `deploy.test.ts`
- **Своя подписка (PEP-80)**: `connectOwnSubscription(db, user, project, kind, secret)` — `claude` (токен), `codex_login` (ChatGPT, device-вход; `ownPendingLogins` отдаёт ссылку и код панели «Подписки» проекта), `codex_key`, `existing`; личный пул «Подписки — <логин>»; общий пул на живой системе выключен (`peppa platform shared-pool -`)
- **Мастер подписки (PEP-82)**: `components/SubscriptionSetup.tsx` на странице проекта без подписки (владелец/суперадмин): «Подключить Claude» (`claude_login`: `claude setup-token` на сервере → ссылка → код → `finishOwnClaudeLogin`) / «Подключить ChatGPT» (`codex_login`); `cancelOwnLogin` удаляет ожидающую подписку; `ownPendingLogins` — входы Claude и Codex пула
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index c12d0429..e20b4de6 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -223,6 +223,10 @@ export default async function Help() {
{rich(t("Деплой — 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 минут; не прошла — откат на предыдущий образ и сообщение вам. Релизы — на странице проекта."))}
+ {/* glossary-ignore: справочник вида «Инженер» */}
+ {rich(t("Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (Dockerfile, product/, готовый deploy) и сразу выкладывается на slug-staging.telecom.quest. Нет здоровой версии для проверки при принятых стори или выкладка упала — Peppa FACTORY сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше."))}
+
+
{rich(t("Превью на ревью: «готово к ревью» и карточка стори (блок «Превью») показывают «Посмотреть» — стенд PR, ссылку на дифф и итог проверок. Шаг деплоя превью снимает скриншоты страниц из deploy.screenshots (по умолчанию главная, [] — выключить) — они в карточке стори."))}
diff --git a/docs/glossary.md b/docs/glossary.md
index bf2da70a..61bf1aef 100644
--- a/docs/glossary.md
+++ b/docs/glossary.md
@@ -29,6 +29,8 @@
| Версия до показа всем | версия для проверки | staging, стейджинг, preview, превью-стенд, стенд | Кнопка «Посмотреть» |
| Версия для всех | рабочая версия, ваш продукт | прод, production, продакшн | «Ваш продукт работает» |
| Показ всем | показать всем, обновить продукт | деплой, выкатка, выкатить, релиз, deploy | «Показать всем пользователям» |
+| Когда версию видят все | показывать всем: сам / по кнопке | автодеплой, автовыкатка, auto-deploy | Настройка проекта: принятая версия открывается всем сама или по кнопке «Показать всем» |
+| Ссылка на продукт | открыть продукт, готовим ссылку на продукт | урл, эндпоинт, endpoint | Кнопка «Открыть продукт»; пока ссылки нет — «Готовим ссылку на продукт» |
| Где лежит код | код проекта | репозиторий, репо, Gitea, git | Продакту адрес кода не нужен |
| На чём работают агенты | подписка | провайдер, токен, пул, OAuth, API-ключ | «Подписка Peppa FACTORY», «своя подписка» |
| Ход работы агента | что делает агент, шаг N из M | терминал, tmux, команда, лог, контекст, хук | Подробности — под «Подробнее» |
diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts
index edb59da9..705dc0d6 100644
--- a/packages/shared/src/i18n/en/project.ts
+++ b/packages/shared/src/i18n/en/project.ts
@@ -420,4 +420,6 @@ export const project: Dict = {
"💡 {project}: показывать новые версии продукта всем пользователям сразу?": "💡 {project}: show new versions of the product to all users right away?",
"Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех.": "Right now only you see a new version at first, and it opens to everyone with the «Show to everyone» button. It can work differently: as soon as the tasks are accepted, Peppa FACTORY updates the product for everyone by itself.",
"Изменить выбор можно в настройках проекта.": "You can change this in the project settings.",
+ "Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (Dockerfile, product/, готовый deploy) и сразу выкладывается на slug-staging.telecom.quest. Нет здоровой версии для проверки при принятых стори или выкладка упала — Peppa FACTORY сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше.":
+ "A product link from day one: a new project is created with the «Product is being built» placeholder (Dockerfile, product/, a ready deploy) and is deployed to slug-staging.telecom.quest right away. No healthy staging while stories are accepted, or a deploy failed — Peppa FACTORY files the story «Продукт должен открываться по ссылке» first in the backlog by itself (one open per project, at most once a day). «⋯ Project settings → Show to everyone»: «Automatically» — a healthy staging whose stories are all accepted goes to prod without the button; «By the button» — as before.",
};
diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts
index 8621d1de..61a2708d 100644
--- a/packages/shared/src/i18n/kk/project.ts
+++ b/packages/shared/src/i18n/kk/project.ts
@@ -365,4 +365,6 @@ export const project: Dict = {
"💡 {project}: показывать новые версии продукта всем пользователям сразу?": "💡 {project}: өнімнің жаңа нұсқаларын барлық пайдаланушыларға бірден көрсету керек пе?",
"Сейчас новую версию сначала видите только вы, а всем она открывается по кнопке «Показать всем». Можно иначе: как только задачи приняты, Peppa FACTORY сама обновляет продукт для всех.": "Қазір жаңа нұсқаны алдымен тек сіз көресіз, ал барлығына ол «Барлығына көрсету» батырмасымен ашылады. Басқаша да болады: тапсырмалар қабылданған бойда Peppa FACTORY өнімді барлығы үшін өзі жаңартады.",
"Изменить выбор можно в настройках проекта.": "Таңдауды жоба баптауларында өзгертуге болады.",
+ "Продукт по ссылке с первого дня: новый проект создаётся с заглушкой «Продукт создаётся» (Dockerfile, product/, готовый deploy) и сразу выкладывается на slug-staging.telecom.quest. Нет здоровой версии для проверки при принятых стори или выкладка упала — Peppa FACTORY сама заводит стори «Продукт должен открываться по ссылке» первой в бэклоге (одна открытая на проект, не чаще раза в сутки). «⋯ Настройки проекта → Показывать всем»: «Сам» — здоровый staging, все стори которого приняты, выкатывается в прод без кнопки; «По кнопке» — как раньше.":
+ "Өнім бірінші күннен сілтеме бойынша ашылады: жаңа жоба «Өнім жасалып жатыр» бітеуішімен (Dockerfile, product/, дайын deploy) құрылады және бірден slug-staging.telecom.quest мекенжайына шығарылады. Сторилер қабылданған, бірақ сау staging жоқ немесе шығару құлады — Peppa FACTORY «Продукт должен открываться по ссылке» сторисін бэклогтың басына өзі қосады (жобаға бір ашық стори, тәулігіне бір реттен жиі емес). «⋯ Жоба баптаулары → Барлығына көрсету»: «Өзі» — барлық сторилері қабылданған сау staging батырмасыз prod-қа шығады; «Батырмамен» — бұрынғыдай.",
};
--
2.45.2
From 56c9c4ff67cc30f352ffb78229d10518fcdb4d68 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 10:40:08 +0500
Subject: [PATCH 007/215] PEP-145: glossary row for the product link
Co-Authored-By: Claude Fable 5.2
---
docs/glossary.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/docs/glossary.md b/docs/glossary.md
index 61bf1aef..fa1c5158 100644
--- a/docs/glossary.md
+++ b/docs/glossary.md
@@ -30,7 +30,7 @@
| Версия для всех | рабочая версия, ваш продукт | прод, production, продакшн | «Ваш продукт работает» |
| Показ всем | показать всем, обновить продукт | деплой, выкатка, выкатить, релиз, deploy | «Показать всем пользователям» |
| Когда версию видят все | показывать всем: сам / по кнопке | автодеплой, автовыкатка, auto-deploy | Настройка проекта: принятая версия открывается всем сама или по кнопке «Показать всем» |
-| Ссылка на продукт | открыть продукт, готовим ссылку на продукт | урл, эндпоинт, endpoint | Кнопка «Открыть продукт»; пока ссылки нет — «Готовим ссылку на продукт» |
+| Ссылка на продукт | открыть продукт, готовим ссылку на продукт | урл, URL продукта | Кнопка «Открыть продукт»; пока ссылки нет — «Готовим ссылку на продукт» |
| Где лежит код | код проекта | репозиторий, репо, Gitea, git | Продакту адрес кода не нужен |
| На чём работают агенты | подписка | провайдер, токен, пул, OAuth, API-ключ | «Подписка Peppa FACTORY», «своя подписка» |
| Ход работы агента | что делает агент, шаг N из M | терминал, tmux, команда, лог, контекст, хук | Подробности — под «Подробнее» |
--
2.45.2
From ef06c112f85ed51d2e7560cf537659057ec596df Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 10:46:33 +0500
Subject: [PATCH 008/215] PEP-145: the card on a phone, plainer wording,
product-mode texts listed in the i18n test, project memory
Co-Authored-By: Claude Fable 5.2
---
.peppa/memory.md | 2 ++
apps/web/components/ProductCard.tsx | 14 +++++------
.../pep-145-product-link-always/tasks.md | 24 +++++++++----------
packages/shared/src/i18n/en/project.ts | 2 +-
packages/shared/src/i18n/kk/project.ts | 2 +-
.../testkit/test/i18n-product-mode.test.ts | 13 +++++++++-
6 files changed, 35 insertions(+), 22 deletions(-)
diff --git a/.peppa/memory.md b/.peppa/memory.md
index f0980a93..aedf6b99 100644
--- a/.peppa/memory.md
+++ b/.peppa/memory.md
@@ -17,6 +17,7 @@
- Безопасность (PEP-133): git-прокси релея агента (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\` — fetch сворачивает %2e%2e как dot-сегмент; защитные заголовки — headers() в next.config.ts, строгий script-CSP не включён (Next inline-скрипты).
- Проверка экранов на `next dev`: открывай `http://localhost:<порт>`, не 127.0.0.1 — иначе dev-скрипты блокируются (allowedDevOrigins), страница без гидрации, кнопки молчат; `PEPPA_WEB_URL` для login-link тот же, ссылка одноразовая. Без playwright-core: `chrome-headless-shell` из `~/Library/Caches/ms-playwright` с `--remote-debugging-port` + CDP через глобальный WebSocket Node.
- Живой сайт — `next dev`: всё, что вкладка заставляет сервер писать под `.next`, запускает обновление страниц по кругу; в next.config.ts выключены `logging.browserToTerminal` и `experimental.mcpServer` (PEP-144, тест dev-server-config.test.ts). Тест testkit не импортирует файлы apps/web статически — типы Next ломают ProcessEnv всего пакета; грузить через `import(new URL(…).href)`.
+- mock-gitea `POST /tags` ставит настоящий git-тег: репозиторию нужны коммиты (`addRepo(…, { files })`), а target — существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Новое слово в «Нельзя» docs/glossary.md проверяй `pnpm lint` сразу: оно может уже стоять в чужих текстах («хост», «эндпоинт»).
## Решения
- Продукт по-настоящему (PEP-112): секреты проекта доходят до выкатки сами (хук `deploy-env` → override в `peppa-deploy.sh`); `ANTHROPIC_*/CLAUDE_*/OPENCODE_*` — только продукту; нужное от владельца — `product.needs:` (MCP `declare_needs`); приёмка — `productReviewTick`. После правок `template/` — `scripts/push-template.sh` и `peppa ci connect ` старым проектам.
@@ -42,3 +43,4 @@
- Долгая форма (PEP-142): кнопка — ``; создание проекта из веба — `provisionProjectOnce` (одновременные отправки делят один промис, повтор владельца за 2 мин — `justCreatedProject`), CLI/MCP — `provisionProject`.
- Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй или `glossary-ignore`; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ).
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`. Состояние — settings `question.state:`, `chat.repeat:`. В тесте нужен второй вопрос — меняй статус, коммит в check_runs или текст.
+- Продукт по ссылке (PEP-145): ссылка и её статус — только через `projectProduct` (`fix`/`broken`/`preparing`) и `productUrls`/`productLookLine`; системную стори заводит `productLinkTick` (в тестах выключен в helpers.ts, свой тест делает `delete process.env.PEPPA_PRODUCT_LINK`); «Показывать всем» — `getPublishMode`/`autoPublish` (вернул true — вопрос с кнопкой не слать). Менял `template/` — после мержа `scripts/push-template.sh`.
diff --git a/apps/web/components/ProductCard.tsx b/apps/web/components/ProductCard.tsx
index fb1f97a1..ff0597f4 100644
--- a/apps/web/components/ProductCard.tsx
+++ b/apps/web/components/ProductCard.tsx
@@ -70,10 +70,10 @@ export async function ProductCard({
{link ? (
-
+
{live ? t("Ваш продукт работает") : t("Ваш продукт готов — пока его видите только вы")}
- {live ? t("Открыт для всех по адресу") : t("Адрес:")} {host(link.url)} · {t("обновлён {when}", { when: ago(link.at, t) })}
+ {live ? t("Открыт для всех по адресу") : t("Адрес:")} {host(link.url)} · {t("обновлён {when}", { when: ago(link.at, t) })}
{link.stories.length > 0 && <> · {t("вошли {tasks} {keys}", { tasks: task("pl"), keys: link.stories.slice(0, 6).join(", ") })}>}
{!live && (
@@ -102,7 +102,7 @@ export async function ProductCard({
{product.fix ? (
<>
- {product.fix.working ? t("Агент уже этим занят:") : t("Это первая в очереди — агент возьмёт её сам:")} {t("{task} {key}", { task: task("nom"), key: product.fix.key })}. {t("Ссылка появится здесь, делать ничего не нужно.")}
+ {product.fix.working ? t("Агент уже этим занят:") : t("Агент возьмёт это первым:")} {product.fix.key}. {t("Ссылка появится здесь, делать ничего не нужно.")}
>
) : product.preparing ? (
t("Продукт запускается — ссылка появится здесь через несколько минут.")
@@ -113,10 +113,10 @@ export async function ProductCard({
+
+ {t("Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.")}{" "}
+ {product.fix && {product.fix.key}}
)}
{live && check && (
diff --git a/openspec/changes/pep-145-product-link-always/tasks.md b/openspec/changes/pep-145-product-link-always/tasks.md
index 445be6f2..da08922f 100644
--- a/openspec/changes/pep-145-product-link-always/tasks.md
+++ b/openspec/changes/pep-145-product-link-always/tasks.md
@@ -1,24 +1,24 @@
## 1. Шаблон и новый проект
-- [ ] 1.1 Заглушка продукта в `template/` (`product/server.mjs`, `product/index.html`, `Dockerfile`), README заготовки
-- [ ] 1.2 `provisionProject`: `deploy` в `.peppa/project.json` новому репозиторию, заглушка не копируется существующему, тег первой выкладки после `setupCi`, режим показа «сам»
-- [ ] 1.3 Правило агентам в `template/RULES.md` и `template/AGENTS.md`
+- [x] 1.1 Заглушка продукта в `template/` (`product/server.mjs`, `product/index.html`, `Dockerfile`), README заготовки
+- [x] 1.2 `provisionProject`: `deploy` в `.peppa/project.json` новому репозиторию, заглушка не копируется существующему, тег первой выкладки после `setupCi`, режим показа «сам»
+- [x] 1.3 Правило агентам в `template/RULES.md` и `template/AGENTS.md`
## 2. Ядро
-- [ ] 2.1 `core/product-link.ts`: настройка показа, состояние системной задачи, текст задачи
-- [ ] 2.2 `core/product.ts`: `fix`, `broken`, `preparing`, `shot` в `projectProduct`
+- [x] 2.1 `core/product-link.ts`: настройка показа, состояние системной задачи, текст задачи
+- [x] 2.2 `core/product.ts`: `fix`, `broken`, `preparing`, `shot` в `projectProduct`
## 3. Вачдог
-- [ ] 3.1 `runner/product-link.ts`: `productLinkTick` (системная задача), `autoPublish`, предложение режима, `onPublishAnswer`; подключить в тик, `recordRelease`, обработчики ответов; `readyBacklog` — системная задача первой
-- [ ] 3.2 Ссылка «Посмотреть» в сообщениях о принятой задаче
+- [x] 3.1 `runner/product-link.ts`: `productLinkTick` (системная задача), `autoPublish`, предложение режима, `onPublishAnswer`; подключить в тик, `recordRelease`, обработчики ответов; `readyBacklog` — системная задача первой
+- [x] 3.2 Ссылка «Посмотреть» в сообщениях о принятой задаче
## 4. Веб
-- [ ] 4.1 `ProductCard`: «Открыть продукт», скриншот, «Готовим ссылку», «чиним»; Главная
-- [ ] 4.2 Настройка «Показывать всем» в настройках проекта; «Посмотреть результат» на странице задачи
-- [ ] 4.3 `/help` (вид «Продакт»), словарь, переводы en/kk
+- [x] 4.1 `ProductCard`: «Открыть продукт», скриншот, «Готовим ссылку», «чиним»; Главная
+- [x] 4.2 Настройка «Показывать всем» в настройках проекта; «Посмотреть результат» на странице задачи
+- [x] 4.3 `/help` (вид «Продакт»), словарь, переводы en/kk
## 5. Проверка
-- [ ] 5.1 Тест `product-link.test.ts` по сценариям спеки; правки существующих тестов
-- [ ] 5.2 Экраны в браузере на копии данных, сверка текстов со словарём
+- [x] 5.1 Тест `product-link.test.ts` по сценариям спеки; правки существующих тестов
+- [x] 5.2 Экраны в браузере на копии данных, сверка текстов со словарём
- [ ] 5.3 lint, typecheck, build, тесты зелёные
## 6. Завершение
diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts
index 705dc0d6..496a1da5 100644
--- a/packages/shared/src/i18n/en/project.ts
+++ b/packages/shared/src/i18n/en/project.ts
@@ -399,7 +399,7 @@ export const project: Dict = {
"Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.": "Once the tasks of this version are accepted, Peppa FACTORY will show it to everyone by itself.",
"Готовим ссылку на продукт": "Preparing the link to your product",
"Агент уже этим занят:": "An agent is already on it:",
- "Это первая в очереди — агент возьмёт её сам:": "It is first in line — an agent will take it by itself:",
+ "Агент возьмёт это первым:": "An agent will take this first:",
"Ссылка появится здесь, делать ничего не нужно.": "The link will appear here; you don't need to do anything.",
"Продукт запускается — ссылка появится здесь через несколько минут.": "The product is starting — the link will appear here in a few minutes.",
"Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.": "The link will appear here by itself — you don't need to do anything. What is already done is on the page of each finished {task}.",
diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts
index 61a2708d..4b07da39 100644
--- a/packages/shared/src/i18n/kk/project.ts
+++ b/packages/shared/src/i18n/kk/project.ts
@@ -344,7 +344,7 @@ export const project: Dict = {
"Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.": "Осы нұсқаның тапсырмалары қабылданғанда, Peppa FACTORY оны барлығына өзі көрсетеді.",
"Готовим ссылку на продукт": "Өнімге сілтеме дайындалып жатыр",
"Агент уже этим занят:": "Агент осымен айналысып жатыр:",
- "Это первая в очереди — агент возьмёт её сам:": "Ол кезекте бірінші — агент оны өзі алады:",
+ "Агент возьмёт это первым:": "Агент мұны бірінші алады:",
"Ссылка появится здесь, делать ничего не нужно.": "Сілтеме осы жерде пайда болады, ештеңе істеудің қажеті жоқ.",
"Продукт запускается — ссылка появится здесь через несколько минут.": "Өнім іске қосылып жатыр — сілтеме осы жерде бірнеше минуттан кейін пайда болады.",
"Ссылка появится здесь сама — делать ничего не нужно. Что уже получилось — на странице каждой готовой {task}.": "Сілтеме осы жерде өзі пайда болады — ештеңе істеудің қажеті жоқ. Дайын нәтиже — әр дайын {task} бетінде.",
diff --git a/packages/testkit/test/i18n-product-mode.test.ts b/packages/testkit/test/i18n-product-mode.test.ts
index db7b04bb..0568c517 100644
--- a/packages/testkit/test/i18n-product-mode.test.ts
+++ b/packages/testkit/test/i18n-product-mode.test.ts
@@ -20,7 +20,7 @@ const check = (file: string) =>
);
// Screens of the «Продакт» view; a story that adds one lists it here.
-const SCREENS = ["apps/web/app/(app)/settings/page.tsx", "apps/web/app/(app)/p/[key]/page.tsx", "apps/web/components/ProductCard.tsx", "apps/web/components/Sidebar.tsx", "apps/web/components/Accounting.tsx", "apps/web/app/(app)/help/page.tsx", "apps/web/app/(app)/t/[key]/page.tsx", "apps/web/components/StoryProduct.tsx", "apps/web/components/FeedbackButton.tsx", "apps/web/components/Feedback.tsx", "apps/web/app/(app)/feedback/page.tsx"];
+const SCREENS = ["apps/web/app/(app)/settings/page.tsx", "apps/web/app/(app)/p/[key]/page.tsx", "apps/web/components/ProductCard.tsx", "apps/web/components/Sidebar.tsx", "apps/web/components/Accounting.tsx", "apps/web/app/(app)/help/page.tsx", "apps/web/app/(app)/t/[key]/page.tsx", "apps/web/components/StoryProduct.tsx", "apps/web/components/FeedbackButton.tsx", "apps/web/components/Feedback.tsx", "apps/web/app/(app)/feedback/page.tsx", "apps/web/components/PublishPanel.tsx", "apps/web/components/ProgressOverview.tsx"];
// Texts only the «Продакт» / «Инженер» views show; a story that adds one lists it here.
const TEXTS = [
@@ -32,6 +32,17 @@ const TEXTS = [
"Всё, что делают агенты: код, проверки, каждый шаг агента, расход. Для тех, кто хочет заглянуть под капот.",
"Показать всем",
"Посмотрите — и, если всё хорошо,",
+ // PEP-145: the product always opens by a link
+ "Показывать всем",
+ "Сам",
+ "По кнопке",
+ "Готовим ссылку на продукт",
+ "Агент уже этим занят:",
+ "Агент возьмёт это первым:",
+ "Ваш продукт готов — пока его видите только вы",
+ "Последнее обновление не запустилось — по ссылке открывается прежняя версия. Чиним.",
+ "Посмотреть результат",
+ "Когда задачи этой версии будут приняты, Peppa FACTORY сама покажет её всем.",
// PEP-121: one line instead of the limits bar.
"Агенты работают",
"Агенты продолжат в",
--
2.45.2
From db6209bda18c2fed7c85194e6b54f4c496a8b620 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 10:47:02 +0500
Subject: [PATCH 009/215] =?UTF-8?q?PEP-145:=20archive=20the=20change=20?=
=?UTF-8?q?=E2=80=94=20the=20requirements=20are=20in=20specs/product-link?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
.../.openspec.yaml | 0
.../design.md | 0
.../proposal.md | 0
.../specs/product-link/spec.md | 0
.../tasks.md | 4 +-
openspec/specs/product-link/spec.md | 103 ++++++++++++++++++
6 files changed, 105 insertions(+), 2 deletions(-)
rename openspec/changes/{pep-145-product-link-always => archive/2026-11-16-pep-145-product-link-always}/.openspec.yaml (100%)
rename openspec/changes/{pep-145-product-link-always => archive/2026-11-16-pep-145-product-link-always}/design.md (100%)
rename openspec/changes/{pep-145-product-link-always => archive/2026-11-16-pep-145-product-link-always}/proposal.md (100%)
rename openspec/changes/{pep-145-product-link-always => archive/2026-11-16-pep-145-product-link-always}/specs/product-link/spec.md (100%)
rename openspec/changes/{pep-145-product-link-always => archive/2026-11-16-pep-145-product-link-always}/tasks.md (94%)
create mode 100644 openspec/specs/product-link/spec.md
diff --git a/openspec/changes/pep-145-product-link-always/.openspec.yaml b/openspec/changes/archive/2026-11-16-pep-145-product-link-always/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-145-product-link-always/.openspec.yaml
rename to openspec/changes/archive/2026-11-16-pep-145-product-link-always/.openspec.yaml
diff --git a/openspec/changes/pep-145-product-link-always/design.md b/openspec/changes/archive/2026-11-16-pep-145-product-link-always/design.md
similarity index 100%
rename from openspec/changes/pep-145-product-link-always/design.md
rename to openspec/changes/archive/2026-11-16-pep-145-product-link-always/design.md
diff --git a/openspec/changes/pep-145-product-link-always/proposal.md b/openspec/changes/archive/2026-11-16-pep-145-product-link-always/proposal.md
similarity index 100%
rename from openspec/changes/pep-145-product-link-always/proposal.md
rename to openspec/changes/archive/2026-11-16-pep-145-product-link-always/proposal.md
diff --git a/openspec/changes/pep-145-product-link-always/specs/product-link/spec.md b/openspec/changes/archive/2026-11-16-pep-145-product-link-always/specs/product-link/spec.md
similarity index 100%
rename from openspec/changes/pep-145-product-link-always/specs/product-link/spec.md
rename to openspec/changes/archive/2026-11-16-pep-145-product-link-always/specs/product-link/spec.md
diff --git a/openspec/changes/pep-145-product-link-always/tasks.md b/openspec/changes/archive/2026-11-16-pep-145-product-link-always/tasks.md
similarity index 94%
rename from openspec/changes/pep-145-product-link-always/tasks.md
rename to openspec/changes/archive/2026-11-16-pep-145-product-link-always/tasks.md
index da08922f..419ee233 100644
--- a/openspec/changes/pep-145-product-link-always/tasks.md
+++ b/openspec/changes/archive/2026-11-16-pep-145-product-link-always/tasks.md
@@ -19,7 +19,7 @@
## 5. Проверка
- [x] 5.1 Тест `product-link.test.ts` по сценариям спеки; правки существующих тестов
- [x] 5.2 Экраны в браузере на копии данных, сверка текстов со словарём
-- [ ] 5.3 lint, typecheck, build, тесты зелёные
+- [x] 5.3 lint, typecheck, build, тесты зелёные
## 6. Завершение
-- [ ] 6.1 AGENTS.md, память проекта, архив change, PR
+- [x] 6.1 AGENTS.md, память проекта, архив change, PR
diff --git a/openspec/specs/product-link/spec.md b/openspec/specs/product-link/spec.md
new file mode 100644
index 00000000..eca28aee
--- /dev/null
+++ b/openspec/specs/product-link/spec.md
@@ -0,0 +1,103 @@
+# product-link Specification
+
+## Purpose
+Продукт проекта открывается по ссылке без действий продакта: заглушка с первого дня, системная задача при отсутствии или сбое выкладки, показ всем по настройке и карточка «Ваш продукт» с честным статусом.
+
+## Requirements
+
+### Requirement: Новый проект открывается по ссылке с первого дня
+Новый проект SHALL создаваться с настроенной выкладкой и заглушкой продукта, а Peppa SHALL сама запросить первую выкладку версии для проверки. Подключаемый существующий репозиторий SHALL оставаться без изменений выкладки.
+
+#### Scenario: Новый проект получает заглушку и первую выкладку
+- **GIVEN** пользователь создаёт новый проект «shop» с ключом «SHP»
+- **WHEN** создание проекта завершилось
+- **THEN** в `.peppa/project.json` репозитория есть `deploy` с `compose` «deploy/compose.yml» и `health` «/healthz»
+- **AND** в репозитории есть `Dockerfile` и страница «Продукт создаётся»
+- **AND** на голове основной ветки стоит тег `deploy-staging-…`
+
+#### Scenario: Существующий репозиторий не получает заглушку
+- **GIVEN** репозиторий «legacy» со своим кодом и без `Dockerfile`
+- **WHEN** его подключают как существующий
+- **THEN** в нём нет заглушки продукта и `deploy` в `.peppa/project.json`
+- **AND** теги `deploy-staging-…` не ставятся
+
+### Requirement: Системная задача при отсутствии ссылки
+Peppa SHALL сама заводить задачу «Продукт должен открываться по ссылке» первой в бэклоге, когда у проекта есть принятые задачи и нет здоровой версии для проверки или последняя выкладка упала либо откатилась; не более одной открытой на проект и не чаще раза в сутки.
+
+#### Scenario: Принятые задачи без выкладки
+- **GIVEN** проект с 2 принятыми задачами и без единой выкладки
+- **WHEN** проходит тик вачдога
+- **THEN** первой в бэклоге стоит задача «Продукт должен открываться по ссылке»
+- **AND** диспетчер проекта с автономностью берёт её раньше остальных
+
+#### Scenario: Упавшая выкладка
+- **GIVEN** последняя выкладка версии для проверки упала с причиной «сборка образа не удалась»
+- **WHEN** проходит тик вачдога
+- **THEN** заведена системная задача, в описании которой есть «сборка образа не удалась»
+
+#### Scenario: Вторая задача не заводится
+- **GIVEN** системная задача проекта уже открыта
+- **WHEN** проходит ещё один тик вачдога
+- **THEN** в проекте по-прежнему одна такая задача
+
+#### Scenario: Не чаще раза в сутки
+- **GIVEN** системную задачу приняли 2 часа назад, а выкладка снова упала
+- **WHEN** проходит тик вачдога
+- **THEN** новая системная задача не заведена
+
+### Requirement: Показ всем без нажатий
+У проекта SHALL быть настройка «Показывать всем: сам / по кнопке». В режиме «сам» здоровая версия для проверки, все задачи которой приняты, SHALL становиться рабочей версией без действий пользователя; в режиме «по кнопке» — только по «Показать всем». Новый проект SHALL получать «сам», существующий — оставаться «по кнопке», пока владелец не выберет.
+
+#### Scenario: Режим «сам»
+- **GIVEN** проект в режиме «сам» и задача «SHP-1» принята
+- **WHEN** версия для проверки с «SHP-1» стала здоровой
+- **THEN** запущено обновление рабочей версии на тот же коммит
+- **AND** вопрос «Показать её всем пользователям?» не приходит
+
+#### Scenario: Режим «по кнопке»
+- **GIVEN** проект в режиме «по кнопке»
+- **WHEN** версия для проверки стала здоровой
+- **THEN** рабочая версия не обновляется
+- **AND** приходит вопрос с кнопкой «🚀 Показать всем»
+
+#### Scenario: Не все задачи приняты
+- **GIVEN** проект в режиме «сам», в версии для проверки задача «SHP-2» в ревью
+- **WHEN** версия для проверки стала здоровой
+- **THEN** рабочая версия не обновляется, пока «SHP-2» не принята
+
+#### Scenario: Существующему проекту — предложение один раз
+- **GIVEN** существующий проект без выбранного режима и со здоровой версией для проверки
+- **WHEN** проходят два тика вачдога
+- **THEN** владельцу пришло одно сообщение с кнопками «Показывать сразу» и «Оставить по кнопке»
+
+### Requirement: Карточка «Ваш продукт» с честным статусом
+Карточка SHALL показывать кнопку «Открыть продукт», время обновления и вошедшие задачи, когда ссылка есть; без ссылки — «Готовим ссылку на продукт» со ссылкой на системную задачу; при упавшей выкладке — прошлую работающую версию и статус «чиним». Совета «попросите аналитика» в карточке SHALL NOT быть.
+
+#### Scenario: Ссылка есть
+- **GIVEN** здоровая версия для проверки по адресу «shop-staging.telecom.quest»
+- **WHEN** продакт открывает страницу проекта
+- **THEN** он видит кнопку «Открыть продукт», ведущую на «https://shop-staging.telecom.quest»
+
+#### Scenario: Ссылки нет
+- **GIVEN** проект с принятыми задачами, без выкладок и с системной задачей «SHP-7»
+- **WHEN** продакт открывает страницу проекта
+- **THEN** он видит «Готовим ссылку на продукт» и ссылку на «SHP-7»
+- **AND** не видит слов «попросите аналитика»
+
+#### Scenario: Выкладка упала, прошлая версия работает
+- **GIVEN** прошлая версия для проверки здорова, а последняя выкладка откатилась
+- **WHEN** продакт открывает страницу проекта
+- **THEN** он видит «Открыть продукт» на прошлую версию и статус «чиним»
+
+### Requirement: Ссылка на продукт у принятой задачи
+Сообщение о принятой задаче и страница принятой задачи в виде «Продакт» SHALL вести на продукт проекта, когда ссылка есть.
+
+#### Scenario: Сообщение о принятой задаче
+- **GIVEN** у проекта есть рабочая версия «https://shop-prod.telecom.quest»
+- **WHEN** задача закрывается автоматически после проверок
+- **THEN** в сообщении есть строка «Посмотреть: https://shop-prod.telecom.quest»
+
+#### Scenario: Ссылки нет
+- **GIVEN** у проекта нет ни одной здоровой выкладки
+- **WHEN** задача закрывается автоматически
+- **THEN** в сообщении нет строки «Посмотреть»
--
2.45.2
From 54f242d0c592bc74a8cefceb009e66b8604a5823 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:23:26 +0500
Subject: [PATCH 010/215] =?UTF-8?q?PEP-149:=20proposal=20=E2=80=94=20four?=
=?UTF-8?q?=20kinds=20of=20agent=20messages?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
.../.openspec.yaml | 2 +
.../pep-149-agent-message-kinds/design.md | 31 ++++++
.../pep-149-agent-message-kinds/proposal.md | 30 +++++
.../specs/agent-messages/spec.md | 104 ++++++++++++++++++
.../pep-149-agent-message-kinds/tasks.md | 22 ++++
5 files changed, 189 insertions(+)
create mode 100644 openspec/changes/pep-149-agent-message-kinds/.openspec.yaml
create mode 100644 openspec/changes/pep-149-agent-message-kinds/design.md
create mode 100644 openspec/changes/pep-149-agent-message-kinds/proposal.md
create mode 100644 openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md
create mode 100644 openspec/changes/pep-149-agent-message-kinds/tasks.md
diff --git a/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml b/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml
new file mode 100644
index 00000000..90080a92
--- /dev/null
+++ b/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-16
diff --git a/openspec/changes/pep-149-agent-message-kinds/design.md b/openspec/changes/pep-149-agent-message-kinds/design.md
new file mode 100644
index 00000000..2b5b8ea4
--- /dev/null
+++ b/openspec/changes/pep-149-agent-message-kinds/design.md
@@ -0,0 +1,31 @@
+# Design: PEP-149
+
+## Context
+
+Сообщение пользователю сегодня — строка `questions` с `kind` (`question | permission | approval | attention`). `attention` — это и «готово к ревью», и сбой, и «агент закончил ход». Ход работы (`report_progress`) — событие `progress`, которое `syncChats` кладёт в тред задачи.
+
+## Decisions
+
+**1. Где хранится тип.** Две новые колонки `questions`: `msg_type` (`question | done | progress | blocker`, nullable) и `default_option` (текст варианта по умолчанию). `kind` не трогаем: на нём держатся хук разрешений, одобрение плана, «Принять», сбои. Сообщения, у которых нет строки вопроса, типизирует само событие: `progress` и новое `blocker` в `events` (их проекция в `chat_messages` идёт по типу события). Колонку в `chat_messages` не добавляем: у сообщения чата есть `question_id` или оно пришло из события — тип выводится. Альтернатива «расширить enum `kind`» отвергнута: десятки мест сравнивают `kind === "attention"`, в том числе в файлах соседних задач.
+
+**2. Тип новых и старых строк.** При вставке (`askPm`, `askPmProject`, `raiseSessionQuestion`) тип берётся из аргумента, иначе: не `attention` → `question`; `attention` с вариантами ответа → `question`. Остальные `attention` (сбои, лимиты, выкладки — тексты соседних задач) остаются без типа. Для чтения — одна функция `questionType(q, taskStatus)`: сохранённый тип → правило выше → `attention` у задачи в ревью = `done` → `null` («сообщение от фабрики»). Старые строки не переписываются — работают по тому же правилу.
+
+**3. Маршруты.**
+- `question` и `done` — «ждут человека»: «Ждут вашего ответа» (только question), счётчики меню и `/api/attention` (question + done), push, Telegram с кнопками. Одно SQL-условие `NEEDS_PERSON` в `core/questions.ts` для счётчиков.
+- `progress` — только событие → тред задачи в «Событиях агентов». Ни вопроса, ни Telegram, ни push.
+- `blocker` — `report_blocker`: продуктовый (с вариантами и вариантом по умолчанию) создаёт question; непродуктовый — событие `blocker` в треде задачи и сообщение администраторам фабрики (`alertAdmins`), владельцу проекта ничего. Что делать с блокером дальше — задача про сбои.
+- Сообщения без типа (сбои и т. п.) по-прежнему уходят в Telegram и чат проекта, но без кнопки «Продолжай», не в «Ждут вашего ответа», не в счётчик и без push. Их дальнейшая судьба — задача про сбои.
+
+**4. Конец хода.** Последняя ветка `turnEnd`: событие `progress` (`{text, auto: true}`) вместо вопроса; сессия → `idle` (не `waiting_input`: она не ждёт человека и не должна светиться в «ждут вас»). Чтобы такие сессии не висели вечно, `idleStopTick` останавливает и `idle`-сессии задач (одно условие, тексты не меняются). Открытые сообщения без типа больше не блокируют подталкивание агента — блокируют только question.
+
+**5. Кто будит агента.** Красные проверки, ревьюер, rebase и комментарии уже будят. Добавляется зелёный случай: отчёт о пройденной проверке, задача в работе, ход агента окончен, гейт ревью открыт → одно сообщение агенту на коммит («проверки прошли — переводи в review»), отметка `ci.woke:`.
+
+**6. `done`.** Только через `sendReviewCard` (гейт PEP-127 без изменений), тип `done`. Если в тексте нет ни одной ссылки — добавляется ссылка на страницу задачи.
+
+**7. `ask_pm`.** `options` (2–4) и `default` (текст одного из вариантов) проверяются в обработчике, а не схемой, чтобы агент получил объяснение, а не ошибку валидации. Вариант по умолчанию ставится первым и подсвечивается; под вопросом — «Если не ответите, агент продолжит по варианту …».
+
+## Risks / Trade-offs
+
+- Соседние задачи эпика тоже могут добавить миграцию → конфликт журнала drizzle при rebase: перегенерировать свою миграцию поверх main.
+- Агент, который закончил ход и ничего не ждёт, остаётся без пинка до остановки по простою — сознательно: это «сбой», а не вопрос продакту (соседняя задача).
+- Вопрос «проверки не проходят 3 раза» (`ci-feedback.ts`) остаётся вопросом без вариантов — его перепишет задача про сбои.
diff --git a/openspec/changes/pep-149-agent-message-kinds/proposal.md b/openspec/changes/pep-149-agent-message-kinds/proposal.md
new file mode 100644
index 00000000..db50313b
--- /dev/null
+++ b/openspec/changes/pep-149-agent-message-kinds/proposal.md
@@ -0,0 +1,30 @@
+# PEP-149: четыре типа сообщений агента
+
+## Why
+
+Пользователь Peppa FACTORY — продакт. Сейчас любой конец хода агента превращается в «вопрос» с сырым текстом последней реплики и кнопкой «Продолжай» (PEP-147: девять одинаковых сообщений за 18 минут). В «Ждут вашего ответа» и в Telegram попадает всё подряд, и настоящие вопросы теряются.
+
+## What Changes
+
+- У сообщения агента пользователю появляется тип: **question**, **done**, **progress**, **blocker**. От типа зависит маршрут.
+- Конец хода без смены статуса задачи больше не будит пользователя: реплика агента становится записью хода работы (`progress`) в «Событиях агентов». Агента, который ждёт проверок, будит платформа, когда проверки прошли.
+- `ask_pm` требует 2–4 варианта ответа и вариант по умолчанию; без них — отказ с объяснением. Новый инструмент `report_blocker`. `report_progress` — тип progress.
+- «Готово» (`done`) шлёт только платформа, только после зелёных проверок и всегда со ссылкой на результат.
+- Кнопка «Продолжай» убрана из веба и бота. **BREAKING** для старых сообщений Telegram: кнопка на них больше не срабатывает.
+- «Ждут вашего ответа», счётчики, напоминания и push считают только question (и done — как «ждёт „Принять“»).
+- `template/RULES.md` и «Помощь» описывают четыре типа.
+
+## Capabilities
+
+### New Capabilities
+- `agent-messages`: типы сообщений агента пользователю и маршрут каждого типа.
+
+### Modified Capabilities
+
+Нет: поведение прежних спецификаций (хуки, MCP, уведомления) описывается здесь одним новым контрактом; требования соседних возможностей про сбои и повторы не меняются.
+
+## Impact
+
+- БД: `questions.msg_type`, `questions.default_option` (миграция; применяет координатор).
+- `packages/core` (новый `questions.ts`, `tasks.ts`, `sessions.ts`, `review-card.ts`, `notifications.ts`, строка в `EVENT_TEXT`), `packages/runner` (`hook.ts`, `ci-feedback.ts`, одно условие в `recovery.ts`), `packages/mcp` (`agent.ts`, `manager.ts`), `apps/web` (карточка вопроса, «Ждут вашего ответа», счётчики, «Помощь»), `apps/bot` (`render.ts`, `bot.ts`), `template/RULES.md`, переводы en/kk.
+- Тексты сбоев (`recovery.ts`, `watchdog.ts`, `autonomy.ts`) и логика повторов в `core/chats.ts` не меняются — соседние задачи эпика.
diff --git a/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md b/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md
new file mode 100644
index 00000000..669e5093
--- /dev/null
+++ b/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md
@@ -0,0 +1,104 @@
+# Spec Delta
+
+## Purpose
+Сообщения агента пользователю делятся на четыре типа — вопрос, готово, ход работы, блокер; от типа зависит, увидит ли его пользователь в «Ждут вашего ответа», в Telegram или только в «Событиях агентов».
+
+## ADDED Requirements
+
+### Requirement: Тип сообщения определяет маршрут
+Система SHALL присваивать каждому новому сообщению агента пользователю один из типов `question`, `done`, `progress`, `blocker`. В «Ждут вашего ответа» SHALL попадать только `question`; счётчик «ждут вас», напоминания и push SHALL учитывать только `question` и `done`.
+
+#### Scenario: Вопрос попадает в «Ждут вашего ответа»
+- **GIVEN** задача PEP-1 в работе
+- **WHEN** агент задаёт вопрос «Какой цвет кнопки?» с вариантами «Синий» и «Зелёный», по умолчанию «Синий»
+- **THEN** на Главной в «Ждут вашего ответа» есть этот вопрос с кнопками «Синий» и «Зелёный» и полем «Свой ответ»
+- **AND** счётчик «ждут вас» равен 1
+
+#### Scenario: Сообщение о сбое не попадает в «Ждут вашего ответа»
+- **GIVEN** открытое сообщение фабрики без вариантов ответа «агент остановился с ошибкой»
+- **WHEN** пользователь открывает Главную
+- **THEN** в «Ждут вашего ответа» этого сообщения нет
+- **AND** счётчик «ждут вас» равен 0
+
+### Requirement: Конец хода — это ход работы, а не вопрос
+Когда агент закончил ход, а статус задачи не изменился и подталкивания исчерпаны, система SHALL записать последнюю реплику агента как `progress` в «События агентов» и SHALL NOT создавать вопрос, отправлять Telegram или push.
+
+#### Scenario: Агент закончил ход, статус задачи тот же
+- **GIVEN** задача PEP-1 в работе, агент уже дважды получил подталкивание
+- **WHEN** агент заканчивает ход с текстом «Жду проверок»
+- **THEN** в «Ждут вашего ответа» и в Telegram владельца ничего нового нет
+- **AND** в «Событиях агентов» проекта, в треде PEP-1, есть запись «Жду проверок»
+
+#### Scenario: У агента есть открытый вопрос
+- **GIVEN** агент задал вопрос с вариантами и не получил ответа
+- **WHEN** агент заканчивает ход
+- **THEN** новая запись хода работы не создаётся, вопрос остаётся в «Ждут вашего ответа»
+
+### Requirement: Платформа будит агента, когда проверки прошли
+Когда все проверки последнего коммита задачи в работе прошли, а ход агента окончен, система SHALL один раз на коммит сообщить агенту, что задачу можно переводить в ревью.
+
+#### Scenario: Проверки прошли, агент ждал
+- **GIVEN** задача PEP-1 в работе, агент закончил ход, проверки коммита `abc1234` ещё шли
+- **WHEN** последняя проверка коммита `abc1234` проходит
+- **THEN** агент получает сообщение «проверки прошли»
+
+#### Scenario: Повторный отчёт о том же коммите
+- **GIVEN** агент уже получил сообщение о коммите `abc1234`
+- **WHEN** приходит ещё один успешный отчёт по коммиту `abc1234`
+- **THEN** второго сообщения агент не получает
+
+### Requirement: «Готово» шлёт платформа после проверок
+Сообщение типа `done` SHALL отправляться только платформой, только когда проверки последнего коммита прошли и нет конфликта, и SHALL содержать ссылку на результат.
+
+#### Scenario: Проверки прошли
+- **GIVEN** задача PEP-1 в ревью, проверки зелёные, результат `https://git.example/pulls/7`
+- **WHEN** агент заканчивает ход
+- **THEN** владелец получает сообщение «готова к ревью» типа `done` со ссылкой `https://git.example/pulls/7` и кнопкой «Принять»
+
+#### Scenario: Проверки ещё идут
+- **GIVEN** задача PEP-1 в ревью, одна проверка не завершена
+- **WHEN** агент заканчивает ход
+- **THEN** владелец ничего не получает, пока проверки не пройдут
+
+### Requirement: Вопрос агента — с вариантами и вариантом по умолчанию
+Инструмент `ask_pm` SHALL принимать вопрос только с 2–4 вариантами ответа и вариантом по умолчанию из их числа; иначе SHALL отклонять вызов с объяснением.
+
+#### Scenario: Вопрос с вариантами принят
+- **WHEN** агент вызывает `ask_pm` с вариантами «Да», «Нет» и вариантом по умолчанию «Да»
+- **THEN** вопрос отправлен, вариант «Да» показан первым и отмечен как выбранный по умолчанию
+
+#### Scenario Outline: Вопрос без вариантов отклонён
+- **WHEN** агент вызывает `ask_pm` с вариантами <варианты> и вариантом по умолчанию <по умолчанию>
+- **THEN** вызов отклонён с объяснением «<причина>», вопрос не создан
+
+| варианты | по умолчанию | причина |
+|---|---|---|
+| нет | нет | нужны 2–4 варианта |
+| «Да» | «Да» | нужны 2–4 варианта |
+| «Да», «Нет» | нет | нужен вариант по умолчанию |
+| «Да», «Нет» | «Может быть» | вариант по умолчанию — один из вариантов |
+
+### Requirement: Блокер идёт по своему маршруту
+Инструмент `report_blocker` SHALL принимать, что мешает и что агент уже пробовал. Продуктовый блокер SHALL идти пользователю как `question` с вариантами; непродуктовый SHALL записываться в «События агентов» и SHALL NOT отправляться владельцу проекта.
+
+#### Scenario: Непродуктовый блокер
+- **WHEN** агент сообщает блокер «нет доступа к серверу сборки», пробовал «повторил три раза»
+- **THEN** в треде задачи в «Событиях агентов» есть запись о блокере
+- **AND** владелец не получает ни вопроса, ни сообщения в Telegram
+
+#### Scenario: Продуктовый блокер без вариантов
+- **WHEN** агент сообщает продуктовый блокер без вариантов ответа
+- **THEN** вызов отклонён с объяснением, что нужны варианты и вариант по умолчанию
+
+### Requirement: Нет кнопки «Продолжай»
+Веб и Telegram-бот SHALL NOT показывать кнопку «Продолжай» ни у какого сообщения; у `question` SHALL быть кнопки вариантов и возможность своего ответа.
+
+#### Scenario: Сообщение фабрики в Telegram
+- **GIVEN** открытое сообщение фабрики без вариантов ответа
+- **WHEN** бот отправляет его в Telegram
+- **THEN** у сообщения нет кнопки «Продолжай»
+
+#### Scenario: Старая кнопка «Продолжай»
+- **GIVEN** старое сообщение в Telegram с кнопкой «Продолжай»
+- **WHEN** пользователь нажимает её
+- **THEN** агенту ничего не отправляется
diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/pep-149-agent-message-kinds/tasks.md
new file mode 100644
index 00000000..e470d634
--- /dev/null
+++ b/openspec/changes/pep-149-agent-message-kinds/tasks.md
@@ -0,0 +1,22 @@
+# Tasks: PEP-149
+
+## 1. Ядро
+- [ ] 1.1 Миграция: `questions.msg_type`, `questions.default_option`
+- [ ] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion`
+- [ ] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна
+- [ ] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`)
+
+## 2. Агент
+- [ ] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle`
+- [ ] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит)
+- [ ] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress`
+
+## 3. Веб и бот
+- [ ] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике)
+- [ ] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP
+- [ ] 3.3 Переводы en/kk
+
+## 4. Правила, помощь, проверки
+- [ ] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа
+- [ ] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов
+- [ ] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта
--
2.45.2
From 45754f1f239856d4039ef166838f2ad7190d7c95 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:26:41 +0500
Subject: [PATCH 011/215] =?UTF-8?q?PEP-149:=20message=20types=20=E2=80=94?=
=?UTF-8?q?=20end=20of=20turn=20is=20progress,=20ask=5Fpm=20with=20options?=
=?UTF-8?q?=20and=20default,=20report=5Fblocker,=20no=20=C2=ABcontinue?=
=?UTF-8?q?=C2=BB=20button?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
apps/bot/src/bot.ts | 15 ++++++--
apps/bot/src/render.ts | 18 +++++-----
apps/web/app/(app)/page.tsx | 9 +++--
apps/web/components/cards.tsx | 9 ++---
apps/web/lib/queries.ts | 23 +++++++++---
packages/core/src/chats.ts | 7 ++--
packages/core/src/index.ts | 1 +
packages/core/src/notifications.ts | 16 +++++----
packages/core/src/questions.ts | 56 ++++++++++++++++++++++++++++++
packages/core/src/review-card.ts | 6 ++--
packages/core/src/sessions.ts | 5 +--
packages/core/src/tasks.ts | 24 +++++++++++--
packages/db/src/schema.ts | 5 +++
packages/mcp/src/agent.ts | 48 +++++++++++++++++++++----
packages/mcp/src/manager.ts | 9 +++--
packages/runner/src/ci-feedback.ts | 29 ++++++++++++++++
packages/runner/src/hook.ts | 18 ++++++----
packages/runner/src/recovery.ts | 4 ++-
18 files changed, 249 insertions(+), 53 deletions(-)
create mode 100644 packages/core/src/questions.ts
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 6f0f0cad..851119d2 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -39,6 +39,7 @@ import {
markOutboxRetry,
markOutboxSent,
pendingQuestions,
+ needsPerson,
questionByTelegramMessage,
setOffset,
setSetting,
@@ -305,12 +306,20 @@ export function createBot(o: BotOptions) {
const waitingFor = async (userId: number) => {
if (!projectsOf.has(userId)) projectsOf.set(userId, new Set(await userProjectIds(db, userId)));
const ids = projectsOf.get(userId)!;
- return open.filter((x) => ids.has(x.projectId)).length;
+ return open.filter((x) => ids.has(x.projectId) && waits.has(x.id)).length;
};
+ // PEP-149: what waits for a person — questions and finished stories; only these push and count.
+ const ctxOf = new Map>>();
+ const waits = new Set();
+ for (const q of open) {
+ const c = await context(q);
+ ctxOf.set(q.id, c);
+ if (needsPerson(q, c.taskStatus)) waits.add(q.id);
+ }
for (const q of open) {
const audience = await projectAudience(db, q.projectId);
if (!audience.length) continue;
- const ctx = await context(q);
+ const ctx = ctxOf.get(q.id)!;
const event = questionEvent(q, { taskStatus: ctx.taskStatus, sessionStatus: ctx.session?.status });
const r = renderQuestion(q, ctx);
// A push is a "now" signal: questions older than this don't pop up on a fresh subscription.
@@ -323,7 +332,7 @@ export function createBot(o: BotOptions) {
dedupeKey: `q:${q.id}:${u.telegramChatId}`,
pushKey: `q:${q.id}:u${u.id}`,
telegram: { questionId: q.id, params: { text: r.text, parse_mode: "HTML", reply_markup: { inline_keyboard: r.buttons } } },
- push: fresh ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
+ push: fresh && waits.has(q.id) ? { ...pushFor(q, event, ctx), url, tag: `q:${q.id}`, count: await waitingFor(u.id) } : undefined,
urgency: event === "questions" || event === "failures" ? "high" : "normal",
});
}
diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts
index 5536a560..dcff09a2 100644
--- a/apps/bot/src/render.ts
+++ b/apps/bot/src/render.ts
@@ -1,5 +1,5 @@
// Telegram message texts and buttons for PM questions. HTML parse mode.
-import type { Question, SessionView } from "@peppa/core";
+import { questionType, type Question, type SessionView } from "@peppa/core";
import type { InlineButton } from "./telegram.ts";
import { m as tr } from "@peppa/shared/i18n";
@@ -31,6 +31,7 @@ export function renderQuestion(
const lines = [head, KIND[q.kind], "", body];
const buttons: InlineButton[][] = [];
+ const type = questionType(q, ctx.taskStatus);
if (q.kind === "approval") {
buttons.push([{ text: tr("✅ Одобрить"), callback_data: `q:${q.id}:approve` }]);
lines.push("", italic(tr("Чтобы вернуть на доработку — ответьте на это сообщение комментарием.")));
@@ -40,23 +41,24 @@ export function renderQuestion(
{ text: tr("♾ Всегда"), callback_data: `q:${q.id}:always` },
{ text: tr("⛔ Запретить"), callback_data: `q:${q.id}:deny` },
]);
- } else if (q.kind === "question") {
+ } else if (type === "question") {
+ // PEP-149: a question always comes with answers to tap; the default goes first.
(q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }]));
+ if (q.kind === "attention") lines[1] = KIND.question;
lines.push("", italic(tr("Выберите вариант или ответьте на это сообщение своим текстом.")));
- } else if (ctx.taskStatus === "review") {
+ if (q.defaultOption) lines.push(italic(esc(tr("Если не ответите, агент продолжит по варианту «{option}».", { option: q.defaultOption }))));
+ } else if (type === "done") {
lines[1] = tr("✅ Готово к ревью");
buttons.push([{ text: tr("✅ Принять"), callback_data: `q:${q.id}:accept` }]);
lines.push("", italic(tr("Есть замечания — ответьте на это сообщение, агент доработает.")));
} else {
+ // A message of the factory itself (a failure, a limit): nothing to choose — no «continue» button.
const s = ctx.session;
if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) {
buttons.push([
{ text: tr("🔁 Перезапустить"), callback_data: `s:${s.id}:resume` },
{ text: tr("⏹ Остановить"), callback_data: `s:${s.id}:stop` },
]);
- } else {
- buttons.push([{ text: tr("▶️ Продолжай"), callback_data: `q:${q.id}:cont` }]);
- lines.push("", italic(tr("Или ответьте на это сообщение — текст уйдёт агенту.")));
}
}
if (ctx.session) lines.push(`tmux attach -t ${esc(ctx.session.tmuxName)}`);
@@ -75,8 +77,8 @@ export function renderAnswered(original: string, q: Question): string {
export function choiceToAnswer(q: Question, choice: string): string | null {
if (q.kind === "approval" && choice === "approve") return "ок"; // i18n-ignore: the answer goes to the agent
if (q.kind === "permission" && ["allow", "always", "deny"].includes(choice)) return choice;
- if (q.kind === "attention" && choice === "cont") return "Продолжай."; // i18n-ignore: the answer goes to the agent
+ // PEP-149: the «continue» button is gone — an old one on an earlier message answers nothing.
const m = /^o(\d+)$/.exec(choice);
- if (q.kind === "question" && m) return q.options?.[Number(m[1])] ?? null;
+ if (m) return q.options?.[Number(m[1])] ?? null;
return null;
}
diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx
index 2148b466..6ce600d7 100644
--- a/apps/web/app/(app)/page.tsx
+++ b/apps/web/app/(app)/page.tsx
@@ -12,7 +12,7 @@ import { Workspace } from "@/components/Workspace";
import { requireUser, words } from "@/lib/auth";
import { db } from "@/lib/db";
import { getT } from "@/lib/i18n";
-import { activeSessions, inbox } from "@/lib/queries";
+import { acceptInbox, activeSessions, inbox } from "@/lib/queries";
export default async function Home({ searchParams }: { searchParams: Promise<{ error?: string }> }) {
const user = await requireUser();
@@ -20,7 +20,7 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
const t = await getT();
const w = await words();
if (await claimWelcome(db, user.id)) redirect("/welcome");
- const [items, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
+ const [items, ready, sessions, projects, onboarding, progress] = await Promise.all([inbox(user.id), acceptInbox(user.id), activeSessions(user.id), listUserProjects(db, user.id), onboardingChecklist(db, user), progressOverview(db, user.id)]);
// PEP-143: users' reports about Peppa FACTORY wait for the superadmin's decision here.
const reports = (await isSuperadmin(db, user)) ? await pendingFeedback(db) : [];
return (
@@ -33,6 +33,11 @@ export default async function Home({ searchParams }: { searchParams: Promise<{ e
{items.map((q) => )}
+ {ready.length > 0 && (
+
+ {ready.map((q) => )}
+
+ )}
{reports.length > 0 && (
{t("все обращения")}}>
{reports.slice(0, 5).map((f) => )}
diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx
index ac09bb01..47eb7afe 100644
--- a/apps/web/components/cards.tsx
+++ b/apps/web/components/cards.tsx
@@ -37,7 +37,8 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
const t = await getT();
const review = q.kind === "attention" && taskStatus === "review";
const answered = !!q.answeredAt;
- const k = KIND[q.kind];
+ // PEP-149: a factory message with answers to choose from is a question for the person.
+ const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind];
const Icon = review ? CircleCheck : k.icon;
// PEP-151: the same state came again — one message with the time it was last refreshed.
const state = await questionState(db, q.id).catch(() => null);
@@ -89,12 +90,12 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
>
)}
{review && {t("Принять")}}
- {/* i18n-ignore: the value is the message to the agent */}
- {q.kind === "attention" && !review && {t("Продолжай")}}
+ {/* PEP-149: no «continue» button — a message either has answers to choose from or needs none. */}
{(q.options ?? []).map((o) => (
- {t.text(o)}
+ {t.text(o)}
))}
+ {q.defaultOption &&
{t("Если не ответите, агент продолжит по варианту «{option}».", { option: t.text(q.defaultOption) })}
}
{q.kind !== "permission" && (
diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts
index 4bd2a7e6..e5598a4e 100644
--- a/apps/web/lib/queries.ts
+++ b/apps/web/lib/queries.ts
@@ -1,4 +1,4 @@
-import { listSessions, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
+import { listSessions, needsPerson, questionType, PeppaError, STEP_EVENT, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef, discussionUnread } from "@peppa/core";
import { events, projects, questions, sessions, tasks } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { m } from "@peppa/shared/i18n";
@@ -7,8 +7,22 @@ import { db } from "./db";
export type InboxItem = Awaited>[number];
-/** Open PM questions across the user's projects, oldest first. */
+/**
+ * PEP-149: «Ждут вашего ответа» — open messages of type `question` across the user's projects,
+ * oldest first. Stories waiting for «Принять» (`done`) have their own block; progress, blockers
+ * and factory messages never land here.
+ */
export async function inbox(userId: number) {
+ return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "question");
+}
+
+/** PEP-149: finished stories waiting for «Принять» — open messages of type `done`. */
+export async function acceptInbox(userId: number) {
+ return (await openMessages(userId)).filter((q) => questionType(q, q.taskStatus) === "done" && q.taskStatus === "review");
+}
+
+/** Every open message of the user's projects (any type), oldest first. */
+async function openMessages(userId: number) {
const ids = await userProjectIds(db, userId);
if (!ids.length) return [];
const rows = await db
@@ -65,11 +79,12 @@ export const isActiveSession = (status: string) => !["done", "failed"].includes(
export async function navCounts(userId: number): Promise<{ questions: number; waitingRunners: number; chats: number }> {
const ids = await userProjectIds(db, userId);
if (!ids.length) return { questions: 0, waitingRunners: 0, chats: 0 };
- const [q] = await db.select({ n: count() }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)));
+ // PEP-149: only what waits for the person — questions and finished stories to accept.
+ const q = { n: (await openMessages(userId)).filter((x) => needsPerson(x, x.taskStatus)).length };
const [r] = await db.select({ n: count() }).from(sessions).where(and(inArray(sessions.projectId, ids), eq(sessions.status, "waiting_input")));
// PEP-106: messages of other people in the projects' discussions the user has not read.
const chats = [...(await discussionUnread(db, userId)).values()].reduce((a, b) => a + b, 0);
- return { questions: q?.n ?? 0, waitingRunners: r?.n ?? 0, chats };
+ return { questions: q.n, waitingRunners: r?.n ?? 0, chats };
}
/** Latest events of one runner, newest first (runner details panel, PEP-38). */
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index c9d1bc4e..7d1157da 100644
--- a/packages/core/src/chats.ts
+++ b/packages/core/src/chats.ts
@@ -10,6 +10,7 @@ import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lt, lte, or, sql, t
import { PeppaError } from "./errors.ts";
import { getNotifyPrefs, projectAudience } from "./notifications.ts";
import { notify } from "./notify.ts";
+import { IS_QUESTION } from "./questions.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { projectForUser, userProjectIds, type User } from "./users.ts";
import type { OutboxRow } from "./telegram.ts";
@@ -84,7 +85,7 @@ export async function listChats(db: Db, user: Pick): Promise`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt))).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)])
+ ? (await db.select({ p: questions.projectId, n: sql`count(*)` }).from(questions).where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt), IS_QUESTION)).groupBy(questions.projectId)).map((r) => [r.p, Number(r.n)])
: [],
);
const masterAt = [...last.values()].reduce((a, b) => (b && (!a || b > a) ? b : a), null);
@@ -315,7 +316,7 @@ export async function chatThreads(db: Db, chatId: number, limit = 50): Promise`count(*)`,
lastId: sql`max(${chatMessages.id})`,
lastAt: sql`max(${chatMessages.createdAt})`,
- open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL THEN 1 ELSE 0 END)`,
+ open: sql`sum(CASE WHEN ${questions.id} IS NOT NULL AND ${questions.answeredAt} IS NULL AND ${IS_QUESTION} THEN 1 ELSE 0 END)`,
})
.from(chatMessages)
.leftJoin(questions, eq(chatMessages.questionId, questions.id))
@@ -367,6 +368,8 @@ const EVENT_TEXT: Record { text: string; important?: boolean;
return { text: said[String(to)] ?? tr("• Статус: {to}", { to: statusRu(String(to)) }), important: ["review", "done", "blocked", "awaiting_approval"].includes(String(to)) };
},
progress: (p) => ({ text: `📈 ${cut(s(p.text), 1500)}`, author: "agent" }),
+ // PEP-149: the agent cannot go on (not a product decision) — a record, not a question.
+ blocker: (p) => ({ text: `⛔ ${tr("Агент не может продолжить: {what}", { what: cut(s(p.what), 1000) })}${s(p.tried) ? `\n${tr("Что уже пробовал: {tried}", { tried: cut(s(p.tried), 500) })}` : ""}`, author: "agent" }),
pm_comment: () => null, // handled separately: a person's message
// PEP-4: the project's repo moved to another Gitea namespace.
repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }),
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index d32cfffe..efa518ee 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -3,6 +3,7 @@ export * from "./notify.ts";
export * from "./project-file.ts";
export * from "./projects.ts";
export * from "./tasks.ts";
+export * from "./questions.ts";
export * from "./sessions.ts";
export * from "./rules.ts";
export * from "./settings.ts";
diff --git a/packages/core/src/notifications.ts b/packages/core/src/notifications.ts
index df268cce..d8c6d448 100644
--- a/packages/core/src/notifications.ts
+++ b/packages/core/src/notifications.ts
@@ -5,6 +5,7 @@ import { eq, inArray } from "drizzle-orm";
import { getSetting, setSetting } from "./settings.ts";
import { enqueueTelegram, type OutboxRow } from "./telegram.ts";
import type { Question } from "./tasks.ts";
+import { questionType } from "./questions.ts";
import type { User } from "./users.ts";
import { enqueuePush, type PushPayload } from "./webpush.ts";
import { addMasterMessage } from "./chats.ts";
@@ -139,13 +140,14 @@ export function inQuietHours(prefs: Pick, now
return from < to ? m >= from && m < to : m >= from || m < to;
}
-/** Which event a PM question stands for. */
-export function questionEvent(q: Pick, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent {
- if (q.kind !== "attention") return q.taskId == null && q.sessionId == null ? "releases" : "questions";
- if (ctx.taskStatus === "review") return "review";
- if (ctx.sessionStatus && ["failed", "rate_limited", "stalled"].includes(ctx.sessionStatus)) return "failures";
- if (q.taskId == null && q.sessionId == null) return "releases";
- return "questions";
+/** Which event a message for the person stands for (PEP-149: by its type). */
+export function questionEvent(q: Pick & Partial>, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent {
+ const type = questionType(q, ctx.taskStatus);
+ if (type === "done") return "review";
+ const projectLevel = q.taskId == null && q.sessionId == null;
+ if (type === "question") return projectLevel ? "releases" : "questions";
+ // A message of the factory itself: about the product as a whole, or about an agent's trouble.
+ return projectLevel ? "releases" : "failures";
}
/** Owner and members of a project (whether or not they paired Telegram). */
diff --git a/packages/core/src/questions.ts b/packages/core/src/questions.ts
new file mode 100644
index 00000000..8a238191
--- /dev/null
+++ b/packages/core/src/questions.ts
@@ -0,0 +1,56 @@
+// PEP-149: four kinds of agent messages for the person — question, done, progress, blocker.
+// The kind decides the route: only a `question` lands in «Ждут вашего ответа» and comes to
+// Telegram as a question; `done` waits for «Принять»; `progress` and a non-product `blocker`
+// are events of the story thread («События агентов») and never wake the person.
+import { questions } from "@peppa/db";
+import { sql, type SQL } from "drizzle-orm";
+import { PeppaError } from "./errors.ts";
+
+export const MESSAGE_TYPES = ["question", "done", "progress", "blocker"] as const;
+export type MessageType = (typeof MESSAGE_TYPES)[number];
+
+type Typed = { kind: string; msgType?: MessageType | null; options?: string[] | null; taskId?: number | null };
+
+/** The type a new row gets when the caller names none: anything a person must decide is a question. */
+export function defaultMessageType(q: Pick): MessageType | null {
+ if (q.kind !== "attention") return "question";
+ return q.options?.length ? "question" : null;
+}
+
+/**
+ * The type of a message: the stored one, else derived (rows before PEP-149 and messages of the
+ * factory itself). null — a factory message nobody has to answer (a failure, a limit, a release).
+ */
+export function questionType(q: Typed, taskStatus?: string | null): MessageType | null {
+ if (q.msgType) return q.msgType;
+ const d = defaultMessageType(q);
+ if (d) return d;
+ return q.taskId != null && taskStatus === "review" ? "done" : null;
+}
+
+/** True for what waits for a person: a question to answer or a finished story to accept. */
+export function needsPerson(q: Typed, taskStatus?: string | null): boolean {
+ const t = questionType(q, taskStatus);
+ return t === "question" || t === "done";
+}
+
+/** SQL twin of `questionType(q) === "question"` (counters of open questions). */
+export const IS_QUESTION: SQL = sql`(${questions.msgType} = 'question' OR (${questions.msgType} IS NULL AND (${questions.kind} != 'attention' OR json_array_length(${questions.options}) > 0)))`;
+
+export const ASK_MIN_OPTIONS = 2;
+export const ASK_MAX_OPTIONS = 4;
+
+/**
+ * Checks the answers of an agent's question: 2–4 different options and a default among them.
+ * Returns the options with the default first. The text of the refusal is for the agent.
+ */
+export function checkChoices(options: string[] | undefined, def: string | undefined): { options: string[]; defaultOption: string } {
+ const opts = [...new Set((options ?? []).map((o) => o.trim()).filter(Boolean))];
+ if (opts.length < ASK_MIN_OPTIONS || opts.length > ASK_MAX_OPTIONS) {
+ throw new PeppaError(`Not sent: a question to the owner needs ${ASK_MIN_OPTIONS}–${ASK_MAX_OPTIONS} answer options (got ${opts.length}). The owner answers with one tap — give the possible answers as \`options\` and your recommendation as \`default\`. If there is nothing to choose from, it is not a question: decide yourself, or use report_progress / report_blocker.`);
+ }
+ const d = def?.trim();
+ if (!d) throw new PeppaError("Not sent: name the `default` — the option you go on with while the owner has not answered (one of `options`).");
+ if (!opts.includes(d)) throw new PeppaError(`Not sent: \`default\` must be exactly one of \`options\` (${opts.map((o) => `«${o}»`).join(", ")}).`);
+ return { options: [d, ...opts.filter((o) => o !== d)], defaultOption: d };
+}
diff --git a/packages/core/src/review-card.ts b/packages/core/src/review-card.ts
index 42035ad0..94135c67 100644
--- a/packages/core/src/review-card.ts
+++ b/packages/core/src/review-card.ts
@@ -50,8 +50,10 @@ export async function sendReviewCard(db: Db, ref: TaskRef, text: string, session
if (gate?.ok) {
await clearReviewHold(db, ref.task.id);
// PEP-151: «готово» for the same head commit is one message, however many times it is sent.
- const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null };
- return session ? raiseSessionQuestion(db, session, "attention", text, undefined, false, state) : askPm(db, ref, { kind: "attention", text, ...state });
+ // PEP-149: it is a `done` message and always carries a link to the result.
+ const state = { topic: "review" as const, head: gate.pull?.head.sha ?? null, msgType: "done" as const };
+ const card = /https?:\/\//.test(text) ? text : `${text}\n\n${m("Посмотреть: {url}", { url: `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/t/${ref.key}` })}`;
+ return session ? raiseSessionQuestion(db, session, "attention", card, undefined, false, state) : askPm(db, ref, { kind: "attention", text: card, ...state });
}
const prev = await getReviewHold(db, ref.task.id);
await setReviewHold(db, ref.task.id, { ...prev, text, at: Date.now() });
diff --git a/packages/core/src/sessions.ts b/packages/core/src/sessions.ts
index ec796bea..4ca96cca 100644
--- a/packages/core/src/sessions.ts
+++ b/packages/core/src/sessions.ts
@@ -5,6 +5,7 @@ import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import { actorColumns } from "./actor.ts";
import type { Question, QuestionKind } from "./tasks.ts";
+import { defaultMessageType, type MessageType } from "./questions.ts";
import { userProjectIds } from "./users.ts";
import { questionStates, raiseOnce, type MessageTopic } from "./message-state.ts";
@@ -180,12 +181,12 @@ export async function raiseSessionQuestion(
text: string,
options?: string[],
awaitingHook = false,
- o: { topic?: MessageTopic; head?: string | null } = {},
+ { msgType, ...o }: { topic?: MessageTopic; head?: string | null; /** PEP-149: default — by kind (core/questions.ts). */ msgType?: MessageType | null } = {},
): Promise {
const row = await raiseOnce(db, { projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, ...o }, async () => {
const [created] = await db
.insert(questions)
- .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook })
+ .values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook, msgType: msgType ?? defaultMessageType({ kind, options }) })
.returning();
return created!;
});
diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts
index aeba839e..56d9e115 100644
--- a/packages/core/src/tasks.ts
+++ b/packages/core/src/tasks.ts
@@ -15,6 +15,7 @@ import { blockersOf, dependentsOf, type Blocker } from "./deps.ts";
import { taskBudgetView, type TaskBudgetView } from "./budgets.ts";
import { productNeeds, type ProductNeedView } from "./product-needs.ts";
import { raiseOnce, type MessageTopic } from "./message-state.ts";
+import { defaultMessageType, type MessageType } from "./questions.ts";
export type Task = typeof tasks.$inferSelect;
export type TaskStatus = (typeof taskStatus.enumValues)[number];
@@ -306,6 +307,10 @@ export interface NewQuestion {
topic?: MessageTopic;
/** Head commit of the result, when the caller knows it. */
head?: string | null;
+ /** PEP-149: what the message is for the person; default — by kind (core/questions.ts). */
+ msgType?: MessageType | null;
+ /** PEP-149: the option the agent goes on with meanwhile (one of `options`). */
+ defaultOption?: string;
}
/** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */
@@ -314,7 +319,7 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
const row = await raiseOnce(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: q.sessionId ?? null, kind: q.kind, text: q.text, options: q.options, topic, head }, async () => {
const [created] = await db
.insert(questions)
- .values({ projectId: ref.project.id, taskId: ref.task.id, ...q })
+ .values({ projectId: ref.project.id, taskId: ref.task.id, ...q, msgType: q.msgType ?? defaultMessageType(q) })
.returning();
return created!;
});
@@ -324,8 +329,8 @@ export async function askPm(db: Db, ref: TaskRef, { topic, head, ...q }: NewQues
}
/** A message for the PM about the project as a whole (releases), not about a task. */
-export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[] }): Promise {
- const [row] = await db.insert(questions).values({ projectId: project.id, ...q }).returning();
+export async function askPmProject(db: Db, project: Project, q: { kind: QuestionKind; text: string; options?: string[]; msgType?: MessageType | null }): Promise {
+ const [row] = await db.insert(questions).values({ projectId: project.id, ...q, msgType: q.msgType ?? defaultMessageType(q) }).returning();
await notify(db, { type: "question", questionId: row!.id });
return row!;
}
@@ -378,6 +383,19 @@ export async function reportProgress(db: Db, ref: TaskRef, text: string, session
return row!;
}
+/**
+ * PEP-149: the agent cannot go on and it is not a product decision — a `blocker` event in the
+ * story thread («События агентов»). The owner is not asked; what happens next is Peppa's job.
+ */
+export async function reportBlocker(db: Db, ref: TaskRef, b: { what: string; tried: string }, sessionId?: number) {
+ const [row] = await db
+ .insert(events)
+ .values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "blocker", payload: { what: b.what, tried: b.tried }, ...actorColumns(sessionId) })
+ .returning();
+ await notify(db, { type: "progress", eventId: row!.id });
+ return row!;
+}
+
function pick(o: T, keys: string[]): Record {
return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]]));
}
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index adf8164b..666b1fe1 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -377,6 +377,11 @@ export const questions = sqliteTable("questions", {
kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
text: text("text").notNull(),
options: text("options", { mode: "json" }).$type(),
+ // PEP-149: what the message is for the person — decides where it shows up (core/questions.ts).
+ // null: a message of the factory itself (failures, limits, releases) and rows before PEP-149.
+ msgType: text("msg_type", { enum: ["question", "done", "progress", "blocker"] }),
+ // PEP-149: the option the agent goes on with while nobody answered (one of `options`).
+ defaultOption: text("default_option"),
answer: text("answer"),
// "system": closed by Peppa itself (session stopped/resumed), not by a person.
answeredVia: text("answered_via", { enum: ["telegram", "web", "terminal", "system"] }),
diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts
index 5b632a87..0c8b0fe2 100644
--- a/packages/mcp/src/agent.ts
+++ b/packages/mcp/src/agent.ts
@@ -4,6 +4,9 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import {
askPm,
+ alertAdmins,
+ checkChoices,
+ reportBlocker,
createTask,
giteaForBot,
getIncident,
@@ -40,6 +43,7 @@ import {
import type { Db } from "@peppa/db";
import { requestReview, reviewGate, sayInDiscussion, storyBranch } from "@peppa/runner";
import { z } from "zod";
+import { m } from "@peppa/shared/i18n";
import { formatIncident, formatTask } from "./format.ts";
export interface AgentServerOptions {
@@ -216,24 +220,31 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
},
);
+ // PEP-149: four kinds of messages to the owner — question (here), done (Peppa sends it itself
+ // after green checks), progress (report_progress), blocker (report_blocker).
+ const optionsArg = z.array(z.string()).optional().describe("2–4 possible answers, shown to the owner as buttons");
+ const defaultArg = z.string().optional().describe("Your recommendation — exactly one of `options`; you go on with it while the owner has not answered");
+
tool(
"ask_pm",
- "Ask the PM a PRODUCT question only — what users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. Put your recommended answer FIRST in options. Don't wait: keep working with your recommendation in this turn; the PM's answer arrives later as a message, and you adjust if it differs.",
+ "Ask the owner a PRODUCT question — the ONLY kind of message that reaches their «Ждут вашего ответа» and Telegram. What users see or get, business terms, a secret/account only they can provide — in plain words for a non-engineer. NEVER technical (stack, libraries, architecture, data model, CI, git, runners, tests, permissions): decide those yourself and record them in design.md. REQUIRED: `options` (2–4 answers as buttons) and `default` (your recommendation, one of the options) — without them the call is refused. Don't wait: keep working with your default in this turn; the owner's answer arrives later as a message, and you adjust if it differs.",
{
task: taskArg,
question: z.string().min(5).describe("One product question in plain words, 1–2 sentences of context, no jargon"),
- options: z.array(z.string()).max(6).optional().describe("Answers shown as buttons; your recommendation first"),
+ options: optionsArg,
+ default: defaultArg,
},
- async ({ task, question, options }) => {
+ async ({ task, question, options, default: def }) => {
const ref = await resolve(task);
- const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId });
- return `Question #${q.id} sent to the PM. Don't wait for the answer: continue with your recommended option now (note it in design.md); if the PM answers differently, the answer arrives as a message and you adjust.`;
+ const c = checkChoices(options, def);
+ const q = await askPm(db, ref, { kind: "question", msgType: "question", text: question, options: c.options, defaultOption: c.defaultOption, sessionId });
+ return `Question #${q.id} sent to the owner. Don't wait for the answer: continue with «${c.defaultOption}» now (note it in design.md); if the owner answers differently, the answer arrives as a message and you adjust.`;
},
);
tool(
"report_progress",
- "Log a short progress note on a story (visible to the PM in the web UI / Telegram digest).",
+ "Log a short progress note on a story. It is a `progress` message: it goes to the story thread in «События агентов» and never wakes the owner (not in «Ждут вашего ответа», not in Telegram). Don't use it to ask for anything.",
{ task: taskArg, text: z.string().min(3) },
async ({ task, text }) => {
const ref = await resolve(task);
@@ -242,6 +253,31 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
},
);
+ tool(
+ "report_blocker",
+ "Say that you cannot go on with the story: what stops you and what you already tried. Use it only after trying another approach or a mock. A PRODUCT blocker (only the owner can decide or give something: `product: true`) goes to the owner as a question — `options` (2–4) and `default` are required. Any other blocker (access, a broken service, CI, git, a limit) is recorded in the story thread and does NOT go to the owner: Peppa's administrators see it. After the call end your turn — Peppa wakes you when there is something to do.",
+ {
+ task: taskArg,
+ what: z.string().min(5).describe("What stops you, in plain words"),
+ tried: z.string().min(3).describe("What you already tried"),
+ product: z.boolean().optional().describe("true: only the owner can unblock it (a product decision, an account or a key only they have)"),
+ options: optionsArg,
+ default: defaultArg,
+ },
+ async ({ task, what, tried, product, options, default: def }) => {
+ const ref = await resolve(task);
+ if (product) {
+ const c = checkChoices(options, def);
+ const q = await askPm(db, ref, { kind: "question", msgType: "question", text: what, options: c.options, defaultOption: c.defaultOption, sessionId });
+ return `Blocker sent to the owner as question #${q.id}. End your turn — the answer arrives as a message.`;
+ }
+ const e = await reportBlocker(db, ref, { what, tried }, sessionId);
+ // Not the owner's business: the administrators of the factory hear about it.
+ await alertAdmins(db, `blocker:${e.id}`, `⛔ ${ref.key}: ${m("Агент не может продолжить: {what}", { what })}\n${m("Что уже пробовал: {tried}", { tried })}`, () => {}).catch(() => 0);
+ return `Blocker recorded on ${ref.key} (the owner is not asked about it). End your turn now; Peppa wakes you when there is something to do.`;
+ },
+ );
+
tool(
"list_incidents",
"List production errors (Bugsink incidents) of a project: id, status, title, where, release, event count, linked story.",
diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts
index 368b5e01..e606617d 100644
--- a/packages/mcp/src/manager.ts
+++ b/packages/mcp/src/manager.ts
@@ -46,6 +46,7 @@ import {
setTaskAgentSettings,
type AgentSettings,
type AgentSettingsPatch,
+ needsPerson,
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
@@ -511,11 +512,13 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ
.leftJoin(tasks, eq(questions.taskId, tasks.id))
.where(and(inArray(projects.id, ids), isNull(questions.answeredAt)))
.orderBy(asc(questions.id));
- if (!rows.length) return "Inbox is empty — agents need nothing from you.";
- return rows
+ // PEP-149: only questions and stories waiting for «accept»; factory messages are not the inbox.
+ const waiting = rows.filter(({ q, status }) => needsPerson(q, status));
+ if (!waiting.length) return "Inbox is empty — agents need nothing from you.";
+ return waiting
.map(({ q, key, number, status }) => {
const kind = q.kind === "attention" && status === "review" ? "ready for review (answer 'accept' or a comment)" : q.kind;
- return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}`;
+ return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${q.text.replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}${q.defaultOption ? `\n default (the agent goes on with it meanwhile): ${q.defaultOption}` : ""}`;
})
.join("\n");
});
diff --git a/packages/runner/src/ci-feedback.ts b/packages/runner/src/ci-feedback.ts
index 422fc5f2..7e65b509 100644
--- a/packages/runner/src/ci-feedback.ts
+++ b/packages/runner/src/ci-feedback.ts
@@ -4,6 +4,9 @@
import { m } from "@peppa/shared/i18n";
import {
askPm,
+ getSetting,
+ setSetting,
+ pendingReview,
giteaForBot,
listSessions,
listTasks,
@@ -41,6 +44,31 @@ async function activeSessionId(db: Db, taskId: number): Promise {
return (await listSessions(db, { active: true, taskId }))[0]?.id ?? null;
}
+const wokeKey = (taskId: number) => `ci.woke:${taskId}`;
+
+/**
+ * PEP-149: an agent that ended its turn waiting for the checks is woken by Peppa, not by the
+ * person: every check of the PR head passed and the story is still in work → one message per
+ * commit. Returns true when the agent was told.
+ */
+export async function wakeOnGreen(db: Db, ref: TaskRef, r: Pick, gitea: GiteaClient = giteaForBot()): Promise {
+ if (!["proposing", "in_progress"].includes(ref.task.status)) return false;
+ const [s] = await listSessions(db, { active: true, taskId: ref.task.id });
+ if (!s || (s.status !== "idle" && s.status !== "waiting_input")) return false;
+ if ((await getSetting(db, wokeKey(ref.task.id))) === r.sha) return false;
+ if (await pendingReview(db, ref.task.id)) return false;
+ const { giteaOwner: o, giteaRepo: repo } = ref.project;
+ const n = taskPrNumber(ref.project, ref.task.prUrl) ?? r.prNumber ?? (r.branch ? (await gitea.openPullForBranch(o, repo, r.branch))?.number : null);
+ if (!n) return false;
+ const gate = await prGate({ ...ref, task: { ...ref.task, prUrl: `/${o}/${repo}/pulls/${n}` } }, gitea);
+ // Only the commit the PR stands on now; a branch behind the base is updated by Peppa itself.
+ if (!(gate.ok || gate.behind) || !gate.summary || gate.pull?.head.sha !== r.sha) return false;
+ await setSetting(db, wokeKey(ref.task.id), r.sha);
+ await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s.id, type: "checks_passed_wake", payload: { sha: r.sha, pr: n } });
+ await sendToSession(db, s.id, `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}). Если работа закончена — update_task(status: review${ref.task.prUrl ? "" : ", pr_url"}); если нет — продолжай.`);
+ return true;
+}
+
export interface CheckOutcome {
task: string | null;
/** What Peppa did: nothing, told the agent, restarted it, asked the PM, reset the counter. */
@@ -56,6 +84,7 @@ export async function recordCheck(db: Db, project: Project, r: CheckReport): Pro
if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" };
if (r.state === "success") {
+ await wakeOnGreen(db, ref, r).catch(() => {});
const [red] = await db
.select({ id: checkRuns.id })
.from(checkRuns)
diff --git a/packages/runner/src/hook.ts b/packages/runner/src/hook.ts
index c355aaa6..08594939 100644
--- a/packages/runner/src/hook.ts
+++ b/packages/runner/src/hook.ts
@@ -31,6 +31,9 @@ import {
demoNote,
reviewRejections,
getSession,
+ getProject,
+ needsPerson,
+ reportProgress,
logSessionEvent,
peppaInputSentAt,
pendingSessionQuestions,
@@ -186,13 +189,13 @@ async function askQuestion(db: Db, s: SessionView, input: HookInput) {
}
const NUDGE = (key: string) =>
- `Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Если упёрся в архитектурный стоппер — ask_pm и закончи ход. Когда стори готова — PR и update_task(status: review).`;
+ `Продолжай работу над ${key} по tasks.md и правилам Пеппы, не жди PM. Когда стори готова — PR и update_task(status: review). Ждёшь проверок, ревьюера или мержа — просто закончи ход: Пеппа разбудит тебя сама, PM об этом писать не нужно. Не можешь продолжать — report_blocker (что мешает, что пробовал) и закончи ход.`;
/**
* The agent finished a turn. Pending question → PM already has it. Task in review →
* "ready for review" (accept / comment). Task still in work → ask the agent to keep going
* (Claude only, via the Stop hook's block decision), at most MAX_AUTO_NUDGES in a row.
- * Otherwise the PM gets "the session is waiting for you".
+ * Otherwise (PEP-149) the last reply becomes a `progress` record — the person is not woken.
* Returns the Stop-hook output to print, if any.
*/
async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue: boolean): Promise {
@@ -209,7 +212,8 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
- if ((await pendingSessionQuestions(db, s.id)).length > 0) {
+ // PEP-149: only what a person must answer holds the agent; a factory message does not.
+ if ((await pendingSessionQuestions(db, s.id)).some((q) => needsPerson(q, s.taskStatus))) {
await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
return null;
}
@@ -262,9 +266,11 @@ async function turnEnd(db: Db, s: SessionView, text: string | null, canContinue:
await logSessionEvent(db, s, "auto_continue", { n: s.autoNudges + 1 });
return { decision: "block", reason: NUDGE(s.taskKey ?? "стори") };
}
- // PEP-151: the agent retells the same state in new words — one message, not one per turn.
- await raiseSessionQuestion(db, s, "attention", clip(text ?? m("Агент закончил ход и ждёт вашего ответа.")), undefined, false, { topic: "turn" });
- await updateSession(db, s.id, { status: "waiting_input", lastActivityAt: new Date() });
+ // PEP-149: the end of a turn is progress, not a question — a record in the story thread
+ // («События агентов»); nobody is woken. Peppa wakes the agent when there is something to do
+ // (checks passed or failed, the reviewer, a rebase, a comment of the person).
+ if (text && task) await reportProgress(db, { project: await getProject(db, s.projectKey), task, key: s.taskKey ?? "" }, clip(text), s.id);
+ await updateSession(db, s.id, { status: "idle", lastActivityAt: new Date() });
return null;
}
diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts
index 61a699a8..9236ff86 100644
--- a/packages/runner/src/recovery.ts
+++ b/packages/runner/src/recovery.ts
@@ -282,7 +282,9 @@ export async function idleStopTick(db: Db, o: { now: Date; cfg: WatchdogSettings
if (o.cfg.idleStopHours <= 0) return 0;
let stopped = 0;
for (const s of await listSessions(db, { active: true })) {
- if (s.status !== "waiting_input" || !s.taskId || !s.lastActivityAt) continue;
+ // PEP-149: an agent that ended its turn without a question is `idle` while its story is in work.
+ const turnOver = s.status === "waiting_input" || (s.status === "idle" && ["proposing", "in_progress"].includes(s.taskStatus ?? ""));
+ if (!turnOver || !s.taskId || !s.lastActivityAt) continue;
const idleMs = o.now.getTime() - s.lastActivityAt.getTime();
if (idleMs < o.cfg.idleStopHours * 3600_000) continue;
if ((await pendingSessionQuestions(db, s.id)).some((q) => q.kind !== "attention")) continue;
--
2.45.2
From 4c0a08bef27e830e7dfdd3bea796e9d085cefcfc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:29:29 +0500
Subject: [PATCH 012/215] PEP-149: translations, help, agent rules, scenario
tests
Co-Authored-By: Claude Fable 5.2
---
apps/bot/package.json | 2 +-
apps/bot/src/bot.ts | 3 +-
apps/web/app/(app)/help/page.tsx | 7 +
packages/core/src/help-texts.ts | 29 ++
packages/shared/src/i18n/en/bot.ts | 1 -
packages/shared/src/i18n/en/help.ts | 1 +
packages/shared/src/i18n/en/project.ts | 1 -
packages/shared/src/i18n/en/story.ts | 5 +
packages/shared/src/i18n/kk/bot.ts | 1 -
packages/shared/src/i18n/kk/help.ts | 1 +
packages/shared/src/i18n/kk/project.ts | 1 -
packages/shared/src/i18n/kk/story.ts | 5 +
packages/testkit/test/agent-messages.test.ts | 301 +++++++++++++++++++
packages/testkit/test/product-help.test.ts | 2 +-
template/RULES.md | 30 +-
15 files changed, 378 insertions(+), 12 deletions(-)
create mode 100644 packages/testkit/test/agent-messages.test.ts
diff --git a/apps/bot/package.json b/apps/bot/package.json
index 5e87285a..1313b8b1 100644
--- a/apps/bot/package.json
+++ b/apps/bot/package.json
@@ -3,7 +3,7 @@
"version": "0.0.0",
"private": true,
"type": "module",
- "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
+ "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts", "./render": "./src/render.ts" },
"bin": { "peppa-bot": "./bin/peppa-bot" },
"scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
"dependencies": {
diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts
index 851119d2..7ea26041 100644
--- a/apps/bot/src/bot.ts
+++ b/apps/bot/src/bot.ts
@@ -937,7 +937,8 @@ export function createBot(o: BotOptions) {
} else if (kind === "q") {
const q = await getQuestion(db, id).catch(() => null);
const text = q && choice ? choiceToAnswer(q, choice) : null;
- toast = q && text ? await answer(q, text) : tr("Вопрос не найден");
+ // PEP-149: the «continue» button of an earlier message answers nothing.
+ toast = q && text ? await answer(q, text) : q && choice === "cont" ? tr("Кнопка устарела — ответьте на сообщение текстом.") : tr("Вопрос не найден");
} else if (kind === "i" && (choice === "backlog" || choice === "start" || choice === "ignore")) {
// Decision on a new production error (PEP-58).
try {
diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx
index e20b4de6..e8dc3b2b 100644
--- a/apps/web/app/(app)/help/page.tsx
+++ b/apps/web/app/(app)/help/page.tsx
@@ -102,6 +102,12 @@ async function ProductHelp() {
{rich(t("Новый терминал — раннер без стори: в «Раннерах» или на вкладке «Сессии» проекта выберите проект, имя, агента и напишите промпт (можно голосом — кнопка «Голосом» в браузерах с распознаванием речи). После ходов такой раннер не пингует — им управляете вы в терминале. Получилась работа — «Оформить стори» в карточке раннера: стори создаётся в работе, раннер ведёт её дальше. Раннер можно переименовать."))}
{rich(t("Раннеры и стори — «⋯ Настройки проекта → Раннеры» (и на странице стори — для неё одной): «один раннер на стори» (по умолчанию) или «раннер ведёт очередь стори» — стори достаётся свободному раннеру, при лимите раннеров проекта ждёт в его очереди, а «Принять» не останавливает раннер, а даёт ему следующую стори; переход — «свежий контекст» (тот же терминал, новый разговор) или «один разговор». «Свой git worktree на раннер» — у каждого раннера своя копия и ветка task/…, параллельные стори не мешают друг другу; копия убирается, когда всё запушено. В карточке раннера — история его стори и очередь."))}
{rich(t("Изоляция и хосты — там же: «Контейнер на раннер» запускает агента в docker-образе раннера — он видит только свою рабочую копию, работает на подписке из пула проекта и не видит токенов Peppa FACTORY и чужих проектов; хуки, MCP и git идут в Peppa FACTORY через релей и только к репозиторию проекта (PR агент открывает инструментом open_pull_request). «Где запускать раннеры» — Mac Peppa FACTORY или отмеченные хосты: раннер уходит на наименее занятый онлайн-хост, там клонируется рабочая копия, а терминал, ввод и ответы работают как обычно. Хосты подключает суперадмин в разделе «Хосты» (SSH-ключ Peppa FACTORY на хосте, tmux и docker); недоступный хост помечается «офлайн», его раннеры не считаются упавшими."))}
+
{rich(t("Сообщения агента — четырёх типов. Вопрос — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. Готово — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. Ход работы — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. Блокер — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY."))}
{rich(t("Главная — вопросы агентов (только архитектурные стопперы) и «готово к ревью», активные раннеры и проекты. Отвечать можно в вебе, Telegram или через MCP. Список проектов и «Новый проект» — в разделе Проекты."))}
diff --git a/packages/core/src/help-texts.ts b/packages/core/src/help-texts.ts
index 40c18d20..1bb3da1e 100644
--- a/packages/core/src/help-texts.ts
+++ b/packages/core/src/help-texts.ts
@@ -18,6 +18,8 @@ export interface ProductHelpText {
problem: string;
/** PEP-145: where the product is. */
product: string;
+ /** PEP-149: the four kinds of messages an agent sends. */
+ messages: { title: string; items: [string, string, string, string] };
more: string;
moreLink: string;
}
@@ -62,6 +64,15 @@ export const PRODUCT_HELP: Record = {
question: "Агент задал вопрос? Он появится на Главной и в Telegram. Ответьте кнопкой или своими словами — агент продолжит работу.",
problem: "Что-то не работает в самой Peppa FACTORY? Нажмите «Сообщить о проблеме» внизу любой страницы: напишите, что случилось, и приложите скриншот. В Telegram то же самое — отправьте боту /problem. Что стало с обращением, видно в разделе «Обращения».",
product: "Где посмотреть продукт? На странице проекта и на Главной есть кнопка «Открыть продукт». Ссылка появляется сама, в первый же день проекта; если её пока нет, на её месте написано, что происходит, — делать ничего не нужно.",
+ messages: {
+ title: "Какие сообщения присылает агент",
+ items: [
+ "Вопрос — нужно ваше решение. У него всегда есть кнопки с вариантами ответа; один из них агент выберет сам, если вы не ответите.",
+ "Готово — задачу можно посмотреть и принять. Приходит только когда проверки прошли, вместе со ссылкой на результат.",
+ "Ход работы — что агент уже сделал. Это лежит в «Событиях агентов» в чате проекта; отвечать не нужно, уведомлений не будет.",
+ "Агент не может продолжить — если дело в вашем продукте, он задаст вопрос с вариантами. С остальным Peppa FACTORY разбирается сама.",
+ ],
+ },
more: "Хотите видеть всё, что делают агенты, и полный справочник? Включите вид «Инженер».",
moreLink: "Открыть Настройки",
},
@@ -101,6 +112,15 @@ export const PRODUCT_HELP: Record = {
question: "Агент сұрақ қойды ма? Ол Басты бетте және Telegram-да пайда болады. Батырмамен немесе өз сөзіңізбен жауап беріңіз — агент жұмысын жалғастырады.",
problem: "Peppa FACTORY-дің өзінде бірдеңе жұмыс істемей тұр ма? Кез келген беттің төменгі жағындағы «Мәселе туралы хабарлау» батырмасын басыңыз: не болғанын жазып, скриншот тіркеңіз. Telegram-да да солай — ботқа /problem жіберіңіз. Өтінішіңіздің не болғаны «Өтініштер» бөлімінде көрінеді.",
product: "Өнімді қайдан көруге болады? Жоба бетінде және Басты бетте «Өнімді ашу» батырмасы бар. Сілтеме жобаның бірінші күнінде-ақ өзі пайда болады; әзірге жоқ болса, оның орнында не болып жатқаны жазылған — ештеңе істеудің қажеті жоқ.",
+ messages: {
+ title: "Агент қандай хабарламалар жібереді",
+ items: [
+ "Сұрақ — сіздің шешіміңіз керек. Оның әрқашан жауап нұсқалары бар батырмалары болады; жауап бермесеңіз, агент біреуін өзі таңдайды.",
+ "Дайын — тапсырманы қарап, қабылдауға болады. Тек тексерулер өткенде, нәтижеге сілтемемен бірге келеді.",
+ "Жұмыс барысы — агент не істеп үлгергені. Бұл жоба чатындағы «Агенттер оқиғаларында» тұрады; жауап берудің қажеті жоқ, хабарландыру келмейді.",
+ "Агент жалғастыра алмайды — мәселе сіздің өніміңізде болса, ол нұсқалары бар сұрақ қояды. Қалғанын Peppa FACTORY өзі шешеді.",
+ ],
+ },
more: "Агенттердің барлық іс-әрекетін және толық анықтамалықты көргіңіз келе ме? «Инженер» көрінісін қосыңыз.",
moreLink: "Баптауларды ашу",
},
@@ -140,6 +160,15 @@ export const PRODUCT_HELP: Record = {
question: "Did an agent ask a question? It appears on Home and in Telegram. Answer with a button or in your own words — the agent carries on.",
problem: "Is something not working in Peppa FACTORY itself? Press “Report a problem” at the bottom of any page: write what happened and attach a screenshot. In Telegram it is the same — send /problem to the bot. What became of your report is shown in “Reports”.",
product: "Where is the product? The project page and Home have an «Open product» button. The link appears by itself on the project's first day; if it is not there yet, the same place says what is happening — you don't need to do anything.",
+ messages: {
+ title: "What messages an agent sends",
+ items: [
+ "Question — your decision is needed. It always has buttons with answers; the agent picks one of them itself if you don't reply.",
+ "Done — the task can be looked at and accepted. It comes only when the checks have passed, with a link to the result.",
+ "Progress — what the agent has done so far. It stays in “Agent events” in the project chat; no reply is needed and no notification comes.",
+ "The agent cannot go on — if it is about your product, it asks a question with options. Peppa FACTORY sorts out the rest itself.",
+ ],
+ },
more: "Want to see everything the agents do and the full reference? Turn on the “Engineer” view.",
moreLink: "Open Settings",
},
diff --git a/packages/shared/src/i18n/en/bot.ts b/packages/shared/src/i18n/en/bot.ts
index 3e5e6b01..b630e2eb 100644
--- a/packages/shared/src/i18n/en/bot.ts
+++ b/packages/shared/src/i18n/en/bot.ts
@@ -94,7 +94,6 @@ export const bot: Dict = {
"✅ Принять": "✅ Accept",
"Есть замечания — ответь на это сообщение, агент доработает.": "Have remarks? Reply to this message and the agent will rework it.",
"🔁 Перезапустить": "🔁 Restart",
- "▶️ Продолжай": "▶️ Continue",
"Или ответь на это сообщение — текст уйдёт в сессию.": "Or reply to this message — the text goes into the session.",
"в Telegram": "in Telegram",
"в вебе": "on the web",
diff --git a/packages/shared/src/i18n/en/help.ts b/packages/shared/src/i18n/en/help.ts
index 7a171d70..89abe659 100644
--- a/packages/shared/src/i18n/en/help.ts
+++ b/packages/shared/src/i18n/en/help.ts
@@ -287,4 +287,5 @@ export const help: Dict = {
" — {n} вопроса ниже.": " — {n} questions below.",
" — {n} вопросов ниже.": " — {n} questions below.",
"Тихо… Агентам от тебя ничего не нужно, мопс спит.": "All quiet… The agents don't need anything from you, the pug is asleep.",
+ "Сообщения агента — четырёх типов. Вопрос — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. Готово — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. Ход работы — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. Блокер — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY.": "Agent messages come in four types. Question — your product decision is needed: always with answer buttons and a default option; only it lands in “Agent questions” on Home and comes to Telegram as a question. Done — the task can be accepted: it comes only after the checks have passed, with a link to the result. Progress — what the agent did; it stays in “Agent events” in the project chat and wakes nobody. Blocker — the agent cannot go on: if it is about the product, it asks you with answer options; everything else goes to the factory administrators. The “Continue” button is gone: Peppa FACTORY itself wakes an agent that waits for checks.",
};
diff --git a/packages/shared/src/i18n/en/project.ts b/packages/shared/src/i18n/en/project.ts
index 496a1da5..91408982 100644
--- a/packages/shared/src/i18n/en/project.ts
+++ b/packages/shared/src/i18n/en/project.ts
@@ -127,7 +127,6 @@ export const project: Dict = {
Разрешить: "Allow",
Всегда: "Always",
Запретить: "Deny",
- Продолжай: "Continue",
"Замечание — вернёт на доработку": "Remark — sends it back for rework",
"Свой ответ": "Your answer",
Ответ: "Answer",
diff --git a/packages/shared/src/i18n/en/story.ts b/packages/shared/src/i18n/en/story.ts
index 8a984261..0eab6477 100644
--- a/packages/shared/src/i18n/en/story.ts
+++ b/packages/shared/src/i18n/en/story.ts
@@ -416,4 +416,9 @@ export const story: Dict = {
"ждёт сброса лимита": "waiting for the limit reset",
закончил: "finished",
"остановился с ошибкой": "stopped with an error",
+ "Ждут «Принять»": "Waiting for “Accept”",
+ "Если не ответите, агент продолжит по варианту «{option}».": "If you don't answer, the agent goes on with “{option}”.",
+ "Агент не может продолжить: {what}": "The agent cannot go on: {what}",
+ "Что уже пробовал: {tried}": "What it already tried: {tried}",
+ "Кнопка устарела — ответьте на сообщение текстом.": "This button no longer works — reply to the message with text.",
};
diff --git a/packages/shared/src/i18n/kk/bot.ts b/packages/shared/src/i18n/kk/bot.ts
index 6b8ca6b1..0bc4ff1f 100644
--- a/packages/shared/src/i18n/kk/bot.ts
+++ b/packages/shared/src/i18n/kk/bot.ts
@@ -93,7 +93,6 @@ export const bot: Dict = {
"✅ Принять": "✅ Қабылдау",
"Есть замечания — ответь на это сообщение, агент доработает.": "Ескертулер болса — осы хабарламаға жауап беріңіз, агент жетілдіреді.",
"🔁 Перезапустить": "🔁 Қайта іске қосу",
- "▶️ Продолжай": "▶️ Жалғастыр",
"Или ответь на это сообщение — текст уйдёт в сессию.": "Немесе осы хабарламаға жауап беріңіз — мәтін сессияға кетеді.",
"в Telegram": "Telegram-да",
"в вебе": "вебте",
diff --git a/packages/shared/src/i18n/kk/help.ts b/packages/shared/src/i18n/kk/help.ts
index 8ad3592f..85c03c92 100644
--- a/packages/shared/src/i18n/kk/help.ts
+++ b/packages/shared/src/i18n/kk/help.ts
@@ -235,4 +235,5 @@ export const help: Dict = {
" — {n} вопроса ниже.": " — төменде {n} сұрақ.",
" — {n} вопросов ниже.": " — төменде {n} сұрақ.",
"Тихо… Агентам от тебя ничего не нужно, мопс спит.": "Тыныш… Агенттерге сізден ештеңе керек емес, мопс ұйықтап жатыр.",
+ "Сообщения агента — четырёх типов. Вопрос — нужно ваше решение о продукте: всегда с вариантами ответа кнопками и вариантом по умолчанию; только он попадает в «Вопросы агентов» на Главной и приходит в Telegram как вопрос. Готово — задачу можно принять: приходит только после того, как проверки прошли, со ссылкой на результат. Ход работы — что агент сделал; лежит в «Событиях агентов» в чате проекта и никого не будит. Блокер — агент не может продолжить: если дело в продукте, он спросит вас с вариантами ответа, остальное уходит администраторам фабрики. Кнопки «Продолжай» больше нет: агента, который ждёт проверок, будит сама Peppa FACTORY.": "Агент хабарламалары төрт түрлі. Сұрақ — өнім туралы сіздің шешіміңіз керек: әрқашан жауап нұсқалары батырмалармен және әдепкі нұсқамен; тек осы түрі Басты беттегі «Агенттердің сұрақтары» бөліміне түседі және Telegram-ға сұрақ ретінде келеді. Дайын — тапсырманы қабылдауға болады: тек тексерулер өткеннен кейін, нәтижеге сілтемемен келеді. Жұмыс барысы — агент не істегені; жоба чатындағы «Агенттер оқиғаларында» тұрады және ешкімді мазаламайды. Кедергі — агент жалғастыра алмайды: мәселе өнімде болса, ол сізден жауап нұсқаларымен сұрайды, қалғаны фабрика әкімшілеріне кетеді. «Жалғастыр» батырмасы енді жоқ: тексерулерді күтіп тұрған агентті Peppa FACTORY өзі оятады.",
};
diff --git a/packages/shared/src/i18n/kk/project.ts b/packages/shared/src/i18n/kk/project.ts
index 4b07da39..97f53c64 100644
--- a/packages/shared/src/i18n/kk/project.ts
+++ b/packages/shared/src/i18n/kk/project.ts
@@ -98,7 +98,6 @@ export const project: Dict = {
"Разрешить": "Рұқсат беру",
"Всегда": "Әрқашан",
"Запретить": "Тыйым салу",
- "Продолжай": "Жалғастырыңыз",
"Замечание — вернёт на доработку": "Ескерту — пысықтауға қайтарады",
"Свой ответ": "Өз жауабыңыз",
"Ответ": "Жауап",
diff --git a/packages/shared/src/i18n/kk/story.ts b/packages/shared/src/i18n/kk/story.ts
index 6735bea4..a2a6086c 100644
--- a/packages/shared/src/i18n/kk/story.ts
+++ b/packages/shared/src/i18n/kk/story.ts
@@ -381,4 +381,9 @@ export const story: Dict = {
"ждёт сброса лимита": "лимит тасталуын күтуде",
"закончил": "аяқтады",
"остановился с ошибкой": "қатемен тоқтады",
+ "Ждут «Принять»": "«Қабылдау» күтуде",
+ "Если не ответите, агент продолжит по варианту «{option}».": "Жауап бермесеңіз, агент «{option}» нұсқасымен жалғастырады.",
+ "Агент не может продолжить: {what}": "Агент жалғастыра алмайды: {what}",
+ "Что уже пробовал: {tried}": "Не істеп көрді: {tried}",
+ "Кнопка устарела — ответьте на сообщение текстом.": "Батырма ескірді — хабарламаға мәтінмен жауап беріңіз.",
};
diff --git a/packages/testkit/test/agent-messages.test.ts b/packages/testkit/test/agent-messages.test.ts
new file mode 100644
index 00000000..473f241d
--- /dev/null
+++ b/packages/testkit/test/agent-messages.test.ts
@@ -0,0 +1,301 @@
+// PEP-149, spec agent-messages: four kinds of agent messages — question, done, progress, blocker —
+// and where each of them goes. mock-claude runners, mock Gitea.
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { after, before, describe, test } from "node:test";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
+import { chatMessages, events, questions } from "@peppa/db";
+import { and, eq } from "drizzle-orm";
+import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
+import { MockGitea } from "../src/mock-gitea.ts";
+
+process.env.PEPPA_SECRET = "mock-secret-for-tests";
+process.env.PEPPA_WEB_URL = "http://peppa.test";
+const { createAgentServer } = await import("@peppa/mcp/agent");
+const { renderQuestion, choiceToAnswer } = await import("@peppa/bot/render");
+
+const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-msg-")), "gitea"));
+const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
+const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
+
+before(async () => {
+ await gitea.start();
+ process.env.GITEA_URL = gitea.url;
+ process.env.GITEA_TOKEN = BOT.token;
+ gitea.addUser(BOT);
+});
+after(async () => {
+ await gitea.stop();
+ await teardown();
+});
+
+type Turns = Parameters[0]["turns"];
+
+/** A story with an open PR (task/-1) in mock Gitea; checks are set by the test. */
+async function prTask(turns: Turns) {
+ const tp = await project({ turns });
+ const proj = await core.getProject(db, tp.key);
+ const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS });
+ writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
+ gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
+ gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
+ const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" });
+ const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
+ const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
+ const set = (check: string, state: string) => gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${check}`, state);
+ const ref = () => core.resolveTask(db, tp.taskKey);
+ return { tp, proj, sha, prUrl, set, ref };
+}
+
+async function agent(projectKey: string, sessionId?: number) {
+ const [a, b] = InMemoryTransport.createLinkedPair();
+ await createAgentServer(db, { defaultKey: projectKey, sessionId }).connect(a);
+ const client = new Client({ name: "mock-agent", version: "0" });
+ await client.connect(b);
+ return async (name: string, args: Record = {}) => {
+ const r = await client.callTool({ name, arguments: args });
+ return { text: (r.content as Array<{ text: string }>)[0]!.text, isError: !!r.isError };
+ };
+}
+
+const projectQuestions = (projectId: number) => db.select().from(questions).where(eq(questions.projectId, projectId));
+const taskEvents = (taskId: number, type: string) => db.select().from(events).where(and(eq(events.taskId, taskId), eq(events.type, type)));
+
+describe("Конец хода — это ход работы, а не вопрос", () => {
+ test("Агент закончил ход, статус задачи тот же", async () => {
+ const tp = await project({ turns: [[{ say: "Начал." }], [{ say: "Продолжаю." }], [{ say: "Жду проверок" }]] });
+ const p = await core.getProject(db, tp.key);
+ await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
+ const sid = await tp.start();
+ // Two nudges of the Stop hook, then the turn really ends.
+ await tp.waitStatus(sid, "idle");
+ const task = await tp.task();
+ assert.equal(task.status, "in_progress");
+
+ // Nothing for the person: no message at all (the bot sends to Telegram only what is in `questions`).
+ assert.deepEqual(await projectQuestions(p.id), [], "no question, nothing in «Ждут вашего ответа» or Telegram");
+
+ // «События агентов»: a record in the story thread.
+ const progress = await taskEvents(task.id, "progress");
+ assert.equal(progress.length, 1);
+ assert.equal((progress[0]!.payload as { text: string }).text, "Жду проверок");
+ await core.syncChats(db);
+ const chat = await core.ensureProjectChat(db, p.id);
+ const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`)));
+ const record = thread.find((m) => m.text.includes("Жду проверок"));
+ assert.ok(record, "the reply is in the story thread");
+ assert.equal(record.kind, "event");
+ assert.equal(record.important, false, "not in the master feed");
+ assert.equal(record.questionId, null);
+ await runner.stopSession(db, sid);
+ });
+
+ test("У агента есть открытый вопрос", async () => {
+ const tp = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], default: "Синий" } }, { say: "Спросил." }]] });
+ const p = await core.getProject(db, tp.key);
+ await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress" });
+ const sid = await tp.start();
+ await tp.waitStatus(sid, "waiting_input");
+ const qs = await projectQuestions(p.id);
+ assert.equal(qs.length, 1);
+ assert.equal(core.questionType(qs[0]!, "in_progress"), "question");
+ assert.deepEqual(await taskEvents((await tp.task()).id, "progress"), [], "no progress record on top of the question");
+ await runner.stopSession(db, sid);
+ });
+});
+
+describe("Тип сообщения определяет маршрут", () => {
+ const base = { taskId: 1, sessionId: 1, msgType: null, options: null } as const;
+
+ test("Вопрос попадает в «Ждут вашего ответа»", () => {
+ assert.equal(core.questionType({ ...base, kind: "question", options: ["Синий", "Зелёный"] }, "in_progress"), "question");
+ assert.equal(core.questionType({ ...base, kind: "permission", options: ["allow", "always", "deny"] }), "question");
+ assert.equal(core.questionType({ ...base, kind: "attention", options: ["🚀 Выкатить"] }), "question", "a factory message with answers to choose from");
+ assert.equal(core.needsPerson({ ...base, kind: "question" }, "in_progress"), true);
+ assert.equal(core.questionEvent({ ...base, kind: "question" }, { taskStatus: "in_progress" }), "questions");
+ });
+
+ test("Сообщение о сбое не попадает в «Ждут вашего ответа»", () => {
+ const failure = { ...base, kind: "attention" as const };
+ assert.equal(core.questionType(failure, "in_progress"), null);
+ assert.equal(core.needsPerson(failure, "in_progress"), false);
+ assert.equal(core.questionEvent(failure, { taskStatus: "in_progress", sessionStatus: "failed" }), "failures");
+ // «Готово» — отдельным блоком: ждёт «Принять», но это не вопрос.
+ assert.equal(core.questionType({ ...failure, msgType: "done" }, "review"), "done");
+ assert.equal(core.questionType(failure, "review"), "done", "rows before PEP-149");
+ assert.equal(core.needsPerson(failure, "review"), true);
+ assert.equal(core.questionEvent(failure, { taskStatus: "review" }), "review");
+ });
+
+ test("Счётчик открытых вопросов чата считает только вопросы", async () => {
+ const tp = await project({ turns: [] });
+ const p = await core.getProject(db, tp.key);
+ const ref = await core.resolveTask(db, tp.taskKey);
+ await core.askPm(db, ref, { kind: "attention", text: "агент остановился с ошибкой" });
+ await core.askPm(db, ref, { kind: "question", text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], defaultOption: "Синий" });
+ const u = await core.upsertUserFromGitea(db, { id: 9149, login: "mock-pm-149" }, { access_token: "a" });
+ await core.setProjectOwner(db, p.id, u.id);
+ const chat = (await core.listChats(db, u)).find((c) => c.projectId === p.id)!;
+ assert.equal(chat.open, 1);
+ });
+});
+
+describe("«Готово» шлёт платформа после проверок", () => {
+ test("Проверки ещё идут", async () => {
+ const t = await prTask([]);
+ t.set("typecheck", "success");
+ t.set("test", "pending");
+ await core.updateTask(db, await t.ref(), { prUrl: t.prUrl });
+ const sent = await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью");
+ assert.equal(sent, null, "held");
+ assert.deepEqual(await projectQuestions(t.proj.id), [], "the owner got nothing");
+ assert.ok(await core.getReviewHold(db, (await t.ref()).task.id));
+
+ // Red checks: still nothing.
+ t.set("test", "failure");
+ assert.equal(await core.sendReviewCard(db, await t.ref(), "✅ Задача готова к ревью"), null);
+ assert.deepEqual(await projectQuestions(t.proj.id), []);
+ });
+
+ test("Проверки прошли", async () => {
+ const t = await prTask([]);
+ t.set("typecheck", "success");
+ t.set("test", "success");
+ await core.updateTask(db, await t.ref(), { status: "review", prUrl: t.prUrl });
+ const sent = await core.sendReviewCard(db, await t.ref(), `✅ Задача ${t.tp.taskKey} готова к ревью · Результат: ${t.prUrl}`);
+ assert.ok(sent);
+ assert.equal(sent.msgType, "done");
+ assert.ok(sent.text.includes(t.prUrl), "the link to the result");
+ assert.equal(core.questionType(sent, "review"), "done");
+
+ // A card without any link gets the link to the task page.
+ const bare = await core.sendReviewCard(db, await t.ref(), "✅ Готово");
+ assert.match(bare!.text, new RegExp(`http://peppa\\.test/t/${t.tp.taskKey}`));
+ });
+});
+
+describe("Платформа будит агента, когда проверки прошли", () => {
+ test("Проверки прошли, агент ждал; повторный отчёт о том же коммите", async () => {
+ const t = await prTask([[{ say: "PR открыт." }], [{ say: "Жду." }], [{ say: "Жду проверок" }], [{ say: "Перевожу." }], [{ say: "Ок." }], [{ say: "Ок." }]]);
+ await core.updateTask(db, await t.ref(), { status: "in_progress" });
+ t.set("typecheck", "pending");
+ t.set("test", "pending");
+ const sid = await t.tp.start();
+ await t.tp.waitStatus(sid, "idle");
+ const woke = () => t.tp.log().filter((e) => e.ev === "prompt" && String(e.prompt).includes("Проверки PR"));
+
+ // One check of two passed: not yet.
+ t.set("typecheck", "success");
+ await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "typecheck", state: "success" });
+ assert.equal(woke().length, 0);
+
+ t.set("test", "success");
+ await runner.recordCheck(db, t.proj, { sha: t.sha, branch: `task/${t.tp.taskKey}`, check: "test", state: "success" });
+ await waitFor("the agent is told the checks passed", async () => woke().length || undefined);
+ assert.match(String(woke()[0]!.prompt), /прошли/);
+ assert.deepEqual(await projectQuestions(t.proj.id), [], "the person is not involved");
+
+ await t.tp.waitStatus(sid, "idle");
+ assert.equal(await runner.wakeOnGreen(db, await t.ref(), { sha: t.sha, branch: `task/${t.tp.taskKey}` }), false, "once per commit");
+ assert.equal(woke().length, 1);
+ await runner.stopSession(db, sid);
+ });
+});
+
+describe("Вопрос агента — с вариантами и вариантом по умолчанию", () => {
+ test("Вопрос с вариантами принят", async () => {
+ const tp = await project({ turns: [] });
+ const p = await core.getProject(db, tp.key);
+ const call = await agent(tp.key);
+ const r = await call("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", options: ["Нет", "Да"], default: "Да" });
+ assert.equal(r.isError, false, r.text);
+ const [q] = await projectQuestions(p.id);
+ assert.equal(q!.msgType, "question");
+ assert.equal(q!.defaultOption, "Да");
+ assert.deepEqual(q!.options, ["Да", "Нет"], "the default goes first");
+ });
+
+ for (const [name, args, why] of [
+ ["без вариантов", {}, /2–4 answer options/],
+ ["один вариант", { options: ["Да"], default: "Да" }, /2–4 answer options/],
+ ["пять вариантов", { options: ["1", "2", "3", "4", "5"], default: "1" }, /2–4 answer options/],
+ ["без варианта по умолчанию", { options: ["Да", "Нет"] }, /`default`/],
+ ["вариант по умолчанию не из списка", { options: ["Да", "Нет"], default: "Может быть" }, /one of `options`/],
+ ] as const) {
+ test(`Вопрос без вариантов отклонён: ${name}`, async () => {
+ const tp = await project({ turns: [] });
+ const p = await core.getProject(db, tp.key);
+ const r = await (await agent(tp.key))("ask_pm", { task: tp.taskKey, question: "Показывать цену сразу?", ...args });
+ assert.equal(r.isError, true);
+ assert.match(r.text, why);
+ assert.deepEqual(await projectQuestions(p.id), [], "no question");
+ });
+ }
+});
+
+describe("Блокер идёт по своему маршруту", () => {
+ test("Непродуктовый блокер", async () => {
+ const tp = await project({ turns: [] });
+ const p = await core.getProject(db, tp.key);
+ const r = await (await agent(tp.key))("report_blocker", { task: tp.taskKey, what: "нет доступа к серверу сборки", tried: "повторил три раза" });
+ assert.equal(r.isError, false, r.text);
+ assert.deepEqual(await projectQuestions(p.id), [], "the owner is not asked");
+ const task = await tp.task();
+ assert.equal((await taskEvents(task.id, "blocker")).length, 1);
+ await core.syncChats(db);
+ const chat = await core.ensureProjectChat(db, p.id);
+ const thread = await db.select().from(chatMessages).where(and(eq(chatMessages.chatId, chat.id), eq(chatMessages.threadKey, `task:${task.id}`)));
+ const record = thread.find((m) => m.text.includes("нет доступа к серверу сборки"));
+ assert.ok(record);
+ assert.equal(record.important, false);
+ assert.match(record.text, /повторил три раза/);
+ });
+
+ test("Продуктовый блокер без вариантов; с вариантами — вопрос", async () => {
+ const tp = await project({ turns: [] });
+ const p = await core.getProject(db, tp.key);
+ const call = await agent(tp.key);
+ const refused = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true });
+ assert.equal(refused.isError, true);
+ assert.match(refused.text, /2–4 answer options/);
+ assert.deepEqual(await projectQuestions(p.id), []);
+
+ const ok = await call("report_blocker", { task: tp.taskKey, what: "Нужен аккаунт платёжного сервиса", tried: "сделал на моке", product: true, options: ["Оставить демо", "Дам аккаунт"], default: "Оставить демо" });
+ assert.equal(ok.isError, false, ok.text);
+ const [q] = await projectQuestions(p.id);
+ assert.equal(core.questionType(q!), "question");
+ assert.equal(q!.defaultOption, "Оставить демо");
+ });
+});
+
+describe("Нет кнопки «Продолжай»", () => {
+ const q = (over: Record) => ({ id: 7, projectId: 1, taskId: 1, sessionId: null, kind: "attention", text: "агент остановился с ошибкой", options: null, msgType: null, defaultOption: null, answer: null, answeredVia: null, telegramMessageId: null, awaitingHook: false, reminders: 0, createdAt: new Date(), answeredAt: null, ...over }) as never;
+ const ctx = { taskKey: "PEP-1", taskTitle: "t", taskStatus: "in_progress", session: null, webUrl: "http://peppa.test" };
+
+ test("Сообщение фабрики в Telegram", () => {
+ const r = renderQuestion(q({}), ctx);
+ assert.deepEqual(r.buttons, [], "no buttons at all");
+ assert.doesNotMatch(r.text, /Продолжай/);
+ });
+
+ test("Вопрос — кнопки вариантов и вариант по умолчанию", () => {
+ const r = renderQuestion(q({ kind: "question", text: "Какой цвет?", options: ["Синий", "Зелёный"], msgType: "question", defaultOption: "Синий" }), ctx);
+ assert.deepEqual(r.buttons.flat().map((b) => b.text), ["Синий", "Зелёный"]);
+ assert.match(r.text, /продолжит по варианту «Синий»/);
+ assert.match(r.text, /своим текстом/);
+ });
+
+ test("Старая кнопка «Продолжай»", () => {
+ assert.equal(choiceToAnswer(q({}), "cont"), null, "nothing goes to the agent");
+ });
+
+ test("В вебе и боте кнопки нет", () => {
+ const root = join(import.meta.dirname, "../../..");
+ for (const f of ["apps/web/components/cards.tsx", "apps/bot/src/render.ts"]) {
+ assert.doesNotMatch(readFileSync(join(root, f), "utf8").replace(/\/\/.*|\{\/\*.*?\*\/\}/g, ""), /Продолжай|"cont"/, f);
+ }
+ });
+});
diff --git a/packages/testkit/test/product-help.test.ts b/packages/testkit/test/product-help.test.ts
index d5f121c4..b113bd50 100644
--- a/packages/testkit/test/product-help.test.ts
+++ b/packages/testkit/test/product-help.test.ts
@@ -4,7 +4,7 @@ import { readFileSync } from "node:fs";
import { describe, test } from "node:test";
import { HELP_LANGS, PRODUCT_HELP, type ProductHelpText } from "@peppa/core";
-const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
+const strings = (t: ProductHelpText) => [t.title, t.lead, t.question, t.product, t.messages.title, ...t.messages.items, t.more, t.moreLink, ...t.sections.flatMap((s) => [s.title, ...s.steps, s.note])];
/** «Нельзя» column of docs/glossary.md. */
function forbidden(): string[] {
diff --git a/template/RULES.md b/template/RULES.md
index 3736d5a1..e7468854 100644
--- a/template/RULES.md
+++ b/template/RULES.md
@@ -56,7 +56,8 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
выполнения и коммить маленькими шагами: `PEP-42: <что сделано>`.
- `peppa.report_progress` на каждые 2–3 пункта или раз в ~30 минут.
- Не заканчивай ход посреди работы: если остановишься без вопроса PM, Пеппа попросит
- продолжить, а на третий раз позовёт PM.
+ продолжить; на третий раз твоя реплика уйдёт в ход работы, а PM никто не позовёт
+ (см. «Сообщения PM: четыре типа»).
- Тесты и линтеры проекта должны проходить до PR.
### Завершение
@@ -226,13 +227,32 @@ git, тесты, раннеры — решаешь ты сам и пишешь,
платёжный сервис подключить), доступ, который есть только у PM (аккаунт, ключ сервиса).
- Нельзя: всё техническое — стек, библиотеки, архитектура, данные, CI и проверки, git,
раннеры, разрешения, «как лучше сделать». Это решаешь ты.
-- `peppa.ask_pm`: один вопрос, 1–2 предложения контекста, твой рекомендуемый вариант —
- первым в `options`. **Не жди ответа и не заканчивай ход**: продолжай по своему
- варианту и запиши его в `design.md`. Ответ придёт позже сообщением — если он другой,
- переделаешь.
+- `peppa.ask_pm`: один вопрос, 1–2 предложения контекста, **обязательно** `options`
+ (2–4 варианта ответа — PM отвечает одной кнопкой) и `default` (твой рекомендуемый
+ вариант, один из `options`); без них вызов отклоняется. **Не жди ответа и не заканчивай
+ ход**: продолжай по `default` и запиши его в `design.md`. Ответ придёт позже
+ сообщением — если он другой, переделаешь.
- Нужен ключ или аккаунт, которого нет, — делай на моке (раздел ниже) и объяви его через
`peppa.declare_needs`: владелец получит список «что дать и куда вставить».
+## Сообщения PM: четыре типа
+
+Всё, что ты сообщаешь PM, — одного из четырёх типов. От типа зависит, увидит ли он это.
+
+| Тип | Что это | Как отправить | Куда попадает |
+|---|---|---|---|
+| **question** | нужно решение PM о продукте | `ask_pm` с `options` (2–4) и `default` | «Ждут вашего ответа», Telegram — единственный тип, который будит PM |
+| **done** | стори готова, можно принять | сам не шлёшь: `update_task(status: review)`, сообщение отправит Пеппа после зелёных проверок, со ссылкой на результат | «Ждут „Принять“», Telegram |
+| **progress** | ход работы | `report_progress`; последняя реплика твоего хода тоже становится progress | «События агентов» (тред стори); PM не будит |
+| **blocker** | не можешь продолжать | `report_blocker` (что мешает, что уже пробовал) | продуктовый (`product: true` + `options` и `default`) — PM как question; остальное — в тред стори и администраторам Пеппы, не PM |
+
+- Последняя реплика хода — не способ что-то спросить: PM её не получит. Нужен ответ — `ask_pm`.
+- Ждёшь проверок, ревьюера или мержа — просто закончи ход. Пеппа разбудит тебя сама: красные
+ проверки придут с логом, зелёные — сообщением «проверки прошли», замечания — текстом.
+ Писать PM «жду проверок» не нужно и некуда.
+- Кнопки «Продолжай» у PM нет: никто не подтолкнёт тебя вручную. Не можешь двигаться —
+ сначала смени подход или сделай мок, потом `report_blocker`.
+
## Если MCP `peppa` недоступен
Работай напрямую через OpenSpec CLI (`openspec list`, `openspec show `,
--
2.45.2
From ceef0d7e2f9a001b96417b222e9edec81d98c80d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:30:40 +0500
Subject: [PATCH 013/215] PEP-149: story page shows only questions; AGENTS.md
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 1 +
apps/web/app/(app)/t/[key]/page.tsx | 4 +++-
2 files changed, 4 insertions(+), 1 deletion(-)
diff --git a/AGENTS.md b/AGENTS.md
index 577e31f0..3f1dcd15 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,6 +43,7 @@
- **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики»
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
- **Слова по режиму (PEP-123)**: `@peppa/shared/wording` — `wording(mode)`: `task(форма)` / `Task` / `tasks(n)` («задача» в «Продакте», «стори» в «Инженере»), `runner(форма)` («агент» / «раннер»), формы `nom|gen|dat|acc|ins|pre|pl|genPl|datPl|accPl|insPl|prePl`. Веб: серверный компонент — `const w = await words()` (`lib/auth.ts`), клиентский — `useWords()` (`components/Words.tsx`, `WordsProvider` в раскладке). Что читает только инженер (репозиторий, раннеры, модель, секреты, бюджет, ревьюер в «Настройках проекта», команда терминала, адрес кода, подробная автономность) — под `w.engineer`. Тексты без читателя (события чатов `EVENT_TEXT`, вопросы и сообщения PM из runner, Telegram, push, подписи из core) — всегда словами «Продакта»: «задача», «агент», «Peppa FACTORY», «вы», «Результат:» вместо «PR:». Промпты агентам, MCP и CLI — прежние слова. Страница задачи, полоса лимитов и «Помощь» — PEP-120/121/122. Тест `wording.test.ts`
+- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0019; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts`
- **Комментарий уточняет постановку (PEP-115)**: `pm_comment` к стори в бэклоге без живого агента → `storyRefineTick` в тике вачдога (`runner/story-refine.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`/`_MODEL`), промпт `refinePrompt` (core/story-refine.ts: контекст `intakeContext`, текущая постановка, обсуждение, новые комментарии), ответ — JSON аналитика (`parseAnalystNote`) → описание через `intakeDescription` («Исходный запрос» сохраняется, `originalRequest`) + заметка аналитика `intake_note` в «Обсуждении» стори. Курсор `refine.task:`, комментарии старше `PEPPA_STORY_REFINE_MAX_AGE_MIN` (60) не трогаются, сбой — одна заметка без повторов, стори взяли в работу до ответа — описание не меняется, роли PEP-84 не закончили — ждёт; `PEPPA_STORY_REFINE=off`. `refinePending` — «Аналитик уточняет постановку…» и исключение из `readyBacklog`. Подпись поля — `apps/web/lib/comment-hint.ts`. Мок — роль `refine` в `mock-intake` (`slowMs`); тест `story-refine.test.ts`
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
- **Страница задачи в режиме «Продакт» (PEP-120)**: `t/[key]/page.tsx` при `uiMode()` = product рисует `components/StoryProduct.tsx` — карточку из `storyProductView` (core/story-product.ts, чистая функция; все тексты — `STORY_PRODUCT_TEXT`; `plainStep` не показывает пункт tasks.md с путями, файлами и идентификаторами): что сейчас, «Шаг N из M», «Посмотреть» (`reviewPreview().previewUrl`), что нужно от вас, что дальше, открытые вопросы (`QuestionCard plain`: команда разрешения — под «Подробнее»), «Принять» (`acceptStoryAction`) и «Поправить» (`fixStoryAction` → `fixStory` в runner/flow.ts: только из ревью, комментарий + закрыть «готово к ревью» + `moveTask in_progress` + замечание агенту). Прежнее содержимое страницы и блоки правой панели — под ссылкой «Подробнее» (`?more=1`, также `?tab=`/`?edit=`; закрыто — терминал не монтируется), без правой панели и значка статуса. «Инженер» — без изменений. Тест `story-product.test.ts`
diff --git a/apps/web/app/(app)/t/[key]/page.tsx b/apps/web/app/(app)/t/[key]/page.tsx
index b75d6fce..53320906 100644
--- a/apps/web/app/(app)/t/[key]/page.tsx
+++ b/apps/web/app/(app)/t/[key]/page.tsx
@@ -42,6 +42,7 @@ import {
taskCiSummary,
type GateResult,
productUrls,
+ questionType,
} from "@peppa/core";
import { checkRuns } from "@peppa/db";
import { desc, eq } from "drizzle-orm";
@@ -236,7 +237,8 @@ export default async function StoryPage({ params, searchParams }: { params: Prom
);
// What a product manager reads first: open questions (the «готово к ревью» message is the card's own buttons).
- const productQuestions = questions.filter((q) => !q.answeredAt && !(q.kind === "attention" && task.status === "review")).reverse();
+ // PEP-149: only messages of type `question`; failures and other factory messages stay under «Подробнее».
+ const productQuestions = questions.filter((q) => !q.answeredAt && questionType(q, task.status) === "question").reverse();
const productView = storyProductView({
status: task.status,
archived: !!task.archivedAt,
--
2.45.2
From 11d6bbafdf0fa6bdada54e4e5a141ef5141b3d90 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:30:48 +0500
Subject: [PATCH 014/215] PEP-149: project memory
Co-Authored-By: Claude Fable 5.2
---
.peppa/memory.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/.peppa/memory.md b/.peppa/memory.md
index aedf6b99..cd62bdfa 100644
--- a/.peppa/memory.md
+++ b/.peppa/memory.md
@@ -44,3 +44,4 @@
- Обращения (PEP-143): вся логика в `core/feedback.ts`, агент — `feedbackTick` (runner/feedback.ts, одна попытка, сбой → суперадмину без разбора); новый текст — в `i18n/{en,kk}/feedback.ts`; файл в Telegram — outbox-метод `sendPhoto` с `params.photo_path`; слово «команда» (люди) словарь запрещает — перефразируй или `glossary-ignore`; загрузка файлов из веба — route handler с multipart, не server action (предел 1 МБ).
- Без повторов (PEP-151): `raiseSessionQuestion`/`askPm` при том же состоянии задачи (отпечаток, `core/message-state.ts`) не создают вопрос, а обновляют прежний и возвращают его id (закрытый открывается снова); свободный текст агента — `topic: "turn"`, «готово» — `topic: "review"`. Состояние — settings `question.state:`, `chat.repeat:`. В тесте нужен второй вопрос — меняй статус, коммит в check_runs или текст.
- Продукт по ссылке (PEP-145): ссылка и её статус — только через `projectProduct` (`fix`/`broken`/`preparing`) и `productUrls`/`productLookLine`; системную стори заводит `productLinkTick` (в тестах выключен в helpers.ts, свой тест делает `delete process.env.PEPPA_PRODUCT_LINK`); «Показывать всем» — `getPublishMode`/`autoPublish` (вернул true — вопрос с кнопкой не слать). Менял `template/` — после мержа `scripts/push-template.sh`.
+- Типы сообщений (PEP-149): пишешь пользователю — выбери тип: вопрос только с вариантами (`askPm`/`raiseSessionQuestion` с `msgType`, `defaultOption`), «готово» — только `sendReviewCard`, ход работы/блокер — события `progress`/`blocker`; читать тип — `questionType`/`needsPerson` (core/questions.ts), не `kind === "attention"`. Конец хода агента вопроса не создаёт: в тестах жди статус сессии `idle`, а не `waitQuestion(sid, "attention")`.
--
2.45.2
From 0a5eff6485c0aa1a01fbb30f3a52b60cfcd95014 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:33:55 +0500
Subject: [PATCH 015/215] =?UTF-8?q?PEP-149:=20old=20tests=20follow=20the?=
=?UTF-8?q?=20new=20contract=20(no=20=C2=ABagent=20ended=20its=20turn?=
=?UTF-8?q?=C2=BB=20message,=20ask=5Fpm=20with=20options)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
.../pep-149-agent-message-kinds/tasks.md | 24 +++++++++----------
packages/testkit/test/autonomy.test.ts | 14 +++++------
packages/testkit/test/bot.test.ts | 18 ++++++++------
packages/testkit/test/budgets.test.ts | 2 +-
packages/testkit/test/cjm.test.ts | 8 ++++---
packages/testkit/test/limits.test.ts | 4 ++--
packages/testkit/test/oauth.test.ts | 2 +-
packages/testkit/test/usage.test.ts | 2 +-
8 files changed, 40 insertions(+), 34 deletions(-)
diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/pep-149-agent-message-kinds/tasks.md
index e470d634..83ed215d 100644
--- a/openspec/changes/pep-149-agent-message-kinds/tasks.md
+++ b/openspec/changes/pep-149-agent-message-kinds/tasks.md
@@ -1,22 +1,22 @@
# Tasks: PEP-149
## 1. Ядро
-- [ ] 1.1 Миграция: `questions.msg_type`, `questions.default_option`
-- [ ] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion`
-- [ ] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна
-- [ ] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`)
+- [x] 1.1 Миграция: `questions.msg_type`, `questions.default_option`
+- [x] 1.2 `core/questions.ts`: типы, `questionType`, условие «ждёт человека»; тип и вариант по умолчанию в `askPm` / `askPmProject` / `raiseSessionQuestion`
+- [x] 1.3 `sendReviewCard`: тип `done`, ссылка на результат обязательна
+- [x] 1.4 Событие `blocker` в «Событиях агентов» (`EVENT_TEXT`)
## 2. Агент
-- [ ] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle`
-- [ ] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит)
-- [ ] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress`
+- [x] 2.1 `turnEnd`: конец хода → `progress`, сессия `idle`; остановка по простою для `idle`
+- [x] 2.2 Платформа будит агента после зелёных проверок (один раз на коммит)
+- [x] 2.3 MCP: `ask_pm` с вариантами и вариантом по умолчанию, `report_blocker`, описание `report_progress`
## 3. Веб и бот
-- [ ] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике)
-- [ ] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP
-- [ ] 3.3 Переводы en/kk
+- [x] 3.1 Веб: карточка без «Продолжай», вариант по умолчанию; «Ждут вашего ответа», `navCounts`, `/api/attention`, счётчики чатов — только question (+ done в счётчике)
+- [x] 3.2 Бот: без «Продолжай», вариант по умолчанию, push и счётчик только для question/done; `list_inbox` удалённого MCP
+- [x] 3.3 Переводы en/kk
## 4. Правила, помощь, проверки
-- [ ] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа
-- [ ] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов
+- [x] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа
+- [x] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов
- [ ] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта
diff --git a/packages/testkit/test/autonomy.test.ts b/packages/testkit/test/autonomy.test.ts
index 83015627..06330323 100644
--- a/packages/testkit/test/autonomy.test.ts
+++ b/packages/testkit/test/autonomy.test.ts
@@ -42,17 +42,17 @@ describe("autonomous cycle", () => {
assert.equal((await core.getQuestion(db, review.id)).answer, "✅ Принято");
});
- test("after two nudges in a row the PM is called; a human answer resets the counter", async () => {
+ test("after two nudges in a row the turn ends as progress — the PM is not called (PEP-149); a human message resets the counter", async () => {
const p = await project({
turns: [[{ mcp: "update_task", args: { task: "1", status: "in_progress" } }, { say: "шаг 1" }], [{ say: "шаг 2" }], [{ say: "застрял на шаге 3" }], [{ say: "понял" }]],
});
const sid = await p.start();
- const q = await p.waitQuestion(sid, "attention");
- assert.match(q.text, /застрял на шаге 3/);
+ await p.waitStatus(sid, "idle");
assert.equal(await nudges(sid), runner.MAX_AUTO_NUDGES);
- await runner.answerAndDeliver(db, q.id, "делай вариант Б", "telegram");
- assert.equal((await p.session(sid)).autoNudges, 0);
- await p.waitLog("answer delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б"));
+ assert.deepEqual(await p.pending(sid), [], "nobody is asked");
+ await runner.sendToSession(db, sid, "делай вариант Б");
+ await p.waitLog("message delivered", (e) => e.ev === "prompt" && String(e.prompt).includes("вариант Б"));
+ await waitFor("the counter is reset", async () => (await p.session(sid)).autoNudges === 0);
await runner.stopSession(db, sid);
});
@@ -71,7 +71,7 @@ describe("autonomous cycle", () => {
describe("task board", () => {
test("moving a card to In progress starts an agent; back to Backlog stops it", async () => {
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?" } }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Стоппер?", options: ["Да", "Нет"], default: "Да" } }]] });
let ref = await core.resolveTask(db, p.taskKey);
assert.equal(runner.columnOf(ref.task.status), "backlog");
const { started } = await runner.moveTask(db, ref, "in_progress");
diff --git a/packages/testkit/test/bot.test.ts b/packages/testkit/test/bot.test.ts
index 9d63e985..a9f1e97d 100644
--- a/packages/testkit/test/bot.test.ts
+++ b/packages/testkit/test/bot.test.ts
@@ -79,7 +79,7 @@ describe("pairing", () => {
describe("answering from Telegram", () => {
test("question with options: button press reaches the agent, message is closed", async () => {
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду." }], [{ say: "Ок." }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду." }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
@@ -138,7 +138,9 @@ describe("answering from Telegram", () => {
test("free-text reply to a 'session is waiting' alert is typed into the session", async () => {
const p = await project({ turns: [[{ say: "Сделал черновик. Что дальше?" }], [{ say: "Понял." }]] });
const sid = await p.start();
- const q = await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
+ // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
+ const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Сделал черновик. Что дальше?");
const m = await messageFor(q.id);
assert.match(m.text, /Что дальше/);
tg.userSends(PM, "добавь тесты\nи README", m.message_id);
@@ -154,7 +156,7 @@ describe("several users", () => {
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 mine = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Секрет проекта PM?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
const sid = await mine.start();
const q = await mine.waitQuestion(sid, "question");
const m = await messageFor(q.id);
@@ -198,7 +200,7 @@ describe("review", () => {
describe("staleness and reliability", () => {
test("answered in the terminal: Telegram message is closed and old buttons do nothing", async () => {
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Порт сервиса?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
@@ -213,7 +215,9 @@ describe("staleness and reliability", () => {
test("an update re-delivered after a restart is not replayed", async () => {
const p = await project({ turns: [[{ say: "Жду указаний." }], [{ say: "Ок." }], [{ say: "лишний ход" }]] });
const sid = await p.start();
- const q = await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
+ // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
+ const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Жду указаний.");
const m = await messageFor(q.id);
const updateId = tg.userSends(PM, "сделай раз", m.message_id);
await p.waitLog("delivered once", isPrompt("сделай раз"));
@@ -227,7 +231,7 @@ describe("staleness and reliability", () => {
test("outbox retries after 429 (retry_after) and 5xx", async () => {
tg.failNext("sendMessage", 429, 1);
tg.failNext("sendMessage", 500);
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?" } }], [{ say: "Ок." }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Проверка ретраев?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
@@ -259,7 +263,7 @@ describe("staleness and reliability", () => {
});
test("tmux killed while waiting: answer is saved, PM told the session is down", async () => {
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?" } }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Что с API?", options: ["Да", "Нет"], default: "Да" } }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
const m = await messageFor(q.id);
diff --git a/packages/testkit/test/budgets.test.ts b/packages/testkit/test/budgets.test.ts
index f77c4a59..3ca60c6c 100644
--- a/packages/testkit/test/budgets.test.ts
+++ b/packages/testkit/test/budgets.test.ts
@@ -21,7 +21,7 @@ const budgetQuestion = (taskId: number) =>
async function spentRunner() {
const p = await project({ turns: [[{ usage: { input: 1000, output: 500 } }, { say: "Сделал часть." }]] });
const sid = await p.start();
- await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
await waitFor("usage recorded", async () => core.usageTotals((await core.getSession(db, sid)).usage).total === 1500);
return { p, sid, task: await p.task() };
}
diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts
index 47ba8e10..d996e9ab 100644
--- a/packages/testkit/test/cjm.test.ts
+++ b/packages/testkit/test/cjm.test.ts
@@ -76,7 +76,7 @@ describe("Claude: task lifecycle", () => {
describe("Claude: questions to the PM", () => {
test("ask_pm question answered from Telegram is typed into the session", async () => {
const p = await project({
- turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"] } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]],
+ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]],
});
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
@@ -90,7 +90,9 @@ describe("Claude: questions to the PM", () => {
test("multi-line answer arrives as one prompt (bracketed paste)", async () => {
const p = await project({ turns: [[{ say: "Что дальше?" }], [{ say: "Понял." }]] });
const sid = await p.start();
- const q = await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
+ // PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
+ const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Что дальше?");
await runner.answerAndDeliver(db, q.id, "строка один\nстрока два", PM);
const e = await p.waitLog("pasted prompt", isPrompt("строка один"));
assert.equal(e.prompt, "строка один\nстрока два");
@@ -127,7 +129,7 @@ describe("Claude: questions to the PM", () => {
});
test("typing in the terminal answers whatever the session was waiting for", async () => {
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?" } }], [{ say: "Ок." }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
await runner.sendToSession(db, sid, "назови peppa-api");
diff --git a/packages/testkit/test/limits.test.ts b/packages/testkit/test/limits.test.ts
index 1d4e23e6..11ebd45c 100644
--- a/packages/testkit/test/limits.test.ts
+++ b/packages/testkit/test/limits.test.ts
@@ -90,9 +90,9 @@ describe("Защита от зацикливания", () => {
test("Предел достигнут", async () => {
const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 120 } }]] });
const sid = await p.start();
- await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
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 runner.sendToSession(db, sid, "дальше");
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.equal(s.resumeAt, null, "no more auto-resumes today");
diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts
index 70f94d04..61e178a8 100644
--- a/packages/testkit/test/oauth.test.ts
+++ b/packages/testkit/test/oauth.test.ts
@@ -94,7 +94,7 @@ async function mcpAs(user: typeof owner) {
describe("PM tools over MCP", () => {
test("list, create, move (starts an agent), inbox, answer; strangers see nothing", async () => {
- const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"] } }], [{ say: "Ок." }]] });
+ const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "2", question: "Какой порт?", options: ["8080", "3000"], default: "8080" } }], [{ say: "Ок." }]] });
const proj = await core.getProject(db, p.key);
await core.setProjectOwner(db, proj.id, owner.id);
const { client, call } = await mcpAs(owner);
diff --git a/packages/testkit/test/usage.test.ts b/packages/testkit/test/usage.test.ts
index 2c9a4ffe..8bade025 100644
--- a/packages/testkit/test/usage.test.ts
+++ b/packages/testkit/test/usage.test.ts
@@ -56,7 +56,7 @@ describe("Расход сессии из statusLine и transcript", () => {
const p = await project({ turns: [[{ usage: { input: 1200, output: 300, costUsd: 0.42, context: { used: 50000, size: 200000 }, fiveHour: 42, sevenDay: 18 } }, { say: "Готово." }]] });
const sid = await p.start();
await p.waitLog("statusline", (e) => e.ev === "statusline");
- await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
const s = await core.getSession(db, sid);
const t = core.usageTotals(s.usage);
assert.equal(t.total, 1500);
--
2.45.2
From 5f738942e0c5cad7230bb894b392dc16626a760e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:48:31 +0500
Subject: [PATCH 016/215] PEP-149: remaining old tests follow the new
end-of-turn behaviour
Co-Authored-By: Claude Fable 5.2
---
.../changes/pep-149-agent-message-kinds/tasks.md | 2 +-
packages/testkit/test/cjm.test.ts | 16 ++++++++--------
packages/testkit/test/claude-live.test.ts | 10 ++++++----
packages/testkit/test/rotation.test.ts | 4 ++--
packages/testkit/test/sandbox-hosts.test.ts | 6 +++---
5 files changed, 20 insertions(+), 18 deletions(-)
diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/pep-149-agent-message-kinds/tasks.md
index 83ed215d..621df364 100644
--- a/openspec/changes/pep-149-agent-message-kinds/tasks.md
+++ b/openspec/changes/pep-149-agent-message-kinds/tasks.md
@@ -19,4 +19,4 @@
## 4. Правила, помощь, проверки
- [x] 4.1 `template/RULES.md`, «Помощь», AGENTS.md — четыре типа
- [x] 4.2 Тесты по сценариям (`agent-messages.test.ts`), правка старых тестов
-- [ ] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта
+- [x] 4.3 lint, typecheck, build, тесты; проверка экранов; память проекта
diff --git a/packages/testkit/test/cjm.test.ts b/packages/testkit/test/cjm.test.ts
index d996e9ab..0baf4e8f 100644
--- a/packages/testkit/test/cjm.test.ts
+++ b/packages/testkit/test/cjm.test.ts
@@ -244,7 +244,7 @@ describe("Claude: failures and recovery", () => {
test("tmux session killed from outside → failed, PM alerted", async () => {
const p = await project({ turns: [[{ say: "Работаю." }]] });
const sid = await p.start();
- await p.waitStatus(sid, "waiting_input");
+ await p.waitStatus(sid, "idle");
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
await tick();
assert.equal((await p.session(sid)).status, "failed");
@@ -258,7 +258,7 @@ describe("Claude: failures and recovery", () => {
const cleared = await p.waitLog("cleared", (e) => e.ev === "clear");
await waitFor("new conversation id stored", async () => (await p.session(sid)).conversationId === cleared.newConversationId);
assert.notEqual(before, cleared.newConversationId);
- await p.waitStatus(sid, "waiting_input");
+ await p.waitStatus(sid, "idle");
await runner.stopSession(db, sid);
});
@@ -282,14 +282,14 @@ describe("Codex", () => {
const mcpCall = await p.waitLog("codex reaches peppa MCP", (e) => e.ev === "mcp" && e.tool === "get_task");
assert.equal(mcpCall.isError, false);
- const alert = await p.waitQuestion(sid, "attention");
- assert.match(alert.text, /какой фреймворк/);
+ // PEP-149: the end of a turn is a progress record, not a question to the PM.
+ await p.waitStatus(sid, "idle");
+ assert.deepEqual(await p.pending(sid), []);
const s = await p.session(sid);
assert.equal(s.provider, "codex");
- assert.equal(s.status, "waiting_input");
assert.equal(s.conversationId, start.conversationId);
- await runner.answerAndDeliver(db, alert.id, "Fastify", PM);
+ await runner.sendToSession(db, sid, "Fastify");
await p.waitLog("answer typed in", isPrompt("Fastify"));
await runner.stopSession(db, sid);
});
@@ -309,9 +309,9 @@ describe("Codex", () => {
test("crash → resume uses `codex resume `", async () => {
const p = await project({ turns: [[{ say: "Первый ход." }], [{ crash: 2 }]], resumeTurns: [[{ say: "Вернулся." }]] });
const sid = await p.start({ provider: "codex" });
- const alert = await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
const thread = (await p.session(sid)).conversationId;
- await runner.answerAndDeliver(db, alert.id, "продолжай", PM);
+ await runner.sendToSession(db, sid, "продолжай");
await p.waitLog("crashed", (e) => e.ev === "exit");
await waitFor("failed", async () => {
await tick();
diff --git a/packages/testkit/test/claude-live.test.ts b/packages/testkit/test/claude-live.test.ts
index 3cfce8a1..96d26177 100644
--- a/packages/testkit/test/claude-live.test.ts
+++ b/packages/testkit/test/claude-live.test.ts
@@ -9,7 +9,7 @@ import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, describe, test } from "node:test";
import { events } from "@peppa/db";
-import { asc, eq } from "drizzle-orm";
+import { and, asc, eq } from "drizzle-orm";
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
after(teardown);
@@ -177,7 +177,7 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", ()
await runner.stopSession(db, sid);
});
- test("Stop: стори в работе → decision block; после двух — PM", async () => {
+ test("Stop: стори в работе → decision block; после двух — ход работы, PM не зовём", async () => {
const p = await project({ turns: [[{ sleep: 60_000 }]] });
const sid = await p.start();
// The prompt hook resets auto_nudges; let it finish before the Stop hooks are counted.
@@ -190,8 +190,10 @@ describe("Живой Claude Code: peppa-hook на снятых payload'ах", ()
assert.match(first.reason, new RegExp(p.taskKey));
assert.equal((await hook("stop", fixture("stop-after-block"), sid, s.generation)).decision, "block");
assert.equal(await hook("stop", fixture("stop-after-block"), sid, s.generation), null);
- const q = await p.waitQuestion(sid, "attention");
- assert.equal(q.text, fixture("stop-after-block").last_assistant_message);
+ // PEP-149: the last reply becomes a progress record — the PM is not asked.
+ assert.deepEqual(await p.pending(sid), []);
+ const [progress] = await db.select().from(events).where(and(eq(events.sessionId, sid), eq(events.type, "progress")));
+ assert.equal((progress!.payload as { text: string }).text, fixture("stop-after-block").last_assistant_message);
await runner.stopSession(db, sid);
});
});
diff --git a/packages/testkit/test/rotation.test.ts b/packages/testkit/test/rotation.test.ts
index 020a0e4a..dd9bf13b 100644
--- a/packages/testkit/test/rotation.test.ts
+++ b/packages/testkit/test/rotation.test.ts
@@ -166,9 +166,9 @@ describe("Предохранители", () => {
const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 3600, credential: "caplimA" } }]] });
await poolFor(p.key, [a.id, b.id]);
const sid = await p.start();
- const q = await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
for (let i = 0; i < runner.maxRotationsPerHour(); i++) await core.logSessionEvent(db, await sess(sid), runner.SWITCH_EVENT, { reason: "limit" });
- await runner.answerAndDeliver(db, q.id, "дальше", "web");
+ await runner.sendToSession(db, sid, "дальше");
await p.waitStatus(sid, "rate_limited");
assert.equal((await sess(sid)).rotateReason, null);
assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/);
diff --git a/packages/testkit/test/sandbox-hosts.test.ts b/packages/testkit/test/sandbox-hosts.test.ts
index 89c307af..97e55944 100644
--- a/packages/testkit/test/sandbox-hosts.test.ts
+++ b/packages/testkit/test/sandbox-hosts.test.ts
@@ -142,7 +142,7 @@ describe("PEP-17: агент в контейнере", () => {
const p = await project({ turns: [[{ say: "ok" }]] });
const before = runs().length;
const sid = await p.start();
- await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
const s = await core.getSession(db, sid);
assert.equal(s.container, null);
assert.equal(s.host, null);
@@ -193,7 +193,7 @@ describe("PEP-17: агент в контейнере", () => {
await new Promise((r) => setTimeout(r, 1200)); // longer than one relay wait
await runner.answerAndDeliver(db, q.id, "allow", "web");
await p.waitLog("permission allowed by hook", (e) => e.ev === "permission" && e.via === "hook" && e.behavior === "allow");
- await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
// Stop hook through the relay with the transcript: tokens counted as for a local agent.
assert.equal(core.usageTotals((await core.getSession(db, sid)).usage).total, 1500);
assert.ok((await evs(sid, "turn_end")).length >= 1);
@@ -300,7 +300,7 @@ describe("PEP-40: хосты раннеров", () => {
const log = join(remoteWs, ".peppa", "mock-log.jsonl");
await waitFor("mcp from the host", async () => existsSync(log) && readFileSync(log, "utf8").includes('"tool":"report_progress","args":{"task":"'));
assert.match(readFileSync(log, "utf8"), /"tool":"report_progress".*"isError":false/);
- await p.waitQuestion(sid, "attention");
+ await p.waitStatus(sid, "idle");
// PEP-9 over SSH: the frame comes from the host's pane.
const frame = await new Promise((resolve, reject) => {
--
2.45.2
From 1353b358b837f9358e3c73360f5a849c89c366f9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 11:48:34 +0500
Subject: [PATCH 017/215] PEP-149: archive the change
Co-Authored-By: Claude Fable 5.2
---
.../.openspec.yaml | 0
.../design.md | 0
.../proposal.md | 0
.../specs/agent-messages/spec.md | 0
.../tasks.md | 0
openspec/specs/agent-messages/spec.md | 104 ++++++++++++++++++
6 files changed, 104 insertions(+)
rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/.openspec.yaml (100%)
rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/design.md (100%)
rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/proposal.md (100%)
rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/specs/agent-messages/spec.md (100%)
rename openspec/changes/{pep-149-agent-message-kinds => archive/2026-11-16-pep-149-agent-message-kinds}/tasks.md (100%)
create mode 100644 openspec/specs/agent-messages/spec.md
diff --git a/openspec/changes/pep-149-agent-message-kinds/.openspec.yaml b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/.openspec.yaml
similarity index 100%
rename from openspec/changes/pep-149-agent-message-kinds/.openspec.yaml
rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/.openspec.yaml
diff --git a/openspec/changes/pep-149-agent-message-kinds/design.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/design.md
similarity index 100%
rename from openspec/changes/pep-149-agent-message-kinds/design.md
rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/design.md
diff --git a/openspec/changes/pep-149-agent-message-kinds/proposal.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/proposal.md
similarity index 100%
rename from openspec/changes/pep-149-agent-message-kinds/proposal.md
rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/proposal.md
diff --git a/openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/specs/agent-messages/spec.md
similarity index 100%
rename from openspec/changes/pep-149-agent-message-kinds/specs/agent-messages/spec.md
rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/specs/agent-messages/spec.md
diff --git a/openspec/changes/pep-149-agent-message-kinds/tasks.md b/openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/tasks.md
similarity index 100%
rename from openspec/changes/pep-149-agent-message-kinds/tasks.md
rename to openspec/changes/archive/2026-11-16-pep-149-agent-message-kinds/tasks.md
diff --git a/openspec/specs/agent-messages/spec.md b/openspec/specs/agent-messages/spec.md
new file mode 100644
index 00000000..f6555fe7
--- /dev/null
+++ b/openspec/specs/agent-messages/spec.md
@@ -0,0 +1,104 @@
+# agent-messages Specification
+
+## Purpose
+Сообщения агента пользователю делятся на четыре типа — вопрос, готово, ход работы, блокер; от типа зависит, увидит ли его пользователь в «Ждут вашего ответа», в Telegram или только в «Событиях агентов».
+
+## Requirements
+
+### Requirement: Тип сообщения определяет маршрут
+Система SHALL присваивать каждому новому сообщению агента пользователю один из типов `question`, `done`, `progress`, `blocker`. В «Ждут вашего ответа» SHALL попадать только `question`; счётчик «ждут вас», напоминания и push SHALL учитывать только `question` и `done`.
+
+#### Scenario: Вопрос попадает в «Ждут вашего ответа»
+- **GIVEN** задача PEP-1 в работе
+- **WHEN** агент задаёт вопрос «Какой цвет кнопки?» с вариантами «Синий» и «Зелёный», по умолчанию «Синий»
+- **THEN** на Главной в «Ждут вашего ответа» есть этот вопрос с кнопками «Синий» и «Зелёный» и полем «Свой ответ»
+- **AND** счётчик «ждут вас» равен 1
+
+#### Scenario: Сообщение о сбое не попадает в «Ждут вашего ответа»
+- **GIVEN** открытое сообщение фабрики без вариантов ответа «агент остановился с ошибкой»
+- **WHEN** пользователь открывает Главную
+- **THEN** в «Ждут вашего ответа» этого сообщения нет
+- **AND** счётчик «ждут вас» равен 0
+
+### Requirement: Конец хода — это ход работы, а не вопрос
+Когда агент закончил ход, а статус задачи не изменился и подталкивания исчерпаны, система SHALL записать последнюю реплику агента как `progress` в «События агентов» и SHALL NOT создавать вопрос, отправлять Telegram или push.
+
+#### Scenario: Агент закончил ход, статус задачи тот же
+- **GIVEN** задача PEP-1 в работе, агент уже дважды получил подталкивание
+- **WHEN** агент заканчивает ход с текстом «Жду проверок»
+- **THEN** в «Ждут вашего ответа» и в Telegram владельца ничего нового нет
+- **AND** в «Событиях агентов» проекта, в треде PEP-1, есть запись «Жду проверок»
+
+#### Scenario: У агента есть открытый вопрос
+- **GIVEN** агент задал вопрос с вариантами и не получил ответа
+- **WHEN** агент заканчивает ход
+- **THEN** новая запись хода работы не создаётся, вопрос остаётся в «Ждут вашего ответа»
+
+### Requirement: Платформа будит агента, когда проверки прошли
+Когда все проверки последнего коммита задачи в работе прошли, а ход агента окончен, система SHALL один раз на коммит сообщить агенту, что задачу можно переводить в ревью.
+
+#### Scenario: Проверки прошли, агент ждал
+- **GIVEN** задача PEP-1 в работе, агент закончил ход, проверки коммита `abc1234` ещё шли
+- **WHEN** последняя проверка коммита `abc1234` проходит
+- **THEN** агент получает сообщение «проверки прошли»
+
+#### Scenario: Повторный отчёт о том же коммите
+- **GIVEN** агент уже получил сообщение о коммите `abc1234`
+- **WHEN** приходит ещё один успешный отчёт по коммиту `abc1234`
+- **THEN** второго сообщения агент не получает
+
+### Requirement: «Готово» шлёт платформа после проверок
+Сообщение типа `done` SHALL отправляться только платформой, только когда проверки последнего коммита прошли и нет конфликта, и SHALL содержать ссылку на результат.
+
+#### Scenario: Проверки прошли
+- **GIVEN** задача PEP-1 в ревью, проверки зелёные, результат `https://git.example/pulls/7`
+- **WHEN** агент заканчивает ход
+- **THEN** владелец получает сообщение «готова к ревью» типа `done` со ссылкой `https://git.example/pulls/7` и кнопкой «Принять»
+
+#### Scenario: Проверки ещё идут
+- **GIVEN** задача PEP-1 в ревью, одна проверка не завершена
+- **WHEN** агент заканчивает ход
+- **THEN** владелец ничего не получает, пока проверки не пройдут
+
+### Requirement: Вопрос агента — с вариантами и вариантом по умолчанию
+Инструмент `ask_pm` SHALL принимать вопрос только с 2–4 вариантами ответа и вариантом по умолчанию из их числа; иначе SHALL отклонять вызов с объяснением.
+
+#### Scenario: Вопрос с вариантами принят
+- **WHEN** агент вызывает `ask_pm` с вариантами «Да», «Нет» и вариантом по умолчанию «Да»
+- **THEN** вопрос отправлен, вариант «Да» показан первым и отмечен как выбранный по умолчанию
+
+#### Scenario Outline: Вопрос без вариантов отклонён
+- **WHEN** агент вызывает `ask_pm` с вариантами <варианты> и вариантом по умолчанию <по умолчанию>
+- **THEN** вызов отклонён с объяснением «<причина>», вопрос не создан
+
+| варианты | по умолчанию | причина |
+|---|---|---|
+| нет | нет | нужны 2–4 варианта |
+| «Да» | «Да» | нужны 2–4 варианта |
+| «Да», «Нет» | нет | нужен вариант по умолчанию |
+| «Да», «Нет» | «Может быть» | вариант по умолчанию — один из вариантов |
+
+### Requirement: Блокер идёт по своему маршруту
+Инструмент `report_blocker` SHALL принимать, что мешает и что агент уже пробовал. Продуктовый блокер SHALL идти пользователю как `question` с вариантами; непродуктовый SHALL записываться в «События агентов» и SHALL NOT отправляться владельцу проекта.
+
+#### Scenario: Непродуктовый блокер
+- **WHEN** агент сообщает блокер «нет доступа к серверу сборки», пробовал «повторил три раза»
+- **THEN** в треде задачи в «Событиях агентов» есть запись о блокере
+- **AND** владелец не получает ни вопроса, ни сообщения в Telegram
+
+#### Scenario: Продуктовый блокер без вариантов
+- **WHEN** агент сообщает продуктовый блокер без вариантов ответа
+- **THEN** вызов отклонён с объяснением, что нужны варианты и вариант по умолчанию
+
+### Requirement: Нет кнопки «Продолжай»
+Веб и Telegram-бот SHALL NOT показывать кнопку «Продолжай» ни у какого сообщения; у `question` SHALL быть кнопки вариантов и возможность своего ответа.
+
+#### Scenario: Сообщение фабрики в Telegram
+- **GIVEN** открытое сообщение фабрики без вариантов ответа
+- **WHEN** бот отправляет его в Telegram
+- **THEN** у сообщения нет кнопки «Продолжай»
+
+#### Scenario: Старая кнопка «Продолжай»
+- **GIVEN** старое сообщение в Telegram с кнопкой «Продолжай»
+- **WHEN** пользователь нажимает её
+- **THEN** агенту ничего не отправляется
--
2.45.2
From 2dd13261bc413c9f5666ae10ef8468a92c6364d3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 12:08:52 +0500
Subject: [PATCH 018/215] PEP-149: migration regenerated on top of main (0020)
Co-Authored-By: Claude Fable 5.2
---
AGENTS.md | 2 +-
packages/db/migrations/0020_fuzzy_plazm.sql | 2 +
.../db/migrations/meta/0020_snapshot.json | 4372 +++++++++++++++++
packages/db/migrations/meta/_journal.json | 7 +
4 files changed, 4382 insertions(+), 1 deletion(-)
create mode 100644 packages/db/migrations/0020_fuzzy_plazm.sql
create mode 100644 packages/db/migrations/meta/0020_snapshot.json
diff --git a/AGENTS.md b/AGENTS.md
index 3f1dcd15..906a0217 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -43,7 +43,7 @@
- **Чаты для продакта (PEP-117)**: `/chats` — обзор (`chatOverview` в core/chats.ts: карточка проекта — непрочитанное, открытые вопросы, последнее сообщение; сверху `inbox` «Ждут вашего ответа»); журнал — `/chats/master` («Все события»). В журналах (`master`, `?thread=feed`) поля ввода нет. `EVENT_TEXT`: смена статуса словами по `to` (и `from` для «на доработку»), сбои, которые Peppa чинит сама, не `important`. Подписи: `attention` — «Сообщение от фабрики»
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
- **Слова по режиму (PEP-123)**: `@peppa/shared/wording` — `wording(mode)`: `task(форма)` / `Task` / `tasks(n)` («задача» в «Продакте», «стори» в «Инженере»), `runner(форма)` («агент» / «раннер»), формы `nom|gen|dat|acc|ins|pre|pl|genPl|datPl|accPl|insPl|prePl`. Веб: серверный компонент — `const w = await words()` (`lib/auth.ts`), клиентский — `useWords()` (`components/Words.tsx`, `WordsProvider` в раскладке). Что читает только инженер (репозиторий, раннеры, модель, секреты, бюджет, ревьюер в «Настройках проекта», команда терминала, адрес кода, подробная автономность) — под `w.engineer`. Тексты без читателя (события чатов `EVENT_TEXT`, вопросы и сообщения PM из runner, Telegram, push, подписи из core) — всегда словами «Продакта»: «задача», «агент», «Peppa FACTORY», «вы», «Результат:» вместо «PR:». Промпты агентам, MCP и CLI — прежние слова. Страница задачи, полоса лимитов и «Помощь» — PEP-120/121/122. Тест `wording.test.ts`
-- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0019; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts`
+- **Четыре типа сообщений агента (PEP-149)**: `questions.msg_type` (`question | done | progress | blocker`, миграция 0020; null — сообщение самой фабрики: сбой, лимит, выкладка) + `questions.default_option`; чтение — только через `core/questions.ts`: `questionType(q, taskStatus)` (сохранённый тип → не `attention` или есть варианты = question → `attention` у задачи в ревью = done → null), `needsPerson` (question или done), SQL-близнец `IS_QUESTION`. Маршруты: **question** — «Вопросы агентов» на Главной (`inbox` в web/lib/queries.ts), Telegram с кнопками вариантов, push, напоминания; **done** — блок «Ждут „Принять“» (`acceptInbox`), шлёт только `sendReviewCard` (тип `done`, ссылка на результат обязательна); счётчики (`navCounts`, `/api/attention`, счётчик push бота) = question + done; **progress** — событие `progress` → тред задачи в «Событиях агентов», никого не будит; **blocker** — MCP `report_blocker`: `product: true` + варианты → question, иначе событие `blocker` (строка в `EVENT_TEXT`) + `alertAdmins`, владельцу ничего. Сообщения без типа по-прежнему уходят в Telegram и чат, но без кнопок выбора, не в «Вопросы агентов», не в счётчик и без push. Stop-хук (`turnEnd`): конец хода без смены статуса → `reportProgress` последней реплики, сессия `idle` (не `waiting_input`); подталкивание держит только открытое сообщение `needsPerson`; `idleStopTick` останавливает и `idle`-сессии задач в работе. Агента, ждущего проверок, будит `wakeOnGreen` (runner/ci-feedback.ts: зелёный отчёт + открытый гейт → одно сообщение на коммит, `ci.woke:`). MCP агента: `ask_pm` — обязательны `options` (2–4) и `default` (`checkChoices`, отказ с объяснением), вариант по умолчанию первым. Кнопки «Продолжай» нет ни в вебе, ни в боте (старая кнопка в Telegram — тост «Кнопка устарела»). Новый путь, который пишет пользователю, — выбери тип явно (`msgType` в `askPm` / `raiseSessionQuestion`). Тест `agent-messages.test.ts`
- **Комментарий уточняет постановку (PEP-115)**: `pm_comment` к стори в бэклоге без живого агента → `storyRefineTick` в тике вачдога (`runner/story-refine.ts`): `claudePrint` на подписке проекта (`PEPPA_INTAKE_BIN`/`_MODEL`), промпт `refinePrompt` (core/story-refine.ts: контекст `intakeContext`, текущая постановка, обсуждение, новые комментарии), ответ — JSON аналитика (`parseAnalystNote`) → описание через `intakeDescription` («Исходный запрос» сохраняется, `originalRequest`) + заметка аналитика `intake_note` в «Обсуждении» стори. Курсор `refine.task:`, комментарии старше `PEPPA_STORY_REFINE_MAX_AGE_MIN` (60) не трогаются, сбой — одна заметка без повторов, стори взяли в работу до ответа — описание не меняется, роли PEP-84 не закончили — ждёт; `PEPPA_STORY_REFINE=off`. `refinePending` — «Аналитик уточняет постановку…» и исключение из `readyBacklog`. Подпись поля — `apps/web/lib/comment-hint.ts`. Мок — роль `refine` в `mock-intake` (`slowMs`); тест `story-refine.test.ts`
- **Режимы «Продакт» / «Инженер» (PEP-119)**: `core/ui-mode.ts` (`getUiMode`/`setUiMode`, `settings` `ui.mode:`, по умолчанию `product`; `PRODUCT_PROJECT_TABS`), веб `uiMode()` в `lib/auth.ts`, переключатель «Настройки → Вид Peppa FACTORY» (`setUiModeAction`). В «Продакте»: вкладки проекта board/epics/bugs + «Чат с аналитиком», в меню нет `/runners` (`Item.engineer`), в `ProductCard` кнопка «Показать всем». Новое для инженера прячь за `engineer`. `next.config.ts`: `devIndicators: false`, `logging.browserToTerminal: false` (иначе ошибка браузера на каждой загрузке → петля перезагрузок)
- **Страница задачи в режиме «Продакт» (PEP-120)**: `t/[key]/page.tsx` при `uiMode()` = product рисует `components/StoryProduct.tsx` — карточку из `storyProductView` (core/story-product.ts, чистая функция; все тексты — `STORY_PRODUCT_TEXT`; `plainStep` не показывает пункт tasks.md с путями, файлами и идентификаторами): что сейчас, «Шаг N из M», «Посмотреть» (`reviewPreview().previewUrl`), что нужно от вас, что дальше, открытые вопросы (`QuestionCard plain`: команда разрешения — под «Подробнее»), «Принять» (`acceptStoryAction`) и «Поправить» (`fixStoryAction` → `fixStory` в runner/flow.ts: только из ревью, комментарий + закрыть «готово к ревью» + `moveTask in_progress` + замечание агенту). Прежнее содержимое страницы и блоки правой панели — под ссылкой «Подробнее» (`?more=1`, также `?tab=`/`?edit=`; закрыто — терминал не монтируется), без правой панели и значка статуса. «Инженер» — без изменений. Тест `story-product.test.ts`
diff --git a/packages/db/migrations/0020_fuzzy_plazm.sql b/packages/db/migrations/0020_fuzzy_plazm.sql
new file mode 100644
index 00000000..ab537714
--- /dev/null
+++ b/packages/db/migrations/0020_fuzzy_plazm.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `questions` ADD `msg_type` text;--> statement-breakpoint
+ALTER TABLE `questions` ADD `default_option` text;
\ No newline at end of file
diff --git a/packages/db/migrations/meta/0020_snapshot.json b/packages/db/migrations/meta/0020_snapshot.json
new file mode 100644
index 00000000..75262e8e
--- /dev/null
+++ b/packages/db/migrations/meta/0020_snapshot.json
@@ -0,0 +1,4372 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "53ced319-040c-444d-8e11-97e95c7b2821",
+ "prevId": "61f327b6-cb6a-4359-9b4b-23df03040aa9",
+ "tables": {
+ "agents": {
+ "name": "agents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "character": {
+ "name": "character",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "agents_name_unique": {
+ "name": "agents_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chat_messages": {
+ "name": "chat_messages",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "thread_key": {
+ "name": "thread_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thread_title": {
+ "name": "thread_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "important": {
+ "name": "important",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "author_kind": {
+ "name": "author_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'system'"
+ },
+ "author_user_id": {
+ "name": "author_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_login": {
+ "name": "author_login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "via": {
+ "name": "via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_message_id": {
+ "name": "tg_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "chat_messages_dedupe_key_unique": {
+ "name": "chat_messages_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ },
+ "chat_messages_chat": {
+ "name": "chat_messages_chat",
+ "columns": [
+ "chat_id",
+ "id"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_created_at": {
+ "name": "chat_messages_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "chat_messages_tg": {
+ "name": "chat_messages_tg",
+ "columns": [
+ "tg_chat_id",
+ "tg_message_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "chat_messages_chat_id_chats_id_fk": {
+ "name": "chat_messages_chat_id_chats_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "chats",
+ "columnsFrom": [
+ "chat_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chat_messages_author_user_id_users_id_fk": {
+ "name": "chat_messages_author_user_id_users_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "author_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_question_id_questions_id_fk": {
+ "name": "chat_messages_question_id_questions_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "questions",
+ "columnsFrom": [
+ "question_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chat_messages_task_id_tasks_id_fk": {
+ "name": "chat_messages_task_id_tasks_id_fk",
+ "tableFrom": "chat_messages",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "chats": {
+ "name": "chats",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_chat_id": {
+ "name": "tg_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_title": {
+ "name": "tg_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_at": {
+ "name": "tg_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_linked_by": {
+ "name": "tg_linked_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tg_bot_user_id": {
+ "name": "tg_bot_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "chats_user_id_unique": {
+ "name": "chats_user_id_unique",
+ "columns": [
+ "user_id"
+ ],
+ "isUnique": true
+ },
+ "chats_project_id_unique": {
+ "name": "chats_project_id_unique",
+ "columns": [
+ "project_id"
+ ],
+ "isUnique": true
+ },
+ "chats_tg_chat_id_unique": {
+ "name": "chats_tg_chat_id_unique",
+ "columns": [
+ "tg_chat_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "chats_user_id_users_id_fk": {
+ "name": "chats_user_id_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_project_id_projects_id_fk": {
+ "name": "chats_project_id_projects_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "chats_tg_linked_by_users_id_fk": {
+ "name": "chats_tg_linked_by_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "tg_linked_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "chats_tg_bot_user_id_users_id_fk": {
+ "name": "chats_tg_bot_user_id_users_id_fk",
+ "tableFrom": "chats",
+ "tableTo": "users",
+ "columnsFrom": [
+ "tg_bot_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "check_runs": {
+ "name": "check_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "branch": {
+ "name": "branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "check": {
+ "name": "check",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "duration_sec": {
+ "name": "duration_sec",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'report'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "check_runs_project_sha_check": {
+ "name": "check_runs_project_sha_check",
+ "columns": [
+ "project_id",
+ "sha",
+ "check"
+ ],
+ "isUnique": true
+ }
+ },
+ "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": {},
+ "checkConstraints": {}
+ },
+ "code_reviews": {
+ "name": "code_reviews",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "findings": {
+ "name": "findings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "code_reviews_project_id_projects_id_fk": {
+ "name": "code_reviews_project_id_projects_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "code_reviews_task_id_tasks_id_fk": {
+ "name": "code_reviews_task_id_tasks_id_fk",
+ "tableFrom": "code_reviews",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "error_sources": {
+ "name": "error_sources",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_project_id": {
+ "name": "bugsink_project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "error_sources_bugsink_project_id_unique": {
+ "name": "error_sources_bugsink_project_id_unique",
+ "columns": [
+ "bugsink_project_id"
+ ],
+ "isUnique": true
+ },
+ "error_sources_project_kind": {
+ "name": "error_sources_project_kind",
+ "columns": [
+ "project_id",
+ "kind"
+ ],
+ "isUnique": true
+ }
+ },
+ "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": {},
+ "checkConstraints": {}
+ },
+ "events": {
+ "name": "events",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_kind": {
+ "name": "actor_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_user_id": {
+ "name": "actor_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_channel": {
+ "name": "actor_channel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor_client_id": {
+ "name": "actor_client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "events_created_at": {
+ "name": "events_created_at",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "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"
+ },
+ "events_actor_user_id_users_id_fk": {
+ "name": "events_actor_user_id_users_id_fk",
+ "tableFrom": "events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actor_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "feedback": {
+ "name": "feedback",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "via": {
+ "name": "via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "context": {
+ "name": "context",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'received'"
+ },
+ "analysis": {
+ "name": "analysis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "analysis_error": {
+ "name": "analysis_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "analysis_started_at": {
+ "name": "analysis_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "option_index": {
+ "name": "option_index",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "reject_reason": {
+ "name": "reject_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_at": {
+ "name": "decided_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "feedback_user": {
+ "name": "feedback_user",
+ "columns": [
+ "user_id",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "feedback_status": {
+ "name": "feedback_status",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "feedback_user_id_users_id_fk": {
+ "name": "feedback_user_id_users_id_fk",
+ "tableFrom": "feedback",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "feedback_task_id_tasks_id_fk": {
+ "name": "feedback_task_id_tasks_id_fk",
+ "tableFrom": "feedback",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "feedback_decided_by_users_id_fk": {
+ "name": "feedback_decided_by_users_id_fk",
+ "tableFrom": "feedback",
+ "tableTo": "users",
+ "columnsFrom": [
+ "decided_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "goals": {
+ "name": "goals",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'open'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "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": {},
+ "checkConstraints": {}
+ },
+ "incident_settings": {
+ "name": "incident_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "hook_secret": {
+ "name": "hook_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "triage_prompt": {
+ "name": "triage_prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environments": {
+ "name": "environments",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[\"prod\",\"production\"]'"
+ },
+ "daily_limit": {
+ "name": "daily_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 5
+ },
+ "ignore_pattern": {
+ "name": "ignore_pattern",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "webhook_auto": {
+ "name": "webhook_auto",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incident_settings_hook_secret_unique": {
+ "name": "incident_settings_hook_secret_unique",
+ "columns": [
+ "hook_secret"
+ ],
+ "isUnique": true
+ }
+ },
+ "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": {},
+ "checkConstraints": {}
+ },
+ "incidents": {
+ "name": "incidents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "bugsink_issue_id": {
+ "name": "bugsink_issue_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "friendly_id": {
+ "name": "friendly_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "culprit": {
+ "name": "culprit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "level": {
+ "name": "level",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_release": {
+ "name": "first_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_release": {
+ "name": "last_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "events": {
+ "name": "events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "first_seen": {
+ "name": "first_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "last_seen": {
+ "name": "last_seen",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'new'"
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decided_by": {
+ "name": "decided_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "decision_reason": {
+ "name": "decision_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "task_created_at": {
+ "name": "task_created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_release": {
+ "name": "resolved_release",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "regressions": {
+ "name": "regressions",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "incidents_bugsink_issue_id_unique": {
+ "name": "incidents_bugsink_issue_id_unique",
+ "columns": [
+ "bugsink_issue_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "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": {},
+ "checkConstraints": {}
+ },
+ "oauth_clients": {
+ "name": "oauth_clients",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uris": {
+ "name": "redirect_uris",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "oauth_codes": {
+ "name": "oauth_codes",
+ "columns": {
+ "code_hash": {
+ "name": "code_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "redirect_uri": {
+ "name": "redirect_uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "code_challenge": {
+ "name": "code_challenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": 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": {},
+ "checkConstraints": {}
+ },
+ "oauth_tokens": {
+ "name": "oauth_tokens",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": 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": {},
+ "checkConstraints": {}
+ },
+ "project_invites": {
+ "name": "project_invites",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "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": {
+ "columns": [
+ "project_id",
+ "login"
+ ],
+ "name": "project_invites_project_id_login_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_members": {
+ "name": "project_members",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "added_by": {
+ "name": "added_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "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": {
+ "columns": [
+ "project_id",
+ "user_id"
+ ],
+ "name": "project_members_project_id_user_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "project_secrets": {
+ "name": "project_secrets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value_enc": {
+ "name": "value_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "project_secrets_project_name": {
+ "name": "project_secrets_project_name",
+ "columns": [
+ "project_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "project_secrets_project_id_projects_id_fk": {
+ "name": "project_secrets_project_id_projects_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "project_secrets_created_by_users_id_fk": {
+ "name": "project_secrets_created_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "project_secrets_updated_by_users_id_fk": {
+ "name": "project_secrets_updated_by_users_id_fk",
+ "tableFrom": "project_secrets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "updated_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "projects": {
+ "name": "projects",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_owner": {
+ "name": "gitea_owner",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "gitea_repo": {
+ "name": "gitea_repo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "default_branch": {
+ "name": "default_branch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "owner_id": {
+ "name": "owner_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "next_task_number": {
+ "name": "next_task_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ },
+ "subscription_pool_id": {
+ "name": "subscription_pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "projects_slug_unique": {
+ "name": "projects_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "projects_key_unique": {
+ "name": "projects_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "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"
+ },
+ "projects_subscription_pool_id_subscription_pools_id_fk": {
+ "name": "projects_subscription_pool_id_subscription_pools_id_fk",
+ "tableFrom": "projects",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "subscription_pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_outbox": {
+ "name": "push_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "urgency": {
+ "name": "urgency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'normal'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_outbox_dedupe_key_unique": {
+ "name": "push_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_outbox_subscription_id_push_subscriptions_id_fk": {
+ "name": "push_outbox_subscription_id_push_subscriptions_id_fk",
+ "tableFrom": "push_outbox",
+ "tableTo": "push_subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "push_subscriptions": {
+ "name": "push_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "p256dh": {
+ "name": "p256dh",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth": {
+ "name": "auth",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_ok_at": {
+ "name": "last_ok_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "push_subscriptions_endpoint_unique": {
+ "name": "push_subscriptions_endpoint_unique",
+ "columns": [
+ "endpoint"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "push_subscriptions_user_id_users_id_fk": {
+ "name": "push_subscriptions_user_id_users_id_fk",
+ "tableFrom": "push_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "questions": {
+ "name": "questions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "text": {
+ "name": "text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "msg_type": {
+ "name": "msg_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "default_option": {
+ "name": "default_option",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answer": {
+ "name": "answer",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "answered_via": {
+ "name": "answered_via",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awaiting_hook": {
+ "name": "awaiting_hook",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "reminders": {
+ "name": "reminders",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "answered_at": {
+ "name": "answered_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": 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": {},
+ "checkConstraints": {}
+ },
+ "releases": {
+ "name": "releases",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "previous_sha": {
+ "name": "previous_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_number": {
+ "name": "pr_number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tasks": {
+ "name": "tasks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'deploying'"
+ },
+ "deployed_by": {
+ "name": "deployed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'ci'"
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "run_url": {
+ "name": "run_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "log_tail": {
+ "name": "log_tail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "screenshots": {
+ "name": "screenshots",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "releases_project_id_projects_id_fk": {
+ "name": "releases_project_id_projects_id_fk",
+ "tableFrom": "releases",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "review_settings": {
+ "name": "review_settings",
+ "columns": {
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "max_iterations": {
+ "name": "max_iterations",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 2
+ },
+ "rules": {
+ "name": "rules",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "review_settings_project_id_projects_id_fk": {
+ "name": "review_settings_project_id_projects_id_fk",
+ "tableFrom": "review_settings",
+ "tableTo": "projects",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_commands": {
+ "name": "runner_commands",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_kind": {
+ "name": "error_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "actor": {
+ "name": "actor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host": {
+ "name": "host",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_commands_status_idx": {
+ "name": "runner_commands_status_idx",
+ "columns": [
+ "status",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_hosts": {
+ "name": "runner_hosts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_target": {
+ "name": "ssh_target",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ssh_port": {
+ "name": "ssh_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 22
+ },
+ "workdir": {
+ "name": "workdir",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'peppa'"
+ },
+ "peppa_url": {
+ "name": "peppa_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "info": {
+ "name": "info",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_seen_at": {
+ "name": "last_seen_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "runner_hosts_name_unique": {
+ "name": "runner_hosts_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runner_tasks": {
+ "name": "runner_tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "front": {
+ "name": "front",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "runner_tasks_session_idx": {
+ "name": "runner_tasks_session_idx",
+ "columns": [
+ "session_id",
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "runner_tasks_session_id_sessions_id_fk": {
+ "name": "runner_tasks_session_id_sessions_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "session_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "runner_tasks_task_id_tasks_id_fk": {
+ "name": "runner_tasks_task_id_tasks_id_fk",
+ "tableFrom": "runner_tasks",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tmux_name": {
+ "name": "tmux_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'claude'"
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_session_id": {
+ "name": "claude_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "generation": {
+ "name": "generation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "auto_nudges": {
+ "name": "auto_nudges",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "resume_at": {
+ "name": "resume_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_probe_min": {
+ "name": "limit_probe_min",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumes": {
+ "name": "limit_resumes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "limit_resumes_day": {
+ "name": "limit_resumes_day",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limit_resumed_at": {
+ "name": "limit_resumed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "rotate_reason": {
+ "name": "rotate_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_path": {
+ "name": "workspace_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_id": {
+ "name": "host_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container": {
+ "name": "container",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "usage": {
+ "name": "usage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "watch_state": {
+ "name": "watch_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'starting'"
+ },
+ "last_activity_at": {
+ "name": "last_activity_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "sessions_tmux_name_unique": {
+ "name": "sessions_tmux_name_unique",
+ "columns": [
+ "tmux_name"
+ ],
+ "isUnique": true
+ }
+ },
+ "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"
+ },
+ "sessions_subscription_id_subscriptions_id_fk": {
+ "name": "sessions_subscription_id_subscriptions_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_host_id_runner_hosts_id_fk": {
+ "name": "sessions_host_id_runner_hosts_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "runner_hosts",
+ "columnsFrom": [
+ "host_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sessions_agent_id_agents_id_fk": {
+ "name": "sessions_agent_id_agents_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "agents",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pool_members": {
+ "name": "subscription_pool_members",
+ "columns": {
+ "pool_id": {
+ "name": "pool_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscription_pool_members_pool_id_subscription_pools_id_fk": {
+ "name": "subscription_pool_members_pool_id_subscription_pools_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscription_pools",
+ "columnsFrom": [
+ "pool_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "subscription_pool_members_subscription_id_subscriptions_id_fk": {
+ "name": "subscription_pool_members_subscription_id_subscriptions_id_fk",
+ "tableFrom": "subscription_pool_members",
+ "tableTo": "subscriptions",
+ "columnsFrom": [
+ "subscription_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "subscription_pool_members_pool_id_subscription_id_pk": {
+ "columns": [
+ "pool_id",
+ "subscription_id"
+ ],
+ "name": "subscription_pool_members_pool_id_subscription_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscription_pools": {
+ "name": "subscription_pools",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "subscription_pools_name_unique": {
+ "name": "subscription_pools_name_unique",
+ "columns": [
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "subscription_pools_created_by_users_id_fk": {
+ "name": "subscription_pools_created_by_users_id_fk",
+ "tableFrom": "subscription_pools",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "subscriptions": {
+ "name": "subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "auth_kind": {
+ "name": "auth_kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secret_enc": {
+ "name": "secret_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "key_provider": {
+ "name": "key_provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "limited_until": {
+ "name": "limited_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "activated_at": {
+ "name": "activated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "subscriptions_created_by_users_id_fk": {
+ "name": "subscriptions_created_by_users_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "task_deps": {
+ "name": "task_deps",
+ "columns": {
+ "task_id": {
+ "name": "task_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blocked_by_id": {
+ "name": "blocked_by_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "task_deps_blocked_by": {
+ "name": "task_deps_blocked_by",
+ "columns": [
+ "blocked_by_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "task_deps_task_id_tasks_id_fk": {
+ "name": "task_deps_task_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "task_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_deps_blocked_by_id_tasks_id_fk": {
+ "name": "task_deps_blocked_by_id_tasks_id_fk",
+ "tableFrom": "task_deps",
+ "tableTo": "tasks",
+ "columnsFrom": [
+ "blocked_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "task_deps_task_id_blocked_by_id_pk": {
+ "columns": [
+ "task_id",
+ "blocked_by_id"
+ ],
+ "name": "task_deps_task_id_blocked_by_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tasks": {
+ "name": "tasks",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "project_id": {
+ "name": "project_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "goal_id": {
+ "name": "goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "number": {
+ "name": "number",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'backlog'"
+ },
+ "openspec_change": {
+ "name": "openspec_change",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pr_url": {
+ "name": "pr_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ci_attempts": {
+ "name": "ci_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "ci_failed_sha": {
+ "name": "ci_failed_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "gitea_issue": {
+ "name": "gitea_issue",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "archived_at": {
+ "name": "archived_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {
+ "tasks_project_number": {
+ "name": "tasks_project_number",
+ "columns": [
+ "project_id",
+ "number"
+ ],
+ "isUnique": true
+ },
+ "tasks_project_issue": {
+ "name": "tasks_project_issue",
+ "columns": [
+ "project_id",
+ "gitea_issue"
+ ],
+ "isUnique": true
+ }
+ },
+ "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": {},
+ "checkConstraints": {}
+ },
+ "telegram_outbox": {
+ "name": "telegram_outbox",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "dedupe_key": {
+ "name": "dedupe_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "params": {
+ "name": "params",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "question_id": {
+ "name": "question_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "chat_message_id": {
+ "name": "chat_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "next_attempt_at": {
+ "name": "next_attempt_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "telegram_message_id": {
+ "name": "telegram_message_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "telegram_outbox_dedupe_key_unique": {
+ "name": "telegram_outbox_dedupe_key_unique",
+ "columns": [
+ "dedupe_key"
+ ],
+ "isUnique": true
+ }
+ },
+ "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"
+ },
+ "telegram_outbox_chat_message_id_chat_messages_id_fk": {
+ "name": "telegram_outbox_chat_message_id_chat_messages_id_fk",
+ "tableFrom": "telegram_outbox",
+ "tableTo": "chat_messages",
+ "columnsFrom": [
+ "chat_message_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "telegram_updates": {
+ "name": "telegram_updates",
+ "columns": {
+ "update_id": {
+ "name": "update_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "gitea_id": {
+ "name": "gitea_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "login": {
+ "name": "login",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "avatar_url": {
+ "name": "avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_enc": {
+ "name": "access_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_enc": {
+ "name": "refresh_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_expires_at": {
+ "name": "token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_enc": {
+ "name": "claude_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "claude_token_set_at": {
+ "name": "claude_token_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_chat_id": {
+ "name": "telegram_chat_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_user_id": {
+ "name": "telegram_user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_username": {
+ "name": "telegram_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_paired_at": {
+ "name": "telegram_paired_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_bot_token_enc": {
+ "name": "telegram_bot_token_enc",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "telegram_bot_username": {
+ "name": "telegram_bot_username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "egov_iin": {
+ "name": "egov_iin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "egov_linked_at": {
+ "name": "egov_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "google_sub": {
+ "name": "google_sub",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "google_email": {
+ "name": "google_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "google_linked_at": {
+ "name": "google_linked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_hash": {
+ "name": "password_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_set_at": {
+ "name": "password_set_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "disabled_at": {
+ "name": "disabled_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(cast(unixepoch('subsec') * 1000 as integer))"
+ },
+ "last_login_at": {
+ "name": "last_login_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_gitea_id_unique": {
+ "name": "users_gitea_id_unique",
+ "columns": [
+ "gitea_id"
+ ],
+ "isUnique": true
+ },
+ "users_login_unique": {
+ "name": "users_login_unique",
+ "columns": [
+ "login"
+ ],
+ "isUnique": true
+ },
+ "users_telegram_chat_id_unique": {
+ "name": "users_telegram_chat_id_unique",
+ "columns": [
+ "telegram_chat_id"
+ ],
+ "isUnique": true
+ },
+ "users_egov_iin_unique": {
+ "name": "users_egov_iin_unique",
+ "columns": [
+ "egov_iin"
+ ],
+ "isUnique": true
+ },
+ "users_google_sub_unique": {
+ "name": "users_google_sub_unique",
+ "columns": [
+ "google_sub"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json
index 2081d2ec..ca475679 100644
--- a/packages/db/migrations/meta/_journal.json
+++ b/packages/db/migrations/meta/_journal.json
@@ -141,6 +141,13 @@
"when": 1794806148240,
"tag": "0019_stormy_vin_gonzales",
"breakpoints": true
+ },
+ {
+ "idx": 20,
+ "version": "6",
+ "when": 1794812739508,
+ "tag": "0020_fuzzy_plazm",
+ "breakpoints": true
}
]
}
\ No newline at end of file
--
2.45.2
From 165b4865470f9ba06e83ecf7e8ae6503f0dbdb59 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 12:35:47 +0500
Subject: [PATCH 019/215] =?UTF-8?q?PEP-149:=20rebased=20on=20PEP-151=20?=
=?UTF-8?q?=E2=80=94=20the=20refreshed=20Telegram=20message=20has=20no=20?=
=?UTF-8?q?=C2=ABcontinue=C2=BB=20button?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
packages/testkit/test/no-repeats.test.ts | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/packages/testkit/test/no-repeats.test.ts b/packages/testkit/test/no-repeats.test.ts
index f5cec6e5..d5e4e014 100644
--- a/packages/testkit/test/no-repeats.test.ts
+++ b/packages/testkit/test/no-repeats.test.ts
@@ -96,10 +96,10 @@ describe("Одно состояние — одно сообщение", () => {
assert.equal(inThread.length, 1);
assert.equal(inThread[0]!.repeats, 8);
assert.ok(inThread[0]!.updatedAt);
- // Telegram: still one message, with the last text and the «Продолжай» button back.
+ // Telegram: still one message, with the last text; PEP-149: no «Продолжай» button any more.
const msg = await waitFor("the Telegram message refreshed", async () => {
const [m] = tgAbout(t.project.key);
- return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null;
+ return m && m.text.includes("Продвинуть проверки из этой сессии нельзя") && !m.reply_markup?.inline_keyboard.flat().some((b) => /Продолжай/.test(b.text)) ? m : null;
});
assert.equal(tgAbout(t.project.key).length, 1);
assert.ok(msg.edits >= 1);
--
2.45.2
From 4dec8247a268ac83fee7e6d86d8e85160857c422 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?=
Date: Mon, 16 Nov 2026 12:47:00 +0500
Subject: [PATCH 020/215] =?UTF-8?q?PEP-149:=20=C2=ABproduct=20released?=
=?UTF-8?q?=C2=BB=20and=20=C2=ABbacklog=20is=20empty=C2=BB=20notices=20ask?=
=?UTF-8?q?=20nothing=20=E2=80=94=20no=20answer=20form;=20test?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Co-Authored-By: Claude Fable 5.2
---
apps/web/components/cards.tsx | 6 ++++--
packages/testkit/test/agent-messages.test.ts | 15 +++++++++++++++
2 files changed, 19 insertions(+), 2 deletions(-)
diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx
index 47eb7afe..148c1594 100644
--- a/apps/web/components/cards.tsx
+++ b/apps/web/components/cards.tsx
@@ -1,7 +1,7 @@
// Domain cards shared by pages: agent questions, runners, project list.
import Link from "next/link";
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
-import { questionState, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
+import { questionState, questionType, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
import { db } from "@/lib/db";
import { SubscriptionName } from "@/components/SubscriptionName";
import { answerQuestion, messageSession, resumeTaskSession, stopTaskSession } from "@/app/(app)/actions";
@@ -37,6 +37,7 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
const t = await getT();
const review = q.kind === "attention" && taskStatus === "review";
const answered = !!q.answeredAt;
+ const notice = questionType(q, taskStatus) === null && q.taskId == null && q.sessionId == null;
// PEP-149: a factory message with answers to choose from is a question for the person.
const k = KIND[q.kind === "attention" && !review && q.options?.length ? "question" : q.kind];
const Icon = review ? CircleCheck : k.icon;
@@ -71,12 +72,13 @@ export async function QuestionCard({ q, taskKey, taskStatus, back, compact = fal
{t("Повторов: {n} · первое сообщение {ago}", { n: state.repeats, ago: ago(q.createdAt, t) })}
)}
+ {/* PEP-149: a notice about the product as a whole (released, backlog is empty) asks nothing — no answer form. */}
{answered ? (