feat: Phase1 完整交付——Web 看板(frontend-design) + MCP server(12 工具) + CLI/导入器

- web/: phosphor 调度台风格纯静态看板,审批闸内联 accept/reject(拒绝必填意见),WS 实时
- src/api/static.ts: 手写静态服务(路径穿越防护),daemon 接入
- src/mcp/: stdio MCP server,@modelcontextprotocol/sdk 1.29.0,12 工具薄封装 REST
- src/cli/: 零依赖 CLI(project/task/next/approvals/import-todo),旧 todo.json 导入器
- 实测: pangolin 18 条旧任务导入 45 条;端到端验证通过

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-06-12 21:23:08 +08:00
parent 3172718a94
commit c6e66baa19
11 changed files with 3219 additions and 8 deletions
+611
View File
@@ -0,0 +1,611 @@
#!/usr/bin/env node
/**
* maestro CLI — 通过 REST API 操作 maestrod(零新依赖,node:util parseArgs)。
*
* 子命令:
* project add <repoPath> [--name N] [--branch B] [--verify CMD] [--concurrency N]
* project list
* task list <projectIdOrName>
* task add <projectIdOrName> <title> --complexity hard|medium|easy [--parent ID] [--priority N]
* next <projectIdOrName>
* approvals [projectIdOrName]
* import-todo <todo.json 路径> --repo <repoPath> [--name N]
*
* 环境变量:MAESTRO_URL(默认 http://127.0.0.1:4517
*/
import { parseArgs, type ParseArgsConfig } from 'node:util';
import { readFileSync } from 'node:fs';
import { resolve, basename } from 'node:path';
import type { Project, Task } from '../model/types.js';
import { STATUS_LABEL, type TaskStatus } from '../model/status.js';
import { COMPLEXITY_LABEL, TIER_TO_COMPLEXITY, isComplexity, type Complexity } from '../model/complexity.js';
const BASE = process.env.MAESTRO_URL ?? 'http://127.0.0.1:4517';
const USAGE = `maestro — 多项目 TODO 管理与 Agent 执行系统 CLI
用法:
maestro project add <repoPath> [--name 名称] [--branch 分支] [--verify 命令] [--concurrency 并发数]
注册项目(name 缺省取目录名)
maestro project list
列出所有项目
maestro task list <项目id或名称>
树形列出项目任务(项目名支持模糊匹配)
maestro task add <项目id或名称> <标题> --complexity hard|medium|easy [--parent 父任务id] [--priority 优先级]
新建任务
maestro next <项目id或名称>
取下一个可执行任务
maestro approvals [项目id或名称]
列出待审批任务(不带参数 = 全部项目)
maestro import-todo <todo.json 路径> --repo <仓库路径> [--name 项目名]
新建项目并导入旧 todo skill 的数据(tier 1/2/3 → hard/medium/easy
maestro --help | help
显示本说明
环境变量:
MAESTRO_URL daemon 地址(默认 http://127.0.0.1:4517`;
// ---------- 基础工具 ----------
class ApiError extends Error {}
function fail(msg: string): never {
console.error(`错误:${msg}`);
process.exit(1);
}
async function api<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T> {
let res: Response;
try {
res = await fetch(`${BASE}${path}`, {
method,
headers: body === undefined ? undefined : { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
} catch {
console.error(`无法连接 maestro daemon${BASE})。`);
console.error('请先启动 maestrod:在 maestro 仓库目录执行 `npm run dev`');
console.error('若 daemon 跑在其他地址/端口,请设置 MAESTRO_URL 环境变量。');
process.exit(1);
}
const text = await res.text();
let data: unknown = null;
try {
data = text ? JSON.parse(text) : null;
} catch {
/* 非 JSON 响应 */
}
if (!res.ok) {
const msg = (data as { error?: string } | null)?.error ?? `HTTP ${res.status}`;
throw new ApiError(msg);
}
return data as T;
}
/** 中日韩等全角字符按宽度 2 计算,保证表格对齐 */
function displayWidth(s: string): number {
let w = 0;
for (const ch of s) {
w += /[ᄀ-ᅟ⺀-〾ぁ-㏿㐀-䶿一-鿿ꀀ-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/.test(ch) ? 2 : 1;
}
return w;
}
function pad(s: string, width: number): string {
const gap = width - displayWidth(s);
return gap > 0 ? s + ' '.repeat(gap) : s;
}
function printTable(headers: string[], rows: string[][]): void {
const widths = headers.map((h, i) => {
let w = displayWidth(h);
for (const r of rows) w = Math.max(w, displayWidth(r[i] ?? ''));
return w;
});
const line = (cells: string[]): string => cells.map((c, i) => pad(c, widths[i])).join(' ');
console.log(line(headers));
console.log(widths.map((w) => '-'.repeat(w)).join(' '));
for (const r of rows) console.log(line(r));
}
function parseCmdArgs(
rest: string[],
options: NonNullable<ParseArgsConfig['options']>,
): { values: Record<string, string | boolean | undefined>; positionals: string[] } {
try {
const { values, positionals } = parseArgs({ args: rest, options, allowPositionals: true });
return { values: values as Record<string, string | boolean | undefined>, positionals };
} catch (e) {
fail(`参数不合法:${(e as Error).message}\n\n${USAGE}`);
}
}
async function resolveProject(idOrName: string): Promise<Project> {
const projects = await api<Project[]>('GET', '/api/projects');
const byId = projects.find((p) => p.id === idOrName);
if (byId) return byId;
let matched = projects.filter((p) => p.name === idOrName);
if (matched.length === 0) {
const lower = idOrName.toLowerCase();
matched = projects.filter((p) => p.name.toLowerCase().includes(lower));
}
if (matched.length === 1) return matched[0];
if (matched.length > 1) {
fail(
`项目「${idOrName}」匹配到 ${matched.length} 个,请用更精确的名称或直接用 id\n` +
matched.map((p) => ` - ${p.name} (${p.id})`).join('\n'),
);
}
fail(`找不到项目「${idOrName}」。可先用 \`maestro project list\` 查看全部项目。`);
}
// ---------- project ----------
async function cmdProjectAdd(rest: string[]): Promise<void> {
const { values, positionals } = parseCmdArgs(rest, {
name: { type: 'string' },
branch: { type: 'string' },
verify: { type: 'string' },
concurrency: { type: 'string' },
});
const repoArg = positionals[0];
if (!repoArg) fail('用法:maestro project add <repoPath> [--name N] [--branch B] [--verify CMD] [--concurrency N]');
const repoPath = resolve(repoArg);
const name = (values.name as string | undefined) ?? basename(repoPath);
const concurrency = values.concurrency === undefined ? undefined : Number(values.concurrency);
if (concurrency !== undefined && (!Number.isInteger(concurrency) || concurrency < 1)) {
fail('--concurrency 必须是 >=1 的整数');
}
const p = await api<Project>('POST', '/api/projects', {
name,
repoPath,
defaultBranch: values.branch as string | undefined,
verifyCmd: values.verify as string | undefined,
concurrency,
});
console.log(`已注册项目「${p.name}」(${p.id})`);
console.log(` repo: ${p.repoPath} · 分支: ${p.defaultBranch} · 并发: ${p.concurrency} · verify: ${p.verifyCmd ?? '无'}`);
}
async function cmdProjectList(): Promise<void> {
const projects = await api<Project[]>('GET', '/api/projects');
if (projects.length === 0) {
console.log('暂无项目。用 `maestro project add <repoPath>` 注册一个。');
return;
}
printTable(
['id', 'name', 'repoPath', 'status'],
projects.map((p) => [p.id, p.name, p.repoPath, p.status]),
);
}
// ---------- task ----------
function taskLine(t: Task): string {
const deps = t.deps.length ? ` deps:${t.deps.length}` : '';
return `[${COMPLEXITY_LABEL[t.complexity]}·${STATUS_LABEL[t.status]}] ${t.title}${deps} (${t.id})`;
}
function printTaskTree(tasks: Task[]): void {
const byParent = new Map<string | null, Task[]>();
for (const t of tasks) {
const key = t.parentId;
const list = byParent.get(key) ?? [];
list.push(t);
byParent.set(key, list);
}
const sortFn = (a: Task, b: Task): number => b.priority - a.priority || a.createdAt.localeCompare(b.createdAt);
const walk = (parentId: string | null, indent: string): void => {
const list = (byParent.get(parentId) ?? []).sort(sortFn);
for (const t of list) {
console.log(`${indent}- ${taskLine(t)}`);
walk(t.id, indent + ' ');
}
};
walk(null, '');
}
async function cmdTaskList(rest: string[]): Promise<void> {
const { positionals } = parseCmdArgs(rest, {});
if (!positionals[0]) fail('用法:maestro task list <项目id或名称>');
const project = await resolveProject(positionals[0]);
const tasks = await api<Task[]>('GET', `/api/projects/${project.id}/tasks`);
console.log(`项目「${project.name}」(${project.id}) · 共 ${tasks.length} 条任务\n`);
if (tasks.length === 0) {
console.log('(暂无任务)');
return;
}
printTaskTree(tasks);
}
async function cmdTaskAdd(rest: string[]): Promise<void> {
const { values, positionals } = parseCmdArgs(rest, {
complexity: { type: 'string' },
parent: { type: 'string' },
priority: { type: 'string' },
});
const projectArg = positionals[0];
const title = positionals.slice(1).join(' ').trim();
if (!projectArg || !title) {
fail('用法:maestro task add <项目id或名称> <标题> --complexity hard|medium|easy [--parent ID] [--priority N]');
}
if (!isComplexity(values.complexity)) fail('--complexity 必填,且只能是 hard | medium | easy');
const priority = values.priority === undefined ? undefined : Number(values.priority);
if (priority !== undefined && !Number.isFinite(priority)) fail('--priority 必须是数字');
const project = await resolveProject(projectArg);
const t = await api<Task>('POST', `/api/projects/${project.id}/tasks`, {
title,
complexity: values.complexity,
parentId: values.parent as string | undefined,
priority,
});
console.log(`已创建任务 ${taskLine(t)}`);
}
// ---------- next / approvals ----------
async function cmdNext(rest: string[]): Promise<void> {
const { positionals } = parseCmdArgs(rest, {});
if (!positionals[0]) fail('用法:maestro next <项目id或名称>');
const project = await resolveProject(positionals[0]);
const r = await api<Task | { next: null }>('GET', `/api/projects/${project.id}/next`);
if (!r || !('id' in r)) {
console.log(`项目「${project.name}」当前没有可执行任务(叶子 + ready + 依赖满足)。`);
return;
}
console.log(`下一个可执行任务:`);
console.log(` ${taskLine(r)}`);
}
async function cmdApprovals(rest: string[]): Promise<void> {
const { positionals } = parseCmdArgs(rest, {});
let query = '';
let scope = '全部项目';
if (positionals[0]) {
const project = await resolveProject(positionals[0]);
query = `?projectId=${encodeURIComponent(project.id)}`;
scope = `项目「${project.name}`;
}
const tasks = await api<Task[]>('GET', `/api/approvals${query}`);
if (tasks.length === 0) {
console.log(`${scope}当前没有待审批任务。`);
return;
}
const projects = await api<Project[]>('GET', '/api/projects');
const nameOf = new Map(projects.map((p) => [p.id, p.name]));
console.log(`${scope}待审批任务 ${tasks.length} 条:\n`);
printTable(
['闸', '复杂度', '标题', '任务id', '项目'],
tasks.map((t) => [
STATUS_LABEL[t.status],
COMPLEXITY_LABEL[t.complexity],
t.title,
t.id,
nameOf.get(t.projectId) ?? t.projectId,
]),
);
}
// ---------- import-todo ----------
interface OldGate {
kind?: string | null;
note?: string | null;
ref?: string | null;
approval?: string | null;
}
interface OldSub {
sid: string;
title?: string;
tier?: number | null;
deps?: string[];
status?: string;
}
interface OldItem {
id: number;
title?: string;
desc?: string | null;
level?: string | null;
tier?: number | null;
tags?: string[];
status?: string;
done?: boolean;
version?: string | null;
subtasks?: OldSub[];
gate?: OldGate | null;
reject_reason?: string | null;
}
interface OldDb {
meta?: { title?: string };
items?: OldItem[];
}
type OldStatus = 'open' | 'doing' | 'done' | 'accepted';
const OLD_STATUS_LABEL: Record<OldStatus, string> = {
open: '待开始',
doing: '开发中',
done: '待验收',
accepted: '已验收',
};
interface ImportStats {
total: number;
byComplexity: Record<Complexity, number>;
done: number;
skipped: number;
warnings: string[];
}
function oldStatusOf(raw: string | undefined, doneFlag: boolean | undefined): OldStatus {
if (raw === 'open' || raw === 'doing' || raw === 'done' || raw === 'accepted') return raw;
return doneFlag ? 'accepted' : 'open';
}
function complexityOfTier(tier: number | null | undefined, label: string, stats: ImportStats): Complexity {
const c = tier == null ? undefined : TIER_TO_COMPLEXITY[tier];
if (c) return c;
stats.warnings.push(`${label} 缺少有效 tier${tier ?? '无'}),按 medium 导入`);
return 'medium';
}
function priorityOfLevel(level: string | null | undefined): number {
if (level === 'high') return 2;
if (level === 'mid') return 1;
return 0;
}
/** 旧 item 的描述性字段合成产出内容(plan/spec/operations */
function buildImportNote(item: OldItem, st: OldStatus, extra: string[] = []): string {
const lines = [`【从旧 todo 导入】原 #${item.id} · 原状态:${st}${OLD_STATUS_LABEL[st]}`];
if (st === 'doing') lines.push('注:导入前处于「开发中」,导入后回到初始状态,需按新流程重新推进。');
for (const l of extra) lines.push(l);
if (item.desc) lines.push('', item.desc);
if (item.tags?.length) lines.push('', `标签:${item.tags.join(' / ')}`);
if (item.level) lines.push(`原重要度:${item.level}`);
if (item.gate && (item.gate.note || item.gate.ref)) {
const ref = item.gate.ref ? `(详见 ${item.gate.ref}` : '';
lines.push('', `原方案/改动说明(approval=${item.gate.approval ?? '无'}):${item.gate.note ?? ''}${ref}`);
}
if (item.reject_reason) lines.push(`原拒绝原因:${item.reject_reason}`);
if (item.version) lines.push(`原验收版本:${item.version}`);
return lines.join('\n');
}
const PRODUCE_PATH: Record<Complexity, 'plan' | 'spec' | 'operations'> = {
hard: 'plan',
medium: 'spec',
easy: 'operations',
};
async function setProduce(taskId: string, complexity: Complexity, content: string): Promise<void> {
const field = PRODUCE_PATH[complexity];
await api('POST', `/api/tasks/${taskId}/${field}`, { [field]: content });
}
async function doTransition(taskId: string, to: TaskStatus): Promise<void> {
await api('POST', `/api/tasks/${taskId}/transition`, { to });
}
async function doAccept(taskId: string): Promise<void> {
await api('POST', `/api/tasks/${taskId}/decide`, { action: 'accept', actor: 'importer' });
}
/**
* 把非 Hard 容器任务沿合法路径推到 done:
* easy: ready → queued → executing → exec_review → accept(done)
* medium: speccing → spec_review → accept(ready) → queued → executing → exec_review → accept(done)
* 推不动时记 warning、保留现状,返回 false。
*/
async function pushLeafToDone(taskId: string, complexity: Complexity, label: string, stats: ImportStats): Promise<boolean> {
try {
if (complexity === 'medium') {
await doTransition(taskId, 'spec_review');
await doAccept(taskId); // → ready
}
await doTransition(taskId, 'queued');
await doTransition(taskId, 'executing');
await doTransition(taskId, 'exec_review');
await doAccept(taskId); // → done
stats.done += 1;
return true;
} catch (e) {
stats.warnings.push(`${label} 推进 done 失败:${(e as Error).message}(已保留当前状态)`);
return false;
}
}
/**
* Hard 容器推进:analyzing → plan_review → accept(decomposed)。
* 子任务全部 done(或无子任务,已在 plan 注明)时再 decomposed → done。
*/
async function pushHardContainer(
taskId: string,
label: string,
hasChildren: boolean,
allChildrenDone: boolean,
stats: ImportStats,
): Promise<void> {
try {
await doTransition(taskId, 'plan_review');
await doAccept(taskId); // → decomposed
if (!hasChildren || allChildrenDone) {
await doTransition(taskId, 'done');
stats.done += 1;
} else {
stats.warnings.push(`${label} 原状态为已完成,但子任务未能全部推到 done,容器停在 decomposed`);
}
} catch (e) {
stats.warnings.push(`${label} 推进 done 失败:${(e as Error).message}(已保留当前状态)`);
}
}
async function importItem(projectId: string, item: OldItem, stats: ImportStats): Promise<void> {
const label = `旧 #${item.id}${item.title ?? '?'}`;
if (!item.title) {
stats.skipped += 1;
stats.warnings.push(`旧 #${item.id} 缺少 title,已跳过`);
return;
}
const st = oldStatusOf(item.status, item.done);
const complexity = complexityOfTier(item.tier, label, stats);
const subs = item.subtasks ?? [];
const isDone = st === 'done' || st === 'accepted';
// 1) 建父任务
const task = await api<Task>('POST', `/api/projects/${projectId}/tasks`, {
title: item.title,
complexity,
priority: priorityOfLevel(item.level),
});
stats.total += 1;
stats.byComplexity[complexity] += 1;
// 2) 写产出字段(hard→plan / medium→spec / easy→operations
const extra: string[] = [];
if (isDone && complexity === 'hard' && subs.length === 0) {
extra.push('注:原任务已完成且无子任务,导入时容器直接推到 done。');
}
await setProduce(task.id, complexity, buildImportNote(item, st, extra));
// 3) 建子任务(sid 依赖 → 新任务 id)
const sidToId = new Map<string, string>();
const childPlan: Array<{ id: string; complexity: Complexity; oldStatus: string; label: string }> = [];
for (const sub of subs) {
const subLabel = `旧子任务 ${sub.sid}${sub.title ?? '?'}`;
if (!sub.title) {
stats.skipped += 1;
stats.warnings.push(`${subLabel} 缺少 title,已跳过`);
continue;
}
const subComplexity = complexityOfTier(sub.tier, subLabel, stats);
const deps: string[] = [];
for (const dep of sub.deps ?? []) {
const depId = sidToId.get(dep.toUpperCase());
if (depId) deps.push(depId);
else stats.warnings.push(`${subLabel} 的依赖 ${dep} 未找到对应任务,已忽略该依赖`);
}
const subStatus = sub.status === 'accepted' ? 'done' : (sub.status ?? 'open');
const child = await api<Task>('POST', `/api/projects/${projectId}/tasks`, {
title: sub.title,
complexity: subComplexity,
parentId: task.id,
deps,
});
sidToId.set(sub.sid.toUpperCase(), child.id);
stats.total += 1;
stats.byComplexity[subComplexity] += 1;
const subNote = [
`【从旧 todo 导入】原子任务 ${sub.sid}(父:旧 #${item.id})· 原状态:${subStatus}`,
subStatus === 'doing' ? '注:导入前处于「开发中」,导入后回到初始状态。' : '',
].filter(Boolean).join('\n');
await setProduce(child.id, subComplexity, subNote);
childPlan.push({ id: child.id, complexity: subComplexity, oldStatus: subStatus, label: subLabel });
}
// 4) 先推子任务,再推父任务
let allChildrenDone = childPlan.length > 0;
for (const c of childPlan) {
if (c.oldStatus === 'done') {
let ok: boolean;
if (c.complexity === 'hard') {
// 已完成的 hard 子任务(无下级)按容器路径收口
await pushHardContainer(c.id, c.label, false, true, stats);
const cur = await api<Task>('GET', `/api/tasks/${c.id}`);
ok = cur.status === 'done';
} else {
ok = await pushLeafToDone(c.id, c.complexity, c.label, stats);
}
if (!ok) allChildrenDone = false;
} else {
allChildrenDone = false; // open/doing:建完即停
}
}
if (!isDone) return; // open / doing:建完即停(doing 已在产出里备注)
if (complexity === 'hard') {
await pushHardContainer(task.id, label, childPlan.length > 0, allChildrenDone, stats);
} else {
await pushLeafToDone(task.id, complexity, label, stats);
}
}
async function cmdImportTodo(rest: string[]): Promise<void> {
const { values, positionals } = parseCmdArgs(rest, {
repo: { type: 'string' },
name: { type: 'string' },
});
const file = positionals[0];
if (!file || !values.repo) {
fail('用法:maestro import-todo <todo.json 路径> --repo <仓库路径> [--name 项目名]');
}
const filePath = resolve(file);
let db: OldDb;
try {
db = JSON.parse(readFileSync(filePath, 'utf8')) as OldDb;
} catch (e) {
fail(`读取 ${filePath} 失败:${(e as Error).message}`);
}
const items = db.items ?? [];
if (!Array.isArray(items)) fail(`${filePath} 不是合法的旧 todo.json(缺少 items 数组)`);
const repoPath = resolve(values.repo as string);
const name = (values.name as string | undefined) ?? basename(repoPath);
const project = await api<Project>('POST', '/api/projects', { name, repoPath });
console.log(`已创建项目「${project.name}」(${project.id}),开始导入 ${items.length} 条旧任务…\n`);
const stats: ImportStats = {
total: 0,
byComplexity: { hard: 0, medium: 0, easy: 0 },
done: 0,
skipped: 0,
warnings: [],
};
for (const item of items) {
await importItem(project.id, item, stats);
}
console.log('导入完成:');
console.log(
` 共导入 ${stats.total} 条任务(hard ${stats.byComplexity.hard} / medium ${stats.byComplexity.medium} / easy ${stats.byComplexity.easy}`,
);
console.log(` 推到 done${stats.done} 条 · 跳过:${stats.skipped} 条 · 警告:${stats.warnings.length}`);
for (const w of stats.warnings) console.log(`${w}`);
console.log(`\n查看结果:maestro task list ${project.name}`);
}
// ---------- 入口 ----------
async function main(): Promise<void> {
const argv = process.argv.slice(2);
const cmd = argv[0];
if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
console.log(USAGE);
return;
}
if (cmd === 'project') {
const sub = argv[1];
if (sub === 'add') return cmdProjectAdd(argv.slice(2));
if (sub === 'list') return cmdProjectList();
fail(`未知子命令:project ${sub ?? ''}\n\n${USAGE}`);
}
if (cmd === 'task') {
const sub = argv[1];
if (sub === 'list') return cmdTaskList(argv.slice(2));
if (sub === 'add') return cmdTaskAdd(argv.slice(2));
fail(`未知子命令:task ${sub ?? ''}\n\n${USAGE}`);
}
if (cmd === 'next') return cmdNext(argv.slice(1));
if (cmd === 'approvals') return cmdApprovals(argv.slice(1));
if (cmd === 'import-todo') return cmdImportTodo(argv.slice(1));
fail(`未知命令:${cmd}\n\n${USAGE}`);
}
main().catch((err) => {
if (err instanceof ApiError) fail(err.message);
console.error('执行失败:', err);
process.exit(1);
});