@miphamai/cli 0.85.47 → 0.85.49

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.
@@ -48,6 +48,31 @@ export interface ImprovementReport {
48
48
  problemKey?: string
49
49
  /** SIM:为什么做这次编辑(人可读的一句)。缺席语义同 problemKey。 */
50
50
  rationale?: string
51
+ /**
52
+ * P3 出处:实测用的真实模型 id。缺席 = 无法确定(不是「没有模型」)。
53
+ * 只记录、不进任何判定 —— 与 RSI Tax / 耗时维同一条纪律。
54
+ */
55
+ model?: string
56
+ /**
57
+ * P4:提议者**事前**预测会被修好的题 id。缺席 = 未预测;空数组 = 预测「一题都不会修好」。
58
+ */
59
+ predictedFixes?: string[]
60
+ /**
61
+ * P4:实测中真的从「基线测到过且全败」变「改动后测到过且至少过一次」的题 id。
62
+ * 缺席 = 旧样本没有逐题读数;空数组 = 测得、一题都没修好。只记录、不进判定。
63
+ */
64
+ fixedTasks?: string[]
65
+ /**
66
+ * P4+:`fixedTasks` 中两臂 Wilson 95% 区间**不相交**的题 —— 区间支持「真的变了」的那部分。
67
+ * k 小时通常为空(k=3 连 0/3→3/3 都相交;默认 k=5 起完美翻转可分离),
68
+ * 这是读数不是故障。缺席 = 没有逐题计数。
69
+ */
70
+ fixedSeparated?: string[]
71
+ /**
72
+ * P4:预测了却没修好的题(= `predictedFixes` − `fixedTasks`)。
73
+ * **两者缺一即缺席** —— 没有预测就没有「漏判」,只有实测也不构成漏判。
74
+ */
75
+ missedFixes?: string[]
51
76
  /**
52
77
  * RSI Tax:与分数数组逐项对齐的前/后测量 token。**只记录,不进任何门禁**
53
78
  * (与耗时维同一条纪律)。两个数组同生同灭;缺席 = 未测,不是免费。
@@ -92,6 +117,14 @@ function stdDev(xs: number[]): number {
92
117
  export interface ImprovementContext {
93
118
  problemKey?: string
94
119
  rationale?: string
120
+ /**
121
+ * P3 出处:实测用的**真实模型 id**(如 `deepseek-flash`),不是档位标签
122
+ * (`opus`/`sonnet` 之类在部分配置里会映射到同一模型,标签因此不是标识)。
123
+ * 缺席 = 无法确定(挂载的自定义 Llm 不暴露模型)——**不许**拿注册表当前模型冒充。
124
+ */
125
+ model?: string
126
+ /** P4:提议者事前预测会被修好的题 id。 */
127
+ expectedFixes?: string[]
95
128
  }
96
129
 
97
130
  export function buildImprovementReport(
@@ -152,6 +185,30 @@ export function buildImprovementReport(
152
185
  // 强行绑定只会让调用方为了写一个而编另一个。
153
186
  ...(context?.problemKey ? { problemKey: context.problemKey } : {}),
154
187
  ...(context?.rationale ? { rationale: context.rationale } : {}),
188
+ ...(context?.model ? { model: context.model } : {}),
189
+ // P4:三键各自独立落地 —— 预测可以没有实测(旧样本),实测也可以没有预测(手工路径);
190
+ // 只有**两者都在**时才谈得上「漏判」。空数组是合法读数(预测了「一题都不修好」)。
191
+ ...(context?.expectedFixes !== undefined ? { predictedFixes: context.expectedFixes } : {}),
192
+ ...(sample.fixedTasks !== undefined ? { fixedTasks: sample.fixedTasks } : {}),
193
+ // P4+:区间分离 = 两臂的 Wilson 区间不重叠。用 Wilson 而不是自助重采样,因为在
194
+ // 小样本(如 k=3)上自助会**退化**(0/3 与 3/3 各自重采样只会抽到同一个值 ⇒ 区间
195
+ // 塌成 [1,1],把「三发三中」误报成「确定」)。Wilson 在 n=3 就给得出宽区间。
196
+ ...(sample.fixedTasks !== undefined && sample.taskEvidence !== undefined
197
+ ? {
198
+ fixedSeparated: sample.fixedTasks.filter((id) => {
199
+ const e = sample.taskEvidence!.find((x) => x.id === id)
200
+ if (!e) return false
201
+ const base = wilsonInterval(e.basePass, e.baseSeen)
202
+ const post = wilsonInterval(e.postPass, e.postSeen)
203
+ return post.lo > base.hi
204
+ }),
205
+ }
206
+ : {}),
207
+ ...(context?.expectedFixes !== undefined && sample.fixedTasks !== undefined
208
+ ? {
209
+ missedFixes: context.expectedFixes.filter((id) => !sample.fixedTasks!.includes(id)),
210
+ }
211
+ : {}),
155
212
  // RSI Tax 与耗时维同一纪律:两条同生同灭,缺席即未测。
156
213
  ...(sample.baselineTokens !== undefined && sample.postTokens !== undefined
157
214
  ? { baselineTokens: sample.baselineTokens, postTokens: sample.postTokens }
@@ -193,6 +250,298 @@ export function groupImprovementsByProblem(records: ImprovementRecord[]): Proble
193
250
  .sort((a, b) => b.total - a.total || a.key.localeCompare(b.key))
194
251
  }
195
252
 
253
+ // ── SIM 读侧:把台账渲染成提议者 / 选择者能读的文本 ──
254
+ //
255
+ // 这一步才是 SIM 的机制所在。台账此前只有写侧 + `/crsi stats` 展示 —— 提议者
256
+ // (prose 生成算子)拿到的是教训散文,**零条实测结果**;人类批准闸拿到的是 diff。
257
+ // 也就是说优化器实际跑在「只有根因」的条件下,而那是 SIM 论文里唯一方向不定的档位。
258
+ // 渲染是纯算术(分组、排序、截断、计数),无 LLM 参与 —— 与 verdict 同一纪律。
259
+
260
+ export const SIM_BLOCK_HEADER = '## SIM(Self-Improvement Memory)'
261
+
262
+ /** 默认注入上限。预算 ≈ 8 组 ×(1 + 3)行 × ~100 字符,见 {@link renderSimBlock}。 */
263
+ export const SIM_MAX_GROUPS = 8
264
+ export const SIM_MAX_ATTEMPTS = 3
265
+
266
+ /** 单条理由的截断长度(字符)。超出部分用 `…` 标记,不静默丢。 */
267
+ const SIM_RATIONALE_MAX = 80
268
+
269
+ export interface SimRenderLimits {
270
+ /** 最多注入多少个问题组。 */
271
+ maxGroups?: number
272
+ /** 每组最多注入多少次尝试(取最近的)。 */
273
+ maxAttempts?: number
274
+ }
275
+
276
+ /**
277
+ * 当前设置(规则 8 的比较基准):读侧拿它与每条尝试的出处比。**两个轴各自缺席即未知**,
278
+ * 未知不参与比较 —— 缺席不是「不同」,也不是「相同」。
279
+ */
280
+ export interface SimSetting {
281
+ /** 当前任务电池(skill 名)。 */
282
+ skill?: string
283
+ /** 当前实测模型 id。 */
284
+ model?: string
285
+ }
286
+
287
+ interface SimTier {
288
+ /** 2 = 同设置;1 = 中性(无可比轴 / 部分不同);0 = 双异。 */
289
+ rank: 0 | 1 | 2
290
+ /** 已知不同的轴名(渲染成标注;空数组 = 不标注)。 */
291
+ diff: string[]
292
+ }
293
+
294
+ /**
295
+ * 规则 8(D.2 第 8 条)的可机械化一半:同设置给高相关度、模型与电池**都变**给最低。
296
+ * 只比**两边都已知**的轴:旧记录没有 `model` 时那条轴不可比,不许当成不同。
297
+ */
298
+ function simTier(r: ImprovementRecord, setting?: SimSetting): SimTier {
299
+ if (!setting) return { rank: 1, diff: [] }
300
+ const diff: string[] = []
301
+ let comparable = 0
302
+ if (setting.model && r.model) {
303
+ comparable++
304
+ if (r.model !== setting.model) diff.push('模型')
305
+ }
306
+ // 记录一定有 skillName ⇒ 只要当前 skill 已知,这条轴就可比。
307
+ if (setting.skill) {
308
+ comparable++
309
+ if (r.skillName !== setting.skill) diff.push('skill')
310
+ }
311
+ if (comparable === 0) return { rank: 1, diff }
312
+ if (diff.length === 0) return { rank: 2, diff }
313
+ if (diff.length === comparable) return { rank: 0, diff }
314
+ return { rank: 1, diff }
315
+ }
316
+
317
+ /**
318
+ * 展示次序:同设置优先,其次最近。无 setting 时全部 rank=1 ⇒ 退化为纯最近在前
319
+ * (与加这条规则之前逐字相同的次序)。
320
+ *
321
+ * 同刻按 id 倒序:`chronological` 升序后在 P1 用 `reverse()` 展示,等价于 ts↓、id↓,
322
+ * 这里保持同一口径,免得同一份台账在两个读者眼里次序不同。
323
+ */
324
+ function priorityOrder(rs: ImprovementRecord[], setting?: SimSetting): ImprovementRecord[] {
325
+ return [...rs].sort(
326
+ (a, b) =>
327
+ simTier(b, setting).rank - simTier(a, setting).rank ||
328
+ b.timestamp.localeCompare(a.timestamp) ||
329
+ b.id.localeCompare(a.id),
330
+ )
331
+ }
332
+
333
+ function signed1(n: number): string {
334
+ const s = n.toFixed(1)
335
+ return n > 0 ? `+${s}` : s
336
+ }
337
+
338
+ /** 一条尝试的渲染。ε 缺席时**不写**「预测 0」—— 缺席是未预测,不是预测为零。 */
339
+ function formatAttempt(r: ImprovementRecord, setting?: SimSetting): string {
340
+ const parts = [` - [${r.verdict}] ${r.timestamp.slice(0, 10)}`]
341
+ // 出处紧贴日期:读「什么时候、在哪一个模型上量的」。缺席整节不打。
342
+ if (r.model) parts.push(`模型 ${r.model}`)
343
+ if (r.rationale) {
344
+ const why =
345
+ r.rationale.length > SIM_RATIONALE_MAX
346
+ ? `${r.rationale.slice(0, SIM_RATIONALE_MAX)}…`
347
+ : r.rationale
348
+ parts.push(`理由: ${why}`)
349
+ }
350
+ if (r.predictedDelta !== undefined) {
351
+ // 命中一栏可由旧记录缺席(与 predictionHit 的写入纪律一致)⇒ 读作「未判定」,
352
+ // 不许默认成「未命中」:那会把「没判过」和「判错了」压成同一个读数。
353
+ const hit = r.predictionHit === undefined ? '未判定' : r.predictionHit ? '命中' : '未命中'
354
+ parts.push(`预测 ${r.predictedDelta} → 实测 ${signed1(r.deltaMean)}(${hit})`)
355
+ } else {
356
+ parts.push(`实测 ${signed1(r.deltaMean)}`)
357
+ }
358
+ // P4:任务级预测与实测的配对。漏判点名(最多两个),其余只报个数 —— 读侧有界。
359
+ if (r.predictedFixes !== undefined && r.fixedTasks !== undefined) {
360
+ const hit = r.predictedFixes.filter((id) => r.fixedTasks!.includes(id)).length
361
+ const missed = r.missedFixes ?? []
362
+ const tail =
363
+ missed.length > 0
364
+ ? `(漏 ${missed.slice(0, 2).join('、')}${missed.length > 2 ? ` 等 ${missed.length} 题` : ''})`
365
+ : ''
366
+ const sep = r.fixedSeparated ? `(区间分离 ${r.fixedSeparated.length} 题)` : ''
367
+ parts.push(`预测修好 ${r.predictedFixes.length} 题 → 实际 ${hit} 题${sep}${tail}`)
368
+ } else if (r.fixedTasks !== undefined) {
369
+ const sep = r.fixedSeparated ? `(区间分离 ${r.fixedSeparated.length} 题)` : ''
370
+ parts.push(`修好 ${r.fixedTasks.length} 题${sep}`)
371
+ }
372
+ // 被降权的尝试**自报原因**:静默重排会让读者以为历史次序就是时间次序。
373
+ const tier = simTier(r, setting)
374
+ if (tier.diff.length > 0) parts.push(`⚠️ 异设置:${tier.diff.join('+')}`)
375
+ return parts.join(' · ')
376
+ }
377
+
378
+ /** 组内按时间升序(输出前再倒序);同刻按 id 定序 —— 输出必须确定,否则测试与回执漂移。 */
379
+ function chronological(rs: ImprovementRecord[]): ImprovementRecord[] {
380
+ return [...rs].sort((a, b) => a.timestamp.localeCompare(b.timestamp) || a.id.localeCompare(b.id))
381
+ }
382
+
383
+ function splitByProblem(
384
+ records: ImprovementRecord[],
385
+ setting?: SimSetting,
386
+ ): {
387
+ groups: Array<{ key: string; records: ImprovementRecord[] }>
388
+ ungrouped: number
389
+ } {
390
+ const map = new Map<string, ImprovementRecord[]>()
391
+ let ungrouped = 0
392
+ for (const r of records) {
393
+ if (!r.problemKey) {
394
+ ungrouped++
395
+ continue
396
+ }
397
+ const bucket = map.get(r.problemKey) ?? []
398
+ bucket.push(r)
399
+ map.set(r.problemKey, bucket)
400
+ }
401
+ const groups = [...map.entries()].map(([key, rs]) => ({ key, records: chronological(rs) }))
402
+ // 组级排序(规则 8):组里**最好**的那条证据与当前设置越相关,整组越靠前;同档再按最近活动。
403
+ //
404
+ // 取舍(有意的):一个很久没动、但当时是同设置量出来的组,会压住一个正在复发、却在
405
+ // 别的模型上量过的组。被挤掉的组数在块尾显式计数(「另有 K 组未注入」),不静默丢。
406
+ // 无 setting ⇒ 所有组 rank=1 ⇒ 退化为纯最近活动,与加这条之前逐字相同。
407
+ const bestRank = (rs: ImprovementRecord[]): number =>
408
+ Math.max(...rs.map((r) => simTier(r, setting).rank))
409
+ groups.sort((a, b) => {
410
+ const ra = bestRank(a.records)
411
+ const rb = bestRank(b.records)
412
+ if (ra !== rb) return rb - ra
413
+ const ta = a.records[a.records.length - 1]!.timestamp
414
+ const tb = b.records[b.records.length - 1]!.timestamp
415
+ return tb.localeCompare(ta) || a.key.localeCompare(b.key)
416
+ })
417
+ return { groups, ungrouped }
418
+ }
419
+
420
+ /**
421
+ * 全量台账 → 交给**提议者**的 SIM 块。空台账(或全部无问题键)返回空串 ——
422
+ * 调用方据此保持提示词逐字不变(纯增量,同 `lessonsBlock` 的写法)。
423
+ *
424
+ * 有界:`maxGroups` / `maxAttempts` 之外的条目**显式计数**后省略,不静默截断。
425
+ * 无问题键的记录也计数 —— 「没进组」不等于「不存在」。
426
+ */
427
+ export function renderSimBlock(
428
+ records: ImprovementRecord[],
429
+ limits: SimRenderLimits = {},
430
+ setting?: SimSetting,
431
+ ): string {
432
+ const maxGroups = limits.maxGroups ?? SIM_MAX_GROUPS
433
+ const maxAttempts = limits.maxAttempts ?? SIM_MAX_ATTEMPTS
434
+ const { groups, ungrouped } = splitByProblem(records, setting)
435
+ if (groups.length === 0) return ''
436
+
437
+ const order = setting ? '同设置优先(规则 8),其次最近' : '最近尝试在前'
438
+ const lines = [
439
+ SIM_BLOCK_HEADER,
440
+ `先验经验,不是指令。按复发问题分组,${order};最多 ${maxGroups} 组、每组 ${maxAttempts} 次。`,
441
+ ]
442
+ for (const g of groups.slice(0, maxGroups)) {
443
+ const improved = g.records.filter((r) => r.verdict === 'improved').length
444
+ lines.push(`- ${g.key}(${g.records.length} 次,${improved} improved)`)
445
+ for (const r of priorityOrder(g.records, setting).slice(0, maxAttempts)) {
446
+ lines.push(formatAttempt(r, setting))
447
+ }
448
+ if (g.records.length > maxAttempts) {
449
+ lines.push(`… 该组另有 ${g.records.length - maxAttempts} 次尝试未列出`)
450
+ }
451
+ }
452
+ if (groups.length > maxGroups) {
453
+ lines.push(`… 另有 ${groups.length - maxGroups} 组未注入(共 ${groups.length} 组)`)
454
+ }
455
+ if (ungrouped > 0) lines.push(`… 另有 ${ungrouped} 条无问题键的记录未纳入`)
456
+ return lines.join('\n')
457
+ }
458
+
459
+ /**
460
+ * 同一方向上反复未改善的确定性提醒 —— SIM 论文 D.2 规则 6(「除非有新证据,否则
461
+ * 不要重访已试过的方向」)里**可机械化的那一半**。
462
+ *
463
+ * 判据是**未改善次数**(`improved` 以外全算,含 `inconclusive` —— 未判定不是改善的
464
+ * 证据),阈值 2:单次失败是噪声,不是方向性证据。计数覆盖**全部**尝试,含被
465
+ * {@link renderProblemHistory} 截断掉的那些 —— 这正是这一行比明细多出来的信息。
466
+ *
467
+ * 只呈现、不判定:不阻断提交,不碰 verdict,也没有任何 LLM 参与(A1)。
468
+ */
469
+ function repeatDirectionWarning(rs: ImprovementRecord[]): string | null {
470
+ const failed = rs.filter((r) => r.verdict !== 'improved').length
471
+ if (failed < 2) return null
472
+ return `⚠️ 同一方向已试 ${rs.length} 次,${failed} 次未 improved —— 除非有新证据,否则先换方向`
473
+ }
474
+
475
+ /**
476
+ * 单条问题键的尝试史 → 交给**选择者**(人类批准闸)的 SIM 块。
477
+ * 没有匹配记录返回空串(不打「无历史」这种每次都出现的噪声行)。
478
+ *
479
+ * `problemKey` 由调用方归一化(与写入侧同一把尺子:`normalizeProblemKey`)。
480
+ */
481
+ export function renderProblemHistory(
482
+ records: ImprovementRecord[],
483
+ problemKey: string,
484
+ maxAttempts: number = SIM_MAX_ATTEMPTS,
485
+ setting?: SimSetting,
486
+ ): string {
487
+ const rs = records.filter((r) => r.problemKey === problemKey)
488
+ if (rs.length === 0) return ''
489
+ const order = setting ? '同设置优先,其次最近' : '最近在前'
490
+ const lines = [`🪞 SIM 先验经验(同一问题上的历史尝试,${order};不是指令)`]
491
+ const warning = repeatDirectionWarning(rs)
492
+ if (warning) lines.push(warning)
493
+ for (const r of priorityOrder(rs, setting).slice(0, maxAttempts)) {
494
+ lines.push(formatAttempt(r, setting))
495
+ }
496
+ if (rs.length > maxAttempts) {
497
+ lines.push(`… 该问题另有 ${rs.length - maxAttempts} 次尝试未列出`)
498
+ }
499
+ return lines.join('\n')
500
+ }
501
+
502
+ /**
503
+ * `/crsi stats` 的逐题修复汇总。三个桶**刻意分开**:
504
+ * 有区间读数 / 有修复集但无区间(P4 时代记录)/ 连修复集都没有(旧样本)。
505
+ * 「没法判区间」与「判了、零题分离」不是同一件事 —— 合成一个数会让它们同形。
506
+ *
507
+ * `fixed` / `separated` 是**题次**(按记录累计,同一题在两次尝试里各算一次),
508
+ * 不是去重题数:读者问的是「这些改动累计修好了多少次」。
509
+ */
510
+ export interface FixedSummary {
511
+ recordsWithFixed: number
512
+ fixed: number
513
+ recordsWithInterval: number
514
+ separated: number
515
+ noInterval: number
516
+ noFixed: number
517
+ }
518
+
519
+ export function fixedSummary(records: ImprovementRecord[]): FixedSummary {
520
+ const out: FixedSummary = {
521
+ recordsWithFixed: 0,
522
+ fixed: 0,
523
+ recordsWithInterval: 0,
524
+ separated: 0,
525
+ noInterval: 0,
526
+ noFixed: 0,
527
+ }
528
+ for (const r of records) {
529
+ if (r.fixedTasks === undefined) {
530
+ out.noFixed++
531
+ continue
532
+ }
533
+ out.recordsWithFixed++
534
+ out.fixed += r.fixedTasks.length
535
+ if (r.fixedSeparated === undefined) {
536
+ out.noInterval++
537
+ continue
538
+ }
539
+ out.recordsWithInterval++
540
+ out.separated += r.fixedSeparated.length
541
+ }
542
+ return out
543
+ }
544
+
196
545
  /** RSI Tax 的台账汇总:只统计带 token 量的记录。 */
197
546
  export function measurementTaxSummary(records: ImprovementRecord[]): {
198
547
  records: number
@@ -15,6 +15,7 @@ import {
15
15
  } from './crsi-producer'
16
16
  import { miphamHome } from './paths.ts'
17
17
  import { safeSlice } from '../shared/sanitize'
18
+ import { readRegularFileSync } from '../shared/regular-file'
18
19
 
19
20
  export interface FrontmatterResult {
20
21
  data: Record<string, unknown>
@@ -765,9 +766,13 @@ Never omit it or present the work as purely human-authored.`)
765
766
  const changed: string[] = []
766
767
  for (const inst of this.instructions) {
767
768
  if (this.isUnsafePath(inst.path, inst.level)) continue
768
- if (!existsSync(inst.path)) continue
769
+ // Type, not existence: `existsSync` is true for a FIFO, and reading one
770
+ // with no writer blocks forever inside a synchronous call (the same gate
771
+ // `rules-loader.ts` already uses for rule files).
772
+ const raw = readRegularFileSync(inst.path)
773
+ if (raw === null) continue
769
774
  try {
770
- const { data, content } = parseFrontmatter(readFileSync(inst.path, 'utf-8'))
775
+ const { data, content } = parseFrontmatter(raw)
771
776
  const next = capInstructionContent(content, inst.path)
772
777
  if (next !== inst.content) {
773
778
  inst.content = next
@@ -788,8 +793,12 @@ Never omit it or present the work as purely human-authored.`)
788
793
 
789
794
  if (this.isUnsafePath(path, level)) return
790
795
 
796
+ // A FIFO/socket/device here would block the startup read forever; treat it
797
+ // as "nothing to load" instead of waiting on a writer that may never come.
798
+ const raw = readRegularFileSync(path)
799
+ if (raw === null) return
800
+
791
801
  try {
792
- const raw = readFileSync(path, 'utf-8')
793
802
  const { data, content } = parseFrontmatter(raw)
794
803
  this.instructions.push({
795
804
  path,
@@ -298,6 +298,17 @@ function isSkillFile(filePath: string): boolean {
298
298
  )
299
299
  }
300
300
 
301
+ /**
302
+ * 从 proposal 的路径与内容解出 skill 名(非 skill 文件 / 无 `name` → undefined)。
303
+ * 读侧用它标注「这条证据是不是同一个任务电池上量的」(规则 8);不与
304
+ * `resolveSkillProposal` 合并:那个还要旧内容与任务集,这里只需一个标识。
305
+ */
306
+ export function resolveSkillName(filePath: string, content: string): string | undefined {
307
+ if (!isSkillFile(filePath)) return undefined
308
+ const parsed = parseFrontmatter(content)
309
+ return typeof parsed.data.name === 'string' ? parsed.data.name : undefined
310
+ }
311
+
301
312
  /** 解析改 skill 的 proposal → 名字 + 旧/新 body;非 skill / 无任务集 / 旧不可读 → null。 */
302
313
  function resolveSkillProposal(proposal: {
303
314
  filePath: string
@@ -356,6 +367,15 @@ export async function measureSkillDelta(
356
367
  }
357
368
  }
358
369
 
370
+ /** 逐题两臂计数:pass/seen 分开记 —— 「没量到」不能混进分母。 */
371
+ export interface TaskEvidence {
372
+ id: string
373
+ basePass: number
374
+ baseSeen: number
375
+ postPass: number
376
+ postSeen: number
377
+ }
378
+
359
379
  export interface SkillDeltaSample {
360
380
  skillName: string
361
381
  baselineScores: number[]
@@ -370,7 +390,7 @@ export interface SkillDeltaSample {
370
390
  /**
371
391
  * B2 代价维:与分数数组**逐项对齐**的耗时(第 i 项就是产出第 i 个分数的那次采样)。
372
392
  * 缺席 = 该样本未记代价(旧记录 / 旧调用点),读侧须按「缺席」处理、不得当成 0。
373
- * 只记录,不参与改进判定 —— 样本量 k=3 时再加一个维度只会让统计问题更糟。
393
+ * 只记录,不参与改进判定 —— 样本量这么小的时候,再加一个维度只会让统计问题更糟。
374
394
  */
375
395
  baselineDurations?: number[]
376
396
  postDurations?: number[]
@@ -381,11 +401,25 @@ export interface SkillDeltaSample {
381
401
  */
382
402
  baselineTokens?: number[]
383
403
  postTokens?: number[]
404
+ /**
405
+ * P4+:逐题两臂计数(区间计算的原料)。只含**真的量到**的采样 ——
406
+ * uncertain / truncated 既不进 pass 也不进 seen。缺席 = 旧样本。
407
+ */
408
+ taskEvidence?: TaskEvidence[]
409
+ /**
410
+ * P4 逐题修复集:基线**测到过且全败**、改动后**测到过且至少过一次**的题 id。
411
+ *
412
+ * 确定性算术,无 LLM 裁判(A1)。「测到过」排除 `truncated` / `uncertain` 的采样 ——
413
+ * 某一轮上游抽风不能算「基线失败」,否则一道根本没量到的题会被记成「被修好了」。
414
+ * k 次采样下这是方向性信号,不是统计结论。空数组 = 测得、一题都没修好(不是缺席)。
415
+ */
416
+ fixedTasks?: string[]
384
417
  }
385
418
 
386
419
  /**
387
420
  * 多次采样 before/after(每次都是「LLM 生成 → 冻结测试判定」),供改进轨估噪声。
388
- * 返回 null 门与 measureSkillDelta 相同。k 默认 3。
421
+ * 返回 null 门与 measureSkillDelta 相同。**k 默认 5**:逐题修复的 Wilson 区间要到
422
+ * 这个量级才可能分得开(k=3 时连 0/3→3/3 都相交);成本是每次测量 2×k 次 LLM 调用。
389
423
  */
390
424
  export async function measureSkillDeltaRepeated(
391
425
  llm: Llm,
@@ -395,13 +429,32 @@ export async function measureSkillDeltaRepeated(
395
429
  const resolved = resolveSkillProposal(proposal)
396
430
  if (!resolved) return null
397
431
 
398
- const k = opts?.k ?? 3
432
+ const k = opts?.k ?? 5
399
433
  const baselineScores: number[] = []
400
434
  const postScores: number[] = []
401
435
  const baselineDurations: number[] = []
402
436
  const postDurations: number[] = []
403
437
  const baselineTokens: number[] = []
404
438
  const postTokens: number[] = []
439
+ // 逐题累计:只累计**真的量到**的采样(截断 / 仪器故障不是答错)。
440
+ const perTask = new Map<
441
+ string,
442
+ { baseSeen: number; basePass: number; postSeen: number; postPass: number }
443
+ >()
444
+ const acc = (phase: 'base' | 'post', report: TaskPerformanceReport): void => {
445
+ for (const r of report.results) {
446
+ if (r.truncated || r.uncertain) continue
447
+ const s = perTask.get(r.id) ?? { baseSeen: 0, basePass: 0, postSeen: 0, postPass: 0 }
448
+ if (phase === 'base') {
449
+ s.baseSeen++
450
+ if (r.passed) s.basePass++
451
+ } else {
452
+ s.postSeen++
453
+ if (r.passed) s.postPass++
454
+ }
455
+ perTask.set(r.id, s)
456
+ }
457
+ }
405
458
  for (let i = 0; i < k; i++) {
406
459
  const r = await runTaskPerformance(llm, {
407
460
  skill: { name: resolved.skillName, text: resolved.baselineText },
@@ -409,6 +462,7 @@ export async function measureSkillDeltaRepeated(
409
462
  // 没测到的一轮不许折成 100 塞进样本:那会把「上游挂了」变成「基线满分」,
410
463
  // 进而产出假的 regressed(拦掉一次合法合并)或假的 improved。
411
464
  if (!r.measurable) return null
465
+ acc('base', r)
412
466
  baselineScores.push(r.score)
413
467
  baselineDurations.push(r.durationMs)
414
468
  if (r.tokensUsed !== undefined) baselineTokens.push(r.tokensUsed)
@@ -418,10 +472,21 @@ export async function measureSkillDeltaRepeated(
418
472
  skill: { name: resolved.skillName, text: resolved.postText },
419
473
  })
420
474
  if (!r.measurable) return null
475
+ acc('post', r)
421
476
  postScores.push(r.score)
422
477
  postDurations.push(r.durationMs)
423
478
  if (r.tokensUsed !== undefined) postTokens.push(r.tokensUsed)
424
479
  }
480
+ const fixedTasks = [...perTask.entries()]
481
+ .filter(([, s]) => s.baseSeen > 0 && s.postSeen > 0 && s.basePass === 0 && s.postPass > 0)
482
+ .map(([id]) => id)
483
+ const taskEvidence: TaskEvidence[] = [...perTask.entries()].map(([id, s]) => ({
484
+ id,
485
+ basePass: s.basePass,
486
+ baseSeen: s.baseSeen,
487
+ postPass: s.postPass,
488
+ postSeen: s.postSeen,
489
+ }))
425
490
 
426
491
  // 空模型闸在最后一次采样后算一次:与模型无关,重复跑只是重复同一组测试。
427
492
  const nullCheck = runNullModelCheck(resolved.skillName)
@@ -438,5 +503,7 @@ export async function measureSkillDeltaRepeated(
438
503
  : {}),
439
504
  nullModelPassed: nullCheck.passed,
440
505
  nullModelTotal: nullCheck.total,
506
+ fixedTasks,
507
+ taskEvidence,
441
508
  }
442
509
  }
@@ -758,6 +758,9 @@
758
758
  "user": {
759
759
  "role_label": "User"
760
760
  },
761
+ "compaction": {
762
+ "role_label": "Summary"
763
+ },
761
764
  "input": {
762
765
  "placeholder": "Type a message (Esc to clear)..."
763
766
  },
@@ -758,6 +758,9 @@
758
758
  "user": {
759
759
  "role_label": "用户"
760
760
  },
761
+ "compaction": {
762
+ "role_label": "摘要"
763
+ },
761
764
  "input": {
762
765
  "placeholder": "输入消息(Esc 清空)..."
763
766
  },
@@ -89,9 +89,18 @@ export class PluginManager {
89
89
  }
90
90
  }
91
91
 
92
- // Copy plugin directory
93
- mkdirSync(destDir, { recursive: true })
94
- this.copyDir(sourcePath, destDir)
92
+ // Copy plugin directory. A copy that dies halfway used to leave a partial
93
+ // directory behind, and the `already installed` check above then made every
94
+ // retry fail — a plugin that could never be installed until the user found
95
+ // and deleted the wreckage by hand.
96
+ try {
97
+ mkdirSync(destDir, { recursive: true })
98
+ this.copyDir(sourcePath, destDir)
99
+ } catch (err) {
100
+ rmSync(destDir, { recursive: true, force: true })
101
+ const detail = err instanceof Error ? err.message : String(err)
102
+ return { success: false, message: `Failed to copy plugin: ${detail}` }
103
+ }
95
104
 
96
105
  const similarWarning = this.findSimilarWarning(validation.manifest.name)
97
106
  this.plugins.push({
@@ -11,6 +11,7 @@ import {
11
11
  fetchWithRetry,
12
12
  streamIdleTimeoutMs,
13
13
  isRetryableFailure,
14
+ isAbortError,
14
15
  createAwakeTimer,
15
16
  readErrorBody,
16
17
  } from './fetch-utils'
@@ -263,6 +264,10 @@ export class AnthropicProvider implements ProviderInstance {
263
264
  }),
264
265
  ])
265
266
  } catch (err) {
267
+ // An abort is the caller leaving, not the stream stalling: wrapping it
268
+ // into a retryable error chunk made the engine retry a request the user
269
+ // had just cancelled.
270
+ if (isAbortError(err)) throw err
266
271
  yield { type: 'error', error: `Stream stalled: ${String(err)}` }
267
272
  return
268
273
  } finally {
@@ -108,8 +108,23 @@ function tlsCertCode(err: unknown): string | undefined {
108
108
  return undefined
109
109
  }
110
110
 
111
+ /**
112
+ * Was this failure the caller walking away?
113
+ *
114
+ * Providers used to wrap every stream-read rejection — aborts included — into a
115
+ * retryable `Stream stalled:` error chunk, which turned "the user pressed Esc"
116
+ * into "the request failed once, retrying". Abort has to stay an abort all the
117
+ * way out so the engine's own handler (and the UI) can tell the two apart.
118
+ */
119
+ export function isAbortError(err: unknown): boolean {
120
+ if (err instanceof Error && err.name === 'AbortError') return true
121
+ return (
122
+ typeof DOMException !== 'undefined' && err instanceof DOMException && err.name === 'AbortError'
123
+ )
124
+ }
125
+
111
126
  function isRetryableError(err: unknown): boolean {
112
- if (err instanceof DOMException && err.name === 'AbortError') return false
127
+ if (isAbortError(err)) return false
113
128
  if (tlsCertCode(err) !== undefined) return false
114
129
  return true
115
130
  }
@@ -5,6 +5,7 @@ import {
5
5
  fetchWithRetry,
6
6
  streamIdleTimeoutMs,
7
7
  isRetryableFailure,
8
+ isAbortError,
8
9
  createAwakeTimer,
9
10
  readErrorBody,
10
11
  } from './fetch-utils'
@@ -142,6 +143,9 @@ export class OpenAICompatProvider implements ProviderInstance {
142
143
  }),
143
144
  ])
144
145
  } catch (err) {
146
+ // See anthropic.ts: an abort must stay an abort, not become a
147
+ // retryable "stream stalled" error chunk.
148
+ if (isAbortError(err)) throw err
145
149
  yield { type: 'error', error: `Stream stalled: ${String(err)}` }
146
150
  return
147
151
  } finally {
@@ -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.47' as const
12
+ export const PACKAGE_VERSION = '0.85.49' 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 = 5232 as const
93
+ export const TEST_COUNT = 5332 as const