@miphamai/cli 0.85.49 → 0.85.50

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.49
1
+ # Mipham Code v0.85.50
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 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.49",
3
+ "version": "0.85.50",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -758,6 +758,10 @@ export class SubAgent {
758
758
  // credential executed verbatim one level down.
759
759
  let effectiveInput = tu.input
760
760
  let gateWarnings: string[] = []
761
+ // SIS pre-flight may have applied a signature's fix; score the outcome
762
+ // on this funnel too (the engine's recording never sees this loop).
763
+ let sisFixSignature: string | undefined
764
+ let sisOutcomeRecorded = false
761
765
  if (this.services) {
762
766
  const outcome = await runPreToolGate(tu.name, tu.input, this.services.gate, 'sub-agent')
763
767
  if (!outcome.ok) {
@@ -769,6 +773,7 @@ export class SubAgent {
769
773
  }
770
774
  effectiveInput = outcome.params
771
775
  gateWarnings = outcome.warnings
776
+ sisFixSignature = outcome.sisFixSignature
772
777
  } else if (this.hooks) {
773
778
  // Legacy path: a caller that built a SubAgent by hand with only a
774
779
  // hook engine still gets its PreToolUse hook. The other four gates
@@ -829,6 +834,11 @@ export class SubAgent {
829
834
  try {
830
835
  const result = await tool.execute(effectiveInput, toolContext)
831
836
 
837
+ if (sisFixSignature) {
838
+ this.services?.gate.preflight?.()?.recordOutcome(sisFixSignature, result.success)
839
+ sisOutcomeRecorded = true
840
+ }
841
+
832
842
  // Merge gate: a review delegated here still counts for the session
833
843
  // that will merge. This loop bypasses `Engine.executeTool`, so the
834
844
  // engine's own recording never sees this call — the same two-path
@@ -899,6 +909,13 @@ export class SubAgent {
899
909
  ],
900
910
  })
901
911
  } catch (err) {
912
+ // The applied SIS fix was followed by a thrown error — score it. The
913
+ // flag keeps a later hook throw from failing a fix that worked.
914
+ if (sisFixSignature && !sisOutcomeRecorded) {
915
+ this.services?.gate.preflight?.()?.recordOutcome(sisFixSignature, false)
916
+ sisOutcomeRecorded = true
917
+ }
918
+
902
919
  // ── P0-5: Run PostToolUseFailure hooks ──
903
920
  if (this.hooks) {
904
921
  this.hooks
@@ -86,14 +86,6 @@ export class AutoCorrector {
86
86
  return this.handleUnknownError(toolName, params, error)
87
87
  }
88
88
 
89
- /**
90
- * Record a manual correction (user fixed it themselves).
91
- * Updates the signature's success rate.
92
- */
93
- recordManualFix(signatureId: string, success: boolean): void {
94
- this.errorDB.recordResult(signatureId, success)
95
- }
96
-
97
89
  // ── Private ──
98
90
 
99
91
  /** Handle a known error pattern with an existing signature. */
@@ -19,6 +19,7 @@ import type { ErrorSignatureDB } from './error-signature-db.js'
19
19
  import type { CrsiProvenanceBridge } from '../agent/crsi-provenance-bridge.js'
20
20
  import { getMetrics } from './metrics'
21
21
  import { miphamHome } from './paths.ts'
22
+ import { appendSignals, insightsToSignals } from './crsi-inbox'
22
23
 
23
24
  // ── Types ──
24
25
 
@@ -211,6 +212,18 @@ export class AutoMemoryEngine {
211
212
  howToApply: '下次会话开始时回顾此文件,检查是否有可操作的改进项',
212
213
  })
213
214
 
215
+ // CRSI 信号收件箱:进程退出后信号仍在。
216
+ //
217
+ // 不写的话,「学习」隐含一个前提 —— 失败发生后、进程退出前,有人想起来
218
+ // 敲 `/crsi propose`;人不在,insight 随进程消失。收件箱把这一段变成
219
+ // 每轮同步落盘,下次启动由 `refreshPendingLessons` 自动渲染成待并入教训。
220
+ // 失败不能让一轮对话失败:收件箱是非关键路径。
221
+ try {
222
+ appendSignals(insightsToSignals(reflection.crsiInsights.filter((i) => i.autoApplicable)))
223
+ } catch {
224
+ // ignore — 收件箱写失败不影响本轮
225
+ }
226
+
214
227
  // Feed CRSI insights into the rule engine
215
228
  this.feedCrsiPipeline(reflection)
216
229
  }
@@ -18,6 +18,7 @@ export interface CapabilitySources {
18
18
  active: number
19
19
  degraded: number
20
20
  retired: number
21
+ fixable: number
21
22
  avgSuccessRate: number
22
23
  totalInterceptions: number
23
24
  }
@@ -37,7 +38,36 @@ function safeMetaRuleCount(engine: CapabilitySources): number {
37
38
  }
38
39
  }
39
40
 
40
- export function buildCapabilityReport(engine: CapabilitySources): string {
41
+ /**
42
+ * Ledger-backed numbers, already loaded and summarised by the caller.
43
+ *
44
+ * Kept out of `buildCapabilityReport` so the report stays pure and testable:
45
+ * the command reads `~/.mipham/crsi/*.jsonl`, the builder only renders.
46
+ */
47
+ export interface CapabilityLedgers {
48
+ lastEval?: { score: number; passed: number; total: number; timestamp: string }
49
+ improvements?: { count: number; verdicts: Record<string, number>; latestTimestamp: string }
50
+ probation?: { count: number; latestTimestamp: string }
51
+ }
52
+
53
+ /** A ledger row, stamped with the file and the record's own timestamp. */
54
+ function ledgerRow(metric: string, value: string, file: string, timestamp?: string): string {
55
+ const source = timestamp ? `ledger:${file}@${timestamp}` : `ledger:${file}(未找到)`
56
+ return `| ${metric} | ${value} | ${source} |`
57
+ }
58
+
59
+ /**
60
+ * 能力自报告。
61
+ *
62
+ * **每个数字都带出处**:`now(getter)` 是本次调用实时读到的,`ledger:…@…` 是台账
63
+ * 里那条记录的时间戳。这份报告刻意不引用文档数字 —— 文档值不是实测值,而两者
64
+ * 混在一张「读数」表里,正是 2026-11-26 那次自评把 CLAUDE.md 的 5,349 当成
65
+ * 实测结果的原因。
66
+ */
67
+ export function buildCapabilityReport(
68
+ engine: CapabilitySources,
69
+ ledgers: CapabilityLedgers = {},
70
+ ): string {
41
71
  const lines: string[] = ['## 🧭 能力自报告 (CRSI Inventory)', '']
42
72
 
43
73
  // ── 🧠 学习 (CRSI) ──
@@ -49,24 +79,30 @@ export function buildCapabilityReport(engine: CapabilitySources): string {
49
79
  const insights = engine.getAutoMemory?.()?.accumulatedInsights ?? []
50
80
 
51
81
  lines.push('### 🧠 学习 (CRSI)', '')
52
- lines.push('| 指标 | 值 |')
53
- lines.push('|------|----|')
54
- lines.push(`| 活跃规则 | ${rules.length} (内置 ${builtin} · 自动 ${auto} · 手动 ${manual}) |`)
55
- lines.push(`| 已检测模式 | ${patterns.length} |`)
56
- lines.push(`| 反思洞察 | ${insights.length} |`)
57
- lines.push(`| 元规则 | ${safeMetaRuleCount(engine)} |`)
82
+ lines.push('| 指标 | 值 | 出处 |')
83
+ lines.push('|------|----|------|')
84
+ lines.push(
85
+ `| 活跃规则 | ${rules.length} (内置 ${builtin} · 自动 ${auto} · 手动 ${manual}) | now(getRuleEngine) |`,
86
+ )
87
+ lines.push(`| 已检测模式 | ${patterns.length} | now(getPatternAnalyzer) |`)
88
+ lines.push(`| 反思洞察 | ${insights.length} | now(getAutoMemory) |`)
89
+ lines.push(`| 元规则 | ${safeMetaRuleCount(engine)} | now(getMetaRuleEngine) |`)
58
90
 
59
91
  // ── 🛡️ 免疫 (SIS) ──
60
92
  const sis = engine.getErrorSignatureDB?.()?.getStats()
61
93
  lines.push('', '### 🛡️ 免疫 (SIS)', '')
62
94
  if (sis) {
63
- lines.push('| 指标 | 值 |')
64
- lines.push('|------|----|')
95
+ lines.push('| 指标 | 值 | 出处 |')
96
+ lines.push('|------|----|------|')
65
97
  lines.push(
66
- `| 错误签名 | ${sis.total} 条 (🟢${sis.active} · 🟡${sis.degraded} · ⚫${sis.retired}) |`,
98
+ `| 错误签名 | ${sis.total} 条 (🟢${sis.active} · 🟡${sis.degraded} · ⚫${sis.retired}) | now(getErrorSignatureDB) |`,
67
99
  )
68
- lines.push(`| 平均成功率 | ${Math.round(sis.avgSuccessRate * 100)}% |`)
69
- lines.push(`| 总拦截 | ${sis.totalInterceptions} 次 |`)
100
+ lines.push(
101
+ `| 平均成功率 | ${
102
+ sis.fixable > 0 ? `${Math.round(sis.avgSuccessRate * 100)}%` : '—(无可自动修复签名)'
103
+ } | now(getErrorSignatureDB) |`,
104
+ )
105
+ lines.push(`| 总拦截 | ${sis.totalInterceptions} 次 | now(getErrorSignatureDB) |`)
70
106
  } else {
71
107
  lines.push('_未初始化_')
72
108
  }
@@ -78,13 +114,15 @@ export function buildCapabilityReport(engine: CapabilitySources): string {
78
114
  const karuna = constitution.principles.filter((p) => p.facet === 'karuna').length
79
115
  const prajna = constitution.principles.filter((p) => p.facet === 'prajna').length
80
116
  const vajra = constitution.principles.filter((p) => p.facet === 'vajra').length
81
- lines.push('| 指标 | 值 |')
82
- lines.push('|------|----|')
83
- lines.push(`| 版本 | ${constitution.version} |`)
117
+ lines.push('| 指标 | 值 | 出处 |')
118
+ lines.push('|------|----|------|')
119
+ lines.push(`| 版本 | ${constitution.version} | now(getConstitutionLoader) |`)
120
+ lines.push(
121
+ `| 原则 | ${constitution.principles.length} 条 (悲 ${karuna} · 智 ${prajna} · 金刚 ${vajra}) | now(getConstitutionLoader) |`,
122
+ )
84
123
  lines.push(
85
- `| 原则 | ${constitution.principles.length} 条 (悲 ${karuna} · 智 ${prajna} · 金刚 ${vajra}) |`,
124
+ `| 愿力序言 | ${constitution.preamble ? '已注入 self-critique' : '无'} | now(getConstitutionLoader) |`,
86
125
  )
87
- lines.push(`| 愿力序言 | ${constitution.preamble ? '已注入 self-critique' : '无'} |`)
88
126
  } else {
89
127
  lines.push('_未初始化_')
90
128
  }
@@ -92,7 +130,63 @@ export function buildCapabilityReport(engine: CapabilitySources): string {
92
130
  // ── ⚠️ 未接线 / 待启用 ──
93
131
  const selfCritique = engine.getSelfCritique?.()?.getConfig()
94
132
  lines.push('', '### ⚠️ 未接线 / 待启用', '')
95
- lines.push(`| self-critique | ${selfCritique?.enabled ? '🟢 已启用' : '⚫ 未启用 (opt-in)'} |`)
133
+ lines.push('| 指标 | 值 | 出处 |')
134
+ lines.push('|------|----|------|')
135
+ lines.push(
136
+ `| self-critique | ${selfCritique?.enabled ? '🟢 已启用' : '⚫ 未启用 (opt-in)'} | now(getSelfCritique) |`,
137
+ )
138
+
139
+ // ── 📊 真值评估(台账) ──
140
+ lines.push('', '### 📊 真值评估(台账)', '')
141
+ lines.push('| 指标 | 值 | 出处 |')
142
+ lines.push('|------|----|------|')
143
+ if (ledgers.lastEval) {
144
+ const e = ledgers.lastEval
145
+ lines.push(
146
+ ledgerRow(
147
+ '最近机制 eval',
148
+ `${e.passed}/${e.total}(score ${e.score})`,
149
+ 'eval-scores.jsonl',
150
+ e.timestamp,
151
+ ),
152
+ )
153
+ } else {
154
+ lines.push(ledgerRow('最近机制 eval', '无记录', 'eval-scores.jsonl'))
155
+ }
156
+ if (ledgers.improvements) {
157
+ const im = ledgers.improvements
158
+ const verdicts = Object.entries(im.verdicts)
159
+ .map(([verdict, count]) => `${verdict} ${count}`)
160
+ .join(' · ')
161
+ lines.push(
162
+ ledgerRow(
163
+ '改进台账',
164
+ `${im.count} 条${verdicts ? `(${verdicts})` : ''}`,
165
+ 'improvements.jsonl',
166
+ im.latestTimestamp,
167
+ ),
168
+ )
169
+ } else {
170
+ lines.push(ledgerRow('改进台账', '无记录', 'improvements.jsonl'))
171
+ }
172
+ if (ledgers.probation) {
173
+ lines.push(
174
+ ledgerRow(
175
+ '试用期',
176
+ `${ledgers.probation.count} 条`,
177
+ 'probation.jsonl',
178
+ ledgers.probation.latestTimestamp,
179
+ ),
180
+ )
181
+ } else {
182
+ lines.push(ledgerRow('试用期', '无记录', 'probation.jsonl'))
183
+ }
184
+
185
+ lines.push(
186
+ '',
187
+ '> 出处:`now(getter)` = 本次调用实时读取;`ledger:<文件>@<ISO 时间>` = 该台账最后一条记录。',
188
+ '> 本报告不引用文档数字 —— 文档值不能当作实测值。',
189
+ )
96
190
 
97
191
  return lines.join('\n')
98
192
  }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * CRSI signal inbox —— 让人不在场时失败信号也不蒸发。
3
+ *
4
+ * 缺口:`AutoMemoryEngine` 的 insight 只活在**当前进程**里(`sessionReflections`),
5
+ * `/crsi propose` 读的是 `accumulatedInsights`。于是「学习」有一个隐含前提 ——
6
+ * 失败发生后、进程退出前,得有人想起来敲 `/crsi propose`。人不在,信号就没了。
7
+ *
8
+ * 本模块把这条链拆成两段:
9
+ * 1. **采集**(`appendSignals`):每轮 `persist()` 把 autoApplicable 信号同步落盘
10
+ * 到 `~/.mipham/crsi/signal-inbox.jsonl`(0600,按 category|title 幂等去重)。
11
+ * 2. **产出**(`refreshPendingLessons`):CLI 启动时把收件箱里**尚未并入**的信号
12
+ * 渲染成 `~/.mipham/crsi/pending-lessons.md`。这是一份**派生视图** ——
13
+ * 每次从「收件箱 − 已并入」重算,所以合并后会自动收缩,不需要谁去删。
14
+ *
15
+ * 边界:本模块**只产出候选**,不碰 `crsi-lessons.md` 本体。并入仍走
16
+ * `/crsi propose --pending` → 沙箱 gate → 人类批准/拒绝。自动化的只是「产出」,
17
+ * 不是「合并」—— 后者是 CRSI 的受约束自改进边界,不在这里让渡。
18
+ */
19
+
20
+ import { existsSync, mkdirSync } from 'node:fs'
21
+ import { dirname, join, parse as parsePath } from 'node:path'
22
+ import {
23
+ LESSONS_FILE,
24
+ buildLessonContent,
25
+ normalizeLessonSeverity,
26
+ type CrsiSignal,
27
+ } from './crsi-producer'
28
+ import type { CrsiInsight } from './auto-memory'
29
+ import { miphamHome } from './paths'
30
+ import { atomicWriteFileSync } from '../shared/atomic-write'
31
+ import { appendRegularFileSync, readRegularFileSync } from '../shared/regular-file'
32
+
33
+ /** 单次最多渲染多少条 —— 一次启动塞几十条教训等于把教训淹掉。 */
34
+ export const MAX_PENDING_LESSONS = 10
35
+
36
+ export function signalInboxPath(): string {
37
+ return join(miphamHome(), 'crsi', 'signal-inbox.jsonl')
38
+ }
39
+
40
+ export function pendingLessonsPath(): string {
41
+ return join(miphamHome(), 'crsi', 'pending-lessons.md')
42
+ }
43
+
44
+ function signalKey(signal: CrsiSignal): string {
45
+ return `${signal.category}::${signal.title}`
46
+ }
47
+
48
+ function lessonHeading(signal: CrsiSignal): string {
49
+ return `## ${signal.category}: ${signal.title}`
50
+ }
51
+
52
+ /** 读收件箱;坏行跳过(一行损坏不应拖垮整个收件箱)。 */
53
+ export function readSignals(path = signalInboxPath()): CrsiSignal[] {
54
+ const raw = readRegularFileSync(path)
55
+ if (!raw) return []
56
+ const out: CrsiSignal[] = []
57
+ for (const line of raw.split('\n')) {
58
+ const trimmed = line.trim()
59
+ if (!trimmed) continue
60
+ try {
61
+ const parsed = JSON.parse(trimmed) as Partial<CrsiSignal>
62
+ if (typeof parsed.category !== 'string' || typeof parsed.title !== 'string') continue
63
+ out.push({
64
+ category: parsed.category,
65
+ title: parsed.title,
66
+ severity: typeof parsed.severity === 'string' ? parsed.severity : undefined,
67
+ suggestion: typeof parsed.suggestion === 'string' ? parsed.suggestion : '',
68
+ evidence: Array.isArray(parsed.evidence)
69
+ ? parsed.evidence.filter((e): e is string => typeof e === 'string')
70
+ : [],
71
+ component: parsed.component,
72
+ })
73
+ } catch {
74
+ // 坏行:跳过
75
+ }
76
+ }
77
+ return out
78
+ }
79
+
80
+ /**
81
+ * 追加信号,按 category|title 去重;返回本次实际新增条数。
82
+ *
83
+ * 去重是**跨调用**的(与文件里已有的比),所以同一失败反复发生不会把收件箱撑爆。
84
+ */
85
+ export function appendSignals(signals: CrsiSignal[], path = signalInboxPath()): number {
86
+ if (signals.length === 0) return 0
87
+
88
+ const existing = new Set(readSignals(path).map(signalKey))
89
+ const fresh: CrsiSignal[] = []
90
+ for (const signal of signals) {
91
+ const key = signalKey(signal)
92
+ if (existing.has(key)) continue
93
+ existing.add(key)
94
+ fresh.push(signal)
95
+ }
96
+ if (fresh.length === 0) return 0
97
+
98
+ mkdirSync(dirname(path), { recursive: true })
99
+ const payload = fresh.map((s) => JSON.stringify(s)).join('\n') + '\n'
100
+ return appendRegularFileSync(path, payload, { mode: 0o600 }) ? fresh.length : 0
101
+ }
102
+
103
+ /**
104
+ * 把收件箱渲染成教训 markdown(派生视图)。
105
+ *
106
+ * `mergedLessons` 是 `crsi-lessons.md` 的现状:标题已在里面的信号不再出现。
107
+ * 返回空串表示「没有该产出的东西」—— 不是一段空壳。
108
+ */
109
+ export function pendingLessonsMarkdown(
110
+ signals: CrsiSignal[],
111
+ mergedLessons: string,
112
+ timestamp: string,
113
+ ): string {
114
+ const seen = new Set<string>()
115
+ const blocks: string[] = []
116
+ for (const signal of signals) {
117
+ const heading = lessonHeading(signal)
118
+ if (mergedLessons.includes(heading) || seen.has(heading)) continue
119
+ seen.add(heading)
120
+ blocks.push(
121
+ buildLessonContent(
122
+ signal,
123
+ timestamp,
124
+ normalizeLessonSeverity(signal.severity),
125
+ 'CRSI inbox (auto-collected)',
126
+ ),
127
+ )
128
+ if (blocks.length >= MAX_PENDING_LESSONS) break
129
+ }
130
+ return blocks.join('\n')
131
+ }
132
+
133
+ export function readPendingLessons(path = pendingLessonsPath()): string {
134
+ return readRegularFileSync(path) ?? ''
135
+ }
136
+
137
+ function writePendingLessons(content: string, path = pendingLessonsPath()): void {
138
+ mkdirSync(dirname(path), { recursive: true })
139
+ // 派生视图也走原子写:读侧把「读不动」当空,半截文件会把整份 pending 读没。
140
+ atomicWriteFileSync(path, content, { mode: 0o600 })
141
+ }
142
+
143
+ /** 从 `startDir` 向上找 `apps/cli/crsi-lessons.md`(producer 的仓库内路径)。 */
144
+ export function findLessonsFile(startDir: string): string | null {
145
+ let dir = startDir
146
+ for (;;) {
147
+ const candidate = join(dir, LESSONS_FILE)
148
+ if (existsSync(candidate)) return candidate
149
+ const parent = parsePath(dir).dir
150
+ if (parent === dir) return null
151
+ dir = parent
152
+ }
153
+ }
154
+
155
+ export interface RefreshResult {
156
+ /** 当前 pending 文件里的教训条数。 */
157
+ total: number
158
+ }
159
+
160
+ /**
161
+ * 启动时调用:从收件箱重新派生 pending 教训。
162
+ *
163
+ * 不在 mipham-code 仓库里(找不到 lessons 文件)时**什么都不写** —— 这条流水线
164
+ * 只对「能改自己教训文件」的仓库成立;用户安装里产出的 pending 无人能并入。
165
+ */
166
+ export function refreshPendingLessons(
167
+ startDir: string,
168
+ opts: { inboxPath?: string; pendingPath?: string; timestamp?: string } = {},
169
+ ): RefreshResult {
170
+ const lessonsPath = findLessonsFile(startDir)
171
+ if (!lessonsPath) return { total: 0 }
172
+
173
+ const merged = readRegularFileSync(lessonsPath) ?? ''
174
+ const content = pendingLessonsMarkdown(
175
+ readSignals(opts.inboxPath),
176
+ merged,
177
+ opts.timestamp ?? new Date().toISOString(),
178
+ )
179
+ writePendingLessons(content, opts.pendingPath)
180
+ return { total: content ? (content.match(/^## /gm)?.length ?? 0) : 0 }
181
+ }
182
+
183
+ /**
184
+ * 收件箱信号 → `/crsi propose` 能吃的 insight 形状。
185
+ *
186
+ * 这是「重启后仍能学习」那一步:`produceCrsiProposal` 只认 `CrsiInsight[]`,
187
+ * 而进程内的 `accumulatedInsights` 重启即空。
188
+ */
189
+ export function insightsToSignals(insights: CrsiInsight[]): CrsiSignal[] {
190
+ return insights.map((insight) => ({
191
+ category: insight.category,
192
+ title: insight.description,
193
+ severity: insight.severity,
194
+ suggestion: insight.suggestion,
195
+ evidence: insight.evidence,
196
+ }))
197
+ }
198
+
199
+ /**
200
+ * 按顶层 `## ` 把教训 markdown 切成块(前言/说明不混进任何一块)。
201
+ *
202
+ * pending 文件是独立写的,并入前要逐块与 `crsi-lessons.md` 比对 —— 按块比对,
203
+ * 不按整份文本比对,才能做到「只并入新的那几条」。
204
+ */
205
+ export function splitLessonBlocks(markdown: string): string[] {
206
+ const blocks: string[] = []
207
+ let current: string[] | null = null
208
+ for (const line of markdown.split('\n')) {
209
+ if (line.startsWith('## ')) {
210
+ if (current) blocks.push(current.join('\n'))
211
+ current = [line]
212
+ continue
213
+ }
214
+ if (current) current.push(line)
215
+ }
216
+ if (current) blocks.push(current.join('\n'))
217
+ return blocks
218
+ }
219
+
220
+ export function pendingToInsights(signals: CrsiSignal[]): CrsiInsight[] {
221
+ return signals.map((signal) => ({
222
+ category: signal.category,
223
+ description: signal.title,
224
+ severity:
225
+ signal.severity === 'critical' || signal.severity === 'warning' ? signal.severity : 'info',
226
+ suggestion: signal.suggestion,
227
+ evidence: signal.evidence,
228
+ autoApplicable: true,
229
+ }))
230
+ }
@@ -1587,6 +1587,10 @@ export class QueryEngine {
1587
1587
  }
1588
1588
  const effectiveParams = gateOutcome.params
1589
1589
  const hookWarnings = gateOutcome.warnings
1590
+ // The SIS pre-flight scored the signature by applying its fix; score the
1591
+ // outcome here, once the call actually runs (or throws).
1592
+ const sisFixSignature = gateOutcome.sisFixSignature
1593
+ let sisOutcomeRecorded = false
1590
1594
 
1591
1595
  // The gate at the top of this method ruled on `params`. Everything since —
1592
1596
  // the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
@@ -1657,6 +1661,14 @@ export class QueryEngine {
1657
1661
  // permit a merge. Recorded on the one funnel every tool call passes.
1658
1662
  noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
1659
1663
 
1664
+ // SIS feedback: the pre-flight applied a signature's fix, so this result is
1665
+ // that fix's outcome. Without this line `successRate` never moves and the
1666
+ // confidence gate can never open (2026-11-26).
1667
+ if (sisFixSignature) {
1668
+ this.getPreFlightChecker().recordOutcome(sisFixSignature, result.success)
1669
+ sisOutcomeRecorded = true
1670
+ }
1671
+
1660
1672
  // Prepend PreToolUse `additionalContext` to the result — on failure too.
1661
1673
  // It used to ride only on success, so a hook that warned "this command is
1662
1674
  // about to fail because X" lost its warning at exactly the moment the
@@ -1739,6 +1751,14 @@ export class QueryEngine {
1739
1751
  })
1740
1752
  }
1741
1753
 
1754
+ // The applied SIS fix was followed by a thrown error — score the failure.
1755
+ // Guarded by the flag so a throw *after* a completed run (a hook, the
1756
+ // post-flight checker) cannot retroactively fail a fix that worked.
1757
+ if (sisFixSignature && !sisOutcomeRecorded) {
1758
+ this.getPreFlightChecker().recordOutcome(sisFixSignature, false)
1759
+ sisOutcomeRecorded = true
1760
+ }
1761
+
1742
1762
  // Sanitize error: strip stack traces and internal paths to prevent
1743
1763
  // information disclosure to the LLM conversation context.
1744
1764
  const message =
@@ -41,6 +41,8 @@ export interface ErrorSignature {
41
41
  occurrences: number
42
42
  /** Number of times the fix was applied successfully */
43
43
  successCount: number
44
+ /** Number of times the fix was applied and the call still failed */
45
+ failureCount: number
44
46
  /** ISO timestamp of first encounter */
45
47
  firstSeen: string
46
48
  /** ISO timestamp of most recent encounter */
@@ -56,6 +58,12 @@ export interface ErrorSignatureStats {
56
58
  active: number
57
59
  degraded: number
58
60
  retired: number
61
+ /**
62
+ * Active signatures whose strategy applies a fix (`replace`/`prepend`/`append`).
63
+ * `avgSuccessRate` is averaged over these only — `warn`/`block` have no fix to
64
+ * succeed, and counting their 0es made every advisory look like a failed fix.
65
+ */
66
+ fixable: number
59
67
  avgSuccessRate: number
60
68
  totalInterceptions: number
61
69
  }
@@ -66,6 +74,24 @@ const DEFAULT_STORE_DIR = miphamHome('sis')
66
74
  const STORE_FILE = 'error-signatures.json'
67
75
  const MIN_SUCCESS_RATE = 0.5 // below this → degraded
68
76
  const RETIREMENT_RATE = 0.2 // below this and > 90 days old → retired
77
+ /**
78
+ * Attempts needed before an outcome can degrade a signature. One failed call is
79
+ * noise, not a verdict — degrading on it would retire a fix the first time it
80
+ * met a flaky command.
81
+ */
82
+ const MIN_ATTEMPTS_FOR_DEGRADE = 3
83
+
84
+ /** Strategies that actually apply a fix. `warn`/`block` never do. */
85
+ export function isAutoFixable(sig: Pick<ErrorSignature, 'fixStrategy'>): boolean {
86
+ return (
87
+ sig.fixStrategy === 'replace' || sig.fixStrategy === 'prepend' || sig.fixStrategy === 'append'
88
+ )
89
+ }
90
+
91
+ /** The fix-success rate, or `—` when the strategy does not apply a fix. */
92
+ export function formatFixRate(sig: ErrorSignature): string {
93
+ return isAutoFixable(sig) ? `${Math.round(sig.successRate * 100)}%` : '—'
94
+ }
69
95
  const RETENTION_DAYS = 90 // auto-clean retired signatures older than this
70
96
 
71
97
  // ── Database ──
@@ -94,6 +120,9 @@ export class ErrorSignatureDB {
94
120
  if (!Array.isArray(parsed)) return
95
121
  for (const sig of parsed) {
96
122
  if (!sig || typeof sig !== 'object' || typeof sig.id !== 'string') continue
123
+ // Stores written before 2026-11-26 have no `failureCount`; without this,
124
+ // the first `failureCount + 1` is NaN and the rate silently becomes NaN.
125
+ if (typeof sig.failureCount !== 'number') sig.failureCount = 0
97
126
  this.signatures.set(sig.id, sig)
98
127
  }
99
128
  } catch {
@@ -123,7 +152,14 @@ export class ErrorSignatureDB {
123
152
  insert(
124
153
  sig: Omit<
125
154
  ErrorSignature,
126
- 'id' | 'occurrences' | 'successCount' | 'successRate' | 'firstSeen' | 'lastSeen' | 'status'
155
+ | 'id'
156
+ | 'occurrences'
157
+ | 'successCount'
158
+ | 'failureCount'
159
+ | 'successRate'
160
+ | 'firstSeen'
161
+ | 'lastSeen'
162
+ | 'status'
127
163
  >,
128
164
  ): ErrorSignature {
129
165
  // Dedup: same pattern + toolName + category → update existing
@@ -145,7 +181,8 @@ export class ErrorSignatureDB {
145
181
  id,
146
182
  occurrences: 1,
147
183
  successCount: 0,
148
- successRate: 0, // starts at 0 — must prove itself before auto-apply
184
+ failureCount: 0,
185
+ successRate: 0,
149
186
  firstSeen: now,
150
187
  lastSeen: now,
151
188
  status: 'active',
@@ -195,24 +232,40 @@ export class ErrorSignatureDB {
195
232
 
196
233
  /**
197
234
  * Record the result of applying a fix for a given signature.
198
- * Updates success rate and may auto-degrade/retire low-performing signatures.
235
+ *
236
+ * Only signatures whose strategy actually applies a fix are scored — `warn`
237
+ * and `block` have no outcome, and counting one drove every advisory to 0%
238
+ * (2026-11-26: 10 signatures, 202 occurrences, 0 successes, while this method
239
+ * had no production caller). The denominator is **attempts**, not occurrences:
240
+ * a signature seen ten times but tried once has a rate of one trial.
199
241
  */
200
242
  recordResult(id: string, success: boolean): void {
201
243
  const sig = this.signatures.get(id)
202
244
  if (!sig) return
245
+ if (!isAutoFixable(sig)) return
203
246
 
204
- if (success) {
205
- sig.successCount++
206
- }
207
- sig.successRate = sig.occurrences > 0 ? sig.successCount / sig.occurrences : 1.0
247
+ if (success) sig.successCount++
248
+ else sig.failureCount++
249
+
250
+ const attempts = sig.successCount + sig.failureCount
251
+ sig.successRate = attempts > 0 ? sig.successCount / attempts : 0
208
252
 
209
- // Auto-degrade
210
- if (sig.successRate < MIN_SUCCESS_RATE && sig.status === 'active') {
253
+ // Auto-degrade — only after a real attempt history; one failure is noise.
254
+ if (
255
+ attempts >= MIN_ATTEMPTS_FOR_DEGRADE &&
256
+ sig.successRate < MIN_SUCCESS_RATE &&
257
+ sig.status === 'active'
258
+ ) {
211
259
  sig.status = 'degraded'
212
260
  }
213
261
  // Auto-retire
214
262
  const ageDays = (Date.now() - new Date(sig.firstSeen).getTime()) / (1000 * 60 * 60 * 24)
215
- if (sig.successRate < RETIREMENT_RATE && ageDays > 90 && sig.status === 'degraded') {
263
+ if (
264
+ attempts >= MIN_ATTEMPTS_FOR_DEGRADE &&
265
+ sig.successRate < RETIREMENT_RATE &&
266
+ ageDays > 90 &&
267
+ sig.status === 'degraded'
268
+ ) {
216
269
  sig.status = 'retired'
217
270
  }
218
271
 
@@ -251,14 +304,18 @@ export class ErrorSignatureDB {
251
304
  const degraded = all.filter((s) => s.status === 'degraded')
252
305
  const retired = all.filter((s) => s.status === 'retired')
253
306
 
307
+ const fixableActive = active.filter(isAutoFixable)
254
308
  const avgSuccessRate =
255
- active.length > 0 ? active.reduce((sum, s) => sum + s.successRate, 0) / active.length : 0
309
+ fixableActive.length > 0
310
+ ? fixableActive.reduce((sum, s) => sum + s.successRate, 0) / fixableActive.length
311
+ : 0
256
312
 
257
313
  return {
258
314
  total: all.length,
259
315
  active: active.length,
260
316
  degraded: degraded.length,
261
317
  retired: retired.length,
318
+ fixable: fixableActive.length,
262
319
  avgSuccessRate: Math.round(avgSuccessRate * 100) / 100,
263
320
  totalInterceptions: all.reduce((sum, s) => sum + s.occurrences, 0),
264
321
  }
@@ -177,14 +177,48 @@ export function appendEvalScore(
177
177
  }
178
178
  }
179
179
 
180
- /** 读取某奖励函数最近一次分数(无记录时返回 null)。旧无 name 记录自然跳过。 */
181
- export function getLastEvalScore(name: string): number | null {
180
+ /** One eval ledger line. Old records may lack counts or a timestamp. */
181
+ interface EvalLedgerLine {
182
+ name?: string
183
+ score?: number
184
+ passed?: number
185
+ total?: number
186
+ timestamp?: string
187
+ }
188
+
189
+ /** One eval ledger entry, with the timestamp that makes it citable. */
190
+ export interface LastEvalEntry {
191
+ score: number
192
+ passed: number
193
+ total: number
194
+ /** ISO timestamp, or `unknown` for records written before timestamps were kept. */
195
+ timestamp: string
196
+ }
197
+
198
+ /**
199
+ * 读取某奖励函数最近一次分数**及其时间戳**。
200
+ *
201
+ * 分数单独一个数字无法回答「什么时候测的」—— 而不可追溯的数字正是 2026-11-26
202
+ * 那次自评里被文档值冒充实测值的缺口。报告层要的是带出处的数。
203
+ */
204
+ export function getLastEvalEntry(name: string): LastEvalEntry | null {
182
205
  try {
183
206
  if (!existsSync(SCORES_FILE)) return null
184
207
  const lines = readFileSync(SCORES_FILE, 'utf-8').trim().split('\n').filter(Boolean)
185
208
  for (let i = lines.length - 1; i >= 0; i--) {
186
- const rec = JSON.parse(lines[i]!) as { name?: string; score?: number }
187
- if (rec.name === name && typeof rec.score === 'number') return rec.score
209
+ let rec: EvalLedgerLine
210
+ try {
211
+ rec = JSON.parse(lines[i]!) as EvalLedgerLine
212
+ } catch {
213
+ continue
214
+ }
215
+ if (rec.name !== name || typeof rec.score !== 'number') continue
216
+ return {
217
+ score: rec.score,
218
+ passed: typeof rec.passed === 'number' ? rec.passed : 0,
219
+ total: typeof rec.total === 'number' ? rec.total : 0,
220
+ timestamp: typeof rec.timestamp === 'string' ? rec.timestamp : 'unknown',
221
+ }
188
222
  }
189
223
  return null
190
224
  } catch {
@@ -192,6 +226,11 @@ export function getLastEvalScore(name: string): number | null {
192
226
  }
193
227
  }
194
228
 
229
+ /** 读取某奖励函数最近一次分数(无记录时返回 null)。旧无 name 记录自然跳过。 */
230
+ export function getLastEvalScore(name: string): number | null {
231
+ return getLastEvalEntry(name)?.score ?? null
232
+ }
233
+
195
234
  /**
196
235
  * 某奖励函数最近 n 次**按契约粒度**落盘的记录,新→旧。
197
236
  *
@@ -89,11 +89,11 @@ export class ImmuneMemoryGC {
89
89
  const active = this.errorDB.getActive()
90
90
 
91
91
  for (const sig of active) {
92
- if (
93
- sig.occurrences >= ZERO_SUCCESS_THRESHOLD &&
94
- sig.successCount === 0 &&
95
- sig.status === 'active'
96
- ) {
92
+ // "Never succeeded" only means something if the fix was ever *tried*.
93
+ // `warn`/`block` signatures have no fix (attempts stay 0), so retiring
94
+ // them here would delete exactly the advisories that fire most.
95
+ const attempts = sig.successCount + sig.failureCount
96
+ if (attempts >= ZERO_SUCCESS_THRESHOLD && sig.successCount === 0) {
97
97
  this.errorDB.retire(sig.id)
98
98
  count++
99
99
  }
@@ -302,6 +302,14 @@ export class MetricsRegistry {
302
302
  /** SIS immune system interceptions (block/fix of known error patterns). */
303
303
  readonly sisInterceptions: Counter
304
304
 
305
+ /**
306
+ * Bash commands blocked by the **static** security policy, labelled by rule
307
+ * class. Deliberately *not* in `COUNTER_WHITELIST`: it exists so the caller can
308
+ * tell a static-policy block from an SIS / permission block, which is local
309
+ * diagnosis, not a telemetry dimension.
310
+ */
311
+ readonly policyBlockInterceptions: Counter
312
+
305
313
  constructor() {
306
314
  // Pre-register standard metrics
307
315
  this.cliInvocations = this.counter(
@@ -348,6 +356,11 @@ export class MetricsRegistry {
348
356
  'mipham_code_sis_interceptions_total',
349
357
  'Number of SIS immune system interceptions',
350
358
  )
359
+
360
+ this.policyBlockInterceptions = this.counter(
361
+ 'mipham_code_policy_block_interceptions_total',
362
+ 'Number of Bash commands blocked by the static security policy',
363
+ )
351
364
  }
352
365
 
353
366
  // ── Factory methods ─────────────────────────────────────────────
@@ -95,6 +95,18 @@ export class PreFlightChecker {
95
95
  this.ruleEngine = ruleEngine
96
96
  }
97
97
 
98
+ /**
99
+ * Score an outcome against a signature this checker matched and fixed.
100
+ *
101
+ * The pre-flight applies `replace`/`prepend`/`append` fixes before the tool
102
+ * runs; only the caller sees whether that call succeeded, so the outcome comes
103
+ * back through here. Both tool funnels (engine and sub-agent) call it — one
104
+ * path alone would leave half the fixes unrated.
105
+ */
106
+ recordOutcome(signatureId: string, success: boolean): void {
107
+ this.errorDB.recordResult(signatureId, success)
108
+ }
109
+
98
110
  // ── Private: Signature Conversion ──
99
111
 
100
112
  /**
@@ -39,7 +39,17 @@ export interface ToolGateDeps {
39
39
 
40
40
  export type ToolGateOutcome =
41
41
  | { ok: false; content: string; error: string; notRun?: boolean }
42
- | { ok: true; params: Record<string, unknown>; warnings: string[] }
42
+ | {
43
+ ok: true
44
+ params: Record<string, unknown>
45
+ warnings: string[]
46
+ /**
47
+ * Set when the SIS pre-flight applied a signature's fix. The caller scores
48
+ * the outcome against this id after the tool runs — without it, `successRate`
49
+ * can never move and the confidence gate never opens (2026-11-26).
50
+ */
51
+ sisFixSignature?: string
52
+ }
43
53
 
44
54
  /**
45
55
  * The text a principle's `audit_pattern` is matched against.
@@ -73,6 +83,8 @@ export async function runPreToolGate(
73
83
  ): Promise<ToolGateOutcome> {
74
84
  let effectiveParams = params
75
85
  const warnings: string[] = []
86
+ /** The SIS signature whose fix was applied, if any — scored by the caller. */
87
+ let sisFixSignature: string | undefined
76
88
 
77
89
  // ── PreToolUse hook ──
78
90
  if (deps.hookEngine) {
@@ -155,6 +167,7 @@ export async function runPreToolGate(
155
167
  if (preflight.action === 'fix' && preflight.modifiedParams) {
156
168
  getMetrics().sisInterceptions.inc()
157
169
  effectiveParams = preflight.modifiedParams
170
+ sisFixSignature = preflight.matchedSignature
158
171
  if (preflight.warning) {
159
172
  warnings.push(preflight.warning)
160
173
  }
@@ -224,5 +237,10 @@ export async function runPreToolGate(
224
237
  }
225
238
  }
226
239
 
227
- return { ok: true, params: effectiveParams, warnings }
240
+ return {
241
+ ok: true,
242
+ params: effectiveParams,
243
+ warnings,
244
+ ...(sisFixSignature ? { sisFixSignature } : {}),
245
+ }
228
246
  }
@@ -593,7 +593,7 @@
593
593
  "no_sigs_for_tool": "No error signatures for tool `{tool}`. CRSI immune memory is clean for this tool.",
594
594
  "no_sigs": "No active error signatures. CRSI immune memory is clean.",
595
595
  "sigs_title": "### 🛡️ Error Signatures{tool}",
596
- "sig_success": " Success: {bar} {pct}% | {occurrences}x | {strategy}",
596
+ "sig_success": " Success: {bar} {pct} | {occurrences}x | {strategy}",
597
597
  "sig_fix": " Fix: `{fix}`",
598
598
  "sigs_more": "... and {count} more signatures",
599
599
  "reflection_title": "### 📊 CRSI Reflection Summary",
@@ -672,7 +672,7 @@
672
672
  "provider": "- **Provider**: {provider}",
673
673
  "model": "- **Model**: {model}",
674
674
  "sigs_title": "### Active Error Signatures",
675
- "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}x, {pct}% success)",
675
+ "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}x, {pct} success)",
676
676
  "disabled_hooks": "### Disabled Hooks",
677
677
  "hook_entry": "- `{key}`: {failures} failures, disabled at {time}",
678
678
  "last_dream": "### Last Auto-Dream",
@@ -593,7 +593,7 @@
593
593
  "no_sigs_for_tool": "工具 `{tool}` 没有错误签名。该工具的 CRSI 免疫记忆是干净的。",
594
594
  "no_sigs": "没有活跃的错误签名。CRSI 免疫记忆是干净的。",
595
595
  "sigs_title": "### 🛡️ 错误签名{tool}",
596
- "sig_success": " 成功率: {bar} {pct}% | {occurrences}次 | {strategy}",
596
+ "sig_success": " 成功率: {bar} {pct} | {occurrences}次 | {strategy}",
597
597
  "sig_fix": " 修复: `{fix}`",
598
598
  "sigs_more": "... 还有 {count} 条签名",
599
599
  "reflection_title": "### 📊 CRSI 反思摘要",
@@ -672,7 +672,7 @@
672
672
  "provider": "- **提供商**: {provider}",
673
673
  "model": "- **模型**: {model}",
674
674
  "sigs_title": "### 活跃错误签名",
675
- "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}次, {pct}% 成功率)",
675
+ "sig_entry": "- `{id}`: {pattern} ({category}, {occurrences}次, {pct} 成功率)",
676
676
  "disabled_hooks": "### 已禁用的 Hooks",
677
677
  "hook_entry": "- `{key}`: {failures} 次失败, 于 {time} 禁用",
678
678
  "last_dream": "### 最近一次 Auto-Dream",
package/src/index.tsx CHANGED
@@ -905,6 +905,21 @@ export async function runApp(options: RunOptions): Promise<void> {
905
905
  process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
906
906
  }
907
907
 
908
+ // CRSI 收件箱:上个会话(或更早)攒下的失败信号 → 自动渲染成待并入教训。
909
+ // 这一段不需要人在场 —— 信号在每轮 persist 时已同步落盘,这里只负责产出。
910
+ // 合并仍走 `/crsi propose --pending` → 沙箱 → 批准,自动化的是「产出」不是「合并」。
911
+ try {
912
+ const { refreshPendingLessons } = await import('./core/crsi-inbox')
913
+ const pending = refreshPendingLessons(process.cwd())
914
+ if (pending.total > 0) {
915
+ process.stderr.write(
916
+ `📚 CRSI: ${pending.total} 条教训已自动生成(/crsi propose --pending 并入)\n`,
917
+ )
918
+ }
919
+ } catch {
920
+ // 非关键路径:收件箱坏了不该影响启动
921
+ }
922
+
908
923
  // Initialize agent registry and load plugin agents/skills/MCP/hooks
909
924
  const agentRegistry = new AgentRegistry()
910
925
  if (!safeMode) {
@@ -25,12 +25,22 @@ export function recordLlm(inner: Llm): { llm: Llm; turns: RecordedTurn[] } {
25
25
 
26
26
  /** 回放已记录的 turns(确定性、无网络)。按顺序消费,超出则静默结束。 */
27
27
  export function replayLlm(turns: RecordedTurn[]): Llm {
28
+ return replayChunks(turns.map((turn) => turn.chunks))
29
+ }
30
+
31
+ /**
32
+ * 只回放响应流、不带请求。
33
+ *
34
+ * `RecordedTurn.req` 里嵌着录制时的完整系统提示(本机 cwd、指令文件内容),
35
+ * 不适合提交进仓库;而回放本就忽略请求。提交的夹具用这个形状。
36
+ */
37
+ export function replayChunks(sequences: StreamChunk[][]): Llm {
28
38
  let cursor = 0
29
39
  return {
30
40
  async *chat() {
31
- const turn = turns[cursor++]
32
- if (!turn) return
33
- for (const chunk of turn.chunks) yield chunk
41
+ const chunks = sequences[cursor++]
42
+ if (!chunks) return
43
+ for (const chunk of chunks) yield chunk
34
44
  },
35
45
  }
36
46
  }
@@ -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.49' as const
12
+ export const PACKAGE_VERSION = '0.85.50' 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 = 5332 as const
93
+ export const TEST_COUNT = 5416 as const
@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'
3
3
  import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
4
4
  import { sanitizeCommand } from '../../shared/sanitize.ts'
5
5
  import { DANGEROUS_GIT_PATTERNS } from './git.ts'
6
+ import { getMetrics } from '../../core/metrics'
6
7
  import { isUncOrDevicePath, isWithin } from '../../security/path.ts'
7
8
  import { findWorktreeMarker } from '../../core/paths.ts'
8
9
  import { splitShellSegments, expandKnownPathVars } from '../../core/permission-rules'
@@ -156,7 +157,21 @@ function normalizeEscapes(command: string): string {
156
157
  )
157
158
  }
158
159
 
159
- export function isBlocked(command: string): string | null {
160
+ type BlockReason = 'blocked-command' | 'dangerous-git' | 'unc-path' | 'blocked-pattern'
161
+
162
+ interface BlockVerdict {
163
+ reason: BlockReason
164
+ message: string
165
+ }
166
+
167
+ /**
168
+ * Classify a command against the static policy, keeping *which* rule fired.
169
+ *
170
+ * The reason is the point: a bare "rejected by security policy" is
171
+ * indistinguishable from the SIS / permission gates, so whoever reports on the
172
+ * rejection has to guess — and named the wrong subsystem on 2026-11-26.
173
+ */
174
+ function classifyBlocked(command: string): BlockVerdict | null {
160
175
  // Normalize ANSI-C escape sequences for defense-in-depth
161
176
  const normalized = normalizeEscapes(command)
162
177
  // P0-1: Also sanitize for permission check (strips invisible chars, normalizes homoglyphs)
@@ -172,7 +187,10 @@ export function isBlocked(command: string): string | null {
172
187
  ...commandWords(sanitized),
173
188
  ]) {
174
189
  if (BLOCKED_COMMANDS.includes(word)) {
175
- return `Command "${word}" rejected by security policy.`
190
+ return {
191
+ reason: 'blocked-command',
192
+ message: `Command "${word}" rejected by security policy.`,
193
+ }
176
194
  }
177
195
  }
178
196
 
@@ -184,7 +202,10 @@ export function isBlocked(command: string): string | null {
184
202
  if (/(?:^|[\s;&|])(?:sudo\s+)?git\s+/.test(normalized)) {
185
203
  for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
186
204
  if (pattern.test(normalized)) {
187
- return `Dangerous git command blocked: "${description}". Run manually if intended.`
205
+ return {
206
+ reason: 'dangerous-git',
207
+ message: `Dangerous git command blocked: "${description}". Run manually if intended.`,
208
+ }
188
209
  }
189
210
  }
190
211
  }
@@ -192,19 +213,30 @@ export function isBlocked(command: string): string | null {
192
213
  // Reject UNC / device-namespace paths — accessing one triggers SMB negotiation
193
214
  // on Windows and silently leaks NTLM credentials (Claude Code 2.1.233 CVE-class fix).
194
215
  if (isUncOrDevicePath(command) || isUncOrDevicePath(normalized) || isUncOrDevicePath(sanitized)) {
195
- return `Command rejected: references a UNC or device-namespace path (blocked to prevent NTLM credential leakage).`
216
+ return {
217
+ reason: 'unc-path',
218
+ message: `Command rejected: references a UNC or device-namespace path (blocked to prevent NTLM credential leakage).`,
219
+ }
196
220
  }
197
221
 
198
222
  // Check dangerous patterns (on original, normalized, and sanitized)
199
223
  for (const pattern of BLOCKED_PATTERNS) {
200
224
  if (pattern.test(command) || pattern.test(normalized) || pattern.test(sanitized)) {
201
- return 'Command rejected by security policy.'
225
+ return {
226
+ reason: 'blocked-pattern',
227
+ message: `Command rejected by security policy (pattern: ${pattern.source}).`,
228
+ }
202
229
  }
203
230
  }
204
231
 
205
232
  return null // safe
206
233
  }
207
234
 
235
+ /** The user-facing rejection message, or null when the command may run. */
236
+ export function isBlocked(command: string): string | null {
237
+ return classifyBlocked(command)?.message ?? null
238
+ }
239
+
208
240
  /**
209
241
  * Git commands that rewrite refs a worktree **shares with the main checkout**.
210
242
  *
@@ -890,9 +922,12 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
890
922
  }
891
923
 
892
924
  // Security: check command against deny list
893
- const blockedReason = isBlocked(command)
894
- if (blockedReason) {
895
- return { success: false, content: '', error: blockedReason }
925
+ // Counted at the enforcement point, not inside `isBlocked`: the red team and
926
+ // tests call `isBlocked` for diagnosis, and those are not real blocks.
927
+ const blocked = classifyBlocked(command)
928
+ if (blocked) {
929
+ getMetrics().policyBlockInterceptions.inc({ reason: blocked.reason })
930
+ return { success: false, content: '', error: blocked.message }
896
931
  }
897
932
 
898
933
  try {
@@ -17,7 +17,8 @@ import type { CopyPickerItem } from './copy-picker'
17
17
  import type { InstallState, UpdateStatus } from '../shared/update'
18
18
  import { McpClient } from '../mcp/client'
19
19
  import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registry'
20
- import { buildCapabilityReport } from '../core/capability-inventory'
20
+ import { buildCapabilityReport, type CapabilityLedgers } from '../core/capability-inventory'
21
+ import { formatFixRate, isAutoFixable } from '../core/error-signature-db'
21
22
  import { InstructionsLoader } from '../core/instructions'
22
23
  import { UNDISPATCHED_EVENTS } from '../core/hooks-config'
23
24
  import { findDerivableSections, DERIVABLE_HINTS } from '../core/claude-md-audit'
@@ -32,7 +33,12 @@ import {
32
33
  hasPending,
33
34
  setPendingProbation,
34
35
  } from '../core/crsi-modify'
35
- import { settleProbation, formatProbationLines, PROBATION_WINDOW } from '../core/probation'
36
+ import {
37
+ settleProbation,
38
+ formatProbationLines,
39
+ PROBATION_WINDOW,
40
+ readProbations,
41
+ } from '../core/probation'
36
42
  import {
37
43
  produceCrsiProposal,
38
44
  produceRuleProposal,
@@ -53,6 +59,13 @@ import {
53
59
  LESSONS_FILE,
54
60
  MANAGED_RULES_FILE,
55
61
  } from '../core/crsi-producer'
62
+ import {
63
+ findLessonsFile,
64
+ readPendingLessons,
65
+ readSignals,
66
+ splitLessonBlocks,
67
+ pendingToInsights,
68
+ } from '../core/crsi-inbox'
56
69
  import { prefilterProposal } from '../core/proposal-guard'
57
70
  import { integrateProposals, formatIntegrationSummary } from '../core/proposal-integration'
58
71
  import {
@@ -60,6 +73,7 @@ import {
60
73
  appendEvalScore,
61
74
  getContractHistory,
62
75
  getLastEvalScore,
76
+ getLastEvalEntry,
63
77
  diffContractHistory,
64
78
  renderContractDiff,
65
79
  } from '../core/eval-harness'
@@ -1166,7 +1180,34 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
1166
1180
  }
1167
1181
 
1168
1182
  const crsiInventoryCmd: CommandHandler = async (ctx) => {
1169
- return { content: buildCapabilityReport(ctx.engine) }
1183
+ // Ledger numbers are loaded here, not in the builder: the report stays pure,
1184
+ // and every ledger row can carry the timestamp of the record it came from.
1185
+ const ledgers: CapabilityLedgers = {}
1186
+
1187
+ const evalEntry = getLastEvalEntry('mechanism-sentinel')
1188
+ if (evalEntry) ledgers.lastEval = evalEntry
1189
+
1190
+ const improvements = readImprovements()
1191
+ if (improvements.length > 0) {
1192
+ const verdicts: Record<string, number> = {}
1193
+ for (const record of improvements) {
1194
+ verdicts[record.verdict] = (verdicts[record.verdict] ?? 0) + 1
1195
+ }
1196
+ const latest = improvements.reduce((a, b) => (a.timestamp >= b.timestamp ? a : b))
1197
+ ledgers.improvements = {
1198
+ count: improvements.length,
1199
+ verdicts,
1200
+ latestTimestamp: latest.timestamp,
1201
+ }
1202
+ }
1203
+
1204
+ const probations = readProbations()
1205
+ if (probations.length > 0) {
1206
+ const latest = probations.reduce((a, b) => (a.timestamp >= b.timestamp ? a : b))
1207
+ ledgers.probation = { count: probations.length, latestTimestamp: latest.timestamp }
1208
+ }
1209
+
1210
+ return { content: buildCapabilityReport(ctx.engine, ledgers) }
1170
1211
  }
1171
1212
 
1172
1213
  /**
@@ -1444,7 +1485,12 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1444
1485
  return { content: '⚠️ 已有待批准的修改。先 /crsi modify --approve 或 --reject。' }
1445
1486
  }
1446
1487
 
1447
- const insights = ctx.engine.getAutoMemory?.()?.accumulatedInsights ?? []
1488
+ // 本次会话的洞察 + 收件箱里的历史信号:重启后 `accumulatedInsights` 为空,
1489
+ // 但收件箱不会 —— 否则「学习」仍然要求失败与 propose 发生在同一个进程里。
1490
+ const insights = [
1491
+ ...(ctx.engine.getAutoMemory?.()?.accumulatedInsights ?? []),
1492
+ ...pendingToInsights(readSignals()),
1493
+ ]
1448
1494
  let metaRules: Parameters<typeof produceCrsiProposal>[1] = []
1449
1495
  try {
1450
1496
  metaRules = ctx.engine.getMetaRuleEngine?.()?.analyze().metaRules ?? []
@@ -1463,6 +1509,53 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1463
1509
  // 非 git 目录 → 回退 cwd
1464
1510
  }
1465
1511
 
1512
+ // ── 收件箱路径:/crsi propose --pending ──
1513
+ // 启动时 `refreshPendingLessons` 已把收件箱里尚未并入的信号渲染成 pending 文件
1514
+ // (不需要人在场)。这里只负责把它送进沙箱 gate 与人类审阅 —— 合并仍要批准。
1515
+ if (args[0] === '--pending') {
1516
+ const pendingContent = readPendingLessons()
1517
+ if (!pendingContent.trim()) {
1518
+ return { content: '没有待并入的教训 —— 收件箱为空,或它们都已并入 crsi-lessons.md。' }
1519
+ }
1520
+
1521
+ const { existsSync, readFileSync } = await import('node:fs')
1522
+ const { join } = await import('node:path')
1523
+ // `root` 来自 `git rev-parse`;那条命令在测试里被 mock、也可能在非 git 目录失败。
1524
+ // 读侧允许从 cwd 向上找 —— 而提案里的 `filePath` 仍是仓库根相对路径。
1525
+ const fromRoot = join(root, LESSONS_FILE)
1526
+ const lessonsPath = existsSync(fromRoot) ? fromRoot : findLessonsFile(process.cwd())
1527
+ if (!lessonsPath) {
1528
+ return { content: `❌ 找不到 ${LESSONS_FILE}(当前目录不是 mipham-code 仓库?)。` }
1529
+ }
1530
+ const current = readFileSync(lessonsPath, 'utf-8')
1531
+
1532
+ // 按标题逐块去重:pending 是派生视图,可能比 lessons 慢一拍(刚合并完还没重新渲染)。
1533
+ const fresh = splitLessonBlocks(pendingContent).filter(
1534
+ (block) => !current.includes(block.split('\n', 1)[0]!),
1535
+ )
1536
+ if (fresh.length === 0) {
1537
+ return { content: 'pending 里的教训都已并入 crsi-lessons.md。' }
1538
+ }
1539
+
1540
+ const result = await runCrsiModification({
1541
+ description: `CRSI inbox: ${fresh.length} 条收件箱教训`,
1542
+ filePath: LESSONS_FILE,
1543
+ originalContent: current,
1544
+ newContent: `${current.trimEnd()}\n\n${fresh.join('\n')}\n`,
1545
+ blastRadius: [LESSONS_FILE],
1546
+ })
1547
+ if (!result.applied || result.phase === 'failed') {
1548
+ return { content: `❌ 生成失败(phase: ${result.phase})。\n${result.error ?? ''}` }
1549
+ }
1550
+ return {
1551
+ content:
1552
+ `✅ 已把 ${fresh.length} 条收件箱教训送进沙箱并跑过测试。审阅 diff:\n` +
1553
+ renderGateNote(result) +
1554
+ `\n${result.diff}\n\n` +
1555
+ '/crsi modify --approve 合并 | /crsi modify --reject 丢弃',
1556
+ }
1557
+ }
1558
+
1466
1559
  // ── 散文提议路径:/crsi propose --prose 用 LLM 生成改 skill 散文提议 ──
1467
1560
  if (args[0] === '--prose') {
1468
1561
  const skillFiles = collectSkillFiles(root)
@@ -1708,7 +1801,12 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1708
1801
  current = ''
1709
1802
  }
1710
1803
 
1711
- const proposal = produceCrsiProposal(insights, metaRules, current, new Date().toISOString())
1804
+ // 已并入的教训不参与「选最佳信号」。否则最好那条(critical 优先)刚好已并入时,
1805
+ // `produceCrsiProposal` 的幂等判断会让它返回 null —— 排在后面的可学信号一起被挡。
1806
+ const freshInsights = insights.filter(
1807
+ (i) => !current.includes(`## ${i.category}: ${i.description}`),
1808
+ )
1809
+ const proposal = produceCrsiProposal(freshInsights, metaRules, current, new Date().toISOString())
1712
1810
 
1713
1811
  if (!proposal) {
1714
1812
  return { content: '没有足够的失败信号(autoApplicable insight 或高置信元规则)来生成教训。' }
@@ -2244,7 +2342,7 @@ const sisErrorsCmd: CommandHandler = (ctx) => {
2244
2342
  lines.push(`- ${statusIcon} \`${sig.id}\` [${sig.category}] ${sig.toolName}`)
2245
2343
  lines.push(` 模式: \`${sig.pattern.slice(0, 80)}${sig.pattern.length > 80 ? '...' : ''}\``)
2246
2344
  lines.push(
2247
- ` 修复: ${sig.fixStrategy} → ${sig.fixAction.slice(0, 60)} | 发生 ${sig.occurrences} 次 | 成功率 ${Math.round(sig.successRate * 100)}%`,
2345
+ ` 修复: ${sig.fixStrategy} → ${sig.fixAction.slice(0, 60)} | 发生 ${sig.occurrences} 次 | 成功率 ${formatFixRate(sig)}`,
2248
2346
  )
2249
2347
  lines.push('')
2250
2348
  }
@@ -2264,7 +2362,9 @@ const sisStatsCmd: CommandHandler = (ctx) => {
2264
2362
  lines.push(
2265
2363
  `🟢 活跃: ${stats.active} | 🟡 降级: ${stats.degraded} | ⚫ 已退役: ${stats.retired}`,
2266
2364
  )
2267
- lines.push(`平均成功率: ${Math.round(stats.avgSuccessRate * 100)}%`)
2365
+ lines.push(
2366
+ `平均成功率: ${stats.fixable > 0 ? `${Math.round(stats.avgSuccessRate * 100)}%` : '—(无可自动修复签名)'}`,
2367
+ )
2268
2368
  lines.push(`总拦截次数: ${stats.totalInterceptions}`)
2269
2369
 
2270
2370
  const active = db.getActive()
@@ -2275,9 +2375,7 @@ const sisStatsCmd: CommandHandler = (ctx) => {
2275
2375
  lines.push('|------|------|------|--------|')
2276
2376
  for (const s of active) {
2277
2377
  const icon = s.status === 'active' ? '🟢' : '🟡'
2278
- lines.push(
2279
- `| ${s.id} | ${icon} ${s.status} | ${s.occurrences} | ${Math.round(s.successRate * 100)}% |`,
2280
- )
2378
+ lines.push(`| ${s.id} | ${icon} ${s.status} | ${s.occurrences} | ${formatFixRate(s)} |`)
2281
2379
  }
2282
2380
  }
2283
2381
 
@@ -2421,14 +2519,16 @@ const crsiInterpretCmd: CommandHandler = (ctx, args) => {
2421
2519
  '',
2422
2520
  )
2423
2521
  for (const sig of sigs.slice(0, 15)) {
2424
- const bar =
2425
- '█'.repeat(Math.round(sig.successRate * 10)) +
2426
- '░'.repeat(10 - Math.round(sig.successRate * 10))
2522
+ const fixable = isAutoFixable(sig)
2523
+ const bar = fixable
2524
+ ? '█'.repeat(Math.round(sig.successRate * 10)) +
2525
+ '░'.repeat(10 - Math.round(sig.successRate * 10))
2526
+ : ''
2427
2527
  lines.push(`- **${sig.toolName}**: \`${sig.pattern.slice(0, 60)}\``)
2428
2528
  lines.push(
2429
2529
  t('commands.crsi_interpret.sig_success', {
2430
2530
  bar,
2431
- pct: String(Math.round(sig.successRate * 100)),
2531
+ pct: formatFixRate(sig),
2432
2532
  occurrences: String(sig.occurrences),
2433
2533
  strategy: sig.fixStrategy,
2434
2534
  }),
@@ -2808,7 +2908,7 @@ const bugReportCmd: CommandHandler = async (ctx) => {
2808
2908
  pattern: sig.pattern,
2809
2909
  category: sig.category,
2810
2910
  occurrences: String(sig.occurrences),
2811
- pct: (sig.successRate * 100).toFixed(0),
2911
+ pct: formatFixRate(sig),
2812
2912
  }),
2813
2913
  )
2814
2914
  }
@@ -7528,7 +7628,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7528
7628
  '/crsi inventory': 'Live capability self-report — CRSI/SIS/constitution state',
7529
7629
  '/crsi modify': 'Run a code self-modification through the sandbox (worktree → tests → approve)',
7530
7630
  '/crsi propose':
7531
- '固化 CRSI 失败信号(默认教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7631
+ '固化 CRSI 失败信号(默认教训 / --pending 收件箱自动产出的教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7532
7632
  '/crsi prose-clear': '清空散文提议去重 ledger(~/.mipham/crsi/prose-proposals.jsonl)',
7533
7633
  '/crsi eval': 'Run the ground-truth CRSI eval harness and record the score',
7534
7634
  '/crsi bench':