@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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Mipham Code v0.85.52
1
+ # Mipham Code v0.85.54
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
3
+ **Multi-model open-core intelligent coding terminal** — 12 AI providers, 150 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
5
5
  Built by [One Mipham Corporation](https://onemipham.com) (北京华安麦逄科技有限公司) | Brand: MiphamAI
6
6
 
@@ -16,7 +16,7 @@ Requirements: **Bun 1.2+** (recommended) or **Node.js 22+**
16
16
  ## Features
17
17
 
18
18
  - **12 AI Providers** — Anthropic Claude · OpenAI GPT · DeepSeek · Kimi (Moonshot) · Google Gemini · Doubao 豆包 · Tencent Hunyuan 混元 · Qwen 通义千问 · MiniMax(国内 / 国际)· Ollama(本地)· MiphamAI
19
- - **141 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **150 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
20
20
  - **31 Built-in Tools** — File ops, shell execution, agent dispatch, MCP integration, web search
21
21
  - **28 Skills + Marketplace** — 22 standard + 6 Mipham-exclusive skills. `/browse-skills` `/install-skill` community marketplace
22
22
  - **Self-Update** — `mipham update` / `/upgrade` — one command to check, backup config, upgrade, restore. API keys preserved
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.52",
3
+ "version": "0.85.54",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -44,7 +44,7 @@
44
44
  "mutate": "stryker run"
45
45
  },
46
46
  "dependencies": {
47
- "@larksuiteoapi/node-sdk": "^1.76.0",
47
+ "@larksuiteoapi/node-sdk": "^1.77.0",
48
48
  "commander": "^13.1.0",
49
49
  "ink": "^7.1.1",
50
50
  "ink-text-input": "^6.0.0",
@@ -56,10 +56,10 @@
56
56
  "@mipham/shared": "workspace:*",
57
57
  "@stryker-mutator/core": "10.1.1",
58
58
  "@stryker-mutator/vitest-runner": "10.0.0",
59
- "@types/bun": "^1.4.4",
60
- "@types/node": "^22.20.5",
61
- "@types/react": "^19.3.0",
62
- "@vitest/coverage-v8": "^5.0.5",
59
+ "@types/bun": "^1.4.5",
60
+ "@types/node": "^22.20.7",
61
+ "@types/react": "^19.3.3",
62
+ "@vitest/coverage-v8": "^5.1.2",
63
63
  "ink-testing-library": "^4.0.0",
64
64
  "vitest": "^5.0.5"
65
65
  }
@@ -13,13 +13,28 @@ interface FrontmatterResult {
13
13
  function parseFrontmatter(raw: string): FrontmatterResult {
14
14
  // Strip a leading UTF-8 BOM — otherwise `^---` never matches and a
15
15
  // BOM-prefixed file is silently treated as body text (effectively ignored).
16
- const src = raw.replace(/^\uFEFF/, '')
16
+ // Normalize CRLF: a Windows-authored agent file used to match none of the
17
+ // `\n`-anchored fence below, so its declared name/description were dropped
18
+ // (CC 2.1.333-097).
19
+ const src = raw.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
17
20
  const match = src.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/)
18
21
  if (!match) {
19
22
  return { data: {}, content: src }
20
23
  }
24
+ let data: Record<string, unknown> = {}
25
+ try {
26
+ const parsed = parseYaml(match[1] || '')
27
+ data =
28
+ parsed && typeof parsed === 'object' && !Array.isArray(parsed)
29
+ ? (parsed as Record<string, unknown>)
30
+ : {}
31
+ } catch {
32
+ // Hand-written headers can contain an unquoted `Fix: a bug`, which strict
33
+ // YAML rejects. Dropping the header is better than dropping the file: the
34
+ // body still loads, and `name` falls back to the file name.
35
+ }
21
36
  return {
22
- data: parseYaml(match[1] || '') as Record<string, unknown>,
37
+ data,
23
38
  content: (match[2] || '').trim(),
24
39
  }
25
40
  }
@@ -66,40 +66,56 @@ const ideCmd: CommandHandler = async (_ctx) => {
66
66
  // (and `keybindings.json` is commonly JSONC, so an unparseable file must be
67
67
  // left alone rather than replaced).
68
68
  const { readRegularFileSync } = await import('../shared/regular-file')
69
- const readJson = (path: string): unknown => {
69
+ // `undefined` used to mean both "no file yet" (safe to create) and "a file we
70
+ // could not parse" (must not be touched). The caller treated both as empty,
71
+ // so a JSONC `settings.json` — trailing commas or comments — was replaced
72
+ // with a fresh `{}` plus one profile, destroying every other key. Distinguish
73
+ // the two states and skip the file when we cannot parse it (CC 2.1.335-031).
74
+ type ReadResult =
75
+ { kind: 'missing' } | { kind: 'parsed'; value: unknown } | { kind: 'unparseable' }
76
+ const readJson = (path: string): ReadResult => {
70
77
  const raw = readRegularFileSync(path)
71
- if (raw === null) return undefined
78
+ if (raw === null) return { kind: 'missing' }
72
79
  try {
73
- return JSON.parse(raw)
80
+ return { kind: 'parsed', value: JSON.parse(raw) }
74
81
  } catch {
75
- return undefined // JSONC / hand-edited — refuse to rewrite
82
+ return { kind: 'unparseable' }
76
83
  }
77
84
  }
78
85
  const isObject = (v: unknown): v is Record<string, unknown> =>
79
86
  v !== null && typeof v === 'object' && !Array.isArray(v)
87
+ const skipped: string[] = []
80
88
 
81
89
  // ── settings.json: terminal profile ──
82
90
  const settingsPath = join(vscodeDir, 'settings.json')
83
- const existingSettings = readJson(settingsPath)
84
- const settings: Record<string, unknown> = isObject(existingSettings) ? existingSettings : {}
85
- const profiles = isObject(settings['terminal.integrated.profiles.osx'])
86
- ? (settings['terminal.integrated.profiles.osx'] as Record<string, unknown>)
87
- : {}
88
- profiles.mipham = {
89
- path: bunPath,
90
- args: ['run', 'mipham'],
91
- cwd: '${workspaceFolder}',
91
+ const settingsState = readJson(settingsPath)
92
+ if (settingsState.kind === 'unparseable') {
93
+ skipped.push('.vscode/settings.json (JSONC or hand-edited — left unchanged)')
94
+ } else {
95
+ const settings: Record<string, unknown> =
96
+ settingsState.kind === 'parsed' && isObject(settingsState.value) ? settingsState.value : {}
97
+ const profiles = isObject(settings['terminal.integrated.profiles.osx'])
98
+ ? (settings['terminal.integrated.profiles.osx'] as Record<string, unknown>)
99
+ : {}
100
+ profiles.mipham = {
101
+ path: bunPath,
102
+ args: ['run', 'mipham'],
103
+ cwd: '${workspaceFolder}',
104
+ }
105
+ settings['terminal.integrated.profiles.osx'] = profiles
106
+ atomicWriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', { mode: 0o644 })
107
+ files.push('.vscode/settings.json')
92
108
  }
93
- settings['terminal.integrated.profiles.osx'] = profiles
94
- atomicWriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', { mode: 0o644 })
95
- files.push('.vscode/settings.json')
96
109
 
97
110
  // ── keybindings.json: Cmd+Esc launch ──
98
111
  const keybindingsPath = join(vscodeDir, 'keybindings.json')
99
- const existingKeybindings = readJson(keybindingsPath)
100
- const keybindings: Record<string, unknown>[] = Array.isArray(existingKeybindings)
101
- ? (existingKeybindings as Record<string, unknown>[])
102
- : []
112
+ const keybindingsState = readJson(keybindingsPath)
113
+ const keybindings: Record<string, unknown>[] = []
114
+ if (keybindingsState.kind === 'unparseable') {
115
+ skipped.push('.vscode/keybindings.json (JSONC or hand-edited — left unchanged)')
116
+ } else if (keybindingsState.kind === 'parsed' && Array.isArray(keybindingsState.value)) {
117
+ keybindings.push(...(keybindingsState.value as Record<string, unknown>[]))
118
+ }
103
119
  const wanted = [
104
120
  {
105
121
  key: 'cmd+escape',
@@ -111,27 +127,40 @@ const ideCmd: CommandHandler = async (_ctx) => {
111
127
  command: 'workbench.action.terminal.new',
112
128
  },
113
129
  ]
114
- for (const entry of wanted) {
115
- if (!keybindings.some((k) => k.key === entry.key && k.command === entry.command)) {
116
- keybindings.push(entry)
130
+ if (keybindingsState.kind !== 'unparseable') {
131
+ for (const entry of wanted) {
132
+ if (!keybindings.some((k) => k.key === entry.key && k.command === entry.command)) {
133
+ keybindings.push(entry)
134
+ }
117
135
  }
136
+ atomicWriteFileSync(keybindingsPath, JSON.stringify(keybindings, null, 2) + '\n', {
137
+ mode: 0o644,
138
+ })
139
+ files.push('.vscode/keybindings.json')
118
140
  }
119
- atomicWriteFileSync(keybindingsPath, JSON.stringify(keybindings, null, 2) + '\n', { mode: 0o644 })
120
- files.push('.vscode/keybindings.json')
121
141
 
122
142
  // ── extensions.json: recommended ──
123
143
  const extensionsPath = join(vscodeDir, 'extensions.json')
124
- const existingExtensions = readJson(extensionsPath)
125
- const extensions: Record<string, unknown> = isObject(existingExtensions) ? existingExtensions : {}
126
- const recommendations = Array.isArray(extensions.recommendations)
127
- ? (extensions.recommendations as unknown[])
128
- : []
129
- if (!recommendations.includes('miphamai.mipham-code')) {
130
- recommendations.push('miphamai.mipham-code')
144
+ const extensionsState = readJson(extensionsPath)
145
+ if (extensionsState.kind === 'unparseable') {
146
+ skipped.push('.vscode/extensions.json (JSONC or hand-edited — left unchanged)')
147
+ } else {
148
+ const extensions: Record<string, unknown> =
149
+ extensionsState.kind === 'parsed' && isObject(extensionsState.value)
150
+ ? extensionsState.value
151
+ : {}
152
+ const recommendations = Array.isArray(extensions.recommendations)
153
+ ? (extensions.recommendations as unknown[])
154
+ : []
155
+ if (!recommendations.includes('miphamai.mipham-code')) {
156
+ recommendations.push('miphamai.mipham-code')
157
+ }
158
+ extensions.recommendations = recommendations
159
+ atomicWriteFileSync(extensionsPath, JSON.stringify(extensions, null, 2) + '\n', {
160
+ mode: 0o644,
161
+ })
162
+ files.push('.vscode/extensions.json')
131
163
  }
132
- extensions.recommendations = recommendations
133
- atomicWriteFileSync(extensionsPath, JSON.stringify(extensions, null, 2) + '\n', { mode: 0o644 })
134
- files.push('.vscode/extensions.json')
135
164
 
136
165
  return {
137
166
  content: [
@@ -139,6 +168,13 @@ const ideCmd: CommandHandler = async (_ctx) => {
139
168
  '',
140
169
  `Generated in ${vscodeDir}:`,
141
170
  ...files.map((f) => ` ✅ ${f}`),
171
+ ...(skipped.length > 0
172
+ ? [
173
+ '',
174
+ 'Left unchanged (could not parse as JSON — comments or trailing commas):',
175
+ ...skipped.map((f) => ` ⚠ ${f}`),
176
+ ]
177
+ : []),
142
178
  '',
143
179
  'What was configured:',
144
180
  ' • Terminal profile "mipham" — opens Mipham Code in integrated terminal',
@@ -1025,6 +1025,37 @@ const promptAuditCmd: CommandHandler = async () => {
1025
1025
  message: 'Overly verbose constraint language',
1026
1026
  suggestion: 'Replace "you must ensure that" with imperative: "Ensure".',
1027
1027
  },
1028
+ // These three are the patterns that make a capable model stop thinking:
1029
+ // ask-first for everything, delegate everything, and treat any earlier
1030
+ // answer as permanently settled. Deliberately no rule flags "stop early"
1031
+ // or "stop when the answer is clear" — that guidance is what keeps a model
1032
+ // from grinding past a decision it has already made (CC 2.1.335-069).
1033
+ {
1034
+ id: 'broad-ask-first',
1035
+ pattern:
1036
+ /\b(ask|check with|confirm with)\s+(the user|me|them)\b.{0,40}\b(first|before|whenever|any ?time)\b/i,
1037
+ severity: 'medium',
1038
+ message: 'Broad ask-first rule',
1039
+ suggestion:
1040
+ 'Name the actions that genuinely need confirmation instead of asking before everything.',
1041
+ },
1042
+ {
1043
+ id: 'always-delegate',
1044
+ pattern:
1045
+ /\b(always|whenever|every time)\b.{0,60}\b(delegate|spawn|use)\b.{0,30}\b(sub-?agent|agent)\b/i,
1046
+ severity: 'medium',
1047
+ message: 'Always-delegate instruction',
1048
+ suggestion: 'Delegation is a judgment call. Say when it pays off, not "always".',
1049
+ },
1050
+ {
1051
+ id: 'earlier-answers-done',
1052
+ pattern:
1053
+ /\b(treat|consider|regard|take)\b.{0,40}\b(earlier|previous|prior)\b.{0,30}\b(answer|response|reply)s?\b.{0,20}\b(as )?(done|settled|final|answered)\b/i,
1054
+ severity: 'medium',
1055
+ message: 'Instruction to treat earlier answers as done',
1056
+ suggestion:
1057
+ 'An earlier answer can stop holding when facts change. Say what counts as a change.',
1058
+ },
1028
1059
  ]
1029
1060
 
1030
1061
  // Files to scan
@@ -421,7 +421,10 @@ function loadMcpJson(cwd: string, warn?: (message: string) => void): McpServerCo
421
421
 
422
422
  let parsed: unknown
423
423
  try {
424
- parsed = JSON.parse(raw)
424
+ // Editors on Windows often save a UTF-8 BOM. `JSON.parse` rejects it, and
425
+ // the file is then reported as malformed and skipped — every server it
426
+ // declared silently disappears (CC 2.1.334-074).
427
+ parsed = JSON.parse(raw.replace(/^\uFEFF/, ''))
425
428
  } catch (err) {
426
429
  // A malformed file used to be skipped in silence, so every server it
427
430
  // declared simply did not exist: the user saw "no such server" with no
@@ -642,7 +645,7 @@ export function loadSettingsJson(
642
645
  }
643
646
  continue
644
647
  }
645
- const parsed = JSON.parse(raw) as {
648
+ const parsed = JSON.parse(raw.replace(/^\uFEFF/, '')) as {
646
649
  hooks?: Record<string, unknown>
647
650
  disableAllHooks?: unknown
648
651
  permissions?: {
@@ -909,7 +912,7 @@ export function readSettingsDoc(path: string): Record<string, unknown> {
909
912
  if (raw === null) return {}
910
913
  let parsed: unknown
911
914
  try {
912
- parsed = JSON.parse(raw)
915
+ parsed = JSON.parse(raw.replace(/^\uFEFF/, ''))
913
916
  } catch (err) {
914
917
  throw new Error(
915
918
  `${path} is not valid JSON — ${jsonErrorDetail(raw, err)}. Fix or remove it, then retry.`,
@@ -990,6 +993,52 @@ export function removeSettingsRule(
990
993
  return null
991
994
  }
992
995
 
996
+ /**
997
+ * settings.json key holding the MCP server names the user turned off with
998
+ * `/mcp disable` (user level only — see `loadDisabledMcpServers`).
999
+ */
1000
+ export const DISABLED_MCP_KEY = 'disabledMcpServers'
1001
+
1002
+ /**
1003
+ * MCP servers the user turned off, read from the **user-level** settings.json.
1004
+ *
1005
+ * User level only on purpose: a project-level file would let a repository
1006
+ * silently disable the operator's own servers for every session in that tree —
1007
+ * the same trust problem `permissions.allow` has, resolved the same way (the
1008
+ * loader only reads the user's file).
1009
+ *
1010
+ * A malformed settings.json yields an empty set here rather than an error: this
1011
+ * runs on the startup path, where throwing would take the session down before
1012
+ * the user could fix the file. The writer (`saveDisabledMcpServers`) still
1013
+ * refuses to clobber it.
1014
+ */
1015
+ export function loadDisabledMcpServers(): Set<string> {
1016
+ try {
1017
+ const doc = readSettingsDoc(settingsPathFor('user'))
1018
+ const list = doc[DISABLED_MCP_KEY]
1019
+ if (!Array.isArray(list)) return new Set()
1020
+ return new Set(list.filter((v): v is string => typeof v === 'string'))
1021
+ } catch {
1022
+ return new Set()
1023
+ }
1024
+ }
1025
+
1026
+ /**
1027
+ * Persist the full disabled-server set (sorted, deduped). An empty set removes
1028
+ * the key entirely, so "never disabled anything" and "edited it back" look the
1029
+ * same in the file. Returns the path written; throws if settings.json is not
1030
+ * valid JSON or is not an object — the user's other settings live there.
1031
+ */
1032
+ export function saveDisabledMcpServers(names: Iterable<string>): string {
1033
+ const path = settingsPathFor('user')
1034
+ const doc = readSettingsDoc(path)
1035
+ const sorted = [...new Set(names)].sort()
1036
+ if (sorted.length === 0) delete doc[DISABLED_MCP_KEY]
1037
+ else doc[DISABLED_MCP_KEY] = sorted
1038
+ writeSettingsDoc(path, doc)
1039
+ return path
1040
+ }
1041
+
993
1042
  export function loadConfig(cwd: string = process.cwd()): MiphamConfig {
994
1043
  // `null` when cwd is the home directory, where the "project" config *is* the user
995
1044
  // config read further down (`MIPHAM_HOME` and `join(cwd, MIPHAM_DIR)` coincide) —
@@ -174,6 +174,9 @@ export class ContextManager {
174
174
  this.calculateThresholds()
175
175
  }
176
176
 
177
+ /** User-chosen hard-compaction threshold; `null` = derive from the window. */
178
+ private compactionThresholdOverride: number | null = null
179
+
177
180
  private log?: SessionLog
178
181
 
179
182
  /**
@@ -222,6 +225,15 @@ export class ContextManager {
222
225
  * microcompact: 200K→0.70(→clamped 0.70), 500K→0.80, 1M→0.85
223
226
  */
224
227
  calculateThresholds(): void {
228
+ // An explicit user override wins over the window formula — including on
229
+ // model switches, which re-enter here through `updateMaxTokens()`. It must
230
+ // be applied before the `!w` early return: a session with adaptive
231
+ // thresholds off still has a context window value of undefined.
232
+ if (this.compactionThresholdOverride !== null) {
233
+ this.config.compactionThreshold = this.compactionThresholdOverride
234
+ return
235
+ }
236
+
225
237
  const w = this.config.contextWindow
226
238
  if (!w) return
227
239
 
@@ -236,6 +248,15 @@ export class ContextManager {
236
248
  return this.config.compactionThreshold
237
249
  }
238
250
 
251
+ /**
252
+ * Set (or clear, with `null`) a user-chosen hard-compaction threshold.
253
+ * Microcompaction keeps its own earlier window-derived schedule.
254
+ */
255
+ setCompactionThresholdOverride(threshold: number | null): void {
256
+ this.compactionThresholdOverride = threshold
257
+ this.calculateThresholds()
258
+ }
259
+
239
260
  /** Dynamically update the max token limit (e.g., when switching models). */
240
261
  updateMaxTokens(maxTokens: number, contextWindow?: number): void {
241
262
  this.config.maxTokens = maxTokens
@@ -97,6 +97,26 @@ export function globToRegexSource(pattern: string): string {
97
97
  i++
98
98
  continue
99
99
  }
100
+ if (ch === '{') {
101
+ // Brace alternation, nesting included: `src/{a,b/{c,d}}/*.ts`. Escaped
102
+ // literally before, so a rule's `paths:` silently matched none of the
103
+ // files it named (CC 2.1.334-101).
104
+ let depth = 1
105
+ let j = i + 1
106
+ while (j < pattern.length && depth > 0) {
107
+ if (pattern[j] === '{') depth++
108
+ else if (pattern[j] === '}') depth--
109
+ j++
110
+ }
111
+ if (depth === 0) {
112
+ const inner = pattern.slice(i + 1, j - 1)
113
+ const alternatives = splitBraceAlternatives(inner)
114
+ regexStr += '(?:' + alternatives.map((p) => globToRegexSource(p)).join('|') + ')'
115
+ i = j
116
+ continue
117
+ }
118
+ // Unbalanced `{` — fall through and treat it literally.
119
+ }
100
120
  // Escape regex special chars
101
121
  if ('\\^$.|+()[]{}'.includes(ch)) {
102
122
  regexStr += '\\' + ch
@@ -108,6 +128,24 @@ export function globToRegexSource(pattern: string): string {
108
128
  return regexStr
109
129
  }
110
130
 
131
+ /** Split a brace alternation's body on commas that are not inside nested braces. */
132
+ function splitBraceAlternatives(inner: string): string[] {
133
+ const out: string[] = []
134
+ let depth = 0
135
+ let start = 0
136
+ for (let i = 0; i < inner.length; i++) {
137
+ const ch = inner[i]
138
+ if (ch === '{') depth++
139
+ else if (ch === '}') depth--
140
+ else if (ch === ',' && depth === 0) {
141
+ out.push(inner.slice(start, i))
142
+ start = i + 1
143
+ }
144
+ }
145
+ out.push(inner.slice(start))
146
+ return out
147
+ }
148
+
111
149
  /**
112
150
  * Convert a glob pattern to a full-path-anchored RegExp (see `globToRegexSource`
113
151
  * for the `*`/`**`/`?` translation and escaping rules).
@@ -492,6 +492,25 @@ export class QueryEngine {
492
492
  this.instructionsLoader = loader
493
493
  }
494
494
 
495
+ /**
496
+ * Re-root the instruction chain at `cwd` and rebuild the system prompt
497
+ * (`/cd` — the loader it was built from still points at the directory the
498
+ * session was opened in, so entering a worktree and coming back kept reading
499
+ * the old chain).
500
+ *
501
+ * `loadAll` resets the loader in place, which is what keeps this one object
502
+ * behind both consumers: the base prompt (via the context rebuilder, which
503
+ * re-reads from the same instance) and the per-path nested-file lookup.
504
+ * Returns false when no loader is registered (daemon/attach paths, where the
505
+ * instruction chain belongs to the host process).
506
+ */
507
+ reloadInstructions(cwd: string): boolean {
508
+ if (!this.instructionsLoader) return false
509
+ this.instructionsLoader.loadAll(cwd)
510
+ this.context.refreshSystemPrompt()
511
+ return true
512
+ }
513
+
495
514
  /** Register inference hook (DLP) configuration. */
496
515
  setInferenceHookConfig(config: InferenceHookConfig): void {
497
516
  this.inferenceHookConfig = config
@@ -801,7 +820,10 @@ export class QueryEngine {
801
820
 
802
821
  // Check compaction before processing
803
822
  if (this.context.needsCompaction()) {
804
- await this.compactWithHooks('conversation summary', signal)
823
+ const compact = await this.compactWithHooks('conversation summary', signal)
824
+ if (compact.blocked) {
825
+ yield { type: 'warning', content: `Compaction skipped: ${compact.reason}` }
826
+ }
805
827
  }
806
828
 
807
829
  const systemPrompt = applyUltracodeMode(this.context.getSystemPrompt(), this.ultracode)
@@ -2037,7 +2059,8 @@ export class QueryEngine {
2037
2059
  restart: true,
2038
2060
  }
2039
2061
  try {
2040
- await this.compactWithHooks('context overflow', signal)
2062
+ const compact = await this.compactWithHooks('context overflow', signal)
2063
+ if (compact.blocked) throw new Error(compact.reason)
2041
2064
  msgs = this.context.getMessages()
2042
2065
  sysPrompt = this.context.getSystemPrompt()
2043
2066
  } catch (err) {
@@ -2455,10 +2478,27 @@ export class QueryEngine {
2455
2478
  )
2456
2479
  }
2457
2480
 
2458
- /** Wrap context compaction with PreCompact/PostCompact hooks. */
2459
- private async compactWithHooks(heading: string, signal?: AbortSignal): Promise<void> {
2481
+ /**
2482
+ * Wrap context compaction with PreCompact/PostCompact hooks.
2483
+ *
2484
+ * A blocking PreCompact hook MUST stop the compaction. We used to read only
2485
+ * `additionalContext`, so a hook's `decision: block` and its reason were
2486
+ * discarded and the compaction ran anyway (CC 2.1.334-066). The caller
2487
+ * decides how to surface the block: the turn continues without compacting,
2488
+ * and the 413 retry path falls through to its ordinary failure handling.
2489
+ */
2490
+ private async compactWithHooks(
2491
+ heading: string,
2492
+ signal?: AbortSignal,
2493
+ ): Promise<{ blocked: boolean; reason?: string }> {
2460
2494
  if (this.hookEngine) {
2461
2495
  const preResult = await this.hookEngine.executePreCompact(this.sessionId)
2496
+ if (!preResult.allowed) {
2497
+ return {
2498
+ blocked: true,
2499
+ reason: preResult.reason || 'a PreCompact hook blocked compaction',
2500
+ }
2501
+ }
2462
2502
  if (preResult.additionalContext) {
2463
2503
  this.context.injectContext(
2464
2504
  'pre-compact',
@@ -2484,6 +2524,7 @@ export class QueryEngine {
2484
2524
  )
2485
2525
  }
2486
2526
  }
2527
+ return { blocked: false }
2487
2528
  }
2488
2529
 
2489
2530
  /** Fire Stop hook. If blocked, feed the reason back to the AI and continue. */
package/src/core/hooks.ts CHANGED
@@ -57,6 +57,9 @@ export function mergePermissionDecision(
57
57
  return incScore > currScore ? incoming : current
58
58
  }
59
59
 
60
+ /** Compiled hook matchers, keyed by their source string. Bounded by config size. */
61
+ const matcherCache = new Map<string, RegExp | null>()
62
+
60
63
  export class HookEngine {
61
64
  private hooks: HookDefinition[] = []
62
65
  /** Health tracking per hook key (event[:toolName]) */
@@ -339,14 +342,22 @@ export class HookEngine {
339
342
  */
340
343
  private matchesMatcher(matcher: string | undefined, name: string | undefined): boolean {
341
344
  if (!matcher || !name) return true
342
- try {
343
- return new RegExp(matcher).test(name)
344
- } catch {
345
- // An uncompilable pattern cannot get this far through loadHookConfigs,
346
- // which compiles every matcher when it loads. Keep such a hook running
347
- // rather than dropping it silently.
348
- return true
345
+ // Compile once per pattern. A hook whose matcher does not apply is still
346
+ // consulted on every call/row/key; recompiling its regex there was pure
347
+ // per-keystroke work (CC 2.1.333-167). `null` caches "does not compile".
348
+ let compiled = matcherCache.get(matcher)
349
+ if (compiled === undefined) {
350
+ try {
351
+ compiled = new RegExp(matcher)
352
+ } catch {
353
+ compiled = null
354
+ }
355
+ matcherCache.set(matcher, compiled)
349
356
  }
357
+ // An uncompilable pattern cannot get this far through loadHookConfigs,
358
+ // which compiles every matcher when it loads. Keep such a hook running
359
+ // rather than dropping it silently.
360
+ return compiled === null ? true : compiled.test(name)
350
361
  }
351
362
 
352
363
  private async runHooks(
@@ -25,13 +25,27 @@ export interface FrontmatterResult {
25
25
  export function parseFrontmatter(raw: string): FrontmatterResult {
26
26
  // Strip a leading UTF-8 BOM — otherwise `^---` never matches and a
27
27
  // BOM-prefixed file is silently treated as body text (effectively ignored).
28
- const src = raw.replace(/^\uFEFF/, '')
28
+ // Normalize CRLF: a Windows-authored instruction file used to match none of
29
+ // the `\n`-anchored fence below, so its header (e.g. `prompt-exclude`) was
30
+ // ignored (CC 2.1.333-097).
31
+ const src = raw.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n')
29
32
  const match = src.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/)
30
33
  if (!match) {
31
34
  return { data: {}, content: src }
32
35
  }
36
+ let data: Record<string, unknown> = {}
37
+ try {
38
+ const parsed = parseYaml(match[1] || '')
39
+ data =
40
+ parsed && typeof parsed === 'object' && !Array.isArray(parsed)
41
+ ? (parsed as Record<string, unknown>)
42
+ : {}
43
+ } catch {
44
+ // An unquoted `Fix: a bug` is invalid YAML. Keep the body rather than
45
+ // letting the throw drop the whole instruction file.
46
+ }
33
47
  return {
34
- data: parseYaml(match[1] || '') as Record<string, unknown>,
48
+ data,
35
49
  content: match[2] || '',
36
50
  }
37
51
  }
@@ -273,7 +273,10 @@ export class RulesLoader {
273
273
  return { paths: [], description: '', content: raw.trim() }
274
274
  }
275
275
 
276
- const frontmatter = match[1] || ''
276
+ // The fence regex accepts CRLF, but the line parsers below split on `\n`
277
+ // and anchor with `$`, so a trailing `\r` made `paths:`/`description:`
278
+ // silently miss. Normalize before reading keys.
279
+ const frontmatter = (match[1] || '').replace(/\r/g, '')
277
280
  const body = (match[2] || '').trim()
278
281
 
279
282
  const paths: string[] = []