@miphamai/cli 0.85.39 → 0.85.41

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.
@@ -123,11 +123,8 @@ export const webSearchTool: ToolDefinition = {
123
123
  '',
124
124
  '3. Restart Mipham Code and try again.',
125
125
  '',
126
- 'Alternatives (add API key for any):',
127
- ' TAVILY_API_KEY — https://tavily.com',
128
- ' SERPAPI_API_KEY — https://serpapi.com',
129
- '',
130
126
  'No API key? Use the web-access skill (CDP through your logged-in Chrome) for live web search.',
127
+ 'Do not scrape search-engine result pages with WebFetch/curl — they answer 403/429 or a captcha.',
131
128
  ].join('\n'),
132
129
  }
133
130
  }
package/src/ui/app.tsx CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  } from '../agent/cross-session/discovery'
30
30
  import { ChatPanel } from './chat'
31
31
  import { InputBar } from './input'
32
+ import { recordKeyEvent, recordRenderCommit } from './input-debug'
32
33
  import { ModelPicker } from './picker'
33
34
  import { CopyPicker, type CopyPickerItem } from './copy-picker'
34
35
  import { AgentFooter, type AgentEntry } from './agent-footer'
@@ -1388,7 +1389,14 @@ export function App({
1388
1389
  // Ctrl+C 的「再按一次才退」,语义与计时器见 ui/ctrl-c-confirm.ts
1389
1390
  const ctrlC = useCtrlCConfirm()
1390
1391
 
1392
+ // 诊断(`MIPHAM_DEBUG_INPUT=1`):冻结时区分「输入没送达」与「送达但没渲染」。
1393
+ // 默认关闭时只是一次缓存布尔判断,见 ui/input-debug.ts。
1394
+ useEffect(() => {
1395
+ recordRenderCommit()
1396
+ })
1397
+
1391
1398
  useInput((input, key) => {
1399
+ recordKeyEvent(input, key)
1392
1400
  // Ctrl+C:先关最上面那一层;没得关时**不退出**,只提示「再按一次」。
1393
1401
  //
1394
1402
  // 从前这里没有这个分支,而 Ink 自己的 Ctrl+C 处理(`exitOnCtrlC`,默认
@@ -25,7 +25,14 @@ import { miphamHome, workflowScriptDir, workflowScriptDirs, worktreeRoot } from
25
25
  import { fixDoctor, fixConfig, fixCache, selectRepoClaudeFiles } from '../core/fix'
26
26
  import { fixCodeTarget } from '../core/fix-code'
27
27
  import { homedir } from 'node:os'
28
- import { runCrsiModification, approvePending, rejectPending, hasPending } from '../core/crsi-modify'
28
+ import {
29
+ runCrsiModification,
30
+ approvePending,
31
+ rejectPending,
32
+ hasPending,
33
+ setPendingProbation,
34
+ } from '../core/crsi-modify'
35
+ import { settleProbation, formatProbationLines, PROBATION_WINDOW } from '../core/probation'
29
36
  import {
30
37
  produceCrsiProposal,
31
38
  produceRuleProposal,
@@ -61,7 +68,9 @@ import {
61
68
  runTaskPerformance,
62
69
  measureSkillDeltaRepeated,
63
70
  stripCodeFences,
71
+ loadPerformanceTasks,
64
72
  } from '../core/task-performance'
73
+ import { measureCapture, measureSealed } from '../core/capture-measure'
65
74
  import { randomUUID } from 'node:crypto'
66
75
  import {
67
76
  buildImprovementReport,
@@ -1075,6 +1084,9 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
1075
1084
  }
1076
1085
  }
1077
1086
 
1087
+ // ── 试用期:未结窗口也打出来(「开了没读数」与「从未开窗」不同形) ──
1088
+ lines.push(...formatProbationLines())
1089
+
1078
1090
  return { content: lines.join('\n') }
1079
1091
  }
1080
1092
 
@@ -1111,9 +1123,19 @@ async function measureModification(
1111
1123
  ): Promise<string> {
1112
1124
  const llm = ctx.engine.getLlm() ?? ctx.engine.getRegistry()
1113
1125
  let improvementLine = ''
1126
+ // 先清空:非 skill 文件 / 没量到样本 / 抛错,都不该留下上一轮的基线。
1127
+ setPendingProbation(null)
1114
1128
  try {
1115
1129
  const sample = await measureSkillDeltaRepeated(llm, params)
1116
1130
  if (sample) {
1131
+ // 试用期基线 = 合并后的那一臂(postScores)。窗口问的是「合并后会不会回落」,
1132
+ // 不是「这次改动涨了多少」。没有测量就不开窗(不让旧基线挂到新合并上)。
1133
+ setPendingProbation({
1134
+ filePath: params.filePath,
1135
+ skillName: sample.skillName,
1136
+ baselineScores: sample.postScores,
1137
+ poolSize: loadPerformanceTasks().filter((t) => t.skill === sample.skillName).length,
1138
+ })
1117
1139
  const report = buildImprovementReport(sample, [params.filePath], undefined, {
1118
1140
  // 手工路径没有失败信号,问题键就取「这次想修什么」的规范化描述:
1119
1141
  // 同一句话被反复修时,它们才聚得起来。
@@ -1145,6 +1167,7 @@ async function measureModification(
1145
1167
  }
1146
1168
  } catch {
1147
1169
  // 测量失败(LLM 不可用等)不阻断 modify 流程——改进信号是可选的。
1170
+ setPendingProbation(null)
1148
1171
  }
1149
1172
  return improvementLine
1150
1173
  }
@@ -1156,7 +1179,11 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
1156
1179
  }
1157
1180
  const r = approvePending()
1158
1181
  setPendingVerdict(null)
1159
- return { content: r.success ? `✅ ${r.message}` : `⚠️ ${r.message}` }
1182
+ if (!r.success) return { content: `⚠️ ${r.message}` }
1183
+ const probationNote = r.probationOpened
1184
+ ? `\n🧪 已开启试用期:后续 ${PROBATION_WINDOW} 次同口径重测(同 skill、gate 池、k≥3)后出裁定;退化只提示回退,不自动执行。`
1185
+ : ''
1186
+ return { content: `✅ ${r.message}${probationNote}` }
1160
1187
  }
1161
1188
  if (args[0] === '--reject') {
1162
1189
  const r = rejectPending()
@@ -1653,13 +1680,152 @@ const crsiBenchCmd: CommandHandler = async (ctx, args) => {
1653
1680
  skill = { name: skillName, text: body }
1654
1681
  }
1655
1682
 
1683
+ if (args.includes('--sealed')) {
1684
+ if (!skill) {
1685
+ return {
1686
+ content: '❌ `--sealed` 需要 `--skill <name>`:sealed 是「某份 skill」的留出集。',
1687
+ }
1688
+ }
1689
+ const kIdx = args.indexOf('--k')
1690
+ // 缺省 1:sealed 出的是旁证数,不是裁定数,没必要一上手就烧 k 轮。
1691
+ const k = kIdx >= 0 ? Math.max(1, Number(args[kIdx + 1]) || 1) : 1
1692
+ const s = await measureSealed(llm, { skillName: skill.name, skillText: skill.text, k })
1693
+ const avg = s.off.length > 0 ? s.off.reduce((a, r) => a + r.score, 0) / s.off.length : 0
1694
+ const avgOn = s.on.length > 0 ? s.on.reduce((a, r) => a + r.score, 0) / s.on.length : 0
1695
+ const lines = [
1696
+ `## 🧪 sealed 留出集(skill: ${skill.name}, k=${k})`,
1697
+ '',
1698
+ `off 均分: **${avg.toFixed(1)}/100** · on 均分: **${avgOn.toFixed(1)}/100**`,
1699
+ ]
1700
+ if (!s.oraclePassed) {
1701
+ lines.push('', '❌ 参考解未过自己的冻结测试 ⇒ 该读数不可信(先修题或参考解)。')
1702
+ } else if (s.capture.rate === null) {
1703
+ lines.push(
1704
+ '',
1705
+ `没有率:${s.capture.tasksTotal} 题里没有一道有 headroom(off 已满分)—— 这不是 0。`,
1706
+ )
1707
+ } else {
1708
+ lines.push(
1709
+ '',
1710
+ `rate = ${s.capture.numerator.toFixed(1)}/${s.capture.denominator.toFixed(1)} over ${s.capture.tasksUsed} of ${s.capture.tasksTotal} tasks ⇒ **${(s.capture.rate * 100).toFixed(1)}%**`,
1711
+ )
1712
+ }
1713
+ lines.push(
1714
+ '',
1715
+ 'sealed 不进裁定:不加分、不开试用期 —— 它只答「gate 上的捕获率是不是过拟合」(进裁定 = 把留出集当考场)。',
1716
+ )
1717
+ return { content: lines.join('\n') }
1718
+ }
1719
+
1720
+ if (args.includes('--capture')) {
1721
+ if (!skill) {
1722
+ return {
1723
+ content:
1724
+ '❌ `--capture` 需要 `--skill <name>`:捕获率是「某份 skill 文本吃到了多少上界」。',
1725
+ }
1726
+ }
1727
+ const kIdx = args.indexOf('--k')
1728
+ const k = kIdx >= 0 ? Math.max(1, Number(args[kIdx + 1]) || 3) : 3
1729
+ const m = await measureCapture(llm, { skillName: skill.name, skillText: skill.text, k })
1730
+ const c = m.capture
1731
+ const average = (runs: typeof m.off) =>
1732
+ runs.length > 0 ? runs.reduce((a, r) => a + r.score, 0) / runs.length : 0
1733
+ const all = [...m.off, ...m.on]
1734
+ const tokens = all.every((r) => r.tokensUsed !== undefined)
1735
+ ? all.reduce((a, r) => a + (r.tokensUsed ?? 0), 0)
1736
+ : undefined
1737
+ const lines = [
1738
+ `## 🎯 捕获率(skill: ${skill.name}, k=${k})`,
1739
+ '',
1740
+ `off 均分: **${average(m.off).toFixed(1)}/100** · on 均分: **${average(m.on).toFixed(1)}/100**`,
1741
+ ]
1742
+ if (!m.oraclePassed) {
1743
+ lines.push('', '❌ 参考解未全过自己的冻结测试 ⇒ 上界不可信,**本轮作废**。先修题或参考解。')
1744
+ } else if (c.rate === null) {
1745
+ lines.push(
1746
+ '',
1747
+ `没有率:${c.tasksTotal} 题里没有一道有 headroom(off 已满分)—— 这不是 0,也不是通过。`,
1748
+ )
1749
+ } else {
1750
+ const ci = c.ci
1751
+ ? `; 95% CI ${(c.ci.lo * 100).toFixed(1)}%–${(c.ci.hi * 100).toFixed(1)}%`
1752
+ : '; 区间不可得'
1753
+ lines.push(
1754
+ '',
1755
+ `rate = ${c.numerator.toFixed(1)}/${c.denominator.toFixed(1)} over ${c.tasksUsed} of ${c.tasksTotal} tasks${ci} ⇒ **${(c.rate * 100).toFixed(1)}%**`,
1756
+ )
1757
+ }
1758
+ if (c.noHeadroom.length > 0) lines.push('', `无 headroom: ${c.noHeadroom.join(', ')}`)
1759
+ if (c.dropped.length > 0) lines.push('', `配对剔除: ${c.dropped.join(', ')}`)
1760
+
1761
+ // 正对照(零成本):同一臂喂两侧必须**恰好**得 0。不为 0 ⇒ 臂接反 / 池映射错,
1762
+ // 分子分母再漂亮也是另一个对象的读数。为 null ⇒ on 臂全程无 headroom,本轮没验证到。
1763
+ const controlBroken = m.controlRate !== null && m.controlRate !== 0
1764
+ if (m.controlRate === null) {
1765
+ lines.push('', '正对照: 不可得(off 臂全程无 headroom,本轮本来也没有率)')
1766
+ } else if (controlBroken) {
1767
+ lines.push(
1768
+ '',
1769
+ `❌ 正对照 = **${(m.controlRate * 100).toFixed(1)}%**(应恰为 0)⇒ 分子/分母/臂映射至少有一处接错了,**本轮读数不可信**。`,
1770
+ )
1771
+ }
1772
+
1773
+ // sealed 旁证:只说过拟合,不进任何裁定(设计 §4.3)。
1774
+ const sc = m.sealed.capture
1775
+ if (!m.sealed.oraclePassed) {
1776
+ lines.push('', 'sealed 旁证: 参考解未过自己的冻结测试 ⇒ 不可读')
1777
+ } else if (sc.rate === null) {
1778
+ lines.push('', `sealed 旁证: 无率(${sc.tasksTotal} 题里没有一道有 headroom)`)
1779
+ } else {
1780
+ lines.push(
1781
+ '',
1782
+ `sealed 旁证: **${(sc.rate * 100).toFixed(1)}%**(${sc.tasksUsed}/${sc.tasksTotal} 题;只作过拟合旁证,不进裁定)`,
1783
+ )
1784
+ }
1785
+
1786
+ const unmeasurable = all.filter((r) => !r.measurable).length
1787
+ if (unmeasurable > 0) {
1788
+ lines.push('', `⚠️ ${unmeasurable} 次运行不可测(仪器故障或截断)⇒ 本轮不是一次合格重测`)
1789
+ }
1790
+ lines.push(
1791
+ '',
1792
+ tokens === undefined ? 'RSI Tax: 未测(有运行没报 usage)' : `RSI Tax: ${tokens} tokens`,
1793
+ )
1794
+
1795
+ // 只有 k≥3 才算一次合格重测;k=1 的冒烟永不进观察窗(设计 §4.4)。
1796
+ // 且必须**三项前提同时成立**:参考解可信 · 正对照为 0 · 每轮都可测。否则这一轮
1797
+ // 读数是真的、但描述的不是被测 skill —— 拿它推进观察窗,等于往窗口里掺沙子。
1798
+ const canSettle =
1799
+ k >= 3 && m.oraclePassed && !controlBroken && unmeasurable === 0 && c.rate !== null
1800
+ if (canSettle) {
1801
+ const rec = settleProbation(skill.name, average(m.on))
1802
+ if (rec) {
1803
+ lines.push(
1804
+ '',
1805
+ rec.verdict
1806
+ ? `试用期: ${rec.checks.length}/${PROBATION_WINDOW} → ${rec.verdict}`
1807
+ : `试用期: ${rec.checks.length}/${PROBATION_WINDOW} —— 观察中`,
1808
+ )
1809
+ }
1810
+ } else if (k >= 3) {
1811
+ lines.push('', '试用期: 本轮未推进(观察窗只收前提成立的整轮)')
1812
+ }
1813
+ return { content: lines.join('\n') }
1814
+ }
1815
+
1656
1816
  const report = await runTaskPerformance(llm, skill ? { skill } : undefined)
1657
1817
 
1658
1818
  const lines: string[] = [
1659
1819
  '## 🎯 CRSI 任务表现基准' + (skill ? `(skill: ${skill.name})` : ''),
1660
1820
  '',
1661
1821
  ]
1662
- lines.push(`得分: **${report.score}/100** (${report.passed}/${report.total})`, '')
1822
+ // `measurable === false` 时 score 的 100 是「无题可评分」的占位,不是满分。
1823
+ lines.push(
1824
+ report.measurable
1825
+ ? `得分: **${report.score}/100** (${report.passed}/${report.total})`
1826
+ : `得分: **未测得**(0 道题可评分;${report.total} 题全是仪器故障或截断)`,
1827
+ '',
1828
+ )
1663
1829
  lines.push('| 任务 | 结果 |')
1664
1830
  lines.push('|------|------|')
1665
1831
  for (const r of report.results) {
@@ -7133,7 +7299,8 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7133
7299
  '固化 CRSI 失败信号(默认教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7134
7300
  '/crsi prose-clear': '清空散文提议去重 ledger(~/.mipham/crsi/prose-proposals.jsonl)',
7135
7301
  '/crsi eval': 'Run the ground-truth CRSI eval harness and record the score',
7136
- '/crsi bench': 'Run the LLM task-performance benchmark and report the score',
7302
+ '/crsi bench':
7303
+ 'Run the LLM task-performance benchmark(--capture 出捕获率,--sealed 出留出集旁证,均需 --skill)',
7137
7304
  '/crsi meta': 'RSI Level 3 meta-rule analysis — rules that improve the rules',
7138
7305
  '/crsi interpret': 'Tool-call behavior dashboard — error patterns, usage, health',
7139
7306
  '/crsi critique': 'Enable/disable RLAIF self-critique on tool calls',
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 输入诊断开关:`MIPHAM_DEBUG_INPUT=1`。
3
+ *
4
+ * 「窗口冻结」从进程外看只有一种样子:进程活着、主线程停在 `kevent`、终端还留在
5
+ * raw 模式、按键没有反应。但它至少是两种完全不同的故障:
6
+ *
7
+ * A. 按键**没有送达应用**(stdin 侧:监听被摘掉、流被暂停、子进程抢了 tty)
8
+ * B. 按键送达了,但**没有组件处理或没有渲染**(React 侧:树被替换、handler 早退)
9
+ *
10
+ * 两者的补救方向相反,而进程外无法区分。所以这里在「应用看见每个按键的那一刻」
11
+ * 与「每次提交渲染」各记一笔,按秒汇总成一行写进 `~/.mipham/input-debug.log`:
12
+ *
13
+ * 有 keys、有 renders → 应用在处理(问题在输出/终端侧)
14
+ * 有 keys、无 renders → 渲染死了(B)
15
+ * 一个 key 都没有 → 输入没送达(A)
16
+ *
17
+ * 只记**计数与按键类别**,不记文本内容(与遥测的 no-free-text 约束一致)。
18
+ * 默认关闭;关闭时每条路径只是一次缓存过的布尔判断,不产生任何 I/O。
19
+ */
20
+
21
+ import { statSync, truncateSync } from 'node:fs'
22
+ import { miphamHome } from '../core/paths.ts'
23
+ import { appendRegularFileSync, isRegularFile } from '../shared/regular-file.ts'
24
+
25
+ /** 超过这个大小就在启动时截断:诊断日志不该成为磁盘问题。 */
26
+ const MAX_BYTES = 2 * 1024 * 1024
27
+ /** 汇总行间隔。1s 足够区分「冻结后还有没有活动」。 */
28
+ export const FLUSH_INTERVAL_MS = 1000
29
+
30
+ /** 只取本模块关心的字段,避免把 Ink 的 Key 类型搬进来。 */
31
+ export interface DebugKeyShape {
32
+ ctrl?: boolean
33
+ shift?: boolean
34
+ escape?: boolean
35
+ return?: boolean
36
+ tab?: boolean
37
+ upArrow?: boolean
38
+ downArrow?: boolean
39
+ leftArrow?: boolean
40
+ rightArrow?: boolean
41
+ backspace?: boolean
42
+ delete?: boolean
43
+ }
44
+
45
+ export interface InputDebugOptions {
46
+ /** 写入的文件;默认 `~/.mipham/input-debug.log`。 */
47
+ filePath?: string
48
+ /** 测试注入。 */
49
+ now?: () => number
50
+ pid?: number
51
+ }
52
+
53
+ export interface InputDebug {
54
+ recordKey(input: string, key: DebugKeyShape): void
55
+ recordRender(): void
56
+ /** 把当前窗口的计数写成一行(无新事件时不写)。 */
57
+ flush(): void
58
+ dispose(): void
59
+ }
60
+
61
+ /** 按键的人类可读类别 —— 只有类别,没有文本内容。 */
62
+ export function describeKey(input: string, key: DebugKeyShape): string {
63
+ if (key.ctrl) return `ctrl:${input || '?'}`
64
+ if (key.escape) return 'escape'
65
+ if (key.return) return 'return'
66
+ if (key.tab) return 'tab'
67
+ if (key.upArrow) return 'up'
68
+ if (key.downArrow) return 'down'
69
+ if (key.leftArrow) return 'left'
70
+ if (key.rightArrow) return 'right'
71
+ if (key.backspace) return 'backspace'
72
+ if (key.delete) return 'delete'
73
+ // 整串都可打印才叫文本;混进控制字符(ESC 序列等)就只报长度,
74
+ // 避免把终端逃逸序列原样写进日志。
75
+ const allPrintable = /^[\x20-\x7e\u0080-￿]+$/.test(input)
76
+ return `${allPrintable ? 'text' : 'raw'}:${input.length}`
77
+ }
78
+
79
+ export function createInputDebug(opts: InputDebugOptions = {}): InputDebug {
80
+ const filePath = opts.filePath ?? miphamHome('input-debug.log')
81
+ const now = opts.now ?? Date.now
82
+ const pid = opts.pid ?? process.pid
83
+
84
+ let keys = 0
85
+ let renders = 0
86
+ let bytes = 0
87
+ let last = 'none'
88
+ let dirty = false
89
+
90
+ // 启动标记:一个文件里能分出「这是哪一次进程、从哪一刻开始」。
91
+ try {
92
+ // 只在**普通文件**上截断:`truncateSync` 同样会打开目标,撞上 FIFO 就挂住
93
+ // (见 shared/regular-file.ts 的来由)。
94
+ if (isRegularFile(filePath) && statSync(filePath).size > MAX_BYTES) truncateSync(filePath, 0)
95
+ const wrote = appendRegularFileSync(
96
+ filePath,
97
+ `--- start pid=${pid} at=${new Date(now()).toISOString()} ---\n`,
98
+ )
99
+ if (!wrote) throw new Error('not a regular file')
100
+ } catch {
101
+ // 写不了诊断日志不是运行时错误:静默降级为「不诊断」。
102
+ return {
103
+ recordKey() {},
104
+ recordRender() {},
105
+ flush() {},
106
+ dispose() {},
107
+ }
108
+ }
109
+
110
+ return {
111
+ recordKey(input: string, key: DebugKeyShape): void {
112
+ keys += 1
113
+ bytes += input.length
114
+ last = describeKey(input, key)
115
+ dirty = true
116
+ },
117
+ recordRender(): void {
118
+ renders += 1
119
+ dirty = true
120
+ },
121
+ flush(): void {
122
+ if (!dirty) return
123
+ dirty = false
124
+ const line =
125
+ `${new Date(now()).toISOString()} pid=${pid} ` +
126
+ `keys=${keys} renders=${renders} bytes=${bytes} last=${last}\n`
127
+ try {
128
+ appendRegularFileSync(filePath, line)
129
+ } catch {
130
+ /* 同上:诊断失败不影响主流程 */
131
+ }
132
+ keys = 0
133
+ renders = 0
134
+ bytes = 0
135
+ },
136
+ dispose(): void {
137
+ this.flush()
138
+ },
139
+ }
140
+ }
141
+
142
+ // ── 进程级单例(接线点用;关闭时缓存的 null 让每次调用只是一次比较) ──
143
+
144
+ let singleton: InputDebug | null | undefined
145
+
146
+ export function getInputDebug(): InputDebug | null {
147
+ if (singleton !== undefined) return singleton
148
+ if (process.env.MIPHAM_DEBUG_INPUT !== '1') {
149
+ singleton = null
150
+ return null
151
+ }
152
+ singleton = createInputDebug()
153
+ const timer = setInterval(() => singleton?.flush(), FLUSH_INTERVAL_MS)
154
+ timer.unref?.()
155
+ return singleton
156
+ }
157
+
158
+ export function recordKeyEvent(input: string, key: DebugKeyShape): void {
159
+ getInputDebug()?.recordKey(input, key)
160
+ }
161
+
162
+ export function recordRenderCommit(): void {
163
+ getInputDebug()?.recordRender()
164
+ }