@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.
@@ -2,6 +2,7 @@ import type {
2
2
  StreamChunk,
3
3
  ToolDefinition,
4
4
  ToolResult,
5
+ ToolContext,
5
6
  InferenceHookConfig,
6
7
  CrsiConfig,
7
8
  CrossSessionConfig,
@@ -14,6 +15,14 @@ import { createAwakeTimer } from '../providers/fetch-utils'
14
15
  import type { ChatRequest } from '../providers/registry'
15
16
  import type { Llm } from '../providers/llm'
16
17
  import { ContextManager } from './context'
18
+ import { collectUserIntent } from './user-intent'
19
+ import {
20
+ deriveAllowRule,
21
+ isPromptable,
22
+ type ApprovalChoice,
23
+ type ApprovalPrompter,
24
+ type ApprovalRequest,
25
+ } from './approval-prompt'
17
26
  import { PermissionSystem } from './permission'
18
27
  import type { ApprovalDecision } from './permission'
19
28
  import type { HookEngine } from './hooks'
@@ -28,6 +37,14 @@ import type { Skills } from '../skills/seam'
28
37
  import { getBackgroundAgentRegistry } from '../agent/background-registry'
29
38
  import { RulesLoader } from './rules-loader'
30
39
  import { extractBashFileAccess } from './permission-rules'
40
+ import { writtenPathsFor, type ReviewGateConfig } from './review-gate'
41
+ import { commandFor } from './command-taps'
42
+ import { detectProjectBaseline, evaluateBaseline, hasSourceWrite } from './verification-baseline'
43
+ import type {
44
+ BaselineReport,
45
+ TurnCommand,
46
+ VerificationBaselineConfig,
47
+ } from './verification-baseline'
31
48
  import { noteToolOutcome, reviewLedger } from './merge-gate'
32
49
  import { unprovenCountClaims } from './number-provenance'
33
50
  import type { InstructionsLoader } from './instructions'
@@ -194,6 +211,16 @@ export class QueryEngine {
194
211
  /** 注入的 LLM chat 缝。未设置时回退 this.registry(strangler-fig)。 */
195
212
  private llm?: Llm
196
213
 
214
+ /**
215
+ * The CLI's interactive approval channel.
216
+ *
217
+ * Absent in every headless caller (daemon, bots, sub-agents, attach mode):
218
+ * there is nobody to ask, so `ask` keeps its old meaning — a flat refusal.
219
+ * The CLI hands this in from the Ink layer; see `core/approval-prompt.ts` for
220
+ * which asks may become a prompt.
221
+ */
222
+ private approvalPrompter?: ApprovalPrompter
223
+
197
224
  /** Pending /loop re-invocation prompts, enqueued by the ScheduleWakeup timer. */
198
225
  private wakeupQueue: Array<{ prompt: string; noop: boolean }> = []
199
226
 
@@ -461,6 +488,39 @@ export class QueryEngine {
461
488
  private instructionsLoader?: InstructionsLoader
462
489
  /** Files touched in the current turn (for rules matching). */
463
490
  private touchedFiles: Set<string> = new Set()
491
+ /** Review gate: successful file-write operations this turn (two write paths feed this). */
492
+ private reviewWriteOps = 0
493
+ /** Review gate: the paths written this turn, for the reviewer's brief. */
494
+ private turnWrites: Set<string> = new Set()
495
+ /**
496
+ * Review gate: increments at the start of every turn. A write callback
497
+ * captured by a background/delegated tool keeps the generation it was
498
+ * created in, so a late write from a finished turn cannot open this turn's
499
+ * gate.
500
+ */
501
+ private reviewTurnGeneration = 0
502
+ /** Review gate: config + runner. Absent means the gate is off. */
503
+ private reviewGate?: ReviewGateConfig
504
+ /** Review gate: reviews spent this turn. */
505
+ private reviewRounds = 0
506
+ /** Review gate: write generation already passed. -1 = nothing passed yet. */
507
+ private reviewedAtOps = -1
508
+ /** Review gate: this turn's user input (the reviewer's requirement). */
509
+ private turnPrompt = ''
510
+ /** Verification baseline: commands observed this turn (both tool paths). */
511
+ private turnCommands: TurnCommand[] = []
512
+ /** Verification baseline: writes with their order, to tell stale runs from fresh ones. */
513
+ private turnWriteEvents: Array<{ path: string; seq: number }> = []
514
+ /** Verification baseline: monotonic order shared by writes and commands. */
515
+ private turnOpSeq = 0
516
+ /** Verification baseline: config. Absent means the baseline is off. */
517
+ private verificationConfig?: VerificationBaselineConfig
518
+ /** Verification baseline: this turn's report (passed to the reviewer). */
519
+ private baselineReport?: BaselineReport
520
+ /** Verification baseline: blocked once already this turn. */
521
+ private verificationBlocked = false
522
+ /** Review gate: last FAIL findings, carried into the next review round. */
523
+ private lastReviewFindings?: string
464
524
  /** A tool call failed since the last nudge check. */
465
525
  private pendingToolFailure = false
466
526
  /** 本轮用户输入 —— 数字出处判定里它是合法的出处之一。 */
@@ -547,6 +607,28 @@ export class QueryEngine {
547
607
  }
548
608
  }
549
609
 
610
+ /** Count a successful file write for the review gate. */
611
+ private recordWrite(path: string): void {
612
+ this.reviewWriteOps++
613
+ this.turnWrites.add(path)
614
+ this.turnWriteEvents.push({ path, seq: ++this.turnOpSeq })
615
+ }
616
+
617
+ /** Record an observed Bash command (success or failure) for the verification baseline. */
618
+ private recordCommand(command: string, ok: boolean): void {
619
+ this.turnCommands.push({ command, ok, seq: ++this.turnOpSeq })
620
+ }
621
+
622
+ /** Wire the verification baseline. Absent/disabled means it never runs. */
623
+ setVerificationBaseline(config: VerificationBaselineConfig): void {
624
+ this.verificationConfig = config
625
+ }
626
+
627
+ /** Wire the review gate. Absent/disabled means the gate never runs. */
628
+ setReviewGate(config: ReviewGateConfig): void {
629
+ this.reviewGate = config
630
+ }
631
+
550
632
  /**
551
633
  * Inject path-scoped context for the files touched this round: matching rules
552
634
  * (`.mipham/rules/*.md`) and any nested instruction files (`CLAUDE.md` and
@@ -774,6 +856,22 @@ export class QueryEngine {
774
856
  // provider API (which would otherwise 400 on an empty/blank message).
775
857
  if (!userInput.trim()) return
776
858
 
859
+ // Review gate state is per turn: a new user message starts a new write
860
+ // generation, so a gate that passed the previous turn runs again if this
861
+ // one writes files.
862
+ this.reviewTurnGeneration++
863
+ this.reviewWriteOps = 0
864
+ this.turnWrites.clear()
865
+ this.turnCommands = []
866
+ this.turnWriteEvents = []
867
+ this.turnOpSeq = 0
868
+ this.baselineReport = undefined
869
+ this.verificationBlocked = false
870
+ this.reviewRounds = 0
871
+ this.reviewedAtOps = -1
872
+ this.turnPrompt = userInput
873
+ this.lastReviewFindings = undefined
874
+
777
875
  // Poll for cross-session messages before each turn
778
876
  await this.pollCrossSessionInbox()
779
877
  // Drain in-memory bus messages (same-process SendMessage + cross-session re-posts)
@@ -1586,24 +1684,33 @@ export class QueryEngine {
1586
1684
  // `needsApproval(...)` check would have been a *second* gate, and a second gate
1587
1685
  // is how a call refused here gets allowed there. The signal is the caller's, so
1588
1686
  // an interrupt cancels a ruling in flight (the classifier denies on abort).
1589
- const decision = await this.permission.resolveApproval(tool, params, { signal })
1687
+ //
1688
+ // The user's own recent messages travel with the call: `auto` mode's SOFT
1689
+ // BLOCK rules are defined in terms of "did the user explicitly ask for
1690
+ // this", and without the transcript the classifier could only answer "no"
1691
+ // (see `core/user-intent.ts`).
1692
+ const userIntent = collectUserIntent(this.context.getMessages())
1693
+ const decision = await this.permission.resolveApproval(tool, params, { signal, userIntent })
1590
1694
  if (decision.level === 'ask') {
1591
- // P1-4: Increment consecutive block counter; if limit exceeded,
1592
- // tell the model to move on instead of retrying.
1593
- const limitExceeded = this.permission.incrementBlockCounter()
1594
- const baseError = this.buildDenialError(name, tool, params, decision)
1595
- const moveOnHint = limitExceeded
1596
- ? '\n(Consecutive block limit reached. Please try a different approach or ask the user for guidance.)'
1597
- : ''
1598
- return {
1599
- success: false,
1600
- content: '',
1601
- error: baseError + moveOnHint,
1602
- // It did not run. Whatever refused it — a deny rule, the mode, or the
1603
- // auto-mode classifier with no usable answer — the text below is a
1604
- // *reason*, not output, and a collapsed tool group otherwise renders it
1605
- // as a result line (296-056, 314-031).
1606
- notRun: true,
1695
+ const approval = await this.requestApproval(tool, params, decision, signal)
1696
+ if (!approval.allowed) {
1697
+ // P1-4: Increment consecutive block counter; if limit exceeded,
1698
+ // tell the model to move on instead of retrying.
1699
+ const limitExceeded = this.permission.incrementBlockCounter()
1700
+ const moveOnHint = limitExceeded
1701
+ ? '\n(Consecutive block limit reached. Please try a different approach or ask the user for guidance.)'
1702
+ : ''
1703
+ return {
1704
+ success: false,
1705
+ content: '',
1706
+ error:
1707
+ (approval.denial ?? this.buildDenialError(name, tool, params, decision)) + moveOnHint,
1708
+ // It did not run. Whatever refused it — a deny rule, the mode, the
1709
+ // auto-mode classifier with no usable answer, or the user at the
1710
+ // prompt — the text below is a *reason*, not output, and a collapsed
1711
+ // tool group otherwise renders it as a result line (296-056, 314-031).
1712
+ notRun: true,
1713
+ }
1607
1714
  }
1608
1715
  }
1609
1716
  // P1-4: Tool allowed — reset block counter
@@ -1641,13 +1748,22 @@ export class QueryEngine {
1641
1748
  // (This mirrors the correct order in `agent/sub-agent.ts`: hook → apply
1642
1749
  // `modifiedInput` → resolve approval on the effective input.)
1643
1750
  if (effectiveParams !== params) {
1644
- const recheck = await this.permission.resolveApproval(tool, effectiveParams, { signal })
1751
+ const recheck = await this.permission.resolveApproval(tool, effectiveParams, {
1752
+ signal,
1753
+ userIntent,
1754
+ })
1645
1755
  if (recheck.level === 'ask') {
1646
- return {
1647
- success: false,
1648
- content: '',
1649
- error: this.buildDenialError(name, tool, effectiveParams, recheck),
1650
- notRun: true,
1756
+ // The gate must judge what will actually run: if a hook swapped the
1757
+ // params, the user is asked about the swapped call, not the one they
1758
+ // saw first.
1759
+ const approval = await this.requestApproval(tool, effectiveParams, recheck, signal)
1760
+ if (!approval.allowed) {
1761
+ return {
1762
+ success: false,
1763
+ content: '',
1764
+ error: approval.denial ?? this.buildDenialError(name, tool, effectiveParams, recheck),
1765
+ notRun: true,
1766
+ }
1651
1767
  }
1652
1768
  }
1653
1769
  }
@@ -1669,6 +1785,7 @@ export class QueryEngine {
1669
1785
  return { success: false, content: reason, error: reason }
1670
1786
  }
1671
1787
 
1788
+ const writeGeneration = this.reviewTurnGeneration
1672
1789
  const result = await tool.execute(effectiveParams, {
1673
1790
  cwd,
1674
1791
  sessionId: this.sessionId,
@@ -1690,8 +1807,29 @@ export class QueryEngine {
1690
1807
  // A copy: the sub-agent seeds its own context from this prefix while the
1691
1808
  // parent turn keeps appending to its list.
1692
1809
  parentMessages: this.context.getMessages().slice(),
1810
+ // Ignore a callback that belongs to an earlier turn: a background
1811
+ // agent holding this function can write after its turn ended.
1812
+ onFileWrite: (p) => {
1813
+ if (writeGeneration === this.reviewTurnGeneration) this.recordWrite(p)
1814
+ },
1815
+ onCommand: (command, ok) => {
1816
+ if (writeGeneration === this.reviewTurnGeneration) this.recordCommand(command, ok)
1817
+ },
1693
1818
  })
1694
1819
 
1820
+ // Review gate: count writes on the main tool funnel (the sub-agent loop
1821
+ // reports its own through `onFileWrite`).
1822
+ if (result.success && writeGeneration === this.reviewTurnGeneration) {
1823
+ for (const p of writtenPathsFor(name, effectiveParams)) this.recordWrite(p)
1824
+ }
1825
+
1826
+ // Verification baseline: observe executed commands. Failure is recorded
1827
+ // too — "ran and failed" is a reading, not "did not run".
1828
+ const command = commandFor(name, effectiveParams)
1829
+ if (command !== undefined && writeGeneration === this.reviewTurnGeneration) {
1830
+ this.recordCommand(command, result.success)
1831
+ }
1832
+
1695
1833
  // Track touched files for rules matching
1696
1834
  this.trackTouchedFile(name, effectiveParams)
1697
1835
 
@@ -1858,6 +1996,15 @@ export class QueryEngine {
1858
1996
  this.llm = llm
1859
1997
  }
1860
1998
 
1999
+ /**
2000
+ * Hand in the CLI's interactive approval channel (or `undefined` to remove
2001
+ * it). Only the TUI sets this: a headless engine that did would wait forever
2002
+ * on a question nobody can see, so the absence is the safe default.
2003
+ */
2004
+ setApprovalPrompter(prompter: ApprovalPrompter | undefined): void {
2005
+ this.approvalPrompter = prompter
2006
+ }
2007
+
1861
2008
  /**
1862
2009
  * 统一 chat 出口:优先走注入的 Llm 缝,否则回退 registry。
1863
2010
  *
@@ -2186,6 +2333,124 @@ export class QueryEngine {
2186
2333
  return this.tools
2187
2334
  }
2188
2335
 
2336
+ /**
2337
+ * Ask the human when — and only when — there is a channel and the ask is
2338
+ * negotiable.
2339
+ *
2340
+ * Returns a `denial` when the call must not run: either no prompt is possible
2341
+ * (headless caller, a deny rule, a structural gate, or a non-prompting mode),
2342
+ * or the human declined. The distinction matters in the text the model reads:
2343
+ * a refusal by a person present is final for this call and must not be
2344
+ * answered with "run `/permissions allow`".
2345
+ */
2346
+ private async requestApproval(
2347
+ tool: ToolDefinition,
2348
+ params: Record<string, unknown>,
2349
+ decision: ApprovalDecision,
2350
+ signal?: AbortSignal,
2351
+ ): Promise<{ allowed: boolean; denial?: string }> {
2352
+ const mode = this.permission.getMode()
2353
+ const prompter = this.approvalPrompter
2354
+ if (
2355
+ !prompter ||
2356
+ decision.source === 'classifier' ||
2357
+ !isPromptable(mode, decision.denialReason)
2358
+ ) {
2359
+ return { allowed: false, denial: this.buildDenialError(tool.name, tool, params, decision) }
2360
+ }
2361
+
2362
+ // `isPromptable` guarantees a reason; an `'ask'` decision always carries one.
2363
+ const reason = decision.denialReason!
2364
+ const rule = deriveAllowRule(tool, params, this.permission.getKnownTools())
2365
+ const request: ApprovalRequest = {
2366
+ tool: tool.name,
2367
+ input: params,
2368
+ mode,
2369
+ reason,
2370
+ ...(rule ? { rule } : {}),
2371
+ }
2372
+
2373
+ let choice: ApprovalChoice
2374
+ try {
2375
+ choice = await this.awaitApproval(prompter, request, signal)
2376
+ } catch {
2377
+ // A prompt that throws is a channel failure, not an approval. Fail closed.
2378
+ choice = 'deny'
2379
+ }
2380
+
2381
+ if (choice === 'deny') {
2382
+ return {
2383
+ allowed: false,
2384
+ denial: t('errors.tool_denied_by_user', { name: tool.name }),
2385
+ }
2386
+ }
2387
+
2388
+ if (choice === 'allow-always' && rule) {
2389
+ await this.persistAllowRule(tool, params, rule)
2390
+ }
2391
+ return { allowed: true }
2392
+ }
2393
+
2394
+ /**
2395
+ * Wait for a choice, but never longer than the turn itself.
2396
+ *
2397
+ * A UI that unmounts mid-prompt leaves the promise unresolved; the abort
2398
+ * signal is what turns that into a denial instead of a hung turn.
2399
+ */
2400
+ private awaitApproval(
2401
+ prompter: ApprovalPrompter,
2402
+ request: ApprovalRequest,
2403
+ signal?: AbortSignal,
2404
+ ): Promise<ApprovalChoice> {
2405
+ if (!signal) return prompter(request)
2406
+ if (signal.aborted) return Promise.resolve('deny')
2407
+ return new Promise<ApprovalChoice>((resolve, reject) => {
2408
+ let settled = false
2409
+ const finish = (choice: ApprovalChoice): void => {
2410
+ if (settled) return
2411
+ settled = true
2412
+ signal.removeEventListener('abort', onAbort)
2413
+ resolve(choice)
2414
+ }
2415
+ const onAbort = (): void => finish('deny')
2416
+ signal.addEventListener('abort', onAbort, { once: true })
2417
+ prompter(request).then(finish, (error: unknown) => {
2418
+ if (settled) return
2419
+ settled = true
2420
+ signal.removeEventListener('abort', onAbort)
2421
+ reject(error)
2422
+ })
2423
+ })
2424
+ }
2425
+
2426
+ /**
2427
+ * Make "always allow" true for the rest of this session and the next ones.
2428
+ *
2429
+ * The rule is added in memory **first** and the gate is asked again: an org
2430
+ * ceiling (`maxAllowedMode`) can cap what an allow rule grants, and a rule
2431
+ * the gate will not honour must not be persisted as if it were protection.
2432
+ * A disk failure leaves the in-session grant in place — the user's approval
2433
+ * must not become a denial — and degrades "always" to "this session", which
2434
+ * the next prompt makes visible.
2435
+ */
2436
+ private async persistAllowRule(
2437
+ tool: ToolDefinition,
2438
+ params: Record<string, unknown>,
2439
+ rule: string,
2440
+ ): Promise<void> {
2441
+ this.permission.allow(rule)
2442
+ if (this.permission.check(tool, params) === 'ask') {
2443
+ this.permission.removeRule(rule)
2444
+ return
2445
+ }
2446
+ try {
2447
+ const { addSettingsRule } = await import('../config/loader')
2448
+ addSettingsRule('allow', rule, 'user')
2449
+ } catch {
2450
+ /* in-memory grant stands; see the method comment */
2451
+ }
2452
+ }
2453
+
2189
2454
  /**
2190
2455
  * Build a rich permission-denial error naming the mode (level), the setting
2191
2456
  * (rule/level) that caused the denial, and the correct fix (#52).
@@ -2324,6 +2589,32 @@ export class QueryEngine {
2324
2589
  }
2325
2590
  }
2326
2591
 
2592
+ /** Read-only: are the review gate / verification baseline actually wired on? */
2593
+ getSelfCheckStatus(): { reviewGate: boolean; verification: boolean } {
2594
+ return {
2595
+ reviewGate: Boolean(this.reviewGate?.enabled),
2596
+ verification: Boolean(this.verificationConfig?.enabled),
2597
+ }
2598
+ }
2599
+
2600
+ /**
2601
+ * Tool context for sub-agents spawned outside `executeTool` (workflow
2602
+ * agents). Only the review gate's write tap is shared; the rest of that
2603
+ * context is built per tool call. The generation is captured here so a
2604
+ * callback outliving this turn does not open the next turn's gate.
2605
+ */
2606
+ getToolContext(): Partial<ToolContext> {
2607
+ const generation = this.reviewTurnGeneration
2608
+ return {
2609
+ onFileWrite: (p) => {
2610
+ if (generation === this.reviewTurnGeneration) this.recordWrite(p)
2611
+ },
2612
+ onCommand: (command, ok) => {
2613
+ if (generation === this.reviewTurnGeneration) this.recordCommand(command, ok)
2614
+ },
2615
+ }
2616
+ }
2617
+
2327
2618
  /**
2328
2619
  * SIS Phase 0: Lazily-initialized PreFlightChecker singleton.
2329
2620
  * Checks tool calls against ErrorSignatureDB + ExperienceRuleEngine
@@ -2532,7 +2823,7 @@ export class QueryEngine {
2532
2823
  signal?: AbortSignal,
2533
2824
  roundsLeft: number = MAX_TOOL_TURNS,
2534
2825
  ): AsyncGenerator<StreamChunk> {
2535
- const { block, systemMessage } = await this.stopCheck()
2826
+ const { block, systemMessage } = await this.stopCheck(roundsLeft, signal)
2536
2827
  if (systemMessage) yield { type: 'warning', content: systemMessage }
2537
2828
  if (!block) return
2538
2829
 
@@ -2562,7 +2853,10 @@ export class QueryEngine {
2562
2853
  * 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
2563
2854
  * 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
2564
2855
  */
2565
- private async stopCheck(): Promise<{
2856
+ private async stopCheck(
2857
+ roundsLeft: number = MAX_TOOL_TURNS,
2858
+ signal?: AbortSignal,
2859
+ ): Promise<{
2566
2860
  block: { source: string; text: string; reason: string } | null
2567
2861
  systemMessage?: string
2568
2862
  }> {
@@ -2583,6 +2877,16 @@ export class QueryEngine {
2583
2877
  }
2584
2878
  }
2585
2879
 
2880
+ const baseline = this.checkVerificationBaseline(roundsLeft)
2881
+ if (baseline.block) {
2882
+ return { block: baseline.block, systemMessage: baseline.systemMessage ?? systemMessage }
2883
+ }
2884
+ systemMessage = baseline.systemMessage ?? systemMessage
2885
+
2886
+ const gate = await this.checkReviewGate(roundsLeft, signal)
2887
+ if (gate.block) return { block: gate.block, systemMessage: gate.systemMessage ?? systemMessage }
2888
+ systemMessage = gate.systemMessage ?? systemMessage
2889
+
2586
2890
  const claims = this.unprovenNumbers()
2587
2891
  if (!claims) return { block: null, systemMessage }
2588
2892
  // 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
@@ -2597,6 +2901,169 @@ export class QueryEngine {
2597
2901
  }
2598
2902
  }
2599
2903
 
2904
+ /**
2905
+ * Fourth stop source (after the Stop hook, before the review gate): did the
2906
+ * mechanical checks the project implies actually run after the last source
2907
+ * edit? Observation only — nothing is executed here. Missing checks block
2908
+ * once; the report then travels to the reviewer as a known gap.
2909
+ */
2910
+ private checkVerificationBaseline(roundsLeft: number): {
2911
+ block: { source: string; text: string; reason: string } | null
2912
+ systemMessage?: string
2913
+ } {
2914
+ const config = this.verificationConfig
2915
+ if (!config || !config.enabled) return { block: null }
2916
+
2917
+ // Fail open: a deleted cwd makes `process.cwd()` throw on Node, and a
2918
+ // broken manifest read must not crash the stop path.
2919
+ let baseline
2920
+ try {
2921
+ const cwd = typeof config.cwd === 'function' ? config.cwd() : config.cwd
2922
+ baseline = detectProjectBaseline(cwd)
2923
+ } catch {
2924
+ return { block: null }
2925
+ }
2926
+ if (!baseline) return { block: null }
2927
+ if (
2928
+ !hasSourceWrite(
2929
+ baseline,
2930
+ this.turnWriteEvents.map((e) => e.path),
2931
+ )
2932
+ ) {
2933
+ return { block: null }
2934
+ }
2935
+
2936
+ const sourceWrites = this.turnWriteEvents.filter((e) => hasSourceWrite(baseline, [e.path]))
2937
+ const lastSourceWriteSeq = sourceWrites.reduce((max, e) => Math.max(max, e.seq), -1)
2938
+ const report = evaluateBaseline(baseline, this.turnCommands, lastSourceWriteSeq)
2939
+ this.baselineReport = report
2940
+
2941
+ if (report.missing.length === 0) return { block: null }
2942
+ const missing = report.missing.join(', ')
2943
+
2944
+ if (roundsLeft <= 0) {
2945
+ return {
2946
+ block: null,
2947
+ systemMessage: t('errors.verification_budget_spent', { missing }),
2948
+ }
2949
+ }
2950
+ if (this.verificationBlocked) return { block: null }
2951
+ this.verificationBlocked = true
2952
+ return {
2953
+ block: {
2954
+ source: 'verification-baseline',
2955
+ text: t('errors.verification_missing', { missing }),
2956
+ reason: missing,
2957
+ },
2958
+ systemMessage: t('errors.verification_missing', { missing }),
2959
+ }
2960
+ }
2961
+
2962
+ /**
2963
+ * Third stop source: after a turn that wrote files, run one independent
2964
+ * review. FAIL blocks and feeds the findings back; a broken reviewer is
2965
+ * fail-open (a bad gate must not trap the turn).
2966
+ *
2967
+ * `roundsLeft` is checked here rather than in the caller: the caller's budget
2968
+ * warning would throw a FAIL away, and the longest turns are exactly where
2969
+ * files were written.
2970
+ */
2971
+ private async checkReviewGate(
2972
+ roundsLeft: number,
2973
+ signal?: AbortSignal,
2974
+ ): Promise<{
2975
+ block: { source: string; text: string; reason: string } | null
2976
+ systemMessage?: string
2977
+ }> {
2978
+ const gate = this.reviewGate
2979
+ if (!gate || !gate.enabled) return { block: null }
2980
+ if (this.reviewWriteOps === 0 || this.reviewedAtOps === this.reviewWriteOps) {
2981
+ return { block: null }
2982
+ }
2983
+
2984
+ if (this.reviewRounds >= gate.maxRounds) {
2985
+ this.reviewedAtOps = this.reviewWriteOps
2986
+ return {
2987
+ block: null,
2988
+ systemMessage: t('errors.review_gate_budget_spent', { max: String(gate.maxRounds) }),
2989
+ }
2990
+ }
2991
+
2992
+ this.reviewRounds++
2993
+ let result
2994
+ try {
2995
+ result = await gate.runner({
2996
+ cwd: typeof gate.cwd === 'function' ? gate.cwd() : gate.cwd,
2997
+ userPrompt: this.turnPrompt,
2998
+ changedFiles: [...this.turnWrites],
2999
+ round: this.reviewRounds,
3000
+ maxRounds: gate.maxRounds,
3001
+ previousFindings: this.lastReviewFindings,
3002
+ authorResponse: this.lastAssistantText(),
3003
+ baseline: this.baselineReport,
3004
+ signal,
3005
+ })
3006
+ } catch (err) {
3007
+ result = {
3008
+ status: 'error' as const,
3009
+ message: err instanceof Error ? err.message : String(err),
3010
+ }
3011
+ }
3012
+
3013
+ if (result.status === 'pass') {
3014
+ this.reviewedAtOps = this.reviewWriteOps
3015
+ this.lastReviewFindings = undefined
3016
+ return { block: null }
3017
+ }
3018
+
3019
+ if (result.status === 'error') {
3020
+ this.reviewedAtOps = this.reviewWriteOps
3021
+ return {
3022
+ block: null,
3023
+ systemMessage: t('errors.review_gate_error', { message: result.message }),
3024
+ }
3025
+ }
3026
+
3027
+ this.lastReviewFindings = result.findings
3028
+ // No budget left: blocking would be discarded by the caller, but the
3029
+ // findings still reach the operator as a warning.
3030
+ if (roundsLeft <= 0) {
3031
+ this.reviewedAtOps = this.reviewWriteOps
3032
+ return {
3033
+ block: null,
3034
+ systemMessage: this.capHookContext(`[review gate] ${result.findings}`),
3035
+ }
3036
+ }
3037
+
3038
+ const firstLine = result.findings.split('\n', 1)[0]?.trim() || 'issues found'
3039
+ return {
3040
+ block: {
3041
+ source: 'review-gate',
3042
+ text: `[review gate ${this.reviewRounds}/${gate.maxRounds}]\n${result.findings}`,
3043
+ reason: `review gate round ${this.reviewRounds}/${gate.maxRounds}: ${firstLine}`,
3044
+ },
3045
+ }
3046
+ }
3047
+
3048
+ /** The author's last assistant text, for a round-2 review's rebuttal context. */
3049
+ private lastAssistantText(): string | undefined {
3050
+ const messages = this.context.getMessages()
3051
+ for (let i = messages.length - 1; i >= 0; i--) {
3052
+ const message = messages[i]!
3053
+ if (message.role !== 'assistant') continue
3054
+ const text =
3055
+ typeof message.content === 'string'
3056
+ ? message.content
3057
+ : (message.content as Array<{ type: string; text?: string }>)
3058
+ .filter((block) => block.type === 'text')
3059
+ .map((block) => block.text ?? '')
3060
+ .join('\n')
3061
+ const trimmed = text.trim()
3062
+ return trimmed ? this.capHookContext(trimmed) : undefined
3063
+ }
3064
+ return undefined
3065
+ }
3066
+
2600
3067
  /**
2601
3068
  * 「这个数是你量出来的,还是你推出来的?」
2602
3069
  *
@@ -235,7 +235,7 @@ export function buildPermissionBlock(mode: string): string {
235
235
  // staying stale makes it promise a keypress that does nothing. `bypassPermissions`
236
236
  // is still reachable, but only by naming it in config; saying so is what keeps
237
237
  // the model from offering it as a way out.
238
- return `## Permission Context\n\n${description}\n\nWhen a tool is denied, do NOT retry it or any other approval-gated tool — Bash, WebSearch, network, and Workflow are all blocked in this mode.${escape} If the task genuinely needs a blocked tool, STOP retrying and ask the user to switch modes with Shift+Tab or add an allow rule (/permissions), then wait for the user's answer. Note that Shift+Tab's wheel does not reach bypassPermissions — that mode is set in config, so do not offer it as a keypress.`
238
+ return `## Permission Context\n\n${description}\n\nWhen a tool is denied, do NOT retry it or any other approval-gated tool — Bash, WebSearch, network, and Workflow are all blocked in this mode.${escape} If the task genuinely needs a blocked tool, STOP retrying and ask the user to switch modes with Shift+Tab or add an allow rule (/permissions), then wait for the user's answer. Note that Shift+Tab's wheel does not reach bypassPermissions — that mode is set in config, so do not offer it as a keypress. Independently of permissions, after a turn that writes files this session runs an independent review gate and a verification baseline unless they are turned off (both are on by default; /status reports their state): expect findings to fix, and report checks as Verified or Not verified.`
239
239
  }
240
240
 
241
241
  /** Level label used in each prompt part's provenance comment. */