@miphamai/cli 0.85.37 → 0.85.39

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.37
1
+ # Mipham Code v0.85.39
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 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.37",
3
+ "version": "0.85.39",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -8,6 +8,23 @@ version: 2.0.0
8
8
 
9
9
  Analyzes code changes for bugs, security risks, performance issues, and code quality. Generates structured review reports.
10
10
 
11
+ ## Scope (what `/code-review` reports)
12
+
13
+ `/code-review` reports **two things only**: defects (correctness, security) and
14
+ CLAUDE.md violations. Reuse, simplification, efficiency, architecture and
15
+ test-coverage cleanups belong to `/simplify` (`self-review` skill) — reporting
16
+ them here dilutes the one question the review is answering.
17
+
18
+ Every finding carries exactly one **attribution severity**:
19
+
20
+ - `important` — this change introduced or worsened it
21
+ - `pre_existing` — it was already there before this change
22
+ - `nit` — minor
23
+
24
+ Attribution is not risk ranking: the reader first needs to know whether they
25
+ broke it this time. End the summary with one suggested fix. When there is
26
+ nothing to report, say exactly: `Code review found no issues.`
27
+
11
28
  ## Review Dimensions
12
29
 
13
30
  ### 1. Correctness (Bug Detection)
@@ -66,17 +66,27 @@ You are a research agent. Your task:
66
66
  2. For every claim, follow it back to the source that owns it.
67
67
  If a secondary source makes a claim, find the primary source and cite that.
68
68
 
69
- 3. Use WebSearch to find sources.
69
+ 3. Before external search, scan the local repo and sibling project directories
70
+ for prior work. Open and read the relevant files — a glob hit is not a read.
71
+ Record what you found; if there is none, say "none" explicitly.
72
+
73
+ 4. A number, "unconditional", "record", or "first" is a claim about a theorem
74
+ under its stated assumptions, not about the numeral. Open the source's theorem
75
+ statement (not the abstract), copy the assumption it depends on, and pair the
76
+ value with that assumption wherever you write it. If the same value has several
77
+ provenances, say which one you mean.
78
+
79
+ 5. Use WebSearch to find sources.
70
80
  Use WebFetch to deep-read promising pages.
71
81
  Cross-reference critical claims across 2+ independent primary sources.
72
82
 
73
- 4. Write findings to a SINGLE Markdown file.
83
+ 6. Write findings to a SINGLE Markdown file.
74
84
  - Cite every claim with its primary source URL
75
85
  - Distinguish between facts (needs citation) and reasoning (your own)
76
86
  - Flag outdated content ("article from 2024, may be stale")
77
87
  - Note if a source is official docs vs community
78
88
 
79
- 5. Save the file where the repo already keeps such notes.
89
+ 7. Save the file where the repo already keeps such notes.
80
90
  Match existing conventions. If none exist, put it in docs/research/.
81
91
  ```
82
92
 
@@ -17,8 +17,12 @@ import { CrsiSandbox, validateBlastRadius, validateMergeConvergence } from './cr
17
17
  import type { CrsiModificationResult } from './crsi-sandbox'
18
18
  import {
19
19
  appendEvalScore,
20
+ getContractHistory,
20
21
  getLastEvalScore,
21
22
  instrumentFailure,
23
+ directionalRegret,
24
+ softHurtGate,
25
+ formatRegretNote,
22
26
  regressedAnchors,
23
27
  } from './eval-harness'
24
28
  import { mechanismSentinel, type RewardFn, type ScoreReport } from './reward-fn'
@@ -181,12 +185,43 @@ export async function runCrsiModification(
181
185
  applied.error = `Anchor regression: ${anchors.join(', ')}`
182
186
  return applied
183
187
  }
184
- const last = getLastEvalScore(rewardFn.name)
185
- if (last !== null && report.score < last) {
186
- sandbox.rollback()
187
- applied.phase = 'failed'
188
- applied.error = `Reward regression (${rewardFn.name}): score ${report.score} < last ${last}`
189
- return applied
188
+ // 第二道闸(GUARD,2611.23476):有逐契约历史时看**方向性 regret** ——
189
+ // 收益必须超过回归;没有历史(首跑)或契约集合变了(新增/移除)时方向性比较
190
+ // 不成立,退回标量分数闸(分母变了,分数不可比)。
191
+ const history = getContractHistory(rewardFn.name, 1)
192
+ const comparable =
193
+ report.results !== undefined && history.length > 0
194
+ ? directionalRegret(report.results, history)
195
+ : null
196
+ const setChanged =
197
+ comparable !== null && (comparable.newContracts.length > 0 || comparable.gone.length > 0)
198
+
199
+ if (comparable && !setChanged) {
200
+ const gate = softHurtGate(comparable)
201
+ if (!gate.pass) {
202
+ sandbox.rollback()
203
+ applied.phase = 'failed'
204
+ applied.error = `Directional regret gate (${rewardFn.name}): ${gate.reason}`
205
+ return applied
206
+ }
207
+ // 过闸也要让人看见两侧的数:修好 3 条、弄坏 1 条是**放行**,但读者有权知道
208
+ // 那 1 条是什么这次弄坏的。两侧全零(或只有抖动)不占一行。
209
+ if (
210
+ comparable.newlyBroken.length +
211
+ comparable.newlyFixed.length +
212
+ comparable.stillFailing.length >
213
+ 0
214
+ ) {
215
+ applied.regretNote = formatRegretNote(comparable)
216
+ }
217
+ } else {
218
+ const last = getLastEvalScore(rewardFn.name)
219
+ if (last !== null && report.score < last) {
220
+ sandbox.rollback()
221
+ applied.phase = 'failed'
222
+ applied.error = `Reward regression (${rewardFn.name}): score ${report.score} < last ${last}`
223
+ return applied
224
+ }
190
225
  }
191
226
  appendEvalScore(rewardFn.name, report)
192
227
 
@@ -70,6 +70,11 @@ export interface CrsiModificationResult {
70
70
  * 不静默跳过 —— 沉默与「anchor 全绿」在外部读数上同形。
71
71
  */
72
72
  rewardNote?: string
73
+ /**
74
+ * 方向性 regret 的可见读数(GUARD 闸):新破坏 / 新修复 / 仍未解决。
75
+ * 过闸但两侧有数时必须出现 —— 否则「这次改动弄坏了什么」只有一个看不见的内部值。
76
+ */
77
+ regretNote?: string
73
78
  /** Current phase of the sandbox pipeline */
74
79
  phase:
75
80
  'pending' | 'applied' | 'testing' | 'passed' | 'failed' | 'approved' | 'merged' | 'rolled-back'
@@ -854,6 +854,12 @@ export class QueryEngine {
854
854
  reasoningContent = ''
855
855
  thinkingContent = ''
856
856
  toolUses.length = 0
857
+ // Usage is part of "everything": a provider reports tokens as the
858
+ // stream runs, so the attempt that failed had already added its
859
+ // share before `restart` arrived. Keeping it charges the retried
860
+ // reply twice in `/usage` and in every per-tool attribution.
861
+ turnApiInputTokens = 0
862
+ turnApiOutputTokens = 0
857
863
  }
858
864
 
859
865
  if (chunk.type === 'error') {
@@ -265,6 +265,112 @@ export function diffContractHistory(
265
265
  return out
266
266
  }
267
267
 
268
+ /**
269
+ * 方向性 regret(GUARD,2611.23476):把一次评估拆成「本次新弄坏的」与
270
+ * 「本来就有的缺口」,而不是揉成一个总分。
271
+ *
272
+ * 为什么需要它:标量分数把「新破坏」与「仍未解决」混在一起 —— 一个修好 1 条、
273
+ * 弄坏 1 条的改动与什么都没做的改动同分。GUARD 的判据是**收益必须超过回归**,
274
+ * 故两侧必须分开计数。抖动契约(历史里 true/false 都出现过)不计入任何一侧:
275
+ * 拿一次抖动的翻转当「新破坏」会误拦,当「新修复」会假放。
276
+ */
277
+ export interface DirectionalRegret {
278
+ /** 上次 PASS、本次 FAIL —— 本次改动新弄坏的(不含抖动)。 */
279
+ newlyBroken: string[]
280
+ /** 上次 FAIL、本次仍 FAIL —— 本来就有的缺口,不是本次的账。 */
281
+ stillFailing: string[]
282
+ /** 上次 FAIL、本次 PASS。 */
283
+ newlyFixed: string[]
284
+ /** 近几次 true/false 都出现过 —— 抖动,不计入任何一侧。 */
285
+ flaky: string[]
286
+ /** 历史里没出现过(新增契约)。 */
287
+ newContracts: string[]
288
+ /** 历史有、本次没有(契约被移出)。 */
289
+ gone: string[]
290
+ /** newlyBroken 中 role==='anchor' 的子集(硬闸)。 */
291
+ anchorBroken: string[]
292
+ }
293
+
294
+ export function directionalRegret(
295
+ current: ContractResultRecord[],
296
+ history: ContractSnapshot[],
297
+ ): DirectionalRegret {
298
+ const delta: DirectionalRegret = {
299
+ newlyBroken: [],
300
+ stillFailing: [],
301
+ newlyFixed: [],
302
+ flaky: [],
303
+ newContracts: [],
304
+ gone: [],
305
+ anchorBroken: [],
306
+ }
307
+ const seen = new Set<string>()
308
+ for (const c of current) {
309
+ seen.add(c.id)
310
+ const past = history.filter((h) => c.id in h).map((h) => h[c.id] === true)
311
+ if (past.length === 0) {
312
+ delta.newContracts.push(c.id)
313
+ continue
314
+ }
315
+ if (past.includes(true) && past.includes(false)) {
316
+ delta.flaky.push(c.id)
317
+ continue
318
+ }
319
+ const wasPassing = past[0] === true
320
+ if (wasPassing && !c.passed) {
321
+ delta.newlyBroken.push(c.id)
322
+ if (c.role === 'anchor') delta.anchorBroken.push(c.id)
323
+ } else if (!wasPassing && c.passed) {
324
+ delta.newlyFixed.push(c.id)
325
+ } else if (!c.passed) {
326
+ delta.stillFailing.push(c.id)
327
+ }
328
+ }
329
+ for (const h of history) {
330
+ for (const id of Object.keys(h)) {
331
+ if (seen.has(id)) continue
332
+ seen.add(id)
333
+ delta.gone.push(id)
334
+ }
335
+ }
336
+ return delta
337
+ }
338
+
339
+ export interface SoftHurtVerdict {
340
+ pass: boolean
341
+ reason?: string
342
+ }
343
+
344
+ /**
345
+ * Soft-HURT 门:**收益必须超过回归**才算通过。
346
+ *
347
+ * - anchor 新破坏 ⇒ 直接拒(安全/机制不变量没有「以多换少」的余地);
348
+ * - 新增破坏 ≥ 新增修复 ⇒ 拒。等号也拒:修好一条、弄坏一条**不是**改进,
349
+ * 只是把工作挪了个位置;标量分数在这一格恰好同分,所以它看不见。
350
+ *
351
+ * `stillFailing` 不进判据 —— 它本来就是失败,不是这次改动造成的。
352
+ */
353
+ export function softHurtGate(delta: DirectionalRegret): SoftHurtVerdict {
354
+ if (delta.anchorBroken.length > 0) {
355
+ return { pass: false, reason: `anchor 契约回退: ${delta.anchorBroken.join(', ')}` }
356
+ }
357
+ if (delta.newlyBroken.length > 0 && delta.newlyBroken.length >= delta.newlyFixed.length) {
358
+ return {
359
+ pass: false,
360
+ reason:
361
+ `新破坏 ${delta.newlyBroken.length} 条 ≥ 新修复 ${delta.newlyFixed.length} 条` +
362
+ `(收益未超过回归:${delta.newlyBroken.join(', ')})`,
363
+ }
364
+ }
365
+ return { pass: true }
366
+ }
367
+
368
+ /** 方向性 regret 的一行读数(只描述,不判定)。 */
369
+ export function formatRegretNote(delta: DirectionalRegret): string {
370
+ const flaky = delta.flaky.length > 0 ? ` · 抖动 ${delta.flaky.length}(不计)` : ''
371
+ return `新破坏 ${delta.newlyBroken.length} · 新修复 ${delta.newlyFixed.length} · 仍未解决 ${delta.stillFailing.length}${flaky}`
372
+ }
373
+
268
374
  /**
269
375
  * 把 diffContractHistory 的结果渲染成展示行。纯函数——不做 I/O、不读时钟。
270
376
  * 返回空数组表示「无变化」,调用方据此决定是否打印标题。
@@ -40,6 +40,20 @@ export interface ImprovementReport {
40
40
  nullModelTotal?: number
41
41
  /** 闸的结论:failed = 有题空程序也能过 ⇒ `improved` 不可归因。 */
42
42
  nullModelGate?: 'passed' | 'failed'
43
+ /**
44
+ * SIM(Self-Improvement Memory):这条编辑针对的**复发问题**分组键。
45
+ * 同一 harness 问题被反复修时,记录才能按问题聚在一起,而不是按时间摊平。
46
+ * 缺席 = 旧记录 / 该调用点没有失败信号。
47
+ */
48
+ problemKey?: string
49
+ /** SIM:为什么做这次编辑(人可读的一句)。缺席语义同 problemKey。 */
50
+ rationale?: string
51
+ /**
52
+ * RSI Tax:与分数数组逐项对齐的前/后测量 token。**只记录,不进任何门禁**
53
+ * (与耗时维同一条纪律)。两个数组同生同灭;缺席 = 未测,不是免费。
54
+ */
55
+ baselineTokens?: number[]
56
+ postTokens?: number[]
43
57
  }
44
58
 
45
59
  export interface ImprovementRecord extends ImprovementReport {
@@ -70,10 +84,16 @@ function stdDev(xs: number[]): number {
70
84
  return Math.sqrt(variance)
71
85
  }
72
86
 
87
+ export interface ImprovementContext {
88
+ problemKey?: string
89
+ rationale?: string
90
+ }
91
+
73
92
  export function buildImprovementReport(
74
93
  sample: SkillDeltaSample,
75
94
  changeSet: string[],
76
95
  predicted?: number,
96
+ context?: ImprovementContext,
77
97
  ): ImprovementReport {
78
98
  const deltaMean = mean(sample.postScores) - mean(sample.baselineScores)
79
99
  const noise = stdDev(sample.baselineScores)
@@ -123,7 +143,78 @@ export function buildImprovementReport(
123
143
  nullModelGate,
124
144
  }
125
145
  : {}),
146
+ // SIM 两键各自独立:有理由而没有分组键(或反过来)都是有意义的状态,
147
+ // 强行绑定只会让调用方为了写一个而编另一个。
148
+ ...(context?.problemKey ? { problemKey: context.problemKey } : {}),
149
+ ...(context?.rationale ? { rationale: context.rationale } : {}),
150
+ // RSI Tax 与耗时维同一纪律:两条同生同灭,缺席即未测。
151
+ ...(sample.baselineTokens !== undefined && sample.postTokens !== undefined
152
+ ? { baselineTokens: sample.baselineTokens, postTokens: sample.postTokens }
153
+ : {}),
154
+ }
155
+ }
156
+
157
+ /** 问题分组键的规范化:去空白/大小写差异,截断到 120 字符(防止把整段散文当键)。 */
158
+ export function normalizeProblemKey(text: string): string {
159
+ return text.trim().toLowerCase().replace(/\s+/g, ' ').slice(0, 120)
160
+ }
161
+
162
+ export interface ProblemGroup {
163
+ key: string
164
+ total: number
165
+ improved: number
166
+ meanDelta: number
167
+ }
168
+
169
+ /**
170
+ * 按 `problemKey` 聚合台账(SIM 的读侧)。没有分组键的旧记录不进入任何组,
171
+ * 它们仍在总台账里 —— 分组是视图,不是过滤器。
172
+ */
173
+ export function groupImprovementsByProblem(records: ImprovementRecord[]): ProblemGroup[] {
174
+ const groups = new Map<string, ImprovementRecord[]>()
175
+ for (const r of records) {
176
+ if (!r.problemKey) continue
177
+ const bucket = groups.get(r.problemKey) ?? []
178
+ bucket.push(r)
179
+ groups.set(r.problemKey, bucket)
126
180
  }
181
+ return [...groups.entries()]
182
+ .map(([key, rs]) => ({
183
+ key,
184
+ total: rs.length,
185
+ improved: rs.filter((r) => r.verdict === 'improved').length,
186
+ meanDelta: mean(rs.map((r) => r.deltaMean)),
187
+ }))
188
+ .sort((a, b) => b.total - a.total || a.key.localeCompare(b.key))
189
+ }
190
+
191
+ /** RSI Tax 的台账汇总:只统计带 token 量的记录。 */
192
+ export function measurementTaxSummary(records: ImprovementRecord[]): {
193
+ records: number
194
+ totalTokens: number
195
+ meanTokens: number
196
+ } {
197
+ const measured = records.filter(
198
+ (r) => r.baselineTokens !== undefined && r.postTokens !== undefined,
199
+ )
200
+ const totalTokens = measured.reduce(
201
+ (sum, r) => sum + [...r.baselineTokens!, ...r.postTokens!].reduce((a, b) => a + b, 0),
202
+ 0,
203
+ )
204
+ return {
205
+ records: measured.length,
206
+ totalTokens,
207
+ meanTokens: measured.length > 0 ? Math.round(totalTokens / measured.length) : 0,
208
+ }
209
+ }
210
+
211
+ /** RSI Tax 的只读展示;缺席 → null(调用方整行不打印)。 */
212
+ export function formatRsiTaxLine(report: ImprovementReport): string | null {
213
+ const { baselineTokens: before_, postTokens: after_ } = report
214
+ if (before_ === undefined || after_ === undefined) return null
215
+ const before = before_.reduce((a, b) => a + b, 0)
216
+ const after = after_.reduce((a, b) => a + b, 0)
217
+ return `💸 验证 token(RSI Tax): 前 ${before.toLocaleString()} → 后 ${after.toLocaleString()}(合计 ${(before + after).toLocaleString()})`
127
218
  }
128
219
 
129
220
  /** 空模型闸失败时给出一行可见读数;闸通过则不出声(不占显示行)。 */
@@ -0,0 +1,149 @@
1
+ /**
2
+ * ELITE(2611.21056)的整合算子:多提案 → 一个兼容后代。
3
+ *
4
+ * 论文的观察是:直接「选一个探索出的孩子继续」会丢掉其它孩子里的互补机制。
5
+ * 它改为从**同一父本**并行提出多个聚焦改进,检查它们互补 / 冗余 / 冲突,
6
+ * 再把**兼容子集**重新实现为一个连贯的后代。
7
+ *
8
+ * 本模块只做确定性部分:以 `originalContent` 为共同父本做 3-way merge
9
+ * (`git merge-file -p`,不调 LLM、不判定好坏)。
10
+ * - 能干净合并 ⇒ 互补,收进后代;
11
+ * - 与已有提案字节相同 ⇒ 冗余,只留一份;
12
+ * - 改同一段且内容不同 ⇒ 冲突,**单列并默认拒绝**(不静默丢弃机制)。
13
+ *
14
+ * 冲突默认 fail-closed:`--drop-conflicts` 是调用方显式选择「只整合兼容子集」,
15
+ * 与论文的 compatible subset 对应;没有这个开关时,丢掉一个机制必须是人的决定。
16
+ */
17
+
18
+ import { execFileSync } from 'node:child_process'
19
+ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
20
+ import { tmpdir } from 'node:os'
21
+ import { join } from 'node:path'
22
+
23
+ export interface IntegrationProposal {
24
+ /** 展示名(通常是提案文件路径)。 */
25
+ name: string
26
+ /** 该提案给出的**完整文件内容**(与 `runCrsiModification` 同一形状)。 */
27
+ content: string
28
+ }
29
+
30
+ export interface IntegrationConflict {
31
+ name: string
32
+ /** `git merge-file` 报告的冲突块数。 */
33
+ conflictCount: number
34
+ }
35
+
36
+ export interface IntegrationResult {
37
+ /** 无冲突且至少合并了一个提案。 */
38
+ ok: boolean
39
+ /** 兼容子集的合并结果;一个都没合并成时为 null。 */
40
+ content: string | null
41
+ /** 成功合并的提案名(按输入顺序)。 */
42
+ merged: string[]
43
+ /** 与父本或先前提案字节相同的提案名(保留第一份)。 */
44
+ redundant: string[]
45
+ /** 与已合并内容改同一段的提案。 */
46
+ conflicts: IntegrationConflict[]
47
+ /** 环境/参数错误(与「提案冲突」区分:那是提案的属性,这是没能比较)。 */
48
+ error?: string
49
+ }
50
+
51
+ /** `git merge-file -p` 的退出码 = 冲突块数;0 = 干净合并。 */
52
+ function mergeFile(
53
+ currentPath: string,
54
+ basePath: string,
55
+ otherPath: string,
56
+ ): { merged: true; output: string } | { merged: false; conflictCount: number } {
57
+ try {
58
+ return {
59
+ merged: true,
60
+ output: execFileSync('git', ['merge-file', '-p', currentPath, basePath, otherPath], {
61
+ encoding: 'utf-8',
62
+ stdio: ['ignore', 'pipe', 'pipe'],
63
+ }),
64
+ }
65
+ } catch (err) {
66
+ const status = (err as { status?: unknown }).status
67
+ // 正整数 = 冲突块数(git 的契约),不是「命令坏了」。
68
+ if (typeof status === 'number' && status > 0) {
69
+ return { merged: false, conflictCount: status }
70
+ }
71
+ throw err
72
+ }
73
+ }
74
+
75
+ export function integrateProposals(
76
+ originalContent: string,
77
+ proposals: IntegrationProposal[],
78
+ ): IntegrationResult {
79
+ const base: IntegrationResult = {
80
+ ok: false,
81
+ content: null,
82
+ merged: [],
83
+ redundant: [],
84
+ conflicts: [],
85
+ }
86
+ if (proposals.length < 2) {
87
+ return { ...base, error: '至少需要两个提案才能整合' }
88
+ }
89
+
90
+ const dir = mkdtempSync(join(tmpdir(), 'mipham-crsi-integrate-'))
91
+ try {
92
+ const basePath = join(dir, 'base.txt')
93
+ const currentPath = join(dir, 'current.txt')
94
+ writeFileSync(basePath, originalContent)
95
+ writeFileSync(currentPath, originalContent)
96
+ let current = originalContent
97
+ const seen = new Set<string>([originalContent])
98
+ const merged: string[] = []
99
+ const redundant: string[] = []
100
+ const conflicts: IntegrationConflict[] = []
101
+
102
+ proposals.forEach((proposal, index) => {
103
+ if (seen.has(proposal.content)) {
104
+ // 与父本相同(没改)或与先前提案相同(同一机制说了两遍)——只留一份。
105
+ redundant.push(proposal.name)
106
+ return
107
+ }
108
+ seen.add(proposal.content)
109
+ const otherPath = join(dir, `proposal-${index}.txt`)
110
+ writeFileSync(otherPath, proposal.content)
111
+ let outcome: ReturnType<typeof mergeFile>
112
+ try {
113
+ outcome = mergeFile(currentPath, basePath, otherPath)
114
+ } catch (err) {
115
+ // git 不可用/不可执行:与「提案冲突」不同类,必须报出来而不是读成冲突。
116
+ throw new Error(
117
+ `整合需要 git merge-file,但它没能运行:${err instanceof Error ? err.message : String(err)}`,
118
+ )
119
+ }
120
+ if (!outcome.merged) {
121
+ conflicts.push({ name: proposal.name, conflictCount: outcome.conflictCount })
122
+ return
123
+ }
124
+ current = outcome.output
125
+ writeFileSync(currentPath, current)
126
+ merged.push(proposal.name)
127
+ })
128
+
129
+ return {
130
+ ok: conflicts.length === 0 && merged.length > 0,
131
+ content: merged.length > 0 ? current : null,
132
+ merged,
133
+ redundant,
134
+ conflicts,
135
+ }
136
+ } catch (err) {
137
+ return { ...base, error: err instanceof Error ? err.message : String(err) }
138
+ } finally {
139
+ rmSync(dir, { recursive: true, force: true })
140
+ }
141
+ }
142
+
143
+ /** 整合摘要的一行读数(只描述,不判定)。 */
144
+ export function formatIntegrationSummary(result: IntegrationResult): string {
145
+ const parts = [`兼容 ${result.merged.length}`]
146
+ if (result.redundant.length > 0) parts.push(`冗余 ${result.redundant.length}(只留一份)`)
147
+ if (result.conflicts.length > 0) parts.push(`冲突 ${result.conflicts.length}`)
148
+ return parts.join(' · ')
149
+ }
@@ -111,6 +111,12 @@ export interface TaskPerformanceReport {
111
111
  truncated: number
112
112
  /** B2 代价维:整轮(LLM 生成 + 冻结测试判定)的墙钟耗时。只记录,不参与任何判定。 */
113
113
  durationMs: number
114
+ /**
115
+ * RSI Tax:本轮测量烧掉的 token(provider 报的 usage 之和)。
116
+ * 缺席 = provider 一次 usage 都没报(与「报了 0」区分)—— 缺席按「未测」处理,
117
+ * 不得当成免费。只记录,不参与任何判定。
118
+ */
119
+ tokensUsed?: number
114
120
  }
115
121
 
116
122
  /** 剥掉 LLM 可能包裹的 markdown 代码块(```ts ... ```),拿到裸代码。 */
@@ -123,9 +129,11 @@ async function collectGeneratedCode(
123
129
  llm: Llm,
124
130
  prompt: string,
125
131
  systemPrompt?: string,
126
- ): Promise<{ code: string; truncated: boolean }> {
132
+ ): Promise<{ code: string; truncated: boolean; tokens: number; usageReported: boolean }> {
127
133
  let text = ''
128
134
  let truncated = false
135
+ let tokens = 0
136
+ let usageReported = false
129
137
  const req = {
130
138
  model: '', // falsy → registry 回退到 active model
131
139
  messages: [{ role: 'user' as const, content: prompt }],
@@ -134,11 +142,17 @@ async function collectGeneratedCode(
134
142
  }
135
143
  for await (const chunk of llm.chat(req)) {
136
144
  if (chunk.type === 'text' && chunk.content) text += chunk.content
145
+ // 验证成本(RSI Tax):provider 在流中报的 usage 就是这次测量烧掉的 token。
146
+ // `usageReported` 与数值分开:报 0 和「没报」不是同一件事,0 会被读成免费。
147
+ if (chunk.type === 'usage') {
148
+ usageReported = true
149
+ tokens += (chunk.inputTokens ?? 0) + (chunk.outputTokens ?? 0)
150
+ }
137
151
  // Both providers already emit `truncated` on the stop chunk; reading it here is
138
152
  // what turns the signal into something the score can act on.
139
153
  if (chunk.truncated) truncated = true
140
154
  }
141
- return { code: stripCodeFences(text), truncated }
155
+ return { code: stripCodeFences(text), truncated, tokens, usageReported }
142
156
  }
143
157
 
144
158
  export async function runTaskPerformance(
@@ -149,8 +163,16 @@ export async function runTaskPerformance(
149
163
  const tasks = loadPerformanceTasks().filter((t) => (t.skill ?? undefined) === wanted)
150
164
  const results: TaskPerformanceResult[] = []
151
165
  const startedAt = Date.now()
166
+ let tokensUsed = 0
167
+ let anyUsageReported = false
152
168
  for (const task of tasks) {
153
- const { code, truncated } = await collectGeneratedCode(llm, task.prompt, opts?.skill?.text)
169
+ const { code, truncated, tokens, usageReported } = await collectGeneratedCode(
170
+ llm,
171
+ task.prompt,
172
+ opts?.skill?.text,
173
+ )
174
+ tokensUsed += tokens
175
+ anyUsageReported = anyUsageReported || usageReported
154
176
  if (!code) {
155
177
  results.push({
156
178
  id: task.id,
@@ -188,6 +210,7 @@ export async function runTaskPerformance(
188
210
  failures: results.filter((r) => !r.passed).map((r) => r.id),
189
211
  truncated,
190
212
  durationMs: Date.now() - startedAt,
213
+ ...(anyUsageReported ? { tokensUsed } : {}),
191
214
  }
192
215
  }
193
216
 
@@ -285,6 +308,13 @@ export interface SkillDeltaSample {
285
308
  */
286
309
  baselineDurations?: number[]
287
310
  postDurations?: number[]
311
+ /**
312
+ * RSI Tax:与分数数组逐项对齐的 token 用量(第 i 项 = 产出第 i 个分数那次测量的消耗)。
313
+ * **两个数组同生同灭**;且只有 k 次采样**全部**报了 usage 才出现 —— 少数几次没报时
314
+ * 补齐 0 会把「没测」写成「免费」,宁可整维缺席。
315
+ */
316
+ baselineTokens?: number[]
317
+ postTokens?: number[]
288
318
  }
289
319
 
290
320
  /**
@@ -304,12 +334,15 @@ export async function measureSkillDeltaRepeated(
304
334
  const postScores: number[] = []
305
335
  const baselineDurations: number[] = []
306
336
  const postDurations: number[] = []
337
+ const baselineTokens: number[] = []
338
+ const postTokens: number[] = []
307
339
  for (let i = 0; i < k; i++) {
308
340
  const r = await runTaskPerformance(llm, {
309
341
  skill: { name: resolved.skillName, text: resolved.baselineText },
310
342
  })
311
343
  baselineScores.push(r.score)
312
344
  baselineDurations.push(r.durationMs)
345
+ if (r.tokensUsed !== undefined) baselineTokens.push(r.tokensUsed)
313
346
  }
314
347
  for (let i = 0; i < k; i++) {
315
348
  const r = await runTaskPerformance(llm, {
@@ -317,6 +350,7 @@ export async function measureSkillDeltaRepeated(
317
350
  })
318
351
  postScores.push(r.score)
319
352
  postDurations.push(r.durationMs)
353
+ if (r.tokensUsed !== undefined) postTokens.push(r.tokensUsed)
320
354
  }
321
355
 
322
356
  // 空模型闸在最后一次采样后算一次:与模型无关,重复跑只是重复同一组测试。
@@ -328,6 +362,10 @@ export async function measureSkillDeltaRepeated(
328
362
  postScores,
329
363
  baselineDurations,
330
364
  postDurations,
365
+ // 完整 k 次才写:少数几次没报 usage 时补 0 等于把「没测」写成「免费」。
366
+ ...(baselineTokens.length === k && postTokens.length === k
367
+ ? { baselineTokens, postTokens }
368
+ : {}),
331
369
  nullModelPassed: nullCheck.passed,
332
370
  nullModelTotal: nullCheck.total,
333
371
  }