@miphamai/cli 0.85.26 → 0.85.27

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.26
1
+ # Mipham Code v0.85.27
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.26",
3
+ "version": "0.85.27",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -8,6 +8,7 @@ import { getBackgroundAgentRegistry } from './background-registry'
8
8
  import { formatInboundMessage, getMessageBus } from './message-bus'
9
9
  import type { HookEngine } from '../core/hooks'
10
10
  import { PermissionSystem } from '../core/permission'
11
+ import { noteToolOutcome, reviewLedger } from '../core/merge-gate'
11
12
  import { buildPermissionBlock } from '../core/instructions'
12
13
  import { AgentExperience } from './agent-experience'
13
14
  import { PatternAnalyzer } from './pattern-analyzer.js'
@@ -721,6 +722,18 @@ export class SubAgent {
721
722
  try {
722
723
  const result = await tool.execute(effectiveInput, toolContext)
723
724
 
725
+ // Merge gate: a review delegated here still counts for the session
726
+ // that will merge. This loop bypasses `Engine.executeTool`, so the
727
+ // engine's own recording never sees this call — the same two-path
728
+ // shape as tool telemetry, and both paths have to carry it.
729
+ noteToolOutcome(
730
+ reviewLedger,
731
+ toolContext.parentSessionId ?? 'sub-agent',
732
+ tu.name,
733
+ effectiveInput,
734
+ result.success,
735
+ )
736
+
724
737
  // ── P0-5: Run PostToolUse hooks ──
725
738
  let displayResult = result
726
739
  if (this.hookEngine) {
@@ -5,6 +5,8 @@ import type {
5
5
  InferenceHookConfig,
6
6
  CrsiConfig,
7
7
  CrossSessionConfig,
8
+ Message,
9
+ ContentBlock,
8
10
  } from '../shared/index.ts'
9
11
  import { ProviderRegistry } from '../providers/registry'
10
12
  import type { ChatRequest } from '../providers/registry'
@@ -24,6 +26,8 @@ import type { Skills } from '../skills/seam'
24
26
  import { getBackgroundAgentRegistry } from '../agent/background-registry'
25
27
  import { RulesLoader } from './rules-loader'
26
28
  import { extractBashFileAccess } from './permission-rules'
29
+ import { noteToolOutcome, reviewLedger } from './merge-gate'
30
+ import { unprovenCountClaims } from './number-provenance'
27
31
  import type { InstructionsLoader } from './instructions'
28
32
  import { ExperienceRuleEngine } from './rule-engine.js'
29
33
  import { PatternAnalyzer } from '../agent/pattern-analyzer.js'
@@ -386,6 +390,10 @@ export class QueryEngine {
386
390
  private touchedFiles: Set<string> = new Set()
387
391
  /** A tool call failed since the last nudge check. */
388
392
  private pendingToolFailure = false
393
+ /** 本轮用户输入 —— 数字出处判定里它是合法的出处之一。 */
394
+ private currentTurnInput = ''
395
+ /** 数字出处质疑每轮至多一次。 */
396
+ private numberNudgeSent = false
389
397
  /** The recall nudge is offered at most once per engine (session). */
390
398
  private lessonNudgeOffered = false
391
399
  private usageTracker = new UsageTracker()
@@ -699,6 +707,9 @@ export class QueryEngine {
699
707
 
700
708
  // Add user message to context
701
709
  this.context.addMessage({ role: 'user', content: userInput })
710
+ // 数字出处判定的本轮基准:用户这句话本身是合法出处,一次质疑也只给一回。
711
+ this.currentTurnInput = userInput
712
+ this.numberNudgeSent = false
702
713
 
703
714
  // ── Restore point for `/rewind` ──
704
715
  // Taken **here** — the prompt is in history, none of the reply is. That is what
@@ -1529,6 +1540,10 @@ export class QueryEngine {
1529
1540
  // Track touched files for rules matching
1530
1541
  this.trackTouchedFile(name, effectiveParams)
1531
1542
 
1543
+ // Merge gate: only a review that actually ran (and succeeded) may later
1544
+ // permit a merge. Recorded on the one funnel every tool call passes.
1545
+ noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
1546
+
1532
1547
  // Prepend CRSI warnings to result content
1533
1548
  if (hookWarnings.length > 0 && result.success) {
1534
1549
  result.content = hookWarnings.join('\n') + '\n' + (result.content || '')
@@ -2176,10 +2191,8 @@ export class QueryEngine {
2176
2191
  signal?: AbortSignal,
2177
2192
  roundsLeft: number = MAX_TOOL_TURNS,
2178
2193
  ): AsyncGenerator<StreamChunk> {
2179
- if (!this.hookEngine) return
2180
-
2181
- const stopResult = await this.hookEngine.executeStop(this.sessionId)
2182
- if (stopResult.decision !== 'block') return
2194
+ const block = await this.stopBlock()
2195
+ if (!block) return
2183
2196
 
2184
2197
  // A block asks for more work, and more work means another round — which the
2185
2198
  // turn may have none of left. Saying so is the point: a hook quietly ignored
@@ -2189,21 +2202,93 @@ export class QueryEngine {
2189
2202
  type: 'warning',
2190
2203
  content: t('errors.stop_hook_budget_spent', {
2191
2204
  max: String(MAX_TOOL_TURNS),
2192
- reason: stopResult.reason || 'Continue working.',
2205
+ reason: block.reason,
2193
2206
  }),
2194
2207
  }
2195
2208
  return
2196
2209
  }
2197
2210
 
2198
2211
  // Feed the block reason back to the AI and continue
2199
- this.context.injectContext(
2200
- 'stop-hook',
2201
- t('system.context.stop_blocked', {
2202
- reason: stopResult.reason || 'Continue working.',
2203
- }),
2204
- )
2212
+ this.context.injectContext(block.source, block.text)
2205
2213
  yield* this.continueWithTools(signal, roundsLeft)
2206
2214
  }
2215
+
2216
+ /**
2217
+ * 什么构成了「这一轮还结束不了」。
2218
+ *
2219
+ * 两条来源,同一个后果:用户配置的 Stop 钩子(它先说话,先到先得),以及内置的
2220
+ * 数字出处判定。后者不需要钩子引擎 —— 它是产品行为,不是可配置项。
2221
+ */
2222
+ private async stopBlock(): Promise<{ source: string; text: string; reason: string } | null> {
2223
+ if (this.hookEngine) {
2224
+ const stopResult = await this.hookEngine.executeStop(this.sessionId)
2225
+ if (stopResult.decision === 'block') {
2226
+ const reason = stopResult.reason || 'Continue working.'
2227
+ return {
2228
+ source: 'stop-hook',
2229
+ text: t('system.context.stop_blocked', { reason }),
2230
+ reason,
2231
+ }
2232
+ }
2233
+ }
2234
+
2235
+ const claims = this.unprovenNumbers()
2236
+ if (!claims) return null
2237
+ // 提示语给模型,`reason` 只留数字本身 —— 预算用完时那条告警是给**人**看的,
2238
+ // 把整段问话塞进 warning 只会让人读一屏。
2239
+ return {
2240
+ source: 'number-provenance',
2241
+ text: t('system.context.numbers_unproven', { claims }),
2242
+ reason: claims,
2243
+ }
2244
+ }
2245
+
2246
+ /**
2247
+ * 「这个数是你量出来的,还是你推出来的?」
2248
+ *
2249
+ * 判据只收窄到**带计数单位的数量**(见 `number-provenance.ts`),出处只认本轮
2250
+ * 工具结果与用户这句话 —— 模型自己前一轮写下的话不算,那正是「先猜一个、再当
2251
+ * 事实复述」的形状。每轮至多问一次:问过还不改口就作罢,否则一次质疑会变成
2252
+ * 一台永动机。
2253
+ */
2254
+ private unprovenNumbers(): string | null {
2255
+ if (this.numberNudgeSent) return null
2256
+ const messages = this.context.getMessages()
2257
+
2258
+ let reply = ''
2259
+ for (let i = messages.length - 1; i >= 0 && !reply; i--) {
2260
+ const message = messages[i]!
2261
+ if (message.role === 'assistant') reply = flatText(message.content)
2262
+ }
2263
+ if (!reply) return null
2264
+
2265
+ const evidence = [
2266
+ this.currentTurnInput,
2267
+ ...messages.map((m) => (Array.isArray(m.content) ? toolResultText(m.content) : '')),
2268
+ ].join('\n')
2269
+
2270
+ const claims = unprovenCountClaims(reply, evidence)
2271
+ if (claims.length === 0) return null
2272
+ this.numberNudgeSent = true
2273
+ return claims.map((c) => `\`${c.context}\``).join(' / ')
2274
+ }
2275
+ }
2276
+
2277
+ /** 一条消息里的可见文本(不含 tool_use 入参与 thinking)。 */
2278
+ function flatText(content: Message['content']): string {
2279
+ if (typeof content === 'string') return content
2280
+ return content
2281
+ .filter((b) => b.type === 'text')
2282
+ .map((b) => (b.type === 'text' ? b.text : ''))
2283
+ .join('\n')
2284
+ }
2285
+
2286
+ /** 一条消息里的工具结果正文 —— 数字的唯一合法出处。 */
2287
+ function toolResultText(content: ContentBlock[]): string {
2288
+ return content
2289
+ .filter((b) => b.type === 'tool_result')
2290
+ .map((b) => (b.type === 'tool_result' ? b.content : ''))
2291
+ .join('\n')
2207
2292
  }
2208
2293
 
2209
2294
  /**
@@ -500,7 +500,9 @@ Before merging a PR or committing changes that have not been
500
500
  code-reviewed, run a code review first (the /code-review command or the
501
501
  code-review skill) and address its findings. Do not rely on "the user
502
502
  happened to ask" to trigger a review — review proactively as a fixed
503
- step before merge.`)
503
+ step before merge. This is enforced, not merely advised: a built-in
504
+ PreToolUse gate blocks a gh pr merge command when no review skill has run
505
+ in the session.`)
504
506
 
505
507
  // 不可信内容规则 — 读外部产出当数据不当指令,内嵌指令标记而非转述(对齐 §二 prompt-injection 红线)
506
508
  parts.push(`## Untrusted-Content Rule
@@ -0,0 +1,105 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { extname, join } from 'node:path'
3
+ import { extractWikilinks, readMemoryFile } from './memory-manager'
4
+
5
+ /**
6
+ * 记忆库体检:找出「盘上有、系统看不见」的分歧。
7
+ *
8
+ * 四类问题都是同一物种 —— 存储与加载各说各话,而运行时**静默**吞掉差异:
9
+ *
10
+ * - `invisible`:文件读不出记忆条目(无 frontmatter / 无 name / 读不了),
11
+ * 会永远躺在 `~/.mipham/memory/` 里却召不回来。
12
+ * - `duplicate-name`:两个文件声明同一个 `name`,Map 按 name 存 ⇒ 后读的
13
+ * 覆盖先读的,另一个文件从此不可达。
14
+ * - `broken-link`:`[[x]]` 指向不存在的记忆,链接图里那条边是死边。
15
+ * - `index-drift`:`MEMORY.md` 与真实条目对不上(只在写入时重建,手改文件
16
+ * 就会漂移)—— 漂移的是给人看的那份,人读到的清单会说谎。
17
+ *
18
+ * 只读:不移动、不改写、不归档。`/memory gc` 才是会动手的那个。
19
+ */
20
+
21
+ export type MemoryIssueKind = 'invisible' | 'duplicate-name' | 'broken-link' | 'index-drift'
22
+
23
+ export interface MemoryIssue {
24
+ kind: MemoryIssueKind
25
+ /** 文件名、记忆名或链接目标,视 kind 而定 */
26
+ subject: string
27
+ detail: string
28
+ }
29
+
30
+ const INDEX_FILE = 'MEMORY.md'
31
+
32
+ const PROBLEM_TEXT: Record<string, string> = {
33
+ 'no-frontmatter': 'no frontmatter — the loader skips it',
34
+ 'no-name': 'frontmatter has no name — the loader skips it',
35
+ unreadable: 'unreadable',
36
+ }
37
+
38
+ export function auditMemoryDir(dir: string): MemoryIssue[] {
39
+ const issues: MemoryIssue[] = []
40
+ if (!existsSync(dir)) return issues
41
+
42
+ let files: string[]
43
+ try {
44
+ files = readdirSync(dir)
45
+ .filter((f) => extname(f) === '.md' && f !== INDEX_FILE)
46
+ .sort()
47
+ } catch {
48
+ return issues
49
+ }
50
+
51
+ const byName = new Map<string, string[]>()
52
+ const linkSources = new Map<string, string[]>()
53
+
54
+ for (const file of files) {
55
+ const { entry, problem } = readMemoryFile(join(dir, file))
56
+ if (!entry) {
57
+ issues.push({
58
+ kind: 'invisible',
59
+ subject: file,
60
+ detail: PROBLEM_TEXT[problem ?? 'unreadable']!,
61
+ })
62
+ continue
63
+ }
64
+ byName.set(entry.name, [...(byName.get(entry.name) ?? []), file])
65
+ // 用加载器自己的取链接规则(含 10 条硬上限),否则医生会报出系统根本不认的边。
66
+ for (const target of extractWikilinks(entry.content)) {
67
+ linkSources.set(target, [...(linkSources.get(target) ?? []), file])
68
+ }
69
+ }
70
+
71
+ for (const [name, owners] of byName) {
72
+ if (owners.length > 1) {
73
+ issues.push({ kind: 'duplicate-name', subject: name, detail: owners.join(', ') })
74
+ }
75
+ }
76
+
77
+ for (const [target, sources] of linkSources) {
78
+ if (!byName.has(target)) {
79
+ issues.push({ kind: 'broken-link', subject: target, detail: sources.join(', ') })
80
+ }
81
+ }
82
+
83
+ let indexRaw: string | null = null
84
+ try {
85
+ indexRaw = readFileSync(join(dir, INDEX_FILE), 'utf-8')
86
+ } catch {
87
+ indexRaw = null
88
+ }
89
+ const listed = new Set<string>()
90
+ if (indexRaw) {
91
+ for (const match of indexRaw.matchAll(/^- \[([^\]]+)\]\(/gm)) listed.add(match[1]!)
92
+ }
93
+ for (const name of byName.keys()) {
94
+ if (!listed.has(name)) {
95
+ issues.push({ kind: 'index-drift', subject: name, detail: 'missing from MEMORY.md' })
96
+ }
97
+ }
98
+ for (const name of listed) {
99
+ if (!byName.has(name)) {
100
+ issues.push({ kind: 'index-drift', subject: name, detail: 'stale — no such memory' })
101
+ }
102
+ }
103
+
104
+ return issues
105
+ }
@@ -39,6 +39,78 @@ const CONSOLIDATE_THRESHOLD = 0.5
39
39
  /** 写时去重的 TF-IDF 余弦阈值(> 此值视为近重复,合并而非新增)。高于合并阈值,只拦近重复。 */
40
40
  const DEDUP_THRESHOLD = 0.65
41
41
 
42
+ /**
43
+ * 读出 `[[wikilink]]` 目标(硬上限 10 条)。
44
+ *
45
+ * 模块级而非 MemoryManager 私有方法:`/memory doctor` 必须用**同一把尺子**
46
+ * 才能报出「系统真会当作链接的东西」。
47
+ */
48
+ export function extractWikilinks(content: string): string[] {
49
+ const re = /\[\[([^\]]+)\]\]/g
50
+ const links: string[] = []
51
+ let match: RegExpExecArray | null
52
+ while ((match = re.exec(content)) !== null) {
53
+ if (links.length >= 10) break // hard cap
54
+ links.push(match[1]!)
55
+ }
56
+ return links
57
+ }
58
+
59
+ /**
60
+ * 一个记忆文件被读出来的结果。
61
+ *
62
+ * `entry === null` 时 `problem` 说明**为什么**——这正是 `loadAll` 从前的
63
+ * `catch {}` 与 `return null` 吞掉的那部分:文件还在盘上,召回却永远见不到它。
64
+ */
65
+ export type MemoryFileProblem = 'no-frontmatter' | 'no-name' | 'unreadable'
66
+
67
+ export interface MemoryFileRead {
68
+ filePath: string
69
+ entry: MemoryEntry | null
70
+ problem: MemoryFileProblem | null
71
+ }
72
+
73
+ /**
74
+ * 读一个记忆文件。**加载与体检共用这一条路径**——各写一份解析规则,就会
75
+ * 出现「体检说没事、加载却读不进来」的分歧,而医生报告的可信度全靠它。
76
+ */
77
+ export function readMemoryFile(filePath: string): MemoryFileRead {
78
+ try {
79
+ const raw = readFileSync(filePath, 'utf-8')
80
+ const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
81
+ if (!match) return { filePath, entry: null, problem: 'no-frontmatter' }
82
+
83
+ const frontmatter = match[1] || ''
84
+ const content = (match[2] || '').trim()
85
+
86
+ // Parse simple YAML-like frontmatter
87
+ const nameMatch = frontmatter.match(/name:\s*(\S+)/)
88
+ const descMatch = frontmatter.match(/description:\s*(.+)/)
89
+ const typeMatch = frontmatter.match(/type:\s*(\S+)/)
90
+ const relevanceMatch = frontmatter.match(/relevance:\s*\[(.+)\]/)
91
+
92
+ if (!nameMatch) return { filePath, entry: null, problem: 'no-name' }
93
+
94
+ return {
95
+ filePath,
96
+ problem: null,
97
+ entry: {
98
+ name: nameMatch[1]!,
99
+ description: descMatch?.[1]?.trim() || '',
100
+ metadata: {
101
+ type: (typeMatch?.[1] as MemoryMetadata['type']) || 'reference',
102
+ relevance: relevanceMatch?.[1]?.split(',').map((s) => s.trim()) || [],
103
+ },
104
+ content,
105
+ filePath,
106
+ updatedAt: statSync(filePath).mtime,
107
+ },
108
+ }
109
+ } catch {
110
+ return { filePath, entry: null, problem: 'unreadable' }
111
+ }
112
+ }
113
+
42
114
  /** 确定性 hash(无 Date.now / Math.random,同输入同输出 → 幂等 lesson 名)。 */
43
115
  function stableHash(s: string): string {
44
116
  let h = 0
@@ -93,16 +165,8 @@ export class MemoryManager {
93
165
 
94
166
  for (const entry of entries) {
95
167
  if (entry === INDEX_FILE || entry === LINKS_FILE || extname(entry) !== '.md') continue
96
- const filePath = join(this.memoryDir, entry)
97
- try {
98
- const raw = readFileSync(filePath, 'utf-8')
99
- const parsed = this.parseMemoryFile(raw, filePath)
100
- if (parsed) {
101
- this.memories.set(parsed.name, parsed)
102
- }
103
- } catch {
104
- // skip unparseable
105
- }
168
+ const { entry: parsed } = readMemoryFile(join(this.memoryDir, entry))
169
+ if (parsed) this.memories.set(parsed.name, parsed)
106
170
  }
107
171
 
108
172
  // Try cached link graph first, fall back to rebuild
@@ -480,23 +544,12 @@ export class MemoryManager {
480
544
  atomicWriteFileSync(join(this.memoryDir, INDEX_FILE), lines.join('\n') + '\n', { mode: 0o644 })
481
545
  }
482
546
 
483
- private extractWikilinks(content: string): string[] {
484
- const re = /\[\[([^\]]+)\]\]/g
485
- const links: string[] = []
486
- let match: RegExpExecArray | null
487
- while ((match = re.exec(content)) !== null) {
488
- if (links.length >= 10) break // hard cap
489
- links.push(match[1]!)
490
- }
491
- return links
492
- }
493
-
494
547
  private updateWikilinks(name: string, content: string): void {
495
548
  // Clear stale outbound links for this memory
496
549
  this.linkGraph.delete(name)
497
550
 
498
551
  // Extract outbound wikilinks from content
499
- const links = this.extractWikilinks(content)
552
+ const links = extractWikilinks(content)
500
553
  if (links.length > 0) {
501
554
  this.linkGraph.set(name, new Set(links))
502
555
  }
@@ -504,7 +557,7 @@ export class MemoryManager {
504
557
  // Update reverse links: other memories that link to this one
505
558
  for (const [otherName, otherEntry] of this.memories) {
506
559
  if (otherName === name) continue
507
- const otherLinks = this.extractWikilinks(otherEntry.content)
560
+ const otherLinks = extractWikilinks(otherEntry.content)
508
561
  if (otherLinks.includes(name)) {
509
562
  const otherSet = this.linkGraph.get(otherName) || new Set()
510
563
  otherSet.add(name)
@@ -518,14 +571,14 @@ export class MemoryManager {
518
571
  private rebuildLinkGraph(): void {
519
572
  this.linkGraph.clear()
520
573
  for (const [name, entry] of this.memories) {
521
- const links = this.extractWikilinks(entry.content)
574
+ const links = extractWikilinks(entry.content)
522
575
  if (links.length > 0) {
523
576
  this.linkGraph.set(name, new Set(links))
524
577
  }
525
578
  }
526
579
  // Compute reverse links: other memories that link to each memory
527
580
  for (const [name, entry] of this.memories) {
528
- const linked = this.extractWikilinks(entry.content)
581
+ const linked = extractWikilinks(entry.content)
529
582
  for (const target of linked) {
530
583
  if (target === name) continue
531
584
  const targetSet = this.linkGraph.get(target)
@@ -616,34 +669,6 @@ export class MemoryManager {
616
669
  }
617
670
  }
618
671
 
619
- private parseMemoryFile(raw: string, filePath: string): MemoryEntry | null {
620
- const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
621
- if (!match) return null
622
-
623
- const frontmatter = match[1] || ''
624
- const content = (match[2] || '').trim()
625
-
626
- // Parse simple YAML-like frontmatter
627
- const nameMatch = frontmatter.match(/name:\s*(\S+)/)
628
- const descMatch = frontmatter.match(/description:\s*(.+)/)
629
- const typeMatch = frontmatter.match(/type:\s*(\S+)/)
630
- const relevanceMatch = frontmatter.match(/relevance:\s*\[(.+)\]/)
631
-
632
- if (!nameMatch) return null
633
-
634
- return {
635
- name: nameMatch[1]!,
636
- description: descMatch?.[1]?.trim() || '',
637
- metadata: {
638
- type: (typeMatch?.[1] as MemoryMetadata['type']) || 'reference',
639
- relevance: relevanceMatch?.[1]?.split(',').map((s) => s.trim()) || [],
640
- },
641
- content,
642
- filePath,
643
- updatedAt: statSync(filePath).mtime,
644
- }
645
- }
646
-
647
672
  private formatMemoryFile(name: string, metadata: MemoryMetadata, content: string): string {
648
673
  const body = this.formatMemoryBody(metadata, content)
649
674
  return `---
@@ -0,0 +1,158 @@
1
+ import type { HookContext, HookDefinition, HookResult } from '../shared/index'
2
+ import type { HookEngine } from './hooks'
3
+ import { splitShellSegments } from './permission-rules'
4
+ import { shellWords } from '../tools/exec/bash'
5
+
6
+ /**
7
+ * The merge gate: a review must run in this session before a pull request is
8
+ * merged.
9
+ *
10
+ * `instructions.ts` has carried this rule as prose ("Code-Review Merge Gate")
11
+ * since the CRSI work, and prose is exactly what failed: a session opened its
12
+ * own PR and squash-merged it without a review, because nothing had an
13
+ * implementation point. This module is that point — a PreToolUse guard on
14
+ * `gh pr merge`, with the review recorded by the tool funnel itself.
15
+ */
16
+
17
+ /** How long a review counts for the session that ran it. */
18
+ export const REVIEW_WINDOW_MS = 24 * 60 * 60 * 1000
19
+
20
+ /** The operator's one-way out: an unchanged env is the only way to waive the gate. */
21
+ export const MERGE_GATE_WAIVER_ENV = 'MIPHAM_SKIP_MERGE_GATE'
22
+
23
+ /** Skills whose successful run counts as a review of what is about to merge. */
24
+ export const REVIEW_SKILLS = new Set(['code-review', 'self-review', 'security-review'])
25
+
26
+ /** `NAME=value` ahead of a command — assigned to that command, not a command word. */
27
+ const LEADING_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/
28
+
29
+ /**
30
+ * Commands that run another command in turn. `sudo gh pr merge` merges just as
31
+ * much as the bare form, and the guard has to see through the wrapper.
32
+ */
33
+ const COMMAND_WRAPPERS = new Set([
34
+ 'sudo',
35
+ 'doas',
36
+ 'env',
37
+ 'command',
38
+ 'builtin',
39
+ 'exec',
40
+ 'nohup',
41
+ 'nice',
42
+ 'time',
43
+ ])
44
+
45
+ /**
46
+ * Does this Bash command run `gh pr merge`?
47
+ *
48
+ * Quote-aware on purpose: `git commit -m "gh pr merge 55"` and
49
+ * `echo "gh pr merge"` mention the command without running it. Segments are
50
+ * split with the permission matcher's splitter (which ignores quoting), so a
51
+ * quoted `&&` can still split a segment — the resulting over-match is the safe
52
+ * direction, same trade the matcher makes.
53
+ */
54
+ export function isPrMergeCommand(command: string): boolean {
55
+ for (const segment of splitShellSegments(command)) {
56
+ const words = shellWords(segment)
57
+ let i = 0
58
+ while (
59
+ i < words.length &&
60
+ (LEADING_ASSIGNMENT_RE.test(words[i]!) ||
61
+ COMMAND_WRAPPERS.has(words[i]!) ||
62
+ words[i]!.startsWith('-'))
63
+ ) {
64
+ i++
65
+ }
66
+ if (words[i] !== 'gh') continue
67
+ // `gh` takes global flags before the subcommand (`gh -R owner/repo pr …`),
68
+ // so the subcommand is found by its own name rather than by position.
69
+ const args = words.slice(i + 1)
70
+ const at = args.findIndex((word, n) => word === 'pr' && args[n + 1] === 'merge')
71
+ if (at === -1) continue
72
+ const rest = args.slice(at + 2)
73
+ // `--help` prints usage; it does not merge anything.
74
+ if (rest.includes('--help') || rest.includes('-h')) continue
75
+ return true
76
+ }
77
+ return false
78
+ }
79
+
80
+ /**
81
+ * Which sessions have run a review, and when.
82
+ *
83
+ * Time-bounded rather than cleared on session end: the daemon serves many
84
+ * sessions from one process and has no per-session teardown hook here, so an
85
+ * entry is dropped by age instead. A review is a fact about the last day, not
86
+ * a flag that must be reset.
87
+ */
88
+ export class ReviewLedger {
89
+ private reviewed = new Map<string, number>()
90
+
91
+ markReviewed(sessionId: string, at: number = Date.now()): void {
92
+ this.prune(at)
93
+ this.reviewed.set(sessionId, at)
94
+ }
95
+
96
+ hasReviewed(sessionId: string, now: number = Date.now()): boolean {
97
+ const at = this.reviewed.get(sessionId)
98
+ return at !== undefined && now - at <= REVIEW_WINDOW_MS
99
+ }
100
+
101
+ private prune(now: number): void {
102
+ for (const [sessionId, at] of this.reviewed) {
103
+ if (now - at > REVIEW_WINDOW_MS) this.reviewed.delete(sessionId)
104
+ }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Record a tool outcome for the gate — called from the engine's tool funnel.
110
+ *
111
+ * Only a *successful* review skill counts: a skill that was not found, or whose
112
+ * run failed, reviewed nothing.
113
+ */
114
+ export function noteToolOutcome(
115
+ ledger: ReviewLedger,
116
+ sessionId: string,
117
+ toolName: string,
118
+ input: Record<string, unknown>,
119
+ success: boolean,
120
+ ): void {
121
+ if (!success || toolName !== 'Skill') return
122
+ const skill = input.skill
123
+ if (typeof skill === 'string' && REVIEW_SKILLS.has(skill)) ledger.markReviewed(sessionId)
124
+ }
125
+
126
+ export function createMergeGateHook(ledger: ReviewLedger): HookDefinition {
127
+ return {
128
+ event: 'PreToolUse',
129
+ toolName: 'Bash',
130
+ source: 'builtin:merge-gate',
131
+ // A guard that cannot run must not silently allow the merge.
132
+ failureMode: 'closed',
133
+ async handler(ctx: HookContext): Promise<HookResult> {
134
+ const command = ctx.toolInput?.command
135
+ if (typeof command !== 'string' || !isPrMergeCommand(command)) return { allowed: true }
136
+ if (process.env[MERGE_GATE_WAIVER_ENV] === '1') return { allowed: true }
137
+ if (ledger.hasReviewed(ctx.sessionId)) return { allowed: true }
138
+ return {
139
+ allowed: false,
140
+ reason:
141
+ 'This command merges a pull request, and no code review has run in this session. ' +
142
+ 'Run /code-review (or the code-review skill) and address its findings before merging. ' +
143
+ `If the review genuinely happened outside this session, restart Mipham Code with ${MERGE_GATE_WAIVER_ENV}=1.`,
144
+ }
145
+ },
146
+ }
147
+ }
148
+
149
+ /** Process-wide ledger — the engine records into it, the gate reads it. */
150
+ export const reviewLedger = new ReviewLedger()
151
+
152
+ /**
153
+ * Install the built-in guards. Both startup paths must call this — the one-shot
154
+ * CLI and the daemon — or the gate exists in only one of them.
155
+ */
156
+ export function registerBuiltinHooks(engine: HookEngine): void {
157
+ engine.register(createMergeGateHook(reviewLedger))
158
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * 出处判定:「这个数是你量出来的,还是你推出来的?」
3
+ *
4
+ * 只判一种主张 —— **带计数单位的数量**(`4,572 测试` / `343 files` / `1,834 个字符`)。
5
+ * 版本号、端口、日期、行号都不是计数,代码里的数字是在引用而不是在下结论。
6
+ *
7
+ * 出处的定义刻意收窄到**本轮的工具结果**(与用户这句话):模型自己前一轮写下的数
8
+ * 不算出处 —— 那正是「先猜一个、再当事实复述」的形态,也是这条纪律要拦的东西。
9
+ */
10
+
11
+ export interface CountClaim {
12
+ /** 去掉千分位后的数字 —— 判定身份用这个 */
13
+ digits: string
14
+ /** 原文片段(数字 + 单位),好让提示语点名质疑的是哪一处 */
15
+ context: string
16
+ }
17
+
18
+ /** 计数单位。长的写在前面:正则按顺序试,`字符` 先于 `字` 才能整词匹配。 */
19
+ const UNITS = [
20
+ '行代码',
21
+ '字符',
22
+ '字节',
23
+ '文件',
24
+ '测试',
25
+ '用例',
26
+ '提交',
27
+ '端口',
28
+ 'characters',
29
+ 'character',
30
+ 'chars',
31
+ 'char',
32
+ 'bytes',
33
+ 'tokens',
34
+ 'commits',
35
+ 'entries',
36
+ 'entry',
37
+ 'lines',
38
+ 'line',
39
+ 'tests',
40
+ 'test',
41
+ 'cases',
42
+ 'case',
43
+ 'files',
44
+ 'file',
45
+ 'items',
46
+ 'item',
47
+ 'passes',
48
+ 'pass',
49
+ 'runs',
50
+ 'run',
51
+ '个',
52
+ '条',
53
+ '笔',
54
+ '次',
55
+ '行',
56
+ '处',
57
+ '项',
58
+ '种',
59
+ '轮',
60
+ '份',
61
+ '张',
62
+ '位',
63
+ '家',
64
+ '字',
65
+ ]
66
+
67
+ const UNIT_ALT = UNITS.join('|')
68
+ /** 3 位以上(`343`)或带千分位(`4,572`)—— 一两位的数字太容易是序号而非计数。 */
69
+ const NUMBER = '(\\d{1,3}(?:,\\d{3})+|\\d{3,})'
70
+ const CLAIM_RE = new RegExp(`${NUMBER}\\s*(?:${UNIT_ALT})(?![a-z])`, 'gi')
71
+
72
+ /** 代码块与行内代码里的数字是在引用,不是在下结论。 */
73
+ function stripCode(text: string): string {
74
+ return text.replace(/```[\s\S]*?```/g, ' ').replace(/`[^`\n]*`/g, ' ')
75
+ }
76
+
77
+ function normalize(digits: string): string {
78
+ return digits.replace(/,/g, '')
79
+ }
80
+
81
+ /**
82
+ * 从回复里挑出「没有出处」的计数主张。
83
+ *
84
+ * @param reply 本轮最终回复(模型自己的话)
85
+ * @param evidence 本轮的工具结果 + 用户这句话
86
+ */
87
+ export function unprovenCountClaims(reply: string, evidence: string): CountClaim[] {
88
+ const prose = stripCode(reply)
89
+ const haystack = evidence.replace(/,/g, '')
90
+ const seen = new Set<string>()
91
+ const claims: CountClaim[] = []
92
+
93
+ for (const match of prose.matchAll(CLAIM_RE)) {
94
+ const digits = normalize(match[1]!)
95
+ if (digits.length < 3) continue
96
+ // 「第 1234 行」是位置不是数量 —— 它指的是哪一行,不是有多少行。
97
+ const before = prose.slice(0, match.index).trimEnd()
98
+ if (before.endsWith('第')) continue
99
+ if (seen.has(digits)) continue
100
+ if (new RegExp(`(?<!\\d)${digits}(?!\\d)`).test(haystack)) continue
101
+ seen.add(digits)
102
+ claims.push({ digits, context: match[0].trim() })
103
+ }
104
+
105
+ return claims
106
+ }
@@ -29,6 +29,7 @@ import type { ProviderRegistry } from '../providers/registry'
29
29
  import { SkillsLoader } from '../skills/loader'
30
30
  import { RulesLoader } from '../core/rules-loader'
31
31
  import { HookEngine } from '../core/hooks'
32
+ import { registerBuiltinHooks } from '../core/merge-gate'
32
33
  import { loadHookConfigs } from '../core/hooks-config'
33
34
  import { isSafeMode } from '../core/safe-mode'
34
35
  import { loadSettingsJson } from '../config/loader'
@@ -101,6 +102,7 @@ function hooksFor(cwd: string, skills: SkillsLoader): HookEngine {
101
102
  for (const skill of skills.list()) {
102
103
  for (const hook of skill.hooks ?? []) engine.register(hook)
103
104
  }
105
+ registerBuiltinHooks(engine)
104
106
  // 项目级 hooks 是仓库可控的代码执行面,且 daemon 这条路径**从不**经过交互式信任
105
107
  // 询问 —— 而 `isCwdAllowed` 只要求会话 cwd 在 daemon 根目录之内(`workspace-guard.ts:27`
106
108
  // `isWithin(cwd, daemonRoot) || isTrusted(cwd)`)⇒ 在未信任的克隆里启动的 daemon,
@@ -297,7 +297,14 @@
297
297
  "consolidate_result": "Consolidated: {removed} auto-* removed, {merged} lessons written.",
298
298
  "dedup_title": "─ Memory Near-Duplicates ─",
299
299
  "dedup_none": "No near-duplicate memories found.",
300
- "dedup_footer": "Pairs above the TF-IDF cosine threshold. Merge is manual — run /memory consolidate for auto-* clustering, or edit the files directly."
300
+ "dedup_footer": "Pairs above the TF-IDF cosine threshold. Merge is manual — run /memory consolidate for auto-* clustering, or edit the files directly.",
301
+ "doctor_title": "─ Memory Doctor ─",
302
+ "doctor_clean": "Store is consistent: {count} memories, index in sync, no broken links.",
303
+ "doctor_invisible": "Invisible to recall ({count}) — the loader skips these files:",
304
+ "doctor_duplicate": "Duplicate names ({count}) — only one file of each is reachable:",
305
+ "doctor_broken_link": "Broken wikilinks ({count}):",
306
+ "doctor_index": "Index drift ({count}) — MEMORY.md disagrees with the store:",
307
+ "doctor_footer": "Read-only report. Fix the files above by hand; for the rest, run /memory gc, /memory consolidate or /memory dedup."
301
308
  },
302
309
  "upgrade": {
303
310
  "uptodate": "── Upgrade Mipham Code ──\n\nCurrent version: v{current}\nLatest: v{latest}\n\n✓ Already up to date.\n\nTo check manually: https://www.npmjs.com/package/@miphamai/cli",
@@ -989,7 +996,8 @@
989
996
  "context": {
990
997
  "omitted": "Prior conversation context omitted.",
991
998
  "summary_heading": "[Earlier conversation summary — {heading}]",
992
- "stop_blocked": "[The Stop hook blocked completion]: {reason}"
999
+ "stop_blocked": "[The Stop hook blocked completion]: {reason}",
1000
+ "numbers_unproven": "[Numbers with no source this turn]: {claims}. You reported these counts, but no tool output in this session — and not the user's own words — carries them. Either run the command that produces each one, or say plainly that it is an estimate. Do not restate a guessed number as a measurement."
993
1001
  },
994
1002
  "goal": {
995
1003
  "verified": "✅ Goal verification passed: {script}",
@@ -297,7 +297,14 @@
297
297
  "consolidate_result": "合并完成:删除 {removed} 条 auto-*,写入 {merged} 条 lesson-*。",
298
298
  "dedup_title": "─ 记忆近重复 ─",
299
299
  "dedup_none": "未发现近重复记忆。",
300
- "dedup_footer": "以上为 TF-IDF 余弦超过阈值的近重复对。合并需手动——auto-* 走 /memory consolidate 聚簇,或直接编辑文件。"
300
+ "dedup_footer": "以上为 TF-IDF 余弦超过阈值的近重复对。合并需手动——auto-* 走 /memory consolidate 聚簇,或直接编辑文件。",
301
+ "doctor_title": "─ 记忆体检 ─",
302
+ "doctor_clean": "记忆库一致:{count} 条记忆,索引同步,无断链。",
303
+ "doctor_invisible": "召回看不见({count})—— 加载器会跳过这些文件:",
304
+ "doctor_duplicate": "重名({count})—— 每个同名只有一份够得着:",
305
+ "doctor_broken_link": "断掉的 wikilink({count}):",
306
+ "doctor_index": "索引漂移({count})—— MEMORY.md 与记忆库对不上:",
307
+ "doctor_footer": "只读报告。上面这些需手改或删除文件;其余走 /memory gc、/memory consolidate、/memory dedup。"
301
308
  },
302
309
  "upgrade": {
303
310
  "uptodate": "── 升级 Mipham Code ──\n\n当前版本: v{current}\n最新版本: v{latest}\n\n✓ 已是最新版本。\n\n手动检查: https://www.npmjs.com/package/@miphamai/cli",
@@ -989,7 +996,8 @@
989
996
  "context": {
990
997
  "omitted": "之前的对话上下文已省略。",
991
998
  "summary_heading": "[之前的对话摘要 — {heading}]",
992
- "stop_blocked": "[Stop 钩子阻止完成]:{reason}"
999
+ "stop_blocked": "[Stop 钩子阻止完成]:{reason}",
1000
+ "numbers_unproven": "[本轮没有出处的数字]:{claims}。这些是你汇报的数量,但本次会话的任何工具输出里都没有它们,用户这句话里也没有。要么去跑产它的那一条命令,要么明说这是估算 —— 不要把猜出来的数当量出来的数说出去。"
993
1001
  },
994
1002
  "goal": {
995
1003
  "verified": "✅ 目标验证通过:{script}",
package/src/index.tsx CHANGED
@@ -52,6 +52,7 @@ import { registerMcpServerTools, syncMcpToolsOnChange } from './mcp/registry'
52
52
  import { formatMcpConnectFailures, type McpConnectFailure } from './mcp/connect-failures'
53
53
  import { AgentRegistry } from './agent/agent-registry'
54
54
  import { HookEngine } from './core/hooks'
55
+ import { registerBuiltinHooks } from './core/merge-gate'
55
56
  import { loadHookConfigs } from './core/hooks-config'
56
57
  import { isSafeMode } from './core/safe-mode'
57
58
  import { ArtifactServer } from './artifacts/server'
@@ -797,6 +798,7 @@ export async function runApp(options: RunOptions): Promise<void> {
797
798
  }
798
799
  }
799
800
  }
801
+ registerBuiltinHooks(hookEngine)
800
802
  }
801
803
 
802
804
  // Register settings.json hooks (Claude Code convention — additive across levels).
@@ -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.26' as const
12
+ export const PACKAGE_VERSION = '0.85.27' 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 = 4533 as const
93
+ export const TEST_COUNT = 4585 as const
@@ -421,7 +421,7 @@ const CD_COMMANDS = new Set(['cd', 'pushd'])
421
421
  * Over-splitting is the safe direction here: a word that is not really a
422
422
  * command word simply fails to match `cd`.
423
423
  */
424
- function shellWords(segment: string): string[] {
424
+ export function shellWords(segment: string): string[] {
425
425
  const words: string[] = []
426
426
  let cur = ''
427
427
  let started = false
@@ -76,6 +76,7 @@ import { getPreference, setPreference } from '../config/preferences'
76
76
  import { loadCrossSessionConfig, tryRestoreFromBackup } from '../config/loader'
77
77
  import { getWorkspaceTrust } from '../core/workspace-trust'
78
78
  import { getMemoryManager } from '../core/memory/memory-loader'
79
+ import { auditMemoryDir } from '../core/memory/memory-audit'
79
80
  import {
80
81
  resolveTelemetry,
81
82
  readTelemetrySettings,
@@ -4644,6 +4645,37 @@ const memoryCmd: CommandHandler = async (ctx, args) => {
4644
4645
  return { content: lines.join('\n') }
4645
4646
  }
4646
4647
 
4648
+ // /memory doctor — 只读体检:找出「盘上有、系统看不见」的分歧,不动任何文件
4649
+ if (args[0]?.toLowerCase() === 'doctor') {
4650
+ const issues = auditMemoryDir(memoryDir)
4651
+ const lines: string[] = [t('commands.memories.doctor_title'), '']
4652
+
4653
+ if (issues.length === 0) {
4654
+ const count = existsSync(memoryDir)
4655
+ ? readdirSync(memoryDir).filter((f) => f.endsWith('.md') && f !== 'MEMORY.md').length
4656
+ : 0
4657
+ lines.push(t('commands.memories.doctor_clean', { count: String(count) }))
4658
+ return { content: lines.join('\n') }
4659
+ }
4660
+
4661
+ const order = ['invisible', 'duplicate-name', 'broken-link', 'index-drift'] as const
4662
+ const headers: Record<(typeof order)[number], string> = {
4663
+ invisible: 'commands.memories.doctor_invisible',
4664
+ 'duplicate-name': 'commands.memories.doctor_duplicate',
4665
+ 'broken-link': 'commands.memories.doctor_broken_link',
4666
+ 'index-drift': 'commands.memories.doctor_index',
4667
+ }
4668
+ for (const kind of order) {
4669
+ const group = issues.filter((i) => i.kind === kind)
4670
+ if (group.length === 0) continue
4671
+ lines.push(t(headers[kind], { count: String(group.length) }))
4672
+ lines.push(...group.map((i) => ` • ${i.subject} — ${i.detail}`))
4673
+ lines.push('')
4674
+ }
4675
+ lines.push(t('commands.memories.doctor_footer'))
4676
+ return { content: lines.join('\n') }
4677
+ }
4678
+
4647
4679
  if (!existsSync(memoryDir)) {
4648
4680
  return { content: t('commands.memories.no_memories') }
4649
4681
  }