@miphamai/cli 0.85.40 → 0.85.42

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.
@@ -169,7 +169,11 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
169
169
  if (include) rgArgs.push('--glob', include)
170
170
  rgArgs.push(searchPath)
171
171
  try {
172
- const { stdout, timedOut, exitCode } = await runSearch(rgArgs, ctx.cwd, GREP_TIMEOUT_MS)
172
+ const { stdout, stderr, timedOut, exitCode } = await runSearch(
173
+ rgArgs,
174
+ ctx.cwd,
175
+ GREP_TIMEOUT_MS,
176
+ )
173
177
  if (timedOut) {
174
178
  return {
175
179
  success: false,
@@ -200,6 +204,19 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
200
204
  '\n\n(rg exited 2 — some paths unreadable; narrow scope for complete results)',
201
205
  }
202
206
  }
207
+ // The server's own reason, not a guess. A rejected pattern (a literal
208
+ // line break without multiline mode, an unbalanced bracket) is exit 2
209
+ // with empty stdout exactly like a permission error is — and telling
210
+ // the caller "likely permission denied" sends it to narrow a path when
211
+ // what it has to fix is the pattern.
212
+ const reason = stderr.trim()
213
+ if (reason) {
214
+ return {
215
+ success: false,
216
+ content: '',
217
+ error: `rg rejected the search: ${reason.slice(0, 500)}`,
218
+ }
219
+ }
203
220
  return {
204
221
  success: false,
205
222
  content: '',
@@ -50,6 +50,9 @@ function windowFromString(content: string, offset: number, limit: number): strin
50
50
  let lineNo = 0
51
51
  let start = 0
52
52
  while (out.length < limit) {
53
+ // Nothing follows a terminating newline: `"a\nb\n"` has two lines, not
54
+ // three. An empty string has no lines at all.
55
+ if (start >= content.length) break
53
56
  const nl = content.indexOf('\n', start)
54
57
  const end = nl === -1 ? content.length : nl
55
58
  if (lineNo >= offset) out.push(content.slice(start, end))
@@ -149,7 +152,16 @@ function windowFromFd(
149
152
  if (n <= 0) break
150
153
  got += n
151
154
  }
152
- return { lines: out.toString('utf-8', 0, got).split('\n'), complete }
155
+ // A file that ends with a newline has no line after it. `split('\n')` on
156
+ // `"a\nb\n"` yields `['a','b','']`, and formatting that trailing element
157
+ // printed an extra empty numbered line — the caller asked for the file, not
158
+ // for a line the file does not contain. Only the single element produced by
159
+ // the *final* newline is dropped; blank lines inside the file stay.
160
+ if (got === 0) return { lines: [], complete }
161
+ const text = out.toString('utf-8', 0, got)
162
+ const lines = text.split('\n')
163
+ if (out[got - 1] === 0x0a) lines.pop()
164
+ return { lines, complete }
153
165
  }
154
166
 
155
167
  export function createReadTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
@@ -1,7 +1,7 @@
1
1
  import React from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
- import { sanitizeInlineField } from '../shared/sanitize'
4
+ import { safeSlice, sanitizeInlineField } from '../shared/sanitize'
5
5
 
6
6
  /**
7
7
  * 页脚也是本文件通往终端的一道口 —— 且它内插的字全是**模型写出来的**:
@@ -131,7 +131,7 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
131
131
  <Box>
132
132
  <Text color={toolIndicatorColor(activeTool!.name)}>
133
133
  {' '}[{sanitizeInlineField(activeTool!.name)}{' '}
134
- {sanitizeInlineField(activeTool!.detail).slice(0, 60)}
134
+ {safeSlice(sanitizeInlineField(activeTool!.detail), 60)}
135
135
  {animatedDots(tick)}]
136
136
  </Text>
137
137
  <Box flexGrow={1} />
@@ -167,9 +167,13 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
167
167
  const symbol = isRunning ? '◯' : '◼'
168
168
  const symbolColor = isRunning ? 'cyan' : undefined
169
169
 
170
- // Truncate description to keep lines readable
170
+ // Truncate description to keep lines readable. `safeSlice` refuses to end
171
+ // on the high half of a surrogate pair — a plain `slice(0, 80)` there
172
+ // printed a lone surrogate (a garbled glyph) for any emoji on the edge.
171
173
  const desc =
172
- agent.description.length > 80 ? agent.description.slice(0, 80) + '...' : agent.description
174
+ agent.description.length > 80
175
+ ? safeSlice(agent.description, 80) + '...'
176
+ : agent.description
173
177
 
174
178
  return (
175
179
  <Box key={agent.id}>
package/src/ui/chat.tsx CHANGED
@@ -123,7 +123,7 @@ const MessageRow = React.memo(
123
123
  {msg.toolMeta.name ? (
124
124
  <Text color={toolColor(msg.toolMeta.name)}>
125
125
  {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {sanitizeInlineField(msg.toolMeta.name)}
126
- {msg.toolMeta.input ? ` (${display(msg.toolMeta.input).slice(0, 120)})` : ''}
126
+ {msg.toolMeta.input ? ` (${safeSlice(display(msg.toolMeta.input), 120)})` : ''}
127
127
  </Text>
128
128
  ) : null}
129
129
  {/* Tool result line: ⎿ summary text */}
@@ -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',