@miphamai/cli 0.85.53 → 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.
- package/README.md +1 -1
- package/package.json +6 -6
- package/src/agent/agent-registry.ts +17 -2
- package/src/agent/sub-agent.ts +18 -2
- package/src/agent/types.ts +9 -0
- package/src/commands/environment.ts +71 -35
- package/src/commands/project.ts +31 -0
- package/src/config/loader.ts +112 -3
- package/src/core/command-taps.ts +10 -0
- package/src/core/credential-masker/matcher.ts +38 -0
- package/src/core/engine.ts +351 -6
- package/src/core/hooks.ts +18 -7
- package/src/core/instructions.ts +17 -3
- package/src/core/review-gate.ts +192 -0
- package/src/core/rules-loader.ts +4 -1
- package/src/core/session-insights.ts +8 -2
- package/src/core/session-store.ts +30 -23
- package/src/core/task-performance-tasks.json +18 -0
- package/src/core/verification-baseline.ts +277 -0
- package/src/core/write-paths.ts +19 -0
- package/src/daemon/engine-capabilities.ts +22 -1
- package/src/daemon/launch.ts +11 -1
- package/src/i18n-core/locales/en-US.json +9 -1
- package/src/i18n-core/locales/zh-CN.json +9 -1
- package/src/index.tsx +35 -3
- package/src/mcp/transport.ts +35 -3
- package/src/providers/anthropic.ts +17 -1
- package/src/providers/openai-compat.ts +13 -1
- package/src/shared/package-info.ts +2 -2
- package/src/shared/types.ts +11 -0
- package/src/skills/fork-executor.ts +3 -2
- package/src/skills/loader.ts +9 -2
- package/src/tools/agent/skill.ts +1 -0
- package/src/tools/agent/workflow.ts +3 -0
- package/src/tools/exec/task.ts +41 -0
- package/src/tools/file/grep.ts +30 -1
- package/src/tools/network/web-fetch.ts +11 -2
- package/src/ui/chat.tsx +17 -0
- package/src/ui/commands.ts +280 -29
- package/src/ui/picker.tsx +120 -19
- package/src/workflow/primitives/agent.ts +10 -1
- package/src/workflow/runtime.ts +49 -0
package/src/core/engine.ts
CHANGED
|
@@ -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,
|
|
@@ -28,6 +29,14 @@ import type { Skills } from '../skills/seam'
|
|
|
28
29
|
import { getBackgroundAgentRegistry } from '../agent/background-registry'
|
|
29
30
|
import { RulesLoader } from './rules-loader'
|
|
30
31
|
import { extractBashFileAccess } from './permission-rules'
|
|
32
|
+
import { writtenPathsFor, type ReviewGateConfig } from './review-gate'
|
|
33
|
+
import { commandFor } from './command-taps'
|
|
34
|
+
import { detectProjectBaseline, evaluateBaseline, hasSourceWrite } from './verification-baseline'
|
|
35
|
+
import type {
|
|
36
|
+
BaselineReport,
|
|
37
|
+
TurnCommand,
|
|
38
|
+
VerificationBaselineConfig,
|
|
39
|
+
} from './verification-baseline'
|
|
31
40
|
import { noteToolOutcome, reviewLedger } from './merge-gate'
|
|
32
41
|
import { unprovenCountClaims } from './number-provenance'
|
|
33
42
|
import type { InstructionsLoader } from './instructions'
|
|
@@ -461,6 +470,39 @@ export class QueryEngine {
|
|
|
461
470
|
private instructionsLoader?: InstructionsLoader
|
|
462
471
|
/** Files touched in the current turn (for rules matching). */
|
|
463
472
|
private touchedFiles: Set<string> = new Set()
|
|
473
|
+
/** Review gate: successful file-write operations this turn (two write paths feed this). */
|
|
474
|
+
private reviewWriteOps = 0
|
|
475
|
+
/** Review gate: the paths written this turn, for the reviewer's brief. */
|
|
476
|
+
private turnWrites: Set<string> = new Set()
|
|
477
|
+
/**
|
|
478
|
+
* Review gate: increments at the start of every turn. A write callback
|
|
479
|
+
* captured by a background/delegated tool keeps the generation it was
|
|
480
|
+
* created in, so a late write from a finished turn cannot open this turn's
|
|
481
|
+
* gate.
|
|
482
|
+
*/
|
|
483
|
+
private reviewTurnGeneration = 0
|
|
484
|
+
/** Review gate: config + runner. Absent means the gate is off. */
|
|
485
|
+
private reviewGate?: ReviewGateConfig
|
|
486
|
+
/** Review gate: reviews spent this turn. */
|
|
487
|
+
private reviewRounds = 0
|
|
488
|
+
/** Review gate: write generation already passed. -1 = nothing passed yet. */
|
|
489
|
+
private reviewedAtOps = -1
|
|
490
|
+
/** Review gate: this turn's user input (the reviewer's requirement). */
|
|
491
|
+
private turnPrompt = ''
|
|
492
|
+
/** Verification baseline: commands observed this turn (both tool paths). */
|
|
493
|
+
private turnCommands: TurnCommand[] = []
|
|
494
|
+
/** Verification baseline: writes with their order, to tell stale runs from fresh ones. */
|
|
495
|
+
private turnWriteEvents: Array<{ path: string; seq: number }> = []
|
|
496
|
+
/** Verification baseline: monotonic order shared by writes and commands. */
|
|
497
|
+
private turnOpSeq = 0
|
|
498
|
+
/** Verification baseline: config. Absent means the baseline is off. */
|
|
499
|
+
private verificationConfig?: VerificationBaselineConfig
|
|
500
|
+
/** Verification baseline: this turn's report (passed to the reviewer). */
|
|
501
|
+
private baselineReport?: BaselineReport
|
|
502
|
+
/** Verification baseline: blocked once already this turn. */
|
|
503
|
+
private verificationBlocked = false
|
|
504
|
+
/** Review gate: last FAIL findings, carried into the next review round. */
|
|
505
|
+
private lastReviewFindings?: string
|
|
464
506
|
/** A tool call failed since the last nudge check. */
|
|
465
507
|
private pendingToolFailure = false
|
|
466
508
|
/** 本轮用户输入 —— 数字出处判定里它是合法的出处之一。 */
|
|
@@ -492,6 +534,25 @@ export class QueryEngine {
|
|
|
492
534
|
this.instructionsLoader = loader
|
|
493
535
|
}
|
|
494
536
|
|
|
537
|
+
/**
|
|
538
|
+
* Re-root the instruction chain at `cwd` and rebuild the system prompt
|
|
539
|
+
* (`/cd` — the loader it was built from still points at the directory the
|
|
540
|
+
* session was opened in, so entering a worktree and coming back kept reading
|
|
541
|
+
* the old chain).
|
|
542
|
+
*
|
|
543
|
+
* `loadAll` resets the loader in place, which is what keeps this one object
|
|
544
|
+
* behind both consumers: the base prompt (via the context rebuilder, which
|
|
545
|
+
* re-reads from the same instance) and the per-path nested-file lookup.
|
|
546
|
+
* Returns false when no loader is registered (daemon/attach paths, where the
|
|
547
|
+
* instruction chain belongs to the host process).
|
|
548
|
+
*/
|
|
549
|
+
reloadInstructions(cwd: string): boolean {
|
|
550
|
+
if (!this.instructionsLoader) return false
|
|
551
|
+
this.instructionsLoader.loadAll(cwd)
|
|
552
|
+
this.context.refreshSystemPrompt()
|
|
553
|
+
return true
|
|
554
|
+
}
|
|
555
|
+
|
|
495
556
|
/** Register inference hook (DLP) configuration. */
|
|
496
557
|
setInferenceHookConfig(config: InferenceHookConfig): void {
|
|
497
558
|
this.inferenceHookConfig = config
|
|
@@ -528,6 +589,28 @@ export class QueryEngine {
|
|
|
528
589
|
}
|
|
529
590
|
}
|
|
530
591
|
|
|
592
|
+
/** Count a successful file write for the review gate. */
|
|
593
|
+
private recordWrite(path: string): void {
|
|
594
|
+
this.reviewWriteOps++
|
|
595
|
+
this.turnWrites.add(path)
|
|
596
|
+
this.turnWriteEvents.push({ path, seq: ++this.turnOpSeq })
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** Record an observed Bash command (success or failure) for the verification baseline. */
|
|
600
|
+
private recordCommand(command: string, ok: boolean): void {
|
|
601
|
+
this.turnCommands.push({ command, ok, seq: ++this.turnOpSeq })
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** Wire the verification baseline. Absent/disabled means it never runs. */
|
|
605
|
+
setVerificationBaseline(config: VerificationBaselineConfig): void {
|
|
606
|
+
this.verificationConfig = config
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** Wire the review gate. Absent/disabled means the gate never runs. */
|
|
610
|
+
setReviewGate(config: ReviewGateConfig): void {
|
|
611
|
+
this.reviewGate = config
|
|
612
|
+
}
|
|
613
|
+
|
|
531
614
|
/**
|
|
532
615
|
* Inject path-scoped context for the files touched this round: matching rules
|
|
533
616
|
* (`.mipham/rules/*.md`) and any nested instruction files (`CLAUDE.md` and
|
|
@@ -755,6 +838,22 @@ export class QueryEngine {
|
|
|
755
838
|
// provider API (which would otherwise 400 on an empty/blank message).
|
|
756
839
|
if (!userInput.trim()) return
|
|
757
840
|
|
|
841
|
+
// Review gate state is per turn: a new user message starts a new write
|
|
842
|
+
// generation, so a gate that passed the previous turn runs again if this
|
|
843
|
+
// one writes files.
|
|
844
|
+
this.reviewTurnGeneration++
|
|
845
|
+
this.reviewWriteOps = 0
|
|
846
|
+
this.turnWrites.clear()
|
|
847
|
+
this.turnCommands = []
|
|
848
|
+
this.turnWriteEvents = []
|
|
849
|
+
this.turnOpSeq = 0
|
|
850
|
+
this.baselineReport = undefined
|
|
851
|
+
this.verificationBlocked = false
|
|
852
|
+
this.reviewRounds = 0
|
|
853
|
+
this.reviewedAtOps = -1
|
|
854
|
+
this.turnPrompt = userInput
|
|
855
|
+
this.lastReviewFindings = undefined
|
|
856
|
+
|
|
758
857
|
// Poll for cross-session messages before each turn
|
|
759
858
|
await this.pollCrossSessionInbox()
|
|
760
859
|
// Drain in-memory bus messages (same-process SendMessage + cross-session re-posts)
|
|
@@ -801,7 +900,10 @@ export class QueryEngine {
|
|
|
801
900
|
|
|
802
901
|
// Check compaction before processing
|
|
803
902
|
if (this.context.needsCompaction()) {
|
|
804
|
-
await this.compactWithHooks('conversation summary', signal)
|
|
903
|
+
const compact = await this.compactWithHooks('conversation summary', signal)
|
|
904
|
+
if (compact.blocked) {
|
|
905
|
+
yield { type: 'warning', content: `Compaction skipped: ${compact.reason}` }
|
|
906
|
+
}
|
|
805
907
|
}
|
|
806
908
|
|
|
807
909
|
const systemPrompt = applyUltracodeMode(this.context.getSystemPrompt(), this.ultracode)
|
|
@@ -1647,6 +1749,7 @@ export class QueryEngine {
|
|
|
1647
1749
|
return { success: false, content: reason, error: reason }
|
|
1648
1750
|
}
|
|
1649
1751
|
|
|
1752
|
+
const writeGeneration = this.reviewTurnGeneration
|
|
1650
1753
|
const result = await tool.execute(effectiveParams, {
|
|
1651
1754
|
cwd,
|
|
1652
1755
|
sessionId: this.sessionId,
|
|
@@ -1668,8 +1771,29 @@ export class QueryEngine {
|
|
|
1668
1771
|
// A copy: the sub-agent seeds its own context from this prefix while the
|
|
1669
1772
|
// parent turn keeps appending to its list.
|
|
1670
1773
|
parentMessages: this.context.getMessages().slice(),
|
|
1774
|
+
// Ignore a callback that belongs to an earlier turn: a background
|
|
1775
|
+
// agent holding this function can write after its turn ended.
|
|
1776
|
+
onFileWrite: (p) => {
|
|
1777
|
+
if (writeGeneration === this.reviewTurnGeneration) this.recordWrite(p)
|
|
1778
|
+
},
|
|
1779
|
+
onCommand: (command, ok) => {
|
|
1780
|
+
if (writeGeneration === this.reviewTurnGeneration) this.recordCommand(command, ok)
|
|
1781
|
+
},
|
|
1671
1782
|
})
|
|
1672
1783
|
|
|
1784
|
+
// Review gate: count writes on the main tool funnel (the sub-agent loop
|
|
1785
|
+
// reports its own through `onFileWrite`).
|
|
1786
|
+
if (result.success && writeGeneration === this.reviewTurnGeneration) {
|
|
1787
|
+
for (const p of writtenPathsFor(name, effectiveParams)) this.recordWrite(p)
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
// Verification baseline: observe executed commands. Failure is recorded
|
|
1791
|
+
// too — "ran and failed" is a reading, not "did not run".
|
|
1792
|
+
const command = commandFor(name, effectiveParams)
|
|
1793
|
+
if (command !== undefined && writeGeneration === this.reviewTurnGeneration) {
|
|
1794
|
+
this.recordCommand(command, result.success)
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1673
1797
|
// Track touched files for rules matching
|
|
1674
1798
|
this.trackTouchedFile(name, effectiveParams)
|
|
1675
1799
|
|
|
@@ -2037,7 +2161,8 @@ export class QueryEngine {
|
|
|
2037
2161
|
restart: true,
|
|
2038
2162
|
}
|
|
2039
2163
|
try {
|
|
2040
|
-
await this.compactWithHooks('context overflow', signal)
|
|
2164
|
+
const compact = await this.compactWithHooks('context overflow', signal)
|
|
2165
|
+
if (compact.blocked) throw new Error(compact.reason)
|
|
2041
2166
|
msgs = this.context.getMessages()
|
|
2042
2167
|
sysPrompt = this.context.getSystemPrompt()
|
|
2043
2168
|
} catch (err) {
|
|
@@ -2301,6 +2426,32 @@ export class QueryEngine {
|
|
|
2301
2426
|
}
|
|
2302
2427
|
}
|
|
2303
2428
|
|
|
2429
|
+
/** Read-only: are the review gate / verification baseline actually wired on? */
|
|
2430
|
+
getSelfCheckStatus(): { reviewGate: boolean; verification: boolean } {
|
|
2431
|
+
return {
|
|
2432
|
+
reviewGate: Boolean(this.reviewGate?.enabled),
|
|
2433
|
+
verification: Boolean(this.verificationConfig?.enabled),
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
|
|
2437
|
+
/**
|
|
2438
|
+
* Tool context for sub-agents spawned outside `executeTool` (workflow
|
|
2439
|
+
* agents). Only the review gate's write tap is shared; the rest of that
|
|
2440
|
+
* context is built per tool call. The generation is captured here so a
|
|
2441
|
+
* callback outliving this turn does not open the next turn's gate.
|
|
2442
|
+
*/
|
|
2443
|
+
getToolContext(): Partial<ToolContext> {
|
|
2444
|
+
const generation = this.reviewTurnGeneration
|
|
2445
|
+
return {
|
|
2446
|
+
onFileWrite: (p) => {
|
|
2447
|
+
if (generation === this.reviewTurnGeneration) this.recordWrite(p)
|
|
2448
|
+
},
|
|
2449
|
+
onCommand: (command, ok) => {
|
|
2450
|
+
if (generation === this.reviewTurnGeneration) this.recordCommand(command, ok)
|
|
2451
|
+
},
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
|
|
2304
2455
|
/**
|
|
2305
2456
|
* SIS Phase 0: Lazily-initialized PreFlightChecker singleton.
|
|
2306
2457
|
* Checks tool calls against ErrorSignatureDB + ExperienceRuleEngine
|
|
@@ -2455,10 +2606,27 @@ export class QueryEngine {
|
|
|
2455
2606
|
)
|
|
2456
2607
|
}
|
|
2457
2608
|
|
|
2458
|
-
/**
|
|
2459
|
-
|
|
2609
|
+
/**
|
|
2610
|
+
* Wrap context compaction with PreCompact/PostCompact hooks.
|
|
2611
|
+
*
|
|
2612
|
+
* A blocking PreCompact hook MUST stop the compaction. We used to read only
|
|
2613
|
+
* `additionalContext`, so a hook's `decision: block` and its reason were
|
|
2614
|
+
* discarded and the compaction ran anyway (CC 2.1.334-066). The caller
|
|
2615
|
+
* decides how to surface the block: the turn continues without compacting,
|
|
2616
|
+
* and the 413 retry path falls through to its ordinary failure handling.
|
|
2617
|
+
*/
|
|
2618
|
+
private async compactWithHooks(
|
|
2619
|
+
heading: string,
|
|
2620
|
+
signal?: AbortSignal,
|
|
2621
|
+
): Promise<{ blocked: boolean; reason?: string }> {
|
|
2460
2622
|
if (this.hookEngine) {
|
|
2461
2623
|
const preResult = await this.hookEngine.executePreCompact(this.sessionId)
|
|
2624
|
+
if (!preResult.allowed) {
|
|
2625
|
+
return {
|
|
2626
|
+
blocked: true,
|
|
2627
|
+
reason: preResult.reason || 'a PreCompact hook blocked compaction',
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2462
2630
|
if (preResult.additionalContext) {
|
|
2463
2631
|
this.context.injectContext(
|
|
2464
2632
|
'pre-compact',
|
|
@@ -2484,6 +2652,7 @@ export class QueryEngine {
|
|
|
2484
2652
|
)
|
|
2485
2653
|
}
|
|
2486
2654
|
}
|
|
2655
|
+
return { blocked: false }
|
|
2487
2656
|
}
|
|
2488
2657
|
|
|
2489
2658
|
/** Fire Stop hook. If blocked, feed the reason back to the AI and continue. */
|
|
@@ -2491,7 +2660,7 @@ export class QueryEngine {
|
|
|
2491
2660
|
signal?: AbortSignal,
|
|
2492
2661
|
roundsLeft: number = MAX_TOOL_TURNS,
|
|
2493
2662
|
): AsyncGenerator<StreamChunk> {
|
|
2494
|
-
const { block, systemMessage } = await this.stopCheck()
|
|
2663
|
+
const { block, systemMessage } = await this.stopCheck(roundsLeft, signal)
|
|
2495
2664
|
if (systemMessage) yield { type: 'warning', content: systemMessage }
|
|
2496
2665
|
if (!block) return
|
|
2497
2666
|
|
|
@@ -2521,7 +2690,10 @@ export class QueryEngine {
|
|
|
2521
2690
|
* 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
|
|
2522
2691
|
* 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
|
|
2523
2692
|
*/
|
|
2524
|
-
private async stopCheck(
|
|
2693
|
+
private async stopCheck(
|
|
2694
|
+
roundsLeft: number = MAX_TOOL_TURNS,
|
|
2695
|
+
signal?: AbortSignal,
|
|
2696
|
+
): Promise<{
|
|
2525
2697
|
block: { source: string; text: string; reason: string } | null
|
|
2526
2698
|
systemMessage?: string
|
|
2527
2699
|
}> {
|
|
@@ -2542,6 +2714,16 @@ export class QueryEngine {
|
|
|
2542
2714
|
}
|
|
2543
2715
|
}
|
|
2544
2716
|
|
|
2717
|
+
const baseline = this.checkVerificationBaseline(roundsLeft)
|
|
2718
|
+
if (baseline.block) {
|
|
2719
|
+
return { block: baseline.block, systemMessage: baseline.systemMessage ?? systemMessage }
|
|
2720
|
+
}
|
|
2721
|
+
systemMessage = baseline.systemMessage ?? systemMessage
|
|
2722
|
+
|
|
2723
|
+
const gate = await this.checkReviewGate(roundsLeft, signal)
|
|
2724
|
+
if (gate.block) return { block: gate.block, systemMessage: gate.systemMessage ?? systemMessage }
|
|
2725
|
+
systemMessage = gate.systemMessage ?? systemMessage
|
|
2726
|
+
|
|
2545
2727
|
const claims = this.unprovenNumbers()
|
|
2546
2728
|
if (!claims) return { block: null, systemMessage }
|
|
2547
2729
|
// 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
|
|
@@ -2556,6 +2738,169 @@ export class QueryEngine {
|
|
|
2556
2738
|
}
|
|
2557
2739
|
}
|
|
2558
2740
|
|
|
2741
|
+
/**
|
|
2742
|
+
* Fourth stop source (after the Stop hook, before the review gate): did the
|
|
2743
|
+
* mechanical checks the project implies actually run after the last source
|
|
2744
|
+
* edit? Observation only — nothing is executed here. Missing checks block
|
|
2745
|
+
* once; the report then travels to the reviewer as a known gap.
|
|
2746
|
+
*/
|
|
2747
|
+
private checkVerificationBaseline(roundsLeft: number): {
|
|
2748
|
+
block: { source: string; text: string; reason: string } | null
|
|
2749
|
+
systemMessage?: string
|
|
2750
|
+
} {
|
|
2751
|
+
const config = this.verificationConfig
|
|
2752
|
+
if (!config || !config.enabled) return { block: null }
|
|
2753
|
+
|
|
2754
|
+
// Fail open: a deleted cwd makes `process.cwd()` throw on Node, and a
|
|
2755
|
+
// broken manifest read must not crash the stop path.
|
|
2756
|
+
let baseline
|
|
2757
|
+
try {
|
|
2758
|
+
const cwd = typeof config.cwd === 'function' ? config.cwd() : config.cwd
|
|
2759
|
+
baseline = detectProjectBaseline(cwd)
|
|
2760
|
+
} catch {
|
|
2761
|
+
return { block: null }
|
|
2762
|
+
}
|
|
2763
|
+
if (!baseline) return { block: null }
|
|
2764
|
+
if (
|
|
2765
|
+
!hasSourceWrite(
|
|
2766
|
+
baseline,
|
|
2767
|
+
this.turnWriteEvents.map((e) => e.path),
|
|
2768
|
+
)
|
|
2769
|
+
) {
|
|
2770
|
+
return { block: null }
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
const sourceWrites = this.turnWriteEvents.filter((e) => hasSourceWrite(baseline, [e.path]))
|
|
2774
|
+
const lastSourceWriteSeq = sourceWrites.reduce((max, e) => Math.max(max, e.seq), -1)
|
|
2775
|
+
const report = evaluateBaseline(baseline, this.turnCommands, lastSourceWriteSeq)
|
|
2776
|
+
this.baselineReport = report
|
|
2777
|
+
|
|
2778
|
+
if (report.missing.length === 0) return { block: null }
|
|
2779
|
+
const missing = report.missing.join(', ')
|
|
2780
|
+
|
|
2781
|
+
if (roundsLeft <= 0) {
|
|
2782
|
+
return {
|
|
2783
|
+
block: null,
|
|
2784
|
+
systemMessage: t('errors.verification_budget_spent', { missing }),
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
if (this.verificationBlocked) return { block: null }
|
|
2788
|
+
this.verificationBlocked = true
|
|
2789
|
+
return {
|
|
2790
|
+
block: {
|
|
2791
|
+
source: 'verification-baseline',
|
|
2792
|
+
text: t('errors.verification_missing', { missing }),
|
|
2793
|
+
reason: missing,
|
|
2794
|
+
},
|
|
2795
|
+
systemMessage: t('errors.verification_missing', { missing }),
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
|
|
2799
|
+
/**
|
|
2800
|
+
* Third stop source: after a turn that wrote files, run one independent
|
|
2801
|
+
* review. FAIL blocks and feeds the findings back; a broken reviewer is
|
|
2802
|
+
* fail-open (a bad gate must not trap the turn).
|
|
2803
|
+
*
|
|
2804
|
+
* `roundsLeft` is checked here rather than in the caller: the caller's budget
|
|
2805
|
+
* warning would throw a FAIL away, and the longest turns are exactly where
|
|
2806
|
+
* files were written.
|
|
2807
|
+
*/
|
|
2808
|
+
private async checkReviewGate(
|
|
2809
|
+
roundsLeft: number,
|
|
2810
|
+
signal?: AbortSignal,
|
|
2811
|
+
): Promise<{
|
|
2812
|
+
block: { source: string; text: string; reason: string } | null
|
|
2813
|
+
systemMessage?: string
|
|
2814
|
+
}> {
|
|
2815
|
+
const gate = this.reviewGate
|
|
2816
|
+
if (!gate || !gate.enabled) return { block: null }
|
|
2817
|
+
if (this.reviewWriteOps === 0 || this.reviewedAtOps === this.reviewWriteOps) {
|
|
2818
|
+
return { block: null }
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
if (this.reviewRounds >= gate.maxRounds) {
|
|
2822
|
+
this.reviewedAtOps = this.reviewWriteOps
|
|
2823
|
+
return {
|
|
2824
|
+
block: null,
|
|
2825
|
+
systemMessage: t('errors.review_gate_budget_spent', { max: String(gate.maxRounds) }),
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
this.reviewRounds++
|
|
2830
|
+
let result
|
|
2831
|
+
try {
|
|
2832
|
+
result = await gate.runner({
|
|
2833
|
+
cwd: typeof gate.cwd === 'function' ? gate.cwd() : gate.cwd,
|
|
2834
|
+
userPrompt: this.turnPrompt,
|
|
2835
|
+
changedFiles: [...this.turnWrites],
|
|
2836
|
+
round: this.reviewRounds,
|
|
2837
|
+
maxRounds: gate.maxRounds,
|
|
2838
|
+
previousFindings: this.lastReviewFindings,
|
|
2839
|
+
authorResponse: this.lastAssistantText(),
|
|
2840
|
+
baseline: this.baselineReport,
|
|
2841
|
+
signal,
|
|
2842
|
+
})
|
|
2843
|
+
} catch (err) {
|
|
2844
|
+
result = {
|
|
2845
|
+
status: 'error' as const,
|
|
2846
|
+
message: err instanceof Error ? err.message : String(err),
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
|
|
2850
|
+
if (result.status === 'pass') {
|
|
2851
|
+
this.reviewedAtOps = this.reviewWriteOps
|
|
2852
|
+
this.lastReviewFindings = undefined
|
|
2853
|
+
return { block: null }
|
|
2854
|
+
}
|
|
2855
|
+
|
|
2856
|
+
if (result.status === 'error') {
|
|
2857
|
+
this.reviewedAtOps = this.reviewWriteOps
|
|
2858
|
+
return {
|
|
2859
|
+
block: null,
|
|
2860
|
+
systemMessage: t('errors.review_gate_error', { message: result.message }),
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
|
|
2864
|
+
this.lastReviewFindings = result.findings
|
|
2865
|
+
// No budget left: blocking would be discarded by the caller, but the
|
|
2866
|
+
// findings still reach the operator as a warning.
|
|
2867
|
+
if (roundsLeft <= 0) {
|
|
2868
|
+
this.reviewedAtOps = this.reviewWriteOps
|
|
2869
|
+
return {
|
|
2870
|
+
block: null,
|
|
2871
|
+
systemMessage: this.capHookContext(`[review gate] ${result.findings}`),
|
|
2872
|
+
}
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
const firstLine = result.findings.split('\n', 1)[0]?.trim() || 'issues found'
|
|
2876
|
+
return {
|
|
2877
|
+
block: {
|
|
2878
|
+
source: 'review-gate',
|
|
2879
|
+
text: `[review gate ${this.reviewRounds}/${gate.maxRounds}]\n${result.findings}`,
|
|
2880
|
+
reason: `review gate round ${this.reviewRounds}/${gate.maxRounds}: ${firstLine}`,
|
|
2881
|
+
},
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
|
|
2885
|
+
/** The author's last assistant text, for a round-2 review's rebuttal context. */
|
|
2886
|
+
private lastAssistantText(): string | undefined {
|
|
2887
|
+
const messages = this.context.getMessages()
|
|
2888
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
2889
|
+
const message = messages[i]!
|
|
2890
|
+
if (message.role !== 'assistant') continue
|
|
2891
|
+
const text =
|
|
2892
|
+
typeof message.content === 'string'
|
|
2893
|
+
? message.content
|
|
2894
|
+
: (message.content as Array<{ type: string; text?: string }>)
|
|
2895
|
+
.filter((block) => block.type === 'text')
|
|
2896
|
+
.map((block) => block.text ?? '')
|
|
2897
|
+
.join('\n')
|
|
2898
|
+
const trimmed = text.trim()
|
|
2899
|
+
return trimmed ? this.capHookContext(trimmed) : undefined
|
|
2900
|
+
}
|
|
2901
|
+
return undefined
|
|
2902
|
+
}
|
|
2903
|
+
|
|
2559
2904
|
/**
|
|
2560
2905
|
* 「这个数是你量出来的,还是你推出来的?」
|
|
2561
2906
|
*
|
package/src/core/hooks.ts
CHANGED
|
@@ -57,6 +57,9 @@ export function mergePermissionDecision(
|
|
|
57
57
|
return incScore > currScore ? incoming : current
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/** Compiled hook matchers, keyed by their source string. Bounded by config size. */
|
|
61
|
+
const matcherCache = new Map<string, RegExp | null>()
|
|
62
|
+
|
|
60
63
|
export class HookEngine {
|
|
61
64
|
private hooks: HookDefinition[] = []
|
|
62
65
|
/** Health tracking per hook key (event[:toolName]) */
|
|
@@ -339,14 +342,22 @@ export class HookEngine {
|
|
|
339
342
|
*/
|
|
340
343
|
private matchesMatcher(matcher: string | undefined, name: string | undefined): boolean {
|
|
341
344
|
if (!matcher || !name) return true
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
345
|
+
// Compile once per pattern. A hook whose matcher does not apply is still
|
|
346
|
+
// consulted on every call/row/key; recompiling its regex there was pure
|
|
347
|
+
// per-keystroke work (CC 2.1.333-167). `null` caches "does not compile".
|
|
348
|
+
let compiled = matcherCache.get(matcher)
|
|
349
|
+
if (compiled === undefined) {
|
|
350
|
+
try {
|
|
351
|
+
compiled = new RegExp(matcher)
|
|
352
|
+
} catch {
|
|
353
|
+
compiled = null
|
|
354
|
+
}
|
|
355
|
+
matcherCache.set(matcher, compiled)
|
|
349
356
|
}
|
|
357
|
+
// An uncompilable pattern cannot get this far through loadHookConfigs,
|
|
358
|
+
// which compiles every matcher when it loads. Keep such a hook running
|
|
359
|
+
// rather than dropping it silently.
|
|
360
|
+
return compiled === null ? true : compiled.test(name)
|
|
350
361
|
}
|
|
351
362
|
|
|
352
363
|
private async runHooks(
|
package/src/core/instructions.ts
CHANGED
|
@@ -25,13 +25,27 @@ export interface FrontmatterResult {
|
|
|
25
25
|
export function parseFrontmatter(raw: string): FrontmatterResult {
|
|
26
26
|
// Strip a leading UTF-8 BOM — otherwise `^---` never matches and a
|
|
27
27
|
// BOM-prefixed file is silently treated as body text (effectively ignored).
|
|
28
|
-
|
|
28
|
+
// Normalize CRLF: a Windows-authored instruction file used to match none of
|
|
29
|
+
// the `\n`-anchored fence below, so its header (e.g. `prompt-exclude`) was
|
|
30
|
+
// ignored (CC 2.1.333-097).
|
|
31
|
+
const src = raw.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
|
|
29
32
|
const match = src.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
|
|
30
33
|
if (!match) {
|
|
31
34
|
return { data: {}, content: src }
|
|
32
35
|
}
|
|
36
|
+
let data: Record<string, unknown> = {}
|
|
37
|
+
try {
|
|
38
|
+
const parsed = parseYaml(match[1] || '')
|
|
39
|
+
data =
|
|
40
|
+
parsed && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
41
|
+
? (parsed as Record<string, unknown>)
|
|
42
|
+
: {}
|
|
43
|
+
} catch {
|
|
44
|
+
// An unquoted `Fix: a bug` is invalid YAML. Keep the body rather than
|
|
45
|
+
// letting the throw drop the whole instruction file.
|
|
46
|
+
}
|
|
33
47
|
return {
|
|
34
|
-
data
|
|
48
|
+
data,
|
|
35
49
|
content: match[2] || '',
|
|
36
50
|
}
|
|
37
51
|
}
|
|
@@ -221,7 +235,7 @@ export function buildPermissionBlock(mode: string): string {
|
|
|
221
235
|
// staying stale makes it promise a keypress that does nothing. `bypassPermissions`
|
|
222
236
|
// is still reachable, but only by naming it in config; saying so is what keeps
|
|
223
237
|
// the model from offering it as a way out.
|
|
224
|
-
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.`
|
|
225
239
|
}
|
|
226
240
|
|
|
227
241
|
/** Level label used in each prompt part's provenance comment. */
|