@miphamai/cli 0.85.48 → 0.85.50

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.
@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs'
3
3
  import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
4
4
  import { sanitizeCommand } from '../../shared/sanitize.ts'
5
5
  import { DANGEROUS_GIT_PATTERNS } from './git.ts'
6
+ import { getMetrics } from '../../core/metrics'
6
7
  import { isUncOrDevicePath, isWithin } from '../../security/path.ts'
7
8
  import { findWorktreeMarker } from '../../core/paths.ts'
8
9
  import { splitShellSegments, expandKnownPathVars } from '../../core/permission-rules'
@@ -156,7 +157,21 @@ function normalizeEscapes(command: string): string {
156
157
  )
157
158
  }
158
159
 
159
- export function isBlocked(command: string): string | null {
160
+ type BlockReason = 'blocked-command' | 'dangerous-git' | 'unc-path' | 'blocked-pattern'
161
+
162
+ interface BlockVerdict {
163
+ reason: BlockReason
164
+ message: string
165
+ }
166
+
167
+ /**
168
+ * Classify a command against the static policy, keeping *which* rule fired.
169
+ *
170
+ * The reason is the point: a bare "rejected by security policy" is
171
+ * indistinguishable from the SIS / permission gates, so whoever reports on the
172
+ * rejection has to guess — and named the wrong subsystem on 2026-11-26.
173
+ */
174
+ function classifyBlocked(command: string): BlockVerdict | null {
160
175
  // Normalize ANSI-C escape sequences for defense-in-depth
161
176
  const normalized = normalizeEscapes(command)
162
177
  // P0-1: Also sanitize for permission check (strips invisible chars, normalizes homoglyphs)
@@ -172,7 +187,10 @@ export function isBlocked(command: string): string | null {
172
187
  ...commandWords(sanitized),
173
188
  ]) {
174
189
  if (BLOCKED_COMMANDS.includes(word)) {
175
- return `Command "${word}" rejected by security policy.`
190
+ return {
191
+ reason: 'blocked-command',
192
+ message: `Command "${word}" rejected by security policy.`,
193
+ }
176
194
  }
177
195
  }
178
196
 
@@ -184,7 +202,10 @@ export function isBlocked(command: string): string | null {
184
202
  if (/(?:^|[\s;&|])(?:sudo\s+)?git\s+/.test(normalized)) {
185
203
  for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
186
204
  if (pattern.test(normalized)) {
187
- return `Dangerous git command blocked: "${description}". Run manually if intended.`
205
+ return {
206
+ reason: 'dangerous-git',
207
+ message: `Dangerous git command blocked: "${description}". Run manually if intended.`,
208
+ }
188
209
  }
189
210
  }
190
211
  }
@@ -192,19 +213,30 @@ export function isBlocked(command: string): string | null {
192
213
  // Reject UNC / device-namespace paths — accessing one triggers SMB negotiation
193
214
  // on Windows and silently leaks NTLM credentials (Claude Code 2.1.233 CVE-class fix).
194
215
  if (isUncOrDevicePath(command) || isUncOrDevicePath(normalized) || isUncOrDevicePath(sanitized)) {
195
- return `Command rejected: references a UNC or device-namespace path (blocked to prevent NTLM credential leakage).`
216
+ return {
217
+ reason: 'unc-path',
218
+ message: `Command rejected: references a UNC or device-namespace path (blocked to prevent NTLM credential leakage).`,
219
+ }
196
220
  }
197
221
 
198
222
  // Check dangerous patterns (on original, normalized, and sanitized)
199
223
  for (const pattern of BLOCKED_PATTERNS) {
200
224
  if (pattern.test(command) || pattern.test(normalized) || pattern.test(sanitized)) {
201
- return 'Command rejected by security policy.'
225
+ return {
226
+ reason: 'blocked-pattern',
227
+ message: `Command rejected by security policy (pattern: ${pattern.source}).`,
228
+ }
202
229
  }
203
230
  }
204
231
 
205
232
  return null // safe
206
233
  }
207
234
 
235
+ /** The user-facing rejection message, or null when the command may run. */
236
+ export function isBlocked(command: string): string | null {
237
+ return classifyBlocked(command)?.message ?? null
238
+ }
239
+
208
240
  /**
209
241
  * Git commands that rewrite refs a worktree **shares with the main checkout**.
210
242
  *
@@ -890,9 +922,12 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
890
922
  }
891
923
 
892
924
  // Security: check command against deny list
893
- const blockedReason = isBlocked(command)
894
- if (blockedReason) {
895
- return { success: false, content: '', error: blockedReason }
925
+ // Counted at the enforcement point, not inside `isBlocked`: the red team and
926
+ // tests call `isBlocked` for diagnosis, and those are not real blocks.
927
+ const blocked = classifyBlocked(command)
928
+ if (blocked) {
929
+ getMetrics().policyBlockInterceptions.inc({ reason: blocked.reason })
930
+ return { success: false, content: '', error: blocked.message }
896
931
  }
897
932
 
898
933
  try {
package/src/ui/chat.tsx CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  stripControlCharsForDisplay,
10
10
  } from '../shared/sanitize'
11
11
  import { homedir } from 'node:os'
12
+ import { isCompactionSummary } from '../core/session-log'
12
13
  import type { UpdateStatus } from '../shared/update'
13
14
 
14
15
  interface ChatPanelProps {
@@ -164,7 +165,14 @@ const MessageRow = React.memo(
164
165
  </Box>
165
166
  ) : (
166
167
  <>
167
- {msg.role === 'user' ? (
168
+ {isCompactionSummary(msg) ? (
169
+ // The summary is stored as a user message (that is the role the
170
+ // model reads it in), but showing it under the user label made a
171
+ // resumed session claim the user had typed the whole thing.
172
+ <Text bold color="yellow">
173
+ ⚑ {t('ui.compaction.role_label')}:
174
+ </Text>
175
+ ) : msg.role === 'user' ? (
168
176
  <Text bold color="green">
169
177
  ▸ {displayCwd()}:
170
178
  </Text>
@@ -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'
@@ -1166,7 +1180,34 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
1166
1180
  }
1167
1181
 
1168
1182
  const crsiInventoryCmd: CommandHandler = async (ctx) => {
1169
- return { content: buildCapabilityReport(ctx.engine) }
1183
+ // Ledger numbers are loaded here, not in the builder: the report stays pure,
1184
+ // and every ledger row can carry the timestamp of the record it came from.
1185
+ const ledgers: CapabilityLedgers = {}
1186
+
1187
+ const evalEntry = getLastEvalEntry('mechanism-sentinel')
1188
+ if (evalEntry) ledgers.lastEval = evalEntry
1189
+
1190
+ const improvements = readImprovements()
1191
+ if (improvements.length > 0) {
1192
+ const verdicts: Record<string, number> = {}
1193
+ for (const record of improvements) {
1194
+ verdicts[record.verdict] = (verdicts[record.verdict] ?? 0) + 1
1195
+ }
1196
+ const latest = improvements.reduce((a, b) => (a.timestamp >= b.timestamp ? a : b))
1197
+ ledgers.improvements = {
1198
+ count: improvements.length,
1199
+ verdicts,
1200
+ latestTimestamp: latest.timestamp,
1201
+ }
1202
+ }
1203
+
1204
+ const probations = readProbations()
1205
+ if (probations.length > 0) {
1206
+ const latest = probations.reduce((a, b) => (a.timestamp >= b.timestamp ? a : b))
1207
+ ledgers.probation = { count: probations.length, latestTimestamp: latest.timestamp }
1208
+ }
1209
+
1210
+ return { content: buildCapabilityReport(ctx.engine, ledgers) }
1170
1211
  }
1171
1212
 
1172
1213
  /**
@@ -1444,7 +1485,12 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1444
1485
  return { content: '⚠️ 已有待批准的修改。先 /crsi modify --approve 或 --reject。' }
1445
1486
  }
1446
1487
 
1447
- const insights = ctx.engine.getAutoMemory?.()?.accumulatedInsights ?? []
1488
+ // 本次会话的洞察 + 收件箱里的历史信号:重启后 `accumulatedInsights` 为空,
1489
+ // 但收件箱不会 —— 否则「学习」仍然要求失败与 propose 发生在同一个进程里。
1490
+ const insights = [
1491
+ ...(ctx.engine.getAutoMemory?.()?.accumulatedInsights ?? []),
1492
+ ...pendingToInsights(readSignals()),
1493
+ ]
1448
1494
  let metaRules: Parameters<typeof produceCrsiProposal>[1] = []
1449
1495
  try {
1450
1496
  metaRules = ctx.engine.getMetaRuleEngine?.()?.analyze().metaRules ?? []
@@ -1463,6 +1509,53 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1463
1509
  // 非 git 目录 → 回退 cwd
1464
1510
  }
1465
1511
 
1512
+ // ── 收件箱路径:/crsi propose --pending ──
1513
+ // 启动时 `refreshPendingLessons` 已把收件箱里尚未并入的信号渲染成 pending 文件
1514
+ // (不需要人在场)。这里只负责把它送进沙箱 gate 与人类审阅 —— 合并仍要批准。
1515
+ if (args[0] === '--pending') {
1516
+ const pendingContent = readPendingLessons()
1517
+ if (!pendingContent.trim()) {
1518
+ return { content: '没有待并入的教训 —— 收件箱为空,或它们都已并入 crsi-lessons.md。' }
1519
+ }
1520
+
1521
+ const { existsSync, readFileSync } = await import('node:fs')
1522
+ const { join } = await import('node:path')
1523
+ // `root` 来自 `git rev-parse`;那条命令在测试里被 mock、也可能在非 git 目录失败。
1524
+ // 读侧允许从 cwd 向上找 —— 而提案里的 `filePath` 仍是仓库根相对路径。
1525
+ const fromRoot = join(root, LESSONS_FILE)
1526
+ const lessonsPath = existsSync(fromRoot) ? fromRoot : findLessonsFile(process.cwd())
1527
+ if (!lessonsPath) {
1528
+ return { content: `❌ 找不到 ${LESSONS_FILE}(当前目录不是 mipham-code 仓库?)。` }
1529
+ }
1530
+ const current = readFileSync(lessonsPath, 'utf-8')
1531
+
1532
+ // 按标题逐块去重:pending 是派生视图,可能比 lessons 慢一拍(刚合并完还没重新渲染)。
1533
+ const fresh = splitLessonBlocks(pendingContent).filter(
1534
+ (block) => !current.includes(block.split('\n', 1)[0]!),
1535
+ )
1536
+ if (fresh.length === 0) {
1537
+ return { content: 'pending 里的教训都已并入 crsi-lessons.md。' }
1538
+ }
1539
+
1540
+ const result = await runCrsiModification({
1541
+ description: `CRSI inbox: ${fresh.length} 条收件箱教训`,
1542
+ filePath: LESSONS_FILE,
1543
+ originalContent: current,
1544
+ newContent: `${current.trimEnd()}\n\n${fresh.join('\n')}\n`,
1545
+ blastRadius: [LESSONS_FILE],
1546
+ })
1547
+ if (!result.applied || result.phase === 'failed') {
1548
+ return { content: `❌ 生成失败(phase: ${result.phase})。\n${result.error ?? ''}` }
1549
+ }
1550
+ return {
1551
+ content:
1552
+ `✅ 已把 ${fresh.length} 条收件箱教训送进沙箱并跑过测试。审阅 diff:\n` +
1553
+ renderGateNote(result) +
1554
+ `\n${result.diff}\n\n` +
1555
+ '/crsi modify --approve 合并 | /crsi modify --reject 丢弃',
1556
+ }
1557
+ }
1558
+
1466
1559
  // ── 散文提议路径:/crsi propose --prose 用 LLM 生成改 skill 散文提议 ──
1467
1560
  if (args[0] === '--prose') {
1468
1561
  const skillFiles = collectSkillFiles(root)
@@ -1708,7 +1801,12 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1708
1801
  current = ''
1709
1802
  }
1710
1803
 
1711
- const proposal = produceCrsiProposal(insights, metaRules, current, new Date().toISOString())
1804
+ // 已并入的教训不参与「选最佳信号」。否则最好那条(critical 优先)刚好已并入时,
1805
+ // `produceCrsiProposal` 的幂等判断会让它返回 null —— 排在后面的可学信号一起被挡。
1806
+ const freshInsights = insights.filter(
1807
+ (i) => !current.includes(`## ${i.category}: ${i.description}`),
1808
+ )
1809
+ const proposal = produceCrsiProposal(freshInsights, metaRules, current, new Date().toISOString())
1712
1810
 
1713
1811
  if (!proposal) {
1714
1812
  return { content: '没有足够的失败信号(autoApplicable insight 或高置信元规则)来生成教训。' }
@@ -2244,7 +2342,7 @@ const sisErrorsCmd: CommandHandler = (ctx) => {
2244
2342
  lines.push(`- ${statusIcon} \`${sig.id}\` [${sig.category}] ${sig.toolName}`)
2245
2343
  lines.push(` 模式: \`${sig.pattern.slice(0, 80)}${sig.pattern.length > 80 ? '...' : ''}\``)
2246
2344
  lines.push(
2247
- ` 修复: ${sig.fixStrategy} → ${sig.fixAction.slice(0, 60)} | 发生 ${sig.occurrences} 次 | 成功率 ${Math.round(sig.successRate * 100)}%`,
2345
+ ` 修复: ${sig.fixStrategy} → ${sig.fixAction.slice(0, 60)} | 发生 ${sig.occurrences} 次 | 成功率 ${formatFixRate(sig)}`,
2248
2346
  )
2249
2347
  lines.push('')
2250
2348
  }
@@ -2264,7 +2362,9 @@ const sisStatsCmd: CommandHandler = (ctx) => {
2264
2362
  lines.push(
2265
2363
  `🟢 活跃: ${stats.active} | 🟡 降级: ${stats.degraded} | ⚫ 已退役: ${stats.retired}`,
2266
2364
  )
2267
- lines.push(`平均成功率: ${Math.round(stats.avgSuccessRate * 100)}%`)
2365
+ lines.push(
2366
+ `平均成功率: ${stats.fixable > 0 ? `${Math.round(stats.avgSuccessRate * 100)}%` : '—(无可自动修复签名)'}`,
2367
+ )
2268
2368
  lines.push(`总拦截次数: ${stats.totalInterceptions}`)
2269
2369
 
2270
2370
  const active = db.getActive()
@@ -2275,9 +2375,7 @@ const sisStatsCmd: CommandHandler = (ctx) => {
2275
2375
  lines.push('|------|------|------|--------|')
2276
2376
  for (const s of active) {
2277
2377
  const icon = s.status === 'active' ? '🟢' : '🟡'
2278
- lines.push(
2279
- `| ${s.id} | ${icon} ${s.status} | ${s.occurrences} | ${Math.round(s.successRate * 100)}% |`,
2280
- )
2378
+ lines.push(`| ${s.id} | ${icon} ${s.status} | ${s.occurrences} | ${formatFixRate(s)} |`)
2281
2379
  }
2282
2380
  }
2283
2381
 
@@ -2421,14 +2519,16 @@ const crsiInterpretCmd: CommandHandler = (ctx, args) => {
2421
2519
  '',
2422
2520
  )
2423
2521
  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))
2522
+ const fixable = isAutoFixable(sig)
2523
+ const bar = fixable
2524
+ ? '█'.repeat(Math.round(sig.successRate * 10)) +
2525
+ '░'.repeat(10 - Math.round(sig.successRate * 10))
2526
+ : ''
2427
2527
  lines.push(`- **${sig.toolName}**: \`${sig.pattern.slice(0, 60)}\``)
2428
2528
  lines.push(
2429
2529
  t('commands.crsi_interpret.sig_success', {
2430
2530
  bar,
2431
- pct: String(Math.round(sig.successRate * 100)),
2531
+ pct: formatFixRate(sig),
2432
2532
  occurrences: String(sig.occurrences),
2433
2533
  strategy: sig.fixStrategy,
2434
2534
  }),
@@ -2808,7 +2908,7 @@ const bugReportCmd: CommandHandler = async (ctx) => {
2808
2908
  pattern: sig.pattern,
2809
2909
  category: sig.category,
2810
2910
  occurrences: String(sig.occurrences),
2811
- pct: (sig.successRate * 100).toFixed(0),
2911
+ pct: formatFixRate(sig),
2812
2912
  }),
2813
2913
  )
2814
2914
  }
@@ -7528,7 +7628,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7528
7628
  '/crsi inventory': 'Live capability self-report — CRSI/SIS/constitution state',
7529
7629
  '/crsi modify': 'Run a code self-modification through the sandbox (worktree → tests → approve)',
7530
7630
  '/crsi propose':
7531
- '固化 CRSI 失败信号(默认教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7631
+ '固化 CRSI 失败信号(默认教训 / --pending 收件箱自动产出的教训 / --rule 受管理规则 / --prose 改 skill 散文),沙箱 + 人批准门控',
7532
7632
  '/crsi prose-clear': '清空散文提议去重 ledger(~/.mipham/crsi/prose-proposals.jsonl)',
7533
7633
  '/crsi eval': 'Run the ground-truth CRSI eval harness and record the score',
7534
7634
  '/crsi bench':
package/src/ui/input.tsx CHANGED
@@ -530,7 +530,16 @@ export function InputBar({
530
530
  }
531
531
  // Idle → clear the draft (the intuitive "cancel"), keeping it recoverable:
532
532
  // Up from the now-empty input restores it (see the arrow-key branch).
533
- if (valueRef.current) clearedDraftRef.current = valueRef.current
533
+ // While browsing history, the text on screen is a recalled entry, not the
534
+ // user's draft — save the *draft* slot instead, or Escape overwrites the
535
+ // only copy of what they were typing with an old prompt.
536
+ if (historyIndexRef.current === -1) {
537
+ if (valueRef.current) clearedDraftRef.current = valueRef.current
538
+ } else if (savedDraftRef.current) {
539
+ clearedDraftRef.current = savedDraftRef.current
540
+ }
541
+ historyIndexRef.current = -1
542
+ savedDraftRef.current = ''
534
543
  setValue('')
535
544
  valueRef.current = ''
536
545
  clearSuggestion()
@@ -605,6 +614,16 @@ export function InputBar({
605
614
  return
606
615
  }
607
616
 
617
+ // Editing a recalled entry ends browsing but must not destroy the text
618
+ // that was there before the recall. Down brings that draft back instead of
619
+ // being a no-op (the entry used to blank `savedDraft` on the first edit).
620
+ if (key.downArrow && historyIndexRef.current === -1 && savedDraftRef.current) {
621
+ const restored = savedDraftRef.current
622
+ savedDraftRef.current = ''
623
+ setValue(restored)
624
+ return
625
+ }
626
+
608
627
  const result = navigateHistory(
609
628
  {
610
629
  history,
@@ -698,10 +717,11 @@ export function InputBar({
698
717
  <MiphamTextInput
699
718
  value={value}
700
719
  onChange={(val) => {
701
- // Reset history browsing when user starts typing
720
+ // Reset history browsing when user starts typing. `savedDraft` is
721
+ // deliberately kept: it is the only copy of what they were writing
722
+ // before the recall, and Down restores it (see the arrow branch).
702
723
  if (historyIndexRef.current !== -1) {
703
724
  historyIndexRef.current = -1
704
- savedDraftRef.current = ''
705
725
  }
706
726
  // ── Ghost-text 自动补全:每次输入清 suggestion + 重排防抖 ──
707
727
  setSuggestion(null)
package/src/ui/picker.tsx CHANGED
@@ -45,7 +45,14 @@ export function ModelPicker({
45
45
  const idx = providers.findIndex((p) => p.id === currentProvider)
46
46
  return idx >= 0 ? idx : 0
47
47
  })
48
- const modelIdx = useKeyState(0)
48
+ // Seed the model cursor on the model the session is actually using, so Tab
49
+ // into the model panel lands on it (it used to start at row 0).
50
+ const modelIdx = useKeyState(() => {
51
+ const provider = providers.find((p) => p.id === currentProvider)
52
+ const models = provider ? activeModels(provider) : []
53
+ const idx = models.findIndex((m) => m.id === currentModel)
54
+ return idx >= 0 ? idx : 0
55
+ })
49
56
 
50
57
  const selectedProvider = providers[providerIdx.value]
51
58
  const models = selectedProvider ? activeModels(selectedProvider) : []
@@ -54,10 +61,15 @@ export function ModelPicker({
54
61
  const goToProvider = useCallback(
55
62
  (idx: number) => {
56
63
  providerIdx.set(wrap(idx, providers.length))
57
- modelIdx.set(0)
64
+ // Land on the session's current model when this is its provider; any
65
+ // other provider stays at row 0.
66
+ const provider = providers[wrap(idx, providers.length)]
67
+ const models = provider ? activeModels(provider) : []
68
+ const current = models.findIndex((m) => m.id === currentModel)
69
+ modelIdx.set(current >= 0 ? current : 0)
58
70
  activePanel.set('model') // auto-switch to model panel
59
71
  },
60
- [providers.length, providerIdx, modelIdx],
72
+ [providers, providerIdx, modelIdx, currentModel],
61
73
  )
62
74
 
63
75
  /** 相对移动 —— 按 `read()` 叠加,同一拍里的两次 ↓ 就是两步。 */