@miphamai/cli 0.85.52 → 0.85.54

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.
@@ -20,12 +20,15 @@ import { registerMcpServerTools, unregisterMcpServerTools } from '../mcp/registr
20
20
  import { buildCapabilityReport, type CapabilityLedgers } from '../core/capability-inventory'
21
21
  import { formatFixRate, isAutoFixable } from '../core/error-signature-db'
22
22
  import { InstructionsLoader } from '../core/instructions'
23
+ import { formatInsightsReport, loadSessionLogs, summarizeSessions } from '../core/session-insights'
23
24
  import { UNDISPATCHED_EVENTS } from '../core/hooks-config'
24
25
  import { findDerivableSections, DERIVABLE_HINTS } from '../core/claude-md-audit'
25
26
  import { miphamHome, workflowScriptDir, workflowScriptDirs, worktreeRoot } from '../core/paths.ts'
26
27
  import { fixDoctor, fixConfig, fixCache, selectRepoClaudeFiles } from '../core/fix'
27
28
  import { fixCodeTarget } from '../core/fix-code'
28
29
  import { homedir } from 'node:os'
30
+ import { readFileSync } from 'node:fs'
31
+ import { join } from 'node:path'
29
32
  import {
30
33
  runCrsiModification,
31
34
  approvePending,
@@ -109,7 +112,12 @@ import {
109
112
  } from '../core/improvement-track'
110
113
  import { NPM_UPDATE_COMMAND, PACKAGE_VERSION, COAUTHOR_TRAILER } from '../shared/index.ts'
111
114
  import { getPreference, setPreference } from '../config/preferences'
112
- import { loadCrossSessionConfig, tryRestoreFromBackup } from '../config/loader'
115
+ import {
116
+ loadCrossSessionConfig,
117
+ tryRestoreFromBackup,
118
+ loadDisabledMcpServers,
119
+ saveDisabledMcpServers,
120
+ } from '../config/loader'
113
121
  import { getWorkspaceTrust } from '../core/workspace-trust'
114
122
  import { getMemoryManager } from '../core/memory/memory-loader'
115
123
  import { auditMemoryDir } from '../core/memory/memory-audit'
@@ -171,6 +179,26 @@ import { clearTasks, formatTaskList } from '../tools/exec/task'
171
179
  import { estimateCost, loadPriceBook } from '../providers/pricing'
172
180
  import type { UsageSummary } from '../core/usage-tracker'
173
181
 
182
+ export type StatuslineMode = 'full' | 'compact' | 'off'
183
+
184
+ export const STATUSLINE_MODES: readonly StatuslineMode[] = ['full', 'compact', 'off']
185
+
186
+ /**
187
+ * Which footer segments a mode shows. The permission label is deliberately
188
+ * absent: it is safety information and stays visible in every mode.
189
+ */
190
+ export function statuslineVisibility(mode: StatuslineMode): {
191
+ graft: boolean
192
+ hints: boolean
193
+ git: boolean
194
+ } {
195
+ return {
196
+ graft: mode === 'full',
197
+ hints: mode === 'full',
198
+ git: mode !== 'off',
199
+ }
200
+ }
201
+
174
202
  export interface CommandContext {
175
203
  engine: QueryEngine
176
204
  config: MiphamConfig
@@ -189,6 +217,10 @@ export interface CommandContext {
189
217
  setGoal: (text: string) => void
190
218
  setUltracodeMode: (on: boolean) => void
191
219
  setUpdateStatus: (s: UpdateStatus) => void
220
+ /** Live footer-mode change; absent on surfaces that cannot repaint the App. */
221
+ setStatuslineMode?: (mode: StatuslineMode) => void
222
+ /** Re-run plugin loading; absent under `--safe-mode` / `disableAllHooks`. */
223
+ reloadPlugins?: () => { plugins: number; skills: number }
192
224
  /** Request a permission-mode change and let the App read back the mode that
193
225
  * actually took effect (org limits can clamp it). Absent on surfaces that
194
226
  * cannot switch modes (e.g. a remote attach stub). */
@@ -563,6 +595,18 @@ const approveCmd: CommandHandler = async (ctx) => {
563
595
  }
564
596
  }
565
597
 
598
+ /**
599
+ * One line for `/status`: whether this session is sending anything, and where.
600
+ * The endpoint can be empty for two different reasons (`off` vs the `none`
601
+ * sentinel), so say which instead of printing a bare blank (CC 2.1.335-085).
602
+ */
603
+ function telemetryStatus(_ctx: CommandContext): string {
604
+ const consent = getTelemetryConsent() ?? resolveTelemetry()
605
+ if (!consent.enabled) return `disabled (set by ${consent.source})`
606
+ const destination = consent.endpoint || `nothing (${consent.endpointSource})`
607
+ return `enabled → ${destination} (set by ${consent.source})`
608
+ }
609
+
566
610
  const statusCmd: CommandHandler = async (ctx) => {
567
611
  const t = resolveT(ctx)
568
612
  const c = ctx.engine.getContext()
@@ -586,6 +630,7 @@ const statusCmd: CommandHandler = async (ctx) => {
586
630
  ${t('commands.status.tokens')} ~${c.getEstimatedTokens().toLocaleString()} / ${c.getMaxTokens().toLocaleString()}
587
631
  ${t('commands.status.tools')} ${tools.size} ${t('commands.status.loaded')}
588
632
  ${t('commands.status.permission')} ${liveMode(ctx)}
633
+ Telemetry ${telemetryStatus(ctx)}
589
634
 
590
635
  ${t('commands.status.system_title')}
591
636
  ${t('commands.status.platform')} ${process.platform} ${process.arch}
@@ -973,6 +1018,13 @@ const configCmd: CommandHandler = (ctx) => {
973
1018
  '',
974
1019
  `crossSessionInbound: ${xs.crossSessionInbound}`,
975
1020
  `dialogExpiry: ${xs.dialogExpiry}s`,
1021
+ // The threshold `/autocompact` writes lived only in that command's output;
1022
+ // `/config` — where people look for it — showed nothing (CC 2.1.334-003).
1023
+ `autoCompact: ${
1024
+ getPreference('autocompactThreshold', '')
1025
+ ? `${(Number.parseFloat(getPreference('autocompactThreshold', '')) * 100).toFixed(0)}% (set by /autocompact)`
1026
+ : 'window-derived (see /autocompact)'
1027
+ }`,
976
1028
  ]
977
1029
  return {
978
1030
  content: `${t('commands.config.title')}\n${lines.join('\n')}\n\n${t('commands.config.edit')}`,
@@ -3686,6 +3738,22 @@ const browseMarketplaceCmd: CommandHandler = async (_ctx) => {
3686
3738
  // Plugins — Community plugin marketplace + local management
3687
3739
  // ═══════════════════════════════════════════════════════════════
3688
3740
 
3741
+ const reloadPluginsCmd: CommandHandler = (ctx) => {
3742
+ if (!ctx.reloadPlugins) {
3743
+ return { content: 'Plugin reload is not available in this session.' }
3744
+ }
3745
+ try {
3746
+ const r = ctx.reloadPlugins()
3747
+ return {
3748
+ content:
3749
+ `✓ Reloaded ${r.plugins} enabled plugin(s); ${r.skills} skills loaded.\n\n` +
3750
+ 'Boundaries: already-connected MCP servers stay connected; skills/agents loaded from plugins that are now disabled remain until restart.',
3751
+ }
3752
+ } catch (err) {
3753
+ return { content: `Plugin reload failed: ${String(err)}` }
3754
+ }
3755
+ }
3756
+
3689
3757
  const pluginsCmd: CommandHandler = (ctx) => {
3690
3758
  const t = resolveT(ctx)
3691
3759
  const manager = ctx.pluginManager
@@ -3943,14 +4011,34 @@ const copyCmd: CommandHandler = (ctx, args) => {
3943
4011
  * folds index and worktree into one view; untracked files need `ls-files`
3944
4012
  * because no `git diff` sees them.
3945
4013
  */
3946
- async function readGitChangeSummary(): Promise<{ stat: string; untracked: string[] }> {
4014
+ export interface GitChangeView {
4015
+ stat: string
4016
+ untracked: string[]
4017
+ /** 改动文件的仓库相对路径(含已删除的文件 —— 它们的目录仍可能有 REVIEW.md)。 */
4018
+ files: string[]
4019
+ /** 仓库根(`git rev-parse --show-toplevel`);拿不到时为空串。 */
4020
+ root: string
4021
+ }
4022
+
4023
+ async function readGitChangeSummary(): Promise<GitChangeView> {
3947
4024
  const { execSync } = await import('node:child_process')
3948
4025
  let stat = ''
4026
+ let files: string[] = []
3949
4027
  try {
3950
4028
  stat = execSync('git diff --stat HEAD', { encoding: 'utf-8', timeout: 5000 }).trim()
4029
+ files = execSync('git diff --name-only HEAD', { encoding: 'utf-8', timeout: 5000 })
4030
+ .split('\n')
4031
+ .filter(Boolean)
3951
4032
  } catch {
3952
4033
  // No HEAD yet (fresh repository) — fall back to the index/worktree diff.
3953
4034
  stat = execSync('git diff --stat', { encoding: 'utf-8', timeout: 5000 }).trim()
4035
+ try {
4036
+ files = execSync('git diff --name-only', { encoding: 'utf-8', timeout: 5000 })
4037
+ .split('\n')
4038
+ .filter(Boolean)
4039
+ } catch {
4040
+ files = []
4041
+ }
3954
4042
  }
3955
4043
  let untracked: string[] = []
3956
4044
  try {
@@ -3964,7 +4052,67 @@ async function readGitChangeSummary(): Promise<{ stat: string; untracked: string
3964
4052
  // Not a repository / git unavailable — the stat call above already decided
3965
4053
  // whether there is anything to report.
3966
4054
  }
3967
- return { stat, untracked }
4055
+ let root = ''
4056
+ try {
4057
+ root = execSync('git rev-parse --show-toplevel', { encoding: 'utf-8', timeout: 5000 }).trim()
4058
+ } catch {
4059
+ // Not a repository — no folder-level REVIEW.md discovery.
4060
+ }
4061
+ return { stat, untracked, files: [...files, ...untracked], root }
4062
+ }
4063
+
4064
+ const REVIEW_DOC_NAME = 'REVIEW.md'
4065
+ /** 单份 REVIEW.md 的读取上限 —— 评审指令不是被评审的代码,不需要整本进提示词。 */
4066
+ const REVIEW_DOC_MAX_CHARS = 8_000
4067
+ /** 所有 REVIEW.md 合计上限 —— 防止大仓里几十份文档把提示词挤爆。 */
4068
+ const REVIEW_DOCS_TOTAL_MAX_CHARS = 32_000
4069
+
4070
+ /**
4071
+ * 改动文件祖先目录里的 REVIEW.md(仓库根 → 由外到内)。
4072
+ *
4073
+ * 语义与 `CLAUDE.md` 的加载链一致:外层先读、内层后读,越具体越靠后。
4074
+ * 同一份文件被多个改动文件共享时只收一次。`readFile` 返回 `null` 表示不存在,
4075
+ * 由调用方提供,因此这条发现逻辑不碰真文件系统也能测。
4076
+ */
4077
+ export function collectReviewDocs(
4078
+ files: string[],
4079
+ readFile: (relativePath: string) => string | null,
4080
+ ): Array<{ path: string; content: string }> {
4081
+ const dirs = new Set<string>([''])
4082
+ for (const file of files) {
4083
+ const norm = file.replace(/\\/g, '/').replace(/^\.\//, '')
4084
+ if (norm === '') continue
4085
+ const parts = norm.split('/')
4086
+ let cur = ''
4087
+ for (let i = 0; i < parts.length - 1; i++) {
4088
+ cur = cur === '' ? parts[i]! : `${cur}/${parts[i]!}`
4089
+ dirs.add(cur)
4090
+ }
4091
+ }
4092
+ const depth = (dir: string) => (dir === '' ? 0 : dir.split('/').length)
4093
+ const ordered = [...dirs].sort((a, b) => depth(a) - depth(b) || a.localeCompare(b))
4094
+ const docs: Array<{ path: string; content: string }> = []
4095
+ let budget = REVIEW_DOCS_TOTAL_MAX_CHARS
4096
+ for (const dir of ordered) {
4097
+ if (budget <= 0) break
4098
+ const path = dir === '' ? REVIEW_DOC_NAME : `${dir}/${REVIEW_DOC_NAME}`
4099
+ const content = readFile(path)
4100
+ if (content === null || content.trim() === '') continue
4101
+ const clipped = content.slice(0, Math.min(REVIEW_DOC_MAX_CHARS, budget))
4102
+ budget -= clipped.length
4103
+ docs.push({ path, content: clipped })
4104
+ }
4105
+ return docs
4106
+ }
4107
+
4108
+ /** 把收集到的 REVIEW.md 拼成提示词里的一段;没有文档时返回空串。 */
4109
+ function formatReviewDocs(docs: Array<{ path: string; content: string }>): string {
4110
+ if (docs.length === 0) return ''
4111
+ const blocks = docs.map((d) => `### ${d.path}\n${d.content}`).join('\n\n')
4112
+ return (
4113
+ `\n\nFolder-level review instructions — REVIEW.md files in folders above the changed files. ` +
4114
+ `Outer folders come first, inner folders last; where they conflict, the inner one wins.\n\n${blocks}`
4115
+ )
3968
4116
  }
3969
4117
 
3970
4118
  const diffCmd: CommandHandler = async (_ctx) => {
@@ -4802,21 +4950,22 @@ function gitDiffBridgeCmd(opts: {
4802
4950
  noChangesKey: string
4803
4951
  runningKey: string
4804
4952
  errorKey: string
4805
- /** Either a fixed prompt, or a builder that reads the command args. A builder
4806
- * may return an `{ error }` envelope instead — used when the args are
4807
- * unusable, so the command reports that rather than forwarding a prompt the
4808
- * user's flag never reached. */
4809
- forwardToAI: string | ((args: string[]) => string | { error: string })
4953
+ /** Either a fixed prompt, or a builder that reads the command args and the
4954
+ * change view. A builder may return an `{ error }` envelope instead — used
4955
+ * when the args are unusable, so the command reports that rather than
4956
+ * forwarding a prompt the user's flag never reached. */
4957
+ forwardToAI: string | ((args: string[], change: GitChangeView) => string | { error: string })
4810
4958
  }): CommandHandler {
4811
4959
  return async (ctx, args) => {
4812
4960
  const t = resolveT(ctx)
4813
4961
  try {
4814
- const { stat, untracked } = await readGitChangeSummary()
4962
+ const change = await readGitChangeSummary()
4963
+ const { stat, untracked } = change
4815
4964
  if (!stat && untracked.length === 0) {
4816
4965
  return { content: `─ ${opts.label} ─\n\n${t(opts.noChangesKey)}` }
4817
4966
  }
4818
4967
  const forwarded =
4819
- typeof opts.forwardToAI === 'function' ? opts.forwardToAI(args) : opts.forwardToAI
4968
+ typeof opts.forwardToAI === 'function' ? opts.forwardToAI(args, change) : opts.forwardToAI
4820
4969
  if (typeof forwarded === 'object') {
4821
4970
  return { content: `─ ${opts.label} ─\n\n${forwarded.error}` }
4822
4971
  }
@@ -4872,14 +5021,39 @@ function resolveMaxFindings(
4872
5021
  }
4873
5022
  }
4874
5023
 
5024
+ export const SECURITY_REVIEW_PROMPT =
5025
+ 'Use the security-review skill to review all uncommitted changes for security vulnerabilities only: ' +
5026
+ 'injection, auth/permission bypass, secret exposure, unsafe deserialization, path traversal, and dependency risk. ' +
5027
+ 'Do not report general style or simplification issues — /simplify owns those. ' +
5028
+ 'For each finding give file:line, severity, and a concrete fix. ' +
5029
+ 'If there is nothing to report, write exactly: "Security review found no issues."'
5030
+
5031
+ const securityReviewCmd = gitDiffBridgeCmd({
5032
+ label: 'Security Review',
5033
+ noChangesKey: 'commands.code_review.no_changes',
5034
+ runningKey: 'commands.code_review.running',
5035
+ errorKey: 'commands.code_review.error',
5036
+ forwardToAI: SECURITY_REVIEW_PROMPT,
5037
+ })
5038
+
4875
5039
  const codeReviewCmd = gitDiffBridgeCmd({
4876
5040
  label: 'Code Review',
4877
5041
  noChangesKey: 'commands.code_review.no_changes',
4878
5042
  runningKey: 'commands.code_review.running',
4879
5043
  errorKey: 'commands.code_review.error',
4880
- forwardToAI: (args) => {
5044
+ forwardToAI: (args, change) => {
4881
5045
  const maxFindings = resolveMaxFindings(args)
4882
5046
  if (!maxFindings.ok) return { error: maxFindings.error }
5047
+ const baseDir = change.root !== '' ? change.root : process.cwd()
5048
+ const reviewDocs = formatReviewDocs(
5049
+ collectReviewDocs(change.files, (rel) => {
5050
+ try {
5051
+ return readFileSync(join(baseDir, rel), 'utf-8')
5052
+ } catch {
5053
+ return null
5054
+ }
5055
+ }),
5056
+ )
4883
5057
  const cap =
4884
5058
  maxFindings.value === 'all'
4885
5059
  ? ' Report every finding, however many there are.'
@@ -4899,7 +5073,7 @@ const codeReviewCmd = gitDiffBridgeCmd({
4899
5073
  `Do not report reuse, simplification, efficiency, architecture or test-coverage cleanups — /simplify owns those. ` +
4900
5074
  `Mark each finding with exactly one severity: important (this change introduced or worsened it), ` +
4901
5075
  `pre_existing (it was already there before this change), or nit (minor). ` +
4902
- `End the summary with one suggested fix. If there is nothing to report, write exactly: "Code review found no issues."${cap}`
5076
+ `End the summary with one suggested fix. If there is nothing to report, write exactly: "Code review found no issues."${cap}${reviewDocs}`
4903
5077
  )
4904
5078
  },
4905
5079
  })
@@ -5021,6 +5195,75 @@ const filesCmd: CommandHandler = async (ctx) => {
5021
5195
  }
5022
5196
  }
5023
5197
 
5198
+ const autocompactCmd: CommandHandler = (ctx, args) => {
5199
+ if ((ctx.engine as { isRemote?: boolean }).isRemote === true) {
5200
+ return {
5201
+ content:
5202
+ 'Attached to a daemon: the daemon owns context compaction; this session cannot change its threshold.',
5203
+ }
5204
+ }
5205
+ const cm = ctx.engine.getContext()
5206
+ const arg = (args[0] ?? '').toLowerCase()
5207
+ const current = cm.getCompactionThreshold()
5208
+ if (!arg) {
5209
+ return {
5210
+ content:
5211
+ `Auto-compaction (hard) threshold: ${(current * 100).toFixed(0)}% of context ` +
5212
+ `(window ${cm.getMaxTokens().toLocaleString()} tokens). ` +
5213
+ `Microcompaction still fires earlier on its own window-derived schedule.\n\n` +
5214
+ 'Usage: /autocompact <50-95%> | default',
5215
+ }
5216
+ }
5217
+ if (arg === 'default' || arg === 'off') {
5218
+ cm.setCompactionThresholdOverride(null)
5219
+ setPreference('autocompactThreshold', '')
5220
+ return {
5221
+ content: `Auto-compaction threshold cleared; using the window-derived value (${(cm.getCompactionThreshold() * 100).toFixed(0)}%).`,
5222
+ }
5223
+ }
5224
+ const pct = arg.endsWith('%') ? Number.parseFloat(arg) / 100 : Number.parseFloat(arg)
5225
+ if (!Number.isFinite(pct) || pct < 0.5 || pct > 0.95) {
5226
+ return {
5227
+ content: `Invalid threshold "${arg}". Use a value between 0.50 and 0.95 (or "default").`,
5228
+ }
5229
+ }
5230
+ cm.setCompactionThresholdOverride(pct)
5231
+ setPreference('autocompactThreshold', String(pct))
5232
+ return { content: `Auto-compaction threshold set to ${(pct * 100).toFixed(0)}%.` }
5233
+ }
5234
+
5235
+ const statuslineCmd: CommandHandler = (ctx, args) => {
5236
+ const requested = (args[0] ?? '').toLowerCase()
5237
+ const current = getPreference('statuslineMode', 'full')
5238
+ if (!requested) {
5239
+ return {
5240
+ content:
5241
+ `Statusline mode: ${current}\n\n` +
5242
+ 'Usage: /statusline <full|compact|off>\n' +
5243
+ ' full graft line + hints + git branch\n' +
5244
+ ' compact permission + git branch only\n' +
5245
+ ' off permission line only (never hides the permission mode)',
5246
+ }
5247
+ }
5248
+ if (!STATUSLINE_MODES.includes(requested as StatuslineMode)) {
5249
+ return { content: `Unknown statusline mode "${requested}". Choose full, compact, or off.` }
5250
+ }
5251
+ const mode = requested as StatuslineMode
5252
+ setPreference('statuslineMode', mode)
5253
+ ctx.setStatuslineMode?.(mode)
5254
+ return { content: `Statusline mode set to ${mode}.` }
5255
+ }
5256
+
5257
+ const insightsCmd: CommandHandler = (ctx) => {
5258
+ const dir = miphamHome('sessions')
5259
+ const loaded = loadSessionLogs(dir)
5260
+ const note =
5261
+ (ctx.engine as { isRemote?: boolean }).isRemote === true
5262
+ ? "Attached to a daemon: this covers local CLI sessions only; the attached session's audit log is not included.\n\n"
5263
+ : ''
5264
+ return { content: note + formatInsightsReport(summarizeSessions(loaded.inputs), dir, loaded) }
5265
+ }
5266
+
5024
5267
  const statsCmd: CommandHandler = (ctx) => {
5025
5268
  const t = resolveT(ctx)
5026
5269
  const c = ctx.engine.getContext()
@@ -5164,10 +5407,10 @@ const cdCmd: CommandHandler = async (ctx, args) => {
5164
5407
  ctx.setGitBranch?.((await import('../core/git-pr')).readGitBranch())
5165
5408
 
5166
5409
  // `/cd` 只搬了 cwd,而**按目录装载的闸门**分两半:
5167
- // • 能在这里重放的 —— `.mipham/rules/*.md` 与 settings.json 的 permission 规则;
5168
- // • 启动时一次性装载、搬不动的 —— config.yml 的 permissionRules、hooks、
5169
- // 指令文件(CLAUDE.md 链)。它们仍然属于**原来的**目录。
5170
- // 后半段必须说出口:否则用户以为自己已经在新项目的策略下,而实际生效的
5410
+ // • 能在这里重放的 —— `.mipham/rules/*.md`、settings.json 的 permission 规则,
5411
+ // 以及指令文件(CLAUDE.md 链,`reloadInstructions` 重新锚定装载器并重刷系统提示);
5412
+ // • 启动时一次性装载、搬不动的 —— config.yml 的 permissionRules 与 hooks。
5413
+ // 后者必须说出口:否则用户以为自己已经在新项目的策略下,而实际生效的
5171
5414
  // 是上一个仓库的那一套。重放前半段是纯收紧/纯重放,不会放宽任何东西。
5172
5415
  const notes: string[] = []
5173
5416
  try {
@@ -5205,13 +5448,23 @@ const cdCmd: CommandHandler = async (ctx, args) => {
5205
5448
  notes.push(`Applied ${applied} settings.json permission rule(s) from this directory.`)
5206
5449
  ctx.engine.setRulesLoader(new RulesLoader(resolved))
5207
5450
  notes.push('Project rules now read from this directory.')
5451
+ // The instruction chain is loaded once at startup and the loader that
5452
+ // built the prompt still points at the directory the session opened in.
5453
+ // Re-root it in place; the context rebuilder re-reads from the same
5454
+ // loader instance, so the base prompt (and the per-path nested lookup)
5455
+ // both move to the new directory.
5456
+ notes.push(
5457
+ ctx.engine.reloadInstructions(resolved)
5458
+ ? 'Instruction files (CLAUDE.md chain) now read from this directory.'
5459
+ : 'Instruction files could not be reloaded in this mode.',
5460
+ )
5208
5461
  }
5209
5462
  } catch (err) {
5210
5463
  notes.push(`Could not reload this directory's policy: ${(err as Error).message}`)
5211
5464
  }
5212
5465
  notes.push(
5213
5466
  'Loaded at startup and still belonging to the original directory until restart: ' +
5214
- 'config.yml permissionRules, hooks, and instruction files (CLAUDE.md chain).',
5467
+ 'config.yml permissionRules and hooks.',
5215
5468
  )
5216
5469
 
5217
5470
  try {
@@ -5270,6 +5523,13 @@ const hooksListCmd: CommandHandler = async (ctx) => {
5270
5523
  // display has to name the source and say which entries will not run.
5271
5524
  const gated = !getWorkspaceTrust().isTrusted(cwd)
5272
5525
 
5526
+ // Plugin hooks are registered in the engine, not in settings.json. Reading
5527
+ // only the two settings files hid them: `/hooks` could report "no hooks"
5528
+ // while a plugin's hook still fired (CC 2.1.334-077).
5529
+ const pluginHooks = (ctx.engine?.getHookEngine?.()?.listHooks() ?? []).filter(
5530
+ (hook) => hook.source !== undefined,
5531
+ )
5532
+
5273
5533
  type Entry = { matcher?: string; hooks: Array<{ type: string; command?: string }> }
5274
5534
  const sources: Array<{ project: boolean; hooks: Record<string, Entry[]> }> = [
5275
5535
  { project: true, hooks: projectHooks as Record<string, Entry[]> },
@@ -5288,7 +5548,7 @@ const hooksListCmd: CommandHandler = async (ctx) => {
5288
5548
  }
5289
5549
  }
5290
5550
 
5291
- if (byEvent.size === 0) {
5551
+ if (byEvent.size === 0 && pluginHooks.length === 0) {
5292
5552
  return { content: t('commands.hooks.no_hooks') }
5293
5553
  }
5294
5554
 
@@ -5324,6 +5584,15 @@ const hooksListCmd: CommandHandler = async (ctx) => {
5324
5584
  }
5325
5585
  }
5326
5586
 
5587
+ for (const hook of pluginHooks) {
5588
+ if (!hooksDisabled) count++
5589
+ const matcher = hook.toolName || '*'
5590
+ const suffix = hooksDisabled ? ` ${t('commands.hooks.disabled_all')}` : ''
5591
+ lines.push(
5592
+ ` [${t('commands.hooks.source_plugin')}: ${hook.source}] ${hook.event} [${matcher}] → plugin-handler${suffix}`,
5593
+ )
5594
+ }
5595
+
5327
5596
  lines.push('')
5328
5597
  lines.push(t('commands.hooks.found', { count: String(count) }))
5329
5598
  return { content: lines.join('\n') }
@@ -6355,6 +6624,13 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
6355
6624
  content: `Server "${sanitizeInlineField(name)}" not found in config.\n\nConfigured: ${mcpServers.map((s) => sanitizeInlineField(s.name)).join(', ') || '(none)'}`,
6356
6625
  }
6357
6626
  }
6627
+ // Disabled is a gate on starting it, so an explicit connect must not tunnel
6628
+ // through it — otherwise "off" lasts exactly until the next `/mcp connect`.
6629
+ if (loadDisabledMcpServers().has(name)) {
6630
+ return {
6631
+ content: `Server "${sanitizeInlineField(name)}" is disabled. Run \`/mcp enable ${sanitizeInlineField(name)}\` first.`,
6632
+ }
6633
+ }
6358
6634
  const isOAuth = config.auth?.type === 'oauth'
6359
6635
  const label = isOAuth ? `${name} (OAuth)` : name
6360
6636
  try {
@@ -6470,7 +6746,13 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
6470
6746
 
6471
6747
  const toolsMap = ctx.engine.getTools()
6472
6748
  const lines: string[] = ['── MCP Reload ──', '']
6749
+ const disabled = loadDisabledMcpServers()
6473
6750
  for (const config of mcpServers) {
6751
+ if (disabled.has(config.name)) {
6752
+ unregisterMcpServerTools(config.name, toolsMap)
6753
+ lines.push(`⏸ ${sanitizeInlineField(config.name)} — disabled, skipped.`)
6754
+ continue
6755
+ }
6474
6756
  // Tools live in the engine registry, not in the connection: drop them before
6475
6757
  // reconnecting so a server that no longer offers a tool does not leave a
6476
6758
  // dead entry registered.
@@ -6488,9 +6770,90 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
6488
6770
  return { content: lines.join('\n') }
6489
6771
  }
6490
6772
 
6773
+ // /mcp enable|disable <name|all>
6774
+ if (sub === 'enable' || sub === 'disable') {
6775
+ const disabling = sub === 'disable'
6776
+ const heading = `MCP ${disabling ? 'Disable' : 'Enable'}`
6777
+ const mcpServers = ctx.config.skills?.mcpServers ?? []
6778
+ if (mcpServers.length === 0) {
6779
+ return { content: `── ${heading} ──\n\nNo MCP servers configured.` }
6780
+ }
6781
+ const disabled = loadDisabledMcpServers()
6782
+ const target = args[1]
6783
+
6784
+ // 没有服务器名时 CC 会打开 MCP 屏幕;这里没有屏幕,就把当前状态列出来并给
6785
+ // 用法。假装打开了一个不会出现的界面,比什么都不做更坏。
6786
+ if (!target) {
6787
+ const lines = [`── ${heading} ──`, '']
6788
+ for (const s of mcpServers) {
6789
+ const state = disabled.has(s.name) ? '⏸ disabled' : '● enabled '
6790
+ lines.push(` ${state} ${sanitizeInlineField(s.name)}`)
6791
+ }
6792
+ lines.push('', `Usage: /mcp ${sub} <server-name> | /mcp ${sub} all`)
6793
+ return { content: lines.join('\n') }
6794
+ }
6795
+
6796
+ if (target !== 'all' && !mcpServers.some((s) => s.name === target)) {
6797
+ return {
6798
+ content: [
6799
+ `── ${heading} ──`,
6800
+ '',
6801
+ `Server "${sanitizeInlineField(target)}" not found in config.`,
6802
+ `Configured: ${mcpServers.map((s) => sanitizeInlineField(s.name)).join(', ')}`,
6803
+ ].join('\n'),
6804
+ }
6805
+ }
6806
+
6807
+ const targets = target === 'all' ? mcpServers.map((s) => s.name) : [target]
6808
+ const next = new Set(disabled)
6809
+ for (const name of targets) {
6810
+ if (disabling) next.add(name)
6811
+ else next.delete(name)
6812
+ }
6813
+
6814
+ // Persist the gate **before** acting on connections: if the write fails, a
6815
+ // server that looked disabled would come straight back next session.
6816
+ let savedPath: string
6817
+ try {
6818
+ savedPath = saveDisabledMcpServers(next)
6819
+ } catch (err) {
6820
+ return {
6821
+ content: `── ${heading} ──\n\nFailed to update settings.json: ${sanitizeInlineField(String(err))}`,
6822
+ }
6823
+ }
6824
+
6825
+ const lines = [
6826
+ `── ${heading}: ${target === 'all' ? 'all' : sanitizeInlineField(target)} ──`,
6827
+ '',
6828
+ ]
6829
+ for (const name of targets) {
6830
+ if (disabling) {
6831
+ client.disconnect(name)
6832
+ unregisterMcpServerTools(name, ctx.engine.getTools())
6833
+ lines.push(
6834
+ `⏸ ${sanitizeInlineField(name)} — disabled; it will not start in future sessions.`,
6835
+ )
6836
+ } else {
6837
+ const config = mcpServers.find((s) => s.name === name)!
6838
+ try {
6839
+ await client.connect(config)
6840
+ const registered = registerMcpServerTools(name, ctx.engine.getTools())
6841
+ lines.push(`🟢 ${sanitizeInlineField(name)} — enabled; ${registered} tool(s) registered.`)
6842
+ } catch (err) {
6843
+ lines.push(
6844
+ `🔴 ${sanitizeInlineField(name)} — enabled, but connecting failed: ${sanitizeInlineField(String(err))}`,
6845
+ )
6846
+ }
6847
+ }
6848
+ }
6849
+ lines.push('', `Saved to ${savedPath}.`)
6850
+ return { content: lines.join('\n') }
6851
+ }
6852
+
6491
6853
  // /mcp (default status)
6492
6854
  const configuredServers = ctx.config.skills?.mcpServers ?? []
6493
6855
  const liveConnections = client.listConnections()
6856
+ const disabledServers = loadDisabledMcpServers()
6494
6857
 
6495
6858
  const lines: string[] = ['── MCP Servers ──', '']
6496
6859
 
@@ -6499,16 +6862,19 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
6499
6862
  lines.push('')
6500
6863
  for (const s of configuredServers) {
6501
6864
  const live = liveConnections.find((c) => c.config.name === s.name)
6502
- const statusIcon = live
6503
- ? live.status === 'connected'
6504
- ? '🟢'
6505
- : live.status === 'connecting'
6506
- ? '🟡'
6507
- : live.status === 'error'
6508
- ? '🔴'
6509
- : '⚪'
6510
- : '⚪'
6511
- const statusLabel = live ? live.status : 'not started'
6865
+ const isDisabled = disabledServers.has(s.name)
6866
+ const statusIcon = isDisabled
6867
+ ? '⏸'
6868
+ : live
6869
+ ? live.status === 'connected'
6870
+ ? '🟢'
6871
+ : live.status === 'connecting'
6872
+ ? '🟡'
6873
+ : live.status === 'error'
6874
+ ? '🔴'
6875
+ : '⚪'
6876
+ : '⚪'
6877
+ const statusLabel = isDisabled ? 'disabled' : live ? live.status : 'not started'
6512
6878
  const oauthTag = s.auth?.type === 'oauth' ? ' [OAuth]' : ''
6513
6879
  lines.push(` ${statusIcon} ${sanitizeInlineField(s.name)}${oauthTag} [${statusLabel}]`)
6514
6880
  const transportInfo = s.url
@@ -6530,6 +6896,8 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
6530
6896
  lines.push(' /mcp disconnect <name> Disconnect from a server')
6531
6897
  lines.push(' /mcp reconnect <name> Reconnect a dropped server (with backoff)')
6532
6898
  lines.push(' /mcp reload Disconnect all and reconnect')
6899
+ lines.push(' /mcp enable <name|all> Enable a disabled server (persisted, user level)')
6900
+ lines.push(' /mcp disable <name|all> Disable a server so it stops starting')
6533
6901
  lines.push('')
6534
6902
  lines.push('── Protocol ──')
6535
6903
  lines.push('MCP stdio transport (JSON-RPC 2.0) — fully implemented.')
@@ -6777,6 +7145,24 @@ Or use the Agent tool in a conversation to launch a sub-agent.`,
6777
7145
  return { content: lines.join('\n') }
6778
7146
  }
6779
7147
 
7148
+ const subtaskCmd: CommandHandler = (_ctx, args) => {
7149
+ const prompt = args.join(' ').trim()
7150
+ if (!prompt) {
7151
+ return {
7152
+ content:
7153
+ 'Usage: /subtask <task>\n\n' +
7154
+ "Sends a fork subagent with this conversation's full context; its result returns to this chat.",
7155
+ }
7156
+ }
7157
+ return {
7158
+ content: "Dispatching a fork subagent with this conversation's context…",
7159
+ forwardToAI:
7160
+ 'Use the Agent tool with subagent_type "fork", run_in_background: false, and description "subtask" ' +
7161
+ 'to complete this task with the full conversation context, then report its result in this conversation:\n\n' +
7162
+ prompt,
7163
+ }
7164
+ }
7165
+
6780
7166
  const bgCmd: CommandHandler = async (ctx, args) => {
6781
7167
  const prompt = args.join(' ')
6782
7168
  if (!prompt.trim()) {
@@ -7220,6 +7606,7 @@ const commandsListCmd: CommandHandler = () => {
7220
7606
  '/dream': 'Session & Identity',
7221
7607
  '/constitution': 'Session & Identity',
7222
7608
  '/bug-report': 'Session & Identity',
7609
+ '/bug': 'Session & Identity',
7223
7610
  '/changelog': 'Session & Identity',
7224
7611
  '/resume': 'Session & Identity',
7225
7612
  '/resume last': 'Session & Identity',
@@ -7251,6 +7638,8 @@ const commandsListCmd: CommandHandler = () => {
7251
7638
  '/remove-skill': 'Tools & Skills',
7252
7639
  '/mcp': 'Tools & Skills',
7253
7640
  '/plugins': 'Plugins',
7641
+ '/plugin': 'Plugins',
7642
+ '/reload-plugins': 'Plugins',
7254
7643
  '/browse-plugins': 'Plugins',
7255
7644
  '/install-plugin': 'Plugins',
7256
7645
  '/remove-plugin': 'Plugins',
@@ -7302,6 +7691,7 @@ const commandsListCmd: CommandHandler = () => {
7302
7691
  '/prompt-audit': 'Code Quality',
7303
7692
  '/ide': 'Environment',
7304
7693
  '/terminal-setup': 'Environment',
7694
+ '/statusline': 'Environment',
7305
7695
  '/memory': 'Environment',
7306
7696
  '/release-notes': 'Environment',
7307
7697
  '/login': 'Account',
@@ -7313,6 +7703,8 @@ const commandsListCmd: CommandHandler = () => {
7313
7703
  '/feedback': 'Account',
7314
7704
  '/telemetry': 'Account',
7315
7705
  '/agents': 'Agents',
7706
+ '/list-agents': 'Agents',
7707
+ '/subtask': 'Agents',
7316
7708
  '/bg': 'Agents',
7317
7709
  '/fork': 'Agents',
7318
7710
  '/artifact': 'Artifacts',
@@ -7323,12 +7715,15 @@ const commandsListCmd: CommandHandler = () => {
7323
7715
  '/ship': 'Workflow',
7324
7716
  '/issue': 'Workflow',
7325
7717
  '/code-review': 'Code Quality',
7718
+ '/security-review': 'Code Quality',
7326
7719
  '/simplify': 'Code Quality',
7327
7720
  '/verify': 'Code Quality',
7328
7721
  '/design': 'Code Quality',
7329
7722
  '/lint': 'Code Quality',
7330
7723
  '/files': 'Session & Identity',
7331
7724
  '/stats': 'Session & Identity',
7725
+ '/insights': 'Session & Identity',
7726
+ '/autocompact': 'Session & Identity',
7332
7727
  '/summary': 'Session & Identity',
7333
7728
  '/cd': 'Session & Identity',
7334
7729
  '/hooks': 'Workflow',
@@ -7464,6 +7859,8 @@ registry.set('/marketplace', marketplaceCmd)
7464
7859
  registry.set('/browse-marketplace', browseMarketplaceCmd)
7465
7860
  registry.set('/remove-skill', removeSkillCmd)
7466
7861
  registry.set('/plugins', pluginsCmd)
7862
+ registry.set('/plugin', pluginsCmd)
7863
+ registry.set('/reload-plugins', reloadPluginsCmd)
7467
7864
  registry.set('/browse-plugins', browsePluginsCmd)
7468
7865
  registry.set('/install-plugin', installPluginCmd)
7469
7866
  registry.set('/remove-plugin', removePluginCmd)
@@ -7496,6 +7893,7 @@ registry.set('/sis cleanup', sisCleanupCmd)
7496
7893
  registry.set('/dream', dreamCmd)
7497
7894
  registry.set('/constitution', constitutionCmd)
7498
7895
  registry.set('/bug-report', bugReportCmd)
7896
+ registry.set('/bug', bugReportCmd)
7499
7897
  registry.set('/changelog', changelogCmd)
7500
7898
 
7501
7899
  // Workflow
@@ -7554,8 +7952,10 @@ registry.set('/keys audit', keysCmd)
7554
7952
  registry.set('/keys view', keysCmd)
7555
7953
  registry.set('/feedback', feedbackCmd)
7556
7954
  registry.set('/agents', agentsCmd)
7955
+ registry.set('/list-agents', agentsCmd)
7557
7956
  registry.set('/bg', bgCmd)
7558
7957
  registry.set('/fork', forkCmd)
7958
+ registry.set('/subtask', subtaskCmd)
7559
7959
 
7560
7960
  // Artifacts
7561
7961
  registry.set('/artifact', artifactBaseCmd)
@@ -7573,6 +7973,7 @@ registry.set('/issue', issueCmd)
7573
7973
 
7574
7974
  // Code Quality (Claude Code parity)
7575
7975
  registry.set('/code-review', codeReviewCmd)
7976
+ registry.set('/security-review', securityReviewCmd)
7576
7977
  registry.set('/simplify', simplifyCmd)
7577
7978
  registry.set('/verify', verifyCmd)
7578
7979
  registry.set('/design', designCmd)
@@ -7580,6 +7981,9 @@ registry.set('/lint', lintCmd)
7580
7981
 
7581
7982
  // Session Enhancement (Claude Code parity)
7582
7983
  registry.set('/files', filesCmd)
7984
+ registry.set('/insights', insightsCmd)
7985
+ registry.set('/autocompact', autocompactCmd)
7986
+ registry.set('/statusline', statuslineCmd)
7583
7987
  registry.set('/stats', statsCmd)
7584
7988
  registry.set('/summary', summaryCmd)
7585
7989
  registry.set('/cd', cdCmd)
@@ -7681,6 +8085,7 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7681
8085
  '/dream': 'Background memory consolidation',
7682
8086
  '/constitution': 'View or reload constitutional principles',
7683
8087
  '/bug-report': 'Generate diagnostic report for GitHub Issues',
8088
+ '/bug': 'Report a bug (alias of /bug-report)',
7684
8089
  '/changelog': 'Recent version history',
7685
8090
  '/resume': 'List saved sessions',
7686
8091
  '/resume last': 'Restore the most recent saved session',
@@ -7709,8 +8114,11 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7709
8114
  '/marketplace': 'Manage marketplace sources (add/list/remove)',
7710
8115
  '/browse-marketplace': 'Browse skills across all marketplace sources',
7711
8116
  '/remove-skill': 'Remove an installed skill',
7712
- '/mcp': 'MCP server status',
8117
+ '/mcp': 'MCP server status; enable/disable servers',
7713
8118
  '/plugins': 'List installed plugins',
8119
+ '/plugin':
8120
+ 'List plugins (alias of /plugins; use /install-plugin, /remove-plugin, /plugin-enable, /plugin-disable to manage)',
8121
+ '/reload-plugins': 'Reload enabled plugins in this session',
7714
8122
  '/browse-plugins': 'Browse community plugin marketplace',
7715
8123
  '/install-plugin': 'Install a plugin from npm or local path',
7716
8124
  '/remove-plugin': 'Remove an installed plugin',
@@ -7776,6 +8184,8 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7776
8184
  '/keys view': 'View a provider plaintext API key',
7777
8185
  '/feedback': 'Send feedback',
7778
8186
  '/agents': 'Agent view dashboard',
8187
+ '/list-agents': 'List background agent sessions (alias of /agents)',
8188
+ '/subtask': 'Send a fork subagent with full context; its result returns here',
7779
8189
  '/bg': 'Run a background agent task',
7780
8190
  '/fork': 'Fork task into isolated worktree',
7781
8191
  '/artifact': 'Manage artifacts',
@@ -7786,11 +8196,15 @@ const COMMAND_DESCRIPTIONS: Record<string, string> = {
7786
8196
  '/ship': 'Commit, push, open a PR, review and fix it — never merges',
7787
8197
  '/issue': 'Draft a GitHub issue from your description',
7788
8198
  '/code-review': 'Review code for bugs, security, performance (7 dimensions)',
8199
+ '/security-review': 'Review pending changes for security issues (security-review skill)',
7789
8200
  '/simplify': 'Cleanup-only review: reuse, simplification, efficiency, abstraction',
7790
8201
  '/verify': 'Runtime verification — observe actual execution, not tests',
7791
8202
  '/design': 'Start architectural design session — explore approaches and trade-offs',
7792
8203
  '/lint': 'Run linting on the project',
7793
8204
  '/files': 'List files in current working directory',
8205
+ '/insights': 'Analyze local session history (counts only, no message text)',
8206
+ '/autocompact': 'Show or set the hard context-compaction threshold',
8207
+ '/statusline': 'Configure the footer status line (full|compact|off)',
7794
8208
  '/stats': 'Show session usage statistics',
7795
8209
  '/summary': 'Generate session summary',
7796
8210
  '/cd': 'Change session working directory',