Add Peppa MCP server, core domain package and peppa CLI
- @peppa/core: projects, goals, tasks (atomic per-project numbering), PM questions, progress events, pg NOTIFY on peppa_events - @peppa/mcp (peppa-mcp): get_task, list_tasks, list_goals, create_task, update_task, request_approval, ask_pm, report_progress - @peppa/cli (peppa): project/goal/task/q commands - questions/events now link to project and task; session is optional - scripts/install-bins.sh; bootstrap-project.sh registers the project Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4168e8c867
commit
9824ce4c18
@ -8,14 +8,17 @@
|
||||
- `apps/bot` — Telegram-бот (grammY)
|
||||
- `packages/db` — Drizzle-схема и клиент (Postgres на 127.0.0.1:5433)
|
||||
- `packages/shared` — env, ключи задач (`PEP-42`)
|
||||
- `packages/mcp` — MCP-сервер `peppa` для сессий в проектах
|
||||
- `packages/core` — доменная логика (проекты, цели, задачи, вопросы PM, pg NOTIFY `peppa_events`); всё ходит через неё
|
||||
- `packages/mcp` — MCP-сервер `peppa` (бинарь `peppa-mcp`) для сессий в проектах; проект берётся из `.peppa/project.json` в cwd
|
||||
- `packages/cli` — CLI `peppa` (project/goal/task/q), пока нет веба
|
||||
- `packages/runner` — запуск claude в tmux, `peppa-hook`, вачдог
|
||||
- `template/` — содержимое репо `peppa/template` (AGENTS.md и т.д.), копируется в каждый проект
|
||||
- `scripts/` — push-template.sh, bootstrap-project.sh
|
||||
- `scripts/` — push-template.sh, bootstrap-project.sh, install-bins.sh (симлинки `packages/*/bin/*` в ~/.local/bin)
|
||||
|
||||
## Команды
|
||||
- `pnpm db:up` / `pnpm db:generate` / `pnpm db:migrate`
|
||||
- `pnpm typecheck`
|
||||
- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера
|
||||
- `pnpm dev:web`
|
||||
|
||||
TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`.
|
||||
|
||||
4
packages/cli/bin/peppa
Executable file
4
packages/cli/bin/peppa
Executable file
@ -0,0 +1,4 @@
|
||||
#!/usr/bin/env bash
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a
|
||||
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@"
|
||||
13
packages/cli/package.json
Normal file
13
packages/cli/package.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "@peppa/cli",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": { "peppa": "./bin/peppa" },
|
||||
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": {
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*"
|
||||
}
|
||||
}
|
||||
159
packages/cli/src/index.ts
Normal file
159
packages/cli/src/index.ts
Normal file
@ -0,0 +1,159 @@
|
||||
// `peppa` CLI: manage projects, goals, tasks and PM questions until the web UI exists.
|
||||
import { parseArgs } from "node:util";
|
||||
import { resolve } from "node:path";
|
||||
import {
|
||||
answerQuestion,
|
||||
createGoal,
|
||||
createProject,
|
||||
createTask,
|
||||
findProjectFile,
|
||||
getProject,
|
||||
getTaskDetails,
|
||||
listGoals,
|
||||
listProjects,
|
||||
listTasks,
|
||||
pendingQuestions,
|
||||
PeppaError,
|
||||
resolveTask,
|
||||
TASK_STATUSES,
|
||||
updateTask,
|
||||
type TaskStatus,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
|
||||
const USAGE = `peppa — Peppa software factory CLI
|
||||
|
||||
peppa project add <slug> <KEY> <name> [--owner peppa] [--repo <name>] [--path <dir>]
|
||||
peppa project list
|
||||
peppa goal add [KEY] <title> [-d <description>]
|
||||
peppa goal list [KEY]
|
||||
peppa task add [KEY] <title> [-g <goal-id>] [-d <description>]
|
||||
peppa task list [KEY] [-s <status>]
|
||||
peppa task show <PEP-42|42>
|
||||
peppa task set <PEP-42|42> -s <status>
|
||||
peppa q list [KEY]
|
||||
peppa q answer <id> <answer>
|
||||
|
||||
KEY defaults to the project of the current directory (.peppa/project.json).
|
||||
Statuses: ${TASK_STATUSES.join(", ")}`;
|
||||
|
||||
const { values: opts, positionals } = parseArgs({
|
||||
allowPositionals: true,
|
||||
options: {
|
||||
owner: { type: "string", default: "peppa" },
|
||||
repo: { type: "string" },
|
||||
path: { type: "string" },
|
||||
description: { type: "string", short: "d" },
|
||||
goal: { type: "string", short: "g" },
|
||||
status: { type: "string", short: "s" },
|
||||
help: { type: "boolean", short: "h" },
|
||||
},
|
||||
});
|
||||
|
||||
const env = loadEnv();
|
||||
const db = createDb(env.DATABASE_URL);
|
||||
const here = findProjectFile(process.cwd())?.data.key;
|
||||
const [group, cmd, ...args] = positionals;
|
||||
|
||||
/** Optional leading project KEY: used when there are more args than required. */
|
||||
function withKey(rest: string[], required: number): [string, string[]] {
|
||||
if (rest.length > required) return [rest[0]!, rest.slice(1)];
|
||||
if (!here) throw new PeppaError("No project KEY given and no .peppa/project.json here");
|
||||
return [here, rest];
|
||||
}
|
||||
|
||||
function status(s: string | undefined): TaskStatus | undefined {
|
||||
if (s === undefined) return undefined;
|
||||
if (!(TASK_STATUSES as readonly string[]).includes(s)) throw new PeppaError(`Unknown status "${s}"`);
|
||||
return s as TaskStatus;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
switch (`${group ?? ""} ${cmd ?? ""}`.trim()) {
|
||||
case "project add": {
|
||||
const [slug, key, name] = args;
|
||||
if (!slug || !key || !name) throw new PeppaError("usage: peppa project add <slug> <KEY> <name>");
|
||||
const p = await createProject(db, {
|
||||
slug,
|
||||
key,
|
||||
name,
|
||||
giteaOwner: opts.owner!,
|
||||
giteaRepo: opts.repo,
|
||||
workspacePath: resolve(opts.path ?? `${env.PEPPA_WORKSPACES}/${slug}`),
|
||||
});
|
||||
console.log(`Project ${p.key} (${p.slug}) → ${p.workspacePath}`);
|
||||
break;
|
||||
}
|
||||
case "project list":
|
||||
for (const p of await listProjects(db)) console.log(`${p.key.padEnd(8)} ${p.slug.padEnd(20)} ${p.name} ${p.workspacePath}`);
|
||||
break;
|
||||
case "goal add": {
|
||||
const [key, [title]] = withKey(args, 1);
|
||||
if (!title) throw new PeppaError("usage: peppa goal add [KEY] <title>");
|
||||
const g = await createGoal(db, (await getProject(db, key)).id, title, opts.description);
|
||||
console.log(`Goal #${g.id}: ${g.title}`);
|
||||
break;
|
||||
}
|
||||
case "goal list": {
|
||||
const [key] = withKey(args, 0);
|
||||
for (const g of await listGoals(db, (await getProject(db, key)).id)) console.log(`#${g.id} ${g.title}`);
|
||||
break;
|
||||
}
|
||||
case "task add": {
|
||||
const [key, [title]] = withKey(args, 1);
|
||||
if (!title) throw new PeppaError("usage: peppa task add [KEY] <title>");
|
||||
const p = await getProject(db, key);
|
||||
const ref = await createTask(db, {
|
||||
projectId: p.id,
|
||||
goalId: opts.goal ? Number(opts.goal) : undefined,
|
||||
title,
|
||||
description: opts.description,
|
||||
});
|
||||
console.log(`${ref.key}: ${title}`);
|
||||
break;
|
||||
}
|
||||
case "task list": {
|
||||
const projectId = args[0] ?? here ? (await getProject(db, (args[0] ?? here)!)).id : undefined;
|
||||
const s = status(opts.status);
|
||||
for (const t of await listTasks(db, { projectId, statuses: s ? [s] : undefined })) {
|
||||
console.log(`${t.key.padEnd(10)} ${t.status.padEnd(18)} ${t.title}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "task show": {
|
||||
const ref = await resolveTask(db, args[0] ?? "", here);
|
||||
const d = await getTaskDetails(db, ref);
|
||||
console.log(JSON.stringify({ key: d.key, ...d.task, goal: d.goal, questions: d.questions }, null, 2));
|
||||
break;
|
||||
}
|
||||
case "task set": {
|
||||
const ref = await resolveTask(db, args[0] ?? "", here);
|
||||
const t = await updateTask(db, ref, { status: status(opts.status) });
|
||||
console.log(`${ref.key} → ${t.status}`);
|
||||
break;
|
||||
}
|
||||
case "q list": {
|
||||
const projectId = args[0] ?? here ? (await getProject(db, (args[0] ?? here)!)).id : undefined;
|
||||
for (const q of await pendingQuestions(db, projectId)) console.log(`#${q.id} [${q.kind}] task=${q.taskId ?? "-"} ${q.text}`);
|
||||
break;
|
||||
}
|
||||
case "q answer": {
|
||||
const [id, ...answer] = args;
|
||||
const q = await answerQuestion(db, Number(id), answer.join(" "), "terminal");
|
||||
console.log(`Answered #${q.id}`);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
console.log(USAGE);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (opts.help) console.log(USAGE);
|
||||
else await main();
|
||||
process.exit(0);
|
||||
} catch (e) {
|
||||
console.error(e instanceof PeppaError ? `peppa: ${e.message}` : e);
|
||||
process.exit(1);
|
||||
}
|
||||
1
packages/cli/tsconfig.json
Normal file
1
packages/cli/tsconfig.json
Normal file
@ -0,0 +1 @@
|
||||
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src"] }
|
||||
13
packages/core/package.json
Normal file
13
packages/core/package.json
Normal file
@ -0,0 +1,13 @@
|
||||
{
|
||||
"name": "@peppa/core",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": { ".": "./src/index.ts" },
|
||||
"scripts": { "typecheck": "tsc -p ." },
|
||||
"dependencies": {
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"drizzle-orm": "0.45.4"
|
||||
}
|
||||
}
|
||||
4
packages/core/src/errors.ts
Normal file
4
packages/core/src/errors.ts
Normal file
@ -0,0 +1,4 @@
|
||||
/** Errors whose message is safe and useful to show to an agent or the PM as-is. */
|
||||
export class PeppaError extends Error {
|
||||
override name = "PeppaError";
|
||||
}
|
||||
5
packages/core/src/index.ts
Normal file
5
packages/core/src/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export * from "./errors.ts";
|
||||
export * from "./notify.ts";
|
||||
export * from "./project-file.ts";
|
||||
export * from "./projects.ts";
|
||||
export * from "./tasks.ts";
|
||||
15
packages/core/src/notify.ts
Normal file
15
packages/core/src/notify.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import type { Db } from "@peppa/db";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
export const EVENTS_CHANNEL = "peppa_events";
|
||||
|
||||
export type PeppaNotification =
|
||||
| { type: "question"; questionId: number }
|
||||
| { type: "question_answered"; questionId: number }
|
||||
| { type: "task_updated"; taskId: number }
|
||||
| { type: "progress"; eventId: number };
|
||||
|
||||
/** Broadcasts via Postgres NOTIFY; the bot and web listen on EVENTS_CHANNEL. */
|
||||
export async function notify(db: Db, n: PeppaNotification): Promise<void> {
|
||||
await db.execute(sql`select pg_notify(${EVENTS_CHANNEL}, ${JSON.stringify(n)})`);
|
||||
}
|
||||
15
packages/core/src/project-file.ts
Normal file
15
packages/core/src/project-file.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { PeppaProjectFile } from "@peppa/shared";
|
||||
|
||||
/** Walks up from `dir` looking for `.peppa/project.json`. */
|
||||
export function findProjectFile(dir: string): { path: string; data: PeppaProjectFile } | null {
|
||||
let cur = dir;
|
||||
for (;;) {
|
||||
const path = join(cur, ".peppa", "project.json");
|
||||
if (existsSync(path)) return { path, data: JSON.parse(readFileSync(path, "utf8")) as PeppaProjectFile };
|
||||
const parent = dirname(cur);
|
||||
if (parent === cur) return null;
|
||||
cur = parent;
|
||||
}
|
||||
}
|
||||
60
packages/core/src/projects.ts
Normal file
60
packages/core/src/projects.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import { goals, projects, type Db } from "@peppa/db";
|
||||
import { and, asc, eq, or } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
|
||||
export type Project = typeof projects.$inferSelect;
|
||||
export type Goal = typeof goals.$inferSelect;
|
||||
|
||||
export interface NewProject {
|
||||
slug: string;
|
||||
key: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
giteaOwner: string;
|
||||
giteaRepo?: string;
|
||||
workspacePath: string;
|
||||
}
|
||||
|
||||
export async function createProject(db: Db, p: NewProject): Promise<Project> {
|
||||
const key = p.key.toUpperCase();
|
||||
if (!/^[A-Z][A-Z0-9]{1,9}$/.test(key)) throw new PeppaError(`Invalid project key "${p.key}": 2–10 chars, A–Z/0–9, starts with a letter`);
|
||||
if (!/^[a-z0-9][a-z0-9-]*$/.test(p.slug)) throw new PeppaError(`Invalid slug "${p.slug}": lowercase letters, digits, dashes`);
|
||||
const [row] = await db
|
||||
.insert(projects)
|
||||
.values({ ...p, key, giteaRepo: p.giteaRepo ?? p.slug })
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export async function listProjects(db: Db): Promise<Project[]> {
|
||||
return db.select().from(projects).orderBy(asc(projects.key));
|
||||
}
|
||||
|
||||
/** Finds a project by task key prefix ("PEP") or slug ("peppa"). */
|
||||
export async function getProject(db: Db, keyOrSlug: string): Promise<Project> {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(projects)
|
||||
.where(or(eq(projects.key, keyOrSlug.toUpperCase()), eq(projects.slug, keyOrSlug.toLowerCase())));
|
||||
if (!row) throw new PeppaError(`Project "${keyOrSlug}" not found`);
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function createGoal(db: Db, projectId: number, title: string, description?: string): Promise<Goal> {
|
||||
const [row] = await db.insert(goals).values({ projectId, title, description }).returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export async function listGoals(db: Db, projectId: number, includeClosed = false): Promise<Goal[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(goals)
|
||||
.where(includeClosed ? eq(goals.projectId, projectId) : and(eq(goals.projectId, projectId), eq(goals.status, "open")))
|
||||
.orderBy(asc(goals.id));
|
||||
}
|
||||
|
||||
export async function getGoal(db: Db, projectId: number, goalId: number): Promise<Goal> {
|
||||
const [row] = await db.select().from(goals).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId)));
|
||||
if (!row) throw new PeppaError(`Goal #${goalId} not found in this project`);
|
||||
return row;
|
||||
}
|
||||
186
packages/core/src/tasks.ts
Normal file
186
packages/core/src/tasks.ts
Normal file
@ -0,0 +1,186 @@
|
||||
import { events, goals, projects, questions, taskStatus, tasks, type Db } from "@peppa/db";
|
||||
import { formatTaskKey, parseTaskKey } from "@peppa/shared";
|
||||
import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { PeppaError } from "./errors.ts";
|
||||
import { notify } from "./notify.ts";
|
||||
import { getGoal, getProject, type Goal, type Project } from "./projects.ts";
|
||||
|
||||
export type Task = typeof tasks.$inferSelect;
|
||||
export type TaskStatus = (typeof taskStatus.enumValues)[number];
|
||||
export type Question = typeof questions.$inferSelect;
|
||||
export type QuestionKind = Question["kind"];
|
||||
export const TASK_STATUSES = taskStatus.enumValues;
|
||||
|
||||
export interface TaskRef {
|
||||
project: Project;
|
||||
task: Task;
|
||||
key: string;
|
||||
}
|
||||
|
||||
/** Resolves "PEP-42" / "42" (with a default project key) to the task row. */
|
||||
export async function resolveTask(db: Db, input: string, defaultProjectKey?: string): Promise<TaskRef> {
|
||||
const parsed = parseTaskKey(input, defaultProjectKey);
|
||||
if (!parsed) {
|
||||
throw new PeppaError(
|
||||
defaultProjectKey
|
||||
? `Can't parse task "${input}": expected ${defaultProjectKey}-42 or 42`
|
||||
: `Can't parse task "${input}": expected KEY-42 (no default project here — is .peppa/project.json present?)`,
|
||||
);
|
||||
}
|
||||
const project = await getProject(db, parsed.projectKey);
|
||||
const [task] = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.projectId, project.id), eq(tasks.number, parsed.number)));
|
||||
if (!task) throw new PeppaError(`Task ${formatTaskKey(project.key, parsed.number)} not found`);
|
||||
return { project, task, key: formatTaskKey(project.key, task.number) };
|
||||
}
|
||||
|
||||
export interface NewTask {
|
||||
projectId: number;
|
||||
goalId?: number;
|
||||
title: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
export async function createTask(db: Db, t: NewTask): Promise<TaskRef> {
|
||||
return db.transaction(async (tx) => {
|
||||
// Hand out the per-project number atomically.
|
||||
const [project] = await tx
|
||||
.update(projects)
|
||||
.set({ nextTaskNumber: sql`${projects.nextTaskNumber} + 1` })
|
||||
.where(eq(projects.id, t.projectId))
|
||||
.returning();
|
||||
if (!project) throw new PeppaError(`Project #${t.projectId} not found`);
|
||||
if (t.goalId != null) await getGoal(tx as unknown as Db, t.projectId, t.goalId);
|
||||
const [task] = await tx
|
||||
.insert(tasks)
|
||||
.values({ ...t, number: project.nextTaskNumber - 1 })
|
||||
.returning();
|
||||
return { project, task: task!, key: formatTaskKey(project.key, task!.number) };
|
||||
});
|
||||
}
|
||||
|
||||
export interface TaskFilter {
|
||||
projectId?: number;
|
||||
goalId?: number;
|
||||
statuses?: TaskStatus[];
|
||||
}
|
||||
|
||||
export async function listTasks(db: Db, f: TaskFilter = {}): Promise<Array<Task & { key: string }>> {
|
||||
const where = [];
|
||||
if (f.projectId != null) where.push(eq(tasks.projectId, f.projectId));
|
||||
if (f.goalId != null) where.push(eq(tasks.goalId, f.goalId));
|
||||
if (f.statuses?.length) where.push(inArray(tasks.status, f.statuses));
|
||||
const rows = await db
|
||||
.select({ task: tasks, projectKey: projects.key })
|
||||
.from(tasks)
|
||||
.innerJoin(projects, eq(tasks.projectId, projects.id))
|
||||
.where(and(...where))
|
||||
.orderBy(asc(projects.key), asc(tasks.number));
|
||||
return rows.map((r) => ({ ...r.task, key: formatTaskKey(r.projectKey, r.task.number) }));
|
||||
}
|
||||
|
||||
export interface TaskPatch {
|
||||
status?: TaskStatus;
|
||||
title?: string;
|
||||
description?: string;
|
||||
goalId?: number | null;
|
||||
openspecChange?: string | null;
|
||||
prUrl?: string | null;
|
||||
}
|
||||
|
||||
export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, sessionId?: number): Promise<Task> {
|
||||
if (patch.goalId != null) await getGoal(db, ref.project.id, patch.goalId);
|
||||
const [task] = await db.update(tasks).set(patch).where(eq(tasks.id, ref.task.id)).returning();
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(patch).filter(([k, v]) => v !== undefined && ref.task[k as keyof Task] !== v),
|
||||
);
|
||||
if (Object.keys(changed).length) {
|
||||
await db.insert(events).values({
|
||||
projectId: ref.project.id,
|
||||
taskId: ref.task.id,
|
||||
sessionId,
|
||||
type: "task_updated",
|
||||
payload: { from: pick(ref.task, Object.keys(changed)), to: changed },
|
||||
});
|
||||
await notify(db, { type: "task_updated", taskId: ref.task.id });
|
||||
}
|
||||
return task!;
|
||||
}
|
||||
|
||||
export interface TaskDetails {
|
||||
key: string;
|
||||
task: Task;
|
||||
project: Project;
|
||||
goal: Goal | null;
|
||||
questions: Question[];
|
||||
recentEvents: Array<typeof events.$inferSelect>;
|
||||
}
|
||||
|
||||
export async function getTaskDetails(db: Db, ref: TaskRef): Promise<TaskDetails> {
|
||||
const [goal] = ref.task.goalId ? await db.select().from(goals).where(eq(goals.id, ref.task.goalId)) : [];
|
||||
const qs = await db.select().from(questions).where(eq(questions.taskId, ref.task.id)).orderBy(asc(questions.id));
|
||||
const evs = await db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(eq(events.taskId, ref.task.id))
|
||||
.orderBy(desc(events.id))
|
||||
.limit(20);
|
||||
return { key: ref.key, task: ref.task, project: ref.project, goal: goal ?? null, questions: qs, recentEvents: evs.reverse() };
|
||||
}
|
||||
|
||||
export interface NewQuestion {
|
||||
kind: QuestionKind;
|
||||
text: string;
|
||||
options?: string[];
|
||||
sessionId?: number;
|
||||
}
|
||||
|
||||
/** Records a question for the PM and broadcasts it (the bot forwards it to Telegram). */
|
||||
export async function askPm(db: Db, ref: TaskRef, q: NewQuestion): Promise<Question> {
|
||||
const [row] = await db
|
||||
.insert(questions)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, ...q })
|
||||
.returning();
|
||||
if (q.kind === "approval") await updateTask(db, ref, { status: "awaiting_approval" }, q.sessionId);
|
||||
await notify(db, { type: "question", questionId: row!.id });
|
||||
return row!;
|
||||
}
|
||||
|
||||
export async function pendingQuestions(db: Db, projectId?: number): Promise<Question[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(questions)
|
||||
.where(and(isNull(questions.answeredAt), projectId != null ? eq(questions.projectId, projectId) : undefined))
|
||||
.orderBy(asc(questions.id));
|
||||
}
|
||||
|
||||
export async function answerQuestion(
|
||||
db: Db,
|
||||
questionId: number,
|
||||
answer: string,
|
||||
via: NonNullable<Question["answeredVia"]>,
|
||||
): Promise<Question> {
|
||||
const [row] = await db
|
||||
.update(questions)
|
||||
.set({ answer, answeredVia: via, answeredAt: new Date() })
|
||||
.where(and(eq(questions.id, questionId), isNull(questions.answeredAt)))
|
||||
.returning();
|
||||
if (!row) throw new PeppaError(`Question #${questionId} not found or already answered`);
|
||||
await notify(db, { type: "question_answered", questionId });
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function reportProgress(db: Db, ref: TaskRef, text: string, sessionId?: number) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({ projectId: ref.project.id, taskId: ref.task.id, sessionId, type: "progress", payload: { text } })
|
||||
.returning();
|
||||
await notify(db, { type: "progress", eventId: row!.id });
|
||||
return row!;
|
||||
}
|
||||
|
||||
function pick<T extends object>(o: T, keys: string[]): Record<string, unknown> {
|
||||
return Object.fromEntries(keys.map((k) => [k, o[k as keyof T]]));
|
||||
}
|
||||
1
packages/core/tsconfig.json
Normal file
1
packages/core/tsconfig.json
Normal file
@ -0,0 +1 @@
|
||||
{ "extends": "../../tsconfig.base.json", "compilerOptions": { "allowImportingTsExtensions": true }, "include": ["src"] }
|
||||
@ -3,7 +3,9 @@ CREATE TYPE "public"."session_status" AS ENUM('starting', 'running', 'waiting_in
|
||||
CREATE TYPE "public"."task_status" AS ENUM('backlog', 'proposing', 'awaiting_approval', 'in_progress', 'review', 'done', 'blocked');--> statement-breakpoint
|
||||
CREATE TABLE "events" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"session_id" integer NOT NULL,
|
||||
"project_id" integer NOT NULL,
|
||||
"task_id" integer,
|
||||
"session_id" integer,
|
||||
"type" text NOT NULL,
|
||||
"payload" jsonb,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
@ -38,7 +40,9 @@ CREATE TABLE "projects" (
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "questions" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"session_id" integer NOT NULL,
|
||||
"project_id" integer NOT NULL,
|
||||
"task_id" integer,
|
||||
"session_id" integer,
|
||||
"kind" text NOT NULL,
|
||||
"text" text NOT NULL,
|
||||
"options" jsonb,
|
||||
@ -76,9 +80,13 @@ CREATE TABLE "tasks" (
|
||||
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "events" ADD CONSTRAINT "events_session_id_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "events" ADD CONSTRAINT "events_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "events" ADD CONSTRAINT "events_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "events" ADD CONSTRAINT "events_session_id_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."sessions"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "goals" ADD CONSTRAINT "goals_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "questions" ADD CONSTRAINT "questions_session_id_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."sessions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "questions" ADD CONSTRAINT "questions_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "questions" ADD CONSTRAINT "questions_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "questions" ADD CONSTRAINT "questions_session_id_sessions_id_fk" FOREIGN KEY ("session_id") REFERENCES "public"."sessions"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_task_id_tasks_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."tasks"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "tasks" ADD CONSTRAINT "tasks_project_id_projects_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."projects"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
@ -1,5 +1,5 @@
|
||||
{
|
||||
"id": "62a2731d-7246-4e13-8646-f978422b8513",
|
||||
"id": "2281ab22-b150-4664-9ffc-a0bb54103d9c",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
@ -14,11 +14,23 @@
|
||||
"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": true
|
||||
"notNull": false
|
||||
},
|
||||
"type": {
|
||||
"name": "type",
|
||||
@ -42,6 +54,32 @@
|
||||
},
|
||||
"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",
|
||||
@ -52,7 +90,7 @@
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
@ -249,11 +287,23 @@
|
||||
"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": true
|
||||
"notNull": false
|
||||
},
|
||||
"kind": {
|
||||
"name": "kind",
|
||||
@ -307,6 +357,32 @@
|
||||
},
|
||||
"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",
|
||||
@ -317,7 +393,7 @@
|
||||
"columnsTo": [
|
||||
"id"
|
||||
],
|
||||
"onDelete": "cascade",
|
||||
"onDelete": "set null",
|
||||
"onUpdate": "no action"
|
||||
}
|
||||
},
|
||||
|
||||
@ -5,8 +5,8 @@
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1794492771395,
|
||||
"tag": "0000_tired_thunderbolt_ross",
|
||||
"when": 1794492884912,
|
||||
"tag": "0000_safe_shiver_man",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
|
||||
@ -90,7 +90,10 @@ export const sessions = pgTable("sessions", {
|
||||
/** Questions routed to the PM (Telegram / web) and their answers. */
|
||||
export const questions = pgTable("questions", {
|
||||
id: serial("id").primaryKey(),
|
||||
sessionId: integer("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
||||
// Null when asked from a session Peppa did not start (manual `claude`).
|
||||
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
||||
kind: text("kind", { enum: ["question", "permission", "approval", "attention"] }).notNull(),
|
||||
text: text("text").notNull(),
|
||||
options: jsonb("options").$type<string[]>(),
|
||||
@ -101,10 +104,12 @@ export const questions = pgTable("questions", {
|
||||
answeredAt: timestamp("answered_at", { withTimezone: true }),
|
||||
});
|
||||
|
||||
/** Raw hook / watchdog event log per session. */
|
||||
/** Event log: hook / watchdog events, progress reports, status changes. */
|
||||
export const events = pgTable("events", {
|
||||
id: serial("id").primaryKey(),
|
||||
sessionId: integer("session_id").notNull().references(() => sessions.id, { onDelete: "cascade" }),
|
||||
projectId: integer("project_id").notNull().references(() => projects.id, { onDelete: "cascade" }),
|
||||
taskId: integer("task_id").references(() => tasks.id, { onDelete: "cascade" }),
|
||||
sessionId: integer("session_id").references(() => sessions.id, { onDelete: "set null" }),
|
||||
type: text("type").notNull(),
|
||||
payload: jsonb("payload"),
|
||||
createdAt: createdAt(),
|
||||
@ -123,6 +128,8 @@ export const tasksRelations = relations(tasks, ({ one, many }) => ({
|
||||
project: one(projects, { fields: [tasks.projectId], references: [projects.id] }),
|
||||
goal: one(goals, { fields: [tasks.goalId], references: [goals.id] }),
|
||||
sessions: many(sessions),
|
||||
questions: many(questions),
|
||||
events: many(events),
|
||||
}));
|
||||
export const sessionsRelations = relations(sessions, ({ one, many }) => ({
|
||||
project: one(projects, { fields: [sessions.projectId], references: [projects.id] }),
|
||||
@ -131,8 +138,12 @@ export const sessionsRelations = relations(sessions, ({ one, many }) => ({
|
||||
events: many(events),
|
||||
}));
|
||||
export const questionsRelations = relations(questions, ({ one }) => ({
|
||||
project: one(projects, { fields: [questions.projectId], references: [projects.id] }),
|
||||
task: one(tasks, { fields: [questions.taskId], references: [tasks.id] }),
|
||||
session: one(sessions, { fields: [questions.sessionId], references: [sessions.id] }),
|
||||
}));
|
||||
export const eventsRelations = relations(events, ({ one }) => ({
|
||||
project: one(projects, { fields: [events.projectId], references: [projects.id] }),
|
||||
task: one(tasks, { fields: [events.taskId], references: [tasks.id] }),
|
||||
session: one(sessions, { fields: [events.sessionId], references: [sessions.id] }),
|
||||
}));
|
||||
|
||||
5
packages/mcp/bin/peppa-mcp
Executable file
5
packages/mcp/bin/peppa-mcp
Executable file
@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
# Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves.
|
||||
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
|
||||
[ -f "$PEPPA_ROOT/.env" ] && set -a && . "$PEPPA_ROOT/.env" && set +a
|
||||
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@"
|
||||
@ -3,6 +3,13 @@
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"bin": { "peppa-mcp": "./bin/peppa-mcp" },
|
||||
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." },
|
||||
"dependencies": { "@peppa/db": "workspace:*", "@peppa/shared": "workspace:*" }
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "1.32.2",
|
||||
"@peppa/core": "workspace:*",
|
||||
"@peppa/db": "workspace:*",
|
||||
"@peppa/shared": "workspace:*",
|
||||
"zod": "4.6.7"
|
||||
}
|
||||
}
|
||||
|
||||
22
packages/mcp/scripts/smoke.ts
Normal file
22
packages/mcp/scripts/smoke.ts
Normal file
@ -0,0 +1,22 @@
|
||||
// Smoke test: spawns peppa-mcp in the given project dir and calls a few tools.
|
||||
// Usage: tsx packages/mcp/scripts/smoke.ts <project-dir> <task>
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const [dir = process.cwd(), task = "1"] = process.argv.slice(2);
|
||||
const bin = fileURLToPath(new URL("../bin/peppa-mcp", import.meta.url));
|
||||
const client = new Client({ name: "peppa-smoke", version: "0" });
|
||||
await client.connect(new StdioClientTransport({ command: bin, cwd: dir, env: process.env as Record<string, string> }));
|
||||
|
||||
const { tools } = await client.listTools();
|
||||
console.log("tools:", tools.map((t) => t.name).join(", "));
|
||||
for (const [name, args] of [
|
||||
["list_goals", {}],
|
||||
["list_tasks", {}],
|
||||
["get_task", { task }],
|
||||
] as const) {
|
||||
const r = await client.callTool({ name, arguments: args });
|
||||
console.log(`\n── ${name}${r.isError ? " (error)" : ""}\n${(r.content as Array<{ text: string }>)[0]!.text}`);
|
||||
}
|
||||
await client.close();
|
||||
39
packages/mcp/src/format.ts
Normal file
39
packages/mcp/src/format.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import type { TaskDetails, TaskStatus } from "@peppa/core";
|
||||
|
||||
const NEXT_STEP: Record<TaskStatus, string> = {
|
||||
backlog: "Начни с Proposal: создай OpenSpec change (workflow openspec-propose), затем update_task(status: proposing, openspec_change).",
|
||||
proposing: "Change начат: допиши недостающие артефакты, `openspec validate`, затем request_approval и закончи ход.",
|
||||
awaiting_approval: "Ждём решения PM по proposal. Ничего не реализуй — покажи резюме и закончи ход.",
|
||||
in_progress: "Одобрено. Apply: продолжай с первого невыполненного пункта tasks.md (workflow openspec-apply-change), report_progress по ходу.",
|
||||
review: "PR открыт. Проверь замечания в PR и доделай их.",
|
||||
done: "Задача завершена — ничего делать не нужно.",
|
||||
blocked: "Задача заблокирована — выясни причину в вопросах ниже или спроси PM через ask_pm.",
|
||||
};
|
||||
|
||||
export function formatTask(d: TaskDetails): string {
|
||||
const { task, goal } = d;
|
||||
const lines = [
|
||||
`# ${d.key}: ${task.title}`,
|
||||
"",
|
||||
`- Проект: ${d.project.name} (${d.project.key})`,
|
||||
`- Статус: **${task.status}**`,
|
||||
`- Цель: ${goal ? `#${goal.id} ${goal.title}` : "—"}`,
|
||||
`- OpenSpec change: ${task.openspecChange ? `\`openspec/changes/${task.openspecChange}/\`` : "ещё нет"}`,
|
||||
];
|
||||
if (task.prUrl) lines.push(`- PR: ${task.prUrl}`);
|
||||
lines.push("", "## Описание", "", task.description?.trim() || "_нет описания_");
|
||||
if (goal?.description) lines.push("", `## Цель #${goal.id}: ${goal.title}`, "", goal.description.trim());
|
||||
if (d.questions.length) {
|
||||
lines.push("", "## Вопросы к PM");
|
||||
for (const q of d.questions) {
|
||||
lines.push("", `- [${q.kind} #${q.id}] ${q.text}`, q.answer ? ` - Ответ (${q.answeredVia}): ${q.answer}` : " - _ожидает ответа_");
|
||||
}
|
||||
}
|
||||
const progress = d.recentEvents.filter((e) => e.type === "progress");
|
||||
if (progress.length) {
|
||||
lines.push("", "## Последний прогресс");
|
||||
for (const e of progress.slice(-5)) lines.push(`- ${e.createdAt.toISOString().slice(0, 16)} ${(e.payload as { text: string }).text}`);
|
||||
}
|
||||
lines.push("", "## Следующий шаг", "", NEXT_STEP[task.status]);
|
||||
return lines.join("\n");
|
||||
}
|
||||
@ -1,2 +1,157 @@
|
||||
// Peppa MCP server (stage 2): get_task, create_task, update_task_status, ask_pm, report_progress.
|
||||
console.log("@peppa/mcp: not implemented yet");
|
||||
// Peppa MCP server: gives Claude sessions inside a project access to its goals, tasks
|
||||
// and the PM. Runs over stdio; the project defaults to the repo's .peppa/project.json.
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import {
|
||||
askPm,
|
||||
createTask,
|
||||
findProjectFile,
|
||||
getProject,
|
||||
getTaskDetails,
|
||||
listGoals,
|
||||
listTasks,
|
||||
PeppaError,
|
||||
reportProgress,
|
||||
resolveTask,
|
||||
TASK_STATUSES,
|
||||
updateTask,
|
||||
} from "@peppa/core";
|
||||
import { createDb } from "@peppa/db";
|
||||
import { z } from "zod";
|
||||
import { formatTask } from "./format.ts";
|
||||
|
||||
const db = createDb();
|
||||
const projectFile = findProjectFile(process.env.PEPPA_PROJECT_DIR ?? process.cwd());
|
||||
const defaultKey = projectFile?.data.key;
|
||||
// Set by the runner for sessions it starts; absent for a manual `claude`.
|
||||
const sessionId = process.env.PEPPA_SESSION_ID ? Number(process.env.PEPPA_SESSION_ID) : undefined;
|
||||
|
||||
const server = new McpServer({ name: "peppa", version: "0.1.0" });
|
||||
|
||||
type Result = { content: Array<{ type: "text"; text: string }>; isError?: boolean };
|
||||
|
||||
function tool<S extends z.ZodRawShape>(
|
||||
name: string,
|
||||
description: string,
|
||||
inputSchema: S,
|
||||
run: (args: z.infer<z.ZodObject<S>>) => Promise<string>,
|
||||
) {
|
||||
server.registerTool(name, { description, inputSchema }, (async (args: z.infer<z.ZodObject<S>>): Promise<Result> => {
|
||||
try {
|
||||
return { content: [{ type: "text", text: await run(args) }] };
|
||||
} catch (e) {
|
||||
const msg = e instanceof PeppaError ? e.message : `Internal error: ${(e as Error).message}`;
|
||||
return { content: [{ type: "text", text: msg }], isError: true };
|
||||
}
|
||||
}) as never);
|
||||
}
|
||||
|
||||
const taskArg = z
|
||||
.string()
|
||||
.describe(`Task key like ${defaultKey ?? "PEP"}-42, or just the number for the current project`);
|
||||
const projectArg = z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(`Project key or slug; defaults to the current repo's project${defaultKey ? ` (${defaultKey})` : ""}`);
|
||||
|
||||
async function projectOrDefault(p?: string) {
|
||||
const k = p ?? defaultKey;
|
||||
if (!k) throw new PeppaError("No project given and no .peppa/project.json found in this repo");
|
||||
return getProject(db, k);
|
||||
}
|
||||
|
||||
tool("get_task", "Get a Peppa task: description, goal, status, OpenSpec change, PM Q&A and the next step to take. Call this first when the user names a task number.", { task: taskArg }, async ({ task }) =>
|
||||
formatTask(await getTaskDetails(db, await resolveTask(db, task, defaultKey))),
|
||||
);
|
||||
|
||||
tool(
|
||||
"list_tasks",
|
||||
"List tasks in a project, optionally filtered by status or goal.",
|
||||
{ project: projectArg, status: z.enum(TASK_STATUSES).optional(), goal_id: z.number().int().optional() },
|
||||
async ({ project, status, goal_id }) => {
|
||||
const p = await projectOrDefault(project);
|
||||
const rows = await listTasks(db, { projectId: p.id, goalId: goal_id, statuses: status ? [status] : undefined });
|
||||
if (!rows.length) return "No tasks.";
|
||||
return rows.map((t) => `- ${t.key} [${t.status}]${t.goalId ? ` (goal #${t.goalId})` : ""} ${t.title}`).join("\n");
|
||||
},
|
||||
);
|
||||
|
||||
tool("list_goals", "List the open top-level goals of a project.", { project: projectArg }, async ({ project }) => {
|
||||
const p = await projectOrDefault(project);
|
||||
const rows = await listGoals(db, p.id);
|
||||
if (!rows.length) return "No open goals.";
|
||||
return rows.map((g) => `- #${g.id} ${g.title}${g.description ? ` — ${g.description.split("\n")[0]}` : ""}`).join("\n");
|
||||
});
|
||||
|
||||
tool(
|
||||
"create_task",
|
||||
"Create a new task (e.g. follow-up work discovered outside the current change's scope). Link it to a goal when possible.",
|
||||
{
|
||||
title: z.string().min(3),
|
||||
description: z.string().optional(),
|
||||
goal_id: z.number().int().optional(),
|
||||
project: projectArg,
|
||||
},
|
||||
async ({ title, description, goal_id, project }) => {
|
||||
const p = await projectOrDefault(project);
|
||||
const ref = await createTask(db, { projectId: p.id, goalId: goal_id, title, description });
|
||||
return `Created ${ref.key}: ${title}`;
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"update_task",
|
||||
"Update a task's status, OpenSpec change name, PR URL, title or description.",
|
||||
{
|
||||
task: taskArg,
|
||||
status: z.enum(TASK_STATUSES).optional(),
|
||||
openspec_change: z.string().optional().describe("Change id under openspec/changes/, e.g. pep-42-add-auth"),
|
||||
pr_url: z.string().url().optional(),
|
||||
title: z.string().optional(),
|
||||
description: z.string().optional(),
|
||||
},
|
||||
async ({ task, status, openspec_change, pr_url, title, description }) => {
|
||||
const ref = await resolveTask(db, task, defaultKey);
|
||||
const t = await updateTask(db, ref, { status, openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
|
||||
return `${ref.key} updated: status=${t.status}${t.openspecChange ? `, change=${t.openspecChange}` : ""}${t.prUrl ? `, pr=${t.prUrl}` : ""}`;
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"request_approval",
|
||||
"Ask the PM to approve the OpenSpec proposal for a task. Sets status to awaiting_approval and notifies the PM (Telegram). End your turn afterwards — the decision arrives as the next user message.",
|
||||
{ task: taskArg, summary: z.string().min(10).describe("What, why, risks, open questions — readable on a phone") },
|
||||
async ({ task, summary }) => {
|
||||
const ref = await resolveTask(db, task, defaultKey);
|
||||
const q = await askPm(db, ref, { kind: "approval", text: summary, sessionId });
|
||||
return `Approval requested (#${q.id}); ${ref.key} is awaiting_approval. End your turn now and wait for the PM's reply.`;
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"ask_pm",
|
||||
"Ask the PM a question (delivered to Telegram). Use for decisions that change scope, behavior, data or need access/secrets. End your turn afterwards — the answer arrives as the next user message.",
|
||||
{
|
||||
task: taskArg,
|
||||
question: z.string().min(5).describe("One question, 1–2 sentences of context"),
|
||||
options: z.array(z.string()).max(6).optional().describe("Suggested answers, shown as buttons"),
|
||||
},
|
||||
async ({ task, question, options }) => {
|
||||
const ref = await resolveTask(db, task, defaultKey);
|
||||
const q = await askPm(db, ref, { kind: "question", text: question, options, sessionId });
|
||||
return `Question #${q.id} sent to the PM. End your turn now and wait for the answer.`;
|
||||
},
|
||||
);
|
||||
|
||||
tool(
|
||||
"report_progress",
|
||||
"Log a short progress note on a task (visible to the PM in the web UI / Telegram digest).",
|
||||
{ task: taskArg, text: z.string().min(3) },
|
||||
async ({ task, text }) => {
|
||||
const ref = await resolveTask(db, task, defaultKey);
|
||||
await reportProgress(db, ref, text, sessionId);
|
||||
return `Progress noted on ${ref.key}.`;
|
||||
},
|
||||
);
|
||||
|
||||
await server.connect(new StdioServerTransport());
|
||||
|
||||
797
pnpm-lock.yaml
generated
797
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -35,4 +35,5 @@ git -c user.name="Peppa" -c user.email="peppa@localhost" commit -qm "Bootstrap $
|
||||
git remote add origin "$REMOTE"
|
||||
git push -q -u origin main
|
||||
git remote set-url origin "$GITEA_URL/$OWNER/$SLUG.git"
|
||||
"$ROOT/packages/cli/bin/peppa" project add "$SLUG" "$KEY" "$NAME" --owner "$OWNER" --path "$DEST"
|
||||
echo "ready: $DEST ($GITEA_URL/$OWNER/$SLUG)"
|
||||
|
||||
10
scripts/install-bins.sh
Executable file
10
scripts/install-bins.sh
Executable file
@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
# Symlinks Peppa's CLIs (peppa, peppa-mcp, later peppa-hook) into ~/.local/bin.
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BIN="${PEPPA_BIN_DIR:-$HOME/.local/bin}"
|
||||
mkdir -p "$BIN"
|
||||
for f in "$ROOT"/packages/*/bin/*; do
|
||||
ln -sf "$f" "$BIN/$(basename "$f")"
|
||||
echo "linked $BIN/$(basename "$f")"
|
||||
done
|
||||
Loading…
Reference in New Issue
Block a user