@miphamai/cli 0.85.54 → 0.85.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ /**
2
+ * 收尾评审闸门:把「本轮写了文件之后的独立评审」做成可复用的模块。
3
+ *
4
+ * 两条写入路径共用同一个提取器(`writtenPathsFor`)—— 主引擎的
5
+ * `Engine.executeTool` 与子代理的直接 `tool.execute`。只接一条,
6
+ * 「把实现委派给 subagent」这种最常见形态就会让闸门的计数器停在 0,
7
+ * 而闸门看起来一切正常。
8
+ */
9
+
10
+ import { SubAgent } from '../agent/sub-agent'
11
+ import type { SubAgentServices } from '../agent/services'
12
+ import type { AgentDefinition } from '../agent/types'
13
+ import type { ProviderRegistry } from '../providers/registry'
14
+ import type { ToolDefinition } from '../shared/index.ts'
15
+ import type { PermissionSystem } from './permission'
16
+ import type { BaselineReport } from './verification-baseline'
17
+ export { writtenPathsFor } from './write-paths'
18
+
19
+ export interface ReviewRequest {
20
+ cwd: string
21
+ userPrompt: string
22
+ changedFiles: string[]
23
+ round: number
24
+ maxRounds: number
25
+ /** round > 1 时携带上一轮 findings,供复核而不是从头再报一遍。 */
26
+ previousFindings?: string
27
+ /** 机械检查的观察结果:哪些跑了(含成败)、哪些没跑。 */
28
+ baseline?: BaselineReport
29
+ /** 作者对着 findings 的最后一条说明(申辩或已修复说明),截断后传入。 */
30
+ authorResponse?: string
31
+ /** 本轮 turn 的取消信号 —— Ctrl+C / daemon stop 必须能取消评审。 */
32
+ signal?: AbortSignal
33
+ }
34
+
35
+ export type ReviewResult =
36
+ { status: 'pass' } | { status: 'fail'; findings: string } | { status: 'error'; message: string }
37
+
38
+ export type ReviewRunner = (req: ReviewRequest) => Promise<ReviewResult>
39
+
40
+ /** 引擎收下的闸门配置:开哪一档、跑几次、在哪个目录、用哪个 runner。 */
41
+ export interface ReviewGateConfig {
42
+ enabled: boolean
43
+ maxRounds: number
44
+ /**
45
+ * Reviewer working directory. A getter is resolved at review time so `/cd`
46
+ * moves the reviewer with the session; a string is for callers whose cwd is
47
+ * fixed for the engine's lifetime (the daemon's session cwd).
48
+ */
49
+ cwd: string | (() => string)
50
+ runner: ReviewRunner
51
+ }
52
+
53
+ export interface ReviewRunnerDeps {
54
+ registry: ProviderRegistry
55
+ toolRegistry: Map<string, ToolDefinition>
56
+ permission?: PermissionSystem
57
+ services?: SubAgentServices
58
+ }
59
+
60
+ /**
61
+ * 解析首个 `VERDICT: PASS|FAIL`;FAIL 时取 findings。
62
+ *
63
+ * 提示词约定 findings 写在 verdict **之前**(verdict 是最后一行),所以先取
64
+ * match 之前的正文;若之前为空(评审者写在了后面),再退回取 match 之后。
65
+ * 只取一侧会让「按提示词写」的评审永远返回空 findings —— 阻塞了却没有可修的信号。
66
+ */
67
+ export function parseReviewVerdict(
68
+ text: string,
69
+ ): { verdict: 'pass' | 'fail'; findings: string } | null {
70
+ const match = /^\s*VERDICT:\s*(PASS|FAIL)\b/im.exec(text)
71
+ if (!match) return null
72
+ const verdict = match[1]!.toLowerCase() === 'pass' ? 'pass' : 'fail'
73
+ if (verdict === 'pass') return { verdict, findings: '' }
74
+ const before = text.slice(0, match.index).trim()
75
+ const after = text.slice(match.index + match[0].length).trim()
76
+ return { verdict, findings: before || after }
77
+ }
78
+
79
+ export function buildReviewPrompt(req: ReviewRequest): string {
80
+ const lines = [
81
+ '你是一次独立评审。你看不到作者的推理链;作者也看不到你的。',
82
+ '判断:下面的用户需求是否被产物正确、完整地实现。',
83
+ '',
84
+ `工作目录: ${req.cwd}`,
85
+ '',
86
+ '用户需求:',
87
+ req.userPrompt,
88
+ '',
89
+ '本轮改动的文件:',
90
+ ...(req.changedFiles.length > 0
91
+ ? req.changedFiles.map((f) => `- ${f}`)
92
+ : ['- (没有记录到具体路径;请在工作目录里自行辨认本轮产物)']),
93
+ ]
94
+
95
+ if (req.baseline) {
96
+ lines.push('', '机械检查状态:')
97
+ lines.push(`- 期望: ${req.baseline.expected.join(' / ') || '(无)'}`)
98
+ if (req.baseline.ran.length === 0) {
99
+ lines.push('- 已跑: (无)')
100
+ } else {
101
+ lines.push('- 已跑:')
102
+ for (const run of req.baseline.ran) {
103
+ const outcome = run.ok ? '通过' : '失败'
104
+ lines.push(` - ${run.command} → ${outcome}${run.stale ? '(最后一次修改之前,不算数)' : ''}`)
105
+ }
106
+ }
107
+ lines.push(`- 未运行: ${req.baseline.missing.join(' / ') || '(无)'}`)
108
+ lines.push('未运行的检查不得当作已通过。')
109
+ }
110
+
111
+ if (req.round > 1) {
112
+ lines.push(
113
+ '',
114
+ `这是第 ${req.round}/${req.maxRounds} 轮复核。`,
115
+ '上一轮评审发现:',
116
+ req.previousFindings || '(未记录)',
117
+ '',
118
+ '作者的最后说明:',
119
+ req.authorResponse || '(未提供)',
120
+ '',
121
+ '请判断上一轮的问题是否已修复,或作者的说明是否成立;不要从头重复报告已解决的问题。',
122
+ )
123
+ }
124
+
125
+ lines.push(
126
+ '',
127
+ '要求:',
128
+ '- 只读:不要修改任何文件。',
129
+ '- 假设存在缺陷:主动找,不要做确认性审查。',
130
+ '- 改名/去重/生成标识:结果必须与已有集合不相交。',
131
+ '- 同一事实有两种表示(文本/JSON、服务端/客户端)时,必须交叉一致。',
132
+ '- 禁止静默修正用户输入:钳制、默认值替换要么报错,要么显式告警。',
133
+ '- 每条问题给 file:line、为什么错、以及**建议的**复现步骤(你无法执行命令)。',
134
+ '- 结束时最后一行必须是以下之一:',
135
+ 'VERDICT: PASS',
136
+ 'VERDICT: FAIL',
137
+ 'FAIL 时把 findings 写在 verdict 行之前。',
138
+ )
139
+
140
+ return lines.join('\n')
141
+ }
142
+
143
+ const REVIEW_SYSTEM_PROMPT = [
144
+ '你是一个只读的代码评审者,负责在作者收尾前独立检查产物。',
145
+ '你只能使用 Read / Grep / Glob;不能修改文件,不能执行命令,不能派生子代理。',
146
+ '假设存在缺陷。优先检查:边界输入、错误路径、两个表示之间的一致性、静默丢弃或静默改写的值。',
147
+ '每条 finding 必须给 file:line 和理由;复现步骤只能是建议,因为你无法执行。',
148
+ '最后一行必须是 `VERDICT: PASS` 或 `VERDICT: FAIL`。',
149
+ ].join('\n')
150
+
151
+ export function createReviewRunner(deps: ReviewRunnerDeps): ReviewRunner {
152
+ return async (req) => {
153
+ const agentDef: AgentDefinition = {
154
+ name: 'review-gate',
155
+ description: 'Independent read-only reviewer for the review gate',
156
+ systemPrompt: REVIEW_SYSTEM_PROMPT,
157
+ tools: 'Read,Grep,Glob',
158
+ model: 'inherit',
159
+ permissionMode: 'plan',
160
+ maxTurns: 8,
161
+ source: 'builtin',
162
+ }
163
+
164
+ try {
165
+ const sub = new SubAgent(
166
+ deps.registry,
167
+ deps.toolRegistry,
168
+ deps.permission,
169
+ undefined,
170
+ undefined,
171
+ undefined,
172
+ deps.services,
173
+ )
174
+ const out = await sub.execute(buildReviewPrompt(req), 'review gate', {
175
+ type: 'general',
176
+ agentDef,
177
+ cwd: req.cwd,
178
+ maxTurns: 8,
179
+ signal: req.signal,
180
+ })
181
+ const parsed = parseReviewVerdict(out)
182
+ if (!parsed) {
183
+ return { status: 'error', message: 'reviewer produced no VERDICT line' }
184
+ }
185
+ return parsed.verdict === 'pass'
186
+ ? { status: 'pass' }
187
+ : { status: 'fail', findings: parsed.findings }
188
+ } catch (err) {
189
+ return { status: 'error', message: err instanceof Error ? err.message : String(err) }
190
+ }
191
+ }
192
+ }
@@ -130,6 +130,24 @@
130
130
  "oracleCode": "export function chunk<T>(arr: T[], size: number): T[][] {\n if (!Number.isInteger(size) || size <= 0) throw new RangeError('size must be a positive integer')\n const out: T[][] = []\n for (let i = 0; i < arr.length; i += size) out.push(arr.slice(i, i + size))\n return out\n}\n",
131
131
  "skill": "tdd",
132
132
  "split": "gate"
133
+ },
134
+ {
135
+ "id": "perf-safe-unique-rename",
136
+ "category": "test-driven",
137
+ "skill": "safe-coding",
138
+ "split": "gate",
139
+ "prompt": "实现并导出 dedupeNames 函数:export function dedupeNames(names: string[]): string[]。首次出现的名字原样保留;重复出现的名字按出现顺序追加 _2、_3……;生成的名字不得与输入里的任何原名、或任何已经输出的名字相同;输出顺序与输入一致。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
140
+ "testCode": "import { test, expect } from 'bun:test'\nimport { dedupeNames } from './solution'\n\ntest('renames duplicates', () => {\n expect(dedupeNames(['a', 'a'])).toEqual(['a', 'a_2'])\n})\n\ntest('generated name never collides with an original', () => {\n expect(dedupeNames(['a', 'a_2', 'a'])).toEqual(['a', 'a_2', 'a_3'])\n expect(dedupeNames(['x', 'x', 'x_2'])).toEqual(['x', 'x_3', 'x_2'])\n expect(dedupeNames(['a', 'a_2', 'a', 'a'])).toEqual(['a', 'a_2', 'a_3', 'a_4'])\n})\n\ntest('preserves order and names', () => {\n expect(dedupeNames(['b', 'a', 'b', 'a'])).toEqual(['b', 'a', 'b_2', 'a_2'])\n})\n",
141
+ "oracleCode": "export function dedupeNames(names: string[]): string[] {\n const reserved = new Set(names)\n const used = new Set<string>()\n return names.map((name) => {\n if (!used.has(name)) {\n used.add(name)\n return name\n }\n let n = 2\n while (reserved.has(`${name}_${n}`) || used.has(`${name}_${n}`)) n++\n const candidate = `${name}_${n}`\n used.add(candidate)\n return candidate\n })\n}\n"
142
+ },
143
+ {
144
+ "id": "perf-safe-dual-render",
145
+ "category": "test-driven",
146
+ "skill": "safe-coding",
147
+ "split": "gate",
148
+ "prompt": "实现并导出 summarizeColumns 函数:export function summarizeColumns(headers: string[]): { json: Array<{ index: number; name: string }>; text: string }。json[i].index 从 1 开始;text 每行形如 [index] name;同一列在两种表示里的 index 必须相同,不得遗漏或重排。只输出 TypeScript 代码,不要解释、不要 markdown 代码块。",
149
+ "testCode": "import { test, expect } from 'bun:test'\nimport { summarizeColumns } from './solution'\n\ntest('renders columns in both forms', () => {\n const r = summarizeColumns(['a', 'b'])\n expect(r.json).toEqual([\n { index: 1, name: 'a' },\n { index: 2, name: 'b' },\n ])\n expect(r.text.split('\\n')).toEqual(['[1] a', '[2] b'])\n})\n\ntest('both representations agree per column, even for numeric names', () => {\n const r = summarizeColumns(['b_2', 'b'])\n const lines = r.text.split('\\n')\n expect(lines).toHaveLength(r.json.length)\n lines.forEach((line, i) => {\n const m = /^\\[(\\d+)\\] (.*)$/.exec(line)\n expect(m, line).not.toBeNull()\n expect(Number(m![1])).toBe(r.json[i]!.index)\n expect(m![2]).toBe(r.json[i]!.name)\n })\n})\n",
150
+ "oracleCode": "export function summarizeColumns(headers: string[]): {\n json: Array<{ index: number; name: string }>\n text: string\n} {\n const json = headers.map((name, i) => ({ index: i + 1, name }))\n return { json, text: json.map(({ index, name }) => `[${index}] ${name}`).join('\\n') }\n}\n"
133
151
  }
134
152
  ]
135
153
  }
@@ -0,0 +1,277 @@
1
+ /**
2
+ * 观察式项目验证基线:从清单文件推导「该项目应有的机械检查」,再用**本轮
3
+ * 实际执行过的命令**去比对。这里只读文件与命令字符串,不执行任何项目代码。
4
+ *
5
+ * 失败方向是刻意选的:匹配太严 ⇒ 多问一次;匹配太松 ⇒ 把没跑的检查当成
6
+ * 跑过了。后者正是这道基线要消灭的静默放过。
7
+ */
8
+
9
+ import { existsSync, readFileSync } from 'node:fs'
10
+ import { dirname, join, resolve } from 'node:path'
11
+
12
+ export type ProjectKind = 'rust' | 'node' | 'python' | 'go'
13
+
14
+ export interface CheckMatcher {
15
+ /** 命令段开头的 token,逐字相同。 */
16
+ prefix: string[]
17
+ /** 其他同样算数的段首形式(如无锁文件时任一包管理器)。 */
18
+ prefixAlternatives?: string[][]
19
+ /** 还必须出现在段内的标志位(如 `--check`)。 */
20
+ requiredFlags?: string[]
21
+ }
22
+
23
+ export interface ExpectedCheck {
24
+ id: string
25
+ /** 给人看的命令形态,也是报告里的「缺失项」名字。 */
26
+ label: string
27
+ matcher: CheckMatcher
28
+ }
29
+
30
+ export interface ProjectBaseline {
31
+ kind: ProjectKind
32
+ manifest: string
33
+ sourceExtensions: string[]
34
+ checks: ExpectedCheck[]
35
+ }
36
+
37
+ export interface TurnCommand {
38
+ command: string
39
+ ok: boolean
40
+ seq: number
41
+ }
42
+
43
+ /** Engine-side config. `cwd` is resolved at check time so `/cd` is followed. */
44
+ export interface VerificationBaselineConfig {
45
+ enabled: boolean
46
+ cwd: string | (() => string)
47
+ }
48
+
49
+ export interface BaselineReport {
50
+ expected: string[]
51
+ ran: Array<{ command: string; ok: boolean; stale: boolean }>
52
+ missing: string[]
53
+ }
54
+
55
+ const PACKAGE_RUNNERS = new Set(['pnpm', 'npm', 'yarn', 'bun'])
56
+
57
+ function readable(path: string): string | null {
58
+ try {
59
+ return readFileSync(path, 'utf-8')
60
+ } catch {
61
+ return null
62
+ }
63
+ }
64
+
65
+ function check(
66
+ id: string,
67
+ label: string,
68
+ prefix: string[],
69
+ requiredFlags?: string[],
70
+ ): ExpectedCheck {
71
+ return { id, label, matcher: { prefix, ...(requiredFlags ? { requiredFlags } : {}) } }
72
+ }
73
+
74
+ function detectRust(cwd: string): ProjectBaseline | null {
75
+ if (!existsSync(join(cwd, 'Cargo.toml'))) return null
76
+ const content = readable(join(cwd, 'Cargo.toml'))
77
+ if (content === null) return null
78
+ // Garbage in the manifest means no baseline: the derived commands could
79
+ // never describe this directory.
80
+ if (!/^\s*\[(?:package|workspace)\]/m.test(content)) return null
81
+ return {
82
+ kind: 'rust',
83
+ manifest: 'Cargo.toml',
84
+ sourceExtensions: ['.rs'],
85
+ checks: [
86
+ check('rust-fmt', 'cargo fmt --check', ['cargo', 'fmt'], ['--check']),
87
+ check('rust-clippy', 'cargo clippy', ['cargo', 'clippy']),
88
+ check('rust-test', 'cargo test', ['cargo', 'test']),
89
+ ],
90
+ }
91
+ }
92
+
93
+ const LOCK_RUNNERS: Array<[string, string]> = [
94
+ ['pnpm-lock.yaml', 'pnpm'],
95
+ ['package-lock.json', 'npm'],
96
+ ['yarn.lock', 'yarn'],
97
+ ['bun.lockb', 'bun'],
98
+ ['bun.lock', 'bun'],
99
+ ]
100
+
101
+ /**
102
+ * runner 取自**最近的**锁文件。只找 cwd 会把 monorepo 的子包(锁文件在
103
+ * 仓库根)误判成 npm,于是 `pnpm test` 永远对不上 `npm test` —— 默认开启
104
+ * 时这是每个写码轮次都误报。走到文件系统根为止;找不到返回 null(任一
105
+ * 包管理器都算数)。
106
+ */
107
+ function findNodeRunner(cwd: string): string | null {
108
+ let dir = resolve(cwd)
109
+ for (;;) {
110
+ for (const [file, runner] of LOCK_RUNNERS) {
111
+ if (existsSync(join(dir, file))) return runner
112
+ }
113
+ const parent = dirname(dir)
114
+ if (parent === dir) return null
115
+ dir = parent
116
+ }
117
+ }
118
+
119
+ function detectNode(cwd: string): ProjectBaseline | null {
120
+ const raw = readable(join(cwd, 'package.json'))
121
+ if (raw === null) return null
122
+ let scripts: Record<string, unknown>
123
+ try {
124
+ const parsed = JSON.parse(raw) as { scripts?: Record<string, unknown> }
125
+ scripts = parsed.scripts && typeof parsed.scripts === 'object' ? parsed.scripts : {}
126
+ } catch {
127
+ return null
128
+ }
129
+
130
+ const runner = findNodeRunner(cwd)
131
+ const checks: ExpectedCheck[] = []
132
+ const addScript = (id: string, script: string): void => {
133
+ if (typeof scripts[script] !== 'string') return
134
+ if (runner) {
135
+ checks.push(check(id, `${runner} ${script}`, [runner, script]))
136
+ return
137
+ }
138
+ // No lockfile anywhere: any of the four runners is a legitimate way to run
139
+ // the script, so accept all of them.
140
+ checks.push({
141
+ id,
142
+ label: `npm ${script}`,
143
+ matcher: {
144
+ prefix: ['npm', script],
145
+ prefixAlternatives: [
146
+ ['pnpm', script],
147
+ ['yarn', script],
148
+ ['bun', script],
149
+ ],
150
+ },
151
+ })
152
+ }
153
+ addScript('node-test', 'test')
154
+ addScript('node-lint', 'lint')
155
+ if (typeof scripts.typecheck === 'string') {
156
+ addScript('node-typecheck', 'typecheck')
157
+ } else if (existsSync(join(cwd, 'tsconfig.json'))) {
158
+ checks.push(check('node-tsc', 'tsc --noEmit', ['tsc'], ['--noEmit']))
159
+ }
160
+ addScript('node-format', 'format:check')
161
+
162
+ return {
163
+ kind: 'node',
164
+ manifest: 'package.json',
165
+ sourceExtensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'],
166
+ checks,
167
+ }
168
+ }
169
+
170
+ function detectPython(cwd: string): ProjectBaseline | null {
171
+ if (!existsSync(join(cwd, 'pyproject.toml'))) return null
172
+ const content = readable(join(cwd, 'pyproject.toml'))
173
+ if (content === null) return null
174
+ if (!/^\s*\[(?:project|tool\.)/m.test(content)) return null
175
+ return {
176
+ kind: 'python',
177
+ manifest: 'pyproject.toml',
178
+ sourceExtensions: ['.py'],
179
+ checks: [
180
+ check('python-ruff-check', 'ruff check', ['ruff', 'check']),
181
+ check('python-ruff-format', 'ruff format --check', ['ruff', 'format'], ['--check']),
182
+ check('python-pytest', 'pytest', ['pytest']),
183
+ ],
184
+ }
185
+ }
186
+
187
+ function detectGo(cwd: string): ProjectBaseline | null {
188
+ if (!existsSync(join(cwd, 'go.mod'))) return null
189
+ const content = readable(join(cwd, 'go.mod'))
190
+ if (content === null) return null
191
+ if (!/^\s*module\s+/m.test(content)) return null
192
+ return {
193
+ kind: 'go',
194
+ manifest: 'go.mod',
195
+ sourceExtensions: ['.go'],
196
+ checks: [
197
+ check('go-fmt', 'gofmt -l', ['gofmt'], ['-l']),
198
+ check('go-vet', 'go vet', ['go', 'vet']),
199
+ check('go-test', 'go test', ['go', 'test']),
200
+ ],
201
+ }
202
+ }
203
+
204
+ /** 先命中先得;任何读取/解析失败都返回 null(基线静默不启用)。 */
205
+ export function detectProjectBaseline(cwd: string): ProjectBaseline | null {
206
+ return detectRust(cwd) ?? detectNode(cwd) ?? detectPython(cwd) ?? detectGo(cwd)
207
+ }
208
+
209
+ function commandSegments(command: string): string[][] {
210
+ return command
211
+ .split(/[;&|]{1,2}/)
212
+ .map((segment) => segment.trim().split(/\s+/).filter(Boolean))
213
+ .filter((tokens) => tokens.length > 0)
214
+ }
215
+
216
+ /**
217
+ * 命令是否覆盖某个检查。按 `&&`/`||`/`;`/`|` 切段后做段首前缀匹配;
218
+ * 含 `--help`/`-h` 的段不算执行。包管理器的可选 `run` 跳过(`pnpm run test`
219
+ * 等价 `pnpm test`),且只对包管理器生效。
220
+ */
221
+ export function commandCovers(matcher: CheckMatcher, command: string): boolean {
222
+ const prefixes = [matcher.prefix, ...(matcher.prefixAlternatives ?? [])]
223
+ for (const original of commandSegments(command)) {
224
+ if (original.includes('--help') || original.includes('-h')) continue
225
+ for (const prefix of prefixes) {
226
+ let tokens = original
227
+ if (PACKAGE_RUNNERS.has(prefix[0] ?? '') && tokens[1] === 'run') {
228
+ tokens = [tokens[0]!, ...tokens.slice(2)]
229
+ }
230
+ if (!prefix.every((token, i) => tokens[i] === token)) continue
231
+ if (
232
+ matcher.requiredFlags &&
233
+ !matcher.requiredFlags.every((flag) => original.includes(flag))
234
+ ) {
235
+ continue
236
+ }
237
+ return true
238
+ }
239
+ }
240
+ return false
241
+ }
242
+
243
+ /** 本轮是否写了该项目的源码文件(只认扩展名)。 */
244
+ export function hasSourceWrite(baseline: ProjectBaseline, paths: Iterable<string>): boolean {
245
+ for (const path of paths) {
246
+ const lower = path.toLowerCase()
247
+ if (baseline.sourceExtensions.some((ext) => lower.endsWith(ext))) return true
248
+ }
249
+ return false
250
+ }
251
+
252
+ /**
253
+ * 汇总本轮命令。`stale` 的命令仍然列出来(作者需要看到自己跑过什么),
254
+ * 但只有发生在最近一次源码写入之后的命中才算覆盖。
255
+ */
256
+ export function evaluateBaseline(
257
+ baseline: ProjectBaseline,
258
+ commands: TurnCommand[],
259
+ lastSourceWriteSeq: number,
260
+ ): BaselineReport {
261
+ const ran: BaselineReport['ran'] = []
262
+ const covered = new Set<string>()
263
+
264
+ for (const command of commands) {
265
+ const matched = baseline.checks.filter((c) => commandCovers(c.matcher, command.command))
266
+ if (matched.length === 0) continue
267
+ const stale = command.seq <= lastSourceWriteSeq
268
+ ran.push({ command: command.command, ok: command.ok, stale })
269
+ if (!stale) for (const c of matched) covered.add(c.label)
270
+ }
271
+
272
+ return {
273
+ expected: baseline.checks.map((c) => c.label),
274
+ ran,
275
+ missing: baseline.checks.filter((c) => !covered.has(c.label)).map((c) => c.label),
276
+ }
277
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 哪些工具调用写了哪些文件 —— 收尾评审闸门的共享词汇。
3
+ *
4
+ * 单独成文件是为了避免 import 环:`sub-agent.ts` 需要它,而 `review-gate.ts`
5
+ * 需要 `SubAgent`。两条写入路径(主引擎与子代理)共用同一个提取器。
6
+ */
7
+
8
+ import { extractBashFileAccess } from './permission-rules'
9
+
10
+ /** 成功写入的文件路径;只读工具返回空数组。 */
11
+ export function writtenPathsFor(toolName: string, params: Record<string, unknown>): string[] {
12
+ if (toolName === 'Bash') {
13
+ const command = params.command
14
+ return typeof command === 'string' ? extractBashFileAccess(command).write : []
15
+ }
16
+ if (toolName !== 'Write' && toolName !== 'Edit') return []
17
+ const p = params.file_path
18
+ return typeof p === 'string' && p.length > 0 ? [p] : []
19
+ }
@@ -33,7 +33,8 @@ import { HookEngine } from '../core/hooks'
33
33
  import { registerBuiltinHooks } from '../core/merge-gate'
34
34
  import { loadHookConfigs } from '../core/hooks-config'
35
35
  import { isSafeMode } from '../core/safe-mode'
36
- import { loadSettingsJson } from '../config/loader'
36
+ import { loadReviewGateConfig, loadVerificationConfig, loadSettingsJson } from '../config/loader'
37
+ import { createReviewRunner } from '../core/review-gate'
37
38
  import { getWorkspaceTrust, warnProjectHooksSkipped } from '../core/workspace-trust'
38
39
  import { AgentRegistry } from '../agent/agent-registry'
39
40
  import { InstructionsLoader } from '../core/instructions'
@@ -223,6 +224,26 @@ export function wireDaemonEngine(engine: QueryEngine, opts: DaemonEngineCapabili
223
224
  // 语义等价于不接(`llmChat` 本就是 `this.llm ?? this.registry`),接上是为了让
224
225
  // 两个入口的能力集合真的相等;D2 靠它证明「先修语义再对等」这条顺序约束。
225
226
  engine.setLlm(opts.registry)
227
+
228
+ // Review gate: same factory as the interactive CLI. `cwd` is the **session's**,
229
+ // not the daemon process's — reviewing the wrong tree is worse than not
230
+ // reviewing, and passing it as `worktreePath` would also write a trust entry.
231
+ engine.setReviewGate({
232
+ ...loadReviewGateConfig(),
233
+ cwd: opts.cwd,
234
+ runner: createReviewRunner({
235
+ registry: opts.registry,
236
+ toolRegistry: engine.getTools(),
237
+ permission: engine.getPermission(),
238
+ services: engine.getSubAgentServices(),
239
+ }),
240
+ })
241
+
242
+ // Verification baseline: observation only, session cwd (same as the reviewer).
243
+ engine.setVerificationBaseline({
244
+ ...loadVerificationConfig(),
245
+ cwd: opts.cwd,
246
+ })
226
247
  }
227
248
 
228
249
  /**
@@ -1017,6 +1017,10 @@
1017
1017
  "turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
1018
1018
  "turn_refused_reason": "The model declined this request: {reason}",
1019
1019
  "stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
1020
+ "review_gate_error": "Review gate could not run: {message}. Continuing without a review.",
1021
+ "verification_missing": "This turn wrote source files after the last mechanical check — these baseline checks have not run since the last edit: {missing}. Run them now, or end with two explicit sections: Verified / Not verified.",
1022
+ "verification_budget_spent": "All tool-calling rounds for this turn are used, so these baseline checks were not run: {missing}.",
1023
+ "review_gate_budget_spent": "Review gate reached its {max}-review limit for this turn; continuing without another review.",
1020
1024
  "mcp_not_connected": "Error: MCP server \"{server}\" not connected",
1021
1025
  "mcp_tool_error": "MCP tool error: {error}",
1022
1026
  "mcp_auth_required": "MCP server \"{server}\" needs authorization for this tool (the server asked for more OAuth scope). Re-authenticate with: /mcp connect {server}",
@@ -1017,6 +1017,10 @@
1017
1017
  "turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
1018
1018
  "turn_refused_reason": "模型拒绝了这次请求:{reason}",
1019
1019
  "stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
1020
+ "review_gate_error": "评审闸门无法运行:{message}。本次未评审,继续。",
1021
+ "verification_missing": "本轮写入了源码,但以下基线检查没有在最后一次修改之后运行:{missing}。请先运行它们,或在最终答复中按「已验证 / 未验证」两栏说明。",
1022
+ "verification_budget_spent": "本轮工具调用轮次已用尽,以下验证基线未执行:{missing}。",
1023
+ "review_gate_budget_spent": "评审闸门本轮已达 {max} 次上限,不再评审,继续。",
1020
1024
  "mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
1021
1025
  "mcp_tool_error": "MCP 工具错误:{error}",
1022
1026
  "mcp_auth_required": "MCP 服务器 \"{server}\" 需要为该工具授权(服务器要求更多 OAuth 作用域)。请重新认证:/mcp connect {server}",
package/src/index.tsx CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  loadCredentialMaskingConfig,
11
11
  loadCrossSessionConfig,
12
12
  loadSettingsJson,
13
+ loadReviewGateConfig,
14
+ loadVerificationConfig,
13
15
  settingsPathFor,
14
16
  loadDisabledMcpServers,
15
17
  } from './config/loader'
@@ -43,6 +45,7 @@ import { SkillsLoader } from './skills/loader'
43
45
  import { PluginManager } from './plugin/plugin-manager'
44
46
  import { loadPlugins } from './plugin/plugin-loader'
45
47
  import { createToolRegistry } from './tools'
48
+ import { createReviewRunner } from './core/review-gate'
46
49
  import { Context } from './vajra'
47
50
  import { mountSkills, SKILLS_KEY } from './skills/seam'
48
51
  import { mountLlm, LLM_KEY } from './providers/llm'
@@ -874,6 +877,28 @@ export async function runApp(options: RunOptions): Promise<void> {
874
877
  const inferenceHookConfig = loadInferenceHookConfig()
875
878
  engine.setInferenceHookConfig(inferenceHookConfig)
876
879
 
880
+ // Review gate: after a turn that wrote files, a fresh-context reviewer checks
881
+ // the artifact before the turn is allowed to end. The runner is the same
882
+ // factory the daemon uses, so both entry points carry the same capability.
883
+ // Must come **after** `setInferenceHookConfig`: `getSubAgentServices()` is a
884
+ // snapshot, and wiring earlier would give the reviewer a DLP-free services
885
+ // object — a second uninspected inference path.
886
+ engine.setReviewGate({
887
+ ...loadReviewGateConfig(),
888
+ cwd: () => process.cwd(),
889
+ runner: createReviewRunner({
890
+ registry,
891
+ toolRegistry: tools,
892
+ permission,
893
+ services: engine.getSubAgentServices(),
894
+ }),
895
+ })
896
+
897
+ engine.setVerificationBaseline({
898
+ ...loadVerificationConfig(),
899
+ cwd: () => process.cwd(),
900
+ })
901
+
877
902
  // `config.permission` / `permissionRestrictions` are applied up top, on the instance
878
903
  // handed to `new QueryEngine(...)` — the same one whose mode the system prompt reads.
879
904
 
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.54' as const
12
+ export const PACKAGE_VERSION = '0.85.55' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 5540 as const
93
+ export const TEST_COUNT = 5607 as const
@@ -700,6 +700,17 @@ export interface ToolContext {
700
700
  * than silently behaving like `general`.
701
701
  */
702
702
  parentMessages?: Message[]
703
+ /**
704
+ * Called after a tool successfully wrote a file.
705
+ *
706
+ * The review gate has two write paths: `Engine.executeTool` (which tracks its
707
+ * own calls) and sub-agent loops (which call `tool.execute` directly and never
708
+ * pass through the engine). Without this callback a delegated implementation
709
+ * leaves the gate's counter at zero and the gate silently never fires.
710
+ */
711
+ onFileWrite?: (path: string) => void
712
+ /** Report an executed Bash command (success or failure). The verification baseline observes these. */
713
+ onCommand?: (command: string, ok: boolean) => void
703
714
  /**
704
715
  * Cancellation for the turn this tool call belongs to.
705
716
  *