diff --git a/AGENTS.md b/AGENTS.md index e641ed54..bfcca71c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,6 +51,15 @@ - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`. +## Автономный режим (PEP-7) + +PM двигает карточки на доске (веб, `/p/`): «В работе» запускает агента (`moveTask`), +«Бэклог»/«Готово» останавливают. Proposal без одобрения, `request_approval`/`ask_pm` — +только архитектурные стопперы. Stop-хук Claude сам просит агента продолжать +(`decision: block`, максимум `MAX_AUTO_NUDGES`=2 подряд, счётчик `sessions.auto_nudges` +сбрасывается ответом человека), задача в `review` → сообщение «готово к ревью» с +«Принять» (`acceptTask` → `done`). Агенты мержат свои PR после зелёного e2e. + ## Пеппа ведётся через Пеппу Пеппа — проект `PEP` в самой Пеппе (`.peppa/project.json`, MCP `peppa` из `.mcp.json`). diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index ae71466f..886d19e3 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -27,7 +27,7 @@ import { } from "@peppa/core"; import { questions, tasks, projects, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { answerAndDeliver, resumeSession, stopSession } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, resumeSession, stopSession } from "@peppa/runner"; import { and, eq, gt, isNotNull } from "drizzle-orm"; import { choiceToAnswer, esc, renderAnswered, renderQuestion } from "./render.ts"; import { TelegramApi, TelegramError, type TgCallbackQuery, type TgMessage, type TgUpdate } from "./telegram.ts"; @@ -61,14 +61,16 @@ export function createBot(o: BotOptions) { async function context(q: Question) { let session: SessionView | null = null; if (q.sessionId) session = await getSession(db, q.sessionId).catch(() => null); - if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, session, webUrl: o.webUrl }; + const [st] = q.taskId ? await db.select({ status: tasks.status }).from(tasks).where(eq(tasks.id, q.taskId)) : []; + const taskStatus = st?.status ?? null; + if (session) return { taskKey: session.taskKey, taskTitle: session.taskTitle, taskStatus, session, webUrl: o.webUrl }; if (q.taskId) { const [t] = await db .select({ key: projects.key, number: tasks.number, title: tasks.title }) .from(tasks) .innerJoin(projects, eq(tasks.projectId, projects.id)) .where(eq(tasks.id, q.taskId)); - if (t) return { taskKey: formatTaskKey(t.key, t.number), taskTitle: t.title, session: null, webUrl: o.webUrl }; + if (t) return { taskKey: formatTaskKey(t.key, t.number), taskTitle: t.title, taskStatus, session: null, webUrl: o.webUrl }; } return { taskKey: null, taskTitle: null, session: null, webUrl: o.webUrl }; } @@ -208,7 +210,15 @@ export function createBot(o: BotOptions) { const [kind, idStr, choice] = (c.data ?? "").split(":"); const id = Number(idStr); let toast = "Неизвестная кнопка"; - if (kind === "q") { + if (kind === "q" && choice === "accept") { + try { + const ref = await acceptTask(db, id, "telegram"); + toast = `${ref.key} принята ✅`; + } catch (e) { + toast = (e as Error).message; + } + scheduleReconcile(); + } 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) : "Вопрос не найден"; diff --git a/apps/bot/src/render.ts b/apps/bot/src/render.ts index 51f288ec..46524fd5 100644 --- a/apps/bot/src/render.ts +++ b/apps/bot/src/render.ts @@ -18,7 +18,10 @@ export interface Rendered { } // callback_data (≤64 bytes): "q::" or "s::" -export function renderQuestion(q: Question, ctx: { taskKey: string | null; taskTitle: string | null; session: SessionView | null; webUrl: string }): Rendered { +export function renderQuestion( + q: Question, + ctx: { taskKey: string | null; taskTitle: string | null; taskStatus?: string | null; session: SessionView | null; webUrl: string }, +): Rendered { const head = [`${esc(ctx.taskKey ?? `Сессия ${q.sessionId ?? "?"}`)}`, ctx.taskTitle ? `${esc(clip(ctx.taskTitle, 80))}` : null] .filter(Boolean) .join(" · "); @@ -38,6 +41,10 @@ export function renderQuestion(q: Question, ctx: { taskKey: string | null; taskT } else if (q.kind === "question") { (q.options ?? []).slice(0, 6).forEach((o, i) => buttons.push([{ text: clip(o, 60), callback_data: `q:${q.id}:o${i}` }])); lines.push("", "Выбери вариант или ответь на это сообщение своим текстом."); + } else if (ctx.taskStatus === "review") { + lines[1] = "✅ Готово к ревью"; + buttons.push([{ text: "✅ Принять", callback_data: `q:${q.id}:accept` }]); + lines.push("", "Есть замечания — ответь на это сообщение, агент доработает."); } else { const s = ctx.session; if (s && ["failed", "rate_limited", "stalled"].includes(s.status)) { diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 2c8afc2c..389bd600 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -10,7 +10,7 @@ import { projectForUser, resolveTask, } from "@peppa/core"; -import { answerAndDeliver, provisionProject, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, moveTask, provisionProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -47,6 +47,10 @@ export async function answerQuestion(f: FormData) { const answer = str(f, "choice") || str(f, "answer"); if (!answer) throw new PeppaError("Пустой ответ"); if (q.answeredAt) throw new PeppaError(`Уже отвечено${q.answeredVia === "system" ? "" : ` (${q.answeredVia})`}: ${q.answer}`); + if (answer === "__accept") { + await acceptTask(db, q.id, "web"); + return; + } await answerAndDeliver(db, q.id, answer, "web"); }); } @@ -122,3 +126,14 @@ export async function createProjectAction(f: FormData) { return `/p/${p.key}`; }); } + +export async function moveTaskCard(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const ref = await resolveTask(db, str(f, "taskKey")); + await projectForUser(db, user.id, ref.project.id); + const to = str(f, "to") as BoardColumn; + if (!["backlog", "in_progress", "review", "done"].includes(to)) throw new PeppaError("Неизвестная колонка"); + await moveTask(db, ref, to); + }); +} diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index 8e1b180d..e4c74ab9 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -1,8 +1,9 @@ -import Link from "next/link"; import { notFound } from "next/navigation"; import { loadEnv } from "@peppa/shared"; import { AutoRefresh } from "@/components/AutoRefresh"; -import { Badge, Flash, SessionCard } from "@/components/ui"; +import { Flash, SessionCard } from "@/components/ui"; +import { Board, type Card } from "@/components/Board"; +import { columnOf } from "@peppa/runner"; import { requireUser } from "@/lib/auth"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; import { addGoal, addTask } from "../../actions"; @@ -15,7 +16,15 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr if (!p) notFound(); const [{ goals, tasks }, sessions] = await Promise.all([board(p.id), projectSessions(p.id)]); const back = `/p/${p.key}`; - const groups = [...goals.map((g) => ({ goal: g, tasks: tasks.filter((t) => t.goalId === g.id) })), { goal: null, tasks: tasks.filter((t) => !t.goalId) }]; + const groups = [...goals.map((g) => ({ goal: g })), { goal: null }]; + const goalTitle = new Map(goals.map((g) => [g.id, g.title])); + const cards: Card[] = tasks.map((t) => ({ + key: `${p.key}-${t.number}`, + title: t.title, + status: t.status, + column: columnOf(t.status), + goal: t.goalId ? (goalTitle.get(t.goalId) ?? null) : null, + })); return ( <> @@ -27,35 +36,21 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr {p.giteaOwner}/{p.giteaRepo} · {p.workspacePath}

- {groups.map(({ goal, tasks: ts }) => - goal || ts.length ? ( -
-

{goal ? `🎯 ${goal.title}` : "Без цели"}

- {goal?.description &&

{goal.description}

} -
    - {ts.map((t) => ( -
  • - - {p.key}-{t.number} {t.title} - - -
  • - ))} -
-
- + Задача{goal ? " в эту цель" : ""} -
- - - {goal && } - -