@miphamai/cli 0.85.49 → 0.85.51

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.51
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.51",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -666,7 +666,13 @@ export class SubAgent {
666
666
  break
667
667
  }
668
668
  if (chunk.type === 'usage') {
669
- totalTokens += (chunk.inputTokens ?? 0) + (chunk.outputTokens ?? 0)
669
+ // All four billed buckets, not just the uncached ones: a cache read is
670
+ // still this call's usage, and it is usually the largest bucket.
671
+ totalTokens +=
672
+ (chunk.inputTokens ?? 0) +
673
+ (chunk.outputTokens ?? 0) +
674
+ (chunk.cacheReadTokens ?? 0) +
675
+ (chunk.cacheWriteTokens ?? 0)
670
676
  if (options.onTokenUsage) options.onTokenUsage(totalTokens)
671
677
  }
672
678
  }
@@ -758,6 +764,10 @@ export class SubAgent {
758
764
  // credential executed verbatim one level down.
759
765
  let effectiveInput = tu.input
760
766
  let gateWarnings: string[] = []
767
+ // SIS pre-flight may have applied a signature's fix; score the outcome
768
+ // on this funnel too (the engine's recording never sees this loop).
769
+ let sisFixSignature: string | undefined
770
+ let sisOutcomeRecorded = false
761
771
  if (this.services) {
762
772
  const outcome = await runPreToolGate(tu.name, tu.input, this.services.gate, 'sub-agent')
763
773
  if (!outcome.ok) {
@@ -769,6 +779,7 @@ export class SubAgent {
769
779
  }
770
780
  effectiveInput = outcome.params
771
781
  gateWarnings = outcome.warnings
782
+ sisFixSignature = outcome.sisFixSignature
772
783
  } else if (this.hooks) {
773
784
  // Legacy path: a caller that built a SubAgent by hand with only a
774
785
  // hook engine still gets its PreToolUse hook. The other four gates
@@ -829,6 +840,11 @@ export class SubAgent {
829
840
  try {
830
841
  const result = await tool.execute(effectiveInput, toolContext)
831
842
 
843
+ if (sisFixSignature) {
844
+ this.services?.gate.preflight?.()?.recordOutcome(sisFixSignature, result.success)
845
+ sisOutcomeRecorded = true
846
+ }
847
+
832
848
  // Merge gate: a review delegated here still counts for the session
833
849
  // that will merge. This loop bypasses `Engine.executeTool`, so the
834
850
  // engine's own recording never sees this call — the same two-path
@@ -899,6 +915,13 @@ export class SubAgent {
899
915
  ],
900
916
  })
901
917
  } catch (err) {
918
+ // The applied SIS fix was followed by a thrown error — score it. The
919
+ // flag keeps a later hook throw from failing a fix that worked.
920
+ if (sisFixSignature && !sisOutcomeRecorded) {
921
+ this.services?.gate.preflight?.()?.recordOutcome(sisFixSignature, false)
922
+ sisOutcomeRecorded = true
923
+ }
924
+
902
925
  // ── P0-5: Run PostToolUseFailure hooks ──
903
926
  if (this.hooks) {
904
927
  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
+ }
@@ -838,6 +838,8 @@ export class QueryEngine {
838
838
  let truncationCause: 'max_tokens' | 'connection' | undefined
839
839
  let turnApiInputTokens = 0
840
840
  let turnApiOutputTokens = 0
841
+ let turnApiCacheReadTokens = 0
842
+ let turnApiCacheWriteTokens = 0
841
843
  const turnStart = Date.now()
842
844
  const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
843
845
 
@@ -870,6 +872,8 @@ export class QueryEngine {
870
872
  // reply twice in `/usage` and in every per-tool attribution.
871
873
  turnApiInputTokens = 0
872
874
  turnApiOutputTokens = 0
875
+ turnApiCacheReadTokens = 0
876
+ turnApiCacheWriteTokens = 0
873
877
  }
874
878
 
875
879
  if (chunk.type === 'error') {
@@ -908,6 +912,8 @@ export class QueryEngine {
908
912
  // Accumulate API-reported token counts for this turn
909
913
  turnApiInputTokens += chunk.inputTokens
910
914
  turnApiOutputTokens += chunk.outputTokens || 0
915
+ turnApiCacheReadTokens += chunk.cacheReadTokens ?? 0
916
+ turnApiCacheWriteTokens += chunk.cacheWriteTokens ?? 0
911
917
  }
912
918
 
913
919
  if (chunk.type === 'stop' && chunk.truncated) {
@@ -1065,7 +1071,12 @@ export class QueryEngine {
1065
1071
  }
1066
1072
 
1067
1073
  // Record API token usage for this turn, attributed to executed tools
1068
- if (turnApiInputTokens > 0 || turnApiOutputTokens > 0) {
1074
+ if (
1075
+ turnApiInputTokens > 0 ||
1076
+ turnApiOutputTokens > 0 ||
1077
+ turnApiCacheReadTokens > 0 ||
1078
+ turnApiCacheWriteTokens > 0
1079
+ ) {
1069
1080
  if (toolUses.length > 0) {
1070
1081
  // Attribute tokens equally across all tools invoked this turn
1071
1082
  const perTool = toolUses.length
@@ -1079,6 +1090,11 @@ export class QueryEngine {
1079
1090
  } else {
1080
1091
  this.usageTracker.recordApiUsage(turnApiInputTokens, turnApiOutputTokens, 'chat')
1081
1092
  }
1093
+ // Cache buckets are session-level: a cached prefix is shared context, not
1094
+ // a cost any single tool in this turn caused.
1095
+ if (turnApiCacheReadTokens > 0 || turnApiCacheWriteTokens > 0) {
1096
+ this.usageTracker.recordCacheUsage(turnApiCacheReadTokens, turnApiCacheWriteTokens)
1097
+ }
1082
1098
  } else {
1083
1099
  // Fallback: API doesn't report usage — use char-based estimate
1084
1100
  const estimated = Math.round((assistantContent.length + userInput.length) / 4)
@@ -1587,6 +1603,10 @@ export class QueryEngine {
1587
1603
  }
1588
1604
  const effectiveParams = gateOutcome.params
1589
1605
  const hookWarnings = gateOutcome.warnings
1606
+ // The SIS pre-flight scored the signature by applying its fix; score the
1607
+ // outcome here, once the call actually runs (or throws).
1608
+ const sisFixSignature = gateOutcome.sisFixSignature
1609
+ let sisOutcomeRecorded = false
1590
1610
 
1591
1611
  // The gate at the top of this method ruled on `params`. Everything since —
1592
1612
  // the PreToolUse hook's `modifiedInput`, the CRSI RuleEngine's `modified`, the
@@ -1657,6 +1677,14 @@ export class QueryEngine {
1657
1677
  // permit a merge. Recorded on the one funnel every tool call passes.
1658
1678
  noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
1659
1679
 
1680
+ // SIS feedback: the pre-flight applied a signature's fix, so this result is
1681
+ // that fix's outcome. Without this line `successRate` never moves and the
1682
+ // confidence gate can never open (2026-11-26).
1683
+ if (sisFixSignature) {
1684
+ this.getPreFlightChecker().recordOutcome(sisFixSignature, result.success)
1685
+ sisOutcomeRecorded = true
1686
+ }
1687
+
1660
1688
  // Prepend PreToolUse `additionalContext` to the result — on failure too.
1661
1689
  // It used to ride only on success, so a hook that warned "this command is
1662
1690
  // about to fail because X" lost its warning at exactly the moment the
@@ -1739,6 +1767,14 @@ export class QueryEngine {
1739
1767
  })
1740
1768
  }
1741
1769
 
1770
+ // The applied SIS fix was followed by a thrown error — score the failure.
1771
+ // Guarded by the flag so a throw *after* a completed run (a hook, the
1772
+ // post-flight checker) cannot retroactively fail a fix that worked.
1773
+ if (sisFixSignature && !sisOutcomeRecorded) {
1774
+ this.getPreFlightChecker().recordOutcome(sisFixSignature, false)
1775
+ sisOutcomeRecorded = true
1776
+ }
1777
+
1742
1778
  // Sanitize error: strip stack traces and internal paths to prevent
1743
1779
  // information disclosure to the LLM conversation context.
1744
1780
  const message =