@miphamai/cli 0.85.54 → 0.85.56

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,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
  /**
@@ -723,6 +723,14 @@
723
723
  "auto_mode": "auto mode on",
724
724
  "bypass": "bypass"
725
725
  },
726
+ "approval": {
727
+ "title": "Permission required",
728
+ "hint": "↑/↓ choose · Enter confirm · Esc deny",
729
+ "allow_once": "Allow once",
730
+ "allow_always": "Always allow — {rule}",
731
+ "persist_note": "Writes a user-level allow rule that applies from now on.",
732
+ "deny": "Deny"
733
+ },
726
734
  "loading": {
727
735
  "doodling": "Doodling",
728
736
  "forging": "Forging",
@@ -979,7 +987,8 @@
979
987
  "tool_denied_deny_rule": "Tool \"{name}\" blocked by a deny rule (\"{pattern}\"). Deny rules override permission mode — try a different approach, or drop the rule with: /permissions remove \"{pattern}\"",
980
988
  "tool_denied_ask_rule": "Tool \"{name}\" requires approval (ask rule: \"{pattern}\"). Approve when prompted, or stop being asked with: /permissions allow \"{pattern}\"",
981
989
  "tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\").",
982
- "tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool.",
990
+ "tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. If the user explicitly asked for this action, have them state it in their own message — a request that names the action can clear a soft block. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so it is broader than this refusal needs.",
991
+ "tool_denied_by_user": "The user declined this tool call, so it did not run. Do not re-issue it or try to obtain the same effect another way unless the user asks.",
983
992
  "tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
984
993
  "tool_denied_world_writable_chmod": "Tool \"{name}\" was refused: this is a recursive chmod that grants world-write to a target the command does not bound (\"{target}\"). A world-writable tree plus a target produced at run time is how permissions end up loosened far past what was asked for, and neither an allow rule nor the permission mode can bound where the grant reaches. Name the directory literally instead — `chmod -R 777 ./dist` rather than `chmod -R 777 $DIR` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_CHMOD_PROMPT=1",
985
994
  "tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
@@ -1017,6 +1026,10 @@
1017
1026
  "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
1027
  "turn_refused_reason": "The model declined this request: {reason}",
1019
1028
  "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.",
1029
+ "review_gate_error": "Review gate could not run: {message}. Continuing without a review.",
1030
+ "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.",
1031
+ "verification_budget_spent": "All tool-calling rounds for this turn are used, so these baseline checks were not run: {missing}.",
1032
+ "review_gate_budget_spent": "Review gate reached its {max}-review limit for this turn; continuing without another review.",
1020
1033
  "mcp_not_connected": "Error: MCP server \"{server}\" not connected",
1021
1034
  "mcp_tool_error": "MCP tool error: {error}",
1022
1035
  "mcp_auth_required": "MCP server \"{server}\" needs authorization for this tool (the server asked for more OAuth scope). Re-authenticate with: /mcp connect {server}",
@@ -723,6 +723,14 @@
723
723
  "auto_mode": "自动模式",
724
724
  "bypass": "绕过权限"
725
725
  },
726
+ "approval": {
727
+ "title": "需要授权",
728
+ "hint": "↑/↓ 选择 · Enter 确认 · Esc 拒绝",
729
+ "allow_once": "允许一次",
730
+ "allow_always": "总是允许 — {rule}",
731
+ "persist_note": "会写入用户级 allow 规则,从本次起长期生效。",
732
+ "deny": "拒绝"
733
+ },
726
734
  "loading": {
727
735
  "doodling": "涂鸦中",
728
736
  "forging": "锻造中",
@@ -979,7 +987,8 @@
979
987
  "tool_denied_deny_rule": "工具 \"{name}\" 被拒绝规则(\"{pattern}\")阻止。拒绝规则优先于权限模式 — 请改用其他方式,或移除该规则:/permissions remove \"{pattern}\"",
980
988
  "tool_denied_ask_rule": "工具 \"{name}\" 需要批准(ask 规则:\"{pattern}\")。请在提示时批准,或不再询问:/permissions allow \"{pattern}\"",
981
989
  "tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可)。",
982
- "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,故优先把这次调用改成可接受的,而不是放行整个工具。",
990
+ "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则。如果用户确实明确要求了这个动作,请让用户在自己的消息里明确说出来 —— 点名该动作的请求可以清除软拦截。注意:`/permissions allow \"{name}\"` 会让此后对该工具的**每一次**调用都跳过分类器,而不只是这一次,比这次拒绝所需的范围更宽。",
991
+ "tool_denied_by_user": "用户拒绝了这次工具调用,因此它没有运行。除非用户主动要求,否则不要重发这次调用,也不要换一种方式达成同一效果。",
983
992
  "tool_denied_dangerous_rm": "工具 \"{name}\" 被拒绝:这是一条递归 rm,其目标并非命令里写出的路径(\"{target}\")。该目标要到命令运行时才产生,所以任何放行规则与权限模式都无法界定它会删掉什么。请改为字面写出目录名 —— 用 `rm -rf node_modules` 而不是 `rm -rf \"$(pwd)\"` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
984
993
  "tool_denied_world_writable_chmod": "工具 \"{name}\" 被拒绝:这是一条递归 chmod,它把「其他用户可写」授予了一个命令并未界定边界的目标(\"{target}\")。一棵世界可写的树,加上一个要到运行时才产生的目标,正是权限被放宽到远超所求的由来;而任何放行规则与权限模式都无法界定这次授权会伸到哪里。请改为字面写出目录名 —— 用 `chmod -R 777 ./dist` 而不是 `chmod -R 777 $DIR` —— 并把这次拒绝理解为对结果本身的禁止,而不只是这一种写法。关闭此检查:MIPHAM_DISABLE_CHMOD_PROMPT=1",
985
994
  "tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
@@ -1017,6 +1026,10 @@
1017
1026
  "turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
1018
1027
  "turn_refused_reason": "模型拒绝了这次请求:{reason}",
1019
1028
  "stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
1029
+ "review_gate_error": "评审闸门无法运行:{message}。本次未评审,继续。",
1030
+ "verification_missing": "本轮写入了源码,但以下基线检查没有在最后一次修改之后运行:{missing}。请先运行它们,或在最终答复中按「已验证 / 未验证」两栏说明。",
1031
+ "verification_budget_spent": "本轮工具调用轮次已用尽,以下验证基线未执行:{missing}。",
1032
+ "review_gate_budget_spent": "评审闸门本轮已达 {max} 次上限,不再评审,继续。",
1020
1033
  "mcp_not_connected": "错误:MCP 服务器 \"{server}\" 未连接",
1021
1034
  "mcp_tool_error": "MCP 工具错误:{error}",
1022
1035
  "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.56' 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 = 5648 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
  *
@@ -1,7 +1,7 @@
1
1
  import { SubAgent } from '../agent/sub-agent'
2
2
  import type { ProviderRegistry } from '../providers/registry'
3
3
  import type { Llm } from '../providers/llm'
4
- import type { ToolDefinition, SkillDefinition } from '../shared/index.ts'
4
+ import type { ToolDefinition, SkillDefinition, ToolContext } from '../shared/index.ts'
5
5
  import type { AgentDefinition } from '../agent/types'
6
6
  import type { PermissionSystem } from '../core/permission'
7
7
  import type { SubAgentServices } from '../agent/services'
@@ -24,6 +24,7 @@ export async function executeForkedSkill(
24
24
  permissionSystem?: PermissionSystem,
25
25
  llm?: Llm,
26
26
  services?: SubAgentServices,
27
+ toolContext?: Partial<ToolContext>,
27
28
  ): Promise<string> {
28
29
  const agentDef: AgentDefinition = {
29
30
  name: `skill:${skill.name}`,
@@ -49,7 +50,7 @@ export async function executeForkedSkill(
49
50
  ? `Execute the "${skill.name}" skill with arguments: ${args}`
50
51
  : `Execute the "${skill.name}" skill.`
51
52
 
52
- return sub.execute(prompt, `skill:${skill.name}`, { agentDef })
53
+ return sub.execute(prompt, `skill:${skill.name}`, { agentDef, toolContext })
53
54
  }
54
55
 
55
56
  function buildSkillSystemPrompt(skill: SkillDefinition): string {
@@ -103,6 +103,7 @@ export const skillTool: ToolDefinition = {
103
103
  ctx.permissionSystem,
104
104
  ctx.llm,
105
105
  ctx.subAgentServices,
106
+ ctx,
106
107
  )
107
108
  // Return to AI as internal context
108
109
  recordSkillUsage(skillName)
@@ -107,6 +107,7 @@ export const workflowTool: ToolDefinition = {
107
107
  getPermission: () => ctx.permissionSystem,
108
108
  getLlm: () => ctx.llm,
109
109
  getSubAgentServices: () => ctx.subAgentServices,
110
+ getToolContext: () => ctx,
110
111
  } as unknown as QueryEngine
111
112
 
112
113
  try {
package/src/ui/app.tsx CHANGED
@@ -31,6 +31,8 @@ import { InputBar } from './input'
31
31
  import { recordKeyEvent, recordRenderCommit } from './input-debug'
32
32
  import { ModelPicker } from './picker'
33
33
  import { CopyPicker, type CopyPickerItem } from './copy-picker'
34
+ import { ApprovalPrompt } from './approval-prompt'
35
+ import type { ApprovalChoice, ApprovalRequest } from '../core/approval-prompt'
34
36
  import { AgentFooter, type AgentEntry } from './agent-footer'
35
37
  import { GraftStatusLine } from './graft-status'
36
38
  import { checkForUpdatesAsync, type UpdateStatus } from '../shared/update'
@@ -386,6 +388,17 @@ export function App({
386
388
  [messages],
387
389
  )
388
390
  const [isLoading, setIsLoading] = useState(false)
391
+ /**
392
+ * An open permission prompt. The engine is awaiting `resolve` for this entry,
393
+ * so the turn is paused until the user answers (or aborts).
394
+ *
395
+ * Only `QueryEngine` can produce one — attach mode's `RemoteEngine` never
396
+ * hands in a prompter, so its denial path is unchanged.
397
+ */
398
+ const [pendingApproval, setPendingApproval] = useState<{
399
+ request: ApprovalRequest
400
+ resolve: (choice: ApprovalChoice) => void
401
+ } | null>(null)
389
402
  /** Idle-drain tick — bumped by the engine's onEnqueue callback whenever the
390
403
  * ScheduleWakeup timer fires while the engine is idle. Drives the idle-drain
391
404
  * effect so a queued /loop wakeup re-invokes without waiting for user input. */
@@ -1425,8 +1438,35 @@ export function App({
1425
1438
  recordRenderCommit()
1426
1439
  })
1427
1440
 
1441
+ // The engine's approval channel: it awaits this promise while the tool call
1442
+ // is held, and the modal resolves it. Attach mode (`RemoteEngine`) has no
1443
+ // setter — the daemon has no UI to ask — so the guard keeps its denial path
1444
+ // exactly as it was.
1445
+ useEffect(() => {
1446
+ if (!('setApprovalPrompter' in engine)) return
1447
+ engine.setApprovalPrompter(
1448
+ (request) =>
1449
+ new Promise<ApprovalChoice>((resolve) => {
1450
+ setPendingApproval({ request, resolve })
1451
+ }),
1452
+ )
1453
+ return () => engine.setApprovalPrompter(undefined)
1454
+ }, [engine])
1455
+
1428
1456
  useInput((input, key) => {
1429
1457
  recordKeyEvent(input, key)
1458
+ // A permission prompt is modal: every other key belongs to
1459
+ // `ApprovalPrompt`, and Escape must deny the call rather than abort the
1460
+ // whole turn. Ctrl+C still cancels — a human present wants to stop, not to
1461
+ // exit — so it resolves the prompt as a denial in place.
1462
+ if (pendingApproval) {
1463
+ if (key.ctrl && input === 'c') {
1464
+ pendingApproval.resolve('deny')
1465
+ setPendingApproval(null)
1466
+ ctrlC.reset()
1467
+ }
1468
+ return
1469
+ }
1430
1470
  // Ctrl+C:先关最上面那一层;没得关时**不退出**,只提示「再按一次」。
1431
1471
  //
1432
1472
  // 从前这里没有这个分支,而 Ink 自己的 Ctrl+C 处理(`exitOnCtrlC`,默认
@@ -1571,7 +1611,15 @@ export function App({
1571
1611
  })()}
1572
1612
 
1573
1613
  {/* Input with separator lines */}
1574
- {copyPicker ? (
1614
+ {pendingApproval ? (
1615
+ <ApprovalPrompt
1616
+ request={pendingApproval.request}
1617
+ onChoose={(choice) => {
1618
+ pendingApproval.resolve(choice)
1619
+ setPendingApproval(null)
1620
+ }}
1621
+ />
1622
+ ) : copyPicker ? (
1575
1623
  <CopyPicker
1576
1624
  items={copyPicker.items}
1577
1625
  onSelect={(item) => {