@miphamai/cli 0.85.34 → 0.85.36

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.
@@ -19,6 +19,7 @@ import { McpClient } from '../mcp/client'
19
19
  import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registry'
20
20
  import { buildCapabilityReport } from '../core/capability-inventory'
21
21
  import { InstructionsLoader } from '../core/instructions'
22
+ import { UNDISPATCHED_EVENTS } from '../core/hooks-config'
22
23
  import { findDerivableSections, DERIVABLE_HINTS } from '../core/claude-md-audit'
23
24
  import { miphamHome, workflowScriptDir, workflowScriptDirs, worktreeRoot } from '../core/paths.ts'
24
25
  import { fixDoctor, fixConfig, fixCache, selectRepoClaudeFiles } from '../core/fix'
@@ -63,6 +64,7 @@ import { randomUUID } from 'node:crypto'
63
64
  import {
64
65
  buildImprovementReport,
65
66
  formatCostLine,
67
+ formatNullModelLine,
66
68
  appendImprovement,
67
69
  readImprovements,
68
70
  improvementRate,
@@ -88,7 +90,9 @@ import { getTelemetryConsent, enableTelemetryNow } from '../telemetry/index'
88
90
  import { NO_ENDPOINT } from '../telemetry/endpoint'
89
91
  import { stripIndent } from './strip-indent.js'
90
92
  import { createT } from '../i18n-core/t'
91
- import type { TranslationMap } from '../i18n-core/types'
93
+ import type { Locale, TranslationMap } from '../i18n-core/types'
94
+ import { SUPPORTED_LOCALES } from '../i18n-core/types'
95
+ import { saveLocalePreference } from '../i18n-core/preference'
92
96
  import enUS from '../i18n-core/locales/en-US.json' with { type: 'json' }
93
97
  import zhCN from '../i18n-core/locales/zh-CN.json' with { type: 'json' }
94
98
 
@@ -101,6 +105,15 @@ const defaultT = createT(enUS as unknown as TranslationMap, zhCN as unknown as T
101
105
  function resolveT(ctx: CommandContext): (key: string, params?: Record<string, string>) => string {
102
106
  return ctx.t && typeof ctx.t === 'function' ? ctx.t : defaultT
103
107
  }
108
+
109
+ /**
110
+ * A remote attach session's state lives on the daemon. Commands that would
111
+ * report success after touching only a local no-op are refused here — the
112
+ * alternative is a confirmation for something that did not happen.
113
+ */
114
+ function attachedRefusal(action: string, detail: string): string {
115
+ return `Cannot ${action}: this session is attached to a daemon. ${detail}`
116
+ }
104
117
  import {
105
118
  initCmd,
106
119
  setupCmd,
@@ -111,7 +124,7 @@ import {
111
124
  promptAuditCmd,
112
125
  trustCmd,
113
126
  } from '../commands/project.js'
114
- import { themeCmd, releaseNotesCmd, ideCmd, terminalSetupCmd } from '../commands/environment.js'
127
+ import { releaseNotesCmd, ideCmd, terminalSetupCmd } from '../commands/environment.js'
115
128
  import { commitCmd, pushCmd, prCmd, issueCmd } from '../commands/git.js'
116
129
  import { suggestDirectories } from '../commands/cd-suggest.js'
117
130
  import { keysCmd } from '../commands/keys'
@@ -133,6 +146,8 @@ export interface CommandContext {
133
146
  setSessionTitle: (title: string) => void
134
147
  setEffort: (level: string) => void
135
148
  setFocusMode: (on: boolean) => void
149
+ /** Current focus-view state — `/focus` toggles from this, not from `true`. */
150
+ getFocusMode?: () => boolean
136
151
  setGoal: (text: string) => void
137
152
  setUltracodeMode: (on: boolean) => void
138
153
  setUpdateStatus: (s: UpdateStatus) => void
@@ -145,6 +160,8 @@ export interface CommandContext {
145
160
  /** i18n translate function — populated from React tree via useI18n().
146
161
  * Falls back to module-level defaultT (en-US) in tests / bootstrap. */
147
162
  t: (key: string, params?: Record<string, string>) => string
163
+ /** Locale the UI is currently mounted with (`/lang` reports this, not a guess). */
164
+ locale?: Locale
148
165
  }
149
166
 
150
167
  export interface CommandResult {
@@ -233,8 +250,7 @@ const helpCmd: CommandHandler = (ctx) => {
233
250
  /providers List configured providers
234
251
  /switch <p> <m> Switch provider and model
235
252
  /config View configuration
236
- /effort <lvl> Set reasoning effort (low|medium|high|xhigh|max)
237
- /theme [dark|light|auto] Set terminal theme
253
+ /effort <lvl> Set the stream stall budget (low|medium|high|xhigh|max)
238
254
  /ollama-refresh Refresh Ollama model list at runtime
239
255
 
240
256
  ── Tools & Skills ──────────────────
@@ -260,7 +276,7 @@ const helpCmd: CommandHandler = (ctx) => {
260
276
  /todos [list|create] Task management
261
277
  /tasks Background tasks
262
278
  /review Code review workflow
263
- /pr-comments PR review summary
279
+ /pr-comments PR comments via gh + branch summary
264
280
  /diff Show git diff
265
281
  /workflows List workflow scripts
266
282
  /loop <int> <p> Run prompt on interval
@@ -273,10 +289,10 @@ const helpCmd: CommandHandler = (ctx) => {
273
289
  /schedule View scheduled tasks
274
290
 
275
291
  ── Git & GitHub ─────────────────────
276
- /commit Review staged changes + commit
277
- /push Push current branch
278
- /pr Create a pull request
279
- /issue File a GitHub issue
292
+ /commit Draft a commit message from staged changes
293
+ /push Show push status and the command to run
294
+ /pr Draft a pull request title and body
295
+ /issue Draft a GitHub issue from your description
280
296
 
281
297
  ── Code Quality ─────────────────────
282
298
  /simplify Review for reuse, quality, simplification
@@ -326,7 +342,7 @@ const versionCmd: CommandHandler = (ctx) => {
326
342
  content: stripIndent`
327
343
  Mipham Code v${ctx.version}
328
344
 
329
- Runtime: Bun ${typeof Bun !== 'undefined' ? Bun.version : '(Node.js)'}
345
+ Runtime: ${typeof Bun !== 'undefined' ? `Bun ${Bun.version}` : `Node.js ${process.version}`}
330
346
  Platform: ${process.platform} ${process.arch}
331
347
  Node: ${process.version}
332
348
  CWD: ${process.cwd()}
@@ -340,6 +356,14 @@ const versionCmd: CommandHandler = (ctx) => {
340
356
  }
341
357
 
342
358
  const clearCmd: CommandHandler = (ctx) => {
359
+ if (ctx.engine.isRemote) {
360
+ return {
361
+ content: attachedRefusal(
362
+ 'clear this conversation',
363
+ 'The conversation lives on the daemon; clearing the local view would leave it untouched.',
364
+ ),
365
+ }
366
+ }
343
367
  ctx.engine.getContext().clear()
344
368
  // The task list outlives the process now, so "start over" has to say so
345
369
  // explicitly — otherwise the old plan comes back on resume and the panel keeps
@@ -356,6 +380,14 @@ const exitCmd: CommandHandler = () => ({ content: '', exit: true })
356
380
  // ═══════════════════════════════════════════════════════════════
357
381
 
358
382
  const compactCmd: CommandHandler = async (ctx) => {
383
+ if (ctx.engine.isRemote) {
384
+ return {
385
+ content: attachedRefusal(
386
+ 'compact here',
387
+ 'The conversation and its context live on the daemon, not in this terminal.',
388
+ ),
389
+ }
390
+ }
359
391
  const t = resolveT(ctx)
360
392
  const context = ctx.engine.getContext()
361
393
  const msgsBefore = context.getMessageCount()
@@ -387,6 +419,14 @@ const compactCmd: CommandHandler = async (ctx) => {
387
419
  }
388
420
 
389
421
  const contextCmd: CommandHandler = (ctx) => {
422
+ if (ctx.engine.isRemote) {
423
+ return {
424
+ content: attachedRefusal(
425
+ 'show context usage here',
426
+ 'The context window is held by the daemon session.',
427
+ ),
428
+ }
429
+ }
390
430
  const t = resolveT(ctx)
391
431
  const c = ctx.engine.getContext()
392
432
  const tokens = c.getEstimatedTokens()
@@ -479,7 +519,7 @@ const statusCmd: CommandHandler = async (ctx) => {
479
519
  ${t('commands.status.session_title')}
480
520
  ${t('commands.status.provider')} ${ctx.providerId}
481
521
  ${t('commands.status.model')} ${ctx.modelId}
482
- ${t('commands.status.messages')} ${c.getMessages().length}
522
+ ${t('commands.status.messages')} ${c.getMessageCount()}
483
523
  ${t('commands.status.tokens')} ~${c.getEstimatedTokens().toLocaleString()} / ${c.getMaxTokens().toLocaleString()}
484
524
  ${t('commands.status.tools')} ${tools.size} ${t('commands.status.loaded')}
485
525
  ${t('commands.status.permission')} ${liveMode(ctx)}
@@ -547,7 +587,7 @@ const modelsCmd: CommandHandler = (ctx) => {
547
587
  }
548
588
  }
549
589
 
550
- const ollamaRefreshCmd: CommandHandler = (ctx) => {
590
+ const ollamaRefreshCmd: CommandHandler = async (ctx) => {
551
591
  const t = resolveT(ctx)
552
592
  const ollamaProvider = ctx.config.providers.find((p) => p.id === 'ollama')
553
593
  if (!ollamaProvider) {
@@ -582,24 +622,60 @@ const ollamaRefreshCmd: CommandHandler = (ctx) => {
582
622
  }
583
623
  }
584
624
 
585
- // 3. Update the in-memory provider model list
586
- ollamaProvider.models = refreshed.map((m) => ({
587
- id: m.id,
588
- name: m.id,
589
- providerId: 'ollama',
590
- contextWindow: 128_000,
591
- maxOutput: 32_000,
592
- vision: false,
593
- status: 'active' as const,
594
- }))
625
+ // 3. Ask Ollama for each model's real context length. A hardcoded 128k made
626
+ // an 8k model look like 128k to /context and the compaction threshold.
627
+ const base = (ollamaProvider.baseUrl || 'http://localhost:11434').replace(/\/$/, '')
628
+ let assumed = 0
629
+ const models = await Promise.all(
630
+ refreshed.map(async (m) => {
631
+ let contextWindow = 0
632
+ try {
633
+ const res = await fetch(`${base}/api/show`, {
634
+ method: 'POST',
635
+ headers: { 'content-type': 'application/json' },
636
+ body: JSON.stringify({ name: m.id }),
637
+ signal: AbortSignal.timeout(1500),
638
+ })
639
+ if (res.ok) {
640
+ const info = (await res.json()) as { model_info?: Record<string, unknown> }
641
+ const key = Object.keys(info.model_info ?? {}).find((k) =>
642
+ k.endsWith('.context_length'),
643
+ )
644
+ const value = key ? Number(info.model_info![key]) : NaN
645
+ if (Number.isFinite(value) && value > 0) contextWindow = value
646
+ }
647
+ } catch {
648
+ // Ollama unreachable / old version — the note below records the assumption.
649
+ }
650
+ if (!contextWindow) {
651
+ contextWindow = 128_000
652
+ assumed++
653
+ }
654
+ return {
655
+ id: m.id,
656
+ name: m.id,
657
+ providerId: 'ollama',
658
+ contextWindow,
659
+ maxOutput: Math.min(32_000, contextWindow),
660
+ vision: false,
661
+ status: 'active' as const,
662
+ }
663
+ }),
664
+ )
665
+ ollamaProvider.models = models
595
666
 
596
667
  const after = refreshed.length
597
668
  const added = after - before
669
+ const note =
670
+ assumed > 0
671
+ ? `\n\n⚠ ${assumed} model(s): context window assumed 128k (Ollama /api/show did not answer).`
672
+ : ''
598
673
  return {
599
- content: t('commands.ollama_refresh.done', {
600
- total: String(after),
601
- added: added > 0 ? `+${added}` : String(added),
602
- }),
674
+ content:
675
+ t('commands.ollama_refresh.done', {
676
+ total: String(after),
677
+ added: added > 0 ? `+${added}` : String(added),
678
+ }) + note,
603
679
  }
604
680
  } catch (err: unknown) {
605
681
  const msg = err instanceof Error ? err.message : String(err)
@@ -692,7 +768,7 @@ const configCmd: CommandHandler = (ctx) => {
692
768
  `version: ${c.version}`,
693
769
  `defaultProvider: ${c.defaultProvider}`,
694
770
  `defaultModel: ${c.defaultModel}`,
695
- `permission: ${c.permission}`,
771
+ `permission: ${c.permission} (configured) — live: ${liveMode(ctx)}`,
696
772
  `showThinking: ${c.showThinking ?? 'off'}`,
697
773
  `showSchedulingNotices: ${c.showSchedulingNotices ?? false}`,
698
774
  `showCommandPicker: ${c.showCommandPicker ?? false}`,
@@ -713,21 +789,18 @@ const configCmd: CommandHandler = (ctx) => {
713
789
  const toolsCmd: CommandHandler = (ctx) => {
714
790
  const t = resolveT(ctx)
715
791
  const tools = ctx.engine.getTools()
716
- const categories: Record<string, string[]> = {
717
- file: [],
718
- exec: [],
719
- agent: [],
720
- network: [],
721
- system: [],
722
- }
792
+ // Group by whatever categories the registry actually declares. A fixed key
793
+ // list silently dropped every tool whose category was added later (artifact,
794
+ // scheduling), while the header still printed `tools.size`.
795
+ const categories = new Map<string, string[]>()
723
796
  for (const [name, tool] of tools) {
724
- categories[tool.category]?.push(
725
- ` ${name.padEnd(14)} ${tool.permission.padEnd(8)} ${tool.description}`,
726
- )
797
+ const items = categories.get(tool.category) ?? []
798
+ items.push(` ${name.padEnd(14)} ${tool.permission.padEnd(8)} ${tool.description}`)
799
+ categories.set(tool.category, items)
727
800
  }
728
- const sections = Object.entries(categories)
729
- .filter(([, v]) => v!.length > 0)
730
- .map(([cat, items]) => `── ${cat.toUpperCase()} ──\n${items!.join('\n')}`)
801
+ const sections = [...categories.entries()].map(
802
+ ([cat, items]) => `── ${cat.toUpperCase()} ──\n${items.join('\n')}`,
803
+ )
731
804
 
732
805
  return {
733
806
  content: `${t('commands.tools.title', { count: String(tools.size) })}\n\n${sections.join('\n\n')}`,
@@ -788,9 +861,17 @@ const crsiDisableCmd: CommandHandler = (ctx, args) => {
788
861
  if (!ruleId) {
789
862
  return { content: 'Usage: /crsi disable <rule-id>' }
790
863
  }
791
- engine.setRuleEnabled(ruleId, false)
864
+ const source = engine.getRule(ruleId)?.source
865
+ if (!engine.setRuleEnabled(ruleId, false)) {
866
+ return { content: `Rule \`${ruleId}\` not found. Use \`/crsi rules\` to see rule ids.` }
867
+ }
868
+ // Builtin/managed rules are source-of-truth and never written to the store.
869
+ const note =
870
+ source === 'builtin' || source === 'managed'
871
+ ? '\n\nThis is a builtin/managed rule: the change is not persisted and reverts on restart.'
872
+ : ''
792
873
  return {
793
- content: `Rule \`${ruleId}\` has been disabled. Use \`/crsi restore ${ruleId}\` to re-enable.`,
874
+ content: `Rule \`${ruleId}\` has been disabled. Use \`/crsi restore ${ruleId}\` to re-enable.${note}`,
794
875
  }
795
876
  }
796
877
 
@@ -836,8 +917,15 @@ const crsiRestoreCmd: CommandHandler = (ctx, args) => {
836
917
  if (!ruleId) {
837
918
  return { content: 'Usage: /crsi restore <rule-id>' }
838
919
  }
839
- engine.setRuleEnabled(ruleId, true)
840
- return { content: `Rule \`${ruleId}\` has been re-enabled.` }
920
+ const source = engine.getRule(ruleId)?.source
921
+ if (!engine.setRuleEnabled(ruleId, true)) {
922
+ return { content: `Rule \`${ruleId}\` not found. Use \`/crsi rules\` to see rule ids.` }
923
+ }
924
+ const note =
925
+ source === 'builtin' || source === 'managed'
926
+ ? '\n\nThis is a builtin/managed rule: the change is not persisted and reverts on restart.'
927
+ : ''
928
+ return { content: `Rule \`${ruleId}\` has been re-enabled.${note}` }
841
929
  }
842
930
 
843
931
  /** Render a tiny ASCII sparkline from a series of 0-1 values (success rates). */
@@ -860,6 +948,7 @@ const crsiStatsCmd: CommandHandler = async (ctx) => {
860
948
  lines.push(`Builtin: ${rules.filter((r) => r.source === 'builtin').length}`)
861
949
  lines.push(`Auto-generated: ${rules.filter((r) => r.source === 'pattern-analyzer').length}`)
862
950
  lines.push(`Manual: ${rules.filter((r) => r.source === 'manual').length}`)
951
+ lines.push(`Managed: ${rules.filter((r) => r.source === 'managed').length}`)
863
952
 
864
953
  const effs = tracker?.allRules ?? []
865
954
  if (effs.length > 0) {
@@ -1011,10 +1100,13 @@ const crsiModifyCmd: CommandHandler = async (ctx, args) => {
1011
1100
  const sign = report.deltaMean >= 0 ? '+' : ''
1012
1101
  // B2 代价维:只展示、不进判定(`formatCostLine` 缺席时返回 null ⇒ 整行不打)。
1013
1102
  const costLine = formatCostLine(report)
1103
+ // 空模型闸:只在闸失败时出声;它解释了 verdict 为什么被降级。
1104
+ const nullLine = formatNullModelLine(report)
1014
1105
  improvementLine =
1015
1106
  `\n📊 改进判定: ${label} (delta ${sign}${report.deltaMean.toFixed(1)}, 噪声 ${report.noise.toFixed(1)}, 阈值 ${report.minEffect.toFixed(1)})` +
1016
1107
  `\n 改进率: ${rate.improved}/${rate.total} (${(rate.rate * 100).toFixed(0)}%, Wilson 95% [${(rate.lo * 100).toFixed(0)}%, ${(rate.hi * 100).toFixed(0)}%])` +
1017
1108
  (costLine ? `\n${costLine}` : '') +
1109
+ (nullLine ? `\n${nullLine}` : '') +
1018
1110
  (report.verdict === 'regressed' ? '\n ⚠️ 任务表现倒退:--approve 将被拒绝。' : '')
1019
1111
  }
1020
1112
  } catch {
@@ -1132,6 +1224,9 @@ const crsiProposeCmd: CommandHandler = async (ctx, args) => {
1132
1224
  // 「局部正确全局遗漏」)。ε 行可以有、代价行可以没有,故各自独立追加。
1133
1225
  const costLine = formatCostLine(report)
1134
1226
  if (costLine) predictionLine += `\n${costLine}`
1227
+ // 空模型闸同理:两条渲染路径都接。
1228
+ const nullLine = formatNullModelLine(report)
1229
+ if (nullLine) predictionLine += `\n${nullLine}`
1135
1230
  }
1136
1231
  } catch {
1137
1232
  // 测量失败(LLM 不可用等)不阻断提案流程 —— 与手工路径 :889 的处置一致。
@@ -1438,19 +1533,28 @@ const crsiHealthCmd: CommandHandler = async (ctx) => {
1438
1533
 
1439
1534
  // ── CRSI Section ──
1440
1535
  lines.push('### 🧠 CRSI 学习子系统', '')
1536
+ // Hoisted for the composite score below — the score must be built from the
1537
+ // same readings the table shows, not re-derived from object presence.
1538
+ let activeRuleCount = 0
1539
+ let interceptions = 0
1540
+ let successes = 0
1541
+ let hasTracker = false
1441
1542
  if (engine) {
1442
1543
  const rules = engine.getActiveRules()
1544
+ activeRuleCount = rules.length
1443
1545
  const builtin = rules.filter((r) => r.source === 'builtin').length
1444
1546
  const auto = rules.filter((r) => r.source === 'pattern-analyzer').length
1445
1547
  const manual = rules.filter((r) => r.source === 'manual').length
1548
+ const managed = rules.filter((r) => r.source === 'managed').length
1446
1549
 
1447
1550
  lines.push(`| 指标 | 值 |`)
1448
1551
  lines.push(`|------|----|`)
1449
- lines.push(`| 活跃规则 | ${rules.length} (内置 ${builtin} · 自动 ${auto} · 手动 ${manual}) |`)
1552
+ lines.push(
1553
+ `| 活跃规则 | ${rules.length} (内置 ${builtin} · 自动 ${auto} · 手动 ${manual} · 受管 ${managed}) |`,
1554
+ )
1450
1555
 
1451
1556
  if (tracker) {
1452
- let interceptions = 0
1453
- let successes = 0
1557
+ hasTracker = true
1454
1558
  for (const r of rules) {
1455
1559
  const eff = tracker.getEffectiveness(r.id)
1456
1560
  if (eff) {
@@ -1495,9 +1599,47 @@ const crsiHealthCmd: CommandHandler = async (ctx) => {
1495
1599
  }
1496
1600
 
1497
1601
  // ── Overall Health Score ──
1602
+ //
1603
+ // Scored from **evidence**, not presence. The previous reading was
1604
+ // `engine ? 50 : 0` — a freshly constructed rule engine that had learned
1605
+ // nothing scored full marks, which made "A — 优秀" reachable by doing no
1606
+ // work at all. Each half is 25 points for having data + 25 for its quality
1607
+ // signal, and the basis is printed so the number can be audited.
1498
1608
  lines.push('', '### 📊 综合健康评分', '')
1499
- const crsiScore = engine ? 50 : 0
1500
- const sisScore = db ? (db.getStats().avgSuccessRate >= 0.8 ? 50 : 25) : 0
1609
+
1610
+ const crsiBasis: string[] = []
1611
+ let crsiScore = 0
1612
+ if (activeRuleCount > 0) {
1613
+ crsiScore += 25
1614
+ crsiBasis.push(`活跃规则 ${activeRuleCount} 条 +25`)
1615
+ } else {
1616
+ crsiBasis.push('无活跃规则 +0')
1617
+ }
1618
+ if (interceptions > 0) {
1619
+ const pts = Math.round((successes / interceptions) * 25)
1620
+ crsiScore += pts
1621
+ crsiBasis.push(`拦截成功 ${successes}/${interceptions} +${pts}`)
1622
+ } else {
1623
+ crsiBasis.push(hasTracker ? '尚无拦截记录 +0' : '无 EffectivenessTracker +0')
1624
+ }
1625
+
1626
+ const sisBasis: string[] = []
1627
+ let sisScore = 0
1628
+ if (db) {
1629
+ const stats = db.getStats()
1630
+ if (stats.total > 0) {
1631
+ sisScore += 25
1632
+ sisBasis.push(`免疫记忆 ${stats.total} 条 +25`)
1633
+ const pts = Math.round(stats.avgSuccessRate * 25)
1634
+ sisScore += pts
1635
+ sisBasis.push(`平均成功率 ${Math.round(stats.avgSuccessRate * 100)}% +${pts}`)
1636
+ } else {
1637
+ sisBasis.push('免疫记忆为空 +0', '无成功率数据 +0')
1638
+ }
1639
+ } else {
1640
+ sisBasis.push('SIS 未初始化 +0')
1641
+ }
1642
+
1501
1643
  const totalScore = crsiScore + sisScore
1502
1644
 
1503
1645
  const grade =
@@ -1514,6 +1656,8 @@ const crsiHealthCmd: CommandHandler = async (ctx) => {
1514
1656
  lines.push(`| CRSI 学习 | ${engine ? '✅ 在线' : '❌ 离线'} | ${crsiScore}/50 |`)
1515
1657
  lines.push(`| SIS 免疫 | ${db ? '✅ 在线' : '❌ 离线'} | ${sisScore}/50 |`)
1516
1658
  lines.push(`| **综合** | **${grade}** | **${totalScore}/100** |`)
1659
+ lines.push('')
1660
+ lines.push(`计分依据:CRSI ${crsiBasis.join(' · ')};SIS ${sisBasis.join(' · ')}`)
1517
1661
 
1518
1662
  return { content: lines.join('\n') }
1519
1663
  }
@@ -1584,7 +1728,7 @@ const crsiMetaCmd: CommandHandler = async (ctx) => {
1584
1728
  lines.push(`- \`${mr.id}\`: ${mr.recommendation}`)
1585
1729
  }
1586
1730
  lines.push('')
1587
- lines.push('使用 `/crsi meta --apply` 自动应用高置信度元规则。')
1731
+ lines.push('元规则只是建议:当前版本不自动应用,请人工复核后固化。')
1588
1732
  }
1589
1733
 
1590
1734
  return { content: lines.join('\n') }
@@ -2428,6 +2572,14 @@ const renameCmd: CommandHandler = (ctx, args) => {
2428
2572
  }
2429
2573
 
2430
2574
  const goalCmd: CommandHandler = (ctx, args) => {
2575
+ if (ctx.engine.isRemote) {
2576
+ return {
2577
+ content: attachedRefusal(
2578
+ 'use /goal here',
2579
+ 'Goals are owned by the daemon session; setting one here would report success without taking effect.',
2580
+ ),
2581
+ }
2582
+ }
2431
2583
  const t = resolveT(ctx)
2432
2584
  const input = args.join(' ')
2433
2585
 
@@ -2516,9 +2668,10 @@ const recapCmd: CommandHandler = (ctx) => {
2516
2668
  const tokens = c.getEstimatedTokens()
2517
2669
  const checkpointCount = c.getCheckpoints().length
2518
2670
 
2671
+ // The label says "recent": take the tail, not the first lines of the session.
2519
2672
  const topics = msgs
2520
2673
  .filter((m) => m.role === 'user' && typeof m.content === 'string')
2521
- .slice(0, 5)
2674
+ .slice(-5)
2522
2675
  .map((m) => {
2523
2676
  const text = typeof m.content === 'string' ? m.content : ''
2524
2677
  return text.length > 80 ? text.slice(0, 80) + '...' : text
@@ -2540,6 +2693,14 @@ const recapCmd: CommandHandler = (ctx) => {
2540
2693
  }
2541
2694
 
2542
2695
  const usageCmd: CommandHandler = (ctx) => {
2696
+ if (ctx.engine.isRemote) {
2697
+ return {
2698
+ content: attachedRefusal(
2699
+ 'show per-tool usage here',
2700
+ 'Tool-level token accounting lives in the daemon session.',
2701
+ ),
2702
+ }
2703
+ }
2543
2704
  const t = resolveT(ctx)
2544
2705
  const c = ctx.engine.getContext()
2545
2706
  const estTokens = c.getEstimatedTokens()
@@ -2962,6 +3123,14 @@ const pluginDisableCmd: CommandHandler = (ctx, args) => {
2962
3123
  // ═══════════════════════════════════════════════════════════════
2963
3124
 
2964
3125
  const rewindCmd: CommandHandler = (ctx) => {
3126
+ if (ctx.engine.isRemote) {
3127
+ return {
3128
+ content: attachedRefusal(
3129
+ 'rewind here',
3130
+ 'Checkpoints are restored in the daemon session, not in this terminal.',
3131
+ ),
3132
+ }
3133
+ }
2965
3134
  const t = resolveT(ctx)
2966
3135
  const c = ctx.engine.getContext()
2967
3136
  const checkpoints = c.getCheckpoints()
@@ -3036,23 +3205,66 @@ const copyCmd: CommandHandler = (ctx, args) => {
3036
3205
  }
3037
3206
  }
3038
3207
 
3208
+ /**
3209
+ * Tracked changes **including staged ones**, plus untracked files.
3210
+ *
3211
+ * `git diff --stat` compares the worktree to the index, so `git add` made every
3212
+ * change invisible — `/review`, `/code-review`, `/simplify`, `/verify` and
3213
+ * `/diff` all reported "no changes" on a fully staged tree. `HEAD` as the base
3214
+ * folds index and worktree into one view; untracked files need `ls-files`
3215
+ * because no `git diff` sees them.
3216
+ */
3217
+ async function readGitChangeSummary(): Promise<{ stat: string; untracked: string[] }> {
3218
+ const { execSync } = await import('node:child_process')
3219
+ let stat = ''
3220
+ try {
3221
+ stat = execSync('git diff --stat HEAD', { encoding: 'utf-8', timeout: 5000 }).trim()
3222
+ } catch {
3223
+ // No HEAD yet (fresh repository) — fall back to the index/worktree diff.
3224
+ stat = execSync('git diff --stat', { encoding: 'utf-8', timeout: 5000 }).trim()
3225
+ }
3226
+ let untracked: string[] = []
3227
+ try {
3228
+ untracked = execSync('git ls-files --others --exclude-standard', {
3229
+ encoding: 'utf-8',
3230
+ timeout: 5000,
3231
+ })
3232
+ .split('\n')
3233
+ .filter(Boolean)
3234
+ } catch {
3235
+ // Not a repository / git unavailable — the stat call above already decided
3236
+ // whether there is anything to report.
3237
+ }
3238
+ return { stat, untracked }
3239
+ }
3240
+
3039
3241
  const diffCmd: CommandHandler = async (_ctx) => {
3040
3242
  const t = resolveT(_ctx)
3041
3243
  try {
3042
3244
  const { execSync } = await import('node:child_process')
3043
- const output = execSync('git diff --stat', { encoding: 'utf-8', timeout: 5000 })
3044
- if (!output.trim()) {
3245
+ const { stat, untracked } = await readGitChangeSummary()
3246
+ if (!stat && untracked.length === 0) {
3045
3247
  return { content: t('commands.diff.clean') }
3046
3248
  }
3047
- // Get full diff but limit to reasonable size
3048
- const fullDiff = execSync('git diff --no-color', { encoding: 'utf-8', timeout: 5000 })
3249
+ // Full diff (staged + unstaged) limited to a readable size; untracked files
3250
+ // have no diff to print, so they are listed.
3251
+ let fullDiff = ''
3252
+ try {
3253
+ fullDiff = execSync('git diff --no-color HEAD', { encoding: 'utf-8', timeout: 5000 })
3254
+ } catch {
3255
+ fullDiff = execSync('git diff --no-color', { encoding: 'utf-8', timeout: 5000 })
3256
+ }
3049
3257
  const MAX_LINES = 60
3050
3258
  const lines = fullDiff.split('\n')
3051
- const truncated =
3259
+ let truncated =
3052
3260
  lines.length > MAX_LINES
3053
3261
  ? lines.slice(0, MAX_LINES).join('\n') +
3054
3262
  `\n\n... (${lines.length - MAX_LINES} more lines. Use git diff to see full output.)`
3055
3263
  : fullDiff
3264
+ if (truncated.trim()) truncated += '\n\n'
3265
+ if (untracked.length > 0) {
3266
+ truncated += `Untracked files:\n${untracked.map((f) => ` ${f}`).join('\n')}`
3267
+ }
3056
3268
 
3057
3269
  return {
3058
3270
  content: `${t('commands.diff.title')}\n\n${truncated}`,
@@ -3069,6 +3281,14 @@ const diffCmd: CommandHandler = async (_ctx) => {
3069
3281
  // ═══════════════════════════════════════════════════════════════
3070
3282
 
3071
3283
  const effortCmd: CommandHandler = (ctx, args) => {
3284
+ if (ctx.engine.isRemote) {
3285
+ return {
3286
+ content: attachedRefusal(
3287
+ 'change effort here',
3288
+ "The daemon chooses the attached session's reasoning effort.",
3289
+ ),
3290
+ }
3291
+ }
3072
3292
  const t = resolveT(ctx)
3073
3293
  const VALID_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max']
3074
3294
  const level = args[0]?.toLowerCase()
@@ -3083,8 +3303,13 @@ const effortCmd: CommandHandler = (ctx, args) => {
3083
3303
 
3084
3304
  const focusCmd: CommandHandler = (ctx) => {
3085
3305
  const t = resolveT(ctx)
3086
- ctx.setFocusMode(true)
3087
- return { content: t('commands.focus.on') }
3306
+ // Toggle from the live state. It used to set `true` unconditionally while
3307
+ // app.tsx intercepted the command — the handler was unreachable, so the bug
3308
+ // was invisible; once the interception is gone it would have made /focus
3309
+ // impossible to turn off.
3310
+ const next = !(ctx.getFocusMode?.() ?? false)
3311
+ ctx.setFocusMode(next)
3312
+ return { content: t(next ? 'commands.focus.on' : 'commands.focus.off') }
3088
3313
  }
3089
3314
 
3090
3315
  // ═══════════════════════════════════════════════════════════════
@@ -3092,6 +3317,14 @@ const focusCmd: CommandHandler = (ctx) => {
3092
3317
  // ═══════════════════════════════════════════════════════════════
3093
3318
 
3094
3319
  const ultracodeCmd: CommandHandler = (ctx, args) => {
3320
+ if (ctx.engine.isRemote) {
3321
+ return {
3322
+ content: attachedRefusal(
3323
+ 'toggle ultracode here',
3324
+ 'The daemon owns the attached session and its system prompt.',
3325
+ ),
3326
+ }
3327
+ }
3095
3328
  const t = resolveT(ctx)
3096
3329
  const arg = args[0]?.toLowerCase()
3097
3330
  if (arg === 'on') {
@@ -3343,8 +3576,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
3343
3576
  or: /loop status Show autonomous loop progress
3344
3577
  or: /loop init [path] Scaffold project vault structure
3345
3578
 
3346
- Fixed interval formats:
3347
- 10s — 10 seconds
3579
+ Fixed interval formats (60s minimum, 1h maximum):
3580
+ 60s — 1 minute
3348
3581
  5m — 5 minutes
3349
3582
  1h — 1 hour
3350
3583
 
@@ -3389,16 +3622,34 @@ const loopCmd: CommandHandler = async (ctx, args) => {
3389
3622
  }
3390
3623
  }
3391
3624
  return {
3392
- content: `── Invalid Interval ──\n\n"${interval}" is not a recognised interval.\n\nUse formats like: 10s, 5m, 1h, 30min, 2hr\nOr use /loop auto <prompt> for autonomous mode.`,
3625
+ content: `── Invalid Interval ──\n\n"${interval}" is not a recognised interval.\n\nUse formats like: 60s, 5m, 1h, 30min\nOr use /loop auto <prompt> for autonomous mode.`,
3626
+ }
3627
+ }
3628
+
3629
+ // The scheduler accepts 60–3600s. Reject here so the user gets the range
3630
+ // instead of "Loop failed: delaySeconds must be in [60, 3600]".
3631
+ if (seconds < 60 || seconds > 3600) {
3632
+ return {
3633
+ content:
3634
+ `── Interval Out of Range ──\n\n"${interval}" is ${seconds}s; the scheduler accepts ` +
3635
+ '60–3600 seconds (1 minute to 1 hour).\n\nUse 60s, 5m, or 1h.',
3393
3636
  }
3394
3637
  }
3395
3638
 
3396
3639
  // Fixed-interval loop — directly invoke ScheduleWakeup
3397
3640
  try {
3398
3641
  const { scheduleWakeupTool } = await import('../tools/scheduling/schedule-wakeup.js')
3642
+ // The interval loop must re-arm itself after each fire; nothing in the
3643
+ // scheduler repeats a fixed interval on its own.
3644
+ const scheduledPrompt =
3645
+ `${prompt}\n\n[Repeating every ${seconds}s — after handling this prompt, call ` +
3646
+ `ScheduleWakeup again with delaySeconds: ${seconds} and this same prompt to keep the ` +
3647
+ `loop going. Stop when the task is complete.]`
3399
3648
  const result = await scheduleWakeupTool.execute(
3400
- { delaySeconds: seconds, reason: `Loop: ${prompt.slice(0, 40)}`, prompt },
3401
- { cwd: process.cwd(), sessionId: 'loop-session', provider: '', model: '' },
3649
+ { delaySeconds: seconds, reason: `Loop: ${prompt.slice(0, 40)}`, prompt: scheduledPrompt },
3650
+ // Session-keyed, same as the engine's handler: a hardcoded id fires into
3651
+ // nobody and the loop silently never runs.
3652
+ { cwd: process.cwd(), sessionId: ctx.sessionId, provider: '', model: '' },
3402
3653
  )
3403
3654
  if (!result.success) {
3404
3655
  return { content: `Loop failed: ${result.error || 'unknown error'}` }
@@ -3450,13 +3701,11 @@ const doctorCmd: CommandHandler = async (ctx) => {
3450
3701
  ]
3451
3702
 
3452
3703
  const c = ctx.engine.getContext()
3453
- const msgs = c.getMessages()
3454
3704
  const tokens = c.getEstimatedTokens()
3455
3705
  const maxTokens = c.getMaxTokens()
3456
- lines.push(`Messages ${msgs.length}`)
3457
- lines.push(
3458
- `Tokens ~${tokens.toLocaleString()} / ${maxTokens.toLocaleString()} (${((tokens / maxTokens) * 100).toFixed(1)}%)`,
3459
- )
3706
+ const pct = maxTokens > 0 ? `${((tokens / maxTokens) * 100).toFixed(1)}%` : '—'
3707
+ lines.push(`Messages ${c.getMessageCount()}`)
3708
+ lines.push(`Tokens ~${tokens.toLocaleString()} / ${maxTokens.toLocaleString()} (${pct})`)
3460
3709
  lines.push(`Checkpoints ${c.getCheckpoints().length}`)
3461
3710
 
3462
3711
  // Git info
@@ -3795,9 +4044,8 @@ function gitDiffBridgeCmd(opts: {
3795
4044
  return async (ctx, args) => {
3796
4045
  const t = resolveT(ctx)
3797
4046
  try {
3798
- const { execSync } = await import('node:child_process')
3799
- const diff = execSync('git diff --stat', { encoding: 'utf-8', timeout: 5000 }).trim()
3800
- if (!diff) {
4047
+ const { stat, untracked } = await readGitChangeSummary()
4048
+ if (!stat && untracked.length === 0) {
3801
4049
  return { content: `─ ${opts.label} ─\n\n${t(opts.noChangesKey)}` }
3802
4050
  }
3803
4051
  const forwarded =
@@ -3805,8 +4053,12 @@ function gitDiffBridgeCmd(opts: {
3805
4053
  if (typeof forwarded === 'object') {
3806
4054
  return { content: `─ ${opts.label} ─\n\n${forwarded.error}` }
3807
4055
  }
4056
+ const untrackedBlock =
4057
+ untracked.length > 0
4058
+ ? `\n\nUntracked files:\n${untracked.map((f) => ` ${f}`).join('\n')}`
4059
+ : ''
3808
4060
  return {
3809
- content: `─ ${opts.label} ─\n\n${t(opts.runningKey)}\n\nChanged files:\n${diff}`,
4061
+ content: `─ ${opts.label} ─\n\n${t(opts.runningKey)}\n\nChanged files:\n${stat}${untrackedBlock}`,
3810
4062
  forwardToAI: forwarded,
3811
4063
  }
3812
4064
  } catch {
@@ -3997,6 +4249,7 @@ const statsCmd: CommandHandler = (ctx) => {
3997
4249
  const c = ctx.engine.getContext()
3998
4250
  const msgs = c.getMessages()
3999
4251
  const tokens = c.getEstimatedTokens()
4252
+ const maxTokens = c.getMaxTokens()
4000
4253
  const tools = ctx.engine.getTools()
4001
4254
 
4002
4255
  const userMsgs = msgs.filter((m) => m.role === 'user').length
@@ -4014,14 +4267,16 @@ const statsCmd: CommandHandler = (ctx) => {
4014
4267
  }),
4015
4268
  t('commands.stats.tokens', {
4016
4269
  tokens: tokens.toLocaleString(),
4017
- max: c.getMaxTokens().toLocaleString(),
4270
+ max: maxTokens.toLocaleString(),
4018
4271
  }),
4019
4272
  t('commands.stats.tools', { count: String(tools.size) }),
4020
4273
  t('commands.stats.provider', { provider: ctx.providerId }),
4021
4274
  t('commands.stats.model', { model: ctx.modelId }),
4022
4275
  t('commands.stats.permission', { permission: liveMode(ctx) }),
4023
4276
  '',
4024
- t('commands.stats.usage', { pct: ((tokens / c.getMaxTokens()) * 100).toFixed(1) }),
4277
+ t('commands.stats.usage', {
4278
+ pct: maxTokens > 0 ? ((tokens / maxTokens) * 100).toFixed(1) : '—',
4279
+ }),
4025
4280
  ]
4026
4281
 
4027
4282
  // ── CRSI & SIS extensions ──
@@ -4080,9 +4335,10 @@ const summaryCmd: CommandHandler = (ctx) => {
4080
4335
  return { content: t('commands.summary.no_conversation') }
4081
4336
  }
4082
4337
 
4338
+ // "recent topics" means the latest five user messages, not the earliest.
4083
4339
  const userMsgs = msgs
4084
4340
  .filter((m) => m.role === 'user' && typeof m.content === 'string')
4085
- .slice(0, 5)
4341
+ .slice(-5)
4086
4342
  .map((m) => {
4087
4343
  const text = typeof m.content === 'string' ? m.content : ''
4088
4344
  return text.length > 100 ? text.slice(0, 100) + '...' : text
@@ -4206,7 +4462,7 @@ const cdCmd: CommandHandler = async (ctx, args) => {
4206
4462
  }
4207
4463
  }
4208
4464
 
4209
- const hooksCmd: CommandHandler = async (ctx) => {
4465
+ const hooksListCmd: CommandHandler = async (ctx) => {
4210
4466
  const t = resolveT(ctx)
4211
4467
  const { loadSettingsJson } = await import('../config/loader')
4212
4468
  const cwd = process.cwd()
@@ -4257,13 +4513,23 @@ const hooksCmd: CommandHandler = async (ctx) => {
4257
4513
 
4258
4514
  let count = 0
4259
4515
  for (const [eventName, bucket] of byEvent) {
4516
+ // These events have no dispatch point, so `loadHookConfigs` drops them. This
4517
+ // listing reads the *config files*, not the engine's registry, so it has to
4518
+ // apply the same verdict here — otherwise the entry looks installed and the
4519
+ // count says it will run. Rendered, not hidden: the marker is the honest
4520
+ // version of "we saw your hook and it will not fire". Excluded from `count`
4521
+ // because `found N` must mean "these will run".
4522
+ const undispatchable = UNDISPATCHED_EVENTS.has(eventName)
4260
4523
  for (const { entry, project } of bucket) {
4261
4524
  for (const hook of entry.hooks) {
4262
- count++
4525
+ if (!undispatchable) count++
4263
4526
  const matcher = entry.matcher || '*'
4264
4527
  const cmd = hook.type === 'command' && hook.command ? hook.command : hook.type
4265
4528
  const source = t(project ? 'commands.hooks.source_project' : 'commands.hooks.source_user')
4266
- const suffix = project && gated ? ` ${t('commands.hooks.gated')}` : ''
4529
+ const markers: string[] = []
4530
+ if (project && gated) markers.push(t('commands.hooks.gated'))
4531
+ if (undispatchable) markers.push(t('commands.hooks.undispatched'))
4532
+ const suffix = markers.map((marker) => ` ${marker}`).join('')
4267
4533
  lines.push(` [${source}] ${eventName} [${matcher}] → ${cmd}${suffix}`)
4268
4534
  }
4269
4535
  }
@@ -4448,6 +4714,12 @@ const reviewCmd = codeReviewCmd
4448
4714
  // PR Comments
4449
4715
  // ═══════════════════════════════════════════════════════════════
4450
4716
 
4717
+ function snippetForReview(body: string | undefined): string {
4718
+ const oneLine = (body ?? '').replace(/\s+/g, ' ').trim()
4719
+ if (!oneLine) return '(empty)'
4720
+ return oneLine.length > 200 ? `${oneLine.slice(0, 200)}…` : oneLine
4721
+ }
4722
+
4451
4723
  const prCommentsCmd: CommandHandler = async () => {
4452
4724
  try {
4453
4725
  const { execSync } = await import('node:child_process')
@@ -4497,9 +4769,52 @@ const prCommentsCmd: CommandHandler = async () => {
4497
4769
  lines.push('')
4498
4770
  }
4499
4771
 
4500
- lines.push(
4501
- 'To generate PR description: type "write a PR description for these changes" in chat.',
4502
- )
4772
+ // The command is called `/pr-comments`, so it must read the PR's comments.
4773
+ // `gh pr view` is read-only; when it cannot answer (no PR for this branch,
4774
+ // gh missing, not authenticated) say which — the branch summary above is
4775
+ // not a substitute and silently showing only it is the fake reading.
4776
+ lines.push('PR comments:')
4777
+ try {
4778
+ const raw = execSync('gh pr view --json number,title,url,reviews,comments', {
4779
+ encoding: 'utf-8',
4780
+ timeout: 8000,
4781
+ stdio: ['ignore', 'pipe', 'pipe'],
4782
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
4783
+ }).trim()
4784
+ const pr = JSON.parse(raw) as {
4785
+ number?: number
4786
+ title?: string
4787
+ url?: string
4788
+ reviews?: { author?: { login?: string }; state?: string; body?: string }[]
4789
+ comments?: { author?: { login?: string }; body?: string }[]
4790
+ }
4791
+ const reviews = pr.reviews ?? []
4792
+ const comments = pr.comments ?? []
4793
+ lines.push(` PR #${pr.number ?? '?'}: ${pr.title ?? ''}`.trimEnd())
4794
+ if (pr.url) lines.push(` ${pr.url}`)
4795
+ for (const r of reviews.slice(-10)) {
4796
+ lines.push(` @${r.author?.login ?? '?'} (${r.state ?? '?'}): ${snippetForReview(r.body)}`)
4797
+ }
4798
+ for (const c of comments.slice(-10)) {
4799
+ lines.push(` @${c.author?.login ?? '?'}: ${snippetForReview(c.body)}`)
4800
+ }
4801
+ if (reviews.length === 0 && comments.length === 0) {
4802
+ lines.push(' No reviews or comments on this PR yet.')
4803
+ }
4804
+ lines.push('')
4805
+ } catch (err) {
4806
+ const e = err as { status?: number; stderr?: string; message?: string }
4807
+ const reason =
4808
+ e.status === 127
4809
+ ? 'gh CLI not found'
4810
+ : (e.stderr ?? '').trim().split('\n')[0] ||
4811
+ (e.message ?? 'unknown error').split('\n')[0] ||
4812
+ 'unknown error'
4813
+ lines.push(` unavailable — ${reason.slice(0, 160)}`)
4814
+ lines.push(' Only the local branch summary above is available.')
4815
+ lines.push('')
4816
+ }
4817
+
4503
4818
  lines.push('To review PR: type "review this PR" or use /review.')
4504
4819
 
4505
4820
  return { content: lines.join('\n') }
@@ -4920,11 +5235,26 @@ const upgradeCmd: CommandHandler = async (ctx) => {
4920
5235
 
4921
5236
  const langCmd: CommandHandler = (ctx, args) => {
4922
5237
  const t = resolveT(ctx)
4923
- const requested = args[0]
4924
- if (!requested || !['en-US', 'zh-CN'].includes(requested)) {
4925
- return { content: t('commands.lang.current', { locale: 'en-US' }) }
5238
+ const requested = args[0]?.toLowerCase().replace('_', '-')
5239
+ const current = ctx.locale ?? 'en-US'
5240
+
5241
+ if (!requested) {
5242
+ return { content: t('commands.lang.current', { locale: current }) }
5243
+ }
5244
+
5245
+ const locale = SUPPORTED_LOCALES.find((l) => l.toLowerCase() === requested) as Locale | undefined
5246
+ if (!locale) {
5247
+ return {
5248
+ content: `${t('commands.lang.current', { locale: current })}\n\nUsage: /lang ${SUPPORTED_LOCALES.join(' | ')}`,
5249
+ }
4926
5250
  }
4927
- return { content: t('commands.lang.set', { locale: requested }) }
5251
+
5252
+ // Persisted for the next start; this session keeps the locale it was mounted
5253
+ // with (the provider is created once, before any command runs).
5254
+ if (!saveLocalePreference(locale)) {
5255
+ return { content: `Failed to save the locale preference to ~/.mipham/settings.json.` }
5256
+ }
5257
+ return { content: t('commands.lang.set', { locale }) }
4928
5258
  }
4929
5259
 
4930
5260
  // ═══════════════════════════════════════════════════════════════
@@ -4933,6 +5263,29 @@ const langCmd: CommandHandler = (ctx, args) => {
4933
5263
 
4934
5264
  const noPlanCmd: CommandHandler = (ctx) => {
4935
5265
  const t = resolveT(ctx)
5266
+ const mode = liveMode(ctx)
5267
+ if (mode !== 'plan') {
5268
+ return {
5269
+ content:
5270
+ `Not in plan mode (current mode: ${mode}). Nothing changed.\n\n` +
5271
+ 'Use /plan to start a plan, or Shift+Tab to cycle modes.',
5272
+ }
5273
+ }
5274
+ if (!ctx.setPermissionMode) {
5275
+ return {
5276
+ content: 'This surface cannot switch permission modes. Use Shift+Tab to leave plan mode.',
5277
+ }
5278
+ }
5279
+ ctx.setPermissionMode('default')
5280
+ const now = liveMode(ctx)
5281
+ // The org limit can clamp the request (same read-back as /approve).
5282
+ if (now === 'plan') {
5283
+ return {
5284
+ content:
5285
+ "Plan mode exit requested, but the organisation's permission limit kept the mode at plan. " +
5286
+ 'Use Shift+Tab or contact your administrator.',
5287
+ }
5288
+ }
4936
5289
  return { content: t('commands.no_plan.confirmed') }
4937
5290
  }
4938
5291
 
@@ -5067,7 +5420,7 @@ const workflowRunCmd = async (name: string): Promise<CommandResult> => {
5067
5420
  }
5068
5421
  }
5069
5422
 
5070
- const workflowAutoCmd: CommandHandler = async (_ctx, args) => {
5423
+ const workflowTaskCmd: CommandHandler = async (_ctx, args) => {
5071
5424
  const task = args.join(' ').trim()
5072
5425
 
5073
5426
  if (!task) {
@@ -5994,9 +6347,20 @@ const artifactListCmd: CommandHandler = async (ctx, _args) => {
5994
6347
  }
5995
6348
 
5996
6349
  const artifactServerCmd: CommandHandler = async (_ctx, _args) => {
5997
- const url = 'http://localhost:9876'
6350
+ // The server picks a free port and records it in the manifest; 9876 is only
6351
+ // the first candidate. Reporting the constant would name a port nothing
6352
+ // listens on whenever it was taken.
6353
+ const { readManifest } = await import('../artifacts/manifest')
6354
+ const { artifactsRoot } = await import('../artifacts/paths')
6355
+ const { port } = readManifest(artifactsRoot(process.cwd()))
6356
+ if (!port) {
6357
+ return {
6358
+ content:
6359
+ '── Artifact Server ──\n\n Not running. The server starts when an artifact is created or opened.',
6360
+ }
6361
+ }
5998
6362
  return {
5999
- content: `── Artifact Server ──\n\n URL: ${url}\n Port: 9876\n\nArtifacts are served locally. No external network access.`,
6363
+ content: `── Artifact Server ──\n\n URL: http://localhost:${port}\n Port: ${port}\n\nArtifacts are served locally. No external network access.`,
6000
6364
  }
6001
6365
  }
6002
6366
 
@@ -6026,6 +6390,7 @@ const commandsListCmd: CommandHandler = () => {
6026
6390
  History: [],
6027
6391
  'Model & Provider': [],
6028
6392
  'Tools & Skills': [],
6393
+ 'Code Quality': [],
6029
6394
  Plugins: [],
6030
6395
  Workflow: [],
6031
6396
  Project: [],
@@ -6076,7 +6441,6 @@ const commandsListCmd: CommandHandler = () => {
6076
6441
  '/switch': 'Model & Provider',
6077
6442
  '/config': 'Model & Provider',
6078
6443
  '/effort': 'Model & Provider',
6079
- '/theme': 'Model & Provider',
6080
6444
  '/upgrade': 'Model & Provider',
6081
6445
  '/tools': 'Tools & Skills',
6082
6446
  '/skills': 'Tools & Skills',
@@ -6094,6 +6458,7 @@ const commandsListCmd: CommandHandler = () => {
6094
6458
  '/plugin-enable': 'Plugins',
6095
6459
  '/plugin-disable': 'Plugins',
6096
6460
  '/commands': 'Tools & Skills',
6461
+ '/crsi': 'Tools & Skills',
6097
6462
  '/crsi rules': 'Tools & Skills',
6098
6463
  '/crsi disable': 'Tools & Skills',
6099
6464
  '/crsi analyze': 'Tools & Skills',
@@ -6110,6 +6475,7 @@ const commandsListCmd: CommandHandler = () => {
6110
6475
  '/crsi interpret': 'Tools & Skills',
6111
6476
  '/crsi critique': 'Tools & Skills',
6112
6477
  '/crsi red-team': 'Tools & Skills',
6478
+ '/sis': 'Tools & Skills',
6113
6479
  '/sis errors': 'Tools & Skills',
6114
6480
  '/sis stats': 'Tools & Skills',
6115
6481
  '/sis clear': 'Tools & Skills',
@@ -6196,6 +6562,54 @@ const commandsListCmd: CommandHandler = () => {
6196
6562
 
6197
6563
  const registry = new Map<string, CommandHandler>()
6198
6564
 
6565
+ /**
6566
+ * Parents that read `args[0]` themselves instead of routing through
6567
+ * `subcommandRouter`. Their multi-word entries (`/keys rotate`, `/resume last`)
6568
+ * are aliases, so the reachability guard exempts them from the router marker.
6569
+ */
6570
+ export const SELF_ROUTING_PARENTS: ReadonlySet<string> = new Set(['/keys', '/resume'])
6571
+
6572
+ /** Handlers built by `subcommandRouter` — the reachability guard's marker. */
6573
+ const subcommandRouters = new WeakSet<CommandHandler>()
6574
+
6575
+ /** True when `handler` was produced by `subcommandRouter`. */
6576
+ export function isSubcommandRouter(handler: CommandHandler | undefined): boolean {
6577
+ return handler !== undefined && subcommandRouters.has(handler)
6578
+ }
6579
+
6580
+ /**
6581
+ * A handler whose job is to hand `args[0]` to the multi-word command registered
6582
+ * under `parent` (`/crsi rules`, `/sis stats`, `/hooks health`).
6583
+ *
6584
+ * `parseSlashCommand` keeps only `parts[0]`, so a multi-word key without a parent
6585
+ * is unreachable — the input renders nothing at all. When nothing resolves, the
6586
+ * router falls back to `fallback` if one is given (bare `/hooks` lists hooks,
6587
+ * bare `/workflow <task>` still forwards a task), otherwise it prints the
6588
+ * subcommand list instead of staying silent.
6589
+ */
6590
+ function subcommandRouter(parent: string, fallback?: CommandHandler): CommandHandler {
6591
+ const handler: CommandHandler = async (ctx, args) => {
6592
+ const sub = args[0]?.toLowerCase()
6593
+ const routed = sub ? registry.get(`${parent} ${sub}`) : undefined
6594
+ if (routed) return routed(ctx, args.slice(1))
6595
+ if (fallback) return fallback(ctx, args)
6596
+
6597
+ const subs = getCommandNames()
6598
+ .filter((name) => name.startsWith(`${parent} `))
6599
+ .map((name) => name.slice(parent.length + 1))
6600
+ return {
6601
+ content: [
6602
+ `Usage: ${parent} <subcommand> [...args]`,
6603
+ '',
6604
+ 'Subcommands:',
6605
+ ...subs.map((name) => ` ${name}`),
6606
+ ].join('\n'),
6607
+ }
6608
+ }
6609
+ subcommandRouters.add(handler)
6610
+ return handler
6611
+ }
6612
+
6199
6613
  // Session
6200
6614
  registry.set('/help', helpCmd)
6201
6615
  const pickCmd: CommandHandler = (ctx) => ({
@@ -6255,6 +6669,7 @@ registry.set('/remove-plugin', removePluginCmd)
6255
6669
  registry.set('/plugin-enable', pluginEnableCmd)
6256
6670
  registry.set('/plugin-disable', pluginDisableCmd)
6257
6671
  registry.set('/commands', commandsListCmd)
6672
+ registry.set('/crsi', subcommandRouter('/crsi'))
6258
6673
  registry.set('/crsi rules', crsiRulesCmd)
6259
6674
  registry.set('/crsi disable', crsiDisableCmd)
6260
6675
  registry.set('/crsi analyze', crsiAnalyzeCmd)
@@ -6272,6 +6687,7 @@ registry.set('/crsi meta', crsiMetaCmd)
6272
6687
  registry.set('/crsi interpret', crsiInterpretCmd)
6273
6688
  registry.set('/crsi critique', crsiCritiqueCmd)
6274
6689
  registry.set('/crsi red-team', crsiRedTeamCmd)
6690
+ registry.set('/sis', subcommandRouter('/sis'))
6275
6691
  registry.set('/sis errors', sisErrorsCmd)
6276
6692
  registry.set('/sis stats', sisStatsCmd)
6277
6693
  registry.set('/sis clear', sisClearCmd)
@@ -6289,7 +6705,7 @@ registry.set('/tasks', tasksCmd)
6289
6705
  registry.set('/diff', diffCmd)
6290
6706
  registry.set('/loop', loopCmd)
6291
6707
  registry.set('/no-plan', noPlanCmd)
6292
- registry.set('/workflow', workflowAutoCmd)
6708
+ registry.set('/workflow', subcommandRouter('/workflow', workflowTaskCmd))
6293
6709
  registry.set('/workflows', workflowsCmd)
6294
6710
  registry.set('/workflow view', workflowViewCmd)
6295
6711
  registry.set('/workflow watch', workflowWatchCmd)
@@ -6322,7 +6738,6 @@ registry.set('/trust', trustCmd)
6322
6738
  registry.set('/prompt-audit', promptAuditCmd)
6323
6739
 
6324
6740
  // Environment
6325
- registry.set('/theme', themeCmd)
6326
6741
  registry.set('/lang', langCmd)
6327
6742
  registry.set('/ide', ideCmd)
6328
6743
  registry.set('/terminal-setup', terminalSetupCmd)
@@ -6366,7 +6781,7 @@ registry.set('/files', filesCmd)
6366
6781
  registry.set('/stats', statsCmd)
6367
6782
  registry.set('/summary', summaryCmd)
6368
6783
  registry.set('/cd', cdCmd)
6369
- registry.set('/hooks', hooksCmd)
6784
+ registry.set('/hooks', subcommandRouter('/hooks', hooksListCmd))
6370
6785
  registry.set('/hooks health', hooksHealthCmd)
6371
6786
  registry.set('/hooks enable', hooksEnableCmd)
6372
6787
  registry.set('/telemetry', telemetryCmd)
@@ -6380,6 +6795,15 @@ export function getCommand(name: string): CommandHandler | undefined {
6380
6795
  return registry.get(name)
6381
6796
  }
6382
6797
 
6798
+ /**
6799
+ * What the UI shows when dispatch resolves nothing. Before this, an unknown
6800
+ * slash command rendered **nothing** — the input was cleared and no message was
6801
+ * pushed, which is indistinguishable from the CLI being broken.
6802
+ */
6803
+ export function unknownCommandMessage(command: string): string {
6804
+ return `Unknown command: ${command}\n\nType /help to see available commands, or /commands for the full list.`
6805
+ }
6806
+
6383
6807
  export function getCommandNames(): string[] {
6384
6808
  return Array.from(registry.keys()).sort()
6385
6809
  }
@@ -6392,7 +6816,9 @@ export function getCommandNames(): string[] {
6392
6816
  * at all — the other five are, so listing them here is belt-and-braces rather
6393
6817
  * than a claim that they are missing.
6394
6818
  */
6395
- const PRE_REGISTRY_COMMANDS = ['/switch', '/pick', '/model-picker', '/exit', '/quit', '/focus']
6819
+ // `/focus` is NOT here: it lives in the registry and toggles through
6820
+ // `getFocusMode` — the app-side duplicate was removed so there is one handler.
6821
+ const PRE_REGISTRY_COMMANDS = ['/switch', '/pick', '/model-picker', '/exit', '/quit']
6396
6822
 
6397
6823
  /**
6398
6824
  * The bucket an unrecognised command name is recorded under.
@@ -6470,8 +6896,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
6470
6896
  '/providers': 'List configured providers',
6471
6897
  '/switch': 'Switch provider and model',
6472
6898
  '/config': 'View configuration',
6473
- '/effort': 'Set reasoning effort',
6474
- '/theme': 'Set terminal theme',
6899
+ '/effort': 'Set the stream stall budget (does not change reasoning depth)',
6475
6900
  '/lang': 'Set display language (en-US, zh-CN)',
6476
6901
  '/tools': 'List available tools',
6477
6902
  '/skills': 'List loaded skills',
@@ -6488,6 +6913,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
6488
6913
  '/remove-plugin': 'Remove an installed plugin',
6489
6914
  '/plugin-enable': 'Enable a disabled plugin',
6490
6915
  '/plugin-disable': 'Disable an enabled plugin',
6916
+ '/crsi': 'CRSI subcommands — run /crsi for the list',
6491
6917
  '/crsi rules': 'List all active CRSI rules with their status',
6492
6918
  '/crsi disable': 'Disable a CRSI rule by ID',
6493
6919
  '/crsi analyze': 'Manually trigger CRSI pattern analysis across all agents',
@@ -6505,6 +6931,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
6505
6931
  '/crsi interpret': 'Tool-call behavior dashboard — error patterns, usage, health',
6506
6932
  '/crsi critique': 'Enable/disable RLAIF self-critique on tool calls',
6507
6933
  '/crsi red-team': 'Run adversarial self-test — verify SIS blocks known attacks',
6934
+ '/sis': 'SIS subcommands — run /sis for the list',
6508
6935
  '/sis errors': 'List all active SIS immune memory signatures',
6509
6936
  '/sis stats': 'Show SIS self-immune system aggregate statistics',
6510
6937
  '/sis clear': 'Retire an immune memory signature by ID',
@@ -6515,7 +6942,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
6515
6942
  '/todos': 'Task management (list/create tasks)',
6516
6943
  '/tasks': 'Background tasks',
6517
6944
  '/review': 'Review code for bugs, security, performance (alias for /code-review)',
6518
- '/pr-comments': 'PR review summary',
6945
+ '/pr-comments': 'PR comments via gh + local branch summary',
6519
6946
  '/diff': 'Show git diff',
6520
6947
  '/workflows': 'List workflow scripts',
6521
6948
  '/workflow view': 'View workflow run details or list runs',
@@ -6549,10 +6976,10 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
6549
6976
  '/fork': 'Fork task into isolated worktree',
6550
6977
  '/artifact': 'Manage artifacts',
6551
6978
  '/schedule': 'View scheduled tasks and cron jobs',
6552
- '/commit': 'Generate commit message and review staged changes',
6553
- '/push': 'Push the current branch',
6554
- '/pr': 'Create a pull request',
6555
- '/issue': 'File a GitHub issue',
6979
+ '/commit': 'Draft a commit message from staged changes',
6980
+ '/push': 'Show push status and the command to run',
6981
+ '/pr': 'Draft a pull request title and body',
6982
+ '/issue': 'Draft a GitHub issue from your description',
6556
6983
  '/code-review': 'Review code for bugs, security, performance (7 dimensions)',
6557
6984
  '/simplify': 'Cleanup-only review: reuse, simplification, efficiency, abstraction',
6558
6985
  '/verify': 'Runtime verification — observe actual execution, not tests',