@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.
@@ -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'
@@ -154,6 +168,8 @@ import { execSync } from 'node:child_process'
154
168
  import { MIPHAM_DIR, OLLAMA_PRESET_MODELS } from '../shared/constants'
155
169
  import { renameActiveSession } from '../agent/cross-session/discovery'
156
170
  import { clearTasks, formatTaskList } from '../tools/exec/task'
171
+ import { estimateCost, loadPriceBook } from '../providers/pricing'
172
+ import type { UsageSummary } from '../core/usage-tracker'
157
173
 
158
174
  export interface CommandContext {
159
175
  engine: QueryEngine
@@ -582,6 +598,87 @@ const statusCmd: CommandHandler = async (ctx) => {
582
598
  }
583
599
  }
584
600
 
601
+ const CURRENCY_SYMBOLS: Record<string, string> = { USD: '$', CNY: '¥' }
602
+
603
+ /**
604
+ * 金额显示:估算值,不是账单。太小的数不四舍五入成 0 —— 「<$0.0001」与「0」
605
+ * 对用户是两件事(前者说明有花费,只是很小)。
606
+ */
607
+ function formatCostAmount(amount: number): string {
608
+ if (amount === 0) return '0'
609
+ if (amount < 0.0001) return '<0.0001'
610
+ return String(Number(amount.toFixed(6)))
611
+ }
612
+
613
+ /** `/cost` 的会话计费段:四桶实报用量 + 按用户价格表估算的费用。 */
614
+ function sessionBillingLines(
615
+ ctx: Parameters<CommandHandler>[0],
616
+ t: (key: string, params?: Record<string, string>) => string,
617
+ ): string[] {
618
+ const tracker = ctx.engine.getUsageTracker() as { getSummary?: () => UsageSummary } | undefined
619
+ // 远端 attach 的 tracker 只有 getStats —— 那类会话没有本地计费账,整段省略,
620
+ // 不能因此把 `/cost` 打死。
621
+ if (typeof tracker?.getSummary !== 'function') return []
622
+ const summary = tracker.getSummary()
623
+
624
+ const input = summary.apiInputTokens ?? 0
625
+ const output = summary.apiOutputTokens ?? 0
626
+ const cacheRead = summary.apiCacheReadTokens ?? 0
627
+ const cacheWrite = summary.apiCacheWriteTokens ?? 0
628
+ const billedInput = input + cacheRead + cacheWrite
629
+ const hitRatio = billedInput > 0 ? Math.min(1, cacheRead / billedInput) * 100 : 0
630
+
631
+ const lines = [
632
+ '',
633
+ t('commands.cost.session_title'),
634
+ t('commands.cost.buckets', {
635
+ input: input.toLocaleString(),
636
+ cache_read: cacheRead.toLocaleString(),
637
+ cache_write: cacheWrite.toLocaleString(),
638
+ output: output.toLocaleString(),
639
+ }),
640
+ ]
641
+ if (billedInput > 0) {
642
+ lines.push(t('commands.cost.cache_hit', { ratio: hitRatio.toFixed(1) }))
643
+ }
644
+
645
+ const loaded = loadPriceBook()
646
+ if (loaded.error !== undefined) {
647
+ lines.push(t('commands.cost.file_error', { error: loaded.error }))
648
+ return lines
649
+ }
650
+
651
+ const result = estimateCost(loaded.book, ctx.providerId, ctx.modelId, {
652
+ inputTokens: input,
653
+ outputTokens: output,
654
+ cacheReadTokens: cacheRead,
655
+ cacheWriteTokens: cacheWrite,
656
+ })
657
+ const route = { provider: ctx.providerId, model: ctx.modelId }
658
+ switch (result.kind) {
659
+ case 'ok':
660
+ lines.push(
661
+ t(result.asOf === undefined ? 'commands.cost.estimate_no_date' : 'commands.cost.estimate', {
662
+ symbol: CURRENCY_SYMBOLS[result.currency] ?? '',
663
+ amount: formatCostAmount(result.amount),
664
+ ...route,
665
+ ...(result.asOf !== undefined ? { asOf: result.asOf } : {}),
666
+ }),
667
+ // 账是「整段会话的桶 × 当前模型单价」,中途换过模型就不再是精确认账 ——
668
+ // 说在显示上,而不是留给用户自己发现。
669
+ t('commands.cost.caveat'),
670
+ )
671
+ break
672
+ case 'incomplete':
673
+ lines.push(t('commands.cost.incomplete', { missing: result.missing.join(', ') }))
674
+ break
675
+ case 'no-price':
676
+ lines.push(t('commands.cost.no_price', route))
677
+ break
678
+ }
679
+ return lines
680
+ }
681
+
585
682
  const costCmd: CommandHandler = (ctx) => {
586
683
  const t = resolveT(ctx)
587
684
  const c = ctx.engine.getContext()
@@ -591,6 +688,7 @@ const costCmd: CommandHandler = (ctx) => {
591
688
  const hitRatio = tokens > 0 ? Math.min(1, cachedTokens / tokens) : 0
592
689
  const uncachedTokens = Math.max(0, tokens - cachedTokens)
593
690
  const maxTokens = c.getMaxTokens()
691
+ const billing = sessionBillingLines(ctx, t).join('\n')
594
692
  return {
595
693
  content: stripIndent`
596
694
  ${t('commands.context_tokens.title')}
@@ -601,6 +699,7 @@ const costCmd: CommandHandler = (ctx) => {
601
699
  ratio: (hitRatio * 100).toFixed(1),
602
700
  uncached: uncachedTokens.toLocaleString(),
603
701
  })}
702
+ ${billing}
604
703
 
605
704
  ${t('commands.context_tokens.footer')}
606
705
  `,
@@ -1166,7 +1265,34 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
1166
1265
  }
1167
1266
 
1168
1267
  const crsiInventoryCmd: CommandHandler = async (ctx) => {
1169
- return { content: buildCapabilityReport(ctx.engine) }
1268
+ // Ledger numbers are loaded here, not in the builder: the report stays pure,
1269
+ // and every ledger row can carry the timestamp of the record it came from.
1270
+ const ledgers: CapabilityLedgers = {}
1271
+
1272
+ const evalEntry = getLastEvalEntry('mechanism-sentinel')
1273
+ if (evalEntry) ledgers.lastEval = evalEntry
1274
+
1275
+ const improvements = readImprovements()
1276
+ if (improvements.length > 0) {
1277
+ const verdicts: Record<string, number> = {}
1278
+ for (const record of improvements) {
1279
+ verdicts[record.verdict] = (verdicts[record.verdict] ?? 0) + 1
1280
+ }
1281
+ const latest = improvements.reduce((a, b) => (a.timestamp >= b.timestamp ? a : b))
1282
+ ledgers.improvements = {
1283
+ count: improvements.length,
1284
+ verdicts,
1285
+ latestTimestamp: latest.timestamp,
1286
+ }
1287
+ }
1288
+
1289
+ const probations = readProbations()
1290
+ if (probations.length > 0) {
1291
+ const latest = probations.reduce((a, b) => (a.timestamp >= b.timestamp ? a : b))
1292
+ ledgers.probation = { count: probations.length, latestTimestamp: latest.timestamp }
1293
+ }
1294
+
1295
+ return { content: buildCapabilityReport(ctx.engine, ledgers) }
1170
1296
  }
1171
1297
 
1172
1298
  /**
@@ -1444,7 +1570,12 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1444
1570
  return { content: '⚠️ 已有待批准的修改。先 /crsi modify --approve 或 --reject。' }
1445
1571
  }
1446
1572
 
1447
- const insights = ctx.engine.getAutoMemory?.()?.accumulatedInsights ?? []
1573
+ // 本次会话的洞察 + 收件箱里的历史信号:重启后 `accumulatedInsights` 为空,
1574
+ // 但收件箱不会 —— 否则「学习」仍然要求失败与 propose 发生在同一个进程里。
1575
+ const insights = [
1576
+ ...(ctx.engine.getAutoMemory?.()?.accumulatedInsights ?? []),
1577
+ ...pendingToInsights(readSignals()),
1578
+ ]
1448
1579
  let metaRules: Parameters<typeof produceCrsiProposal>[1] = []
1449
1580
  try {
1450
1581
  metaRules = ctx.engine.getMetaRuleEngine?.()?.analyze().metaRules ?? []
@@ -1463,6 +1594,53 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1463
1594
  // 非 git 目录 → 回退 cwd
1464
1595
  }
1465
1596
 
1597
+ // ── 收件箱路径:/crsi propose --pending ──
1598
+ // 启动时 `refreshPendingLessons` 已把收件箱里尚未并入的信号渲染成 pending 文件
1599
+ // (不需要人在场)。这里只负责把它送进沙箱 gate 与人类审阅 —— 合并仍要批准。
1600
+ if (args[0] === '--pending') {
1601
+ const pendingContent = readPendingLessons()
1602
+ if (!pendingContent.trim()) {
1603
+ return { content: '没有待并入的教训 —— 收件箱为空,或它们都已并入 crsi-lessons.md。' }
1604
+ }
1605
+
1606
+ const { existsSync, readFileSync } = await import('node:fs')
1607
+ const { join } = await import('node:path')
1608
+ // `root` 来自 `git rev-parse`;那条命令在测试里被 mock、也可能在非 git 目录失败。
1609
+ // 读侧允许从 cwd 向上找 —— 而提案里的 `filePath` 仍是仓库根相对路径。
1610
+ const fromRoot = join(root, LESSONS_FILE)
1611
+ const lessonsPath = existsSync(fromRoot) ? fromRoot : findLessonsFile(process.cwd())
1612
+ if (!lessonsPath) {
1613
+ return { content: `❌ 找不到 ${LESSONS_FILE}(当前目录不是 mipham-code 仓库?)。` }
1614
+ }
1615
+ const current = readFileSync(lessonsPath, 'utf-8')
1616
+
1617
+ // 按标题逐块去重:pending 是派生视图,可能比 lessons 慢一拍(刚合并完还没重新渲染)。
1618
+ const fresh = splitLessonBlocks(pendingContent).filter(
1619
+ (block) => !current.includes(block.split('\n', 1)[0]!),
1620
+ )
1621
+ if (fresh.length === 0) {
1622
+ return { content: 'pending 里的教训都已并入 crsi-lessons.md。' }
1623
+ }
1624
+
1625
+ const result = await runCrsiModification({
1626
+ description: `CRSI inbox: ${fresh.length} 条收件箱教训`,
1627
+ filePath: LESSONS_FILE,
1628
+ originalContent: current,
1629
+ newContent: `${current.trimEnd()}\n\n${fresh.join('\n')}\n`,
1630
+ blastRadius: [LESSONS_FILE],
1631
+ })
1632
+ if (!result.applied || result.phase === 'failed') {
1633
+ return { content: `❌ 生成失败(phase: ${result.phase})。\n${result.error ?? ''}` }
1634
+ }
1635
+ return {
1636
+ content:
1637
+ `✅ 已把 ${fresh.length} 条收件箱教训送进沙箱并跑过测试。审阅 diff:\n` +
1638
+ renderGateNote(result) +
1639
+ `\n${result.diff}\n\n` +
1640
+ '/crsi modify --approve 合并 | /crsi modify --reject 丢弃',
1641
+ }
1642
+ }
1643
+
1466
1644
  // ── 散文提议路径:/crsi propose --prose 用 LLM 生成改 skill 散文提议 ──
1467
1645
  if (args[0] === '--prose') {
1468
1646
  const skillFiles = collectSkillFiles(root)
@@ -1708,7 +1886,12 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1708
1886
  current = ''
1709
1887
  }
1710
1888
 
1711
- const proposal = produceCrsiProposal(insights, metaRules, current, new Date().toISOString())
1889
+ // 已并入的教训不参与「选最佳信号」。否则最好那条(critical 优先)刚好已并入时,
1890
+ // `produceCrsiProposal` 的幂等判断会让它返回 null —— 排在后面的可学信号一起被挡。
1891
+ const freshInsights = insights.filter(
1892
+ (i) => !current.includes(`## ${i.category}: ${i.description}`),
1893
+ )
1894
+ const proposal = produceCrsiProposal(freshInsights, metaRules, current, new Date().toISOString())
1712
1895
 
1713
1896
  if (!proposal) {
1714
1897
  return { content: '没有足够的失败信号(autoApplicable insight 或高置信元规则)来生成教训。' }
@@ -2244,7 +2427,7 @@ const sisErrorsCmd: CommandHandler = (ctx) => {
2244
2427
  lines.push(`- ${statusIcon} \`${sig.id}\` [${sig.category}] ${sig.toolName}`)
2245
2428
  lines.push(` 模式: \`${sig.pattern.slice(0, 80)}${sig.pattern.length > 80 ? '...' : ''}\``)
2246
2429
  lines.push(
2247
- ` 修复: ${sig.fixStrategy} → ${sig.fixAction.slice(0, 60)} | 发生 ${sig.occurrences} 次 | 成功率 ${Math.round(sig.successRate * 100)}%`,
2430
+ ` 修复: ${sig.fixStrategy} → ${sig.fixAction.slice(0, 60)} | 发生 ${sig.occurrences} 次 | 成功率 ${formatFixRate(sig)}`,
2248
2431
  )
2249
2432
  lines.push('')
2250
2433
  }
@@ -2264,7 +2447,9 @@ const sisStatsCmd: CommandHandler = (ctx) => {
2264
2447
  lines.push(
2265
2448
  `🟢 活跃: ${stats.active} | 🟡 降级: ${stats.degraded} | ⚫ 已退役: ${stats.retired}`,
2266
2449
  )
2267
- lines.push(`平均成功率: ${Math.round(stats.avgSuccessRate * 100)}%`)
2450
+ lines.push(
2451
+ `平均成功率: ${stats.fixable > 0 ? `${Math.round(stats.avgSuccessRate * 100)}%` : '—(无可自动修复签名)'}`,
2452
+ )
2268
2453
  lines.push(`总拦截次数: ${stats.totalInterceptions}`)
2269
2454
 
2270
2455
  const active = db.getActive()
@@ -2275,9 +2460,7 @@ const sisStatsCmd: CommandHandler = (ctx) => {
2275
2460
  lines.push('|------|------|------|--------|')
2276
2461
  for (const s of active) {
2277
2462
  const icon = s.status === 'active' ? '🟢' : '🟡'
2278
- lines.push(
2279
- `| ${s.id} | ${icon} ${s.status} | ${s.occurrences} | ${Math.round(s.successRate * 100)}% |`,
2280
- )
2463
+ lines.push(`| ${s.id} | ${icon} ${s.status} | ${s.occurrences} | ${formatFixRate(s)} |`)
2281
2464
  }
2282
2465
  }
2283
2466
 
@@ -2421,14 +2604,16 @@ const crsiInterpretCmd: CommandHandler = (ctx, args) => {
2421
2604
  '',
2422
2605
  )
2423
2606
  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))
2607
+ const fixable = isAutoFixable(sig)
2608
+ const bar = fixable
2609
+ ? '█'.repeat(Math.round(sig.successRate * 10)) +
2610
+ '░'.repeat(10 - Math.round(sig.successRate * 10))
2611
+ : ''
2427
2612
  lines.push(`- **${sig.toolName}**: \`${sig.pattern.slice(0, 60)}\``)
2428
2613
  lines.push(
2429
2614
  t('commands.crsi_interpret.sig_success', {
2430
2615
  bar,
2431
- pct: String(Math.round(sig.successRate * 100)),
2616
+ pct: formatFixRate(sig),
2432
2617
  occurrences: String(sig.occurrences),
2433
2618
  strategy: sig.fixStrategy,
2434
2619
  }),
@@ -2808,7 +2993,7 @@ const bugReportCmd: CommandHandler = async (ctx) => {
2808
2993
  pattern: sig.pattern,
2809
2994
  category: sig.category,
2810
2995
  occurrences: String(sig.occurrences),
2811
- pct: (sig.successRate * 100).toFixed(0),
2996
+ pct: formatFixRate(sig),
2812
2997
  }),
2813
2998
  )
2814
2999
  }
@@ -3260,6 +3445,19 @@ const usageCmd: CommandHandler = (ctx) => {
3260
3445
  }
3261
3446
 
3262
3447
  const apiTotal = summary.apiInputTokens + summary.apiOutputTokens
3448
+ // 缓存读/写单独一行:它们不在 inputTokens 里(四桶不相交),不列出来就等于
3449
+ // 告诉用户这次会话没走缓存。
3450
+ const cacheRead = summary.apiCacheReadTokens ?? 0
3451
+ const cacheWrite = summary.apiCacheWriteTokens ?? 0
3452
+ const billedInput = summary.apiInputTokens + cacheRead + cacheWrite
3453
+ const cacheLine =
3454
+ cacheRead > 0 || cacheWrite > 0
3455
+ ? `\n${t('commands.usage.cache_tokens', {
3456
+ read: cacheRead.toLocaleString(),
3457
+ write: cacheWrite.toLocaleString(),
3458
+ ratio: billedInput > 0 ? ((cacheRead / billedInput) * 100).toFixed(1) : '0.0',
3459
+ })}`
3460
+ : ''
3263
3461
  const apiLine =
3264
3462
  summary.apiInputTokens > 0 || summary.apiOutputTokens > 0
3265
3463
  ? t('commands.usage.api_tokens', {
@@ -3281,7 +3479,7 @@ const usageCmd: CommandHandler = (ctx) => {
3281
3479
  return {
3282
3480
  content: stripIndent`
3283
3481
  ${t('commands.usage.title')}
3284
- ${apiLine}
3482
+ ${apiLine}${cacheLine}
3285
3483
  ${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokensShown.toLocaleString(), pct })}
3286
3484
  ${t('commands.usage.messages_line', { count: String(msgs.length) })}
3287
3485
  ${t('commands.usage.provider_line', { provider: ctx.providerId })}
@@ -7528,7 +7726,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7528
7726
  '/crsi inventory': 'Live capability self-report — CRSI/SIS/constitution state',
7529
7727
  '/crsi modify': 'Run a code self-modification through the sandbox (worktree → tests → approve)',
7530
7728
  '/crsi propose':
7531
- '固化 CRSI 失败信号(默认教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7729
+ '固化 CRSI 失败信号(默认教训 / --pending 收件箱自动产出的教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7532
7730
  '/crsi prose-clear': '清空散文提议去重 ledger(~/.mipham/crsi/prose-proposals.jsonl)',
7533
7731
  '/crsi eval': 'Run the ground-truth CRSI eval harness and record the score',
7534
7732
  '/crsi bench':
@@ -27,6 +27,17 @@ function sameStats(a: GraftStats | null, b: GraftStats | null): boolean {
27
27
  /** 重读间隔。与 `goal-progress` / `workflow-progress` 同法(那两处也是 1s 一拍)。 */
28
28
  const STATS_REFRESH_MS = 1000
29
29
 
30
+ /**
31
+ * 会话计费 token 的紧凑写法:`999 tok` / `12.3k tok` / `1.2M tok`。
32
+ * 页脚是单行,四位以上的原数会把 `ctx` 与 `last:` 挤出去。
33
+ */
34
+ export function formatCompactTokens(tokens: number): string {
35
+ const trim = (v: number): string => v.toFixed(1).replace(/\.0$/, '')
36
+ if (tokens < 1_000) return `${tokens} tok`
37
+ if (tokens < 1_000_000) return `${trim(tokens / 1_000)}k tok`
38
+ return `${trim(tokens / 1_000_000)}M tok`
39
+ }
40
+
30
41
  /**
31
42
  * Bottom-of-screen graft status line — mirrors graft's own "◤ graft · …" bar:
32
43
  * ◤ graft · N nodes / E edges · ✓ synced · ~T tok saved
@@ -43,7 +54,16 @@ const STATS_REFRESH_MS = 1000
43
54
  * 其余同前:tok-saved 每次渲染实时读;只在有 graft 图或有已知 ctx% 时渲染 —— ctx% 行
44
55
  * 在本目录没建过 graft 时也照常显示。
45
56
  */
46
- export function GraftStatusLine({ cwd, ctxPct }: { cwd: string; ctxPct?: number }) {
57
+ export function GraftStatusLine({
58
+ cwd,
59
+ ctxPct,
60
+ tokens,
61
+ }: {
62
+ cwd: string
63
+ ctxPct?: number
64
+ /** 本会话的计费 token 合计(四桶)。0/undefined ⇒ 不显示,不以 0 tok 冒充。 */
65
+ tokens?: number
66
+ }) {
47
67
  const [stats, setStats] = useState(() => findGraftStats(cwd))
48
68
 
49
69
  useEffect(() => {
@@ -54,13 +74,15 @@ export function GraftStatusLine({ cwd, ctxPct }: { cwd: string; ctxPct?: number
54
74
  return () => clearInterval(timer)
55
75
  }, [cwd])
56
76
  const showCtx = typeof ctxPct === 'number'
57
- if (!stats && !showCtx) return null
77
+ const showTokens = typeof tokens === 'number' && tokens > 0
78
+ if (!stats && !showCtx && !showTokens) return null
58
79
  const fresh = stats ? freshnessSegment(stats) : null
59
80
  const saved = getGraftSavings()
60
81
  const lastFile = stats?.lastFile ? basename(stats.lastFile) : null
61
82
 
62
83
  const bottom: string[] = []
63
84
  if (typeof ctxPct === 'number') bottom.push(`ctx ${ctxPct}%`)
85
+ if (showTokens) bottom.push(formatCompactTokens(tokens))
64
86
  if (lastFile) bottom.push(`last: ${lastFile}`)
65
87
 
66
88
  return (