From 39367b1d82b7eebb94fc7e5c61d6dfbd65d8f720 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 21:38:09 +0500 Subject: [PATCH 001/554] PEP-8: remote MCP for ChatGPT with Peppa as OAuth 2.1 server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - OAuth: RFC 8414/9728 metadata, RFC 7591 dynamic registration, authorization code + PKCE S256 with a consent screen after Gitea login, refresh token rotation; tokens and codes stored hashed; revoke in web - /mcp: stateless Streamable HTTP, Bearer → user; PM tools from @peppa/mcp/manager: projects, goals, tasks, create, move (board semantics, starts agents), inbox, answer/accept — owner-scoped - login keeps ?next= through Gitea OAuth; Settings page with MCP URL and connected apps - 5 new tests (53 e2e total, green); verified on prod as a client: DCR → consent → token → MCP over HTTPS → revoke → 401 - OpenSpec: pep-8 archived into spec remote-mcp Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 +- apps/web/app/(app)/actions.ts | 8 + apps/web/app/(app)/layout.tsx | 1 + apps/web/app/(app)/settings/page.tsx | 42 + .../[[...path]]/route.ts | 4 + .../[[...path]]/route.ts | 4 + .../.well-known/openid-configuration/route.ts | 4 + apps/web/app/auth/callback/route.ts | 5 +- apps/web/app/auth/start/route.ts | 6 +- apps/web/app/globals.css | 5 + apps/web/app/login/page.tsx | 10 +- apps/web/app/mcp/route.ts | 36 + apps/web/app/oauth/authorize/actions.ts | 35 + apps/web/app/oauth/authorize/page.tsx | 71 + apps/web/app/oauth/register/route.ts | 27 + apps/web/app/oauth/token/route.ts | 17 + apps/web/lib/auth.ts | 4 + apps/web/lib/oauth.ts | 33 + apps/web/next.config.ts | 2 +- apps/web/package.json | 4 +- .../.openspec.yaml | 2 + .../2026-11-12-pep-8-remote-mcp/design.md | 21 + .../2026-11-12-pep-8-remote-mcp/proposal.md | 41 + .../specs/remote-mcp/spec.md | 49 + .../2026-11-12-pep-8-remote-mcp/tasks.md | 16 + openspec/specs/remote-mcp/spec.md | 48 + packages/core/src/index.ts | 1 + packages/core/src/oauth.ts | 181 +++ .../db/migrations/0006_crazy_stellaris.sql | 34 + .../db/migrations/meta/0006_snapshot.json | 1231 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 33 + packages/mcp/package.json | 16 +- packages/mcp/src/manager.ts | 150 ++ packages/testkit/package.json | 3 +- packages/testkit/test/oauth.test.ts | 127 ++ pnpm-lock.yaml | 15 + 37 files changed, 2280 insertions(+), 16 deletions(-) create mode 100644 apps/web/app/(app)/settings/page.tsx create mode 100644 apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts create mode 100644 apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts create mode 100644 apps/web/app/.well-known/openid-configuration/route.ts create mode 100644 apps/web/app/mcp/route.ts create mode 100644 apps/web/app/oauth/authorize/actions.ts create mode 100644 apps/web/app/oauth/authorize/page.tsx create mode 100644 apps/web/app/oauth/register/route.ts create mode 100644 apps/web/app/oauth/token/route.ts create mode 100644 apps/web/lib/oauth.ts create mode 100644 openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md create mode 100644 openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md create mode 100644 openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md create mode 100644 openspec/specs/remote-mcp/spec.md create mode 100644 packages/core/src/oauth.ts create mode 100644 packages/db/migrations/0006_crazy_stellaris.sql create mode 100644 packages/db/migrations/meta/0006_snapshot.json create mode 100644 packages/mcp/src/manager.ts create mode 100644 packages/testkit/test/oauth.test.ts diff --git a/AGENTS.md b/AGENTS.md index bfcca71c..48b12d13 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,8 @@ - `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433) - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё -- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd +- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов +- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, list_goals, list_tasks, get_task, create_task, move_task (как доска — запускает агента), list_inbox, answer_question - `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 389bd600..1049f281 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -9,6 +9,7 @@ import { PeppaError, projectForUser, resolveTask, + revokeApp, } from "@peppa/core"; import { acceptTask, answerAndDeliver, moveTask, provisionProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; @@ -137,3 +138,10 @@ export async function moveTaskCard(f: FormData) { await moveTask(db, ref, to); }); } + +export async function revokeConnectedApp(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await revokeApp(db, user.id, str(f, "clientId")); + }); +} diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index 961c90af..b677f059 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -13,6 +13,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
{user.avatarUrl && } diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx new file mode 100644 index 00000000..c42c8a8e --- /dev/null +++ b/apps/web/app/(app)/settings/page.tsx @@ -0,0 +1,42 @@ +import { connectedApps } from "@peppa/core"; +import { ago, Flash } from "@/components/ui"; +import { publicOrigin, requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { revokeConnectedApp } from "../actions"; + +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string }> }) { + const user = await requireUser(); + const { error } = await searchParams; + const apps = await connectedApps(db, user.id); + const origin = await publicOrigin(); + return ( +
+ +

Настройки

+

MCP для ChatGPT и других клиентов

+

+ Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент + зарегистрируется сам, вы подтвердите доступ на экране Пеппы. +

+ {origin}/mcp +

Подключённые приложения

+ {apps.length === 0 ? ( +

Нет подключённых приложений.

+ ) : ( + apps.map((a) => ( +
+
+ {a.name} +
с {a.since.toLocaleDateString("ru-RU")} · последний запрос {ago(a.lastUsedAt)}
+
+
+ + + +
+
+ )) + )} +
+ ); +} diff --git a/apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts b/apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts new file mode 100644 index 00000000..909d8fe7 --- /dev/null +++ b/apps/web/app/.well-known/oauth-authorization-server/[[...path]]/route.ts @@ -0,0 +1,4 @@ +import { authServerMetadata, json, preflight } from "@/lib/oauth"; + +export const GET = async () => json(await authServerMetadata()); +export const OPTIONS = preflight; diff --git a/apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts b/apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts new file mode 100644 index 00000000..6f96a7b2 --- /dev/null +++ b/apps/web/app/.well-known/oauth-protected-resource/[[...path]]/route.ts @@ -0,0 +1,4 @@ +import { json, preflight, resourceMetadata } from "@/lib/oauth"; + +export const GET = async () => json(await resourceMetadata()); +export const OPTIONS = preflight; diff --git a/apps/web/app/.well-known/openid-configuration/route.ts b/apps/web/app/.well-known/openid-configuration/route.ts new file mode 100644 index 00000000..909d8fe7 --- /dev/null +++ b/apps/web/app/.well-known/openid-configuration/route.ts @@ -0,0 +1,4 @@ +import { authServerMetadata, json, preflight } from "@/lib/oauth"; + +export const GET = async () => json(await authServerMetadata()); +export const OPTIONS = preflight; diff --git a/apps/web/app/auth/callback/route.ts b/apps/web/app/auth/callback/route.ts index 80c8cf80..47a49b49 100644 --- a/apps/web/app/auth/callback/route.ts +++ b/apps/web/app/auth/callback/route.ts @@ -2,7 +2,7 @@ import { exchangeOAuthCode, GiteaClient, upsertUserFromGitea } from "@peppa/core import { loadEnv } from "@peppa/shared"; import { cookies } from "next/headers"; import { NextResponse, type NextRequest } from "next/server"; -import { publicOrigin, sessionCookie, STATE_COOKIE } from "@/lib/auth"; +import { NEXT_COOKIE, publicOrigin, safeNext, sessionCookie, STATE_COOKIE } from "@/lib/auth"; import { db } from "@/lib/db"; export async function GET(req: NextRequest) { @@ -18,7 +18,8 @@ export async function GET(req: NextRequest) { const tokens = await exchangeOAuthCode(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, env.GITEA_OAUTH_CLIENT_SECRET, code, `${origin}/auth/callback`); const me = await new GiteaClient(env.GITEA_URL, tokens.access_token).me(); const user = await upsertUserFromGitea(db, me, tokens); - const res = NextResponse.redirect(`${origin}/`); + const res = NextResponse.redirect(`${origin}${safeNext((await cookies()).get(NEXT_COOKIE)?.value)}`); + res.cookies.delete({ name: NEXT_COOKIE, path: "/auth" }); const c = sessionCookie(user.id); res.cookies.set(c.name, c.value, c.options); res.cookies.delete({ name: STATE_COOKIE, path: "/auth" }); diff --git a/apps/web/app/auth/start/route.ts b/apps/web/app/auth/start/route.ts index aeb36d5c..2564e2ea 100644 --- a/apps/web/app/auth/start/route.ts +++ b/apps/web/app/auth/start/route.ts @@ -2,13 +2,15 @@ import { randomBytes } from "node:crypto"; import { oauthAuthorizeUrl } from "@peppa/core"; import { loadEnv } from "@peppa/shared"; import { NextResponse } from "next/server"; -import { publicOrigin, STATE_COOKIE } from "@/lib/auth"; +import { NEXT_COOKIE, publicOrigin, safeNext, STATE_COOKIE } from "@/lib/auth"; -export async function GET() { +export async function GET(req: Request) { const env = loadEnv(); if (!env.GITEA_OAUTH_CLIENT_ID) return new NextResponse("GITEA_OAUTH_CLIENT_ID is not configured", { status: 500 }); const state = randomBytes(18).toString("base64url"); const res = NextResponse.redirect(oauthAuthorizeUrl(env.GITEA_URL, env.GITEA_OAUTH_CLIENT_ID, `${await publicOrigin()}/auth/callback`, state)); + const next = safeNext(new URL(req.url).searchParams.get("next")); + res.cookies.set(NEXT_COOKIE, next, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") }); res.cookies.set(STATE_COOKIE, state, { httpOnly: true, sameSite: "lax", path: "/auth", maxAge: 600, secure: env.PEPPA_WEB_URL.startsWith("https://") }); return res; } diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index 45389fad..e7a018ae 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -151,3 +151,8 @@ details.add { margin: 4px 0; } ul.tasks li { flex-direction: column; align-items: flex-start; } .board { grid-template-columns: 1fr; } } + +.consent { text-align: left; align-items: stretch; } +.consent h1 { justify-content: flex-start; } +.scopes { margin: 0; padding-left: 20px; } +.mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; } diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx index 793d1757..096819b0 100644 --- a/apps/web/app/login/page.tsx +++ b/apps/web/app/login/page.tsx @@ -1,18 +1,18 @@ import { redirect } from "next/navigation"; -import { currentUser } from "@/lib/auth"; +import { currentUser, safeNext } from "@/lib/auth"; import { Flash } from "@/components/ui"; export const dynamic = "force-dynamic"; -export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string }> }) { - if (await currentUser()) redirect("/"); - const { error } = await searchParams; +export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; next?: string }> }) { + const { error, next } = await searchParams; + if (await currentUser()) redirect(safeNext(next)); return (

🐷 Peppa

Софтвейр-фабрика: проекты в Gitea, задачи по OpenSpec, агенты Claude Code и Codex.

- Войти через Gitea + Войти через Gitea
); } diff --git a/apps/web/app/mcp/route.ts b/apps/web/app/mcp/route.ts new file mode 100644 index 00000000..1ed31626 --- /dev/null +++ b/apps/web/app/mcp/route.ts @@ -0,0 +1,36 @@ +import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js"; +import { getUser, verifyAccessToken } from "@peppa/core"; +import { createManagerServer } from "@peppa/mcp/manager"; +import { publicOrigin } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { json, preflight } from "@/lib/oauth"; + +export const dynamic = "force-dynamic"; + +async function unauthorized() { + const o = await publicOrigin(); + return json({ error: "invalid_token", error_description: "Bearer access token required" }, 401, { + "WWW-Authenticate": `Bearer resource_metadata="${o}/.well-known/oauth-protected-resource"`, + }); +} + +/** Remote MCP (Streamable HTTP, stateless): PM tools scoped to the token's user. */ +export async function POST(req: Request) { + const token = req.headers.get("authorization")?.match(/^Bearer\s+(.+)$/i)?.[1]; + const auth = await verifyAccessToken(db, token); + const user = auth && (await getUser(db, auth.userId)); + if (!user) return unauthorized(); + const server = createManagerServer(db, user, await publicOrigin()); + const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true }); + await server.connect(transport); + const res = await transport.handleRequest(req); + const out = new Response(res.body, res); + out.headers.set("Access-Control-Allow-Origin", "*"); + return out; +} + +export async function GET(req: Request) { + if (!req.headers.get("authorization")) return unauthorized(); + return new Response("Method Not Allowed (stateless server: POST only)", { status: 405, headers: { Allow: "POST" } }); +} +export const OPTIONS = preflight; diff --git a/apps/web/app/oauth/authorize/actions.ts b/apps/web/app/oauth/authorize/actions.ts new file mode 100644 index 00000000..fb945033 --- /dev/null +++ b/apps/web/app/oauth/authorize/actions.ts @@ -0,0 +1,35 @@ +"use server"; + +import { issueCode } from "@peppa/core"; +import { redirect } from "next/navigation"; +import { requireUser } from "@/lib/auth"; +import { db } from "@/lib/db"; + +const read = (f: FormData) => ({ + clientId: String(f.get("client_id")), + redirectUri: String(f.get("redirect_uri")), + codeChallenge: String(f.get("code_challenge")), + codeChallengeMethod: String(f.get("code_challenge_method")), + responseType: String(f.get("response_type")), + scope: String(f.get("scope") || "") || undefined, +}); + +function back(redirectUri: string, params: Record, state: string) { + const u = new URL(redirectUri); + for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v); + if (state) u.searchParams.set("state", state); + return u.toString(); +} + +export async function approve(f: FormData) { + const user = await requireUser(); + const r = read(f); + const code = await issueCode(db, r, user.id); + redirect(back(r.redirectUri, { code }, String(f.get("state") ?? ""))); +} + +export async function deny(f: FormData) { + await requireUser(); + const r = read(f); + redirect(back(r.redirectUri, { error: "access_denied" }, String(f.get("state") ?? ""))); +} diff --git a/apps/web/app/oauth/authorize/page.tsx b/apps/web/app/oauth/authorize/page.tsx new file mode 100644 index 00000000..ce003176 --- /dev/null +++ b/apps/web/app/oauth/authorize/page.tsx @@ -0,0 +1,71 @@ +import { checkAuthorizeRequest, OAuthError, type OAuthClient } from "@peppa/core"; +import { redirect } from "next/navigation"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { approve, deny } from "./actions"; + +export const dynamic = "force-dynamic"; + +type Params = Record; + +/** OAuth consent screen: who asks, what they get, allow / deny. */ +export default async function Authorize({ searchParams }: { searchParams: Promise }) { + const p = await searchParams; + const user = await currentUser(); + if (!user) redirect(`/login?next=${encodeURIComponent(`/oauth/authorize?${new URLSearchParams(p as Record)}`)}`); + let client: OAuthClient | null = null; + let error: string | null = null; + try { + client = await checkAuthorizeRequest(db, { + clientId: p.client_id ?? "", + redirectUri: p.redirect_uri ?? "", + codeChallenge: p.code_challenge ?? "", + codeChallengeMethod: p.code_challenge_method ?? "", + responseType: p.response_type ?? "", + scope: p.scope, + }); + } catch (e) { + error = e instanceof OAuthError ? e.message : (e as Error).message; + } + const host = p.redirect_uri ? new URL(p.redirect_uri).host : ""; + return ( +
+

🐷 Peppa

+ {error || !client ? ( +

Запрос авторизации некорректен: {error}

+ ) : ( + <> +

+ {client.name} ({host}) просит доступ к Пеппе от имени {user.login}. +

+
    +
  • видеть ваши проекты, цели, задачи и вопросы агентов;
  • +
  • создавать задачи и двигать карточки — перенос в «В работе» запускает агента;
  • +
  • отвечать на вопросы агентов и принимать ревью.
  • +
+

Отозвать доступ можно в «Настройки → Подключённые приложения».

+
+
+ + + +
+ + + +
+ + )} +
+ ); +} + +function Hidden({ p }: { p: Params }) { + return ( + <> + {(["client_id", "redirect_uri", "code_challenge", "code_challenge_method", "response_type", "scope", "state"] as const).map((k) => ( + + ))} + + ); +} diff --git a/apps/web/app/oauth/register/route.ts b/apps/web/app/oauth/register/route.ts new file mode 100644 index 00000000..e6b92fc5 --- /dev/null +++ b/apps/web/app/oauth/register/route.ts @@ -0,0 +1,27 @@ +import { OAuthError, registerClient } from "@peppa/core"; +import { db } from "@/lib/db"; +import { json, preflight } from "@/lib/oauth"; + +/** RFC 7591 dynamic client registration. */ +export async function POST(req: Request) { + const body = (await req.json().catch(() => ({}))) as { client_name?: string; redirect_uris?: unknown }; + try { + const c = await registerClient(db, body.client_name, body.redirect_uris); + return json( + { + client_id: c.id, + client_name: c.name, + redirect_uris: c.redirectUris, + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_id_issued_at: Math.floor(c.createdAt.getTime() / 1000), + }, + 201, + ); + } catch (e) { + if (e instanceof OAuthError) return json({ error: e.error, error_description: e.message }, 400); + throw e; + } +} +export const OPTIONS = preflight; diff --git a/apps/web/app/oauth/token/route.ts b/apps/web/app/oauth/token/route.ts new file mode 100644 index 00000000..db9b879b --- /dev/null +++ b/apps/web/app/oauth/token/route.ts @@ -0,0 +1,17 @@ +import { exchangeToken, OAuthError } from "@peppa/core"; +import { db } from "@/lib/db"; +import { json, preflight } from "@/lib/oauth"; + +export async function POST(req: Request) { + const type = req.headers.get("content-type") ?? ""; + const params: Record = type.includes("application/json") + ? ((await req.json().catch(() => ({}))) as Record) + : Object.fromEntries(new URLSearchParams(await req.text())); + try { + return json(await exchangeToken(db, params)); + } catch (e) { + if (e instanceof OAuthError) return json({ error: e.error, error_description: e.message }, e.error === "invalid_client" ? 401 : 400); + throw e; + } +} +export const OPTIONS = preflight; diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.ts index 73f11960..0ad62a98 100644 --- a/apps/web/lib/auth.ts +++ b/apps/web/lib/auth.ts @@ -6,6 +6,10 @@ import { db } from "./db"; export const SESSION_COOKIE = "peppa_session"; export const STATE_COOKIE = "peppa_oauth_state"; +export const NEXT_COOKIE = "peppa_next"; + +/** Only same-site relative paths are allowed as a post-login destination. */ +export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/"); const SESSION_DAYS = 30; interface SessionPayload { diff --git a/apps/web/lib/oauth.ts b/apps/web/lib/oauth.ts new file mode 100644 index 00000000..3b55cd7c --- /dev/null +++ b/apps/web/lib/oauth.ts @@ -0,0 +1,33 @@ +import { publicOrigin } from "./auth"; + +export async function authServerMetadata() { + const o = await publicOrigin(); + return { + issuer: o, + authorization_endpoint: `${o}/oauth/authorize`, + token_endpoint: `${o}/oauth/token`, + registration_endpoint: `${o}/oauth/register`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: ["peppa"], + }; +} + +export async function resourceMetadata() { + const o = await publicOrigin(); + return { resource: `${o}/mcp`, authorization_servers: [o], scopes_supported: ["peppa"], bearer_methods_supported: ["header"], resource_name: "Peppa" }; +} + +export const json = (body: unknown, status = 200, headers: Record = {}) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*", ...headers }, + }); + +export const preflight = () => + new Response(null, { + status: 204, + headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "Authorization, Content-Type, Mcp-Protocol-Version" }, + }); diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index becb03c4..bd041e4a 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -2,7 +2,7 @@ import type { NextConfig } from "next"; const config: NextConfig = { // Workspace packages ship TypeScript sources. - transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner"], + transpilePackages: ["@peppa/db", "@peppa/shared", "@peppa/core", "@peppa/runner", "@peppa/mcp"], }; export default config; diff --git a/apps/web/package.json b/apps/web/package.json index 3f69586a..fa129491 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -17,7 +17,9 @@ "react-dom": "19.3.1", "@peppa/core": "workspace:*", "@peppa/runner": "workspace:*", - "drizzle-orm": "0.45.4" + "drizzle-orm": "0.45.4", + "@peppa/mcp": "workspace:*", + "@modelcontextprotocol/sdk": "1.32.2" }, "devDependencies": { "@types/react": "19.3.0", diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md new file mode 100644 index 00000000..1ba7fea3 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/design.md @@ -0,0 +1,21 @@ +# Design: PEP-8 + +## Decisions + +1. **Пеппа — свой сервер авторизации** (не Gitea): ChatGPT нужен DCR, а токен должен + ограничиваться проектами пользователя Пеппы. Вход пользователя — существующая cookie + (Gitea OAuth), затем согласие. +2. **Непрозрачные токены** (32 байта, base64url), в БД — HMAC-хэш; без JWT: проверка + всё равно ходит в БД (отзыв). +3. **MCP stateless**: на каждый POST — новый `McpServer` + `WebStandardStreamableHTTPServerTransport` + с `enableJsonResponse`; пользователь берётся из токена. Инструменты PM — модуль + `@peppa/mcp/manager`, тонкие обёртки над core/runner (`moveTask`, `acceptTask`, + `answerAndDeliver`) с `projectForUser`. +4. **Redirect URI** при регистрации — только https или http://localhost/127.0.0.1; + при авторизации — точное совпадение с зарегистрированным. + +## Risks / Trade-offs + +- [Широкий доступ одного токена ко всем проектам пользователя] → согласие явно говорит + об этом; отзыв в вебе. +- [Спам регистраций DCR] → клиенты без токенов дешёвые; чистка неиспользуемых позже. diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md new file mode 100644 index 00000000..14865525 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/proposal.md @@ -0,0 +1,41 @@ +# Proposal: PEP-8 — удалённый MCP Пеппы (ChatGPT и др.) + +Задача Пеппы: **PEP-8** · Цель #2 «Мультипользовательская веб-платформа». + +## Why + +PM хочет управлять задачами из ChatGPT: «двинь PEP-3 в работу», «что ждёт моего +ответа?». ChatGPT подключает только удалённые MCP-серверы по HTTPS с OAuth; текущий +MCP Пеппы — локальный stdio для агентов. + +## What Changes + +- Пеппа становится OAuth 2.1 сервером авторизации для своих API: метаданные + (RFC 8414, RFC 9728), динамическая регистрация клиентов (RFC 7591), authorization code + + PKCE S256, refresh-токены с ротацией. Вход — обычный вход Пеппы через Gitea, затем + экран согласия. +- MCP-эндпоинт `https://peppa.telecom.quest/mcp` (Streamable HTTP, без сессий), токен + Bearer. Инструменты PM в рамках проектов пользователя: проекты, цели, задачи + (список/детали/создание), **перенос карточки** (как на доске — запускает/останавливает + агента), входящие вопросы и ответ на них, приёмка ревью. +- Страница «Подключённые приложения» в вебе: список и отзыв доступа. + +Вне scope: MCP для агентов по HTTP (остаётся stdio), скоупы мельче «всё в моих проектах». + +## Capabilities + +### New Capabilities +- `remote-mcp`: OAuth-доступ сторонних клиентов (ChatGPT) к Пеппе и MCP-инструменты PM. + +### Modified Capabilities + +## Impact + +`packages/db` (oauth_clients, oauth_codes, oauth_tokens), `packages/core` (OAuth), +`packages/mcp` (инструменты PM как модуль), `apps/web` (well-known, /oauth/*, /mcp, +согласие, подключённые приложения, `next` при входе), testkit. + +## Решение без вопроса к PM + +Публичный MCP без авторизации отклонён (раскрыл бы проекты всем); OAuth — единственный +вариант, который поддерживает ChatGPT для приватных данных. PM запросил задачу напрямую. diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md new file mode 100644 index 00000000..4394b4d2 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/specs/remote-mcp/spec.md @@ -0,0 +1,49 @@ +# Spec Delta: remote-mcp + +## Purpose + +Даёт сторонним MCP-клиентам (ChatGPT и др.) доступ к проектам пользователя Пеппы по OAuth и набор инструментов PM для управления задачами. + +## ADDED Requirements + +### Requirement: Обнаружение и регистрация клиента +Пеппа SHALL публиковать метаданные защищённого ресурса и сервера авторизации и +принимать динамическую регистрацию клиентов с redirect URI по HTTPS (или localhost). + +#### Scenario: Клиент подключается впервые +- **WHEN** клиент обращается к `/mcp` без токена +- **THEN** получает 401 с `WWW-Authenticate`, указывающим на метаданные ресурса, находит по ним сервер авторизации и регистрируется, получая `client_id` + +### Requirement: Авторизация пользователем +Доступ SHALL выдаваться только после входа пользователя Пеппы и явного согласия на +экране, где названо приложение; используется authorization code с PKCE S256. + +#### Scenario: Согласие +- **WHEN** пользователь, войдя через Gitea, нажимает «Разрешить» для приложения +- **THEN** клиент получает код, обменивает его с верным `code_verifier` на access и refresh токены + +#### Scenario: Отказ или подделка +- **WHEN** пользователь нажимает «Отклонить», или код предъявлен повторно, с неверным verifier или другим redirect URI +- **THEN** токены не выдаются + +### Requirement: Токены +Access-токен SHALL действовать 1 час, refresh — 30 дней с ротацией при использовании; +храниться только в виде хэшей; пользователь видит подключённые приложения и может +отозвать доступ, после чего токены приложения не работают. + +#### Scenario: Отзыв +- **WHEN** пользователь отзывает приложение в вебе +- **THEN** следующий запрос этого приложения к `/mcp` получает 401 + +### Requirement: Инструменты PM +MCP SHALL давать инструменты в пределах проектов пользователя: список проектов и целей, +список и детали задач, создание задачи, перенос карточки (Бэклог/В работе/Ревью/Готово — +с теми же последствиями, что на доске), открытые вопросы и ответ на них, приёмка ревью. + +#### Scenario: Двинуть задачу +- **WHEN** клиент вызывает перенос задачи `PEP-3` в «В работе» +- **THEN** задача `in_progress` и по ней запущен агент, как при переносе на доске + +#### Scenario: Чужой проект +- **WHEN** клиент обращается к задаче проекта, которым пользователь не владеет +- **THEN** получает «не найдено» diff --git a/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md new file mode 100644 index 00000000..af8148d6 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-8-remote-mcp/tasks.md @@ -0,0 +1,16 @@ +# Tasks: PEP-8 + +## 1. OAuth + +- [x] 1.1 Таблицы oauth_clients/codes/tokens; core: регистрация, код с PKCE, обмен, refresh с ротацией, проверка access, отзыв; тесты +- [x] 1.2 Веб: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, `/oauth/register`, `/oauth/authorize` (согласие), `/oauth/token`; `next` после входа + +## 2. MCP + +- [x] 2.1 `@peppa/mcp/manager`: инструменты PM; `/mcp` (401 + WWW-Authenticate, Bearer); тест через MCP-клиент +- [x] 2.2 Страница «Подключённые приложения» с отзывом + +## 3. Проверка + +- [x] 3.1 e2e набор зелёный; выкатка; на проде: DCR → согласие в браузере → токен → MCP-клиент двигает задачу; отзыв → 401 +- [x] 3.2 AGENTS.md + инструкция подключения в ChatGPT; `openspec validate` diff --git a/openspec/specs/remote-mcp/spec.md b/openspec/specs/remote-mcp/spec.md new file mode 100644 index 00000000..c5ee809e --- /dev/null +++ b/openspec/specs/remote-mcp/spec.md @@ -0,0 +1,48 @@ +# remote-mcp Specification + +## Purpose +Даёт сторонним MCP-клиентам (ChatGPT и др.) доступ к проектам пользователя Пеппы по OAuth и набор инструментов PM для управления задачами. + +## Requirements + +### Requirement: Обнаружение и регистрация клиента +Пеппа SHALL публиковать метаданные защищённого ресурса и сервера авторизации и +принимать динамическую регистрацию клиентов с redirect URI по HTTPS (или localhost). + +#### Scenario: Клиент подключается впервые +- **WHEN** клиент обращается к `/mcp` без токена +- **THEN** получает 401 с `WWW-Authenticate`, указывающим на метаданные ресурса, находит по ним сервер авторизации и регистрируется, получая `client_id` + +### Requirement: Авторизация пользователем +Доступ SHALL выдаваться только после входа пользователя Пеппы и явного согласия на +экране, где названо приложение; используется authorization code с PKCE S256. + +#### Scenario: Согласие +- **WHEN** пользователь, войдя через Gitea, нажимает «Разрешить» для приложения +- **THEN** клиент получает код, обменивает его с верным `code_verifier` на access и refresh токены + +#### Scenario: Отказ или подделка +- **WHEN** пользователь нажимает «Отклонить», или код предъявлен повторно, с неверным verifier или другим redirect URI +- **THEN** токены не выдаются + +### Requirement: Токены +Access-токен SHALL действовать 1 час, refresh — 30 дней с ротацией при использовании; +храниться только в виде хэшей; пользователь видит подключённые приложения и может +отозвать доступ, после чего токены приложения не работают. + +#### Scenario: Отзыв +- **WHEN** пользователь отзывает приложение в вебе +- **THEN** следующий запрос этого приложения к `/mcp` получает 401 + +### Requirement: Инструменты PM +MCP SHALL давать инструменты в пределах проектов пользователя: список проектов и целей, +список и детали задач, создание задачи, перенос карточки (Бэклог/В работе/Ревью/Готово — +с теми же последствиями, что на доске), открытые вопросы и ответ на них, приёмка ревью. + +#### Scenario: Двинуть задачу +- **WHEN** клиент вызывает перенос задачи `PEP-3` в «В работе» +- **THEN** задача `in_progress` и по ней запущен агент, как при переносе на доске + +#### Scenario: Чужой проект +- **WHEN** клиент обращается к задаче проекта, которым пользователь не владеет +- **THEN** получает «не найдено» diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c29e957c..d755f68a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -10,3 +10,4 @@ export * from "./telegram.ts"; export * from "./crypto.ts"; export * from "./gitea.ts"; export * from "./users.ts"; +export * from "./oauth.ts"; diff --git a/packages/core/src/oauth.ts b/packages/core/src/oauth.ts new file mode 100644 index 00000000..942e7154 --- /dev/null +++ b/packages/core/src/oauth.ts @@ -0,0 +1,181 @@ +// OAuth 2.1 authorization server for Peppa's remote MCP (ChatGPT connectors etc.): +// dynamic client registration, authorization code + PKCE (S256), access/refresh tokens. +import { createHash, randomBytes } from "node:crypto"; +import { oauthClients, oauthCodes, oauthTokens, type Db } from "@peppa/db"; +import { and, desc, eq, gt, isNull } from "drizzle-orm"; +import { hashToken } from "./crypto.ts"; +import { PeppaError } from "./errors.ts"; + +export type OAuthClient = typeof oauthClients.$inferSelect; + +export const ACCESS_TTL_SEC = 3600; +const REFRESH_TTL_SEC = 30 * 86400; +const CODE_TTL_MS = 10 * 60_000; + +export class OAuthError extends PeppaError { + constructor( + readonly error: "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied", + description: string, + ) { + super(description); + } +} + +const random = () => randomBytes(32).toString("base64url"); + +function validRedirect(uri: string): boolean { + try { + const u = new URL(uri); + if (u.hash) return false; + return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname)); + } catch { + return false; + } +} + +/** RFC 7591 dynamic client registration (public clients, PKCE required). */ +export async function registerClient(db: Db, name: string | undefined, redirectUris: unknown): Promise { + if (!Array.isArray(redirectUris) || !redirectUris.length || !redirectUris.every((u) => typeof u === "string" && validRedirect(u))) { + throw new OAuthError("invalid_redirect_uri", "redirect_uris must be https (or http://localhost) URLs"); + } + const [row] = await db + .insert(oauthClients) + .values({ id: `peppa-${randomBytes(12).toString("base64url")}`, name: (name || "MCP client").slice(0, 100), redirectUris }) + .returning(); + return row!; +} + +export async function getClient(db: Db, id: string): Promise { + const [row] = await db.select().from(oauthClients).where(eq(oauthClients.id, id)); + return row ?? null; +} + +export interface AuthorizeRequest { + clientId: string; + redirectUri: string; + codeChallenge: string; + codeChallengeMethod: string; + responseType: string; + scope?: string; +} + +/** Validates an /authorize request; throws OAuthError (shown to the user, not redirected). */ +export async function checkAuthorizeRequest(db: Db, r: AuthorizeRequest): Promise { + const client = await getClient(db, r.clientId); + if (!client) throw new OAuthError("invalid_client", "Неизвестное приложение (client_id)"); + if (!client.redirectUris.includes(r.redirectUri)) throw new OAuthError("invalid_redirect_uri", "redirect_uri не зарегистрирован для приложения"); + if (r.responseType !== "code") throw new OAuthError("invalid_request", "response_type должен быть code"); + if (r.codeChallengeMethod !== "S256" || !/^[A-Za-z0-9_-]{43,128}$/.test(r.codeChallenge)) { + throw new OAuthError("invalid_request", "Нужен PKCE (code_challenge, метод S256)"); + } + return client; +} + +/** Issues a one-time authorization code after the user consented. */ +export async function issueCode(db: Db, r: AuthorizeRequest, userId: number): Promise { + await checkAuthorizeRequest(db, r); + const code = random(); + await db.insert(oauthCodes).values({ + codeHash: hashToken(code), + clientId: r.clientId, + userId, + redirectUri: r.redirectUri, + codeChallenge: r.codeChallenge, + scope: r.scope ?? null, + expiresAt: new Date(Date.now() + CODE_TTL_MS), + }); + return code; +} + +export interface TokenResponse { + access_token: string; + token_type: "Bearer"; + expires_in: number; + refresh_token: string; + scope?: string; +} + +async function issueTokens(db: Db, clientId: string, userId: number, scope: string | null): Promise { + const access = random(); + const refresh = random(); + await db.insert(oauthTokens).values([ + { tokenHash: hashToken(access), kind: "access", clientId, userId, scope, expiresAt: new Date(Date.now() + ACCESS_TTL_SEC * 1000) }, + { tokenHash: hashToken(refresh), kind: "refresh", clientId, userId, scope, expiresAt: new Date(Date.now() + REFRESH_TTL_SEC * 1000) }, + ]); + return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_SEC, refresh_token: refresh, ...(scope ? { scope } : {}) }; +} + +const s256 = (verifier: string) => createHash("sha256").update(verifier).digest("base64url"); + +/** POST /oauth/token for authorization_code and refresh_token grants. */ +export async function exchangeToken(db: Db, p: Record): Promise { + if (p.grant_type === "authorization_code") { + if (!p.code || !p.client_id || !p.redirect_uri || !p.code_verifier) throw new OAuthError("invalid_request", "code, client_id, redirect_uri and code_verifier are required"); + // Mark used atomically: a replayed code never yields tokens. + const [c] = await db + .update(oauthCodes) + .set({ usedAt: new Date() }) + .where(and(eq(oauthCodes.codeHash, hashToken(p.code)), isNull(oauthCodes.usedAt), gt(oauthCodes.expiresAt, new Date()))) + .returning(); + if (!c) throw new OAuthError("invalid_grant", "code is invalid, expired or already used"); + if (c.clientId !== p.client_id || c.redirectUri !== p.redirect_uri) throw new OAuthError("invalid_grant", "client_id or redirect_uri mismatch"); + if (s256(p.code_verifier) !== c.codeChallenge) throw new OAuthError("invalid_grant", "PKCE verification failed"); + return issueTokens(db, c.clientId, c.userId, c.scope); + } + if (p.grant_type === "refresh_token") { + if (!p.refresh_token) throw new OAuthError("invalid_request", "refresh_token is required"); + const [t] = await db + .update(oauthTokens) + .set({ revokedAt: new Date() }) + .where( + and( + eq(oauthTokens.tokenHash, hashToken(p.refresh_token)), + eq(oauthTokens.kind, "refresh"), + isNull(oauthTokens.revokedAt), + gt(oauthTokens.expiresAt, new Date()), + ), + ) + .returning(); + if (!t || (p.client_id && p.client_id !== t.clientId)) throw new OAuthError("invalid_grant", "refresh_token is invalid"); + return issueTokens(db, t.clientId, t.userId, t.scope); + } + throw new OAuthError("unsupported_grant_type", `grant_type ${p.grant_type ?? "(none)"} is not supported`); +} + +/** Bearer token → { userId, clientId }, or null. */ +export async function verifyAccessToken(db: Db, token: string | undefined | null): Promise<{ userId: number; clientId: string } | null> { + if (!token) return null; + const [t] = await db + .update(oauthTokens) + .set({ lastUsedAt: new Date() }) + .where(and(eq(oauthTokens.tokenHash, hashToken(token)), eq(oauthTokens.kind, "access"), isNull(oauthTokens.revokedAt), gt(oauthTokens.expiresAt, new Date()))) + .returning(); + return t ? { userId: t.userId, clientId: t.clientId } : null; +} + +/** Apps the user has granted access to (live refresh tokens), most recent first. */ +export async function connectedApps(db: Db, userId: number) { + const rows = await db + .select({ clientId: oauthTokens.clientId, name: oauthClients.name, createdAt: oauthTokens.createdAt, lastUsedAt: oauthTokens.lastUsedAt }) + .from(oauthTokens) + .innerJoin(oauthClients, eq(oauthTokens.clientId, oauthClients.id)) + .where(and(eq(oauthTokens.userId, userId), isNull(oauthTokens.revokedAt), gt(oauthTokens.expiresAt, new Date()))) + .orderBy(desc(oauthTokens.createdAt)); + const byClient = new Map(); + for (const r of rows) { + const cur = byClient.get(r.clientId); + if (!cur) byClient.set(r.clientId, { clientId: r.clientId, name: r.name, since: r.createdAt, lastUsedAt: r.lastUsedAt }); + else if (r.lastUsedAt && (!cur.lastUsedAt || r.lastUsedAt > cur.lastUsedAt)) cur.lastUsedAt = r.lastUsedAt; + } + return [...byClient.values()]; +} + +/** Revokes every token of `clientId` for this user. */ +export async function revokeApp(db: Db, userId: number, clientId: string): Promise { + const rows = await db + .update(oauthTokens) + .set({ revokedAt: new Date() }) + .where(and(eq(oauthTokens.userId, userId), eq(oauthTokens.clientId, clientId), isNull(oauthTokens.revokedAt))) + .returning(); + return rows.length; +} diff --git a/packages/db/migrations/0006_crazy_stellaris.sql b/packages/db/migrations/0006_crazy_stellaris.sql new file mode 100644 index 00000000..d458e934 --- /dev/null +++ b/packages/db/migrations/0006_crazy_stellaris.sql @@ -0,0 +1,34 @@ +CREATE TABLE "oauth_clients" ( + "id" text PRIMARY KEY NOT NULL, + "name" text NOT NULL, + "redirect_uris" jsonb NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "oauth_codes" ( + "code_hash" text PRIMARY KEY NOT NULL, + "client_id" text NOT NULL, + "user_id" integer NOT NULL, + "redirect_uri" text NOT NULL, + "code_challenge" text NOT NULL, + "scope" text, + "expires_at" timestamp with time zone NOT NULL, + "used_at" timestamp with time zone +); +--> statement-breakpoint +CREATE TABLE "oauth_tokens" ( + "token_hash" text PRIMARY KEY NOT NULL, + "kind" text NOT NULL, + "client_id" text NOT NULL, + "user_id" integer NOT NULL, + "scope" text, + "expires_at" timestamp with time zone NOT NULL, + "revoked_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "last_used_at" timestamp with time zone +); +--> statement-breakpoint +ALTER TABLE "oauth_codes" ADD CONSTRAINT "oauth_codes_client_id_oauth_clients_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_clients"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "oauth_codes" ADD CONSTRAINT "oauth_codes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "oauth_tokens" ADD CONSTRAINT "oauth_tokens_client_id_oauth_clients_id_fk" FOREIGN KEY ("client_id") REFERENCES "public"."oauth_clients"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "oauth_tokens" ADD CONSTRAINT "oauth_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action; \ No newline at end of file diff --git a/packages/db/migrations/meta/0006_snapshot.json b/packages/db/migrations/meta/0006_snapshot.json new file mode 100644 index 00000000..c656e4b6 --- /dev/null +++ b/packages/db/migrations/meta/0006_snapshot.json @@ -0,0 +1,1231 @@ +{ + "id": "141bce5b-54a3-438f-b6c9-edf22525ab7b", + "prevId": "62fecad8-73cc-4298-a603-a38021323859", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 3f8f0819..2126e00e 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -43,6 +43,13 @@ "when": 1794499927803, "tag": "0005_sloppy_blue_marvel", "breakpoints": true + }, + { + "idx": 6, + "version": "7", + "when": 1794500991061, + "tag": "0006_crazy_stellaris", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index f2390918..f9178bac 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -177,6 +177,39 @@ export const telegramUpdates = pgTable("telegram_updates", { createdAt: createdAt(), }); +/** OAuth clients registered dynamically (RFC 7591), e.g. ChatGPT connectors. */ +export const oauthClients = pgTable("oauth_clients", { + id: text("id").primaryKey(), + name: text("name").notNull(), + redirectUris: jsonb("redirect_uris").$type().notNull(), + createdAt: createdAt(), +}); + +/** Authorization codes (PKCE S256), single use, 10 minutes. Stored hashed. */ +export const oauthCodes = pgTable("oauth_codes", { + codeHash: text("code_hash").primaryKey(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + redirectUri: text("redirect_uri").notNull(), + codeChallenge: text("code_challenge").notNull(), + scope: text("scope"), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + usedAt: timestamp("used_at", { withTimezone: true }), +}); + +/** Access (1 h) and refresh (30 d, rotated) tokens. Stored hashed. */ +export const oauthTokens = pgTable("oauth_tokens", { + tokenHash: text("token_hash").primaryKey(), + kind: text("kind", { enum: ["access", "refresh"] }).notNull(), + clientId: text("client_id").notNull().references(() => oauthClients.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + scope: text("scope"), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + createdAt: createdAt(), + lastUsedAt: timestamp("last_used_at", { withTimezone: true }), +}); + export const projectsRelations = relations(projects, ({ many }) => ({ goals: many(goals), tasks: many(tasks), diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 8ca924af..f38906c2 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -3,13 +3,23 @@ "version": "0.0.0", "private": true, "type": "module", - "bin": { "peppa-mcp": "./bin/peppa-mcp" }, - "scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, + "bin": { + "peppa-mcp": "./bin/peppa-mcp" + }, + "scripts": { + "start": "tsx src/index.ts", + "typecheck": "tsc -p ." + }, "dependencies": { "@modelcontextprotocol/sdk": "1.32.2", "@peppa/core": "workspace:*", "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*", - "zod": "4.6.7" + "zod": "4.6.7", + "@peppa/runner": "workspace:*", + "drizzle-orm": "0.45.4" + }, + "exports": { + "./manager": "./src/manager.ts" } } diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts new file mode 100644 index 00000000..6aed54f6 --- /dev/null +++ b/packages/mcp/src/manager.ts @@ -0,0 +1,150 @@ +// PM-side MCP tools for remote clients (ChatGPT connectors etc.), scoped to one Peppa +// user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server. +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { + createTask, + getProject, + getQuestion, + getTaskDetails, + listGoals, + listTasks, + listUserProjects, + PeppaError, + projectForUser, + resolveTask, + type User, +} from "@peppa/core"; +import { questions, projects, tasks, type Db } from "@peppa/db"; +import { formatTaskKey } from "@peppa/shared"; +import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, type BoardColumn, type Provider } from "@peppa/runner"; +import { and, asc, eq, isNull } from "drizzle-orm"; +import { z } from "zod"; +import { formatTask } from "./format.ts"; + +type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean }; +const COLUMNS = ["backlog", "in_progress", "review", "done"] as const; +const COLUMN_NAME: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" }; + +export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { + const server = new McpServer({ name: "peppa", version: "0.2.0" }); + + function tool(name: string, description: string, inputSchema: S, readOnly: boolean, run: (a: z.infer>) => Promise) { + server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer>): Promise => { + try { + return { content: [{ type: "text", text: await run(a) }] }; + } catch (e) { + return { content: [{ type: "text", text: e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}` }], isError: true }; + } + }) as never); + } + + const ownedProject = async (keyOrSlug: string) => projectForUser(db, user.id, (await getProject(db, keyOrSlug).catch(() => { throw new PeppaError("Не найдено"); })).id); + const ownedTask = async (key: string) => { + const ref = await resolveTask(db, key).catch(() => { throw new PeppaError("Не найдено"); }); + await projectForUser(db, user.id, ref.project.id); + return ref; + }; + const taskArg = z.string().describe("Task key, e.g. PEP-3"); + const projectArg = z.string().describe("Project key (e.g. PEP) or slug"); + + tool("list_projects", "List the user's Peppa projects (key, name, Gitea repo, task counts by board column).", {}, true, async () => { + const ps = await listUserProjects(db, user.id); + if (!ps.length) return "No projects yet. Create one at " + webUrl + "/projects/new"; + const lines = []; + for (const p of ps) { + const ts = await listTasks(db, { projectId: p.id }); + const counts = COLUMNS.map((c) => `${COLUMN_NAME[c]} ${ts.filter((t) => columnOf(t.status) === c).length}`).join(", "); + lines.push(`- ${p.key} — ${p.name} (${p.giteaOwner}/${p.giteaRepo}): ${counts}`); + } + return lines.join("\n"); + }); + + tool("list_goals", "List open top-level goals of a project.", { project: projectArg }, true, async ({ project }) => { + const p = await ownedProject(project); + const gs = await listGoals(db, p.id); + return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals."; + }); + + tool( + "list_tasks", + "List tasks of a project as a board (Backlog / In progress / Review / Done), optionally one column.", + { project: projectArg, column: z.enum(COLUMNS).optional() }, + true, + async ({ project, column }) => { + const p = await ownedProject(project); + const ts = await listTasks(db, { projectId: p.id }); + const out: string[] = []; + for (const c of column ? [column] : COLUMNS) { + const inCol = ts.filter((t) => columnOf(t.status) === c); + out.push(`## ${COLUMN_NAME[c]} (${inCol.length})`, ...inCol.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`)); + } + return out.join("\n"); + }, + ); + + tool("get_task", "Get a task: description, goal, status, OpenSpec change, PM questions, progress.", { task: taskArg }, true, async ({ task }) => { + const ref = await ownedTask(task); + return `${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`; + }); + + tool( + "create_task", + "Create a task in a project (lands in Backlog). Link it to a goal when possible.", + { project: projectArg, title: z.string().min(3), description: z.string().optional(), goal_id: z.number().int().optional() }, + false, + async ({ project, title, description, goal_id }) => { + const p = await ownedProject(project); + const ref = await createTask(db, { projectId: p.id, title, description, goalId: goal_id }); + return `Created ${ref.key}: ${title} (Backlog). ${webUrl}/t/${ref.key}`; + }, + ); + + tool( + "move_task", + "Move a task card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.", + { task: taskArg, to: z.enum(COLUMNS), provider: z.enum(["claude", "codex"]).optional().describe("Agent for in_progress (default claude)") }, + false, + async ({ task, to, provider }) => { + const ref = await ownedTask(task); + const r = await moveTask(db, ref, to, { provider: provider as Provider | undefined }); + return `${ref.key} → ${COLUMN_NAME[to]}${r.started ? ` · agent session #${r.started} started` : ""}${r.stopped ? ` · ${r.stopped} session(s) stopped` : ""}`; + }, + ); + + tool("list_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => { + const rows = await db + .select({ q: questions, key: projects.key, number: tasks.number, status: tasks.status }) + .from(questions) + .innerJoin(projects, eq(questions.projectId, projects.id)) + .leftJoin(tasks, eq(questions.taskId, tasks.id)) + .where(and(eq(projects.ownerId, user.id), isNull(questions.answeredAt))) + .orderBy(asc(questions.id)); + if (!rows.length) return "Inbox is empty — agents need nothing from you."; + return rows + .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(" | ")}` : ""}`; + }) + .join("\n"); + }); + + tool( + "answer_question", + "Answer an open inbox question; the answer is delivered into the agent's session. For approvals answer 'ok' to approve or a comment to send back. For permissions: allow | always | deny. For ready-for-review: 'accept' closes the task, any other text goes back to the agent.", + { question_id: z.number().int(), answer: z.string().min(1) }, + false, + async ({ question_id, answer }) => { + const q = await getQuestion(db, question_id).catch(() => { throw new PeppaError("Не найдено"); }); + await projectForUser(db, user.id, q.projectId); + if (q.answeredAt) return `Already answered (${q.answeredVia}): ${q.answer}`; + if (answer.trim().toLowerCase() === "accept" && (await isReviewQuestion(db, q))) { + const ref = await acceptTask(db, q.id, "web"); + return `${ref.key} accepted → Done`; + } + const { delivered } = await answerAndDeliver(db, q.id, answer, "web"); + return delivered ? "Delivered to the agent session." : "Saved; the session is not running right now."; + }, + ); + + return server; +} diff --git a/packages/testkit/package.json b/packages/testkit/package.json index f8220cca..4a9e15a9 100644 --- a/packages/testkit/package.json +++ b/packages/testkit/package.json @@ -14,6 +14,7 @@ "@peppa/runner": "workspace:*", "@peppa/shared": "workspace:*", "drizzle-orm": "0.45.4", - "@peppa/bot": "workspace:*" + "@peppa/bot": "workspace:*", + "@peppa/mcp": "workspace:*" } } diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts new file mode 100644 index 00000000..eeb62c01 --- /dev/null +++ b/packages/testkit/test/oauth.test.ts @@ -0,0 +1,127 @@ +// PEP-8: OAuth 2.1 server and the PM MCP tools served to remote clients (ChatGPT). +import assert from "node:assert/strict"; +import { createHash, randomBytes } from "node:crypto"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const { createManagerServer } = await import("@peppa/mcp/manager"); + +const REDIRECT = "https://chatgpt.com/connector_platform_oauth_redirect"; +let owner: Awaited>; +let stranger: Awaited>; + +before(async () => { + owner = await core.upsertUserFromGitea(db, { id: 21, login: "mock-owner" }, { access_token: "x" }); + stranger = await core.upsertUserFromGitea(db, { id: 22, login: "mock-stranger" }, { access_token: "y" }); +}); +after(teardown); + +const pkce = () => { + const verifier = randomBytes(32).toString("base64url"); + return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") }; +}; + +async function authorize(clientId: string, userId: number, challenge: string) { + return core.issueCode(db, { clientId, redirectUri: REDIRECT, codeChallenge: challenge, codeChallengeMethod: "S256", responseType: "code" }, userId); +} + +describe("OAuth server", () => { + test("dynamic registration accepts https/localhost redirects only", async () => { + await assert.rejects(core.registerClient(db, "bad", ["http://evil.example/cb"]), /redirect_uris/); + await assert.rejects(core.registerClient(db, "bad", []), /redirect_uris/); + const c = await core.registerClient(db, "ChatGPT", [REDIRECT, "http://localhost:8765/cb"]); + assert.match(c.id, /^peppa-/); + }); + + test("authorize request validation", async () => { + const c = await core.registerClient(db, "ChatGPT", [REDIRECT]); + const ok = { clientId: c.id, redirectUri: REDIRECT, codeChallenge: pkce().challenge, codeChallengeMethod: "S256", responseType: "code" }; + await core.checkAuthorizeRequest(db, ok); + await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, clientId: "nope" }), /Неизвестное приложение/); + await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, redirectUri: "https://other.example/cb" }), /не зарегистрирован/); + await assert.rejects(core.checkAuthorizeRequest(db, { ...ok, codeChallengeMethod: "plain" }), /PKCE/); + }); + + test("code + PKCE → tokens; replay, wrong verifier and wrong redirect are refused", async () => { + const c = await core.registerClient(db, "ChatGPT", [REDIRECT]); + const { verifier, challenge } = pkce(); + const code = await authorize(c.id, owner.id, challenge); + const base = { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT }; + const t = await core.exchangeToken(db, { ...base, code, code_verifier: verifier }); + assert.equal(t.token_type, "Bearer"); + assert.deepEqual(await core.verifyAccessToken(db, t.access_token), { userId: owner.id, clientId: c.id }); + await assert.rejects(core.exchangeToken(db, { ...base, code, code_verifier: verifier }), /already used/); + + const p2 = pkce(); + const code2 = await authorize(c.id, owner.id, p2.challenge); + await assert.rejects(core.exchangeToken(db, { ...base, code: code2, code_verifier: pkce().verifier }), /PKCE/); + const p3 = pkce(); + const code3 = await authorize(c.id, owner.id, p3.challenge); + await assert.rejects(core.exchangeToken(db, { ...base, redirect_uri: "https://other.example/cb", code: code3, code_verifier: p3.verifier }), /mismatch/); + assert.equal(await core.verifyAccessToken(db, "garbage"), null); + }); + + test("refresh tokens rotate; revoking the app kills its tokens", async () => { + const c = await core.registerClient(db, "ChatGPT revoke", [REDIRECT]); + const { verifier, challenge } = pkce(); + const t1 = await core.exchangeToken(db, { grant_type: "authorization_code", client_id: c.id, redirect_uri: REDIRECT, code: await authorize(c.id, owner.id, challenge), code_verifier: verifier }); + const t2 = await core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token, client_id: c.id }); + await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t1.refresh_token }), /invalid/, "old refresh token is single use"); + assert.ok(await core.verifyAccessToken(db, t2.access_token)); + assert.ok((await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id)); + assert.ok((await core.revokeApp(db, owner.id, c.id)) > 0); + assert.equal(await core.verifyAccessToken(db, t2.access_token), null); + await assert.rejects(core.exchangeToken(db, { grant_type: "refresh_token", refresh_token: t2.refresh_token }), /invalid/); + assert.ok(!(await core.connectedApps(db, owner.id)).some((a) => a.clientId === c.id)); + }); +}); + +async function mcpAs(user: typeof owner) { + const [a, b] = InMemoryTransport.createLinkedPair(); + await createManagerServer(db, user, "https://peppa.test").connect(a); + const client = new Client({ name: "mock-chatgpt", version: "0" }); + await client.connect(b); + const call = 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 }; + }; + return { client, call }; +} + +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 proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + const { client, call } = await mcpAs(owner); + const tools = (await client.listTools()).tools; + assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task"]); + assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); + assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); + + assert.match((await call("list_projects")).text, new RegExp(`${p.key} — `)); + const created = await call("create_task", { project: p.key, title: "Из ChatGPT: порт сервиса" }); + assert.match(created.text, new RegExp(`Created ${p.key}-2`)); + assert.match((await call("list_tasks", { project: p.key, column: "backlog" })).text, /Из ChatGPT/); + + const moved = await call("move_task", { task: `${p.key}-2`, to: "in_progress" }); + assert.match(moved.text, /agent session #\d+ started/); + const sid = Number(/#(\d+)/.exec(moved.text)![1]); + const q = await p.waitQuestion(sid, "question"); + assert.match((await call("list_inbox")).text, new RegExp(`#${q.id} ${p.key}-2 · question`)); + assert.match((await call("answer_question", { question_id: q.id, answer: "3000" })).text, /Delivered/); + await p.waitLog("answer reached the agent", (e) => e.ev === "prompt" && String(e.prompt).includes(": 3000")); + + const s = await mcpAs(stranger); + assert.match((await s.call("list_projects")).text, /No projects/); + const denied = await s.call("move_task", { task: `${p.key}-2`, to: "backlog" }); + assert.ok(denied.isError); + assert.match(denied.text, /Не найдено/); + assert.ok((await s.call("answer_question", { question_id: q.id, answer: "x" })).isError); + + assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/); + }); +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9a62b0de..3bacea5e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -196,12 +196,18 @@ importers: apps/web: dependencies: + '@modelcontextprotocol/sdk': + specifier: 1.32.2 + version: 1.32.2(zod@4.6.7) '@peppa/core': specifier: workspace:* version: link:../../packages/core '@peppa/db': specifier: workspace:* version: link:../../packages/db + '@peppa/mcp': + specifier: workspace:* + version: link:../../packages/mcp '@peppa/runner': specifier: workspace:* version: link:../../packages/runner @@ -282,9 +288,15 @@ importers: '@peppa/db': specifier: workspace:* version: link:../db + '@peppa/runner': + specifier: workspace:* + version: link:../runner '@peppa/shared': specifier: workspace:* version: link:../shared + drizzle-orm: + specifier: 0.45.4 + version: 0.45.4(postgres@4.1.1) zod: specifier: 4.6.7 version: 4.6.7 @@ -324,6 +336,9 @@ importers: '@peppa/db': specifier: workspace:* version: link:../db + '@peppa/mcp': + specifier: workspace:* + version: link:../mcp '@peppa/runner': specifier: workspace:* version: link:../runner -- 2.45.2 From 4e20f767675dea740eab5ace8709dd921815d030 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 21:52:46 +0500 Subject: [PATCH 002/554] PEP-11: update_task in the remote MCP - edit a task's title and/or description by key through the owner-scoped manager tools; goal, status and other fields kept, no agent started; uses core updateTask (event log, NOTIFY) and returns the updated card - test: title only, description only, both; goal/status/sessions intact; empty call and another user's task refused (54 e2e total, green) - verified on prod: tools/list over HTTPS includes update_task - OpenSpec: pep-11 archived into spec remote-mcp Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../.openspec.yaml | 2 + .../proposal.md | 28 ++++++++++++ .../specs/remote-mcp/spec.md | 20 +++++++++ .../tasks.md | 10 +++++ openspec/specs/remote-mcp/spec.md | 17 +++++++ packages/mcp/src/manager.ts | 19 ++++++++ packages/testkit/test/oauth.test.ts | 44 ++++++++++++++++++- 8 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/proposal.md create mode 100644 openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/specs/remote-mcp/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/tasks.md diff --git a/AGENTS.md b/AGENTS.md index 48b12d13..713777b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё - `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов -- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, list_goals, list_tasks, get_task, create_task, move_task (как доска — запускает агента), list_inbox, answer_question +- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, list_goals, list_tasks, get_task, create_task, update_task (название/описание, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question - `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` diff --git a/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/proposal.md b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/proposal.md new file mode 100644 index 00000000..83224f73 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/proposal.md @@ -0,0 +1,28 @@ +# Proposal: PEP-11 — update_task в удалённом MCP + +Задача Пеппы: **PEP-11** · Цель #2. + +## Why + +Через удалённый MCP (ChatGPT, Codex) задачу можно создать и подвинуть, но нельзя +исправить её название или описание — приходится заводить дубликат. + +## What Changes + +- Новый инструмент `update_task` в удалённом MCP: ключ задачи, `title` и/или + `description` (каждое необязательно, хотя бы одно обязательно). Цель, статус и прочие + поля не меняются, исполнитель не запускается и не останавливается. Ответ — обновлённая + карточка (как `get_task`). +- Изменение пишется в ленту событий задачи тем же механизмом, что остальные правки. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `remote-mcp`: инструменты PM дополняются редактированием названия и описания задачи. + +## Impact + +`packages/mcp/src/manager.ts`, тест в `packages/testkit`. Клиентам, которые кэшируют +список инструментов (ChatGPT, Codex), может понадобиться обновить/переподключить коннектор. diff --git a/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/specs/remote-mcp/spec.md b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/specs/remote-mcp/spec.md new file mode 100644 index 00000000..d6718d80 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/specs/remote-mcp/spec.md @@ -0,0 +1,20 @@ +# Spec Delta: remote-mcp + +## ADDED Requirements + +### Requirement: Редактирование задачи +MCP SHALL позволять менять название и описание задачи проекта пользователя независимо +друг от друга, не меняя цель, статус и прочие поля и не запуская и не останавливая +агента; ответ содержит обновлённую карточку задачи. + +#### Scenario: Только название +- **WHEN** клиент вызывает `update_task` с ключом и новым `title` +- **THEN** меняется только название; описание, цель и статус прежние, сессий не прибавилось + +#### Scenario: Только описание +- **WHEN** клиент вызывает `update_task` с ключом и новым `description` +- **THEN** меняется только описание; название, цель и статус прежние + +#### Scenario: Без полей или чужая задача +- **WHEN** не передано ни `title`, ни `description`, или задача из чужого проекта +- **THEN** ошибка, задача не меняется diff --git a/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/tasks.md b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/tasks.md new file mode 100644 index 00000000..825860b6 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-11-mcp-update-task/tasks.md @@ -0,0 +1,10 @@ +# Tasks: PEP-11 + +## 1. Инструмент + +- [x] 1.1 `update_task` в `@peppa/mcp/manager` через `updateTask` core (события, NOTIFY) с проверкой владельца; ответ — карточка +- [x] 1.2 Тест: только название, только описание, оба; цель/статус/сессии не меняются; пустой вызов и чужая задача — ошибка; инструмент в `tools/list` + +## 2. Выкатка + +- [x] 2.1 Сборка и перезапуск веба; `tools/list` на проде содержит `update_task`; `openspec validate` diff --git a/openspec/specs/remote-mcp/spec.md b/openspec/specs/remote-mcp/spec.md index c5ee809e..4b38c8fc 100644 --- a/openspec/specs/remote-mcp/spec.md +++ b/openspec/specs/remote-mcp/spec.md @@ -46,3 +46,20 @@ MCP SHALL давать инструменты в пределах проекто #### Scenario: Чужой проект - **WHEN** клиент обращается к задаче проекта, которым пользователь не владеет - **THEN** получает «не найдено» + +### Requirement: Редактирование задачи +MCP SHALL позволять менять название и описание задачи проекта пользователя независимо +друг от друга, не меняя цель, статус и прочие поля и не запуская и не останавливая +агента; ответ содержит обновлённую карточку задачи. + +#### Scenario: Только название +- **WHEN** клиент вызывает `update_task` с ключом и новым `title` +- **THEN** меняется только название; описание, цель и статус прежние, сессий не прибавилось + +#### Scenario: Только описание +- **WHEN** клиент вызывает `update_task` с ключом и новым `description` +- **THEN** меняется только описание; название, цель и статус прежние + +#### Scenario: Без полей или чужая задача +- **WHEN** не передано ни `title`, ни `description`, или задача из чужого проекта +- **THEN** ошибка, задача не меняется diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 6aed54f6..d76a3aef 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -12,6 +12,7 @@ import { PeppaError, projectForUser, resolveTask, + updateTask, type User, } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; @@ -99,6 +100,24 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ }, ); + tool( + "update_task", + "Edit a task's title and/or description (each optional, at least one). Goal, status and everything else stay as they are; no agent is started or stopped. Returns the updated card.", + { + task: taskArg, + title: z.string().trim().min(3).optional().describe("New title"), + description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"), + }, + false, + async ({ task, title, description }) => { + if (title === undefined && description === undefined) throw new PeppaError("Nothing to update: pass title and/or description"); + const ref = await ownedTask(task); + await updateTask(db, ref, { title, description }); + const updated = await resolveTask(db, ref.key); + return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`; + }, + ); + tool( "move_task", "Move a task card on the board. in_progress starts an AI agent session on it (if none is running); backlog and done stop the agent; done also accepts the work.", diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index eeb62c01..eb7bfab3 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -5,6 +5,7 @@ import { after, before, describe, test } from "node:test"; import { core, db, project, runner, teardown } from "./helpers.ts"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { eq } from "drizzle-orm"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const { createManagerServer } = await import("@peppa/mcp/manager"); @@ -98,7 +99,7 @@ describe("PM tools over MCP", () => { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); @@ -125,3 +126,44 @@ describe("PM tools over MCP", () => { assert.match((await call("move_task", { task: `${p.key}-2`, to: "backlog" })).text, /1 session\(s\) stopped/); }); }); + +describe("update_task over MCP", () => { + test("title only, description only, both — goal, status and sessions untouched", async () => { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + const goal = await core.createGoal(db, proj.id, "Цель для правки"); + const ref = await core.createTask(db, { projectId: proj.id, goalId: goal.id, title: "Начать делать", description: "старое описание" }); + const { client, call } = await mcpAs(owner); + assert.equal((await client.listTools()).tools.find((t) => t.name === "update_task")?.annotations?.readOnlyHint, false); + const snapshot = async () => { + const t = (await core.resolveTask(db, ref.key)).task; + return { title: t.title, description: t.description, goalId: t.goalId, status: t.status, sessions: (await core.listSessions(db, { taskId: t.id })).length }; + }; + + const r1 = await call("update_task", { task: ref.key, title: "Новое название" }); + assert.ok(!r1.isError, r1.text); + assert.match(r1.text, new RegExp(`# ${ref.key}: Новое название`)); + assert.deepEqual(await snapshot(), { title: "Новое название", description: "старое описание", goalId: goal.id, status: "backlog", sessions: 0 }); + + const desc = "Сделать доску.\n\nУсловия готовности:\n- пункт 1\n- пункт 2"; + const r2 = await call("update_task", { task: ref.key, description: desc }); + assert.match(r2.text, /Условия готовности/); + assert.deepEqual(await snapshot(), { title: "Новое название", description: desc, goalId: goal.id, status: "backlog", sessions: 0 }); + + const r3 = await call("update_task", { task: ref.key, title: "Оба поля", description: "оба описания" }); + assert.match(r3.text, /Оба поля/); + assert.match(r3.text, /оба описания/); + assert.match(r3.text, /Цель: #\d+ Цель для правки/); + assert.deepEqual(await snapshot(), { title: "Оба поля", description: "оба описания", goalId: goal.id, status: "backlog", sessions: 0 }); + + assert.ok((await call("update_task", { task: ref.key })).isError, "nothing to update"); + const s = await mcpAs(stranger); + const denied = await s.call("update_task", { task: ref.key, title: "чужое" }); + assert.ok(denied.isError); + assert.match(denied.text, /Не найдено/); + assert.equal((await snapshot()).title, "Оба поля"); + const evs = await db.select().from((await import("@peppa/db")).events).where(eq((await import("@peppa/db")).events.taskId, ref.task.id)); + assert.equal(evs.filter((e) => e.type === "task_updated").length, 3, "each edit is in the task's event log"); + }); +}); -- 2.45.2 From 3f5524815025fc06e832caab078714e8c3399870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 22:06:37 +0500 Subject: [PATCH 003/554] PEP-13: connect Claude from the web for remote users MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Settings → Claude: Peppa runs 'claude setup-token' in tmux, shows the claude.com sign-in link, the user pastes the code into the form; the 1-year token is stored encrypted on the user (users.claude_token_enc) - Claude sessions of the owner's projects get CLAUDE_CODE_OAUTH_TOKEN; projects without an owner token keep using the machine login - disconnect / reconnect; setup times out after 10 min and its tmux session (and scrollback with the token) is killed right after saving - mock-claude setup-token; 2 new tests (56 e2e total, green) - verified on prod: the button yields the real claude.com authorize URL - OpenSpec: pep-13 archived into spec agent-credentials Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + apps/web/app/(app)/actions.ts | 32 +- apps/web/app/(app)/settings/page.tsx | 56 +- apps/web/app/globals.css | 2 + .../.openspec.yaml | 2 + .../proposal.md | 37 + .../specs/agent-credentials/spec.md | 35 + .../2026-11-12-pep-13-connect-claude/tasks.md | 16 + openspec/specs/agent-credentials/spec.md | 34 + packages/core/src/users.ts | 14 + packages/db/migrations/0007_empty_crystal.sql | 2 + .../db/migrations/meta/0007_snapshot.json | 1243 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 4 + packages/runner/src/claude-auth.ts | 90 ++ packages/runner/src/index.ts | 1 + packages/runner/src/sessions.ts | 5 + packages/runner/src/tmux.ts | 3 +- packages/testkit/src/mock-agent.ts | 37 +- packages/testkit/test/claude-auth.test.ts | 54 + 20 files changed, 1668 insertions(+), 7 deletions(-) create mode 100644 openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md create mode 100644 openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md create mode 100644 openspec/specs/agent-credentials/spec.md create mode 100644 packages/db/migrations/0007_empty_crystal.sql create mode 100644 packages/db/migrations/meta/0007_snapshot.json create mode 100644 packages/runner/src/claude-auth.ts create mode 100644 packages/testkit/test/claude-auth.test.ts diff --git a/AGENTS.md b/AGENTS.md index 713777b7..afc633c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ - SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane - StopFailure `rate_limit` → `rate_limited`; `peppa session resume ` → `claude --resume` - агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP) +- **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем - `scripts/` — push-template.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin), install-launchd.sh (вачдог как launchd-агент с caffeinate) diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 1049f281..66b07186 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -10,8 +10,9 @@ import { projectForUser, resolveTask, revokeApp, + setClaudeToken, } from "@peppa/core"; -import { acceptTask, answerAndDeliver, moveTask, provisionProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, startClaudeSetup, 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"; @@ -145,3 +146,32 @@ export async function revokeConnectedApp(f: FormData) { await revokeApp(db, user.id, str(f, "clientId")); }); } + +export async function connectClaude(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await startClaudeSetup(db, user.id); + }); +} + +export async function submitClaudeCode(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await finishClaudeSetup(db, user.id, str(f, "code")); + return "/settings?claude=connected"; + }); +} + +export async function cancelClaude(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await cancelClaudeSetup(db, user.id); + }); +} + +export async function disconnectClaude(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + await setClaudeToken(db, user.id, null); + }); +} diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index c42c8a8e..19f75a2e 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -2,17 +2,67 @@ import { connectedApps } from "@peppa/core"; import { ago, Flash } from "@/components/ui"; import { publicOrigin, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; -import { revokeConnectedApp } from "../actions"; +import { pendingClaudeSetup } from "@peppa/runner"; +import { cancelClaude, connectClaude, disconnectClaude, revokeConnectedApp, submitClaudeCode } from "../actions"; -export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string }> }) { +export default async function Settings({ searchParams }: { searchParams: Promise<{ error?: string; claude?: string }> }) { const user = await requireUser(); - const { error } = await searchParams; + const { error, claude } = await searchParams; + const setup = await pendingClaudeSetup(db, user.id); const apps = await connectedApps(db, user.id); const origin = await publicOrigin(); return (

Настройки

+

Claude

+ {claude === "connected" &&

Claude подключён ✅

} + {setup ? ( +
+

+ 1. Откройте ссылку на любом устройстве и войдите в аккаунт Claude (нужна подписка): +

+ Войти в Claude ↗ +

2. Claude покажет код — вставьте его сюда:

+
+ + + +
+
+ + +
+
+ ) : user.claudeTokenEnc ? ( +
+
+ Claude подключён +
+ с {user.claudeTokenSetAt?.toLocaleDateString("ru-RU")} · сессии ваших проектов работают на вашей подписке +
+
+
+ + +
+
+ + +
+
+ ) : ( +
+

+ Агенты ваших проектов запускаются как Claude Code. Подключите свой аккаунт Claude — Пеппа получит годовой + токен через claude setup-token, вход делаете вы сами по ссылке. +

+
+ + +
+
+ )}

MCP для ChatGPT и других клиентов

Адрес сервера — подключите его как MCP-коннектор с авторизацией OAuth. Клиент diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index e7a018ae..b748e021 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -156,3 +156,5 @@ details.add { margin: 4px 0; } .consent h1 { justify-content: flex-start; } .scopes { margin: 0; padding-left: 20px; } .mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; } + +.ok { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md new file mode 100644 index 00000000..52707cde --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/proposal.md @@ -0,0 +1,37 @@ +# Proposal: PEP-13 — подключить Claude из веба + +Задача Пеппы: **PEP-13** · Цель #3 «Надёжность фабрики на живых агентах». + +## Why + +Сессии агентов падают с `authentication_failed`: вход Claude CLI на Mac истёк, а PM +работает удалённо и не может выполнить `claude login` на машине. + +## What Changes + +- «Настройки → Claude»: кнопка «Подключить». Пеппа запускает на Mac `claude setup-token`, + показывает ссылку входа; пользователь открывает её на своём устройстве, вставляет код в + форму Пеппы; полученный годовой токен хранится зашифрованным у пользователя. +- Сессии Claude по проектам владельца запускаются с его токеном + (`CLAUDE_CODE_OAUTH_TOKEN`); без токена — как сейчас (вход машины). +- Статус подключения, дата, «Отключить». Токен нигде не показывается. + +Вне scope: Codex (позже тем же способом), токены участников при шеринге (PEP-12). + +## Capabilities + +### New Capabilities +- `agent-credentials`: подключение аккаунта агента (Claude) пользователем из веба и использование его в сессиях. + +### Modified Capabilities + +## Impact + +`packages/db` (`users.claude_token_enc`, `claude_token_set_at`), `packages/runner` +(процесс setup-token в tmux, env сессий), `apps/web` (Настройки), `packages/testkit` +(mock-claude `setup-token`). + +## Решение по секретам + +Хранение — как у токенов Gitea (AES-256-GCM от `PEPPA_SECRET`); код вводит сам +пользователь, агент Пеппы его не видит. Согласовано с PM в чате. diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md new file mode 100644 index 00000000..1261aaf3 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/specs/agent-credentials/spec.md @@ -0,0 +1,35 @@ +# Spec Delta: agent-credentials + +## Purpose + +Позволяет пользователю, работающему удалённо, подключить свой аккаунт Claude к Пеппе из веба, чтобы сессии его проектов работали на его подписке. + +## ADDED Requirements + +### Requirement: Подключение Claude из веба +Пользователь SHALL мочь подключить Claude, не имея доступа к машине Пеппы: Пеппа +показывает ссылку входа Claude, пользователь вводит полученный код в веб-форму, Пеппа +сохраняет долгоживущий токен. + +#### Scenario: Успешное подключение +- **WHEN** пользователь нажимает «Подключить Claude», открывает показанную ссылку, получает код и вставляет его в форму +- **THEN** в настройках отображается «Claude подключён» с датой, токен не показывается + +#### Scenario: Неверный или просроченный код +- **WHEN** введённый код не принят Claude +- **THEN** пользователь видит ошибку и может начать заново; старый токен (если был) не меняется + +### Requirement: Хранение и отключение +Токен SHALL храниться только в зашифрованном виде и удаляться по «Отключить». + +#### Scenario: Отключение +- **WHEN** пользователь нажимает «Отключить» +- **THEN** токен удалён, новые сессии его проектов запускаются без него + +### Requirement: Токен в сессиях +Сессии Claude по проектам владельца с подключённым Claude SHALL запускаться с его +токеном; проекты без владельца или владельцы без токена используют вход машины. + +#### Scenario: Запуск сессии +- **WHEN** запускается сессия Claude по задаче проекта, владелец которого подключил Claude +- **THEN** процесс агента получает токен владельца diff --git a/openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md new file mode 100644 index 00000000..122a757f --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-13-connect-claude/tasks.md @@ -0,0 +1,16 @@ +# Tasks: PEP-13 + +## 1. Токен + +- [x] 1.1 Миграция `users.claude_token_enc`, `claude_token_set_at`; core: set/clear/get (шифрование) +- [x] 1.2 runner: процесс `claude setup-token` в tmux (`peppa-auth-u`): старт → ссылка; ввод кода → токен или ошибка; таймаут и уборка +- [x] 1.3 runner: сессии Claude получают `CLAUDE_CODE_OAUTH_TOKEN` владельца проекта + +## 2. Веб + +- [x] 2.1 Настройки → Claude: статус, «Подключить» (ссылка + поле кода), «Отключить» + +## 3. Проверка + +- [x] 3.1 mock-claude `setup-token`; тесты: подключение, неверный код, токен в env сессии, отключение; весь набор зелёный +- [x] 3.2 Выкатка; на проде «Подключить» показывает настоящую ссылку claude.com; `openspec validate` diff --git a/openspec/specs/agent-credentials/spec.md b/openspec/specs/agent-credentials/spec.md new file mode 100644 index 00000000..29441d1a --- /dev/null +++ b/openspec/specs/agent-credentials/spec.md @@ -0,0 +1,34 @@ +# agent-credentials Specification + +## Purpose +Позволяет пользователю, работающему удалённо, подключить свой аккаунт Claude к Пеппе из веба, чтобы сессии его проектов работали на его подписке. + +## Requirements + +### Requirement: Подключение Claude из веба +Пользователь SHALL мочь подключить Claude, не имея доступа к машине Пеппы: Пеппа +показывает ссылку входа Claude, пользователь вводит полученный код в веб-форму, Пеппа +сохраняет долгоживущий токен. + +#### Scenario: Успешное подключение +- **WHEN** пользователь нажимает «Подключить Claude», открывает показанную ссылку, получает код и вставляет его в форму +- **THEN** в настройках отображается «Claude подключён» с датой, токен не показывается + +#### Scenario: Неверный или просроченный код +- **WHEN** введённый код не принят Claude +- **THEN** пользователь видит ошибку и может начать заново; старый токен (если был) не меняется + +### Requirement: Хранение и отключение +Токен SHALL храниться только в зашифрованном виде и удаляться по «Отключить». + +#### Scenario: Отключение +- **WHEN** пользователь нажимает «Отключить» +- **THEN** токен удалён, новые сессии его проектов запускаются без него + +### Requirement: Токен в сессиях +Сессии Claude по проектам владельца с подключённым Claude SHALL запускаться с его +токеном; проекты без владельца или владельцы без токена используют вход машины. + +#### Scenario: Запуск сессии +- **WHEN** запускается сессия Claude по задаче проекта, владелец которого подключил Claude +- **THEN** процесс агента получает токен владельца diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index c5c58db2..2c46d808 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -107,3 +107,17 @@ export async function consumeLoginLink(db: Db, code: string): Promise { + await db + .update(users) + .set({ claudeTokenEnc: token ? encrypt(token) : null, claudeTokenSetAt: token ? new Date() : null }) + .where(eq(users.id, userId)); +} + +/** The decrypted Claude token of a project's owner, if they connected Claude. */ +export async function claudeTokenForProject(db: Db, project: Pick): Promise { + if (!project.ownerId) return null; + const u = await getUser(db, project.ownerId); + return u?.claudeTokenEnc ? decrypt(u.claudeTokenEnc) : null; +} diff --git a/packages/db/migrations/0007_empty_crystal.sql b/packages/db/migrations/0007_empty_crystal.sql new file mode 100644 index 00000000..ebad339b --- /dev/null +++ b/packages/db/migrations/0007_empty_crystal.sql @@ -0,0 +1,2 @@ +ALTER TABLE "users" ADD COLUMN "claude_token_enc" text;--> statement-breakpoint +ALTER TABLE "users" ADD COLUMN "claude_token_set_at" timestamp with time zone; \ No newline at end of file diff --git a/packages/db/migrations/meta/0007_snapshot.json b/packages/db/migrations/meta/0007_snapshot.json new file mode 100644 index 00000000..3d6d1c5d --- /dev/null +++ b/packages/db/migrations/meta/0007_snapshot.json @@ -0,0 +1,1243 @@ +{ + "id": "d7d79655-c98d-4cc6-b49b-b8db3ce22738", + "prevId": "141bce5b-54a3-438f-b6c9-edf22525ab7b", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 2126e00e..0aa98ed7 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -50,6 +50,13 @@ "when": 1794500991061, "tag": "0006_crazy_stellaris", "breakpoints": true + }, + { + "idx": 7, + "version": "7", + "when": 1794502693680, + "tag": "0007_empty_crystal", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index f9178bac..ec8be278 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -17,6 +17,10 @@ export const users = pgTable("users", { accessTokenEnc: text("access_token_enc"), refreshTokenEnc: text("refresh_token_enc"), tokenExpiresAt: timestamp("token_expires_at", { withTimezone: true }), + // Long-lived Claude Code token from `claude setup-token` (encrypted); used for the + // Claude sessions of this user's projects. + claudeTokenEnc: text("claude_token_enc"), + claudeTokenSetAt: timestamp("claude_token_set_at", { withTimezone: true }), createdAt: createdAt(), lastLoginAt: timestamp("last_login_at", { withTimezone: true }), }); diff --git a/packages/runner/src/claude-auth.ts b/packages/runner/src/claude-auth.ts new file mode 100644 index 00000000..8221df0e --- /dev/null +++ b/packages/runner/src/claude-auth.ts @@ -0,0 +1,90 @@ +// "Connect Claude" from the web: runs `claude setup-token` on this machine in a tmux +// session, hands the sign-in URL to the user, types back the code they paste into the +// web form, and stores the resulting long-lived token (encrypted) on the user. +import { homedir } from "node:os"; +import { deleteSetting, getSetting, PeppaError, setClaudeToken, setSetting } from "@peppa/core"; +import type { Db } from "@peppa/db"; +import * as tmux from "./tmux.ts"; + +const SETUP_TTL_MS = 10 * 60_000; +const URL_RE = /https:\/\/\S+\/oauth\/authorize\?\S+/; +const TOKEN_RE = /sk-ant-oat\d{2}-[A-Za-z0-9_-]{20,}/; +const ERROR_RE = /(error|invalid|failed|expired)/i; + +const sessionName = (userId: number) => `peppa-auth-u${userId}`; +const settingKey = (userId: number) => `claude.setup.u${userId}`; +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +export interface ClaudeSetup { + url: string; + startedAt: number; +} + +/** Pending setup of this user (null if none or expired). */ +export async function pendingClaudeSetup(db: Db, userId: number): Promise { + const s = await getSetting(db, settingKey(userId)); + if (!s) return null; + if (Date.now() - s.startedAt > SETUP_TTL_MS || !(await tmux.hasSession(sessionName(userId)))) { + await cancelClaudeSetup(db, userId); + return null; + } + return s; +} + +export async function cancelClaudeSetup(db: Db, userId: number): Promise { + await deleteSetting(db, settingKey(userId)); + if (await tmux.hasSession(sessionName(userId))) await tmux.killSession(sessionName(userId)).catch(() => {}); +} + +/** Starts `claude setup-token` and returns the sign-in URL to show the user. */ +export async function startClaudeSetup(db: Db, userId: number): Promise { + await cancelClaudeSetup(db, userId); + await tmux.newSession({ + name: sessionName(userId), + cwd: homedir(), + command: `${process.env.PEPPA_CLAUDE_BIN ?? "claude"} setup-token`, + env: { BROWSER: "/usr/bin/true" }, // don't open a browser on this machine + width: 1000, + }); + for (let i = 0; i < 60; i++) { + await sleep(500); + const url = URL_RE.exec(await tmux.capturePane(sessionName(userId)))?.[0]; + if (url) { + const setup = { url, startedAt: Date.now() }; + await setSetting(db, settingKey(userId), setup); + return setup; + } + } + const tail = await tmux.capturePane(sessionName(userId)).catch(() => ""); + await cancelClaudeSetup(db, userId); + throw new PeppaError(`claude setup-token не показал ссылку входа${tail.trim() ? `: ${tail.trim().split("\n").slice(-3).join(" ")}` : ""}`); +} + +/** Types the user's code into setup-token and stores the token it prints. */ +export async function finishClaudeSetup(db: Db, userId: number, code: string): Promise { + const c = code.trim(); + if (!c || /\s/.test(c)) throw new PeppaError("Вставьте код целиком, без пробелов"); + if (!(await pendingClaudeSetup(db, userId))) throw new PeppaError("Подключение не начато или истекло — нажмите «Подключить Claude» ещё раз"); + const name = sessionName(userId); + const before = await tmux.capturePane(name); + await tmux.sendText(name, c); + for (let i = 0; i < 60; i++) { + await sleep(500); + const screen = await tmux.capturePane(name, 200); + const token = TOKEN_RE.exec(screen)?.[0]; + if (token) { + await setClaudeToken(db, userId, token); + await cancelClaudeSetup(db, userId); // also wipes the token from the tmux scrollback + return; + } + const after = screen.slice(screen.indexOf(c) >= 0 ? screen.indexOf(c) + c.length : before.length); + const dead = (await tmux.paneState(name)).dead; + if (dead || ERROR_RE.test(after)) { + const msg = after.replace(TOKEN_RE, "…").trim().split("\n").filter(Boolean).slice(-2).join(" "); + await cancelClaudeSetup(db, userId); + throw new PeppaError(`Claude не принял код${msg ? `: ${msg.slice(0, 200)}` : ""}. Начните заново.`); + } + } + await cancelClaudeSetup(db, userId); + throw new PeppaError("Claude не ответил на код за 30 секунд. Начните заново."); +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 6a842df0..3cc94a96 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -6,3 +6,4 @@ export * from "./run-settings.ts"; export * from "./providers.ts"; export * from "./provision.ts"; export * from "./flow.ts"; +export * from "./claude-auth.ts"; diff --git a/packages/runner/src/sessions.ts b/packages/runner/src/sessions.ts index 3dc8ca90..8fa5bdcd 100644 --- a/packages/runner/src/sessions.ts +++ b/packages/runner/src/sessions.ts @@ -2,6 +2,7 @@ import { chmodSync, existsSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { answerQuestion, + claudeTokenForProject, createSession, expireSessionQuestions, getSession, @@ -81,6 +82,8 @@ async function launch( ): Promise { const generation = s.generation + 1; const rules = await loadSharedRules(); + const [owner] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, s.projectId)); + const claudeToken = s.provider === "claude" && owner ? await claudeTokenForProject(db, owner) : null; const argv = buildCommand(s.provider, { sessionId: s.id, generation, @@ -109,6 +112,8 @@ async function launch( // Hooks and the MCP server must talk to the same DB / state dir as the runner. DATABASE_URL: loadEnv().DATABASE_URL, ...(process.env.PEPPA_HOME ? { PEPPA_HOME: process.env.PEPPA_HOME } : {}), + // The project owner's own Claude subscription, if they connected it (PEP-13). + ...(claudeToken ? { CLAUDE_CODE_OAUTH_TOKEN: claudeToken } : {}), ...(process.env.PEPPA_HOOK_WAIT_SEC ? { PEPPA_HOOK_WAIT_SEC: process.env.PEPPA_HOOK_WAIT_SEC } : {}), }, }); diff --git a/packages/runner/src/tmux.ts b/packages/runner/src/tmux.ts index 28ed1ef9..fedf053f 100644 --- a/packages/runner/src/tmux.ts +++ b/packages/runner/src/tmux.ts @@ -16,6 +16,7 @@ export interface NewTmuxSession { cwd: string; command: string; env: Record; + width?: number; } export async function newSession(s: NewTmuxSession): Promise { @@ -23,7 +24,7 @@ export async function newSession(s: NewTmuxSession): Promise { // Keep the server up when its last session ends: otherwise a session created while the // previous last one is being killed can land on a server that is shutting down. await tmux("start-server", ";", "set-option", "-s", "exit-empty", "off"); - await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", "220", "-y", "50", ...envArgs, s.command); + await tmux("new-session", "-d", "-s", s.name, "-c", s.cwd, "-x", String(s.width ?? 220), "-y", "50", ...envArgs, s.command); // Keep the pane after claude exits so the watchdog can read the exit status. await tmux("set-option", "-t", s.name, "remain-on-exit", "on"); await tmux("set-option", "-t", s.name, "history-limit", "20000"); diff --git a/packages/testkit/src/mock-agent.ts b/packages/testkit/src/mock-agent.ts index fe09ba85..7e8d8274 100644 --- a/packages/testkit/src/mock-agent.ts +++ b/packages/testkit/src/mock-agent.ts @@ -329,7 +329,14 @@ async function main() { const scenario: Scenario = existsSync(SCENARIO) ? JSON.parse(readFileSync(SCENARIO, "utf8")) : { turns: [] }; const turns = (args.resume && scenario.resumeTurns) || scenario.turns; const rules = args.rulesFile ? readFileSync(args.rulesFile, "utf8") : (args.developerInstructions ?? ""); - log("start", { argv, resume: args.resume ?? null, conversationId, rulesChars: rules.length, rulesHead: rules.split("\n")[0] }); + log("start", { + argv, + resume: args.resume ?? null, + conversationId, + rulesChars: rules.length, + rulesHead: rules.split("\n")[0], + oauthToken: process.env.CLAUDE_CODE_OAUTH_TOKEN ? `…${process.env.CLAUDE_CODE_OAUTH_TOKEN.slice(-4)}` : null, + }); if (process.stdin.isTTY) process.stdin.setRawMode(true); process.stdin.setEncoding("utf8"); @@ -349,7 +356,33 @@ async function main() { for (;;) await run(await nextPrompt()); } -main().catch((e) => { +/** + * `claude setup-token`: prints a sign-in URL, waits for the code. "mock-good-…" codes + * yield a token, anything else fails like an invalid code. + */ +async function setupToken() { + out(" This will guide you through long-lived (1-year) auth token setup for your Claude account.\n"); + out(" Browser didn't open? Use the url below to sign in (c to copy)\n\n"); + out(`https://claude.com/cai/oauth/authorize?code=true&client_id=mock-client&response_type=code&state=mock-${randomUUID()}\n\n`); + out(" Paste code here if prompted > "); + process.stdin.setEncoding("utf8"); + let buf = ""; + for await (const chunk of process.stdin) { + buf += String(chunk).replace(/\x1b\[20[01]~/g, ""); + if (/[\r\n]/.test(buf)) break; + } + const code = buf.trim(); + // Runs in the home dir: log next to Peppa's state, never into a stray ~/.peppa. + if (process.env.PEPPA_HOME) appendFileSync(join(process.env.PEPPA_HOME, "mock-setup-log.jsonl"), `${JSON.stringify({ ev: "setup_token", code, t: Date.now() })}\n`); + if (code.startsWith("mock-good-")) { + out(`\n\n ✓ Long-lived authentication token created successfully!\n\n Your OAuth token (valid for 1 year):\n\n sk-ant-oat01-mock${randomUUID().replace(/-/g, "")}\n\n Store this token securely.\n`); + process.exit(0); + } + out("\n\n OAuth error: Invalid code\n"); + process.exit(1); +} + +(argv[0] === "setup-token" ? setupToken() : main()).catch((e) => { log("fatal", { error: String(e?.stack ?? e) }); process.exit(1); }); diff --git a/packages/testkit/test/claude-auth.test.ts b/packages/testkit/test/claude-auth.test.ts new file mode 100644 index 00000000..83d47458 --- /dev/null +++ b/packages/testkit/test/claude-auth.test.ts @@ -0,0 +1,54 @@ +// PEP-13: connect Claude from the web (setup-token in tmux) and use the token in sessions. +import assert from "node:assert/strict"; +import { after, before, describe, test } from "node:test"; +import { core, db, project, runner, teardown } from "./helpers.ts"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; + +let user: Awaited>; +before(async () => { + user = await core.upsertUserFromGitea(db, { id: 31, login: "mock-claude-user" }, { access_token: "x" }); +}); +after(teardown); + +describe("connect Claude", () => { + test("wrong code → error, nothing stored; right code → encrypted token", async () => { + const s1 = await runner.startClaudeSetup(db, user.id); + assert.match(s1.url, /^https:\/\/claude\.com\/cai\/oauth\/authorize\?/); + assert.deepEqual((await runner.pendingClaudeSetup(db, user.id))?.url, s1.url); + await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-bad-code"), /не принял код/); + assert.equal((await core.getUser(db, user.id))?.claudeTokenEnc, null); + assert.equal(await runner.pendingClaudeSetup(db, user.id), null, "failed setup is cleaned up"); + await assert.rejects(runner.finishClaudeSetup(db, user.id, "mock-good-1"), /не начато/); + + await runner.startClaudeSetup(db, user.id); + await runner.finishClaudeSetup(db, user.id, "mock-good-1"); + const u = (await core.getUser(db, user.id))!; + assert.ok(u.claudeTokenEnc && !u.claudeTokenEnc.includes("sk-ant"), "stored encrypted"); + assert.match(core.decrypt(u.claudeTokenEnc), /^sk-ant-oat01-mock/); + assert.ok(u.claudeTokenSetAt); + assert.equal(await runner.pendingClaudeSetup(db, user.id), null); + }); + + test("sessions of the owner's projects get the token; other projects and disconnect don't", async () => { + const token = core.decrypt((await core.getUser(db, user.id))!.claudeTokenEnc!); + const mine = await project({ turns: [[{ say: "ok" }]] }); + await core.setProjectOwner(db, (await core.getProject(db, mine.key)).id, user.id); + const sid = await mine.start(); + const start = await mine.waitLog("started", (e) => e.ev === "start"); + assert.equal(start.oauthToken, `…${token.slice(-4)}`); + await runner.stopSession(db, sid); + + const other = await project({ turns: [[{ say: "ok" }]] }); + const sid2 = await other.start(); + assert.equal((await other.waitLog("started", (e) => e.ev === "start")).oauthToken, null); + await runner.stopSession(db, sid2); + + await core.setClaudeToken(db, user.id, null); + const again = await project({ turns: [[{ say: "ok" }]] }); + await core.setProjectOwner(db, (await core.getProject(db, again.key)).id, user.id); + const sid3 = await again.start(); + assert.equal((await again.waitLog("started", (e) => e.ev === "start")).oauthToken, null); + await runner.stopSession(db, sid3); + }); +}); -- 2.45.2 From cf43669ce8595152aeffe9391f59a5d5e17cad2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 22:24:05 +0500 Subject: [PATCH 004/554] PEP-14: full PM toolkit over MCP and a Help page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - MCP: create_goal, update_goal (title, description, open/done/archived), create_project (same provisioning as the web, as the user), update_task goal_id (move between goals / detach); server instructions explain the project → goals → tasks → board model and good habits - web: /help — concepts, connecting ChatGPT/Codex/other MCP clients, scenarios with example phrases, tool reference; links in menu/settings - PEPPA_TEMPLATE_URL override for provisioning (tests) - 3 new tests (59 e2e total, green); prod tools/list and /help verified - OpenSpec: pep-14 archived (remote-mcp, web-workspace) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- apps/web/app/(app)/help/page.tsx | 81 +++++++++++++++++++ apps/web/app/(app)/layout.tsx | 1 + apps/web/app/(app)/settings/page.tsx | 1 + apps/web/app/globals.css | 8 ++ .../.openspec.yaml | 2 + .../proposal.md | 33 ++++++++ .../specs/remote-mcp/spec.md | 37 +++++++++ .../specs/web-workspace/spec.md | 11 +++ .../tasks.md | 15 ++++ openspec/specs/remote-mcp/spec.md | 34 ++++++++ openspec/specs/web-workspace/spec.md | 8 ++ packages/core/src/projects.ts | 12 +++ packages/mcp/src/manager.ts | 80 ++++++++++++++++-- packages/runner/src/provision.ts | 2 +- packages/testkit/test/oauth.test.ts | 72 ++++++++++++++++- 16 files changed, 390 insertions(+), 9 deletions(-) create mode 100644 apps/web/app/(app)/help/page.tsx create mode 100644 openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md create mode 100644 openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md diff --git a/AGENTS.md b/AGENTS.md index afc633c8..e34d2e5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,7 @@ - `packages/shared` — env, ключи задач (`PEP-42`) - `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё - `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd. `@peppa/mcp/manager` — инструменты PM для удалённых клиентов -- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, list_goals, list_tasks, get_task, create_task, update_task (название/описание, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question +- **Удалённый MCP (PEP-8)**: `https://peppa.telecom.quest/mcp` (Streamable HTTP, stateless, Bearer). Пеппа — OAuth 2.1 сервер: `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, DCR `/oauth/register`, `/oauth/authorize` (вход через Gitea + экран согласия), `/oauth/token` (PKCE S256, refresh с ротацией). Токены — хэши в `oauth_tokens`, отзыв в вебе «Настройки». Инструменты: list_projects, create_project, list_goals, create_goal, update_goal, list_tasks, get_task, create_task, update_task (название/описание/цель, без запуска агента), move_task (как доска — запускает агента), list_inbox, answer_question; `instructions` сервера объясняют модель клиенту. Пользовательская документация — `/help` в вебе (держать в актуальном состоянии при изменении инструментов) - `packages/testkit` — `mock-claude` / `mock-codex`, `mock-telegram` (мок Bot API) (моки CLI агентов по сценариям: хуки, notify, MCP, лимиты, зависания, падения) и e2e-набор CJM - `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба - `packages/runner` — запуск claude в tmux (`peppa--s`), вачдог, `peppa-hook` diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx new file mode 100644 index 00000000..c575c092 --- /dev/null +++ b/apps/web/app/(app)/help/page.tsx @@ -0,0 +1,81 @@ +import Link from "next/link"; +import { publicOrigin } from "@/lib/auth"; + +const TOOLS: Array<[string, string]> = [ + ["list_projects", "мои проекты и сколько задач в каждой колонке"], + ["create_project", "новый проект: репозиторий в Gitea + шаблон + OpenSpec (или подключить существующий)"], + ["list_goals / create_goal / update_goal", "цели проекта: завести, переименовать, отметить достигнутой или убрать в архив"], + ["list_tasks", "доска проекта: Бэклог / В работе / Ревью / Готово"], + ["get_task", "карточка задачи: описание, цель, статус, OpenSpec, вопросы, прогресс"], + ["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"], + ["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"], + ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"], +]; + +const CASES: Array<{ title: string; say: string; how: string }> = [ + { title: "Создать проект", say: "Создай проект «Платежи», репо payments, ключ PAY", how: "create_project → проект с доской; агенты будут работать в этом репозитории" }, + { title: "Завести цель", say: "В PAY заведи цель «Приём оплат картой» — зачем и какой результат", how: "create_goal. Цель — верхнеуровневый результат, под ней собираются задачи" }, + { title: "Создать задачу под целью", say: "Под этой целью создай задачу «Форма оплаты» с условиями готовности: …", how: "create_task с goal_id. Пишите контекст и список «Условия готовности» — по ним работает агент" }, + { title: "Поправить задачу", say: "Переименуй PAY-3 в … и замени описание на …; перенеси в цель #5", how: "update_task — статус и агент не трогаются, дубликат не нужен" }, + { title: "Посмотреть статус", say: "Покажи доску PAY · Что с PAY-3?", how: "list_tasks / get_task" }, + { title: "Запустить работу", say: "Двинь PAY-3 в работу", how: "move_task → in_progress: агент пишет proposal, реализует, открывает PR и переводит задачу в Ревью" }, + { title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" }, + { title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" }, + { title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" }, + { title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" }, +]; + +export default async function Help() { + const mcp = `${await publicOrigin()}/mcp`; + return ( +

+

Помощь

+ +

Как устроена Пеппа

+
    +
  • Проект — репозиторий в Gitea с ключом задач (например, PEP). Создаётся из веба или через MCP.
  • +
  • Цель — верхнеуровневый результат («Мультипользовательская платформа»). Группирует задачи и даёт агенту контекст «зачем».
  • +
  • Задача (PEP-12) — один результат с описанием и условиями готовности.
  • +
  • Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
  • +
  • Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
  • +
  • Входящие — вопросы агентов (только архитектурные стопперы) и «готово к ревью». Отвечать можно в вебе, Telegram или через MCP.
  • +
+ +

Подключить MCP

+

Адрес сервера:

+ {mcp} +
    +
  • ChatGPT: Settings → Apps & Connectors → Advanced → включить Developer mode → Create: URL выше, авторизация OAuth. Откроется Пеппа — войдите через Gitea и нажмите «Разрешить». В чате включите коннектор Peppa.
  • +
  • Codex, Claude и другие MCP-клиенты: добавьте удалённый MCP-сервер по этому URL с OAuth — клиент зарегистрируется сам, вход и согласие на экране Пеппы.
  • +
  • Если клиент не видит новых инструментов — обновите или переподключите коннектор. Доступ отзывается в Настройках.
  • +
  • Чтобы агенты работали на вашей подписке, подключите Claude в Настройках.
  • +
+ +

Сценарии

+ {CASES.map((c) => ( +
+ {c.title} +

«{c.say}»

+

{c.how}

+
+ ))} + +

Инструменты MCP

+ + + {TOOLS.map(([name, what]) => ( + + + + + ))} + +
{name}{what}
+ +

Telegram

+

+ Бот присылает вопросы агентов и «готово к ревью» с кнопками; ответ реплаем уходит прямо в сессию агента. +

+
+ ); +} diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index b677f059..435a0c55 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -14,6 +14,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) { Входящие Новый проект Настройки + Помощь
{user.avatarUrl && } diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 19f75a2e..1221d0e4 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -69,6 +69,7 @@ export default async function Settings({ searchParams }: { searchParams: Promise зарегистрируется сам, вы подтвердите доступ на экране Пеппы.

{origin}/mcp +

Как подключить и что спрашивать — в Помощи.

Подключённые приложения

{apps.length === 0 ? (

Нет подключённых приложений.

diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index b748e021..fa27012d 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -158,3 +158,11 @@ details.add { margin: 4px 0; } .mcp-url { display: block; padding: 10px 12px; background: var(--code-bg); border-radius: 8px; overflow-x: auto; } .ok { background: color-mix(in srgb, var(--ok) 12%, var(--surface)); border: 1px solid var(--ok); border-radius: var(--radius); padding: 10px 14px; } + +.help ul { padding-left: 20px; } +.help li { margin: 4px 0; } +.say { margin: 6px 0; font-style: italic; } +table.tools { width: 100%; border-collapse: collapse; } +table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; } +table.tools td.mono { white-space: nowrap; } +@media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } } diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md new file mode 100644 index 00000000..948c344a --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/proposal.md @@ -0,0 +1,33 @@ +# Proposal: PEP-14 — полный набор MCP для PM и «Помощь» + +Задача Пеппы: **PEP-14** · Цель #2. + +## Why + +Через удалённый MCP нельзя завести или поправить цель, создать проект, перенести задачу +в другую цель — PM приходится идти в веб. И нигде не описано, как пользоваться Пеппой +через MCP. + +## What Changes + +- Инструменты MCP: `create_goal`, `update_goal` (название, описание, статус + open/done/archived), `create_project` (новый или существующий репо в Gitea — тот же + `provisionProject`, что веб, от имени пользователя), `update_task` получает `goal_id` + (перенести в цель или отвязать). +- MCP-сервер отдаёт клиенту инструкции (`instructions`): модель Пеппы (проект → цели → + задачи → доска → агенты), как формулировать задачи, когда что вызывать. +- Страница «Помощь» в вебе (`/help`, в меню): подключение MCP в ChatGPT/Codex, словарь + (цель, задача, доска, сессия, входящие, ревью) и сценарии с примерами фраз. + +## Capabilities + +### New Capabilities + +### Modified Capabilities +- `remote-mcp`: цели, создание проекта, цель задачи, инструкции сервера. +- `web-workspace`: страница «Помощь». + +## Impact + +`packages/mcp/src/manager.ts`, `packages/core` (updateGoal), `apps/web` (/help, меню), +testkit. diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md new file mode 100644 index 00000000..dbd54cb5 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/remote-mcp/spec.md @@ -0,0 +1,37 @@ +# Spec Delta: remote-mcp + +## ADDED Requirements + +### Requirement: Цели через MCP +MCP SHALL позволять создавать цели в проекте пользователя и менять их название, +описание и статус (открыта, достигнута, в архиве). + +#### Scenario: Новая цель и задачи под ней +- **WHEN** клиент создаёт цель и затем задачу с её `goal_id` +- **THEN** цель видна в списке целей проекта, задача — под этой целью + +#### Scenario: Цель достигнута +- **WHEN** клиент меняет статус цели на «достигнута» +- **THEN** цель пропадает из списка открытых целей, её задачи не меняются + +### Requirement: Цель задачи +`update_task` SHALL позволять перенести задачу в другую цель своего проекта или отвязать от цели, не меняя остальное. + +#### Scenario: Перенос в другую цель +- **WHEN** клиент вызывает `update_task` с `goal_id` другой цели проекта +- **THEN** задача относится к этой цели, статус и название прежние + +### Requirement: Создание проекта через MCP +MCP SHALL создавать проект так же, как веб: новый или существующий репозиторий в +пространстве пользователя или его организации, от имени пользователя. + +#### Scenario: Новый проект +- **WHEN** клиент вызывает `create_project` с названием, slug и ключом +- **THEN** проект создан с пользователем-владельцем и виден в `list_projects` + +### Requirement: Инструкции сервера +MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться инструментами. + +#### Scenario: Подключение +- **WHEN** клиент инициализирует соединение +- **THEN** получает инструкции сервера с моделью проект → цели → задачи → доска diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md new file mode 100644 index 00000000..05bd5b80 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/specs/web-workspace/spec.md @@ -0,0 +1,11 @@ +# Spec Delta: web-workspace + +## ADDED Requirements + +### Requirement: Помощь +Веб SHALL иметь страницу «Помощь», доступную из меню, с описанием понятий Пеппы, +подключения MCP-клиентов и сценариев работы с примерами. + +#### Scenario: Открыть помощь +- **WHEN** пользователь открывает «Помощь» +- **THEN** видит адрес MCP, шаги подключения ChatGPT и Codex и сценарии: создать проект, цели, задачи, проверить статус, ответить агенту, принять ревью diff --git a/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md new file mode 100644 index 00000000..e10a7518 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-14-mcp-pm-toolkit-help/tasks.md @@ -0,0 +1,15 @@ +# Tasks: PEP-14 + +## 1. MCP + +- [x] 1.1 core `updateGoal`; MCP `create_goal`, `update_goal`, `update_task.goal_id`, `create_project` +- [x] 1.2 `instructions` MCP-сервера +- [x] 1.3 Тесты: цели (создание, правка, статус), перенос задачи в цель и отвязка, чужая цель — ошибка, создание проекта через mock-gitea, инструкции в initialize + +## 2. Помощь + +- [x] 2.1 `/help` в вебе + пункт меню; ссылка из Настроек + +## 3. Выкатка + +- [x] 3.1 Набор зелёный; выкатка; `tools/list` на проде; страница видна; `openspec validate` diff --git a/openspec/specs/remote-mcp/spec.md b/openspec/specs/remote-mcp/spec.md index 4b38c8fc..295033c8 100644 --- a/openspec/specs/remote-mcp/spec.md +++ b/openspec/specs/remote-mcp/spec.md @@ -63,3 +63,37 @@ MCP SHALL позволять менять название и описание #### Scenario: Без полей или чужая задача - **WHEN** не передано ни `title`, ни `description`, или задача из чужого проекта - **THEN** ошибка, задача не меняется + +### Requirement: Цели через MCP +MCP SHALL позволять создавать цели в проекте пользователя и менять их название, +описание и статус (открыта, достигнута, в архиве). + +#### Scenario: Новая цель и задачи под ней +- **WHEN** клиент создаёт цель и затем задачу с её `goal_id` +- **THEN** цель видна в списке целей проекта, задача — под этой целью + +#### Scenario: Цель достигнута +- **WHEN** клиент меняет статус цели на «достигнута» +- **THEN** цель пропадает из списка открытых целей, её задачи не меняются + +### Requirement: Цель задачи +`update_task` SHALL позволять перенести задачу в другую цель своего проекта или отвязать от цели, не меняя остальное. + +#### Scenario: Перенос в другую цель +- **WHEN** клиент вызывает `update_task` с `goal_id` другой цели проекта +- **THEN** задача относится к этой цели, статус и название прежние + +### Requirement: Создание проекта через MCP +MCP SHALL создавать проект так же, как веб: новый или существующий репозиторий в +пространстве пользователя или его организации, от имени пользователя. + +#### Scenario: Новый проект +- **WHEN** клиент вызывает `create_project` с названием, slug и ключом +- **THEN** проект создан с пользователем-владельцем и виден в `list_projects` + +### Requirement: Инструкции сервера +MCP-сервер SHALL при подключении сообщать клиенту, как устроена Пеппа и как пользоваться инструментами. + +#### Scenario: Подключение +- **WHEN** клиент инициализирует соединение +- **THEN** получает инструкции сервера с моделью проект → цели → задачи → доска diff --git a/openspec/specs/web-workspace/spec.md b/openspec/specs/web-workspace/spec.md index 13a5659c..191fca29 100644 --- a/openspec/specs/web-workspace/spec.md +++ b/openspec/specs/web-workspace/spec.md @@ -76,3 +76,11 @@ #### Scenario: Карточку в готово - **WHEN** PM переносит карточку из «Ревью» в «Готово» - **THEN** задача `done`, активная сессия по ней остановлена + +### Requirement: Помощь +Веб SHALL иметь страницу «Помощь», доступную из меню, с описанием понятий Пеппы, +подключения MCP-клиентов и сценариев работы с примерами. + +#### Scenario: Открыть помощь +- **WHEN** пользователь открывает «Помощь» +- **THEN** видит адрес MCP, шаги подключения ChatGPT и Codex и сценарии: создать проект, цели, задачи, проверить статус, ответить агенту, принять ревью diff --git a/packages/core/src/projects.ts b/packages/core/src/projects.ts index 51401540..5cd61037 100644 --- a/packages/core/src/projects.ts +++ b/packages/core/src/projects.ts @@ -59,3 +59,15 @@ export async function getGoal(db: Db, projectId: number, goalId: number): Promis if (!row) throw new PeppaError(`Goal #${goalId} not found in this project`); return row; } + +export interface GoalPatch { + title?: string; + description?: string | null; + status?: Goal["status"]; +} + +export async function updateGoal(db: Db, projectId: number, goalId: number, patch: GoalPatch): Promise { + await getGoal(db, projectId, goalId); + const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning(); + return row!; +} diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index d76a3aef..2ff1775d 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -2,7 +2,11 @@ // user's projects. Served over HTTP by the web app at /mcp; agents keep the stdio server. import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { + createGoal, createTask, + getGoal, + giteaForUser, + updateGoal, getProject, getQuestion, getTaskDetails, @@ -17,7 +21,7 @@ import { } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, type BoardColumn, type Provider } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, provisionProject, type BoardColumn, type Provider } from "@peppa/runner"; import { and, asc, eq, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatTask } from "./format.ts"; @@ -26,8 +30,21 @@ type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolea const COLUMNS = ["backlog", "in_progress", "review", "done"] as const; const COLUMN_NAME: Record = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" }; +/** Sent to clients on initialize: how Peppa is organised and how to use the tools. */ +export const MANAGER_INSTRUCTIONS = `Peppa is a software factory: AI agents (Claude Code / Codex) implement tasks in Gitea repos, following OpenSpec. + +Model: project (a Gitea repo, key like PEP) → goals (top-level objectives) → tasks (PEP-12, one deliverable each) → board columns Backlog / In progress / Review / Done. +- Moving a task to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the task to review. backlog/done stop the agent. +- Agents only ask the user about architectural stoppers; those questions and "ready for review" messages are in the inbox (list_inbox → answer_question; answer "accept" to close a reviewed task). + +Good habits: +- Before creating, look: list_projects, list_goals, list_tasks. Don't duplicate — fix with update_task / update_goal. +- Put tasks under a goal (goal_id). Write task descriptions with context and a "Definition of done" list; the agent works from them. +- Only move a task to in_progress when the user asks to start the work. +- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user.`; + export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { - const server = new McpServer({ name: "peppa", version: "0.2.0" }); + const server = new McpServer({ name: "peppa", version: "0.3.0" }, { instructions: MANAGER_INSTRUCTIONS }); function tool(name: string, description: string, inputSchema: S, readOnly: boolean, run: (a: z.infer>) => Promise) { server.registerTool(name, { description, inputSchema, annotations: { readOnlyHint: readOnly, openWorldHint: false } }, (async (a: z.infer>): Promise => { @@ -66,6 +83,56 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ return gs.length ? gs.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open goals."; }); + tool( + "create_goal", + "Create a top-level goal in a project (an objective that groups tasks).", + { project: projectArg, title: z.string().trim().min(3), description: z.string().optional() }, + false, + async ({ project, title, description }) => { + const p = await ownedProject(project); + const g = await createGoal(db, p.id, title, description); + return `Created goal #${g.id} in ${p.key}: ${g.title}`; + }, + ); + + tool( + "update_goal", + "Edit a goal: title, description and/or status (open, done = achieved, archived). Its tasks are not changed.", + { + project: projectArg, + goal_id: z.number().int(), + title: z.string().trim().min(3).optional(), + description: z.string().optional(), + status: z.enum(["open", "done", "archived"]).optional(), + }, + false, + async ({ project, goal_id, title, description, status }) => { + if (title === undefined && description === undefined && status === undefined) throw new PeppaError("Nothing to update: pass title, description and/or status"); + const p = await ownedProject(project); + await getGoal(db, p.id, goal_id).catch(() => { throw new PeppaError("Не найдено"); }); + const g = await updateGoal(db, p.id, goal_id, { title, description, status }); + return `Goal #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`; + }, + ); + + tool( + "create_project", + "Create a Peppa project: a new private Gitea repo (or connect an existing one you admin) in your namespace or an org you can create repos in, filled from the Peppa template with OpenSpec. Takes ~15 s.", + { + name: z.string().trim().min(2).describe("Human name, e.g. Payments"), + slug: z.string().describe("Repo name: a-z, 0-9, dashes"), + key: z.string().describe("Task key prefix, 2–10 letters/digits, e.g. PAY"), + owner: z.string().optional().describe("Gitea namespace: your login (default) or an org"), + existing: z.boolean().optional().describe("Connect an existing repo owner/slug instead of creating one"), + }, + false, + async ({ name, slug, key, owner, existing }) => { + const ns = owner || user.login; + const p = await provisionProject(db, { gitea: await giteaForUser(db, user), owner: ns, ownerIsUser: ns === user.login, slug: slug.toLowerCase(), key, name, existing, ownerId: user.id }); + return `Created project ${p.key} — ${p.name} (${p.giteaOwner}/${p.giteaRepo}). ${webUrl}/p/${p.key}`; + }, + ); + tool( "list_tasks", "List tasks of a project as a board (Backlog / In progress / Review / Done), optionally one column.", @@ -102,17 +169,18 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ tool( "update_task", - "Edit a task's title and/or description (each optional, at least one). Goal, status and everything else stay as they are; no agent is started or stopped. Returns the updated card.", + "Edit a task: title, description and/or goal (each optional, at least one). Status and everything else stay as they are; no agent is started or stopped. Returns the updated card.", { task: taskArg, title: z.string().trim().min(3).optional().describe("New title"), description: z.string().optional().describe("New description (replaces the old one; Markdown is fine)"), + goal_id: z.number().int().nullable().optional().describe("Move to this goal of the same project; null detaches the task from its goal"), }, false, - async ({ task, title, description }) => { - if (title === undefined && description === undefined) throw new PeppaError("Nothing to update: pass title and/or description"); + async ({ task, title, description, goal_id }) => { + if (title === undefined && description === undefined && goal_id === undefined) throw new PeppaError("Nothing to update: pass title, description and/or goal_id"); const ref = await ownedTask(task); - await updateTask(db, ref, { title, description }); + await updateTask(db, ref, { title, description, goalId: goal_id }); const updated = await resolveTask(db, ref.key); return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`; }, diff --git a/packages/runner/src/provision.ts b/packages/runner/src/provision.ts index 47bc600b..4c56f12f 100644 --- a/packages/runner/src/provision.ts +++ b/packages/runner/src/provision.ts @@ -78,7 +78,7 @@ export async function provisionProject(db: Db, o: ProvisionOptions): Promise { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "update_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_goal", "create_project", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "update_goal", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); @@ -167,3 +167,73 @@ describe("update_task over MCP", () => { assert.equal(evs.filter((e) => e.type === "task_updated").length, 3, "each edit is in the task's event log"); }); }); + +describe("goals, task goal and project creation over MCP", () => { + test("server instructions explain the model", async () => { + const { client } = await mcpAs(owner); + assert.match(client.getInstructions() ?? "", /project .*goals .*tasks/s); + }); + + test("create/update goals; move a task between goals and detach; foreign goal refused", async () => { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + const { call } = await mcpAs(owner); + const g1 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель один", description: "зачем" })).text)![1]); + const g2 = Number(/goal #(\d+)/.exec((await call("create_goal", { project: p.key, title: "Цель два" })).text)![1]); + assert.match((await call("list_goals", { project: p.key })).text, /Цель один[\s\S]*Цель два/); + assert.match((await call("update_goal", { project: p.key, goal_id: g1, title: "Цель первая" })).text, /Цель первая \[open\]/); + + const t = await call("create_task", { project: p.key, title: "Задача в цели", goal_id: g1 }); + const key = /Created (\S+):/.exec(t.text)![1]!; + assert.match((await call("update_task", { task: key, goal_id: g2 })).text, /Цель: #\d+ Цель два/); + const moved = (await core.resolveTask(db, key)).task; + assert.equal(moved.goalId, g2); + assert.equal(moved.title, "Задача в цели"); + assert.equal(moved.status, "backlog"); + await call("update_task", { task: key, goal_id: null }); + assert.equal((await core.resolveTask(db, key)).task.goalId, null); + + const other = await project({ turns: [] }); + const foreignGoal = await core.createGoal(db, (await core.getProject(db, other.key)).id, "Чужая цель"); + assert.ok((await call("update_task", { task: key, goal_id: foreignGoal.id })).isError, "goal of another project"); + assert.ok((await call("update_goal", { project: p.key, goal_id: foreignGoal.id, title: "взлом" })).isError); + + assert.match((await call("update_goal", { project: p.key, goal_id: g1, status: "done" })).text, /\[done\]/); + assert.doesNotMatch((await call("list_goals", { project: p.key })).text, /Цель первая/); + }); + + test("create_project through MCP, owned by the user", async () => { + const { MockGitea } = await import("../src/mock-gitea.ts"); + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join, resolve } = await import("node:path"); + const { fileURLToPath } = await import("node:url"); + const { execFileSync } = await import("node:child_process"); + const tmp = mkdtempSync(join(tmpdir(), "peppa-mcp-proj-")); + const gitea = await new MockGitea(join(tmp, "gitea")).start(); + const prevUrl = process.env.GITEA_URL; + try { + process.env.GITEA_URL = gitea.url; + process.env.PEPPA_WORKSPACES = join(tmp, "ws"); + gitea.addUser({ id: 41, login: "mock-mcp-owner", token: "mock-token-mcp" }); + const tpl = gitea.addRepo("peppa-bot", "template"); + const root = resolve(fileURLToPath(import.meta.url), "../../../.."); + execFileSync("bash", ["-c", `cd ${JSON.stringify(join(root, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]); + process.env.PEPPA_TEMPLATE_URL = tpl.path; + const u = await core.upsertUserFromGitea(db, { id: 41, login: "mock-mcp-owner" }, { access_token: "mock-token-mcp" }); + const { call } = await mcpAs(u); + const r = await call("create_project", { name: "Mock MCP project", slug: "mock-mcp-proj", key: "MMCP" }); + assert.ok(!r.isError, r.text); + assert.match(r.text, /Created project MMCP/); + assert.equal((await core.getProject(db, "MMCP")).ownerId, u.id); + assert.ok(gitea.files("mock-mcp-owner", "mock-mcp-proj").includes("AGENTS.md")); + assert.match((await call("list_projects")).text, /MMCP — Mock MCP project/); + assert.ok((await call("create_project", { name: "dup", slug: "mock-mcp-proj", key: "MMCP2" })).isError, "duplicate refused"); + } finally { + process.env.GITEA_URL = prevUrl; + delete process.env.PEPPA_TEMPLATE_URL; + await gitea.stop(); + } + }); +}); -- 2.45.2 From 56b622458705e0593fa2b4fc4d73f41e9db7d161 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 22:35:56 +0500 Subject: [PATCH 005/554] PEP-12: share projects with other users - project_members / project_invites; owner adds people by Gitea login, invitations are applied at first login; members get the owner's access except member management; a member can leave - access everywhere via projectForUser / userProjectIds (owner or member): web inbox, sessions, project pages, MCP - shareProject / unshareProject: login checked in Gitea, repo collaborator (write) added by the owner's client or peppa-bot; missing admin rights don't block membership (repoAccess flag) - web: Members block on the project page, 'shared' badge; MCP: list_members, add_member, remove_member; Help updated - tests: 5 sharing journeys on mock-gitea (64 e2e total, green); test DB now also clears users and OAuth clients between files - OpenSpec: pep-12 archived (project-sharing, web-auth) Co-Authored-By: Claude --- AGENTS.md | 1 + apps/web/app/(app)/actions.ts | 22 +- apps/web/app/(app)/help/page.tsx | 3 + apps/web/app/(app)/p/[key]/page.tsx | 55 +- apps/web/app/(app)/page.tsx | 4 +- apps/web/app/globals.css | 3 + apps/web/lib/queries.ts | 13 +- .../.openspec.yaml | 2 + .../design.md | 18 + .../proposal.md | 36 + .../specs/project-sharing/spec.md | 53 + .../specs/web-auth/spec.md | 15 + .../tasks.md | 16 + openspec/specs/project-sharing/spec.md | 52 + openspec/specs/web-auth/spec.md | 10 +- packages/core/src/gitea.ts | 14 + packages/core/src/users.ts | 89 +- .../migrations/0008_wandering_jetstream.sql | 21 + .../db/migrations/meta/0008_snapshot.json | 1402 +++++++++++++++++ packages/db/migrations/meta/_journal.json | 7 + packages/db/src/schema.ts | 26 +- packages/mcp/src/manager.ts | 49 +- packages/runner/src/index.ts | 1 + packages/runner/src/share.ts | 71 + packages/testkit/src/mock-gitea.ts | 12 + packages/testkit/test/helpers.ts | 2 +- packages/testkit/test/oauth.test.ts | 2 +- packages/testkit/test/sharing.test.ts | 137 ++ 28 files changed, 2106 insertions(+), 30 deletions(-) create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/design.md create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/proposal.md create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/project-sharing/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/web-auth/spec.md create mode 100644 openspec/changes/archive/2026-11-12-pep-12-project-sharing/tasks.md create mode 100644 openspec/specs/project-sharing/spec.md create mode 100644 packages/db/migrations/0008_wandering_jetstream.sql create mode 100644 packages/db/migrations/meta/0008_snapshot.json create mode 100644 packages/runner/src/share.ts create mode 100644 packages/testkit/test/sharing.test.ts diff --git a/AGENTS.md b/AGENTS.md index e34d2e5f..da7064f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ - SessionEnd ≠ смерть процесса (/clear, /resume) — это решает вачдог по tmux pane - StopFailure `rate_limit` → `rate_limited`; `peppa session resume ` → `claude --resume` - агент не может сам поставить `done` или выйти из `awaiting_approval` (guard в MCP) +- **Шеринг (PEP-12)**: `project_members` + `project_invites` (по логину Gitea, принимаются при первом входе); доступ везде через `projectForUser` / `userProjectIds` (владелец или участник); `shareProject` / `unshareProject` в runner добавляют/убирают соавтора репо (клиент владельца, затем peppa-bot). Участник может всё, кроме управления участниками; сессии идут на подписке Claude владельца. MCP: list_members, add_member, remove_member - **Подключить Claude (PEP-13)**: «Настройки → Claude» запускает `claude setup-token` в tmux `peppa-auth-u` (runner/claude-auth.ts), пользователь входит по ссылке на своём устройстве и вставляет код в форму; токен шифруется в `users.claude_token_enc` и идёт в сессии проектов владельца как `CLAUDE_CODE_OAUTH_TOKEN`; без токена — вход машины - `template/` — содержимое репо `peppa-bot/template` в Gitea (`scripts/push-template.sh`). `RULES.md` — общие правила агентов: не копируется в проекты, раннер берёт свежую версию из Gitea при каждом запуске (`--append-system-prompt-file`), кэш `~/.peppa/rules.md`; MCP `get_rules` для ручных сессий. `AGENTS.md` — заготовка под специфику проекта - Gitea: бот `peppa-bot` (токен в `.env`), репо `peppa-bot/peppa` (эта платформа), `peppa-bot/template`; git-доступ через per-repo `credential.helper peppa` (`git-credential-peppa`), глобальный git config не трогаем diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 66b07186..908b4570 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -12,7 +12,7 @@ import { revokeApp, setClaudeToken, } from "@peppa/core"; -import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, startClaudeSetup, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; +import { acceptTask, answerAndDeliver, cancelClaudeSetup, finishClaudeSetup, moveTask, provisionProject, shareProject, startClaudeSetup, unshareProject, type BoardColumn, resumeSession, sendToSession, startSession, stopSession, type Provider } from "@peppa/runner"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { requireUser } from "@/lib/auth"; @@ -175,3 +175,23 @@ export async function disconnectClaude(f: FormData) { await setClaudeToken(db, user.id, null); }); } + +export async function addProjectMember(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const r = await shareProject(db, user, p, str(f, "login")); + if (!r.repoAccess) throw new PeppaError(`${r.login} добавлен, но доступ к репозиторию в Gitea выдать не удалось — добавьте соавтора в Gitea вручную`); + }); +} + +export async function removeProjectMember(f: FormData) { + const user = await requireUser(); + await attempt(f, async () => { + const p = await projectForUser(db, user.id, Number(str(f, "projectId"))); + const login = str(f, "login"); + await unshareProject(db, user, p, login); + // Left the project myself: its page is gone for me. + if (login.toLowerCase() === user.login.toLowerCase()) return "/"; + }); +} diff --git a/apps/web/app/(app)/help/page.tsx b/apps/web/app/(app)/help/page.tsx index c575c092..6f75bfbd 100644 --- a/apps/web/app/(app)/help/page.tsx +++ b/apps/web/app/(app)/help/page.tsx @@ -9,6 +9,7 @@ const TOOLS: Array<[string, string]> = [ ["get_task", "карточка задачи: описание, цель, статус, OpenSpec, вопросы, прогресс"], ["create_task / update_task", "завести задачу (в Бэклог); поправить название, описание, цель"], ["move_task", "передвинуть карточку; «В работе» запускает агента, «Бэклог»/«Готово» останавливают"], + ["list_members / add_member / remove_member", "участники проекта: посмотреть, добавить по логину Gitea, убрать или выйти"], ["list_inbox / answer_question", "что ждёт вашего ответа; ответить агенту, принять ревью (accept)"], ]; @@ -22,6 +23,7 @@ const CASES: Array<{ title: string; say: string; how: string }> = [ { title: "Ответить агенту", say: "Что ждёт моего ответа? · Ответь на #42: берём Postgres", how: "list_inbox → answer_question. Агенты спрашивают только об архитектурных стопперах" }, { title: "Принять ревью", say: "Прими PAY-3 · Верни PAY-3: добавь тесты", how: "answer_question с accept (→ Готово) или с замечанием (агент доработает)" }, { title: "Остановить", say: "Верни PAY-3 в бэклог", how: "move_task → backlog: агент останавливается, открытые вопросы закрываются" }, + { title: "Работать вместе", say: "Добавь в PAY участника dana", how: "add_member (только владелец). Участник видит доску и входящие, двигает карточки, отвечает агентам и получает доступ к репозиторию. Тот, кто ещё не входил в Пеппу, получит приглашение — оно сработает при первом входе" }, { title: "Закрыть цель", say: "Отметь цель #5 достигнутой", how: "update_goal status=done" }, ]; @@ -38,6 +40,7 @@ export default async function Help() {
  • Задача (PEP-12) — один результат с описанием и условиями готовности.
  • Доска — Бэклог → В работе → Ревью → Готово. Перенос в «В работе» запускает агента.
  • Агент — Claude Code (или Codex) в сессии на машине Пеппы: пишет OpenSpec-proposal, реализует, открывает PR и отдаёт задачу на ревью.
  • +
  • Участники — владелец проекта добавляет людей по логину Gitea (блок «Участники» на странице проекта). Агенты проекта работают на подписке Claude владельца.
  • Входящие — вопросы агентов (только архитектурные стопперы) и «готово к ревью». Отвечать можно в вебе, Telegram или через MCP.
  • diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index e4c74ab9..68964803 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -6,7 +6,9 @@ import { Board, type Card } from "@/components/Board"; import { columnOf } from "@peppa/runner"; import { requireUser } from "@/lib/auth"; import { board, projectForUserByKey, projectSessions } from "@/lib/queries"; -import { addGoal, addTask } from "../../actions"; +import { listMembers } from "@peppa/core"; +import { db } from "@/lib/db"; +import { addGoal, addProjectMember, addTask, removeProjectMember } from "../../actions"; export default async function ProjectPage({ params, searchParams }: { params: Promise<{ key: string }>; searchParams: Promise<{ error?: string }> }) { const user = await requireUser(); @@ -14,7 +16,8 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr const { error } = await searchParams; const p = await projectForUserByKey(user.id, key).catch(() => null); if (!p) notFound(); - const [{ goals, tasks }, sessions] = await Promise.all([board(p.id), projectSessions(p.id)]); + const [{ goals, tasks }, sessions, team] = await Promise.all([board(p.id), projectSessions(p.id), listMembers(db, p)]); + const isOwner = p.ownerId === user.id; const back = `/p/${p.key}`; const groups = [...goals.map((g) => ({ goal: g })), { goal: null }]; const goalTitle = new Map(goals.map((g) => [g.id, g.title])); @@ -65,6 +68,54 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
    +
    +

    Участники

    +
      +
    • + {team.owner?.login ?? "—"} владелец · агенты работают на его подписке Claude +
    • + {team.members.map((m) => ( +
    • + {m.login} участник + {(isOwner || m.id === user.id) && ( +
      + + + + +
      + )} +
    • + ))} + {team.invites.map((login) => ( +
    • + {login} приглашён · появится после первого входа в Пеппу + {isOwner && ( +
      + + + + +
      + )} +
    • + ))} +
    + {isOwner && ( +
    + + + + +
    + )} + {isOwner && ( +

    + Участник видит доску и входящие, двигает карточки и отвечает агентам; получает доступ на запись к репозиторию. +

    + )} +
    +

    Сессии

    {sessions.length === 0 ?

    Сессий ещё не было.

    : sessions.map((s) => )} diff --git a/apps/web/app/(app)/page.tsx b/apps/web/app/(app)/page.tsx index 8e68f599..0880c2dc 100644 --- a/apps/web/app/(app)/page.tsx +++ b/apps/web/app/(app)/page.tsx @@ -35,7 +35,9 @@ export default async function Inbox({ searchParams }: { searchParams: Promise<{ {p.key} {p.name} - {p.giteaOwner}/{p.giteaRepo} + + {p.ownerId !== user.id && общий} {p.giteaOwner}/{p.giteaRepo} + ))} diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index fa27012d..4227e984 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -166,3 +166,6 @@ table.tools { width: 100%; border-collapse: collapse; } table.tools td { border-top: 1px solid var(--border); padding: 6px 8px; vertical-align: top; } table.tools td.mono { white-space: nowrap; } @media (max-width: 640px) { table.tools td.mono { white-space: normal; overflow-wrap: anywhere; } } + +ul.members { list-style: none; padding: 0; margin: 0 0 10px; } +ul.members li { display: flex; gap: 10px; align-items: center; justify-content: space-between; padding: 6px 0; border-bottom: 1px dashed var(--border); } diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index a118f9f6..3ac1e0d4 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -1,30 +1,31 @@ import { existsSync, readdirSync, readFileSync } from "node:fs"; import { join } from "node:path"; -import { listSessions, PeppaError, projectForUser, resolveTask, type Project, type TaskRef } from "@peppa/core"; +import { listSessions, PeppaError, projectForUser, resolveTask, userProjectIds, type Project, type TaskRef } from "@peppa/core"; import { events, goals, projects, questions, sessions, tasks } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { and, asc, desc, eq, isNull } from "drizzle-orm"; +import { and, asc, desc, eq, inArray, isNull } from "drizzle-orm"; import { db } from "./db"; export type InboxItem = Awaited>[number]; /** Open PM questions across the user's projects, oldest first. */ export async function inbox(userId: number) { + const ids = await userProjectIds(db, userId); + if (!ids.length) return []; const rows = await db .select({ q: questions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title, taskStatus: tasks.status, tmux: sessions.tmuxName }) .from(questions) .innerJoin(projects, eq(questions.projectId, projects.id)) .leftJoin(tasks, eq(questions.taskId, tasks.id)) .leftJoin(sessions, eq(questions.sessionId, sessions.id)) - .where(and(eq(projects.ownerId, userId), isNull(questions.answeredAt))) + .where(and(inArray(projects.id, ids), isNull(questions.answeredAt))) .orderBy(asc(questions.id)); return rows.map((r) => ({ ...r.q, taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null, taskTitle: r.taskTitle, taskStatus: r.taskStatus, tmux: r.tmux })); } export async function activeSessions(userId: number) { - const mine = await db.select({ id: projects.id }).from(projects).where(eq(projects.ownerId, userId)); - if (!mine.length) return []; - const ids = new Set(mine.map((p) => p.id)); + const ids = new Set(await userProjectIds(db, userId)); + if (!ids.size) return []; return (await listSessions(db, { active: true })).filter((s) => ids.has(s.projectId)); } diff --git a/openspec/changes/archive/2026-11-12-pep-12-project-sharing/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/archive/2026-11-12-pep-12-project-sharing/design.md b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/design.md new file mode 100644 index 00000000..4f085d66 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/design.md @@ -0,0 +1,18 @@ +# Design: PEP-12 + +## Decisions + +1. **`projects.owner_id` остаётся** (владелец — чей Claude и кто админ репо), участники — + таблица `project_members`; приглашения по логину — `project_invites`, принимаются в + `upsertUserFromGitea`. Одна точка доступа — `projectForUser` (владелец или участник); + списки — через `userProjectIds`. +2. **Gitea**: существование логина проверяется API; соавтор добавляется клиентом + владельца проекта, при отказе — клиентом `peppa-bot` (проекты в пространстве бота). + Неудача прав не блокирует участие — возвращается флаг `repoAccess: false`. +3. **Сессии по-прежнему на подписке владельца** проекта — менять плательщика без + решения PM не будем. + +## Risks / Trade-offs + +- [Участник тратит лимит Claude владельца] → явно написано в UI блока «Участники». +- [Вопросы агентов в Telegram получает только привязанный чат] → PEP-2. diff --git a/openspec/changes/archive/2026-11-12-pep-12-project-sharing/proposal.md b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/proposal.md new file mode 100644 index 00000000..dae407b1 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/proposal.md @@ -0,0 +1,36 @@ +# Proposal: PEP-12 — шеринг проекта + +Задача Пеппы: **PEP-12** · Цель #2 «Мультипользовательская веб-платформа». + +## Why + +Проект видит только владелец, поэтому работать над ним вдвоём нельзя: второй человек +не видит доску, не может двигать карточки и отвечать агентам. + +## What Changes + +- Участники проекта: владелец добавляет людей по логину Gitea. Если человек уже входил + в Пеппу — он сразу участник; если нет — создаётся приглашение, которое срабатывает + при его первом входе. +- Участник видит проект, доску, задачи, сессии и входящие, создаёт цели и задачи, + двигает карточки, отвечает агентам и принимает ревью — в вебе и через MCP. + Управлять участниками может только владелец; участник может выйти сам. +- Участник добавляется соавтором (write) репозитория в Gitea; при удалении — убирается. +- Веб: блок «Участники» на странице проекта, пометка общих проектов в списке. + MCP: `list_members`, `add_member`, `remove_member`. «Помощь» дополняется. + +Вне scope: Telegram участникам (одна привязка бота, PEP-2); роли тоньше +владелец/участник; чей Claude оплачивает сессии — остаётся подписка владельца проекта. + +## Capabilities + +### New Capabilities +- `project-sharing`: участники и приглашения проекта, их права и доступ к репозиторию. + +### Modified Capabilities +- `web-auth`: доступ к проекту получает не только владелец, но и участники. + +## Impact + +`packages/db` (project_members, project_invites), `packages/core` (доступ, участники), +`packages/runner` (share/unshare с Gitea), `packages/mcp`, `apps/web`, testkit (mock-gitea). diff --git a/openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/project-sharing/spec.md b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/project-sharing/spec.md new file mode 100644 index 00000000..9f6e16ec --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/project-sharing/spec.md @@ -0,0 +1,53 @@ +# Spec Delta: project-sharing + +## Purpose + +Позволяет нескольким пользователям Пеппы вести один проект: владелец добавляет участников, участники работают с задачами и агентами наравне с ним. + +## ADDED Requirements + +### Requirement: Добавление участника +Владелец проекта SHALL добавлять участника по логину Gitea. Существующий пользователь +Пеппы становится участником сразу; для ещё не входившего создаётся приглашение, которое +превращается в участие при его первом входе. Логин, которого нет в Gitea, отклоняется. + +#### Scenario: Пользователь уже есть в Пеппе +- **WHEN** владелец добавляет логин пользователя, который уже входил в Пеппу +- **THEN** проект появляется у этого пользователя в списке проектов + +#### Scenario: Пользователь ещё не входил +- **WHEN** владелец добавляет логин, существующий в Gitea, но не входивший в Пеппу +- **THEN** создаётся приглашение; после первого входа этого человека он участник проекта + +#### Scenario: Несуществующий логин +- **WHEN** владелец добавляет логин, которого нет в Gitea +- **THEN** ошибка, участников и приглашений не прибавилось + +### Requirement: Права участника +Участник SHALL иметь те же возможности в проекте, что владелец (цели, задачи, доска, +сессии, входящие, ревью — в вебе и через MCP), кроме управления участниками. + +#### Scenario: Участник двигает карточку +- **WHEN** участник переносит задачу проекта в «В работе» +- **THEN** действие выполняется так же, как у владельца + +#### Scenario: Участник пытается добавить участника +- **WHEN** участник (не владелец) добавляет или удаляет другого участника +- **THEN** действие отклоняется + +### Requirement: Удаление и выход +Владелец SHALL мочь удалить участника или отозвать приглашение; участник SHALL мочь +выйти из проекта сам. После этого проект ему недоступен. + +#### Scenario: Удаление +- **WHEN** владелец удаляет участника +- **THEN** проект пропадает из его списка, обращение к проекту и его задачам даёт «не найдено» + +### Requirement: Доступ к репозиторию +При добавлении участника Пеппа SHALL добавить его соавтором репозитория проекта с +правом записи, а при удалении — убрать; если у Пеппы нет прав на это в Gitea, участие +всё равно создаётся, а пользователю сообщается, что доступ к репозиторию не выдан. + +#### Scenario: Соавтор +- **WHEN** владелец добавляет участника в проект, репозиторий которого он администрирует +- **THEN** участник — соавтор репозитория с правом write diff --git a/openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/web-auth/spec.md b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/web-auth/spec.md new file mode 100644 index 00000000..a162c2b9 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/specs/web-auth/spec.md @@ -0,0 +1,15 @@ +# Spec Delta: web-auth + +## MODIFIED Requirements + +### Requirement: Доступ только к своим проектам +Пользователь SHALL видеть и изменять только проекты, в которых он владелец или участник, +а также их цели, задачи, сессии и вопросы. + +#### Scenario: Чужой проект +- **WHEN** пользователь открывает проект, задачу или сессию проекта, где он не владелец и не участник (в том числе по прямой ссылке), или отправляет по ним действие +- **THEN** он получает «не найдено», данные не раскрываются и не меняются + +#### Scenario: Проект, где пользователь участник +- **WHEN** участник открывает общий проект +- **THEN** он видит его так же, как владелец diff --git a/openspec/changes/archive/2026-11-12-pep-12-project-sharing/tasks.md b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/tasks.md new file mode 100644 index 00000000..da2a49f3 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-12-project-sharing/tasks.md @@ -0,0 +1,16 @@ +# Tasks: PEP-12 + +## 1. Данные и доступ + +- [x] 1.1 Таблицы `project_members`, `project_invites`; core: `projectForUser`/`listUserProjects`/`userProjectIds` с участниками, `addMember`, `removeMember`, `listMembers`, приём приглашений при входе +- [x] 1.2 runner: `shareProject` / `unshareProject` (проверка логина в Gitea, соавтор, права владельца, выход участника) + +## 2. Интерфейсы + +- [x] 2.1 Веб: блок «Участники» на странице проекта, пометка общих проектов, входящие и сессии общих проектов +- [x] 2.2 MCP: `list_members`, `add_member`, `remove_member`; входящие с общими проектами; «Помощь» + +## 3. Проверка + +- [x] 3.1 Тесты на mock-gitea: добавление, приглашение и приём при входе, несуществующий логин, права участника, удаление, выход, соавтор и fallback на бота; весь набор зелёный +- [x] 3.2 Выкатка (миграция, сборка); проверка на проде глазами участника; `openspec validate` diff --git a/openspec/specs/project-sharing/spec.md b/openspec/specs/project-sharing/spec.md new file mode 100644 index 00000000..b14417e9 --- /dev/null +++ b/openspec/specs/project-sharing/spec.md @@ -0,0 +1,52 @@ +# project-sharing Specification + +## Purpose +Позволяет нескольким пользователям Пеппы вести один проект: владелец добавляет участников, участники работают с задачами и агентами наравне с ним. + +## Requirements + +### Requirement: Добавление участника +Владелец проекта SHALL добавлять участника по логину Gitea. Существующий пользователь +Пеппы становится участником сразу; для ещё не входившего создаётся приглашение, которое +превращается в участие при его первом входе. Логин, которого нет в Gitea, отклоняется. + +#### Scenario: Пользователь уже есть в Пеппе +- **WHEN** владелец добавляет логин пользователя, который уже входил в Пеппу +- **THEN** проект появляется у этого пользователя в списке проектов + +#### Scenario: Пользователь ещё не входил +- **WHEN** владелец добавляет логин, существующий в Gitea, но не входивший в Пеппу +- **THEN** создаётся приглашение; после первого входа этого человека он участник проекта + +#### Scenario: Несуществующий логин +- **WHEN** владелец добавляет логин, которого нет в Gitea +- **THEN** ошибка, участников и приглашений не прибавилось + +### Requirement: Права участника +Участник SHALL иметь те же возможности в проекте, что владелец (цели, задачи, доска, +сессии, входящие, ревью — в вебе и через MCP), кроме управления участниками. + +#### Scenario: Участник двигает карточку +- **WHEN** участник переносит задачу проекта в «В работе» +- **THEN** действие выполняется так же, как у владельца + +#### Scenario: Участник пытается добавить участника +- **WHEN** участник (не владелец) добавляет или удаляет другого участника +- **THEN** действие отклоняется + +### Requirement: Удаление и выход +Владелец SHALL мочь удалить участника или отозвать приглашение; участник SHALL мочь +выйти из проекта сам. После этого проект ему недоступен. + +#### Scenario: Удаление +- **WHEN** владелец удаляет участника +- **THEN** проект пропадает из его списка, обращение к проекту и его задачам даёт «не найдено» + +### Requirement: Доступ к репозиторию +При добавлении участника Пеппа SHALL добавить его соавтором репозитория проекта с +правом записи, а при удалении — убрать; если у Пеппы нет прав на это в Gitea, участие +всё равно создаётся, а пользователю сообщается, что доступ к репозиторию не выдан. + +#### Scenario: Соавтор +- **WHEN** владелец добавляет участника в проект, репозиторий которого он администрирует +- **THEN** участник — соавтор репозитория с правом write diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md index fd2080bd..1ee2108d 100644 --- a/openspec/specs/web-auth/spec.md +++ b/openspec/specs/web-auth/spec.md @@ -30,13 +30,17 @@ - **THEN** cookie сессии удаляется, и следующий запрос требует входа ### Requirement: Доступ только к своим проектам -Пользователь SHALL видеть и изменять только проекты, владельцем которых он является, а -также их цели, задачи, сессии и вопросы. +Пользователь SHALL видеть и изменять только проекты, в которых он владелец или участник, +а также их цели, задачи, сессии и вопросы. #### Scenario: Чужой проект -- **WHEN** пользователь открывает проект, задачу или сессию чужого проекта (в том числе по прямой ссылке) или отправляет по ним действие +- **WHEN** пользователь открывает проект, задачу или сессию проекта, где он не владелец и не участник (в том числе по прямой ссылке), или отправляет по ним действие - **THEN** он получает «не найдено», данные не раскрываются и не меняются +#### Scenario: Проект, где пользователь участник +- **WHEN** участник открывает общий проект +- **THEN** он видит его так же, как владелец + ### Requirement: Токены Gitea пользователя Токены OAuth пользователя SHALL храниться только в зашифрованном виде и обновляться по refresh-токену, когда истекли. Токены не показываются в вебе и не пишутся в логи. diff --git a/packages/core/src/gitea.ts b/packages/core/src/gitea.ts index d9c8a59a..c188e020 100644 --- a/packages/core/src/gitea.ts +++ b/packages/core/src/gitea.ts @@ -99,6 +99,20 @@ export class GiteaClient { return this.request("PUT", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`, { permission }); } + removeCollaborator(owner: string, repo: string, login: string) { + return this.request("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/collaborators/${encodeURIComponent(login)}`); + } + + /** A Gitea account by login (null if there is none). */ + async getUserByLogin(login: string): Promise { + try { + return await this.request("GET", `/users/${encodeURIComponent(login)}`); + } catch (e) { + if (e instanceof GiteaError && e.status === 404) return null; + throw e; + } + } + deleteRepo(owner: string, repo: string) { return this.request("DELETE", `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`); } diff --git a/packages/core/src/users.ts b/packages/core/src/users.ts index 2c46d808..b765e1d4 100644 --- a/packages/core/src/users.ts +++ b/packages/core/src/users.ts @@ -1,6 +1,6 @@ -import { projects, users, type Db } from "@peppa/db"; +import { projectInvites, projectMembers, projects, users, type Db } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; -import { and, asc, eq } from "drizzle-orm"; +import { and, asc, eq, inArray, sql } from "drizzle-orm"; import { decrypt, encrypt, hashToken } from "./crypto.ts"; import { randomBytes } from "node:crypto"; import { deleteSetting, getSetting, setSetting } from "./settings.ts"; @@ -26,6 +26,7 @@ export async function upsertUserFromGitea(db: Db, g: GiteaUser, tokens: OAuthTok .values(values) .onConflictDoUpdate({ target: users.giteaId, set: values }) .returning(); + await acceptInvites(db, row!); return row!; } @@ -72,20 +73,90 @@ export function giteaForBot(): GiteaClient { return new GiteaClient(env.GITEA_URL, env.GITEA_TOKEN); } -export async function listUserProjects(db: Db, userId: number): Promise { - return db.select().from(projects).where(eq(projects.ownerId, userId)).orderBy(asc(projects.key)); +/** Ids of the projects a user owns or is a member of. */ +export async function userProjectIds(db: Db, userId: number): Promise { + const owned = await db.select({ id: projects.id }).from(projects).where(eq(projects.ownerId, userId)); + const shared = await db.select({ id: projectMembers.projectId }).from(projectMembers).where(eq(projectMembers.userId, userId)); + return [...new Set([...owned, ...shared].map((r) => r.id))]; } -/** The project if `userId` owns it; otherwise "not found" (no existence leak). */ +/** Projects the user owns or is a member of. */ +export async function listUserProjects(db: Db, userId: number): Promise { + const ids = await userProjectIds(db, userId); + if (!ids.length) return []; + return db.select().from(projects).where(inArray(projects.id, ids)).orderBy(asc(projects.key)); +} + +/** The project if `userId` owns it or is a member; otherwise "not found" (no existence leak). */ export async function projectForUser(db: Db, userId: number, projectId: number): Promise { - const [row] = await db - .select() - .from(projects) - .where(and(eq(projects.id, projectId), eq(projects.ownerId, userId))); + const [row] = await db.select().from(projects).where(eq(projects.id, projectId)); + if (row && row.ownerId !== userId) { + const [m] = await db + .select() + .from(projectMembers) + .where(and(eq(projectMembers.projectId, projectId), eq(projectMembers.userId, userId))); + if (!m) throw new PeppaError("Не найдено"); + } if (!row) throw new PeppaError("Не найдено"); return row; } +const loginIs = (login: string) => sql`lower(${users.login}) = ${login.toLowerCase()}`; + +export interface ProjectMembers { + owner: User | null; + members: User[]; + invites: string[]; +} + +export async function listMembers(db: Db, project: Pick): Promise { + const owner = project.ownerId ? await getUser(db, project.ownerId) : null; + const rows = await db + .select({ user: users }) + .from(projectMembers) + .innerJoin(users, eq(projectMembers.userId, users.id)) + .where(eq(projectMembers.projectId, project.id)) + .orderBy(asc(users.login)); + const invites = await db.select().from(projectInvites).where(eq(projectInvites.projectId, project.id)).orderBy(asc(projectInvites.login)); + return { owner, members: rows.map((r) => r.user), invites: invites.map((i) => i.login) }; +} + +/** + * Adds a Gitea login to a project: a member right away if that person has logged into + * Peppa, otherwise an invitation accepted at their first login. + */ +export async function addMember(db: Db, project: Pick, login: string, addedBy: number | null): Promise<"added" | "invited"> { + const [u] = await db.select().from(users).where(loginIs(login)); + if (u) { + if (u.id === project.ownerId) throw new PeppaError(`${u.login} — владелец проекта`); + await db.insert(projectMembers).values({ projectId: project.id, userId: u.id, addedBy }).onConflictDoNothing(); + return "added"; + } + await db.insert(projectInvites).values({ projectId: project.id, login: login.toLowerCase(), invitedBy: addedBy }).onConflictDoNothing(); + return "invited"; +} + +/** Removes a member or a pending invitation. False if the login was neither. */ +export async function removeMember(db: Db, projectId: number, login: string): Promise { + const [u] = await db.select().from(users).where(loginIs(login)); + const removed = u + ? await db.delete(projectMembers).where(and(eq(projectMembers.projectId, projectId), eq(projectMembers.userId, u.id))).returning() + : []; + const invites = await db + .delete(projectInvites) + .where(and(eq(projectInvites.projectId, projectId), eq(projectInvites.login, login.toLowerCase()))) + .returning(); + return removed.length + invites.length > 0; +} + +/** Turns pending invitations for this login into memberships (called at login). */ +async function acceptInvites(db: Db, user: User): Promise { + const invites = await db.delete(projectInvites).where(eq(projectInvites.login, user.login.toLowerCase())).returning(); + for (const i of invites) { + await db.insert(projectMembers).values({ projectId: i.projectId, userId: user.id, addedBy: i.invitedBy }).onConflictDoNothing(); + } +} + export async function setProjectOwner(db: Db, projectId: number, userId: number | null): Promise { await db.update(projects).set({ ownerId: userId }).where(eq(projects.id, projectId)); } diff --git a/packages/db/migrations/0008_wandering_jetstream.sql b/packages/db/migrations/0008_wandering_jetstream.sql new file mode 100644 index 00000000..f94bc48f --- /dev/null +++ b/packages/db/migrations/0008_wandering_jetstream.sql @@ -0,0 +1,21 @@ +CREATE TABLE "project_invites" ( + "project_id" integer NOT NULL, + "login" text NOT NULL, + "invited_by" integer, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "project_invites_project_id_login_pk" PRIMARY KEY("project_id","login") +); +--> statement-breakpoint +CREATE TABLE "project_members" ( + "project_id" integer NOT NULL, + "user_id" integer NOT NULL, + "added_by" integer, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "project_members_project_id_user_id_pk" PRIMARY KEY("project_id","user_id") +); +--> statement-breakpoint +ALTER TABLE "project_invites" ADD CONSTRAINT "project_invites_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project_invites" ADD CONSTRAINT "project_invites_invited_by_users_id_fk" FOREIGN KEY ("invited_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project_members" ADD CONSTRAINT "project_members_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project_members" ADD CONSTRAINT "project_members_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "project_members" ADD CONSTRAINT "project_members_added_by_users_id_fk" FOREIGN KEY ("added_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action; \ No newline at end of file diff --git a/packages/db/migrations/meta/0008_snapshot.json b/packages/db/migrations/meta/0008_snapshot.json new file mode 100644 index 00000000..4c6b99ff --- /dev/null +++ b/packages/db/migrations/meta/0008_snapshot.json @@ -0,0 +1,1402 @@ +{ + "id": "69625371-6b59-41c2-8555-4582c3e311fa", + "prevId": "d7d79655-c98d-4cc6-b49b-b8db3ce22738", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "events_project_id_projects_id_fk": { + "name": "events_project_id_projects_id_fk", + "tableFrom": "events", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_task_id_tasks_id_fk": { + "name": "events_task_id_tasks_id_fk", + "tableFrom": "events", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "events_session_id_sessions_id_fk": { + "name": "events_session_id_sessions_id_fk", + "tableFrom": "events", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.goals": { + "name": "goals", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "goal_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "goals_project_id_projects_id_fk": { + "name": "goals_project_id_projects_id_fk", + "tableFrom": "goals", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_clients": { + "name": "oauth_clients", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "redirect_uris": { + "name": "redirect_uris", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_codes": { + "name": "oauth_codes", + "schema": "", + "columns": { + "code_hash": { + "name": "code_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "redirect_uri": { + "name": "redirect_uri", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "code_challenge": { + "name": "code_challenge", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_codes_client_id_oauth_clients_id_fk": { + "name": "oauth_codes_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_codes_user_id_users_id_fk": { + "name": "oauth_codes_user_id_users_id_fk", + "tableFrom": "oauth_codes", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.oauth_tokens": { + "name": "oauth_tokens", + "schema": "", + "columns": { + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "oauth_tokens_client_id_oauth_clients_id_fk": { + "name": "oauth_tokens_client_id_oauth_clients_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "oauth_clients", + "columnsFrom": [ + "client_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "oauth_tokens_user_id_users_id_fk": { + "name": "oauth_tokens_user_id_users_id_fk", + "tableFrom": "oauth_tokens", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_invites": { + "name": "project_invites", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "invited_by": { + "name": "invited_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "project_invites_project_id_projects_id_fk": { + "name": "project_invites_project_id_projects_id_fk", + "tableFrom": "project_invites", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_invites_invited_by_users_id_fk": { + "name": "project_invites_invited_by_users_id_fk", + "tableFrom": "project_invites", + "tableTo": "users", + "columnsFrom": [ + "invited_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_invites_project_id_login_pk": { + "name": "project_invites_project_id_login_pk", + "columns": [ + "project_id", + "login" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.project_members": { + "name": "project_members", + "schema": "", + "columns": { + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_by": { + "name": "added_by", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "project_members_project_id_projects_id_fk": { + "name": "project_members_project_id_projects_id_fk", + "tableFrom": "project_members", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_user_id_users_id_fk": { + "name": "project_members_user_id_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "project_members_added_by_users_id_fk": { + "name": "project_members_added_by_users_id_fk", + "tableFrom": "project_members", + "tableTo": "users", + "columnsFrom": [ + "added_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "project_members_project_id_user_id_pk": { + "name": "project_members_project_id_user_id_pk", + "columns": [ + "project_id", + "user_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.projects": { + "name": "projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "gitea_owner": { + "name": "gitea_owner", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "gitea_repo": { + "name": "gitea_repo", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_branch": { + "name": "default_branch", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'main'" + }, + "workspace_path": { + "name": "workspace_path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "next_task_number": { + "name": "next_task_number", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "projects_owner_id_users_id_fk": { + "name": "projects_owner_id_users_id_fk", + "tableFrom": "projects", + "tableTo": "users", + "columnsFrom": [ + "owner_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "projects_slug_unique": { + "name": "projects_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "projects_key_unique": { + "name": "projects_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.questions": { + "name": "questions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "answer": { + "name": "answer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "answered_via": { + "name": "answered_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "awaiting_hook": { + "name": "awaiting_hook", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "questions_project_id_projects_id_fk": { + "name": "questions_project_id_projects_id_fk", + "tableFrom": "questions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_task_id_tasks_id_fk": { + "name": "questions_task_id_tasks_id_fk", + "tableFrom": "questions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "questions_session_id_sessions_id_fk": { + "name": "questions_session_id_sessions_id_fk", + "tableFrom": "questions", + "tableTo": "sessions", + "columnsFrom": [ + "session_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "task_id": { + "name": "task_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "tmux_name": { + "name": "tmux_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'claude'" + }, + "claude_session_id": { + "name": "claude_session_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "auto_nudges": { + "name": "auto_nudges", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "session_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'starting'" + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_project_id_projects_id_fk": { + "name": "sessions_project_id_projects_id_fk", + "tableFrom": "sessions", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "sessions_task_id_tasks_id_fk": { + "name": "sessions_task_id_tasks_id_fk", + "tableFrom": "sessions", + "tableTo": "tasks", + "columnsFrom": [ + "task_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_tmux_name_unique": { + "name": "sessions_tmux_name_unique", + "nullsNotDistinct": false, + "columns": [ + "tmux_name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.settings": { + "name": "settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tasks": { + "name": "tasks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "project_id": { + "name": "project_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "goal_id": { + "name": "goal_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "task_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'backlog'" + }, + "openspec_change": { + "name": "openspec_change", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pr_url": { + "name": "pr_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tasks_project_number": { + "name": "tasks_project_number", + "columns": [ + { + "expression": "project_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "tasks_project_id_projects_id_fk": { + "name": "tasks_project_id_projects_id_fk", + "tableFrom": "tasks", + "tableTo": "projects", + "columnsFrom": [ + "project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tasks_goal_id_goals_id_fk": { + "name": "tasks_goal_id_goals_id_fk", + "tableFrom": "tasks", + "tableTo": "goals", + "columnsFrom": [ + "goal_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_outbox": { + "name": "telegram_outbox", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "params": { + "name": "params", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "question_id": { + "name": "question_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt_at": { + "name": "next_attempt_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "telegram_message_id": { + "name": "telegram_message_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "telegram_outbox_question_id_questions_id_fk": { + "name": "telegram_outbox_question_id_questions_id_fk", + "tableFrom": "telegram_outbox", + "tableTo": "questions", + "columnsFrom": [ + "question_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "telegram_outbox_dedupe_key_unique": { + "name": "telegram_outbox_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.telegram_updates": { + "name": "telegram_updates", + "schema": "", + "columns": { + "update_id": { + "name": "update_id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "gitea_id": { + "name": "gitea_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "login": { + "name": "login", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_enc": { + "name": "access_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token_enc": { + "name": "refresh_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "token_expires_at": { + "name": "token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claude_token_enc": { + "name": "claude_token_enc", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claude_token_set_at": { + "name": "claude_token_set_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_login_at": { + "name": "last_login_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_gitea_id_unique": { + "name": "users_gitea_id_unique", + "nullsNotDistinct": false, + "columns": [ + "gitea_id" + ] + }, + "users_login_unique": { + "name": "users_login_unique", + "nullsNotDistinct": false, + "columns": [ + "login" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.goal_status": { + "name": "goal_status", + "schema": "public", + "values": [ + "open", + "done", + "archived" + ] + }, + "public.session_status": { + "name": "session_status", + "schema": "public", + "values": [ + "starting", + "running", + "waiting_input", + "idle", + "stalled", + "rate_limited", + "done", + "failed" + ] + }, + "public.task_status": { + "name": "task_status", + "schema": "public", + "values": [ + "backlog", + "proposing", + "awaiting_approval", + "in_progress", + "review", + "done", + "blocked" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 0aa98ed7..2f3c2115 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -57,6 +57,13 @@ "when": 1794502693680, "tag": "0007_empty_crystal", "breakpoints": true + }, + { + "idx": 8, + "version": "7", + "when": 1794504595170, + "tag": "0008_wandering_jetstream", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index ec8be278..d6f38cc7 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -1,5 +1,5 @@ import { relations } from "drizzle-orm"; -import { boolean, integer, jsonb, pgEnum, pgTable, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core"; +import { boolean, integer, jsonb, pgEnum, pgTable, primaryKey, serial, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core"; const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow(); const updatedAt = () => @@ -44,6 +44,30 @@ export const projects = pgTable("projects", { updatedAt: updatedAt(), }); +/** People who work on a project besides its owner (projects.owner_id). */ +export const projectMembers = pgTable( + "project_members", + { + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + userId: integer("user_id").notNull().references(() => users.id, { onDelete: "cascade" }), + addedBy: integer("added_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.projectId, t.userId] })], +); + +/** Invitations for Gitea logins that have not logged into Peppa yet; accepted at first login. */ +export const projectInvites = pgTable( + "project_invites", + { + projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }), + login: text("login").notNull(), // lower-cased Gitea login + invitedBy: integer("invited_by").references(() => users.id, { onDelete: "set null" }), + createdAt: createdAt(), + }, + (t) => [primaryKey({ columns: [t.projectId, t.login] })], +); + export const goalStatus = pgEnum("goal_status", ["open", "done", "archived"]); /** Top-level objectives set by the PM; tasks are broken out of them. */ diff --git a/packages/mcp/src/manager.ts b/packages/mcp/src/manager.ts index 2ff1775d..236d2647 100644 --- a/packages/mcp/src/manager.ts +++ b/packages/mcp/src/manager.ts @@ -11,18 +11,20 @@ import { getQuestion, getTaskDetails, listGoals, + listMembers, listTasks, listUserProjects, PeppaError, projectForUser, resolveTask, updateTask, + userProjectIds, type User, } from "@peppa/core"; import { questions, projects, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; -import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, provisionProject, type BoardColumn, type Provider } from "@peppa/runner"; -import { and, asc, eq, isNull } from "drizzle-orm"; +import { acceptTask, answerAndDeliver, columnOf, isReviewQuestion, moveTask, provisionProject, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner"; +import { and, asc, eq, inArray, isNull } from "drizzle-orm"; import { z } from "zod"; import { formatTask } from "./format.ts"; @@ -41,7 +43,8 @@ Good habits: - Before creating, look: list_projects, list_goals, list_tasks. Don't duplicate — fix with update_task / update_goal. - Put tasks under a goal (goal_id). Write task descriptions with context and a "Definition of done" list; the agent works from them. - Only move a task to in_progress when the user asks to start the work. -- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user.`; +- Statuses: get_task for details, list_tasks for the board, list_inbox for what needs the user. +- Projects can be shared: add_member / remove_member (owner only); members can do everything else.`; export function createManagerServer(db: Db, user: User, webUrl: string): McpServer { const server = new McpServer({ name: "peppa", version: "0.3.0" }, { instructions: MANAGER_INSTRUCTIONS }); @@ -72,11 +75,45 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ for (const p of ps) { const ts = await listTasks(db, { projectId: p.id }); const counts = COLUMNS.map((c) => `${COLUMN_NAME[c]} ${ts.filter((t) => columnOf(t.status) === c).length}`).join(", "); - lines.push(`- ${p.key} — ${p.name} (${p.giteaOwner}/${p.giteaRepo}): ${counts}`); + lines.push(`- ${p.key} — ${p.name} (${p.giteaOwner}/${p.giteaRepo})${p.ownerId === user.id ? "" : " [shared with you]"}: ${counts}`); } return lines.join("\n"); }); + tool("list_members", "Who works on a project: owner, members and pending invitations.", { project: projectArg }, true, async ({ project }) => { + const p = await ownedProject(project); + const m = await listMembers(db, p); + return [ + `Owner: ${m.owner?.login ?? "—"}`, + `Members: ${m.members.map((u) => u.login).join(", ") || "—"}`, + `Invited (not logged in yet): ${m.invites.join(", ") || "—"}`, + ].join("\n"); + }); + + tool( + "add_member", + "Share a project with another person by Gitea login (owner only). They get the same access as the owner except managing members, plus write access to the repo. If they never logged into Peppa, an invitation is created and applied at their first login.", + { project: projectArg, login: z.string().min(1).describe("Gitea login") }, + false, + async ({ project, login }) => { + const p = await ownedProject(project); + const r = await shareProject(db, user, p, login); + return `${r.login}: ${r.status === "added" ? "added to" : "invited to"} ${p.key}${r.repoAccess ? " · repo collaborator (write)" : " · repo access NOT granted (no admin rights in Gitea) — add them in Gitea manually"}`; + }, + ); + + tool( + "remove_member", + "Remove a member or cancel an invitation (owner), or leave a shared project yourself (pass your own login).", + { project: projectArg, login: z.string().min(1) }, + false, + async ({ project, login }) => { + const p = await ownedProject(project); + await unshareProject(db, user, p, login); + return `${login} removed from ${p.key}`; + }, + ); + tool("list_goals", "List open top-level goals of a project.", { project: projectArg }, true, async ({ project }) => { const p = await ownedProject(project); const gs = await listGoals(db, p.id); @@ -199,12 +236,14 @@ export function createManagerServer(db: Db, user: User, webUrl: string): McpServ ); tool("list_inbox", "Open questions from agents waiting for the user (approvals, questions, permissions, ready-for-review), oldest first.", {}, true, async () => { + const ids = await userProjectIds(db, user.id); + if (!ids.length) return "Inbox is empty — agents need nothing from you."; const rows = await db .select({ q: questions, key: projects.key, number: tasks.number, status: tasks.status }) .from(questions) .innerJoin(projects, eq(questions.projectId, projects.id)) .leftJoin(tasks, eq(questions.taskId, tasks.id)) - .where(and(eq(projects.ownerId, user.id), isNull(questions.answeredAt))) + .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 diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 3cc94a96..ae1274fb 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -7,3 +7,4 @@ export * from "./providers.ts"; export * from "./provision.ts"; export * from "./flow.ts"; export * from "./claude-auth.ts"; +export * from "./share.ts"; diff --git a/packages/runner/src/share.ts b/packages/runner/src/share.ts new file mode 100644 index 00000000..92816559 --- /dev/null +++ b/packages/runner/src/share.ts @@ -0,0 +1,71 @@ +// Sharing a project: Peppa membership plus collaborator access to its Gitea repo. +import { + addMember, + getUser, + giteaForBot, + giteaForUser, + PeppaError, + removeMember, + type GiteaClient, + type Project, + type User, +} from "@peppa/core"; +import type { Db } from "@peppa/db"; + +/** Gitea clients that may administer the project's repo: its owner, then peppa-bot. */ +async function repoAdmins(db: Db, project: Project): Promise { + const out: GiteaClient[] = []; + const owner = project.ownerId ? await getUser(db, project.ownerId) : null; + if (owner) { + try { + out.push(await giteaForUser(db, owner)); + } catch {} + } + try { + out.push(giteaForBot()); + } catch {} + return out; +} + +export interface ShareResult { + login: string; + status: "added" | "invited"; + /** False when Peppa could not add the person as a repo collaborator in Gitea. */ + repoAccess: boolean; +} + +/** Owner adds a person (by Gitea login) to the project and to its repo (write). */ +export async function shareProject(db: Db, actor: User, project: Project, loginInput: string): Promise { + if (project.ownerId !== actor.id) throw new PeppaError("Участниками управляет только владелец проекта"); + const login = loginInput.trim().replace(/^@/, ""); + if (!login) throw new PeppaError("Укажите логин Gitea"); + const clients = await repoAdmins(db, project); + if (!clients.length) throw new PeppaError("Нет доступа к Gitea — войдите заново"); + const account = await clients[0]!.getUserByLogin(login); + if (!account) throw new PeppaError(`Пользователь «${login}» не найден в Gitea`); + + const status = await addMember(db, project, account.login, actor.id); + let repoAccess = false; + for (const c of clients) { + try { + await c.addCollaborator(project.giteaOwner, project.giteaRepo, account.login, "write"); + repoAccess = true; + break; + } catch {} + } + return { login: account.login, status, repoAccess }; +} + +/** Owner removes a member/invitation, or a member leaves. */ +export async function unshareProject(db: Db, actor: User, project: Project, loginInput: string): Promise { + const login = loginInput.trim().replace(/^@/, ""); + const self = actor.login.toLowerCase() === login.toLowerCase(); + if (project.ownerId !== actor.id && !self) throw new PeppaError("Участниками управляет только владелец проекта"); + if (!(await removeMember(db, project.id, login))) throw new PeppaError(`«${login}» не участник проекта`); + for (const c of await repoAdmins(db, project)) { + try { + await c.removeCollaborator(project.giteaOwner, project.giteaRepo, login); + break; + } catch {} + } +} diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 0c97af03..005cd616 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -123,6 +123,11 @@ export class MockGitea { if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)\/orgs\/([^/]+)\/permissions$/))) { return { status: 200, body: { can_create_repository: (me.orgs ?? []).includes(decodeURIComponent(m[2]!)) } }; } + if (method === "GET" && (m = path.match(/^\/api\/v1\/users\/([^/]+)$/))) { + const want = decodeURIComponent(m[1]!).toLowerCase(); + const u = [...this.users.values()].find((x) => x.login.toLowerCase() === want); + return u ? { status: 200, body: { id: u.id, login: u.login, full_name: u.login } } : { status: 404, body: { message: "user does not exist" } }; + } if ((m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)$/))) { const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); if (!r) return { status: 404, body: { message: "not found" } }; @@ -141,6 +146,13 @@ export class MockGitea { r.collaborators[decodeURIComponent(m[3]!)] = String(body.permission); return { status: 204 }; } + if (method === "DELETE" && (m = path.match(/^\/api\/v1\/repos\/([^/]+)\/([^/]+)\/collaborators\/([^/]+)$/))) { + const r = this.repos.get(`${decodeURIComponent(m[1]!)}/${decodeURIComponent(m[2]!)}`); + if (!r) return { status: 404, body: { message: "not found" } }; + if (!r.admins.has(me.login)) return { status: 403, body: { message: "forbidden" } }; + delete r.collaborators[decodeURIComponent(m[3]!)]; + return { status: 204 }; + } return { status: 404, body: { message: `mock-gitea: ${method} ${path}` } }; } } diff --git a/packages/testkit/test/helpers.ts b/packages/testkit/test/helpers.ts index f6d4a332..26939366 100644 --- a/packages/testkit/test/helpers.ts +++ b/packages/testkit/test/helpers.ts @@ -42,7 +42,7 @@ const { sql } = await import("drizzle-orm"); export const db = dbmod.createDb(); await migrate(db, { migrationsFolder: join(ROOT, "packages/db/migrations") }); -await db.execute(sql`truncate projects, settings, telegram_outbox, telegram_updates restart identity cascade`); +await db.execute(sql`truncate projects, users, settings, telegram_outbox, telegram_updates, oauth_clients restart identity cascade`); export async function teardown() { await db.$client.end(); diff --git a/packages/testkit/test/oauth.test.ts b/packages/testkit/test/oauth.test.ts index 6dee986a..70778c2b 100644 --- a/packages/testkit/test/oauth.test.ts +++ b/packages/testkit/test/oauth.test.ts @@ -99,7 +99,7 @@ describe("PM tools over MCP", () => { await core.setProjectOwner(db, proj.id, owner.id); const { client, call } = await mcpAs(owner); const tools = (await client.listTools()).tools; - assert.deepEqual(tools.map((t) => t.name).sort(), ["answer_question", "create_goal", "create_project", "create_task", "get_task", "list_goals", "list_inbox", "list_projects", "list_tasks", "move_task", "update_goal", "update_task"]); + assert.deepEqual(tools.map((t) => t.name).sort(), ["add_member", "answer_question", "create_goal", "create_project", "create_task", "get_task", "list_goals", "list_inbox", "list_members", "list_projects", "list_tasks", "move_task", "remove_member", "update_goal", "update_task"]); assert.equal(tools.find((t) => t.name === "list_tasks")?.annotations?.readOnlyHint, true); assert.equal(tools.find((t) => t.name === "move_task")?.annotations?.readOnlyHint, false); diff --git a/packages/testkit/test/sharing.test.ts b/packages/testkit/test/sharing.test.ts new file mode 100644 index 00000000..e0ccc38c --- /dev/null +++ b/packages/testkit/test/sharing.test.ts @@ -0,0 +1,137 @@ +// PEP-12: sharing a project — members, invitations, rights, Gitea collaborators. +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 { core, db, project, runner, teardown } from "./helpers.ts"; +import { MockGitea } from "../src/mock-gitea.ts"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; + +process.env.PEPPA_SECRET = "mock-secret-for-tests"; +const { createManagerServer } = await import("@peppa/mcp/manager"); + +const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-share-")), "gitea")); +const OWNER = { id: 51, login: "mock-owner", token: "mock-token-owner" }; +const MEMBER = { id: 52, login: "Mock-Member", token: "mock-token-member" }; +const OUTSIDER = { id: 53, login: "mock-outsider", token: "mock-token-outsider" }; +const GHOST = { id: 54, login: "mock-ghost", token: "mock-token-ghost" }; // in Gitea, never logged into Peppa +const BOT = { id: 55, login: "peppa-bot", token: "mock-token-bot" }; +type U = Awaited>; +let owner: U, member: U, outsider: U; + +before(async () => { + await gitea.start(); + process.env.GITEA_URL = gitea.url; + process.env.GITEA_TOKEN = BOT.token; + for (const u of [OWNER, MEMBER, OUTSIDER, GHOST, BOT]) gitea.addUser(u); + owner = await core.upsertUserFromGitea(db, OWNER, { access_token: OWNER.token }); + member = await core.upsertUserFromGitea(db, MEMBER, { access_token: MEMBER.token }); + outsider = await core.upsertUserFromGitea(db, OUTSIDER, { access_token: OUTSIDER.token }); +}); +after(async () => { + await gitea.stop(); + await teardown(); +}); + +/** A project owned by `owner` whose repo exists in mock Gitea with the given admins. */ +async function shared(admins: string[] = [OWNER.login]) { + const p = await project({ turns: [] }); + const proj = await core.getProject(db, p.key); + await core.setProjectOwner(db, proj.id, owner.id); + const repo = gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { admins }); + return { p, proj: await core.getProject(db, p.key), repo }; +} + +async function mcpAs(user: U) { + const [a, b] = InMemoryTransport.createLinkedPair(); + await createManagerServer(db, user, "https://peppa.test").connect(a); + const client = new Client({ name: "mock-chatgpt", 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 }; + }; +} + +describe("project sharing", () => { + test("owner adds an existing user: same access as the owner, repo collaborator, but no member management", async () => { + const { p, proj, repo } = await shared(); + await assert.rejects(core.projectForUser(db, member.id, proj.id), /Не найдено/); + const r = await runner.shareProject(db, owner, proj, "@mock-member"); // case-insensitive, @ allowed + assert.deepEqual(r, { login: MEMBER.login, status: "added", repoAccess: true }); + assert.equal(repo.collaborators[MEMBER.login], "write"); + assert.equal((await core.projectForUser(db, member.id, proj.id)).key, p.key); + assert.ok((await core.listUserProjects(db, member.id)).some((x) => x.key === p.key)); + await assert.rejects(core.projectForUser(db, outsider.id, proj.id), /Не найдено/); + + // Works through MCP like for the owner: board, tasks, inbox. + const asMember = await mcpAs(member); + assert.match((await asMember("list_projects")).text, new RegExp(`${p.key} — .*\\[shared with you\\]`)); + const created = await asMember("create_task", { project: p.key, title: "Задача от участника" }); + assert.ok(!created.isError, created.text); + const ref = await core.resolveTask(db, `${p.key}-2`); + await core.askPm(db, ref, { kind: "question", text: "Вопрос в общем проекте?" }); + assert.match((await asMember("list_inbox")).text, /Вопрос в общем проекте/); + assert.doesNotMatch((await (await mcpAs(outsider))("list_inbox")).text, /Вопрос в общем проекте/); + assert.match((await asMember("list_members", { project: p.key })).text, /Owner: mock-owner[\s\S]*Members: Mock-Member/); + + // …except managing members. + const denied = await asMember("add_member", { project: p.key, login: OUTSIDER.login }); + assert.ok(denied.isError); + assert.match(denied.text, /только владелец/); + await assert.rejects(runner.unshareProject(db, member, proj, OWNER.login), /только владелец/); + await assert.rejects(runner.shareProject(db, owner, proj, OWNER.login), /владелец проекта/); + }); + + test("a login that never logged in gets an invitation, applied at first login", async () => { + const { proj } = await shared(); + const r = await runner.shareProject(db, owner, proj, GHOST.login); + assert.equal(r.status, "invited"); + assert.deepEqual((await core.listMembers(db, proj)).invites, [GHOST.login]); + const ghost = await core.upsertUserFromGitea(db, GHOST, { access_token: GHOST.token }); + assert.equal((await core.projectForUser(db, ghost.id, proj.id)).id, proj.id); + const team = await core.listMembers(db, proj); + assert.deepEqual(team.invites, []); + assert.deepEqual(team.members.map((m) => m.login), [GHOST.login]); + }); + + test("unknown Gitea login is refused and leaves nothing behind", async () => { + const { proj } = await shared(); + await assert.rejects(runner.shareProject(db, owner, proj, "mock-nobody"), /не найден в Gitea/); + const team = await core.listMembers(db, proj); + assert.deepEqual([team.members.length, team.invites.length], [0, 0]); + }); + + test("owner removes a member; a member can leave; invitations can be cancelled", async () => { + const { p, proj, repo } = await shared(); + await runner.shareProject(db, owner, proj, MEMBER.login); + await runner.unshareProject(db, owner, proj, MEMBER.login); + await assert.rejects(core.projectForUser(db, member.id, proj.id), /Не найдено/); + assert.equal(repo.collaborators[MEMBER.login], undefined, "collaborator removed"); + assert.ok((await (await mcpAs(member))("get_task", { task: `${p.key}-1` })).isError); + await assert.rejects(runner.unshareProject(db, owner, proj, MEMBER.login), /не участник/); + + await runner.shareProject(db, owner, proj, MEMBER.login); + await runner.unshareProject(db, member, proj, MEMBER.login); // leaves on their own + assert.deepEqual((await core.listMembers(db, proj)).members, []); + + gitea.addUser({ id: 56, login: "mock-later", token: "mock-token-later" }); + await runner.shareProject(db, owner, proj, "mock-later"); + await (await mcpAs(owner))("remove_member", { project: p.key, login: "mock-later" }); + assert.deepEqual((await core.listMembers(db, proj)).invites, []); + }); + + test("repo in peppa-bot's namespace: the bot grants access; no admin at all → member without repo access", async () => { + const viaBot = await shared([BOT.login]); + const r1 = await runner.shareProject(db, owner, viaBot.proj, MEMBER.login); + assert.equal(r1.repoAccess, true); + assert.equal(viaBot.repo.collaborators[MEMBER.login], "write"); + + const noAdmin = await shared(["someone-else"]); + const r2 = await runner.shareProject(db, owner, noAdmin.proj, MEMBER.login); + assert.deepEqual([r2.status, r2.repoAccess], ["added", false]); + assert.equal((await core.projectForUser(db, member.id, noAdmin.proj.id)).id, noAdmin.proj.id); + }); +}); -- 2.45.2 From 1fefaa2e831815aa93b1b6878597665bf9fb3250 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 22:54:27 +0500 Subject: [PATCH 006/554] =?UTF-8?q?PEP-51:=20Gherkin=20scenarios=20in=20sp?= =?UTF-8?q?ecs=20=E2=80=94=20shared=20rules=20and=20OpenSpec=20config?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - template/RULES.md: scenarios as GIVEN / WHEN / THEN / AND steps with an example, Scenario Outline, one WHEN, concrete values; loaded into every agent session of every project - rules.specs in the template's and Peppa's openspec/config.yaml (quoted: an unquoted ': ' made OpenSpec ignore the rules) - verified: openspec validate accepts GIVEN/AND and Scenario Outline, and the rules reach 'openspec instructions specs' Co-Authored-By: Claude --- .../.openspec.yaml | 3 ++ .../proposal.md | 29 +++++++++++++++++++ .../2026-11-12-pep-51-gherkin-specs/tasks.md | 7 +++++ openspec/config.yaml | 7 +++++ template/RULES.md | 25 ++++++++++++++++ template/openspec/config.yaml | 5 ++++ 6 files changed, 76 insertions(+) create mode 100644 openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/proposal.md create mode 100644 openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/tasks.md diff --git a/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/.openspec.yaml b/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/.openspec.yaml new file mode 100644 index 00000000..63992e5b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-12 +skip_specs: true diff --git a/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/proposal.md b/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/proposal.md new file mode 100644 index 00000000..15f1ce2b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/proposal.md @@ -0,0 +1,29 @@ +# Proposal: PEP-51 — сценарии спецификаций в формате Gherkin + +Задача Пеппы: **PEP-51**. + +## Why + +PM хочет, чтобы сценарии в спецификациях были в формате Gherkin (GIVEN / WHEN / THEN): +так их однозначно читать и по ним проще писать тесты. Сейчас агенты пишут WHEN/THEN без +исходного состояния и конкретных значений. + +## What Changes + +- Общие правила агентов (`template/RULES.md`, подгружаются в каждую сессию всех проектов): + раздел про Gherkin с примером, Scenario Outline и требованиями к шагам. +- `rules.specs` в `openspec/config.yaml` шаблона новых проектов и самой Пеппы. +- Проверено: `openspec validate` принимает GIVEN/AND и Scenario Outline. + +Существующие спецификации Пеппы не переписываются (см. PEP-50); конфиги уже созданных +проектов не меняются — на них действует правило из RULES.md. + +## Capabilities + +### New Capabilities + +### Modified Capabilities + +## Impact + +Только правила и конфигурация OpenSpec; кода и поведения системы не касается (`skip_specs`). diff --git a/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/tasks.md b/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/tasks.md new file mode 100644 index 00000000..a14b40e3 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-pep-51-gherkin-specs/tasks.md @@ -0,0 +1,7 @@ +# Tasks: PEP-51 + +## 1. Правила + +- [x] 1.1 Проверить в чистом проекте, что `openspec validate` принимает сценарии с GIVEN/AND и Scenario Outline +- [x] 1.2 Раздел про Gherkin в `template/RULES.md`; `rules.specs` в конфиге шаблона и Пеппы +- [x] 1.3 Залить шаблон в Gitea; `openspec validate` change проходит diff --git a/openspec/config.yaml b/openspec/config.yaml index e0e71363..34276f9f 100644 --- a/openspec/config.yaml +++ b/openspec/config.yaml @@ -5,3 +5,10 @@ context: | Claude Code сессий в tmux и Telegram-бот для PM. Всё работает локально на Mac; Git — self-hosted Gitea (git.telecom.quest), БД — Postgres в docker. Артефакты OpenSpec пиши на русском; код и идентификаторы — на английском. + +rules: + specs: + - "Сценарии — в формате Gherkin: шаги списком с жирными GIVEN / WHEN / THEN / AND / BUT, текст шагов на русском" + - "GIVEN обязателен, если результат зависит от состояния; один WHEN на сценарий; THEN — наблюдаемый снаружи результат с конкретными значениями" + - "Наборы данных — «#### Scenario Outline:» с <плейсхолдерами> и таблицей примеров" + - "У каждого требования минимум один успешный сценарий и один на ошибку или границу" diff --git a/template/RULES.md b/template/RULES.md index edb1b031..702a02fd 100644 --- a/template/RULES.md +++ b/template/RULES.md @@ -66,6 +66,31 @@ PM отвечает только на **архитектурные стоппе к ревью»: кнопка «Принять» закрывает задачу, текстом — замечания, их доделываешь. - Статус `done` ставит только PM. +## Спецификации — сценарии в формате Gherkin + +Требования в `specs/**/spec.md` пиши как раньше (`### Requirement:` + текст с SHALL), а +каждый сценарий — в Gherkin, чтобы его можно было проверить руками или превратить в тест: + +```markdown +#### Scenario: Успешный вход +- **GIVEN** зарегистрированный пользователь «anna» с паролем «s3cret» +- **AND** пользователь не заблокирован +- **WHEN** он вводит логин «anna» и пароль «s3cret» +- **THEN** открывается главная страница +- **AND** в шапке видно имя «anna» +``` + +- Ключевые слова — `GIVEN` (исходное состояние), `WHEN` (одно действие), `THEN` + (наблюдаемый результат), `AND` / `BUT` (продолжение предыдущего шага); жирным, по-английски. + Текст шагов — на языке проекта. +- `GIVEN` обязателен, если результат зависит от состояния; один `WHEN` на сценарий. +- Конкретные значения вместо «некоторые данные»; `THEN` — то, что видно снаружи + (экран, ответ API, запись), а не внутренности реализации. +- Несколько наборов данных — `#### Scenario Outline:` с плейсхолдерами `<имя>` и таблицей + примеров под шагами. +- У каждого требования — минимум один успешный сценарий и один на ошибку или границу. +- Тесты называй по сценариям, чтобы было видно, какой сценарий чем покрыт. + ## Когда спрашивать PM Только **стопперы**: то, что ты не вправе или не можешь решить сам. diff --git a/template/openspec/config.yaml b/template/openspec/config.yaml index 134bfdb1..f009d286 100644 --- a/template/openspec/config.yaml +++ b/template/openspec/config.yaml @@ -11,6 +11,11 @@ rules: - Начинай со ссылки на задачу Пеппы (PEP-42) и её цель - Явно перечисли, что вне scope - В конце — открытые вопросы к PM (или «нет») + specs: + - "Сценарии — в формате Gherkin: шаги списком с жирными GIVEN / WHEN / THEN / AND / BUT, текст шагов на русском" + - "GIVEN обязателен, если результат зависит от состояния; один WHEN на сценарий; THEN — наблюдаемый снаружи результат с конкретными значениями" + - "Наборы данных — «#### Scenario Outline:» с <плейсхолдерами> и таблицей примеров" + - "У каждого требования минимум один успешный сценарий и один на ошибку или границу" tasks: - Пункты по 30–120 минут работы, каждый проверяемый - Последний пункт — тесты/проверка и `openspec validate` -- 2.45.2 From 67f13848d323fd3490f7bf82ccf1ec0590408a52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Thu, 12 Nov 2026 23:05:45 +0500 Subject: [PATCH 007/554] Plans for PEP-56 (limit auto-resume), PEP-57 (CI/CD), PEP-58 (Bugsink) and handoff notes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenSpec changes with proposals, designs, Gherkin specs and task lists, ready for apply; docs/HANDOFF.md with the current state and agreed order. Planning only — no code changes. Co-Authored-By: Claude --- AGENTS.md | 2 + docs/HANDOFF.md | 46 ++++++++++ .../pep-56-limit-auto-resume/.openspec.yaml | 2 + .../pep-56-limit-auto-resume/design.md | 49 +++++++++++ .../pep-56-limit-auto-resume/proposal.md | 46 ++++++++++ .../specs/limit-recovery/spec.md | 87 +++++++++++++++++++ .../changes/pep-56-limit-auto-resume/tasks.md | 24 +++++ openspec/changes/pep-57-ci-cd/.openspec.yaml | 2 + openspec/changes/pep-57-ci-cd/design.md | 50 +++++++++++ openspec/changes/pep-57-ci-cd/proposal.md | 71 +++++++++++++++ .../specs/delivery-pipeline/spec.md | 84 ++++++++++++++++++ openspec/changes/pep-57-ci-cd/tasks.md | 36 ++++++++ .../changes/pep-58-bugsink/.openspec.yaml | 2 + openspec/changes/pep-58-bugsink/design.md | 65 ++++++++++++++ openspec/changes/pep-58-bugsink/proposal.md | 58 +++++++++++++ .../specs/error-tracking/spec.md | 80 +++++++++++++++++ openspec/changes/pep-58-bugsink/tasks.md | 32 +++++++ 17 files changed, 736 insertions(+) create mode 100644 docs/HANDOFF.md create mode 100644 openspec/changes/pep-56-limit-auto-resume/.openspec.yaml create mode 100644 openspec/changes/pep-56-limit-auto-resume/design.md create mode 100644 openspec/changes/pep-56-limit-auto-resume/proposal.md create mode 100644 openspec/changes/pep-56-limit-auto-resume/specs/limit-recovery/spec.md create mode 100644 openspec/changes/pep-56-limit-auto-resume/tasks.md create mode 100644 openspec/changes/pep-57-ci-cd/.openspec.yaml create mode 100644 openspec/changes/pep-57-ci-cd/design.md create mode 100644 openspec/changes/pep-57-ci-cd/proposal.md create mode 100644 openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md create mode 100644 openspec/changes/pep-57-ci-cd/tasks.md create mode 100644 openspec/changes/pep-58-bugsink/.openspec.yaml create mode 100644 openspec/changes/pep-58-bugsink/design.md create mode 100644 openspec/changes/pep-58-bugsink/proposal.md create mode 100644 openspec/changes/pep-58-bugsink/specs/error-tracking/spec.md create mode 100644 openspec/changes/pep-58-bugsink/tasks.md diff --git a/AGENTS.md b/AGENTS.md index da7064f9..36ff3710 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,6 +3,8 @@ Софтвейр-фабрика: долгие Claude Code сессии в tmux + вачдог + Telegram-бот для PM, проекты ведутся по OpenSpec. +Текущее состояние и порядок работ: `docs/HANDOFF.md`. + ## Структура - `apps/web` — Next.js платформа (порт 3100, https://peppa.telecom.quest): вход через Gitea OAuth2 (`/auth/start` → `/auth/callback`, подписанная cookie `peppa_session`), всё за входом через route group `(app)`; входящие, проект (цели → задачи), задача (артефакты OpenSpec из рабочей копии, вопросы, сессии), новый проект. Server actions в `app/(app)/actions.ts` — тонкие обёртки над core/runner с проверкой владельца. После правок: `next build` + `launchctl kickstart -k gui/$(id -u)/quest.telecom.peppa.web` - `apps/bot` — Telegram-бот (`peppa-bot`, launchd `quest.telecom.peppa.bot`): свой мини-клиент Bot API (`TELEGRAM_API_URL` для мока), long polling с сохранённым offset, `telegram_updates` фиксирует update до действия (без повторов после рестарта), durable outbox с ретраями (429 retry_after, 5xx), привязка только через `/start <код>` (`peppa telegram pair`), чужие чаты игнорируются. Отвечает только на конкретный вопрос (кнопки/реплай) и умеет resume/stop сессии из алерта diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md new file mode 100644 index 00000000..135300ef --- /dev/null +++ b/docs/HANDOFF.md @@ -0,0 +1,46 @@ +# Передача работ — состояние на 2026-11-12 + +Для агента, который продолжает работу над Пеппой. Источник правды по задачам — сама +Пеппа (`peppa task list PEP`, MCP `peppa`), правила — `AGENTS.md` и `template/RULES.md`. + +## Незаконченное + +- **PEP-2 (Telegram по пользователям)** — ветка `task/PEP-2`, один WIP-коммит: код написан, + тесты **не прогонялись**, на прод не выкачено. Миграция `0009` (поля Telegram у `users`) + уже применена к боевой БД — она аддитивная. Продолжить: прогнать e2e, выкатить бота и + веб, удалить настройку `telegram.binding` (старая общая привязка), попросить + пользователей привязаться в Настройках. +- **Живой Claude ни разу не прогонял задачу целиком** (PEP-3). Токены Claude у `asel` и + `7601978` подключены и проверены одним вызовом. Хуки, автопродолжение через Stop-хук, + вставка в TUI проверены только на `mock-claude`. + +## Порядок, согласованный с PM + +1. **PEP-16** — закрыть вход (регистрация в Gitea открыта, 11 тыс. аккаунтов; любой может + запустить агента на этом Mac). Критично, первым. +2. **PEP-2** — доделать. +3. **PEP-3** — живая сессия; снять реальные строки лимита для PEP-56. +4. **PEP-56** — авто-продолжение после сброса лимита. План готов: + `openspec/changes/pep-56-limit-auto-resume` (решения по умолчанию заданы, можно делать). +5. **PEP-57** — CI/CD. План: `openspec/changes/pep-57-ci-cd`. **Сначала** ответы PM на + «Решения PM» в proposal (архитектура) и сделанный PEP-16. +6. **PEP-58** — Bugsink. План: `openspec/changes/pep-58-bugsink`. Сначала «Решения PM» и + шаг 0.2 (что умеет установленная версия Bugsink). Замыкание с релизами — после PEP-57. + +Остальной бэклог (UI-пульт PEP-38, терминал раннера PEP-9, раннеры PEP-10, хосты PEP-40, +автономность PEP-23/24/25/26/27/28 и др.) — в Пеппе, по целям. + +## Договорённости + +- Всё через задачу `PEP-N` и OpenSpec change; сценарии — в Gherkin (PEP-51). +- PM одобряет только архитектурные решения; свои PR агент мержит сам после зелёного e2e. +- Термины: **раннер** — tmux-сессия с агентом (в коде пока `session`), **хост** — машина. +- Нет доступа к чему-то внешнему — делай мок с префиксом `mock`. + +## Осторожно + +- Бот, вачдог и веб запущены из этой рабочей копии: переключение ветки меняет код, + который подхватится при их перезапуске (PEP-18). Перед `launchctl kickstart` убедись, + что стоишь на `main`. +- После правок веба: `next build` в `apps/web` + перезапуск `quest.telecom.peppa.web`. +- e2e: `pnpm --filter @peppa/testkit test` (~2 минуты, 64 теста на main). diff --git a/openspec/changes/pep-56-limit-auto-resume/.openspec.yaml b/openspec/changes/pep-56-limit-auto-resume/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/pep-56-limit-auto-resume/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/pep-56-limit-auto-resume/design.md b/openspec/changes/pep-56-limit-auto-resume/design.md new file mode 100644 index 00000000..a880716e --- /dev/null +++ b/openspec/changes/pep-56-limit-auto-resume/design.md @@ -0,0 +1,49 @@ +# Design: PEP-56 + +## Context + +`hook.ts` на `StopFailure` с `error: "rate_limit"` ставит `rate_limited` и создаёт вопрос +`attention`; `watchdog.ts` ловит баннер лимита на экране (регулярка `LIMIT_RE`) для агентов +без хука (Codex). Перезапуск — `resumeSession` (новое поколение, `claude --resume` / +`codex resume`). Вачдог хранит хэши экранов в памяти процесса. + +## Decisions + +1. **Разбор времени сброса — чистая функция** `parseResetTime(text, now, tz): Date | null` + в `runner/src/limits.ts`. Источники по приоритету: `error_details` StopFailure → строка + баннера с экрана → окно лимита из statusLine (когда появится PEP-5). Форматы: + `resets 5pm`, `resets at 3:10 AM`, `reset at 15:00`, `resets in 2h 15m`, + `try again at 5:00 PM`, с часовым поясом в скобках и без (тогда пояс машины). + Время без даты — ближайшее будущее. Юнит-тесты на таблицу примеров; реальные строки + настоящего Claude добавить после PEP-3. +2. **Состояние в БД**, а не в памяти вачдога: `sessions.resume_at` (когда продолжать), + `limit_probe_at` (следующая проба, если время неизвестно), `limit_resumes` + дата — для + суточного лимита. Переживает рестарт вачдога. +3. **Продолжение — в `watchdog.tick`**: для `rate_limited`, если `now ≥ resume_at + запас` + или `now ≥ limit_probe_at`: + - панель tmux жива → `tmux.sendText(«Лимит сброшен. Продолжай работу над …»)`, + статус `running`; + - панель мертва или tmux нет → `resumeSession`. + Вопрос `attention` о лимите закрывается как системный («продолжено автоматически»), + событие `limit_resumed`, PM получает информационное сообщение (не вопрос). +4. **Повторный лимит**: если раннер снова получил лимит в течение 5 минут после + продолжения — время сброса считаем неизвестным, интервал пробы удваивается (до 2 ч). + Достигнут суточный предел — раннер остаётся `rate_limited`, PM получает обычный вопрос + с кнопкой «Перезапустить». +5. **Часы для тестов**: `tick(db, { now })` — тесты двигают время, а не ждут. +6. **Моки**: действие сценария `{ "limit": { "resetInSec": 3 } }` — баннер и + `error_details` с временем сброса; `{ "limit": { "reset": "unknown" } }` — без времени; + `{ "limit": { "again": 2 } }` — лимит повторяется N раз после продолжения. Мок в + «живом» режиме принимает сообщение «продолжай» и идёт к следующему ходу сценария. + +## Risks / Trade-offs + +- [Строки настоящего Claude отличаются от ожидаемых] → неизвестное время = пробы; после + PEP-3 добавить реальные примеры в таблицу тестов. +- [Продолжение жжёт лимит на бессмысленной задаче] → суточный предел; бюджет задач — PEP-43. +- [PM вручную ответил/перезапустил в тот же момент] → продолжение только из статуса + `rate_limited` с проверкой поколения; ручной ответ переводит в `running` раньше. + +## Migration Plan + +Миграция аддитивная. Перезапуск вачдога. Откат — `PEPPA_LIMIT_AUTORESUME=off`. diff --git a/openspec/changes/pep-56-limit-auto-resume/proposal.md b/openspec/changes/pep-56-limit-auto-resume/proposal.md new file mode 100644 index 00000000..1a080ec0 --- /dev/null +++ b/openspec/changes/pep-56-limit-auto-resume/proposal.md @@ -0,0 +1,46 @@ +# Proposal: PEP-56 — раннер сам продолжает работу после сброса лимита + +Задача Пеппы: **PEP-56** · Цель «Автономная фабрика». + +## Why + +Когда у Claude (или Codex) заканчивается лимит, раннер переходит в `rate_limited` и стоит, +пока человек не нажмёт «Перезапустить». Лимит сбрасывается ночью — фабрика простаивает до утра. + +## What Changes + +- Пеппа узнаёт **время сброса лимита** (из события StopFailure, из баннера на экране, из + данных statusLine, если есть) и сохраняет его у раннера. +- **Вачдог сам продолжает раннер** после сброса: если процесс агента жив — отправляет в + него «продолжай», если нет — перезапускает с продолжением разговора (`resume`). +- Если время сброса неизвестно — **пробные попытки** с растущим интервалом. +- Защита от зацикливания: не больше N авто-продолжений на раннер в сутки; повторный лимит + сразу после продолжения увеличивает интервал. +- PM получает не вопрос, а **информацию**: при лимите «остановлен, продолжит в 03:10», + после — «лимит сброшен, раннер продолжил». Кнопка «Перезапустить сейчас» остаётся. +- Настройка: включено по умолчанию; выключается переменной и (позже, PEP-23) на проект. +- Моки: `mock-claude` и `mock-codex` умеют «лимит со сбросом через N секунд»; вачдог + получает управляемые часы для тестов. + +Вне scope: переключение на другой аккаунт при лимите (PEP-39), бюджет задач (PEP-43). + +## Capabilities + +### New Capabilities +- `limit-recovery`: определение времени сброса лимита агента и автоматическое продолжение раннера. + +### Modified Capabilities + +## Impact + +`packages/db` (`sessions.resume_at`, `limit_resumes`, `limit_probe_at`), `packages/runner` +(`watchdog.ts`, `hook.ts`, новый `limits.ts` с разбором времени), `apps/bot` (текст +сообщения о лимите), `packages/testkit` (моки, тесты), `AGENTS.md`. + +## Решения (PM может поправить до старта; иначе берём значения по умолчанию) + +1. Живой процесс агента продолжаем сообщением в терминал, а не перезапуском — сохраняется + контекст и не тратится запуск. **По умолчанию: да.** +2. Лимит авто-продолжений: **6 в сутки на раннер**. +3. Неизвестное время сброса: пробы через **30 мин → 1 ч → 2 ч** (дальше каждые 2 ч). +4. Запас после времени сброса: **60 секунд**. diff --git a/openspec/changes/pep-56-limit-auto-resume/specs/limit-recovery/spec.md b/openspec/changes/pep-56-limit-auto-resume/specs/limit-recovery/spec.md new file mode 100644 index 00000000..3c5e5096 --- /dev/null +++ b/openspec/changes/pep-56-limit-auto-resume/specs/limit-recovery/spec.md @@ -0,0 +1,87 @@ +# Spec Delta: limit-recovery + +## Purpose + +Определяет, как Пеппа ведёт себя, когда у агента кончился лимит: узнаёт время сброса и сама продолжает раннер, не дожидаясь человека. + +## ADDED Requirements + +### Requirement: Время сброса лимита +Пеппа SHALL определять время сброса лимита из сообщения агента о лимите и сохранять его у раннера; если время определить нельзя, оно считается неизвестным. + +#### Scenario: Время сброса указано +- **GIVEN** раннер Claude работает над задачей в 22:40 +- **WHEN** агент останавливается с ошибкой лимита «Usage limit reached, resets 3:10 AM» +- **THEN** раннер получает статус `rate_limited` +- **AND** у раннера сохранено время продолжения — ближайшие 03:10 +- **AND** PM получает сообщение «остановлен по лимиту, продолжит в 03:10», а не вопрос + +#### Scenario Outline: Форматы времени сброса +- **GIVEN** сейчас 2026-11-12 22:40 по времени машины +- **WHEN** сообщение о лимите содержит «<текст>» +- **THEN** время сброса определено как «<время>» + +| текст | время | +|---|---| +| resets 5pm | 2026-11-13 17:00 | +| resets at 3:10 AM | 2026-11-13 03:10 | +| resets in 2h 15m | 2026-11-13 00:55 | +| try again at 23:30 | 2026-11-12 23:30 | +| limit reached | неизвестно | + +### Requirement: Автоматическое продолжение после сброса +Вачдог SHALL продолжать раннер в статусе `rate_limited`, когда время сброса (плюс запас 60 секунд) наступило: сообщением в живой процесс агента или перезапуском с продолжением разговора, если процесс завершён. + +#### Scenario: Процесс агента жив +- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10 и работающим процессом агента +- **WHEN** вачдог проверяет раннеры в 03:11 +- **THEN** агент получает сообщение продолжать работу над своей задачей +- **AND** раннер получает статус `running` в том же поколении +- **AND** вопрос о лимите закрыт как системный, PM получает «лимит сброшен, раннер продолжил» + +#### Scenario: Процесс агента завершён +- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10, процесс агента завершился +- **WHEN** вачдог проверяет раннеры в 03:11 +- **THEN** раннер перезапущен в новом поколении с продолжением прежнего разговора + +#### Scenario: Сброс ещё не наступил +- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10 +- **WHEN** вачдог проверяет раннеры в 02:50 +- **THEN** раннер остаётся `rate_limited`, агент ничего не получает + +### Requirement: Неизвестное время сброса +Если время сброса неизвестно, вачдог SHALL делать пробные продолжения через 30 минут, затем через 1 час, затем каждые 2 часа. + +#### Scenario: Проба удалась +- **GIVEN** раннер в статусе `rate_limited` без времени сброса, лимит уже сброшен +- **WHEN** проходит 30 минут и вачдог делает пробу +- **THEN** раннер продолжает работу + +#### Scenario: Лимит ещё действует +- **GIVEN** раннер в статусе `rate_limited` без времени сброса +- **WHEN** проба через 30 минут снова упирается в лимит +- **THEN** раннер остаётся `rate_limited` +- **AND** следующая проба назначена через 1 час +- **AND** PM не получает нового сообщения + +### Requirement: Защита от зацикливания +Пеппа SHALL выполнять не более 6 автоматических продолжений раннера за сутки; после этого раннер ждёт человека. + +#### Scenario: Предел достигнут +- **GIVEN** раннер за сутки уже 6 раз был продолжен автоматически +- **WHEN** он снова упирается в лимит +- **THEN** автоматических продолжений больше нет +- **AND** PM получает вопрос с действием «Перезапустить» + +#### Scenario: Человек вмешался раньше +- **GIVEN** раннер в статусе `rate_limited` со временем продолжения 03:10 +- **WHEN** PM в 01:00 нажимает «Перезапустить» и раннер продолжает работу +- **THEN** в 03:11 вачдог ничего не отправляет этому раннеру + +### Requirement: Отключение +Автоматическое продолжение SHALL отключаться настройкой; тогда поведение прежнее — раннер ждёт человека. + +#### Scenario: Выключено +- **GIVEN** автоматическое продолжение выключено +- **WHEN** наступает время сброса лимита +- **THEN** раннер остаётся `rate_limited`, у PM остаётся вопрос с «Перезапустить» diff --git a/openspec/changes/pep-56-limit-auto-resume/tasks.md b/openspec/changes/pep-56-limit-auto-resume/tasks.md new file mode 100644 index 00000000..12ea8a45 --- /dev/null +++ b/openspec/changes/pep-56-limit-auto-resume/tasks.md @@ -0,0 +1,24 @@ +# Tasks: PEP-56 + +## 1. Время сброса + +- [ ] 1.1 `runner/src/limits.ts`: `parseResetTime(text, now, tz)`; юнит-тест на таблицу форматов из спецификации (+ с часовым поясом, + «через полночь») +- [ ] 1.2 Миграция `sessions.resume_at`, `limit_probe_at`, `limit_resumes`, `limit_resumes_day`; хук `stop-failure` и ветка баннера в вачдоге сохраняют время сброса; сообщение PM «продолжит в HH:MM» (не вопрос, если автопродолжение включено) + +## 2. Продолжение + +- [ ] 2.1 `watchdog.tick(db, { now })`: продолжение `rate_limited` — сообщение в живую панель или `resumeSession`; закрытие вопроса о лимите, событие `limit_resumed`, информационное сообщение PM +- [ ] 2.2 Пробы при неизвестном времени (30 мин → 1 ч → 2 ч), удвоение после повторного лимита в течение 5 минут, суточный предел 6, `PEPPA_LIMIT_AUTORESUME=off` +- [ ] 2.3 Бот и веб: текст «остановлен по лимиту · продолжит в HH:MM» на раннере; кнопка «Перезапустить сейчас» работает как раньше + +## 3. Моки и тесты + +- [ ] 3.1 `mock-agent`: `limit` с `resetInSec`, `reset: "unknown"`, `again: N`; живой мок принимает «продолжай» и переходит к следующему ходу; то же для `mock-codex` (баннер без хука) +- [ ] 3.2 CJM (с управляемым `now`): каждый сценарий спецификации — отдельный тест с тем же названием; плюс Codex: баннер → проба → продолжение через `codex resume`; плюс рестарт вачдога между лимитом и сбросом (состояние в БД) +- [ ] 3.3 Тест бота: сообщение о лимите без кнопок-вопроса, затем «раннер продолжил»; при достигнутом пределе — вопрос с «Перезапустить» +- [ ] 3.4 Весь e2e-набор зелёный, `pnpm typecheck`, `openspec validate pep-56-limit-auto-resume` + +## 4. Выкатка + +- [ ] 4.1 Миграция на проде, перезапуск вачдога и бота; проверка на dev-стенде (`peppa-dev`): мок-раннер с лимитом на 20 секунд продолжает сам, в чате тестового PM два информационных сообщения +- [ ] 4.2 AGENTS.md: раздел про лимиты; заметка в PEP-3 — снять реальные строки лимита настоящего Claude и добавить в таблицу тестов diff --git a/openspec/changes/pep-57-ci-cd/.openspec.yaml b/openspec/changes/pep-57-ci-cd/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/pep-57-ci-cd/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/pep-57-ci-cd/design.md b/openspec/changes/pep-57-ci-cd/design.md new file mode 100644 index 00000000..d7b83f18 --- /dev/null +++ b/openspec/changes/pep-57-ci-cd/design.md @@ -0,0 +1,50 @@ +# Design: PEP-57 + +## Context + +Gitea 1.22 на `git.telecom.quest`, Actions в конфиге явно не настроены, `act_runner` не +запущен. Traefik на хосте маршрутизирует по файлам в `dynamic/` и по docker-меткам. Агент +открывает PR от имени `peppa-bot`. Гейтов нет: `acceptTask` ставит `done` без мержа (PEP-25). + +## Decisions + +1. **Контракт проекта — `.peppa/project.json`**: + ```json + { "checks": { "lint": "pnpm lint", "typecheck": "pnpm typecheck", "test": "pnpm test", "build": "pnpm build" }, + "deploy": { "compose": "deploy/compose.yml", "service": "web", "port": 3000, "health": "/healthz", "migrate": "pnpm db:migrate" } } + ``` + Workflow из шаблона читает эти команды (`jq`), поэтому менять CI под стек не нужно — + агент заполняет файл при первой задаче проекта. Отсутствующая команда = шаг пропущен. +2. **Статусы в Пеппу — через вебхуки Gitea** (`pull_request`, `status`/`workflow_run`, + `push`) на `POST /api/hooks/gitea` с подписью секретом проекта; запасной путь — опрос + `GET /repos/{o}/{r}/commits/{sha}/status` вачдогом раз в минуту для PR задач в работе. + Таблица `check_runs` (задача, SHA, шаг, статус, ссылка на лог, время). +3. **Возврат агенту**: красный CI при живом раннере → сообщение в раннер с именем шага и + хвостом лога (до 200 строк, через API логов Actions); раннера нет → задача из «Ревью» + возвращается в «В работе» и диспетчер запускает раннер. Счётчик попыток на задачу — 3. +4. **Гейты** в `moveTask`/`acceptTask`/автомерже: зелёный последний `check_run` по головному + SHA PR, нет конфликтов. Проект без `checks` — гейт выключен, в карточке «проверки не настроены». +5. **Деплой — `docker compose -p -`** с переменными `IMAGE`, `HOST`; + Traefik-метки в `deploy/compose.yml` шаблона. Образ тегируется SHA, хранится локально на + хосте (реестр Gitea — позже). Откат = `compose up` с предыдущим тегом из `releases`. + Preview удаляется при закрытии PR. +6. **Релиз** = строка `releases` (project, env, sha, previous_sha, tasks[], status: + deploying|healthy|rolled_back|failed, deployed_by). Прод-деплой из веба/Telegram/MCP — + это `workflow_dispatch` в Gitea от имени `peppa-bot`. +7. **Секреты** деплоя — секреты Actions репозитория, Пеппа записывает их из Vault (PEP-54); + до Vault — вручную в Gitea, в плане отмечено. + +## Risks / Trade-offs + +- [docker.sock в CI = полный доступ к хосту] → только после PEP-16; runner с меткой + `peppa-trusted`, workflows принимаются только из веток репозиториев проектов, форки и + внешние PR не запускаются. Целевое решение — отдельный хост (PEP-40). +- [Агент «чинит» CI, отключая тесты] → изменение `checks` и workflow-файлов попадает в + PR-описание отдельным пунктом и требует ревью PM даже в авто-режиме. +- [Mac — и прод, и сборка] → лимит одновременных job = 2, очистка образов старше 14 дней. + +## Migration Plan + +1. act_runner + включение Actions; 2. шаблон и проект-образец (SBX) проходят CI; +3. вебхуки и гейты; 4. staging/preview; 5. прод и откат; 6. перевод самой Пеппы. +Существующие проекты получают workflow отдельным PR от Пеппы («подключить CI»). diff --git a/openspec/changes/pep-57-ci-cd/proposal.md b/openspec/changes/pep-57-ci-cd/proposal.md new file mode 100644 index 00000000..420d8751 --- /dev/null +++ b/openspec/changes/pep-57-ci-cd/proposal.md @@ -0,0 +1,71 @@ +# Proposal: PEP-57 — CI/CD для проектов фабрики + +Задача Пеппы: **PEP-57** · Цель «Автономная фабрика». + +## Why + +Сейчас цикл разработки обрывается на «агент открыл PR»: никто не проверяет код +автоматически, «Принять» не мержит, ничего не выкатывается. Чтобы фабрика доводила +задачу до работающего продукта, нужен конвейер от PR до прода с обратной связью агенту. + +## Цикл, который должен получиться + +``` +цель → задача → раннер (OpenSpec, код, тесты) → PR + → CI: lint · typecheck · test · build ── красное → обратно агенту (до 3 раз) + → ревью (PM или авто по настройкам проекта) + → мерж в main + → CD: сборка образа → стенд (preview/staging) → smoke-проверка + → прод (кнопка PM или авто) → проверка здоровья → при сбое авто-откат + → Bugsink следит за ошибками релиза (PEP-58) → инцидент → новая задача +``` + +## What Changes + +- **CI**: Gitea Actions. В шаблон проекта добавляется `.gitea/workflows/ci.yml`; на хосте + Пеппы поднимается `act_runner`. Команды проверок проект описывает в + `.peppa/project.json` (`checks`: lint, typecheck, test, build) — один источник и для CI, + и для агента перед PR. +- **Обратная связь**: Пеппа получает статусы проверок PR (вебхук Gitea, PEP-46 делает + общую часть) и показывает их в карточке задачи. Красная проверка возвращает задачу + раннеру с логом упавшего шага — до 3 попыток, потом вопрос PM. +- **Гейт**: в «Ревью» задача попадает только с зелёным CI; мерж (ручной «Принять» или + авто) возможен только при зелёном CI и без конфликтов. +- **CD**: `.gitea/workflows/deploy.yml`: сборка Docker-образа с тегом = SHA, деплой + `docker compose` за Traefik. Окружения: `preview` на PR + (`pr-..preview.telecom.quest`), `staging` на мерж в main, `prod` — по кнопке PM + или автоматически (настройка проекта). Smoke-проверка `/healthz` после деплоя, при + провале — откат на предыдущий образ и сообщение PM. +- **Релизы**: каждому деплою — запись в Пеппе (проект, окружение, SHA, задачи в релизе, + кто выкатил, результат); из неё Bugsink получает имя релиза (PEP-58). +- **Пеппа сама** переводится на этот же конвейер (закрывает PEP-22 и PEP-18). + +Вне scope: Kubernetes, несколько хостов деплоя (после PEP-40), миграции БД проектов +сложнее «выполнить команду из `deploy.migrate`». + +## Capabilities + +### New Capabilities +- `delivery-pipeline`: проверки на PR, гейты ревью и мержа, деплой по окружениям, проверка здоровья и откат, учёт релизов. + +### Modified Capabilities + +## Impact + +`template/` (workflows, `.peppa/project.json`, Dockerfile-заготовки, раздел в AGENTS.md и +RULES.md), `infra/` (act_runner, сеть Traefik для стендов), `packages/db` (`releases`, +`check_runs`), `packages/core`/`runner` (приём статусов, возврат агенту, гейты в +`moveTask`/`acceptTask`), `apps/web` (вкладки Tests и Merge request из PEP-32, блок +«Релизы»), `packages/mcp` (статус проверок и релизов), testkit (mock-gitea: статусы и вебхуки). + +## Решения PM (архитектурные — нужны до старта; в скобках рекомендация) + +1. **Движок CI**: Gitea Actions + act_runner (**рекомендую** — стандартно, workflow лежит + в репозитории) или проверки запускает сама Пеппа на хосте раннера (проще, но не + переносимо). +2. **Где деплоятся проекты**: на этом Mac за Traefik (**рекомендую для старта**) или на + отдельном сервере (тогда после PEP-40). +3. **Доступ CI к Docker**: act_runner с доступом к docker.sock хоста (**просто, но это + root-доступ к хосту для любого workflow** — допустимо только после PEP-16 и только для + репозиториев проектов Пеппы) или отдельная VM/сервер для сборок. +4. **Прод по умолчанию**: по кнопке PM (**рекомендую**), авто — включается на проект (PEP-23). diff --git a/openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md b/openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md new file mode 100644 index 00000000..629e482e --- /dev/null +++ b/openspec/changes/pep-57-ci-cd/specs/delivery-pipeline/spec.md @@ -0,0 +1,84 @@ +# Spec Delta: delivery-pipeline + +## Purpose + +Описывает путь изменения от PR агента до работающего продукта: автоматические проверки, условия ревью и мержа, деплой по окружениям, проверку здоровья и откат. + +## ADDED Requirements + +### Requirement: Проверки на каждый PR +Для каждого PR проекта с настроенными проверками SHALL автоматически выполняться lint, typecheck, test и build, а их результат — отображаться в карточке задачи. + +#### Scenario: Зелёные проверки +- **GIVEN** проект «PAY» с настроенными командами проверок и задача PAY-7 в работе +- **WHEN** раннер открывает PR по задаче PAY-7 и все проверки проходят +- **THEN** в карточке PAY-7 видно «Проверки: 4 из 4 пройдены» со ссылкой на прогон + +#### Scenario: Проверки не настроены +- **GIVEN** проект без команд проверок +- **WHEN** раннер открывает PR +- **THEN** в карточке задачи видно «проверки не настроены», а переход в «Ревью» не блокируется + +### Requirement: Красные проверки возвращаются агенту +Проваленная проверка SHALL возвращать задачу раннеру с названием шага и фрагментом лога; после 3 неудачных попыток подряд Пеппа SHALL спросить PM. + +#### Scenario: Агент чинит сам +- **GIVEN** PR задачи PAY-7 с проваленным шагом «test» и работающим раннером +- **WHEN** Пеппа получает результат проверки +- **THEN** раннер получает сообщение с шагом «test» и последними строками лога +- **AND** задача остаётся в «В работе», PM ничего не получает + +#### Scenario: Три неудачи подряд +- **GIVEN** проверки PR задачи PAY-7 провалились 3 раза подряд после исправлений агента +- **WHEN** приходит третий красный результат +- **THEN** PM получает вопрос по задаче PAY-7 со ссылкой на лог +- **AND** раннер ждёт ответа + +### Requirement: Гейт ревью и мержа +Задача SHALL попадать в «Ревью», а её PR — мержиться (вручную или автоматически) только при зелёных проверках последнего коммита и отсутствии конфликтов. + +#### Scenario: Мерж при красных проверках +- **GIVEN** PR задачи PAY-7 с проваленной проверкой последнего коммита +- **WHEN** PM нажимает «Принять» +- **THEN** мерж не выполняется +- **AND** PM видит причину «проверки не пройдены» + +#### Scenario: Приёмка +- **GIVEN** PR задачи PAY-7 с зелёными проверками и без конфликтов +- **WHEN** PM нажимает «Принять» +- **THEN** PR смержен в основную ветку +- **AND** задача PAY-7 в «Готово» + +### Requirement: Деплой по окружениям +Мерж в основную ветку SHALL выкатывать проект на staging; прод SHALL выкатываться по действию PM или автоматически, если это включено в настройках проекта; для открытого PR SHALL быть доступен preview-стенд. + +#### Scenario: Staging после мержа +- **GIVEN** проект «PAY» с настроенным деплоем +- **WHEN** PR задачи PAY-7 смержен +- **THEN** собран образ с тегом коммита и выкачен на staging +- **AND** в Пеппе появился релиз staging со списком задач «PAY-7» + +#### Scenario: Прод по кнопке +- **GIVEN** здоровый релиз на staging и ручной режим прода +- **WHEN** PM нажимает «Выкатить в прод» +- **THEN** тот же образ выкачен в прод +- **AND** релиз прода записан с автором «PM» + +### Requirement: Проверка здоровья и откат +После каждого деплоя SHALL выполняться проверка здоровья; при провале окружение SHALL возвращаться к предыдущему релизу, а PM — получать сообщение. + +#### Scenario: Неудачный релиз +- **GIVEN** в проде работает релиз «a1b2c3» +- **WHEN** выкачен релиз «d4e5f6» и проверка `/healthz` не проходит за 2 минуты +- **THEN** прод возвращён на «a1b2c3» +- **AND** релиз «d4e5f6» помечен «откат» +- **AND** PM получает сообщение с причиной и ссылкой на лог + +### Requirement: Изменение конвейера требует ревью +Изменения файлов конвейера и команд проверок в PR агента SHALL явно показываться PM и не мержиться автоматически. + +#### Scenario: Агент отключил тесты +- **GIVEN** проект в автоматическом режиме мержа +- **WHEN** PR агента меняет команду «test» в настройках проверок +- **THEN** PR не мержится автоматически +- **AND** PM получает вопрос с описанием изменения конвейера diff --git a/openspec/changes/pep-57-ci-cd/tasks.md b/openspec/changes/pep-57-ci-cd/tasks.md new file mode 100644 index 00000000..43f59de1 --- /dev/null +++ b/openspec/changes/pep-57-ci-cd/tasks.md @@ -0,0 +1,36 @@ +# Tasks: PEP-57 + +Порядок — по этапам; каждый этап выкатывается и проверяется отдельно (можно отдельными PR). + +## 0. Перед стартом + +- [ ] 0.1 Получить ответы PM на «Решения PM» в proposal (request_approval — это архитектурные решения); убедиться, что PEP-16 (закрытый вход) сделан — без него этап 1 не начинать + +## 1. CI + +- [ ] 1.1 `infra/`: act_runner в docker (метка `peppa-trusted`), включить Actions в Gitea; проверка: тестовый workflow в `peppa-bot/sandbox` зелёный +- [ ] 1.2 Шаблон: `.gitea/workflows/ci.yml` (читает `checks` из `.peppa/project.json`), поля `checks`/`deploy` в project.json, раздел в RULES.md «перед PR запусти checks локально»; залить шаблон +- [ ] 1.3 Команда «подключить CI к существующему проекту» (PR от Пеппы); применить к SBX + +## 2. Обратная связь и гейты + +- [ ] 2.1 `check_runs` + приём статусов: вебхук Gitea с подписью (общая часть с PEP-46) и опрос статуса как запасной путь; mock-gitea: статусы коммитов и вебхуки +- [ ] 2.2 Возврат красного CI раннеру (шаг + хвост лога), счётчик 3 попыток, вопрос PM; гейты в `moveTask`/`acceptTask`; правило «изменение конвейера требует ревью» +- [ ] 2.3 Веб: проверки в карточке задачи (вкладка Tests из PEP-32 или блок до неё); MCP `get_task` показывает статус проверок +- [ ] 2.4 Тесты: по одному на каждый сценарий спецификации разделов «Проверки», «Красные проверки», «Гейт» + +## 3. CD + +- [ ] 3.1 Шаблон: `Dockerfile`-заготовки (node, python), `deploy/compose.yml` с метками Traefik, `deploy.yml` (build → staging → smoke); `releases` в БД +- [ ] 3.2 Preview на PR и удаление при закрытии; staging на мерж; прод по кнопке (веб, Telegram, MCP `deploy`) через `workflow_dispatch` +- [ ] 3.3 Проверка здоровья и авто-откат; блок «Релизы» на странице проекта; сообщения PM +- [ ] 3.4 Тесты сценариев «Деплой» и «Откат» (деплой — на моке: compose-команда подменяется mock-скриптом) + +## 4. Пеппа на собственном конвейере + +- [ ] 4.1 CI Пеппы: typecheck, build, e2e (закрывает PEP-22) +- [ ] 4.2 CD Пеппы: релизный checkout вместо рабочей копии, миграции, перезапуск сервисов, health, откат (закрывает PEP-18) + +## 5. Завершение + +- [ ] 5.1 Помощь в вебе: раздел «CI/CD»; AGENTS.md; `openspec validate pep-57-ci-cd`; весь e2e-набор зелёный diff --git a/openspec/changes/pep-58-bugsink/.openspec.yaml b/openspec/changes/pep-58-bugsink/.openspec.yaml new file mode 100644 index 00000000..55ab199b --- /dev/null +++ b/openspec/changes/pep-58-bugsink/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-12 diff --git a/openspec/changes/pep-58-bugsink/design.md b/openspec/changes/pep-58-bugsink/design.md new file mode 100644 index 00000000..090845fc --- /dev/null +++ b/openspec/changes/pep-58-bugsink/design.md @@ -0,0 +1,65 @@ +# Design: PEP-58 + +## Context + +Bugsink принимает события по протоколу Sentry (DSN, SDK Sentry без изменений), группирует +их в issues, показывает стек. На хосте Bugsink не установлен. Пеппа уже умеет: задачи и +цели, MCP для агентов (stdio) и PM (HTTP), вебхуки пока не принимает (появятся с PEP-46/57), +релизы появятся с PEP-57. + +**Что нужно проверить первым шагом (версия Bugsink меняется быстро):** +какой способ интеграции доступен в устанавливаемой версии — +(а) REST API с токеном (список issues, события, смена статуса, создание проектов), +(б) исходящие уведомления (webhook/Slack-совместимые алерты) о новой и вернувшейся ошибке. +Дизайн не зависит от ответа: всё идёт через адаптер с двумя входами. + +## Decisions + +1. **Адаптер `packages/bugsink`** с интерфейсом: + `listIssues(project, since)`, `getIssue(id)` (стек, теги, счётчики, последние события), + `resolveIssue(id, release)`, `createProject(name) → dsn`; и `parseWebhook(body)`. + Что версия Bugsink не умеет через API — делается запасным путём: опрос вместо вебхука; + ручной ввод DSN в настройках проекта вместо `createProject`; ссылка «закрыть в Bugsink» + вместо `resolveIssue`. В задаче явно фиксируется, что пошло запасным путём. +2. **Два входа, одна обработка `ingestIssue`**: вебхук + `POST /api/hooks/bugsink/<секрет проекта>` (мгновенно) и опрос раз в 2 минуты + (вачдог/диспетчер) — на случай потерянного вебхука. Идемпотентность по + `(bugsink_project, issue_id, last_seen)`. +3. **Модель**: `incidents` — project_id, source (`web`|`api`), bugsink_issue_id, + fingerprint, title, culprit (файл/функция), level, environment, first_release, + last_release, events, users, first_seen, last_seen, status + (`new`|`task_created`|`ignored`|`resolved`|`regressed`), task_id. + В `projects`: настройки Bugsink (id проектов, DSN, секрет вебхука) и правила. +4. **Правила проекта** (значения по умолчанию из «Решений PM»): окружения (`prod`), + порог, действие (`notify`|`task`|`task_and_start`), лимит задач в сутки (5), + игнор по шаблону названия. Отдельная цель «Стабильность» создаётся в проекте при + подключении — задачи-баги попадают под неё. +5. **Задача-баг**: название `Ошибка: <тип>: <сообщение> ()`, описание — где и + когда, релиз, частота, верх стека (до 30 строк), ссылка на Bugsink, «Условия + готовности»: воспроизводящий тест, исправление, ошибка не повторяется в новом релизе. + Повторные события той же ошибки задачу не плодят — обновляют счётчики инцидента. +6. **Для агента** (stdio MCP): `list_incidents(status?)`, `get_incident(id)`; в + `get_task` задачи-бага — блок «Инцидент» с верхом стека. В RULES.md: как чинить + баг из инцидента (сначала тест, воспроизводящий стек) и как подключать SDK в новом + проекте (фронт: `@sentry/browser` или SDK фреймворка; бэк: SDK языка; DSN только из + окружения: `SENTRY_DSN`, `NEXT_PUBLIC_SENTRY_DSN`; `release`, `environment`). +7. **Замыкание с релизами (PEP-57)**: релиз прода со списком задач → для задач-багов + `resolveIssue(issue, release)` и инцидент `resolved`. Событие той же ошибки в релизе + новее → `regressed`: задача возвращается в бэклог (или новая, если старая закрыта + больше 14 дней назад), PM получает уведомление. +8. **DSN фронта публичен по природе**; секрет вебхука и API-токен Bugsink — в `.env` + Пеппы (позже Vault, PEP-54). Вебхук без верного секрета — 404. + +## Risks / Trade-offs + +- [Поток ошибок завалит бэклог] → склейка, порог, лимит 5 задач/сутки, остальное — + инциденты без задач и одна сводка PM. +- [API Bugsink неполный] → запасные пути из п.1; интеграция не блокируется. +- [Stack trace минифицирован] → загрузка source maps в CD (PEP-57), иначе агент чинит вслепую. +- [Ошибки из preview/staging шумят] → по умолчанию задачи только из `prod`. + +## Migration Plan + +1. Bugsink в docker + маршрут; 2. адаптер и mock-bugsink; 3. инциденты и правила; +4. подключение SBX как образца (фронт+бэк, искусственная ошибка проходит весь путь); +5. замыкание с релизами — после PEP-57 (до неё — ручное закрытие). diff --git a/openspec/changes/pep-58-bugsink/proposal.md b/openspec/changes/pep-58-bugsink/proposal.md new file mode 100644 index 00000000..9dd19372 --- /dev/null +++ b/openspec/changes/pep-58-bugsink/proposal.md @@ -0,0 +1,58 @@ +# Proposal: PEP-58 — Bugsink: ошибки фронта и бэка становятся задачами Пеппы + +Задача Пеппы: **PEP-58** · Цель «Автономная фабрика». + +## Why + +После деплоя фабрика «слепа»: если в проде падает фронт или бэк, об этом узнают от +пользователей. Чтобы цикл разработки замыкался, ошибки из работающего продукта должны +сами приходить в Пеппу, превращаться в задачи и чиниться агентами. + +## What Changes + +- **Bugsink** (self-hosted трекер ошибок, совместимый с SDK Sentry) поднимается рядом с + Пеппой: `bugsink.telecom.quest`, docker за Traefik. +- **Проект Пеппы ↔ проекты Bugsink**: при подключении создаются два источника — `web` + (фронт) и `api` (бэк); их DSN хранятся в настройках проекта. +- **SDK в коде проектов**: шаблон и правила агентов описывают, как подключить Sentry SDK на + фронте и бэке (DSN из переменных окружения, `release` = SHA деплоя, `environment`), + конвейер CI/CD (PEP-57) передаёт эти переменные и загружает source maps. +- **Инциденты в Пеппе**: новые и вернувшиеся (regression) ошибки попадают в Пеппу как + инциденты проекта; по правилам проекта из инцидента создаётся задача-баг в бэклоге с + описанием, стеком и ссылкой. +- **Агент видит ошибку**: MCP-инструменты `list_incidents` и `get_incident` (стек, частота, + релиз, окружение, последние события) — у раннера, чинящего баг, есть всё нужное. +- **Замыкание**: когда задача-баг принята и её релиз выкачен, ошибка в Bugsink помечается + исправленной в этом релизе; если она повторится в более новом релизе — инцидент + открывается заново и задача возвращается. +- **Защита от шума**: порог (сколько событий/пользователей), только выбранные окружения, + список игнорируемых, не больше N задач в сутки, склейка по отпечатку ошибки. +- Веб: раздел «Ошибки» на странице проекта; уведомление PM о новой ошибке в проде. + +Вне scope: производительность/трейсинг, алерты по метрикам, сессии пользователей. + +## Capabilities + +### New Capabilities +- `error-tracking`: приём ошибок работающих продуктов из Bugsink, инциденты, задачи-баги и закрытие ошибок после исправления. + +### Modified Capabilities + +## Impact + +`infra/` (Bugsink в docker, маршрут Traefik), `packages/db` (`incidents`, поля Bugsink в +проекте), `packages/core` (инциденты, правила), новый адаптер `packages/bugsink` (клиент +API + приём вебхуков), `apps/web` (маршрут `/api/hooks/bugsink/...`, раздел «Ошибки», +настройки), `packages/mcp` (инструменты для агентов и PM), `template/` (RULES.md: как +подключать SDK; сниппеты), testkit (`mock-bugsink`). + +## Решения PM (архитектурные — до старта; в скобках рекомендация) + +1. **Новый сервис Bugsink на этом Mac** (**да**; ~300 МБ памяти, своя БД — SQLite или + Postgres Пеппы отдельной базой). +2. **Что делать с новой ошибкой прода по умолчанию**: только уведомить / создать задачу в + бэклог (**рекомендую**) / создать и сразу взять в работу (включается на проект, PEP-23). +3. **Порог создания задачи**: любая новая ошибка в `prod` (**рекомендую для старта**) или + от N событий за час. +4. **Данные пользователей в ошибках**: SDK по умолчанию без персональных данных + (`sendDefaultPii: false`), **да**. diff --git a/openspec/changes/pep-58-bugsink/specs/error-tracking/spec.md b/openspec/changes/pep-58-bugsink/specs/error-tracking/spec.md new file mode 100644 index 00000000..275fb5ad --- /dev/null +++ b/openspec/changes/pep-58-bugsink/specs/error-tracking/spec.md @@ -0,0 +1,80 @@ +# Spec Delta: error-tracking + +## Purpose + +Описывает, как ошибки работающих продуктов (фронт и бэк) попадают из Bugsink в Пеппу, становятся инцидентами и задачами и закрываются после исправления. + +## ADDED Requirements + +### Requirement: Подключение проекта к Bugsink +Владелец проекта SHALL подключать проект к Bugsink из настроек проекта; после подключения у проекта есть отдельные источники для фронта и бэка с их DSN и цель «Стабильность». + +#### Scenario: Подключение +- **GIVEN** проект «PAY» без подключения к Bugsink +- **WHEN** владелец нажимает «Подключить отслеживание ошибок» +- **THEN** в настройках проекта показаны DSN для фронта и для бэка +- **AND** в проекте есть открытая цель «Стабильность» + +### Requirement: Новая ошибка становится инцидентом +Новая ошибка из подключённого проекта SHALL появляться в Пеппе как инцидент с названием, местом возникновения, окружением, релизом и счётчиком событий; повторные события той же ошибки SHALL обновлять тот же инцидент. + +#### Scenario: Первая ошибка в проде +- **GIVEN** проект «PAY», подключённый к Bugsink, без инцидентов +- **WHEN** бэк в окружении «prod» релиза «a1b2c3» присылает ошибку «TypeError: amount is undefined» в «billing/charge.ts» +- **THEN** в разделе «Ошибки» проекта появляется инцидент «TypeError: amount is undefined» с источником «api», окружением «prod», релизом «a1b2c3» и счётчиком 1 + +#### Scenario: Та же ошибка повторилась +- **GIVEN** инцидент «TypeError: amount is undefined» со счётчиком 1 +- **WHEN** та же ошибка приходит ещё 4 раза +- **THEN** инцидент один, его счётчик равен 5 +- **AND** новых задач не создано + +#### Scenario: Запрос с неверным секретом +- **GIVEN** проект «PAY», подключённый к Bugsink +- **WHEN** на адрес приёма ошибок приходит запрос с неверным секретом +- **THEN** запрос отклонён, инцидентов не прибавилось + +### Requirement: Из инцидента создаётся задача +По правилам проекта Пеппа SHALL создавать из инцидента задачу в бэклоге под целью «Стабильность» с описанием ошибки, стеком, ссылкой на Bugsink и условиями готовности, и уведомлять PM. + +#### Scenario: Правило «создавать задачу» +- **GIVEN** проект «PAY» с правилом «новая ошибка в prod → задача» +- **WHEN** появляется инцидент «TypeError: amount is undefined» в «prod» +- **THEN** в бэклоге появляется задача «Ошибка: TypeError: amount is undefined (billing/charge.ts)» под целью «Стабильность» +- **AND** в описании задачи есть верх стека и ссылка на ошибку в Bugsink +- **AND** PM получает уведомление о новой ошибке со ссылкой на задачу + +#### Scenario: Ошибка не из прода +- **GIVEN** проект «PAY» с правилом «новая ошибка в prod → задача» +- **WHEN** появляется инцидент в окружении «staging» +- **THEN** инцидент виден в разделе «Ошибки», задача не создаётся + +#### Scenario: Суточный предел задач +- **GIVEN** проект «PAY», в котором сегодня уже создано 5 задач из инцидентов +- **WHEN** появляется шестой новый инцидент в «prod» +- **THEN** задача не создаётся +- **AND** инцидент помечен «ждёт разбора» + +### Requirement: Агент видит ошибку +Раннер, работающий над задачей из инцидента, SHALL получать через MCP сведения об ошибке: стек, частоту, релиз, окружение и последние события. + +#### Scenario: Агент берёт задачу-баг +- **GIVEN** задача PAY-12, созданная из инцидента «TypeError: amount is undefined» +- **WHEN** раннер запрашивает задачу PAY-12 +- **THEN** в ответе есть блок «Инцидент» с верхом стека, релизом «a1b2c3» и числом событий + +### Requirement: Закрытие после исправления и возврат при повторе +Когда задача из инцидента принята и её релиз выкачен в окружение инцидента, Пеппа SHALL пометить ошибку исправленной в этом релизе; если та же ошибка приходит из более нового релиза, инцидент SHALL открыться заново, а задача — вернуться в бэклог. + +#### Scenario: Исправление выкачено +- **GIVEN** задача PAY-12 из инцидента принята и входит в релиз «d4e5f6» +- **WHEN** релиз «d4e5f6» выкачен в «prod» и здоров +- **THEN** инцидент помечен «исправлен в d4e5f6» +- **AND** ошибка в Bugsink помечена исправленной + +#### Scenario: Ошибка вернулась +- **GIVEN** инцидент, помеченный «исправлен в d4e5f6», и закрытая задача PAY-12 +- **WHEN** та же ошибка приходит из релиза «g7h8i9», который новее «d4e5f6» +- **THEN** инцидент помечен «вернулась» +- **AND** задача PAY-12 снова в бэклоге с пометкой о повторе +- **AND** PM получает уведомление diff --git a/openspec/changes/pep-58-bugsink/tasks.md b/openspec/changes/pep-58-bugsink/tasks.md new file mode 100644 index 00000000..577cdb64 --- /dev/null +++ b/openspec/changes/pep-58-bugsink/tasks.md @@ -0,0 +1,32 @@ +# Tasks: PEP-58 + +## 0. Перед стартом + +- [ ] 0.1 Ответы PM на «Решения PM» (request_approval: новый сервис — архитектурное решение) +- [ ] 0.2 Поднять Bugsink локально в docker и записать в design.md, что умеет установленная версия: REST API (issues, события, resolve, создание проектов, токены) и исходящие вебхуки/алерты; выбрать основной и запасной пути адаптера + +## 1. Инфраструктура и адаптер + +- [ ] 1.1 `infra/`: Bugsink в docker compose, маршрут Traefik `bugsink.telecom.quest`, админ и API-токен в `.env`; проверка: тестовое событие через sentry-sdk видно в Bugsink +- [ ] 1.2 `packages/bugsink`: клиент (`listIssues`, `getIssue`, `resolveIssue`, `createProject`), `parseWebhook`; `mock-bugsink` в testkit (приём событий Sentry, issues, API, исходящий вебхук) + +## 2. Инциденты и задачи + +- [ ] 2.1 Миграция `incidents` и настройки Bugsink/правила в проекте; `ingestIssue` (идемпотентность, счётчики), правила (окружения, порог, действие, предел в сутки, игнор), создание задачи-бага под целью «Стабильность» +- [ ] 2.2 Вход 1: `POST /api/hooks/bugsink/<секрет>`; вход 2: опрос раз в 2 минуты; уведомление PM (Telegram, позже push) +- [ ] 2.3 Тесты: по одному на каждый сценарий требований «Новая ошибка становится инцидентом» и «Из инцидента создаётся задача» + +## 3. Интерфейсы + +- [ ] 3.1 Веб: «Подключить отслеживание ошибок» в настройках проекта (DSN фронта и бэка, правила), раздел «Ошибки» (список, статус, ссылка на задачу и Bugsink, «игнорировать», «создать задачу») +- [ ] 3.2 MCP: агентам `list_incidents`, `get_incident`, блок «Инцидент» в `get_task`; PM — `list_incidents`, `create_task_from_incident`, `ignore_incident`; Помощь в вебе +- [ ] 3.3 RULES.md и шаблон: подключение Sentry SDK на фронте и бэке (DSN из окружения, release, environment, без PII), как чинить задачу из инцидента (сначала воспроизводящий тест); залить шаблон + +## 4. Замыкание цикла + +- [ ] 4.1 Проект-образец SBX: фронт + бэк с SDK, искусственная ошибка в «prod» проходит путь ошибка → инцидент → задача → раннер (mock) видит стек +- [ ] 4.2 После PEP-57: релиз прода закрывает инциденты его задач (`resolveIssue`), повтор в новом релизе → «вернулась»; переменные DSN/release и source maps в CD; тесты сценариев «Закрытие» и «Вернулась» (до PEP-57 — ручная кнопка «исправлено» и пометка в задаче, что автоматика отложена) + +## 5. Завершение + +- [ ] 5.1 Весь e2e-набор зелёный, `pnpm typecheck`, `openspec validate pep-58-bugsink`; AGENTS.md; подключить Bugsink к самой Пеппе (веб, бот, вачдог) -- 2.45.2 From ead62e2c5f18fc72fe60597068009e06cc99a6eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Fri, 13 Nov 2026 03:24:08 +0500 Subject: [PATCH 008/554] PEP-59: version and commit in the web footer; plans for PEP-60, PEP-61 - root package.json carries the Peppa version (0.15.0); next.config.ts stamps version, short/full commit, commit date and a dirty flag at build - Footer on every app page and on the login page, commit linked to Gitea - OpenSpec: pep-59 archived (web-workspace); new planned changes pep-60-platform-channel-digest (Telegram channel of the platform, releases/restarts/digests, superadmin settings) and pep-61-top-menu (Home instead of Inbox, Runners and Projects pages) Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/layout.tsx | 2 + apps/web/app/globals.css | 2 + apps/web/app/login/page.tsx | 2 + apps/web/components/Footer.tsx | 25 +++++++++ apps/web/next.config.ts | 19 +++++++ .../.openspec.yaml | 2 + .../proposal.md | 25 +++++++++ .../specs/web-workspace/spec.md | 17 ++++++ .../2026-11-13-pep-59-build-footer/tasks.md | 5 ++ .../.openspec.yaml | 2 + .../proposal.md | 42 ++++++++++++++ .../specs/platform-notifications/spec.md | 56 +++++++++++++++++++ .../pep-60-platform-channel-digest/tasks.md | 16 ++++++ .../changes/pep-61-top-menu/.openspec.yaml | 2 + openspec/changes/pep-61-top-menu/proposal.md | 30 ++++++++++ .../specs/web-workspace/spec.md | 24 ++++++++ openspec/changes/pep-61-top-menu/tasks.md | 6 ++ openspec/specs/web-workspace/spec.md | 14 +++++ package.json | 1 + 19 files changed, 292 insertions(+) create mode 100644 apps/web/components/Footer.tsx create mode 100644 openspec/changes/archive/2026-11-13-pep-59-build-footer/.openspec.yaml create mode 100644 openspec/changes/archive/2026-11-13-pep-59-build-footer/proposal.md create mode 100644 openspec/changes/archive/2026-11-13-pep-59-build-footer/specs/web-workspace/spec.md create mode 100644 openspec/changes/archive/2026-11-13-pep-59-build-footer/tasks.md create mode 100644 openspec/changes/pep-60-platform-channel-digest/.openspec.yaml create mode 100644 openspec/changes/pep-60-platform-channel-digest/proposal.md create mode 100644 openspec/changes/pep-60-platform-channel-digest/specs/platform-notifications/spec.md create mode 100644 openspec/changes/pep-60-platform-channel-digest/tasks.md create mode 100644 openspec/changes/pep-61-top-menu/.openspec.yaml create mode 100644 openspec/changes/pep-61-top-menu/proposal.md create mode 100644 openspec/changes/pep-61-top-menu/specs/web-workspace/spec.md create mode 100644 openspec/changes/pep-61-top-menu/tasks.md diff --git a/apps/web/app/(app)/layout.tsx b/apps/web/app/(app)/layout.tsx index 435a0c55..f060b390 100644 --- a/apps/web/app/(app)/layout.tsx +++ b/apps/web/app/(app)/layout.tsx @@ -1,6 +1,7 @@ import Link from "next/link"; import type { ReactNode } from "react"; import { requireUser } from "@/lib/auth"; +import { Footer } from "@/components/Footer"; export const dynamic = "force-dynamic"; @@ -25,6 +26,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
    {children}
    +