peppa/packages/mcp/src/manager.ts

719 lines
45 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 {
createEpic,
describeAutonomy,
getAutonomy,
setAutonomy,
createTask,
getEpic,
updateEpic,
getProject,
getQuestion,
getTaskDetails,
listEpics,
listMembers,
listTasks,
listUserProjects,
PeppaError,
projectForUser,
listProjectSecrets,
repoAudience,
repoVisibilityLabel,
resolveTask,
updateTask,
userProjectIds,
getIncident,
getIncidentSettings,
incidentPolicies,
incidentStatuses,
listIncidents,
POLICY_RU,
updateIncidentSettings,
blockedLabel,
blockersMap,
epicProgress,
progressLabel,
setDependencies,
type User,
accountUsageForUser,
describeAccount,
projectMetrics,
getProjectAgentSettings,
resolveAgentSettings,
setProjectAgentSettings,
setTaskAgentSettings,
type AgentSettings,
type AgentSettingsPatch,
needsPerson,
MCP_GUIDE,
GET_STARTED_HINT,
GET_STARTED_DESCRIPTION,
platformStatus,
errorScope,
errorDetail,
listErrors,
markUntrusted,
} from "@peppa/core";
import { questions, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { stripAsIs } from "@peppa/shared/i18n";
import { applyPlan, archiveTask, planEpic, reorderBoardTask, type PlannedStory, currentReleases, deployProd, listReleases, decideIncident, resolveIncident, resolveError, fileErrorTask, acceptTask, answerAndDeliver, columnOf, describeRepo, isReviewQuestion, moveTask, provisionProject, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, type Provider } from "@peppa/runner";
import { and, asc, eq, inArray, isNull } from "drizzle-orm";
import { z } from "zod";
import { formatIncident, formatMetrics, formatTask } from "./format.ts";
import { registerMonitorTools } from "./monitors.ts";
import { createCodeMode, executeJournal } from "./code-mode.ts";
import { isSuperadmin as isPlatformSuperadmin } from "@peppa/core";
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
const COLUMNS = ["backlog", "in_progress", "review", "done"] as const;
const COLUMN_NAME: Record<BoardColumn, string> = { backlog: "Бэклог", in_progress: "В работе", review: "Ревью", done: "Готово" };
/** Sent to clients on initialize: how Peppa is organised and how to use the tools. */
export const MANAGER_INSTRUCTIONS = `${MCP_GUIDE}
FORGE is a software factory: AI agents (Claude Code / Codex) implement stories in Gitea repos, following OpenSpec.
Model: project (a Gitea repo, key like PEP) → epics (optional labels that group stories) → stories (PEP-12: one business story = one OpenSpec change; the tools call them "tasks") → board columns Backlog / In progress / Review / Done. Note: "tasks" inside an OpenSpec change (tasks.md) are the agent's checklist items, not stories.
- Moving a story to in_progress starts an agent on it; the agent writes an OpenSpec proposal, implements it, opens a PR and moves the story 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 story).
Good habits:
- Before creating, look: list_projects, list_epics, list_tasks. Don't duplicate — fix with update_task / update_epic.
- Label stories with an epic (epic_id) when one fits. Write story descriptions with context and a "Definition of done" list; the agent works from them.
- Only move a story to in_progress when the user asks to start the work.
- Board order = priority: list_tasks shows each column top-down; reorder_task moves a story (the backlog dispatcher takes from the top). archive_task hides a story without deleting it.
- Dependencies: a story can wait for others (blocked_by in create_task/update_task, set_dependencies); blocked stories are not started by the dispatcher until predecessors are in review/done.
- Planning: plan_epic breaks an epic into stories with dependencies and returns a draft; after the user agrees (edit freely), apply_plan creates them.
- 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. Repos are public by default; set_project_visibility (owner only) makes one private or public again.
- CI/CD: every PR is checked (get_task shows the checks; red ones go back to the agent; "accept" merges the PR only when they are green). A merge deploys to staging; list_releases shows what runs where; deploy puts the healthy staging release into prod — only when the user asks.
- Autonomy (get_project_settings / update_project_settings): manual by default; "auto" lets FORGE take stories from the backlog, merge green PRs and close stories itself; "assisted" only pushes the user when agents idle. Change it only when the user asks.
- Production errors (Bugsink) arrive as incidents: list_incidents. What happens to a new one is the project's incident policy (get_incident_policy / set_incident_policy: notify, backlog — default, start, ask, triage with the user's mini-prompt). Pending ones wait for decide_incident (backlog / start / ignore); resolve_incident marks one fixed.`;
const agentSchema = z
.object({
provider: z.enum(["claude", "codex", "opencode"]).nullable().optional().describe("Agent CLI; null = inherit (the subscription decides)"),
model: z.string().nullable().optional().describe("--model value (sonnet, opus, gpt-5-codex…); null = inherit"),
effort: z.enum(["low", "medium", "high", "xhigh", "max"]).nullable().optional(),
escalate_model: z.string().nullable().optional().describe("Stronger model after escalate_after failures (red CI attempts + reviewer returns)"),
escalate_effort: z.enum(["low", "medium", "high", "xhigh", "max"]).nullable().optional(),
escalate_after: z.number().int().min(0).max(20).nullable().optional().describe("0 = never escalate"),
fallback_provider: z.enum(["claude", "codex", "opencode"]).nullable().optional().describe("Used when the main provider has no working subscription"),
fallback_model: z.string().nullable().optional(),
claude_model: z.string().nullable().optional().describe("PEP-264: model for Claude only (wins over model there)"),
codex_model: z.string().nullable().optional().describe("PEP-264: model for Codex only"),
opencode_model: z.string().nullable().optional().describe("PEP-264: model for OpenCode only (provider/model)"),
})
.optional()
.describe("PEP-41 agent model settings; fields left out stay, null resets to inherited");
/** MCP snake_case agent patch → stored camelCase patch (null → inherit, escalate_after 0 → off). */
function agentPatch(a: NonNullable<z.infer<typeof agentSchema>>): Record<string, unknown> {
const map: Record<string, string> = { provider: "provider", model: "model", effort: "effort", escalate_model: "escalateModel", escalate_effort: "escalateEffort", escalate_after: "escalateAfter", fallback_provider: "fallbackProvider", fallback_model: "fallbackModel", claude_model: "claudeModel", codex_model: "codexModel", opencode_model: "opencodeModel" };
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(a)) {
if (v === undefined) continue;
const key = map[k]!;
out[key] = key === "escalateAfter" ? (v === 0 ? null : v === null ? "" : v) : v === null ? "" : v;
}
return out;
}
function describeAgent(s: AgentSettings, own: AgentSettingsPatch): string {
const mark = (k: keyof AgentSettings) => (k in own ? "" : " (inherited)");
return [
"Agent model (PEP-41):",
`- provider: ${s.provider ?? "subscription decides"}${mark("provider")}`,
`- model: ${s.model ?? "CLI default"}${mark("model")}, effort: ${s.effort ?? "default"}${mark("effort")}`,
`- escalation: ${s.escalateModel && s.escalateAfter != null ? `${s.escalateModel}${s.escalateEffort ? ` (${s.escalateEffort})` : ""} after ${s.escalateAfter} failures` : "off"}`,
`- fallback provider: ${s.fallbackProvider ? `${s.fallbackProvider}${s.fallbackModel ? ` / ${s.fallbackModel}` : ""}` : "none"}`,
`- per provider (PEP-264): claude ${s.claudeModel ?? "—"}, codex ${s.codexModel ?? "—"}, opencode ${s.opencodeModel ?? "—"}; a model of another CLI is never passed`,
].join("\n");
}
export function createManagerServer(db: Db, user: User, webUrl: string): McpServer {
const server = new McpServer({ name: "peppa", version: "0.3.0" }, { instructions: MANAGER_INSTRUCTIONS });
// PEP-212: one definition per tool; code mode builds `search_api` / `execute` from the same ones.
const codeMode = createCodeMode(server, { direct: ["get_started"], journal: executeJournal(db) });
const tool = codeMode.define;
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("Story key, e.g. PEP-3");
const projectArg = z.string().describe("Project key (e.g. PEP) or slug");
tool("get_started", GET_STARTED_DESCRIPTION, {}, true, async () => MCP_GUIDE);
// PEP-202: Observability — superadmin only.
registerMonitorTools(db, tool, {
async check() {
if (!(await isPlatformSuperadmin(db, user))) throw new PeppaError("Observability is available to the platform superadmin only");
return { author: `user:${user.login}` };
},
});
// PEP-212: the platform's state (what `peppa status` prints) — superadmin only; `peppa.platform.status()` in code mode.
tool("platform_status", "Platform state for the superadmin: services and heartbeats, outbox, checks queue, delays on our side, open questions, subscriptions out of order.", {}, true, async () => {
if (!(await isPlatformSuperadmin(db, user))) throw new PeppaError("Platform status is available to the platform superadmin only");
return platformStatus(db);
});
tool("list_projects", "List the user's FORGE projects (key, name, Gitea repo URL, story counts by board column).", {}, true, async () => {
const ps = await listUserProjects(db, user.id);
if (!ps.length) return `${GET_STARTED_HINT}\n\nNo 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} (${loadEnv().GITEA_URL}/${p.giteaOwner}/${p.giteaRepo})${p.ownerId === user.id ? "" : " [shared with you]"}: ${counts}`);
}
return `${GET_STARTED_HINT}\n\n${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(
"list_secrets",
"Names of a project's secrets (API keys for its agents; values are never returned). Secrets are added and changed only in the web: «⋯ Настройки проекта → Секреты».",
{ project: projectArg },
true,
async ({ project }) => {
const p = await ownedProject(project);
const rows = await listProjectSecrets(db, p.id);
if (!rows.length) return `${p.key} has no secrets.`;
return rows.map((r) => `- ${r.name} · ${r.agentEnv ? "agents and product" : "product only"}${r.connectionId ? " · moved to a connection" : ""} · updated ${r.updatedAt.toISOString().slice(0, 10)}${r.updatedBy ? ` by ${r.updatedBy}` : ""}${r.lastUsedAt ? ` · last given to an agent ${r.lastUsedAt.toISOString().slice(0, 16).replace("T", " ")}` : ""}`).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 FORGE, 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}`;
},
);
// Epics (PEP-66) live in the goals table; the *_goal(s) tools and goal_id stay as aliases.
const listEpicsText = async ({ project }: { project: string }) => {
const p = await ownedProject(project);
const gs = await listEpics(db, p.id);
const progress = await epicProgress(db, p.id);
return gs.length ? gs.map((g) => `- #${g.id} ${g.title} (done ${progressLabel(progress.get(g.id))})${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n") : "No open epics.";
};
const createEpicShape = { project: projectArg, title: z.string().trim().min(3), description: z.string().optional().describe("What the epic is about; agents get it with every story of the epic") };
const createEpicText = async ({ project, title, description }: { project: string; title: string; description?: string }) => {
const p = await ownedProject(project);
const g = await createEpic(db, p.id, title, description);
return `Created epic #${g.id} in ${p.key}: ${g.title}`;
};
const epicPatch = { title: z.string().trim().min(3).optional(), description: z.string().optional(), status: z.enum(["open", "done", "archived"]).optional() };
const updateEpicText = async (a: { project: string; epic_id?: number; goal_id?: number; title?: string; description?: string; status?: "open" | "done" | "archived" }) => {
const { project, title, description, status } = a;
const id = a.epic_id ?? a.goal_id!;
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 getEpic(db, p.id, id).catch(() => { throw new PeppaError("Не найдено"); });
const g = await updateEpic(db, p.id, id, { title, description, status });
return `Epic #${g.id} (${p.key}): ${g.title} [${g.status}]${g.description ? `\n${g.description}` : ""}`;
};
tool("list_epics", "List open epics of a project: labels that group stories (like GitHub labels/milestones).", { project: projectArg }, true, listEpicsText);
tool("create_epic", "Create an epic in a project: a label that groups stories.", createEpicShape, false, createEpicText);
tool("update_epic", "Edit an epic: title, description and/or status (open, done, archived — hidden from the board filter). Its stories are not changed.", { project: projectArg, epic_id: z.number().int(), ...epicPatch }, false, updateEpicText);
tool("list_goals", "Alias of list_epics (goals were renamed to epics).", { project: projectArg }, true, listEpicsText);
tool("create_goal", "Alias of create_epic (goals were renamed to epics).", createEpicShape, false, createEpicText);
tool("update_goal", "Alias of update_epic with goal_id (goals were renamed to epics).", { project: projectArg, goal_id: z.number().int(), ...epicPatch }, false, updateEpicText);
tool(
"create_project",
"Create a FORGE project: a new Gitea repo (public by default, or private) or connect an existing one you admin (its visibility is kept), in your namespace or an org you can create repos in, filled from the FORGE template with OpenSpec. Returns the repo URL, its visibility and who can see it. 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("Story 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"),
visibility: z.enum(["private", "public"]).optional().describe("New repo visibility (default public: everyone with Gitea access sees it; private: only the namespace owner/org members with access, peppa-bot and project members)"),
},
false,
async ({ name, slug, key, owner, existing, visibility }) => {
const p = await provisionProject(db, { ...(await projectNamespace(db, user, owner)), slug: slug.toLowerCase(), key, name, existing, visibility, ownerId: user.id });
const repo = await describeRepo(db, p, { fresh: true });
return [
`Created project ${p.key} — ${p.name}. ${webUrl}/p/${p.key}`,
`Repo: ${repo.url} (${repoVisibilityLabel(repo.private)}${repo.ownerKind ? `, ${repo.ownerKind === "org" ? "organization" : "personal"} namespace` : ""})`,
`Who can see it: ${repoAudience(repo)}`,
].join("\n");
},
);
tool(
"set_project_visibility",
"Make the project's Gitea repo public (everyone with Gitea access sees it) or private (only the namespace owner/org members with access, collaborators and peppa-bot). Owner only. Returns the new visibility and who can see the repo.",
{ project: projectArg, visibility: z.enum(["public", "private"]) },
false,
async ({ project, visibility }) => {
const p = await ownedProject(project);
const repo = await setProjectVisibility(db, p, visibility, { actor: user });
return [`${p.key}: репозиторий ${repo.fullName} теперь ${repoVisibilityLabel(repo.private)}`, `Who can see it: ${repoAudience(repo)}`].join("\n");
},
);
// PEP-23: autonomy of a project — levels and individual settings (owner or member).
tool("get_project_settings", "A project's autonomy settings (who takes stories from the backlog, PM approval of proposals, merge and closing mode, idle pushes) and the agent model (provider, model, effort, escalation, fallback provider).", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
return `${describeAutonomy(await getAutonomy(db, p.id))}\n\n${describeAgent(await resolveAgentSettings(db, p.id), await getProjectAgentSettings(db, p.id))}`;
});
tool(
"update_project_settings",
"Change a project's autonomy. level: manual (the user moves cards and accepts; default), assisted (as manual + a push when agents idle with a non-empty backlog), auto (FORGE takes stories from the backlog itself, merges green PRs and closes stories after the merge). Individual fields override the level. Only when the user asks.",
{
project: projectArg,
level: z.enum(["manual", "assisted", "auto"]).optional(),
pick: z.enum(["pm", "auto"]).optional().describe("Who takes stories from the backlog"),
wip_limit: z.number().int().min(1).max(5).optional().describe("Stories in work at once when pick=auto"),
proposal: z.enum(["agent", "pm"]).optional().describe("pm = the user approves every proposal"),
merge: z.enum(["manual", "auto"]).optional().describe("auto = merge green PRs without conflicts (pipeline changes always need the user)"),
close: z.enum(["pm", "after_merge", "after_hours"]).optional(),
close_after_hours: z.number().int().min(1).max(336).optional(),
accept_own: z.enum(["mine", "mine_breakage", "all"]).optional().describe("Which stories FORGE accepts herself when merge=auto: only the user's own / own and breakages (default) / all"),
idle_push: z.boolean().optional().describe("Push the user when no agent works and the backlog is not empty"),
idle_push_hours: z.number().int().min(1).max(168).optional(),
quiet_from: z.number().int().min(0).max(23).nullable().optional(),
quiet_to: z.number().int().min(0).max(23).nullable().optional(),
agent: agentSchema,
},
false,
async (a) => {
const p = await ownedProject(a.project);
if (a.agent) await setProjectAgentSettings(db, p.id, agentPatch(a.agent), true);
const s = await setAutonomy(db, p.id, {
level: a.level,
pick: a.pick,
wipLimit: a.wip_limit,
proposal: a.proposal,
merge: a.merge,
close: a.close,
closeAfterHours: a.close_after_hours,
acceptOwn: a.accept_own,
idlePush: a.idle_push,
idlePushHours: a.idle_push_hours,
quietFrom: a.quiet_from,
quietTo: a.quiet_to,
});
return `${p.key}:\n${describeAutonomy(s)}\n\n${describeAgent(await resolveAgentSettings(db, p.id), await getProjectAgentSettings(db, p.id))}`;
},
);
tool(
"list_tasks",
"List stories of a project as a board (Backlog / In progress / Review / Done), optionally one column. Each column is in board order (top = highest priority; the backlog dispatcher takes from the top); \"waits for\" marks stories blocked by unfinished predecessors.",
{ 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 deps = await blockersMap(db, 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) => {
const b = blockedLabel(deps.get(t.id))?.replace("ждёт", "waits for");
return `- ${t.key} [${t.status}]${t.goalId ? ` (epic #${t.goalId})` : ""} ${t.title}${b ? ` — ${b}` : ""}`;
}),
);
}
return out.join("\n");
},
);
// PEP-5: subscription limit windows; PEP-47: factory metrics.
tool("get_usage", "Subscription usage limits the user's agents run on: share of the 5-hour and 7-day windows used and when they reset, subscriptions in a limit. «нет данных» = no agent reported it yet.", {}, true, async () => {
const accounts = await accountUsageForUser(db, user);
return accounts.length ? accounts.map((a) => `- ${describeAccount(a)}`).join("\n") : "нет данных о лимитах";
});
tool(
"get_metrics",
"Factory metrics of a project for the last N weeks: stories done, median cycle time (in work → done), share accepted on the first pass, review return rate, PM questions per story, runner hours, hours agents waited for the PM, limit hits, tokens and cost («≈» = estimate); weekly trend and split by agent provider and epic.",
{ project: projectArg, weeks: z.number().int().min(1).max(52).optional().describe("Period in weeks, default 8") },
true,
async ({ project, weeks }) => formatMetrics(await projectMetrics(db, (await ownedProject(project)).id, { weeks })),
);
tool("get_task", "Get a story: description, epic, status, OpenSpec change, PM questions and comments, progress, CI checks.", { task: taskArg }, true, async ({ task }) => {
const ref = await ownedTask(task);
return `${GET_STARTED_HINT}\n\n${formatTask(await getTaskDetails(db, ref))}\n\nWeb: ${webUrl}/t/${ref.key}`;
});
tool(
"create_task",
"Create a story in a project (lands in Backlog). Label it with an epic when one fits.",
{
project: projectArg,
title: z.string().min(3),
description: z.string().optional(),
epic_id: z.number().int().optional().describe("Epic of the same project (list_epics)"),
goal_id: z.number().int().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Stories of the same project this one waits for (keys like PEP-3); the dispatcher won't start it until they are in review/done"),
},
false,
async ({ project, title, description, epic_id, goal_id, blocked_by }) => {
const p = await ownedProject(project);
const ref = await createTask(db, { projectId: p.id, title, description, goalId: epic_id ?? goal_id });
const deps = blocked_by?.length ? await setDependencies(db, ref, blocked_by).catch((e: Error) => { throw new PeppaError(`Created ${ref.key}, but dependencies were not set: ${e.message}`); }) : [];
return `Created ${ref.key}: ${title} (Backlog, bottom of the board)${deps.length ? ` · waits for ${deps.map((d) => d.key).join(", ")}` : ""}. ${webUrl}/t/${ref.key}`;
},
);
tool(
"update_task",
"Edit a story: title, description, epic, dependencies and/or agent model for this story (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)"),
epic_id: z.number().int().nullable().optional().describe("Label with this epic of the same project; null removes the epic"),
goal_id: z.number().int().nullable().optional().describe("Alias of epic_id"),
blocked_by: z.array(z.string()).optional().describe("Replaces the stories this one waits for (keys like PEP-3); [] removes all dependencies"),
agent: agentSchema,
},
false,
async ({ task, title, description, epic_id, goal_id, blocked_by, agent }) => {
const epic = epic_id !== undefined ? epic_id : goal_id;
if (title === undefined && description === undefined && epic === undefined && blocked_by === undefined && agent === undefined) throw new PeppaError("Nothing to update: pass title, description, epic_id, blocked_by and/or agent");
const ref = await ownedTask(task);
if (agent) await setTaskAgentSettings(db, ref.task.id, agentPatch(agent), true);
if (blocked_by !== undefined) await setDependencies(db, ref, blocked_by);
if (title !== undefined || description !== undefined || epic !== undefined) await updateTask(db, ref, { title, description, goalId: epic });
const updated = await resolveTask(db, ref.key);
return `${formatTask(await getTaskDetails(db, updated))}\n\nWeb: ${webUrl}/t/${ref.key}`;
},
);
tool(
"move_task",
"Move a story 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(
"reorder_task",
"Change a story's place on the board (= priority: the backlog dispatcher and idle pushes take from the top). top/bottom are within the story's column; before/after put it next to another story of the same project.",
{ task: taskArg, position: z.enum(["top", "bottom", "before", "after"]), other: z.string().optional().describe("For before/after: the story key to put it next to") },
false,
async ({ task, position, other }) => {
const ref = await ownedTask(task);
if ((position === "before" || position === "after") && !other) throw new PeppaError("Pass `other` for before/after");
const r = position === "top" || position === "bottom" ? { to: position } : { to: position, other: await ownedTask(other!) };
await reorderBoardTask(db, ref, r as never);
const col = columnOf(ref.task.status);
const inCol = (await listTasks(db, { projectId: ref.project.id })).filter((t) => columnOf(t.status) === col);
return `${COLUMN_NAME[col]}: ${inCol.map((t) => t.key).join(", ")}`;
},
);
tool(
"archive_task",
"Archive a story (hide it from the board, the dispatcher and epic progress; its agent stops; history stays) or restore it to the bottom of the board. There is no hard delete.",
{ task: taskArg, archived: z.boolean().default(true).describe("false restores the story") },
false,
async ({ task, archived }) => {
const ref = await ownedTask(task);
const r = await archiveTask(db, ref, archived);
return archived ? `${ref.key} archived${r.stopped ? ` · ${r.stopped} session(s) stopped` : ""}` : `${ref.key} restored to the board`;
},
);
tool(
"set_dependencies",
"Set the stories a story waits for (replaces the list; [] clears it). A story is blocked until every predecessor is in review/done; the dispatcher skips blocked stories. Same project only, no cycles.",
{ task: taskArg, blocked_by: z.array(z.string()).describe("Story keys like PEP-3") },
false,
async ({ task, blocked_by }) => {
const ref = await ownedTask(task);
const list = await setDependencies(db, ref, blocked_by);
return list.length ? `${ref.key} waits for ${list.map((b) => `${b.key} [${b.status}]`).join(", ")}` : `${ref.key} has no dependencies`;
},
);
const planStory = z.object({
title: z.string().trim().min(3),
description: z.string().default(""),
depends_on: z.array(z.union([z.number().int().positive(), z.string()])).default([]).describe("1-based numbers of other stories in this plan, or keys of existing stories"),
});
const planText = (stories: PlannedStory[]) =>
stories.map((s, i) => `${i + 1}. ${s.title}${s.dependsOn.length ? ` (after ${s.dependsOn.join(", ")})` : ""}\n${s.description.replace(/^/gm, " ")}`).join("\n\n");
tool(
"plan_epic",
"Ask FORGE's planner (a short Claude run on the project's subscription, up to ~3 min) to break an epic into stories with acceptance criteria and dependencies. Returns a DRAFT — nothing is created. Show it to the user, edit as they wish, then apply_plan.",
{ project: projectArg, epic_id: z.number().int(), wishes: z.string().optional().describe("Extra guidance for the planner from the user") },
false,
async ({ project, epic_id, wishes }) => {
const p = await ownedProject(project);
const r = await planEpic(db, p, epic_id, { wishes, by: user.login });
if (!r.ok) throw new PeppaError(`Planner failed: ${r.error}`);
const json = JSON.stringify(r.draft.stories.map((s) => ({ title: s.title, description: s.description, depends_on: s.dependsOn })));
return `Draft plan for epic #${epic_id} (${r.draft.stories.length} stories; also editable at ${webUrl}/p/${p.key}/plan/${epic_id}):\n\n${planText(r.draft.stories)}\n\nTo create: apply_plan with these stories (edited if needed):\n${json}`;
},
);
tool(
"apply_plan",
"Create stories from an approved plan: in the backlog under the epic, in plan order (bottom of the board), with dependencies (depends_on: plan numbers from 1 or existing story keys).",
{ project: projectArg, epic_id: z.number().int(), stories: z.array(planStory).min(1).max(15) },
false,
async ({ project, epic_id, stories }) => {
const p = await ownedProject(project);
const created = await applyPlan(db, p, epic_id, stories.map((s) => ({ title: s.title, description: s.description, dependsOn: s.depends_on.map((d) => (typeof d === "string" ? d.toUpperCase() : d)) })));
return `Created ${created.length} stories: ${created.map((r) => r.key).join(", ")}. ${webUrl}/p/${p.key}?epic=${epic_id}`;
},
);
tool("list_releases", "Deployments of a project: what runs on staging and prod, and the latest releases (env, commit, status, stories, who deployed).", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const [cur, rows] = await Promise.all([currentReleases(db, p.id), listReleases(db, p.id, 15)]);
const head = (["staging", "prod"] as const).map((e) => `${e}: ${cur[e] ? `${cur[e]!.sha.slice(0, 7)}${cur[e]!.host ? ` https://${cur[e]!.host}` : ""}` : "—"}`).join(" · ");
if (!rows.length) return `${head}\nNo deployments yet (deploy is configured in .peppa/project.json → "deploy").`;
return [head, ...rows.map((r) => `- ${r.env}${r.prNumber ? ` #${r.prNumber}` : ""} ${r.sha.slice(0, 7)} ${r.status}${r.reason ? ` (${r.reason})` : ""}${r.tasks.length ? ` · ${r.tasks.join(", ")}` : ""} · ${r.deployedBy} · ${r.createdAt.toISOString().slice(0, 16)}`)].join("\n");
});
tool(
"deploy",
"Deploy the project's healthy staging release to prod (the same image); for FORGE itself (no staging) the newest commit of main with green checks, released on its host. Only when the user asks; the result arrives as a release (list_releases) and a message.",
{ project: projectArg, env: z.enum(["prod"]).default("prod") },
false,
async ({ project }) => {
const p = await ownedProject(project);
const r = await deployProd(db, p, user.login);
return `${p.key}: ${r.sha.slice(0, 7)} is being deployed to prod${r.tasks.length ? ` (stories ${r.tasks.join(", ")})` : ""}. Check list_releases in a minute or two.`;
},
);
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(inArray(projects.id, ids), isNull(questions.answeredAt)))
.orderBy(asc(questions.id));
// PEP-149: only questions and stories waiting for «accept»; factory messages are not the inbox.
const waiting = rows.filter(({ q, status }) => needsPerson(q, status));
if (!waiting.length) return "Inbox is empty — agents need nothing from you.";
return waiting
.map(({ q, key, number, status }) => {
const kind = q.kind === "attention" && status === "review" ? "ready for review (answer 'accept' or a comment)" : q.kind;
return `- #${q.id} ${number != null ? formatTaskKey(key, number) : key} · ${kind}\n ${stripAsIs(q.text).replace(/\n/g, "\n ")}${q.options?.length ? `\n options: ${q.options.join(" | ")}` : ""}${q.defaultOption ? `\n default (the agent goes on with it meanwhile): ${q.defaultOption}` : ""}`;
})
.join("\n");
});
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' merges the story's PR (when it can't be merged yet — conflict, behind the main branch, checks not green — the accept is remembered and FORGE merges and closes the story by itself after green checks) and closes the story, 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.pending ? `${ref.key} accepted. Its PR can't be merged right now (conflict, behind the main branch, or checks not green yet): FORGE brings it up to date, merges and closes the story by itself after green checks — nothing more to press.` : `${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.";
},
);
// ── production errors (PEP-58) ──────────────────────────────────────────────────
const ownedIncident = async (id: number) => {
const i = await getIncident(db, id).catch(() => { throw new PeppaError("Не найдено"); });
await projectForUser(db, user.id, i.projectId);
return i;
};
tool(
"list_incidents",
"Production errors of a project (from Bugsink): id, status (pending = waits for the user's decision), title, where, environment, release, events, story.",
{ project: projectArg, status: z.enum(incidentStatuses).optional() },
true,
async ({ project, status }) => {
const p = await ownedProject(project);
const rows = await listIncidents(db, p.id, status ? [status] : undefined);
if (!rows.length) return (await getIncidentSettings(db, p.id)) ? "No incidents." : "Error tracking is not connected for this project (web: project page → «Подключить отслеживание ошибок»).";
const keys = new Map((await listTasks(db, { projectId: p.id })).map((t) => [t.id, t.key]));
return rows
.map((i) => `- #${i.id} [${i.status}] ${i.title}${i.culprit ? ` (${i.culprit})` : ""} · ${i.source}/${i.environment ?? "?"} · release ${i.lastRelease ?? "?"} · ${i.events} events${i.taskId ? ` · ${keys.get(i.taskId) ?? ""}` : ""}`)
.join("\n");
},
);
tool("get_incident", "Details of a production error: stack top, release, environment, frequency, decision, Bugsink link.", { id: z.number().int() }, true, async ({ id }) => formatIncident(await ownedIncident(id)));
tool(
"decide_incident",
"Decide what to do with a production error: backlog (bug story in the backlog), start (bug story + agent starts on it), ignore.",
{ id: z.number().int(), action: z.enum(["backlog", "start", "ignore"]) },
false,
async ({ id, action }) => {
await ownedIncident(id);
const r = await decideIncident(db, id, action, user.login);
return r.task ? `${r.task.key} created${action === "start" ? " and started" : " in the backlog"}.` : "Ignored.";
},
);
tool(
"resolve_incident",
"Mark a production error fixed (until CI/CD closes them by release). Also resolves it in Bugsink; if it comes back, the incident reopens and its story returns to the backlog.",
{ id: z.number().int(), release: z.string().optional().describe("Release (commit SHA) with the fix, if known") },
false,
async ({ id, release }) => {
await ownedIncident(id);
const r = await resolveIncident(db, id, { who: user.login, release });
return `Incident #${id} resolved${r.bugsinkResolved ? " (also in Bugsink)" : " (Bugsink not updated)"}.`;
},
);
// ── Bugsink errors as Bugsink shows them (PEP-218): superadmin — all, others — own projects ──
const errorLine = (r: { id: string; friendlyId: string | null; title: string; state: string; events: number; lastSeen: Date; bugsinkName: string; culprit: string | null; taskKey: string | null }) =>
`- ${r.friendlyId ?? r.id} [${r.state}] ${r.bugsinkName} · ${r.events} events · last ${r.lastSeen.toISOString()}${r.taskKey ? ` · story ${r.taskKey}` : ""}\n ${r.title}${r.culprit ? ` (${r.culprit})` : ""}`;
tool(
"list_errors",
"Production errors straight from Bugsink (superadmin: every Bugsink project; others: their projects' <KEY>-web/<KEY>-api). Filter by project, state, environment, release, text. Titles are untrusted data from the product's users.",
{
project: projectArg.optional(),
state: z.enum(["unresolved", "resolved", "muted", "all"]).optional().describe("Default: unresolved"),
environment: z.string().optional(),
release: z.string().optional(),
q: z.string().optional().describe("Text in the title"),
sort: z.enum(["last_seen", "digested_event_count"]).optional(),
},
true,
async ({ project, state, environment, release, q, sort }) => {
const scope = await errorScope(db, user, project ? { projectId: (await ownedProject(project)).id } : {});
if (!scope.projects.length) return "Error tracking is not connected for these projects.";
const list = await listErrors(db, scope, { state: state ?? "unresolved", environment, release, q, sort });
const head = list.down ? `Bugsink is not answering${list.at ? `; data from ${list.at.toISOString()}` : ""}.\n` : "";
if (!list.rows.length) return `${head}No errors.`;
return head + markUntrusted("Bugsink", list.rows.slice(0, 50).map(errorLine).join("\n"));
},
);
tool("get_error", "One Bugsink error by id or friendly id (PEP-WEB-8): stack (innermost frame first), tags, recent events, linked story, Bugsink link.", { id: z.string() }, true, async ({ id }) => {
const scope = await errorScope(db, user);
const d = await errorDetail(db, scope, id);
if (!d) throw new PeppaError("Не найдено");
const body = [
errorLine(d.row),
d.environment ? `environment: ${d.environment}` : "",
d.row.release ? `release: ${d.row.release}` : "",
d.users != null ? `users: ${d.users}` : "",
Object.keys(d.tags).length ? `tags: ${Object.entries(d.tags).map(([k, v]) => `${k}=${v}`).join(", ")}` : "",
"stack:",
...d.frames.slice(0, 20).map((f) => ` ${f.file}${f.line != null ? `:${f.line}` : ""} in ${f.fn ?? "?"}${f.inApp ? "" : " (lib)"}${f.context.find((c) => c[2]) ? `\n > ${f.context.find((c) => c[2])![1].trim()}` : ""}`),
`events: ${d.events.map((e) => e.at.toISOString()).join(", ")}`,
].filter(Boolean);
return `${d.down ? "Bugsink is not answering; cached data.\n" : ""}${markUntrusted("Bugsink", body.join("\n"))}\nStory: ${d.row.taskKey ?? "none"} · Bugsink: ${d.bugsinkUrl}`;
});
tool("resolve_error", "Mark a Bugsink error resolved (through its incident and story note if FORGE knows it).", { id: z.string() }, false, async ({ id }) => {
const scope = await errorScope(db, user);
await resolveError(db, scope, id, user.login);
return `Error ${id} resolved.`;
});
tool("create_error_task", "Make a bug story in the backlog from a Bugsink error (the same path as the error policy; a second call returns the existing story).", { id: z.string() }, false, async ({ id }) => {
const scope = await errorScope(db, user);
const r = await fileErrorTask(db, scope, id, user.login);
return r.created ? `${r.task.key} created in the backlog.` : `Already has a story: ${r.task.key}.`;
});
tool("get_incident_policy", "A project's incident policy: what happens to a new production error, triage prompt, environments, daily story limit, ignore pattern.", { project: projectArg }, true, async ({ project }) => {
const p = await ownedProject(project);
const s = await getIncidentSettings(db, p.id);
if (!s) return "Error tracking is not connected for this project.";
return [
`Policy: ${s.policy} — ${POLICY_RU[s.policy]}`,
`Triage prompt: ${s.triagePrompt ?? "—"}`,
`Environments: ${s.environments.join(", ")}`,
`Daily story limit: ${s.dailyLimit}`,
`Ignore pattern: ${s.ignorePattern ?? "—"}`,
].join("\n");
});
tool(
"set_incident_policy",
"Change what happens to new production errors: notify (Telegram only), backlog (bug story, default), start (bug story + agent), ask (Telegram buttons), triage (a triage agent decides by triage_prompt — the user's own words on how to decide; falls back to ask when unsure).",
{
project: projectArg,
policy: z.enum(incidentPolicies).optional(),
triage_prompt: z.string().optional(),
environments: z.array(z.string()).optional(),
daily_limit: z.number().int().min(0).optional(),
ignore_pattern: z.string().optional().describe("Regex on the error title; empty string clears it"),
},
false,
async ({ project, policy, triage_prompt, environments, daily_limit, ignore_pattern }) => {
const p = await ownedProject(project);
const s = await updateIncidentSettings(db, p.id, {
policy,
triagePrompt: triage_prompt,
environments,
dailyLimit: daily_limit,
ignorePattern: ignore_pattern === undefined ? undefined : ignore_pattern || null,
});
return `Incident policy of ${p.key}: ${s.policy} — ${POLICY_RU[s.policy]}${s.policy === "triage" ? `; prompt: ${s.triagePrompt ?? "(empty — the triager will ask)"}` : ""}.`;
},
);
codeMode.finish();
return server;
}