feat: PR 审核流程 + 自动合并 + macOS 通知 + 订阅额度透传 + 归档详情
PR 流程(开发→提PR→CodeReview→安全审计→审核→通过即合并): - reviewer 拆分为 code review 与安全审计两个独立 CC run(kind=reviewer/security), TaskResult 四字段(summary/verdict + securitySummary/securityVerdict),闸上两节报告两枚结论徽章 - executor/merge.ts: 通过即合并——临时 worktree 内 merge --no-ff,绝不碰用户工作区/不 push; 冲突安全拒绝(报冲突文件);重复合并幂等;合并后回收执行 worktree + 删分支 - decide 路由 merge:false 逃生口 + 看板「仅通过」按钮(目标分支被工作区检出时用) 通知(daemon/notify.ts): - macOS 原生通知: 进审核闸(复审建议拒绝标⚠)/连续失败需人工/合并完成 - 同任务同类型 60s 抑制、osascript 转义截断、MAESTRO_NOTIFY=0 关闭 订阅额度透传(daemon/usage.ts): - OAuth usage API(与 Claude Code/claude-hud 同源),凭证 keychain→内存零泄漏 - 60s 成败双缓存+并发去重+5s 超时,失败降级 null - GET /api/agents 顶层 usage 字段;Agent 面板显示 5h/周用量条+重置倒计时(>80%琥珀/>95%红) 看板与生命周期: - 归档区: 深度1整树完成沉底,时间倒序分页(尺寸 chip 10/20/50/100 置底) - 归档详情对话框: 全属性/执行历史与时长/审批记录/状态流转时间线(GET /api/tasks/:id/events) - 容器收口: 已拆解 Hard 子任务全 done 自动 done(afterDone 逐级向上) - 同步按钮收进配置面板;执行白名单扩测试命令(npm/go/shellcheck/make/pytest) - Agent 面板显示调度模式与各复杂度模型;被依赖阻塞→被阻塞 测试: 74/74(新增 merge 6/notify 10/usage 7/容器收口/双复审适配) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { mergeBranch, mergeWorktreeDirFor } from '../src/executor/merge.js';
|
||||
|
||||
function gitSync(cwd: string, args: string[]): string {
|
||||
return execFileSync('git', args, { cwd, encoding: 'utf8' });
|
||||
}
|
||||
|
||||
/** /tmp 下建一个带 1 个 commit 的真实 git repo(main 分支) */
|
||||
function makeRepo(): string {
|
||||
const repo = mkdtempSync(join(tmpdir(), 'maestro-merge-repo-'));
|
||||
gitSync(repo, ['init', '-b', 'main']);
|
||||
gitSync(repo, ['config', 'user.name', 'maestro-test']);
|
||||
gitSync(repo, ['config', 'user.email', 'test@maestro.local']);
|
||||
writeFileSync(join(repo, 'README.md'), '# demo\n');
|
||||
gitSync(repo, ['add', '-A']);
|
||||
gitSync(repo, ['commit', '-m', 'init']);
|
||||
return repo;
|
||||
}
|
||||
|
||||
function commitFile(repo: string, file: string, content: string, msg: string): void {
|
||||
writeFileSync(join(repo, file), content);
|
||||
gitSync(repo, ['add', '-A']);
|
||||
gitSync(repo, ['commit', '-m', msg]);
|
||||
}
|
||||
|
||||
/** 每个用例独立的 dataDir + repo,t.after 收尾(不碰 ~/.maestro) */
|
||||
function setup(t: { after: (fn: () => void) => void }): string {
|
||||
const dataDir = mkdtempSync(join(tmpdir(), 'maestro-merge-data-'));
|
||||
const prevDataDir = process.env.MAESTRO_DATA_DIR;
|
||||
process.env.MAESTRO_DATA_DIR = dataDir;
|
||||
const repo = makeRepo();
|
||||
t.after(() => {
|
||||
if (prevDataDir === undefined) delete process.env.MAESTRO_DATA_DIR;
|
||||
else process.env.MAESTRO_DATA_DIR = prevDataDir;
|
||||
rmSync(dataDir, { recursive: true, force: true });
|
||||
rmSync(repo, { recursive: true, force: true });
|
||||
});
|
||||
return repo;
|
||||
}
|
||||
|
||||
/** 临时合并 worktree 已彻底清理:目录不存在 + git worktree list 无 _merge */
|
||||
function assertMergeWorktreeCleaned(repo: string, taskId: string): void {
|
||||
assert.ok(!existsSync(mergeWorktreeDirFor(taskId)), '临时合并 worktree 目录应被删除');
|
||||
const list = gitSync(repo, ['worktree', 'list']);
|
||||
assert.ok(!list.includes('_merge'), `git worktree list 不应再含 _merge:${list}`);
|
||||
}
|
||||
|
||||
test('mergeBranch:可 ff 的分支也产出 --no-ff 合并提交,main 前进、临时 worktree 清理', async (t) => {
|
||||
const repo = setup(t);
|
||||
gitSync(repo, ['checkout', '-b', 'maestro/tsk_ff']);
|
||||
commitFile(repo, 'a.txt', 'A\n', 'maestro(tsk_ff): add a');
|
||||
gitSync(repo, ['switch', '--detach']); // 让 main 不被任何工作区检出
|
||||
|
||||
const r = await mergeBranch(repo, 'maestro/tsk_ff', 'main', 'tsk_ff');
|
||||
assert.equal(r.ok, true, r.error);
|
||||
assert.ok(r.mergeCommit);
|
||||
assert.equal(gitSync(repo, ['rev-parse', 'main']).trim(), r.mergeCommit);
|
||||
// --no-ff:合并提交有 2 个父
|
||||
const parents = gitSync(repo, ['rev-list', '--parents', '-n', '1', 'main']).trim().split(/\s+/);
|
||||
assert.equal(parents.length, 3, '应是双亲合并提交(--no-ff)');
|
||||
assert.match(gitSync(repo, ['log', '-1', '--format=%s', 'main']), /merge: maestro\/tsk_ff \[tsk_ff\]/);
|
||||
assert.equal(gitSync(repo, ['show', 'main:a.txt']), 'A\n');
|
||||
assertMergeWorktreeCleaned(repo, 'tsk_ff');
|
||||
});
|
||||
|
||||
test('mergeBranch:分叉历史(非 ff)无冲突合并成功,两边改动都在', async (t) => {
|
||||
const repo = setup(t);
|
||||
gitSync(repo, ['checkout', '-b', 'maestro/tsk_div']);
|
||||
commitFile(repo, 'b.txt', 'B\n', 'maestro(tsk_div): add b');
|
||||
gitSync(repo, ['checkout', 'main']);
|
||||
commitFile(repo, 'c.txt', 'C\n', 'main: add c'); // main 也前进 → 分叉
|
||||
gitSync(repo, ['switch', '--detach']);
|
||||
|
||||
const r = await mergeBranch(repo, 'maestro/tsk_div', 'main', 'tsk_div');
|
||||
assert.equal(r.ok, true, r.error);
|
||||
assert.equal(gitSync(repo, ['rev-parse', 'main']).trim(), r.mergeCommit);
|
||||
assert.equal(gitSync(repo, ['show', 'main:b.txt']), 'B\n');
|
||||
assert.equal(gitSync(repo, ['show', 'main:c.txt']), 'C\n');
|
||||
assertMergeWorktreeCleaned(repo, 'tsk_div');
|
||||
});
|
||||
|
||||
test('mergeBranch:冲突 → 返回错误含冲突文件列表,main 与用户分支均无损,临时 worktree 清理', async (t) => {
|
||||
const repo = setup(t);
|
||||
gitSync(repo, ['checkout', '-b', 'maestro/tsk_cf']);
|
||||
commitFile(repo, 'README.md', '# demo\nbranch version\n', 'maestro(tsk_cf): edit readme');
|
||||
gitSync(repo, ['checkout', 'main']);
|
||||
commitFile(repo, 'README.md', '# demo\nmain version\n', 'main: edit readme');
|
||||
gitSync(repo, ['switch', '--detach']);
|
||||
const mainBefore = gitSync(repo, ['rev-parse', 'main']).trim();
|
||||
const branchBefore = gitSync(repo, ['rev-parse', 'maestro/tsk_cf']).trim();
|
||||
|
||||
const r = await mergeBranch(repo, 'maestro/tsk_cf', 'main', 'tsk_cf');
|
||||
assert.equal(r.ok, false);
|
||||
assert.match(r.error ?? '', /README\.md/, `错误应含冲突文件列表:${r.error}`);
|
||||
// 双方无损
|
||||
assert.equal(gitSync(repo, ['rev-parse', 'main']).trim(), mainBefore, 'main 应无损');
|
||||
assert.equal(gitSync(repo, ['rev-parse', 'maestro/tsk_cf']).trim(), branchBefore, '用户分支应无损');
|
||||
assertMergeWorktreeCleaned(repo, 'tsk_cf');
|
||||
});
|
||||
|
||||
test('mergeBranch:分支不存在(已删)→ 明确错误', async (t) => {
|
||||
const repo = setup(t);
|
||||
gitSync(repo, ['switch', '--detach']);
|
||||
const r = await mergeBranch(repo, 'maestro/tsk_gone', 'main', 'tsk_gone');
|
||||
assert.equal(r.ok, false);
|
||||
assert.match(r.error ?? '', /分支不存在/);
|
||||
});
|
||||
|
||||
test('mergeBranch:defaultBranch 正被工作区检出 → 失败且不动用户检出', async (t) => {
|
||||
const repo = setup(t); // main 仍在主工作区检出
|
||||
gitSync(repo, ['branch', 'maestro/tsk_co']); // 分支存在但 main 被占用
|
||||
const mainBefore = gitSync(repo, ['rev-parse', 'main']).trim();
|
||||
|
||||
const r = await mergeBranch(repo, 'maestro/tsk_co', 'main', 'tsk_co');
|
||||
assert.equal(r.ok, false);
|
||||
assert.match(r.error ?? '', /检出/, `应提示 defaultBranch 被检出:${r.error}`);
|
||||
assert.equal(gitSync(repo, ['rev-parse', 'main']).trim(), mainBefore);
|
||||
assert.equal(gitSync(repo, ['rev-parse', '--abbrev-ref', 'HEAD']).trim(), 'main', '用户检出不应被切走');
|
||||
assertMergeWorktreeCleaned(repo, 'tsk_co');
|
||||
});
|
||||
|
||||
test('mergeBranch:重复合并(分支已在 main 里)→ ok,不新建提交', async (t) => {
|
||||
const repo = setup(t);
|
||||
gitSync(repo, ['checkout', '-b', 'maestro/tsk_re']);
|
||||
commitFile(repo, 'd.txt', 'D\n', 'maestro(tsk_re): add d');
|
||||
gitSync(repo, ['switch', '--detach']);
|
||||
|
||||
const first = await mergeBranch(repo, 'maestro/tsk_re', 'main', 'tsk_re');
|
||||
assert.equal(first.ok, true, first.error);
|
||||
const second = await mergeBranch(repo, 'maestro/tsk_re', 'main', 'tsk_re');
|
||||
assert.equal(second.ok, true, second.error);
|
||||
assert.equal(second.mergeCommit, first.mergeCommit, '重复合并不应产生新提交(Already up to date)');
|
||||
assertMergeWorktreeCleaned(repo, 'tsk_re');
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { Store } from '../src/store/index.js';
|
||||
import { createNotifier, startNotifier, sanitizeForOsascript, NOTIFY_SUPPRESS_MS } from '../src/daemon/notify.js';
|
||||
|
||||
const noopLog = { info: (): void => undefined, error: (): void => undefined };
|
||||
|
||||
function setup(): { store: Store; projectId: string } {
|
||||
const store = new Store(':memory:');
|
||||
const p = store.createProject({ name: 'notify', repoPath: '/tmp/notify-repo-' + Math.random() });
|
||||
return { store, projectId: p.id };
|
||||
}
|
||||
|
||||
/** 注入假 osascript:捕获脚本文本,不真发通知 */
|
||||
function capture(store: Store, now?: () => number): { scripts: string[]; stop: () => void } {
|
||||
const scripts: string[] = [];
|
||||
const stop = createNotifier(store, noopLog, { osascript: (s) => scripts.push(s), ...(now ? { now } : {}) });
|
||||
return { scripts, stop };
|
||||
}
|
||||
|
||||
const emptyResult = {
|
||||
branch: 'maestro/x', worktree: '/wt', diffSummary: null, commits: [], prUrl: null,
|
||||
summary: null, verdict: null, securitySummary: null, securityVerdict: null,
|
||||
} as const;
|
||||
|
||||
test('notify:进入 spec_review 闸 →「等待审核(方案)」;与任务名一致', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '写登录方案', complexity: 'medium' });
|
||||
const { scripts } = capture(store);
|
||||
store.setSpec(t.id, '方案');
|
||||
store.transition(t.id, 'spec_review');
|
||||
assert.equal(scripts.length, 1);
|
||||
assert.match(scripts[0], /display notification "⏳ 写登录方案 等待审核(方案)" with title "maestro"/);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:exec_review 且任一复审 verdict=reject → 文案改「复审建议拒绝」', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '高危改动', complexity: 'easy' });
|
||||
store.transition(t.id, 'queued');
|
||||
store.transition(t.id, 'executing');
|
||||
store.setResult(t.id, { ...emptyResult, securityVerdict: 'reject' });
|
||||
const { scripts } = capture(store);
|
||||
store.transition(t.id, 'exec_review');
|
||||
assert.equal(scripts.length, 1);
|
||||
assert.match(scripts[0], /⚠ 高危改动 复审建议拒绝/);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:exec_review 复审均通过 →「等待审核(PR)」', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '普通改动', complexity: 'easy' });
|
||||
store.transition(t.id, 'queued');
|
||||
store.transition(t.id, 'executing');
|
||||
store.setResult(t.id, { ...emptyResult, verdict: 'approve', securityVerdict: 'approve' });
|
||||
const { scripts } = capture(store);
|
||||
store.transition(t.id, 'exec_review');
|
||||
assert.equal(scripts.length, 1);
|
||||
assert.match(scripts[0], /⏳ 普通改动 等待审核(PR)/);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:needs_attention →「连续失败需人工」', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '坏任务', complexity: 'easy' });
|
||||
store.transition(t.id, 'queued');
|
||||
store.transition(t.id, 'executing');
|
||||
store.transition(t.id, 'failed');
|
||||
const { scripts } = capture(store);
|
||||
store.transition(t.id, 'needs_attention');
|
||||
assert.equal(scripts.length, 1);
|
||||
assert.match(scripts[0], /❌ 坏任务 连续失败需人工/);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:approval.granted 且 gate=exec →「已合并完成」;plan/spec 闸通过不通知', () => {
|
||||
const { store, projectId } = setup();
|
||||
// spec 闸 accept:不触发"已合并完成"
|
||||
const m = store.createTask({ projectId, title: '方案任务', complexity: 'medium' });
|
||||
store.setSpec(m.id, 'spec');
|
||||
store.transition(m.id, 'spec_review');
|
||||
// exec 闸 accept:触发
|
||||
const e = store.createTask({ projectId, title: '执行任务', complexity: 'easy' });
|
||||
store.transition(e.id, 'queued');
|
||||
store.transition(e.id, 'executing');
|
||||
store.setResult(e.id, { ...emptyResult });
|
||||
store.transition(e.id, 'exec_review');
|
||||
|
||||
const { scripts } = capture(store);
|
||||
store.decide(m.id, 'accept', 'user'); // spec 闸 → 无"合并完成"通知
|
||||
store.decide(e.id, 'accept', 'user'); // exec 闸 → 通知
|
||||
const merged = scripts.filter((s) => s.includes('已合并完成'));
|
||||
assert.equal(merged.length, 1);
|
||||
assert.match(merged[0], /✅ 执行任务 已合并完成/);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:事件过滤——ready/queued/executing 等普通流转不通知', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '安静任务', complexity: 'easy' });
|
||||
const { scripts } = capture(store);
|
||||
store.transition(t.id, 'queued');
|
||||
store.transition(t.id, 'executing');
|
||||
store.transition(t.id, 'failed');
|
||||
store.transition(t.id, 'queued');
|
||||
assert.equal(scripts.length, 0);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:同任务同类型 60s 抑制;超窗后再发;不同任务不互相抑制', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '反复任务', complexity: 'medium' });
|
||||
const t2 = store.createTask({ projectId, title: '另一个', complexity: 'medium' });
|
||||
let fakeNow = 1_000_000;
|
||||
const { scripts } = capture(store, () => fakeNow);
|
||||
|
||||
store.setSpec(t.id, 's1');
|
||||
store.transition(t.id, 'spec_review'); // 第 1 次:发
|
||||
assert.equal(scripts.length, 1);
|
||||
|
||||
store.decide(t.id, 'reject', 'user', '再改改'); // 回 speccing(approval.rejected 不通知)
|
||||
fakeNow += 30_000;
|
||||
store.transition(t.id, 'spec_review'); // 30s 内同类型:抑制
|
||||
assert.equal(scripts.length, 1);
|
||||
|
||||
store.setSpec(t2.id, 's2');
|
||||
store.transition(t2.id, 'spec_review'); // 不同任务:不受抑制
|
||||
assert.equal(scripts.length, 2);
|
||||
|
||||
store.decide(t.id, 'reject', 'user', '还得改');
|
||||
fakeNow += NOTIFY_SUPPRESS_MS; // 距上次该任务通知已 >60s
|
||||
store.transition(t.id, 'spec_review');
|
||||
assert.equal(scripts.length, 3);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:取消订阅后不再收到通知', () => {
|
||||
const { store, projectId } = setup();
|
||||
const t = store.createTask({ projectId, title: '退订', complexity: 'medium' });
|
||||
const { scripts, stop } = capture(store);
|
||||
stop();
|
||||
store.setSpec(t.id, 's');
|
||||
store.transition(t.id, 'spec_review');
|
||||
assert.equal(scripts.length, 0);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('notify:MAESTRO_NOTIFY=0 时 startNotifier 不启用', () => {
|
||||
const { store } = setup();
|
||||
const prev = process.env.MAESTRO_NOTIFY;
|
||||
process.env.MAESTRO_NOTIFY = '0';
|
||||
try {
|
||||
assert.equal(startNotifier(store, { log: noopLog }), null);
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.MAESTRO_NOTIFY;
|
||||
else process.env.MAESTRO_NOTIFY = prev;
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('sanitizeForOsascript:转义引号反斜杠、去换行、截断 80 字符', () => {
|
||||
assert.equal(sanitizeForOsascript('say "hi" \\ ok'), 'say \\"hi\\" \\\\ ok');
|
||||
assert.equal(sanitizeForOsascript('一行\n两行\r\n三行'), '一行 两行 三行');
|
||||
const long = 'x'.repeat(200);
|
||||
const cut = sanitizeForOsascript(long);
|
||||
assert.equal(cut.length, 80);
|
||||
assert.ok(cut.endsWith('…'));
|
||||
});
|
||||
+62
-11
@@ -23,6 +23,13 @@ const okReview: ReviewResult = {
|
||||
sessionId: 'sess-review-1',
|
||||
};
|
||||
|
||||
const okSecurity: ReviewResult = {
|
||||
summary: '## 安全审计\nmock 审计通过',
|
||||
verdict: 'approve',
|
||||
transcriptRef: '/tmp/fake-security.jsonl',
|
||||
sessionId: 'sess-security-1',
|
||||
};
|
||||
|
||||
/** 全 mock 依赖(不真起 CC、不动 git):可按用例覆盖 */
|
||||
function mockDeps(overrides: Partial<OrchestratorDeps> = {}): OrchestratorDeps {
|
||||
return {
|
||||
@@ -30,7 +37,8 @@ function mockDeps(overrides: Partial<OrchestratorDeps> = {}): OrchestratorDeps {
|
||||
worktreeDiff: async () => ({ diffSummary: ' README.md | 1 +', commits: ['abc1234 hello maestro'] }),
|
||||
verify: async () => ({ ok: true, exitCode: 0, logRef: null }),
|
||||
runner: async () => okRun,
|
||||
reviewer: async () => okReview,
|
||||
reviewCode: async () => okReview,
|
||||
reviewSecurity: async () => okSecurity,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -140,7 +148,7 @@ test('concurrency=1:同项目同轮只领 1 个,跑完下一轮再领', asyn
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('成功路径:状态流转 + setResult(含复审 summary/verdict) + 双 run succeeded', async () => {
|
||||
test('成功路径:状态流转 + setResult(四字段) + executor/reviewer/security 三 run succeeded', async () => {
|
||||
const { store, projectId } = setup('auto-easy');
|
||||
const t = store.createTask({ projectId, title: 'tweak', complexity: 'easy' });
|
||||
store.setOperations(t.id, '在 README.md 追加一行');
|
||||
@@ -148,12 +156,17 @@ test('成功路径:状态流转 + setResult(含复审 summary/verdict) + 双 r
|
||||
const seen: string[] = [];
|
||||
store.subscribe((e) => { if (e.type === 'status.changed' && e.taskId === t.id) seen.push(String(e.payload.to)); });
|
||||
|
||||
let reportSeen: string | null = null;
|
||||
let codeReportSeen: string | null = null;
|
||||
let secReportSeen: string | null = null;
|
||||
const orch = createOrchestrator(store, noopLog, mockDeps({
|
||||
reviewer: async (_task, _project, _wt, _runId, executorReport) => {
|
||||
reportSeen = executorReport;
|
||||
reviewCode: async (_task, _project, _wt, _runId, executorReport) => {
|
||||
codeReportSeen = executorReport;
|
||||
return okReview;
|
||||
},
|
||||
reviewSecurity: async (_task, _project, _wt, _runId, executorReport) => {
|
||||
secReportSeen = executorReport;
|
||||
return okSecurity;
|
||||
},
|
||||
}));
|
||||
orch.tick();
|
||||
await orch.drain();
|
||||
@@ -169,11 +182,14 @@ test('成功路径:状态流转 + setResult(含复审 summary/verdict) + 双 r
|
||||
prUrl: null,
|
||||
summary: '## 做了什么\nmock 复审通过',
|
||||
verdict: 'approve',
|
||||
securitySummary: '## 安全审计\nmock 审计通过',
|
||||
securityVerdict: 'approve',
|
||||
});
|
||||
assert.equal(reportSeen, '执行自述:改了 README'); // runner finalText 传给 reviewer 作执行者自述
|
||||
assert.equal(codeReportSeen, '执行自述:改了 README'); // runner finalText 传给两个复审作执行者自述
|
||||
assert.equal(secReportSeen, '执行自述:改了 README');
|
||||
|
||||
const runs = store.listRuns(t.id);
|
||||
assert.equal(runs.length, 2);
|
||||
assert.equal(runs.length, 3);
|
||||
const executor = runs.find((r) => r.kind === 'executor')!;
|
||||
assert.equal(executor.status, 'succeeded');
|
||||
assert.equal(executor.branch, `maestro/${t.id}`);
|
||||
@@ -183,14 +199,19 @@ test('成功路径:状态流转 + setResult(含复审 summary/verdict) + 双 r
|
||||
assert.equal(reviewer.status, 'succeeded');
|
||||
assert.equal(reviewer.transcriptRef, '/tmp/fake-review.jsonl');
|
||||
assert.equal(reviewer.claudeSessionId, 'sess-review-1');
|
||||
const security = runs.find((r) => r.kind === 'security')!;
|
||||
assert.equal(security.status, 'succeeded');
|
||||
assert.equal(security.transcriptRef, '/tmp/fake-security.jsonl');
|
||||
assert.equal(security.claudeSessionId, 'sess-security-1');
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('reviewer verdict=reject 也照常落进 result(最终裁决仍归用户)', async () => {
|
||||
test('任一 verdict=reject 也照常落进 result(最终裁决仍归用户)', async () => {
|
||||
const { store, projectId } = setup('auto-easy');
|
||||
const t = store.createTask({ projectId, title: 'risky', complexity: 'easy' });
|
||||
const orch = createOrchestrator(store, noopLog, mockDeps({
|
||||
reviewer: async () => ({ ...okReview, summary: '发现问题', verdict: 'reject' as const }),
|
||||
reviewCode: async () => ({ ...okReview, summary: '发现问题', verdict: 'reject' as const }),
|
||||
reviewSecurity: async () => ({ ...okSecurity, summary: '发现密钥泄露', verdict: 'reject' as const }),
|
||||
}));
|
||||
orch.tick();
|
||||
await orch.drain();
|
||||
@@ -198,14 +219,16 @@ test('reviewer verdict=reject 也照常落进 result(最终裁决仍归用户
|
||||
assert.equal(done.status, 'exec_review');
|
||||
assert.equal(done.result!.verdict, 'reject');
|
||||
assert.equal(done.result!.summary, '发现问题');
|
||||
assert.equal(done.result!.securityVerdict, 'reject');
|
||||
assert.equal(done.result!.securitySummary, '发现密钥泄露');
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('复审失败不挡任务:照常进 exec_review,summary 记失败原因、verdict=null', async () => {
|
||||
test('code review 失败不挡任务:summary 记失败原因、verdict=null,安全审计照常跑', async () => {
|
||||
const { store, projectId } = setup('auto-easy');
|
||||
const t = store.createTask({ projectId, title: 'review-broken', complexity: 'easy' });
|
||||
const orch = createOrchestrator(store, noopLog, mockDeps({
|
||||
reviewer: async () => { throw new Error('复审 CC 崩了'); },
|
||||
reviewCode: async () => { throw new Error('复审 CC 崩了'); },
|
||||
}));
|
||||
orch.tick();
|
||||
await orch.drain();
|
||||
@@ -214,12 +237,40 @@ test('复审失败不挡任务:照常进 exec_review,summary 记失败原因
|
||||
assert.equal(done.status, 'exec_review'); // 不挡结果闸
|
||||
assert.equal(done.result!.verdict, null);
|
||||
assert.equal(done.result!.summary, '自动复审失败:复审 CC 崩了');
|
||||
assert.equal(done.result!.securityVerdict, 'approve'); // 另一个复审不受影响
|
||||
assert.equal(done.result!.securitySummary, '## 安全审计\nmock 审计通过');
|
||||
|
||||
const runs = store.listRuns(t.id);
|
||||
assert.equal(runs.find((r) => r.kind === 'executor')!.status, 'succeeded');
|
||||
const reviewer = runs.find((r) => r.kind === 'reviewer')!;
|
||||
assert.equal(reviewer.status, 'failed');
|
||||
assert.match(reviewer.error ?? '', /复审 CC 崩了/);
|
||||
assert.equal(runs.find((r) => r.kind === 'security')!.status, 'succeeded');
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('安全审计失败不挡任务:securitySummary 记失败原因、securityVerdict=null,code review 不受影响', async () => {
|
||||
const { store, projectId } = setup('auto-easy');
|
||||
const t = store.createTask({ projectId, title: 'security-broken', complexity: 'easy' });
|
||||
const orch = createOrchestrator(store, noopLog, mockDeps({
|
||||
reviewSecurity: async () => { throw new Error('审计 CC 崩了'); },
|
||||
}));
|
||||
orch.tick();
|
||||
await orch.drain();
|
||||
|
||||
const done = store.getTask(t.id)!;
|
||||
assert.equal(done.status, 'exec_review');
|
||||
assert.equal(done.result!.verdict, 'approve');
|
||||
assert.equal(done.result!.summary, '## 做了什么\nmock 复审通过');
|
||||
assert.equal(done.result!.securityVerdict, null);
|
||||
assert.equal(done.result!.securitySummary, '自动复审失败:审计 CC 崩了');
|
||||
|
||||
const runs = store.listRuns(t.id);
|
||||
assert.equal(runs.find((r) => r.kind === 'executor')!.status, 'succeeded');
|
||||
assert.equal(runs.find((r) => r.kind === 'reviewer')!.status, 'succeeded');
|
||||
const security = runs.find((r) => r.kind === 'security')!;
|
||||
assert.equal(security.status, 'failed');
|
||||
assert.match(security.error ?? '', /审计 CC 崩了/);
|
||||
store.close();
|
||||
});
|
||||
|
||||
|
||||
+25
-6
@@ -32,26 +32,45 @@ test('parseVerdict:VERDICT 行带多余内容不算(如模板原文 approve|
|
||||
assert.equal(verdict, null);
|
||||
});
|
||||
|
||||
test('buildReviewPrompt:含任务说明、执行者自述、diff 指令与固定模板', () => {
|
||||
test('buildReviewPrompt(code):含任务说明、执行者自述、diff 指令与 code review 模板', () => {
|
||||
const task = { id: 'task_1', title: '修复登录', operations: '改 auth.ts', spec: null, plan: null } as Task;
|
||||
const project = { defaultBranch: 'main' } as Project;
|
||||
const wt = { dir: '/tmp/wt', branch: 'maestro/task_1' };
|
||||
const prompt = buildReviewPrompt(task, project, wt, '我改了 auth.ts 并加了测试');
|
||||
const prompt = buildReviewPrompt('code', task, project, wt, '我改了 auth.ts 并加了测试');
|
||||
|
||||
assert.match(prompt, /修复登录/);
|
||||
assert.match(prompt, /改 auth\.ts/);
|
||||
assert.match(prompt, /我改了 auth\.ts 并加了测试/);
|
||||
assert.match(prompt, /git diff main\.\.\.maestro\/task_1/);
|
||||
for (const section of ['## 做了什么', '## 怎么做的', '## 测试情况', '## Code Review', '## 安全 Review', '## 结论']) {
|
||||
for (const section of ['## 做了什么', '## 怎么做的', '## 测试情况', '## Code Review', '## 结论']) {
|
||||
assert.ok(prompt.includes(section), `模板缺少 ${section}`);
|
||||
}
|
||||
assert.ok(!prompt.includes('## 安全审计'), 'code review 模板不应含安全审计节');
|
||||
assert.match(prompt, /VERDICT: approve\|reject/);
|
||||
assert.match(prompt, /只读权限/);
|
||||
});
|
||||
|
||||
test('buildReviewPrompt:执行者无自述时给占位说明', () => {
|
||||
test('buildReviewPrompt(security):安全审计模板(凭证/注入/权限/文案红线/部署风险)', () => {
|
||||
const task = { id: 'task_1', title: '修复登录', operations: '改 auth.ts', spec: null, plan: null } as Task;
|
||||
const project = { defaultBranch: 'main' } as Project;
|
||||
const wt = { dir: '/tmp/wt', branch: 'maestro/task_1' };
|
||||
const prompt = buildReviewPrompt('security', task, project, wt, '我改了 auth.ts');
|
||||
|
||||
assert.match(prompt, /安全审计/);
|
||||
for (const section of ['凭证与密钥泄露', '注入与危险命令', '权限与边界', 'UI 文案红线词', '生产部署风险', '## 结论']) {
|
||||
assert.ok(prompt.includes(section), `安全模板缺少 ${section}`);
|
||||
}
|
||||
assert.ok(!prompt.includes('## 做了什么'), '安全审计模板不应含 code review 节');
|
||||
assert.match(prompt, /git diff main\.\.\.maestro\/task_1/);
|
||||
assert.match(prompt, /VERDICT: approve\|reject/);
|
||||
assert.match(prompt, /只读权限/);
|
||||
});
|
||||
|
||||
test('buildReviewPrompt:执行者无自述时给占位说明(两种角色)', () => {
|
||||
const task = { id: 'task_2', title: 't', operations: null, spec: null, plan: null } as Task;
|
||||
const project = { defaultBranch: 'main' } as Project;
|
||||
const prompt = buildReviewPrompt(task, project, { dir: '/x', branch: 'maestro/task_2' }, '');
|
||||
assert.match(prompt, /执行者未留下自述/);
|
||||
for (const role of ['code', 'security'] as const) {
|
||||
const prompt = buildReviewPrompt(role, task, project, { dir: '/x', branch: 'maestro/task_2' }, '');
|
||||
assert.match(prompt, /执行者未留下自述/);
|
||||
}
|
||||
});
|
||||
|
||||
+1
-1
@@ -96,7 +96,7 @@ test('exec_review 结果闸:accept → done', () => {
|
||||
s.setOperations(t.id, 'op');
|
||||
s.transition(t.id, 'queued');
|
||||
s.transition(t.id, 'executing');
|
||||
s.setResult(t.id, { branch: 'maestro/run', worktree: '/wt', diffSummary: '+1 -0', commits: ['abc'], prUrl: null, summary: null, verdict: null });
|
||||
s.setResult(t.id, { branch: 'maestro/run', worktree: '/wt', diffSummary: '+1 -0', commits: ['abc'], prUrl: null, summary: null, verdict: null, securitySummary: null, securityVerdict: null });
|
||||
s.transition(t.id, 'exec_review');
|
||||
const done = s.decide(t.id, 'accept', 'user');
|
||||
assert.equal(done.status, 'done');
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createUsageFetcher, USAGE_CACHE_MS, USAGE_ENDPOINT } from '../src/daemon/usage.js';
|
||||
|
||||
const SECRET = 'tok-secret-do-not-leak';
|
||||
|
||||
/** 构造可控时钟 + 计数 fetch 的 fetcher(不真打 API) */
|
||||
function setup(opts: {
|
||||
body?: unknown;
|
||||
status?: number;
|
||||
fetchError?: Error;
|
||||
token?: string | null;
|
||||
} = {}): {
|
||||
getUsage: () => Promise<import('../src/daemon/usage.js').UsageInfo | null>;
|
||||
calls: { fetch: number; token: number };
|
||||
logs: string[];
|
||||
clock: { t: number };
|
||||
} {
|
||||
const calls = { fetch: 0, token: 0 };
|
||||
const logs: string[] = [];
|
||||
const clock = { t: 1_000_000 };
|
||||
const body = opts.body ?? {
|
||||
five_hour: { utilization: 47.0, resets_at: '2026-06-12T22:30:00+00:00' },
|
||||
seven_day: { utilization: 57.0, resets_at: '2026-06-13T12:00:00+00:00' },
|
||||
};
|
||||
const fetchFn = (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
calls.fetch += 1;
|
||||
assert.equal(String(url), USAGE_ENDPOINT);
|
||||
assert.match(String((init?.headers as Record<string, string>).Authorization), /^Bearer /);
|
||||
if (opts.fetchError) throw opts.fetchError;
|
||||
return {
|
||||
ok: (opts.status ?? 200) < 400,
|
||||
status: opts.status ?? 200,
|
||||
json: async () => body,
|
||||
} as Response;
|
||||
}) as typeof fetch;
|
||||
const getUsage = createUsageFetcher({
|
||||
fetchFn,
|
||||
readToken: async () => { calls.token += 1; return opts.token === undefined ? SECRET : opts.token; },
|
||||
now: () => clock.t,
|
||||
log: { info: (m) => logs.push(m), error: (m) => logs.push(m) },
|
||||
});
|
||||
return { getUsage, calls, logs, clock };
|
||||
}
|
||||
|
||||
test('usage:成功解析 five_hour/seven_day → UsageInfo(percent 取整,resetsAt 透传)', async () => {
|
||||
const { getUsage } = setup();
|
||||
const u = await getUsage();
|
||||
assert.deepEqual(u, {
|
||||
session: { percent: 47, resetsAt: '2026-06-12T22:30:00+00:00' },
|
||||
weekly: { percent: 57, resetsAt: '2026-06-13T12:00:00+00:00' },
|
||||
});
|
||||
});
|
||||
|
||||
test('usage:60s 内存缓存——窗口内不重复请求,过期后重新拉取', async () => {
|
||||
const { getUsage, calls, clock } = setup();
|
||||
await getUsage();
|
||||
await getUsage();
|
||||
clock.t += USAGE_CACHE_MS - 1;
|
||||
await getUsage();
|
||||
assert.equal(calls.fetch, 1);
|
||||
clock.t += 2; // 越过缓存窗口
|
||||
await getUsage();
|
||||
assert.equal(calls.fetch, 2);
|
||||
});
|
||||
|
||||
test('usage:并发调用共享同一 in-flight 请求', async () => {
|
||||
const { getUsage, calls } = setup();
|
||||
const [a, b] = await Promise.all([getUsage(), getUsage()]);
|
||||
assert.equal(calls.fetch, 1);
|
||||
assert.deepEqual(a, b);
|
||||
});
|
||||
|
||||
test('usage:fetch 抛错 → null 且负缓存 60s(不重试风暴),日志不含 token', async () => {
|
||||
const { getUsage, calls, logs } = setup({ fetchError: new Error('network down') });
|
||||
assert.equal(await getUsage(), null);
|
||||
assert.equal(await getUsage(), null);
|
||||
assert.equal(calls.fetch, 1); // 失败结果同样被缓存
|
||||
assert.ok(logs.some((m) => m.includes('network down')));
|
||||
assert.ok(logs.every((m) => !m.includes(SECRET)));
|
||||
});
|
||||
|
||||
test('usage:HTTP 非 200 → null', async () => {
|
||||
const { getUsage, logs } = setup({ status: 401 });
|
||||
assert.equal(await getUsage(), null);
|
||||
assert.ok(logs.some((m) => m.includes('401')));
|
||||
});
|
||||
|
||||
test('usage:无凭证 → null 且不发起请求', async () => {
|
||||
const { getUsage, calls } = setup({ token: null });
|
||||
assert.equal(await getUsage(), null);
|
||||
assert.equal(calls.fetch, 0);
|
||||
});
|
||||
|
||||
test('usage:响应缺少两个窗口字段 → null;只有一个窗口 → 另一侧为 null', async () => {
|
||||
const none = setup({ body: { unrelated: true } });
|
||||
assert.equal(await none.getUsage(), null);
|
||||
|
||||
const onlyWeek = setup({ body: { seven_day: { utilization: 88.6, resets_at: null } } });
|
||||
assert.deepEqual(await onlyWeek.getUsage(), {
|
||||
session: null,
|
||||
weekly: { percent: 89, resetsAt: null },
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user