feat: Phase2 完整管线——score 调度 + 自动复审 + 模型分级 + 归档与详情
调度: - model/scoring.ts: score = 自身分(P0=3/P1=2/P2=1) + 已完成依赖分(链条惯性) + 等待解锁的 blocked 任务分(解锁加权),编排器与 nextExecutable 同一打分 - createTask 校验 deps 存在且同项目(依赖图天然无环) - daemon 重启中断自愈: executing 任务标 failed run 后重新入队(reconcileInterrupted) 执行管线: - executor/cc.ts: 公共 headless CC 执行器(转录/超时/模型回退重试) - executor/reviewer.ts: 执行后自动复审(只读 CC 审 diff),固定模板 summary (做了什么/怎么做/测试/CodeReview/安全Review/结论) + VERDICT 解析 - executor/models.ts: 按复杂度选模型(easy→sonnet/medium→opus/hard→fable5), env 可覆盖、project.model 最优先、不可用自动回退链 - runner: 测试/构建命令白名单(npm/go/shellcheck/make/pytest),prompt 要求实跑测试 - TaskResult 加 summary/verdict; RunKind 加 reviewer - 容器收口: 已拆解 Hard 子任务全 done → 容器自动 done(afterDone 逐级向上) 看板: - 五徽章组(待审批/待执行/执行中/被阻塞/总量,hover 展开,均不含已完成) - 归档区: 深度1整树完成沉底,时间倒序分页(10/20/50/100 chip 选择) - 归档详情对话框: 全属性/执行历史与时长/审批记录/状态流转时间线(含相关人或事) - Agent 面板显示调度模式 + 各复杂度实际模型 - 结果闸展示复审 summary + 建议通过/拒绝徽章 - 筛选修复(组选与单选分离、已拆解移出进行中)、同步按钮收进配置面板、 保存配置自动收起、预览全宽、被依赖阻塞→被阻塞 - API: GET /api/tasks/:id/events(任务级事件时间线)、/api/agents 带 scheduling/models 测试: 49/49(新增 scoring/复审/模型/容器收口/deps 校验/中断恢复) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
import { createWriteStream, mkdirSync, type WriteStream } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { query } from '@anthropic-ai/claude-agent-sdk';
|
||||
import { isModelError, pickFallbackModel } from './models.js';
|
||||
|
||||
/** 转录目录:<MAESTRO_DATA_DIR 或 ~/.maestro>/transcripts */
|
||||
export function transcriptDir(): string {
|
||||
return join(process.env.MAESTRO_DATA_DIR ?? join(homedir(), '.maestro'), 'transcripts');
|
||||
}
|
||||
|
||||
export interface CCOptions {
|
||||
prompt: string;
|
||||
cwd: string;
|
||||
model: string;
|
||||
runId: string;
|
||||
maxTurns: number;
|
||||
timeoutMs: number;
|
||||
allowedTools: string[];
|
||||
permissionMode?: 'acceptEdits' | 'default';
|
||||
}
|
||||
|
||||
export interface CCResult {
|
||||
ok: boolean;
|
||||
finalText: string; // SDK result 消息的文本(失败时为 '')
|
||||
sessionId: string | null;
|
||||
transcriptRef: string;
|
||||
modelUsed: string; // 实际使用的模型(发生回退时为回退模型)
|
||||
fellBack: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface AttemptResult {
|
||||
ok: boolean;
|
||||
finalText: string;
|
||||
sessionId: string | null;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 单次 headless CC 会话:流式消息逐行写 transcript,不抛错(失败折叠进 error) */
|
||||
async function attempt(opts: CCOptions, model: string, out: WriteStream): Promise<AttemptResult> {
|
||||
let sessionId: string | null = null;
|
||||
let finalText = '';
|
||||
let resultOk = false;
|
||||
let resultError: string | undefined;
|
||||
let sawResult = false;
|
||||
|
||||
const abort = new AbortController();
|
||||
const killer = setTimeout(() => abort.abort(new Error('执行超时')), opts.timeoutMs);
|
||||
|
||||
try {
|
||||
const q = query({
|
||||
prompt: opts.prompt,
|
||||
options: {
|
||||
cwd: opts.cwd,
|
||||
permissionMode: opts.permissionMode ?? 'default',
|
||||
maxTurns: opts.maxTurns,
|
||||
settingSources: ['project'], // 读项目 CLAUDE.md / settings,不读用户全局
|
||||
abortController: abort,
|
||||
model,
|
||||
allowedTools: opts.allowedTools,
|
||||
},
|
||||
});
|
||||
|
||||
for await (const message of q) {
|
||||
out.write(`${JSON.stringify(message)}\n`);
|
||||
const sid = (message as { session_id?: unknown }).session_id;
|
||||
if (typeof sid === 'string' && sid) sessionId = sid;
|
||||
if (message.type === 'result') {
|
||||
sawResult = true;
|
||||
if (message.subtype === 'success' && !message.is_error) {
|
||||
resultOk = true;
|
||||
const txt = (message as { result?: unknown }).result;
|
||||
if (typeof txt === 'string') finalText = txt;
|
||||
} else {
|
||||
const errs = 'errors' in message && Array.isArray(message.errors) ? message.errors.join('; ') : '';
|
||||
resultError = `Claude Code 结束于 ${message.subtype}${errs ? `:${errs}` : ''}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!sawResult && !resultError) resultError = '未收到 result 消息(会话异常结束)';
|
||||
} catch (e) {
|
||||
resultError = `Claude Code 执行异常:${(e as Error).message}`;
|
||||
resultOk = false;
|
||||
} finally {
|
||||
clearTimeout(killer);
|
||||
}
|
||||
|
||||
if (!resultOk) return { ok: false, finalText: '', sessionId, error: resultError ?? '未知错误' };
|
||||
return { ok: true, finalText, sessionId };
|
||||
}
|
||||
|
||||
/**
|
||||
* 跑一次 headless CC(runner / reviewer 公用)。
|
||||
* 模型可用性兜底:失败且错误信息像模型不可用(not_found/invalid/permission 等)时,
|
||||
* 自动用回退链取一个 ≠ 原模型的模型在同一 run 内重试一次;回退记入 transcript 与 finalText。
|
||||
*/
|
||||
export async function runClaude(opts: CCOptions): Promise<CCResult> {
|
||||
const dir = transcriptDir();
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const transcriptRef = join(dir, `${opts.runId}.jsonl`);
|
||||
const out = createWriteStream(transcriptRef, { flags: 'a' });
|
||||
|
||||
try {
|
||||
let r = await attempt(opts, opts.model, out);
|
||||
let modelUsed = opts.model;
|
||||
let fellBack = false;
|
||||
|
||||
if (!r.ok && r.error && isModelError(r.error)) {
|
||||
const fb = pickFallbackModel(opts.model);
|
||||
if (fb) {
|
||||
out.write(`${JSON.stringify({ type: 'maestro.model_fallback', from: opts.model, to: fb, reason: r.error })}\n`);
|
||||
r = await attempt(opts, fb, out);
|
||||
modelUsed = fb;
|
||||
fellBack = true;
|
||||
}
|
||||
}
|
||||
|
||||
const note = fellBack && r.ok ? `\n\n[模型回退] 原模型 ${opts.model} 不可用,实际使用 ${modelUsed}` : '';
|
||||
return {
|
||||
ok: r.ok,
|
||||
finalText: r.finalText + note,
|
||||
sessionId: r.sessionId,
|
||||
transcriptRef,
|
||||
modelUsed,
|
||||
fellBack,
|
||||
...(r.error ? { error: fellBack ? `${r.error}(已回退至 ${modelUsed} 重试)` : r.error } : {}),
|
||||
};
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => out.end(resolve));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { Project, Task } from '../model/types.js';
|
||||
import type { Complexity } from '../model/complexity.js';
|
||||
|
||||
/** 角色:executor(执行改动)/ reviewer(执行后复审) */
|
||||
export type ModelRole = 'executor' | 'reviewer';
|
||||
|
||||
/** 模型不可用时的回退链(按序取第一个 ≠ 失败模型的,同一 run 内只重试一次) */
|
||||
export const MODEL_FALLBACK_CHAIN = ['claude-opus-4-8', 'claude-sonnet-4-6'] as const;
|
||||
|
||||
/** 复杂度 → [env 覆盖变量名, 默认模型] */
|
||||
const MODEL_TABLE: Record<ModelRole, Record<Complexity, [env: string, fallback: string]>> = {
|
||||
executor: {
|
||||
easy: ['MAESTRO_MODEL_EASY', 'claude-sonnet-4-6'],
|
||||
medium: ['MAESTRO_MODEL_MEDIUM', 'claude-opus-4-8'],
|
||||
hard: ['MAESTRO_MODEL_HARD', 'claude-fable-5'],
|
||||
},
|
||||
reviewer: {
|
||||
easy: ['MAESTRO_MODEL_REVIEW_EASY', 'claude-sonnet-4-6'],
|
||||
medium: ['MAESTRO_MODEL_REVIEW_MEDIUM', 'claude-opus-4-8'],
|
||||
hard: ['MAESTRO_MODEL_REVIEW_HARD', 'claude-opus-4-8'],
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 按角色 + 复杂度选模型:
|
||||
* 1. project.model 设了就最优先(executor/reviewer 都用它)
|
||||
* 2. 否则查 env 覆盖(MAESTRO_MODEL_* / MAESTRO_MODEL_REVIEW_*)
|
||||
* 3. 否则按复杂度取默认
|
||||
*/
|
||||
export function pickModel(task: Task, project: Project, role: ModelRole): string {
|
||||
if (project.model) return project.model;
|
||||
const [env, fallback] = MODEL_TABLE[role][task.complexity];
|
||||
const override = process.env[env]?.trim();
|
||||
return override || fallback;
|
||||
}
|
||||
|
||||
/** 看板展示用:当前项目 executor 各复杂度实际会用的模型(含 project.model / env 覆盖解析) */
|
||||
export function resolvedExecutorModels(project: Project): Record<Complexity, string> {
|
||||
const out = {} as Record<Complexity, string>;
|
||||
for (const c of ['easy', 'medium', 'hard'] as Complexity[]) {
|
||||
if (project.model) { out[c] = project.model; continue; }
|
||||
const [env, fallback] = MODEL_TABLE.executor[c];
|
||||
out[c] = process.env[env]?.trim() || fallback;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 错误信息是否像“模型不可用”(not_found / invalid / permission 等模式 + 提到 model) */
|
||||
export function isModelError(msg: string): boolean {
|
||||
if (!/model/i.test(msg)) return false;
|
||||
return /not[_\s-]?found|invalid|permission|forbidden|unauthorized|unavailable|unknown|unsupported|does not exist|no access|404|403/i.test(msg);
|
||||
}
|
||||
|
||||
/** 回退链里取第一个与失败模型不同的;链上全相同(不可能两项都等)则 null */
|
||||
export function pickFallbackModel(failedModel: string): string | null {
|
||||
for (const m of MODEL_FALLBACK_CHAIN) {
|
||||
if (m !== failedModel) return m;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { Project, Task, ReviewVerdict } from '../model/types.js';
|
||||
import type { WorktreeInfo } from './worktree.js';
|
||||
import { runClaude } from './cc.js';
|
||||
import { pickModel } from './models.js';
|
||||
|
||||
export interface ReviewResult {
|
||||
summary: string; // 最终文本去掉 VERDICT 行(markdown)
|
||||
verdict: ReviewVerdict | null; // 解析不到 = null
|
||||
transcriptRef: string | null;
|
||||
sessionId: string | null;
|
||||
}
|
||||
|
||||
/** 复审函数签名(orchestrator 依赖注入点;测试传 mock,生产传 reviewTask)。失败时抛错,由 orchestrator 兜底。 */
|
||||
export type ReviewerFn = (
|
||||
task: Task,
|
||||
project: Project,
|
||||
worktree: WorktreeInfo,
|
||||
runId: string,
|
||||
executorReport: string,
|
||||
) => Promise<ReviewResult>;
|
||||
|
||||
const REVIEW_MAX_TURNS = 40;
|
||||
const REVIEW_TIMEOUT_MS = 15 * 60_000; // 15min
|
||||
|
||||
/** 组装复审提示词:任务说明 + 执行者自述 + 审 diff + 固定模板输出 */
|
||||
export function buildReviewPrompt(task: Task, project: Project, worktree: WorktreeInfo, executorReport: string): string {
|
||||
const body = task.operations ?? task.spec ?? task.plan ?? '';
|
||||
return [
|
||||
`# 复审任务:${task.title}`,
|
||||
`任务 ID:${task.id}`,
|
||||
'',
|
||||
'你是独立的代码复审员。一个执行 agent 刚在当前 git worktree 完成了下述任务,请你复审它的改动。',
|
||||
'',
|
||||
'## 任务原始要求',
|
||||
body || '(无详细说明,以标题为准)',
|
||||
'',
|
||||
'## 执行者自述',
|
||||
executorReport.trim() || '(执行者未留下自述)',
|
||||
'',
|
||||
'## 复审要求',
|
||||
`- 用 \`git diff ${project.defaultBranch}...${worktree.branch}\` 查看全部改动,结合 git log / git show 与源码阅读核对。`,
|
||||
'- 你只有只读权限:不得修改任何文件,不得执行除 git diff/log/show/status 之外的命令。',
|
||||
'- 核对执行者自述与实际 diff 是否一致,注意有没有声称做了但实际没做的内容。',
|
||||
'',
|
||||
'## 输出格式(最终回复必须严格按此模板,markdown)',
|
||||
'```',
|
||||
'## 做了什么',
|
||||
'## 怎么做的',
|
||||
'## 测试情况(有没有测试、跑了没有、结果如何;无测试体系则说明为什么不适用)',
|
||||
'## Code Review(正确性/可维护性问题,逐条带文件:行号)',
|
||||
'## 安全 Review(凭证泄露/注入/权限/危险操作;本项目还需检查 UI 文案红线词与生产部署安全)',
|
||||
'## 结论',
|
||||
'(建议通过 或 建议拒绝;拒绝必须给出理由与改进方案)',
|
||||
'VERDICT: approve|reject',
|
||||
'```',
|
||||
'- 最后一行必须是单独一行 `VERDICT: approve` 或 `VERDICT: reject`(机器解析用,不要带其他内容)。',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 从复审最终文本解析 VERDICT 行:
|
||||
* - verdict = 最后一个匹配 `VERDICT: approve|reject` 的行(解析不到 = null)
|
||||
* - summary = 去掉所有 VERDICT 行后的文本(trim)
|
||||
*/
|
||||
export function parseVerdict(text: string): { summary: string; verdict: ReviewVerdict | null } {
|
||||
let verdict: ReviewVerdict | null = null;
|
||||
const kept: string[] = [];
|
||||
for (const line of text.split('\n')) {
|
||||
const m = line.match(/^\s*VERDICT:\s*(approve|reject)\s*$/i);
|
||||
if (m) {
|
||||
verdict = m[1].toLowerCase() as ReviewVerdict;
|
||||
continue;
|
||||
}
|
||||
kept.push(line);
|
||||
}
|
||||
return { summary: kept.join('\n').trim(), verdict };
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行后自动复审:在 worktree 内再起一个只读 headless CC,审 diff 并产出固定模板 summary + verdict。
|
||||
* 转录写 <transcriptDir>/<runId>.jsonl。失败抛错(orchestrator 兜底,不挡任务)。
|
||||
*/
|
||||
export async function reviewTask(
|
||||
task: Task,
|
||||
project: Project,
|
||||
worktree: WorktreeInfo,
|
||||
runId: string,
|
||||
executorReport: string,
|
||||
): Promise<ReviewResult> {
|
||||
const model = pickModel(task, project, 'reviewer');
|
||||
const cc = await runClaude({
|
||||
prompt: buildReviewPrompt(task, project, worktree, executorReport),
|
||||
cwd: worktree.dir,
|
||||
model,
|
||||
runId,
|
||||
maxTurns: REVIEW_MAX_TURNS,
|
||||
timeoutMs: REVIEW_TIMEOUT_MS,
|
||||
permissionMode: 'default',
|
||||
// 只读白名单:可读文件 + 仅 git 只读命令,不可改文件
|
||||
allowedTools: [
|
||||
'Read', 'Grep', 'Glob',
|
||||
'Bash(git diff:*)', 'Bash(git log:*)', 'Bash(git show:*)', 'Bash(git status:*)',
|
||||
],
|
||||
});
|
||||
|
||||
if (!cc.ok) throw new Error(cc.error ?? '复审执行失败');
|
||||
if (!cc.finalText.trim()) throw new Error('复审未产出最终文本');
|
||||
|
||||
const { summary, verdict } = parseVerdict(cc.finalText);
|
||||
return { summary, verdict, transcriptRef: cc.transcriptRef, sessionId: cc.sessionId };
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { Project, Task } from '../model/types.js';
|
||||
import { git, type WorktreeInfo } from './worktree.js';
|
||||
import { runClaude } from './cc.js';
|
||||
import { pickModel } from './models.js';
|
||||
|
||||
export { transcriptDir } from './cc.js';
|
||||
|
||||
export interface RunnerResult {
|
||||
ok: boolean;
|
||||
transcriptRef: string | null;
|
||||
sessionId: string | null;
|
||||
/** SDK result 消息的文本(执行者自述,传给 reviewer);mock/失败时可缺省 */
|
||||
finalText?: string | null;
|
||||
/** 实际使用的模型(发生回退时为回退模型) */
|
||||
modelUsed?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 执行函数签名(orchestrator 依赖注入点;测试传 mock,生产传 runTask) */
|
||||
export type RunnerFn = (task: Task, project: Project, worktree: WorktreeInfo, runId: string) => Promise<RunnerResult>;
|
||||
|
||||
const DEFAULT_MAX_TURNS = 100;
|
||||
const DEFAULT_TIMEOUT_MS = 30 * 60_000; // 整体兜底超时 30min
|
||||
|
||||
/** 组装任务提示词:标题 + operations/spec 全文 + 执行约束 */
|
||||
export function buildPrompt(task: Task): string {
|
||||
const body = task.operations ?? task.spec ?? task.plan ?? '';
|
||||
return [
|
||||
`# 任务:${task.title}`,
|
||||
`任务 ID:${task.id}`,
|
||||
'',
|
||||
'## 任务内容',
|
||||
body || '(无详细说明,按标题完成)',
|
||||
'',
|
||||
'## 执行约束(必须遵守)',
|
||||
'- 只在当前工作目录(git worktree)内改动文件,不得读写或修改 worktree 之外的任何文件。',
|
||||
`- 完成后用 \`git add -A && git commit\` 提交全部改动,commit message 必须包含任务 ID「${task.id}」。`,
|
||||
'- 不得执行 git push / git merge / 切换分支,当前分支就是你的工作分支。',
|
||||
'- 不要发布、部署或执行任何有外部副作用的操作。',
|
||||
'- 若项目有测试体系且改动可测试,请补充并实际运行相关测试(npm/go/pytest/shellcheck 等已授权),并在最终回复中说明测试命令与结果。',
|
||||
'- 最终回复请简要总结:做了什么、怎么做的、测试结果。',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** CC 没提交时由 runner 兜底:git add -A + commit(无改动则跳过) */
|
||||
async function ensureCommitted(dir: string, task: Task): Promise<void> {
|
||||
const status = (await git(dir, ['status', '--porcelain'])).trim();
|
||||
if (!status) return;
|
||||
await git(dir, ['add', '-A']);
|
||||
await git(dir, ['-c', 'user.name=maestro', '-c', 'user.email=maestro@local', 'commit', '-m', `maestro(${task.id}): ${task.title}`]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 worktree 内用 Claude Agent SDK 起 headless Claude Code 执行任务。
|
||||
* 模型按复杂度选择(project.model 最优先),不可用时自动回退重试(见 cc.ts / models.ts)。
|
||||
* 流式消息逐行写入 <transcriptDir>/<runId>.jsonl;返回 ok/transcriptRef/sessionId/finalText/error。
|
||||
* 不抛错:一切失败都折叠进 { ok: false, error }。
|
||||
*/
|
||||
export async function runTask(task: Task, project: Project, worktree: WorktreeInfo, runId: string): Promise<RunnerResult> {
|
||||
const model = pickModel(task, project, 'executor');
|
||||
const cc = await runClaude({
|
||||
prompt: buildPrompt(task),
|
||||
cwd: worktree.dir,
|
||||
model,
|
||||
runId,
|
||||
maxTurns: DEFAULT_MAX_TURNS,
|
||||
timeoutMs: DEFAULT_TIMEOUT_MS,
|
||||
permissionMode: 'acceptEdits', // worktree 内自动接受编辑
|
||||
allowedTools: [
|
||||
'Read', 'Edit', 'Write', 'Glob', 'Grep',
|
||||
// git:提交所需最小面(不含 push)
|
||||
'Bash(git status:*)', 'Bash(git diff:*)', 'Bash(git log:*)',
|
||||
'Bash(git add:*)', 'Bash(git commit:*)',
|
||||
// 测试/构建:让执行任务自己跑测试(仍关在 worktree 内,无 push 无包发布)
|
||||
'Bash(npm test:*)', 'Bash(npm run:*)', 'Bash(npm ci:*)', 'Bash(npm install:*)',
|
||||
'Bash(npx:*)', 'Bash(node:*)',
|
||||
'Bash(go build:*)', 'Bash(go test:*)', 'Bash(go vet:*)', 'Bash(go mod:*)', 'Bash(go run:*)',
|
||||
'Bash(shellcheck:*)', 'Bash(bash -n:*)', 'Bash(make:*)',
|
||||
'Bash(python3 -m pytest:*)', 'Bash(pytest:*)',
|
||||
],
|
||||
});
|
||||
|
||||
if (!cc.ok) {
|
||||
return { ok: false, transcriptRef: cc.transcriptRef, sessionId: cc.sessionId, finalText: null, modelUsed: cc.modelUsed, error: cc.error ?? '未知错误' };
|
||||
}
|
||||
|
||||
// 兜底:CC 没 commit 时由 runner 代为提交
|
||||
try {
|
||||
await ensureCommitted(worktree.dir, task);
|
||||
} catch (e) {
|
||||
return { ok: false, transcriptRef: cc.transcriptRef, sessionId: cc.sessionId, finalText: cc.finalText || null, modelUsed: cc.modelUsed, error: `兜底提交失败:${(e as Error).message}` };
|
||||
}
|
||||
return { ok: true, transcriptRef: cc.transcriptRef, sessionId: cc.sessionId, finalText: cc.finalText || null, modelUsed: cc.modelUsed };
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import type { Project } from '../model/types.js';
|
||||
import { transcriptDir } from './runner.js';
|
||||
|
||||
export interface VerifyResult {
|
||||
ok: boolean;
|
||||
exitCode: number | null;
|
||||
logRef: string | null; // <transcriptDir>/<runId>.verify.log;无 verifyCmd 时为 null
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 校验函数签名(orchestrator 依赖注入点) */
|
||||
export type VerifyFn = (project: Project, dir: string, runId: string) => Promise<VerifyResult>;
|
||||
|
||||
const VERIFY_TIMEOUT_MS = 10 * 60_000; // 10min
|
||||
|
||||
/**
|
||||
* project.verifyCmd 存在则在 worktree 内以 shell 执行;exit 0 = 通过。
|
||||
* stdout/stderr 写 <transcriptDir>/<runId>.verify.log。无 verifyCmd 视为通过。
|
||||
*/
|
||||
export async function runVerify(project: Project, dir: string, runId: string): Promise<VerifyResult> {
|
||||
const cmd = project.verifyCmd?.trim();
|
||||
if (!cmd) return { ok: true, exitCode: null, logRef: null };
|
||||
|
||||
const logDir = transcriptDir();
|
||||
mkdirSync(logDir, { recursive: true });
|
||||
const logRef = join(logDir, `${runId}.verify.log`);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
execFile('/bin/sh', ['-c', cmd], { cwd: dir, timeout: VERIFY_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }, (err, stdout, stderr) => {
|
||||
const rawCode = err ? (err as { code?: unknown }).code : 0;
|
||||
const numericExit = typeof rawCode === 'number' ? rawCode : (err ? 1 : 0);
|
||||
writeFileSync(logRef, `$ ${cmd}\n--- stdout ---\n${stdout}\n--- stderr ---\n${stderr}\n--- exit: ${numericExit} ---\n`);
|
||||
if (!err) {
|
||||
resolve({ ok: true, exitCode: 0, logRef });
|
||||
} else {
|
||||
const timedOut = (err as { killed?: boolean }).killed === true;
|
||||
resolve({
|
||||
ok: false,
|
||||
exitCode: numericExit,
|
||||
logRef,
|
||||
error: timedOut ? `verify 超时(>${VERIFY_TIMEOUT_MS / 1000}s):${cmd}` : `verify 失败(exit ${numericExit}):${cmd}`,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, dirname, join } from 'node:path';
|
||||
import { mkdirSync, rmSync } from 'node:fs';
|
||||
|
||||
const GIT_TIMEOUT_MS = 60_000;
|
||||
const MAX_BUFFER = 16 * 1024 * 1024;
|
||||
|
||||
/** 在 repoPath 下执行 git(execFile 不走 shell),超时与错误透传(附 stderr)。 */
|
||||
export function git(repoPath: string, args: string[], timeoutMs = GIT_TIMEOUT_MS): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile('git', args, { cwd: repoPath, timeout: timeoutMs, maxBuffer: MAX_BUFFER }, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
reject(new Error(`git ${args.join(' ')} 失败: ${String(stderr).trim() || err.message}`));
|
||||
} else {
|
||||
resolve(stdout);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface WorktreeInfo {
|
||||
dir: string;
|
||||
branch: string;
|
||||
}
|
||||
|
||||
export interface WorktreeDiff {
|
||||
diffSummary: string;
|
||||
commits: string[];
|
||||
}
|
||||
|
||||
/** worktree 根目录:<MAESTRO_DATA_DIR 或 ~/.maestro>/worktrees(调用时读 env,便于测试/PoC 隔离) */
|
||||
export function worktreeBase(): string {
|
||||
return join(process.env.MAESTRO_DATA_DIR ?? join(homedir(), '.maestro'), 'worktrees');
|
||||
}
|
||||
|
||||
/** 任务分支名(确定性,可在创建前预知) */
|
||||
export function branchFor(taskId: string): string {
|
||||
return `maestro/${taskId}`;
|
||||
}
|
||||
|
||||
/** 任务 worktree 目录(确定性):<base>/<repo名>/<taskId>/ */
|
||||
export function worktreeDirFor(repoPath: string, taskId: string): string {
|
||||
return join(worktreeBase(), basename(repoPath), taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为任务创建隔离 worktree:分支 maestro/<taskId>,基于 baseBranch。
|
||||
* 残留的同名 worktree/分支先清理再重建(重试场景从干净的 baseBranch 重新开始)。
|
||||
*/
|
||||
export async function createWorktree(repoPath: string, taskId: string, baseBranch: string): Promise<WorktreeInfo> {
|
||||
const branch = branchFor(taskId);
|
||||
const dir = worktreeDirFor(repoPath, taskId);
|
||||
|
||||
// 清理残留:已注册的同路径 worktree → 强制移除;目录残骸 → 删除;旧分支 → 删除
|
||||
await git(repoPath, ['worktree', 'prune']).catch(() => undefined);
|
||||
await git(repoPath, ['worktree', 'remove', '--force', dir]).catch(() => undefined);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
await git(repoPath, ['branch', '-D', branch]).catch(() => undefined);
|
||||
|
||||
mkdirSync(dirname(dir), { recursive: true });
|
||||
await git(repoPath, ['worktree', 'add', '-b', branch, dir, baseBranch]);
|
||||
return { dir, branch };
|
||||
}
|
||||
|
||||
/** 分支相对 baseBranch 的改动:diff --stat 摘要 + commit 列表(新→旧,"<短hash> <标题>") */
|
||||
export async function worktreeDiff(
|
||||
repoPath: string,
|
||||
_dir: string,
|
||||
branch: string,
|
||||
baseBranch: string,
|
||||
): Promise<WorktreeDiff> {
|
||||
const diffSummary = (await git(repoPath, ['diff', '--stat', `${baseBranch}...${branch}`])).trim();
|
||||
const log = (await git(repoPath, ['log', '--format=%h %s', `${baseBranch}..${branch}`])).trim();
|
||||
const commits = log ? log.split('\n').map((l) => l.trim()).filter(Boolean) : [];
|
||||
return { diffSummary, commits };
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除 worktree(目录 + 注册项)。分支保留(合并后由人/后续清理处理)。
|
||||
* 仅在成功合并后调用;执行失败时保留现场,不要调它。
|
||||
*/
|
||||
export async function removeWorktree(repoPath: string, dir: string): Promise<void> {
|
||||
await git(repoPath, ['worktree', 'remove', '--force', dir]);
|
||||
await git(repoPath, ['worktree', 'prune']).catch(() => undefined);
|
||||
}
|
||||
Reference in New Issue
Block a user