@miphamai/cli 0.85.44 → 0.85.46

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.44
1
+ # Mipham Code v0.85.46
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 140 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, 141 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
- - **140 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **141 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.44",
3
+ "version": "0.85.46",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -207,13 +207,14 @@ export function selectAgentTools(
207
207
  .split(',')
208
208
  .map((s) => s.trim())
209
209
  .filter(Boolean)
210
- // `mcp__server` / `mcp__server__*` mean "every tool on that server".
211
- // Without expansion these exact-match nothing, so an agent that asks for a
212
- // whole server silently receives no tools at all.
213
- const serverPrefixes = allowRules
214
- .map((r) => mcpServerPrefix(r))
215
- .filter((p): p is string => p !== null)
216
- const allowSet = new Set(allowRules.filter((r) => mcpServerPrefix(r) === null))
210
+ // `mcp__server` / `mcp__server__*` mean "every tool on that server", and
211
+ // `mcp__*` means every MCP tool. Without expansion these exact-match
212
+ // nothing, so an agent that asks for a whole server silently receives no
213
+ // tools at all.
214
+ const serverPrefix = (r: string): string | null =>
215
+ r === 'mcp__*' ? 'mcp__' : mcpServerPrefix(r)
216
+ const serverPrefixes = allowRules.map(serverPrefix).filter((p): p is string => p !== null)
217
+ const allowSet = new Set(allowRules.filter((r) => serverPrefix(r) === null))
217
218
  allowedTools = allowedTools.filter(
218
219
  (t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
219
220
  )
@@ -225,13 +226,19 @@ export function selectAgentTools(
225
226
  }
226
227
 
227
228
  if (agentDef.disallowedTools) {
228
- const denySet = new Set(
229
- agentDef.disallowedTools
230
- .split(',')
231
- .map((s) => s.trim())
232
- .filter(Boolean),
229
+ // The deny side needs the same server expansion as the allow side. With
230
+ // exact matching, `disallowedTools: mcp__server` denied nothing — the agent
231
+ // kept every tool on the server it was told to avoid (CC 2.1.178-021).
232
+ const denyRules = agentDef.disallowedTools
233
+ .split(',')
234
+ .map((s) => s.trim())
235
+ .filter(Boolean)
236
+ const denyPrefix = (r: string): string | null => (r === 'mcp__*' ? 'mcp__' : mcpServerPrefix(r))
237
+ const denySet = new Set(denyRules.filter((r) => denyPrefix(r) === null))
238
+ const denyPrefixes = denyRules.map(denyPrefix).filter((p): p is string => p !== null)
239
+ allowedTools = allowedTools.filter(
240
+ (t) => !denySet.has(t.name) && !denyPrefixes.some((p) => t.name.startsWith(p)),
233
241
  )
234
- allowedTools = allowedTools.filter((t) => !denySet.has(t.name))
235
242
  }
236
243
 
237
244
  return allowedTools
@@ -95,6 +95,11 @@ export class BackgroundAgentRegistry {
95
95
  executor: (signal: AbortSignal, id: string) => Promise<string>,
96
96
  kind: BackgroundTaskKind = 'interactive',
97
97
  ): string {
98
+ // Completed tasks keep their full result string forever unless something
99
+ // calls `prune()`, and nothing did — a long session with many subagents
100
+ // grew without bound (CC 2.1.50-016 / -023 / -008). Each spawn is a
101
+ // natural, bounded moment to drop finished tasks older than the TTL.
102
+ this.prune()
98
103
  const id = `bg-${++this.idCounter}-${Date.now().toString(36)}`
99
104
  const now = new Date()
100
105
 
@@ -516,6 +516,9 @@ export class SubAgent {
516
516
  // synchronous (see `resolveRunInBackground`). Set on the shared literal so it
517
517
  // covers the synchronous *and* background runs — both go through here.
518
518
  isSubAgent: true,
519
+ // One level deeper than the caller. The Agent tool refuses past
520
+ // MAX_AGENT_DEPTH; without the increment every nested call reads as 0.
521
+ agentDepth: (options.toolContext?.agentDepth ?? 0) + 1,
519
522
  // Tools that keep per-session state (the Task list) must file it under the
520
523
  // session this work belongs to, not under the literal 'sub-agent' — that
521
524
  // one bucket is shared by every nested call from every session.
@@ -870,11 +873,16 @@ export class SubAgent {
870
873
  // `fix`) is how the model learns the call went through under a
871
874
  // caution. The engine prepends them to a successful result; without
872
875
  // the same line here the warnings were produced and dropped.
873
- if (gateWarnings.length > 0 && displayResult.success) {
874
- displayResult = {
875
- ...displayResult,
876
- content: gateWarnings.join('\n') + '\n' + (displayResult.content || ''),
877
- }
876
+ // On failure the warning goes into `error` — the field a failed
877
+ // result is actually projected from (same fix as the main engine,
878
+ // CC 2.1.110-027).
879
+ if (gateWarnings.length > 0) {
880
+ const warning = gateWarnings.join('\n')
881
+ displayResult = displayResult.success
882
+ ? { ...displayResult, content: warning + '\n' + (displayResult.content || '') }
883
+ : displayResult.error
884
+ ? { ...displayResult, error: warning + '\n' + displayResult.error }
885
+ : { ...displayResult, content: warning + '\n' + (displayResult.content || '') }
878
886
  }
879
887
 
880
888
  currentMessages.push({
@@ -6,7 +6,7 @@
6
6
  */
7
7
  import type { CommandHandler } from '../ui/commands.js'
8
8
 
9
- export { commitCmd, pushCmd, prCmd, issueCmd }
9
+ export { commitCmd, pushCmd, prCmd, issueCmd, shipCmd }
10
10
 
11
11
  /**
12
12
  * Run a git command asynchronously — avoids blocking the TUI event loop.
@@ -189,6 +189,154 @@ const issueCmd: CommandHandler = async (_ctx, args) => {
189
189
  }
190
190
  }
191
191
 
192
+ // ═══════════════════════════════════════════════════════════════
193
+ // /ship — the whole after-you-write-it loop (Claude Ship beta borrow)
194
+ // ═══════════════════════════════════════════════════════════════
195
+
196
+ export interface ShipContext {
197
+ branch: string
198
+ defaultBranch: string
199
+ staged: number
200
+ unstaged: number
201
+ untracked: number
202
+ ahead: string
203
+ gh: boolean
204
+ /** Whatever the user typed after `/ship` (e.g. `--draft`). */
205
+ args: string
206
+ }
207
+
208
+ /**
209
+ * The plan `/ship` hands to the model.
210
+ *
211
+ * Split out from the handler so the parts that are policy — never commit to the
212
+ * default branch, never merge, report an undo command after each push — can be
213
+ * asserted without spawning git or gh. The handler only gathers facts.
214
+ */
215
+ export function buildShipPlan(c: ShipContext): { content: string; forwardToAI?: string } {
216
+ if (!c.branch) {
217
+ return {
218
+ content:
219
+ '── Ship ──\n\n' +
220
+ 'HEAD is detached, so there is no branch to ship. Check out a branch first, then run /ship again.',
221
+ }
222
+ }
223
+
224
+ const onDefault = c.branch === c.defaultBranch
225
+ // Only a known zero means nothing is ahead. An empty string means the
226
+ // upstream count could not be read (no origin, or no upstream branch) — that
227
+ // is "unknown", not "nothing", and the loop must not claim there is no work.
228
+ const nothingToDo = c.staged === 0 && c.unstaged === 0 && c.untracked === 0 && c.ahead === '0'
229
+
230
+ const header = [
231
+ '── Ship ──',
232
+ '',
233
+ `Branch: ${c.branch}${onDefault ? ` (the default branch)` : ''}`,
234
+ `Changes: ${c.staged} staged, ${c.unstaged} unstaged, ${c.untracked} untracked`,
235
+ `Ahead: ${c.ahead || 'unknown'} commit(s) of origin/${c.branch}`,
236
+ `gh: ${c.gh ? 'available' : 'not found'}`,
237
+ ].join('\n')
238
+
239
+ if (nothingToDo) {
240
+ return {
241
+ content:
242
+ `${header}\n\n` + `Nothing to ship: no changes and nothing ahead of origin/${c.branch}.`,
243
+ }
244
+ }
245
+
246
+ const forwardToAI = `Ship this branch end-to-end with the git and Bash tools. Every push and PR step is permission-checked — do not bypass that layer.
247
+
248
+ Context:
249
+ - Branch: ${c.branch}
250
+ - Default branch: ${c.defaultBranch}
251
+ - Staged / unstaged / untracked: ${c.staged} / ${c.unstaged} / ${c.untracked}
252
+ - Commits ahead of origin/${c.branch}: ${c.ahead || '0'}
253
+ - gh CLI: ${c.gh ? 'available' : 'not found'}
254
+ - User arguments: ${c.args || '(none)'}
255
+
256
+ Steps:
257
+ 1. Inspect git status, the diff, and the commits ahead of ${c.defaultBranch}. Never discard the user's uncommitted work.
258
+ 2. If HEAD is on ${c.defaultBranch} or detached, create a feature branch named mipham/ship-<short-slug> first. Never commit directly to ${c.defaultBranch}.
259
+ 3. Stage only the intended changes and write a Conventional Commits message. If there is nothing to commit, skip this step.
260
+ 4. Push the branch you are on with \`git push -u origin <branch>\` (the feature branch from step 2 if you created one).
261
+ 5. If gh is available and authenticated, open a pull request with \`gh pr create --base ${c.defaultBranch} --head <branch>\`; use --draft if the user asked for one. If gh is missing or not authenticated, stop after the push and say the PR was not opened.
262
+ 6. Review the PR diff with the code-review skill. Report findings with severity (important / pre_existing / nit) and file:line. If CI checks fail, read the failing logs (\`gh pr checks <n>\`, \`gh run view --log-failed\`) and fix the cause; if the branch conflicts with the base, bring the base in and resolve the conflicts carefully.
263
+ 7. Fix only defects that are safe and in scope; push each round. Never force-push.
264
+ 8. After every push, state what changed and the exact undo command (\`git revert <sha>\`).
265
+ 9. Finish with: the PR URL, what was reviewed and fixed, and anything that needs a human decision.
266
+
267
+ Never merge, approve, or change branch protection. If a step fails, stop and name the step and its error. Do not claim a step succeeded unless its command exited 0.`
268
+
269
+ const notes = [
270
+ onDefault
271
+ ? 'On the default branch — Claude will create a feature branch before committing.'
272
+ : '',
273
+ c.gh ? '' : 'gh not found — Claude will stop after pushing; no PR will be opened.',
274
+ ].filter(Boolean)
275
+
276
+ return {
277
+ content: notes.length ? `${header}\n\n${notes.map((n) => `• ${n}`).join('\n')}` : header,
278
+ forwardToAI,
279
+ }
280
+ }
281
+
282
+ /** `gh --version` with a short bound; a hung binary must not hang the command. */
283
+ async function commandExists(command: string): Promise<boolean> {
284
+ try {
285
+ const proc = Bun.spawn([command, '--version'], { stdout: 'pipe', stderr: 'pipe' })
286
+ const exitCode = await Promise.race([
287
+ proc.exited,
288
+ new Promise<number>((resolve) => setTimeout(() => resolve(143), 2000)),
289
+ ])
290
+ if (exitCode === 143) {
291
+ proc.kill()
292
+ return false
293
+ }
294
+ return exitCode === 0
295
+ } catch {
296
+ return false
297
+ }
298
+ }
299
+
300
+ const shipCmd: CommandHandler = async (_ctx, args) => {
301
+ try {
302
+ // `git()` maps every failure to '', so "not a repository" and "detached
303
+ // HEAD" would otherwise print the same thing. Ask explicitly.
304
+ const inside = await git(['rev-parse', '--is-inside-work-tree'], 3000)
305
+ if (inside !== 'true') {
306
+ return {
307
+ content: '── Ship ──\n\nNot a git repository. Run /ship from a repository checkout.',
308
+ }
309
+ }
310
+ const branch = await git(['branch', '--show-current'], 3000)
311
+ const remote = await git(['remote', 'show', 'origin'], 3000)
312
+ const defaultBranch = remote.match(/HEAD branch:\s*(\S+)/)?.[1] || 'main'
313
+
314
+ const [stagedRaw, unstagedRaw, untrackedRaw, aheadRaw] = await Promise.all([
315
+ git(['diff', '--cached', '--name-only'], 3000),
316
+ git(['diff', '--name-only'], 3000),
317
+ git(['ls-files', '--others', '--exclude-standard'], 3000),
318
+ branch ? git(['rev-list', '--count', `origin/${branch}..HEAD`], 3000) : Promise.resolve(''),
319
+ ])
320
+
321
+ const count = (s: string): number => s.split('\n').filter(Boolean).length
322
+
323
+ return buildShipPlan({
324
+ branch,
325
+ defaultBranch,
326
+ staged: count(stagedRaw),
327
+ unstaged: count(unstagedRaw),
328
+ untracked: count(untrackedRaw),
329
+ ahead: aheadRaw || '0',
330
+ gh: await commandExists('gh'),
331
+ args: args.join(' ').trim(),
332
+ })
333
+ } catch {
334
+ return {
335
+ content: '── Ship ──\n\nCould not inspect the repository. Are you in a git repository?',
336
+ }
337
+ }
338
+ }
339
+
192
340
  // ═══════════════════════════════════════════════════════════════
193
341
  // Code Quality — bridge slash commands to skills (Claude Code parity)
194
342
  // ═══════════════════════════════════════════════════════════════
@@ -9,6 +9,7 @@ import type {
9
9
  ContentBlock,
10
10
  } from '../shared/index.ts'
11
11
  import { ProviderRegistry } from '../providers/registry'
12
+ import { UNNAMED_TOOL_CALL } from '../shared/constants'
12
13
  import { createAwakeTimer } from '../providers/fetch-utils'
13
14
  import type { ChatRequest } from '../providers/registry'
14
15
  import type { Llm } from '../providers/llm'
@@ -1517,6 +1518,20 @@ export class QueryEngine {
1517
1518
  getMetrics().toolCalls.inc({ tool_name: name })
1518
1519
  const tool = this.tools.get(name)
1519
1520
  if (!tool) {
1521
+ // A provider that sends a tool call with no name is not a tool lookup
1522
+ // failure the model can guess its way out of. Say what happened; the
1523
+ // result goes back as a normal tool_result, so the turn continues and the
1524
+ // model can re-issue the call (331-038).
1525
+ if (name === UNNAMED_TOOL_CALL) {
1526
+ return {
1527
+ success: false,
1528
+ content: '',
1529
+ error:
1530
+ 'The provider returned a tool call with no name, so the call was not dispatched. ' +
1531
+ 'Re-issue the call with a tool name and its arguments.',
1532
+ notRun: true,
1533
+ }
1534
+ }
1520
1535
  // P2-4: Provide a more helpful error for unavailable tools
1521
1536
  const isMcpTool = name.startsWith('mcp__')
1522
1537
  const hint = isMcpTool
@@ -1642,9 +1657,20 @@ export class QueryEngine {
1642
1657
  // permit a merge. Recorded on the one funnel every tool call passes.
1643
1658
  noteToolOutcome(reviewLedger, this.sessionId, name, effectiveParams, result.success)
1644
1659
 
1645
- // Prepend CRSI warnings to result content
1646
- if (hookWarnings.length > 0 && result.success) {
1647
- result.content = hookWarnings.join('\n') + '\n' + (result.content || '')
1660
+ // Prepend PreToolUse `additionalContext` to the result — on failure too.
1661
+ // It used to ride only on success, so a hook that warned "this command is
1662
+ // about to fail because X" lost its warning at exactly the moment the
1663
+ // command failed (CC 2.1.110-027). A failed result is projected as
1664
+ // `error || content`, so the warning goes where it is actually read.
1665
+ if (hookWarnings.length > 0) {
1666
+ const warning = hookWarnings.join('\n')
1667
+ if (result.success) {
1668
+ result.content = warning + '\n' + (result.content || '')
1669
+ } else if (result.error) {
1670
+ result.error = warning + '\n' + result.error
1671
+ } else {
1672
+ result.content = warning + '\n' + (result.content || '')
1673
+ }
1648
1674
  }
1649
1675
 
1650
1676
  // Run PostToolUse hooks
@@ -1,4 +1,4 @@
1
- import { exec } from 'node:child_process'
1
+ import { exec, execFileSync } from 'node:child_process'
2
2
 
3
3
  export interface GitPr {
4
4
  number: number
@@ -39,6 +39,22 @@ export function prColor(pr: GitPr): PrColor {
39
39
  return 'white'
40
40
  }
41
41
 
42
+ /** The current branch of `cwd`, or null when it is not a git repo / detached HEAD.
43
+ * Read on demand rather than once at mount: `/cd` changes the directory, and a
44
+ * cached branch then describes the previous repository (CC 2.1.176-012). */
45
+ export function readGitBranch(cwd: string = process.cwd()): string | null {
46
+ try {
47
+ const branch = execFileSync('git', ['branch', '--show-current'], {
48
+ cwd,
49
+ encoding: 'utf-8',
50
+ stdio: ['ignore', 'pipe', 'pipe'],
51
+ }).trim()
52
+ return branch || null
53
+ } catch {
54
+ return null
55
+ }
56
+ }
57
+
42
58
  /** Detect the PR whose head is `branch`. gh unavailable / no PR / non-zero exit → null.
43
59
  * Async so the status line never blocks startup. */
44
60
  export function resolveGitPr(branch: string): Promise<GitPr | null> {
@@ -67,6 +67,15 @@ export function loadHookConfigs(configs: SettingsHooks): HookDefinition[] {
67
67
  }
68
68
 
69
69
  for (const entry of entries) {
70
+ // A group with no `hooks` array used to throw at `for … of entry.hooks`
71
+ // and take *every* hook with it — one malformed group disabled the entire
72
+ // wiring (CC 2.1.122-017). Skip that group, keep the rest.
73
+ if (!entry || typeof entry !== 'object' || !Array.isArray(entry.hooks)) {
74
+ process.stderr.write(
75
+ `⚠️ Hook group on ${eventName} has no "hooks" array — skipped; other hooks still load.\n`,
76
+ )
77
+ continue
78
+ }
70
79
  // A matcher is only a *filter*, so a malformed one must not take the whole
71
80
  // hook set down with it. `new RegExp` throws here, and both callers register
72
81
  // the result in a plain `for…of` (`index.tsx:742`,
@@ -202,7 +202,7 @@ export const CLASSIFIER_RULES: ClassifierRule[] = [
202
202
  {
203
203
  tier: 'soft',
204
204
  name: 'Irreversible Local Destruction',
205
- text: 'deleting or overwriting work that cannot be recovered: `rm -rf`, `git reset --hard`, `git clean -f`, `git checkout .`, truncating a file, dropping a table or bucket. Uncommitted work counts as at risk.',
205
+ text: 'deleting or overwriting work that cannot be recovered: `rm -rf`, `git reset --hard`, `git clean -f`, `git checkout .`, `git stash drop`, `git commit --amend` (on a commit this session did not make), `terraform destroy` / `pulumi destroy` / `cdk destroy` (unless the user named that stack), truncating a file, dropping a table or bucket. Uncommitted work counts as at risk.',
206
206
  },
207
207
  {
208
208
  tier: 'soft',
@@ -107,6 +107,12 @@ const PREFIX_COMMANDS = new Set([
107
107
  'xargs',
108
108
  'eval',
109
109
  'stdbuf',
110
+ // Schedulers/session leaders: they run the command that follows. Without
111
+ // these, `watch rm -rf x` / `setsid rm -rf x` / `ionice -c3 rm -rf x` ran
112
+ // past a deny rule that named `rm` (CC 2.1.113-015).
113
+ 'watch',
114
+ 'setsid',
115
+ 'ionice',
110
116
  ])
111
117
 
112
118
  /** `timeout` 的 duration 形态:`5` / `0.5` / `30s` / `2m` / `1h` / `1d`。 */
@@ -572,7 +578,7 @@ export interface CommandSegmentGroup {
572
578
  */
573
579
  export function flattenCommandGroups(command: string, depth = 0): CommandSegmentGroup[] {
574
580
  const groups: CommandSegmentGroup[] = []
575
- for (const seg of splitShellSegments(joinLineContinuations(command))) {
581
+ for (const seg of splitSegmentsForMatching(joinLineContinuations(command))) {
576
582
  const variants: string[] = [seg]
577
583
  // The shell removes quotes before running the command, so `rm "-rf" /tmp`
578
584
  // *is* `rm -rf /tmp` — but the rule text is written without quotes, so the
@@ -657,6 +663,135 @@ export function joinLineContinuations(command: string): string {
657
663
  return out
658
664
  }
659
665
 
666
+ /** Commands whose heredoc body is itself shell code, not data. */
667
+ const SHELL_INTERPRETERS = new Set([
668
+ 'bash',
669
+ 'sh',
670
+ 'zsh',
671
+ 'ksh',
672
+ 'dash',
673
+ 'fish',
674
+ 'eval',
675
+ 'source',
676
+ '.',
677
+ ])
678
+
679
+ /**
680
+ * Heredoc delimiters declared on one line (`cat <<EOF`, `cat <<-'EOF'`).
681
+ *
682
+ * Scanned with quote state rather than a bare regex: `echo "a << b"` mentions a
683
+ * heredoc without opening one, and a regex would take `b` for the delimiter.
684
+ */
685
+ function heredocSpecs(line: string): Array<{ delim: string; stripTabs: boolean }> {
686
+ const specs: Array<{ delim: string; stripTabs: boolean }> = []
687
+ let quote: "'" | '"' | null = null
688
+ for (let i = 0; i < line.length; i++) {
689
+ const ch = line[i]!
690
+ if (quote) {
691
+ if (ch === '\\' && quote === '"') i += 1
692
+ else if (ch === quote) quote = null
693
+ continue
694
+ }
695
+ if (ch === "'" || ch === '"') {
696
+ quote = ch
697
+ continue
698
+ }
699
+ if (ch === '\\') {
700
+ i += 1
701
+ continue
702
+ }
703
+ // `<<<` is a here-string, not a heredoc.
704
+ if (ch !== '<' || line[i + 1] !== '<' || line[i + 2] === '<') continue
705
+ let j = i + 2
706
+ let stripTabs = false
707
+ if (line[j] === '-') {
708
+ stripTabs = true
709
+ j += 1
710
+ }
711
+ while (line[j] === ' ' || line[j] === '\t') j += 1
712
+ let delimQuote: string | null = null
713
+ if (line[j] === "'" || line[j] === '"') {
714
+ delimQuote = line[j]!
715
+ j += 1
716
+ }
717
+ const start = j
718
+ while (j < line.length) {
719
+ const c = line[j]!
720
+ if (delimQuote) {
721
+ if (c === delimQuote) break
722
+ j += 1
723
+ } else if (/[A-Za-z0-9_]/.test(c)) j += 1
724
+ else break
725
+ }
726
+ const delim = line.slice(start, j)
727
+ if (delim) {
728
+ specs.push({ delim, stripTabs })
729
+ i = j
730
+ }
731
+ }
732
+ return specs
733
+ }
734
+
735
+ /**
736
+ * Split a command for **permission matching**, keeping a heredoc body attached
737
+ * to the command that reads it.
738
+ *
739
+ * `splitShellSegments` splits on every newline, so `cat <<EOF\nhello\nEOF`
740
+ * became three segments and an allow rule `Bash(cat:*)` required `hello` to
741
+ * match it too — the rule that names the command never matched its most common
742
+ * form (same class as the no-argument case in `wildcardMatch`). The body of a
743
+ * heredoc is data the command consumes, not another command.
744
+ *
745
+ * The exception is a heredoc that feeds a shell interpreter (`bash <<EOF …`):
746
+ * that body *is* shell code, and folding it into the parent segment would hide
747
+ * `rm -rf /` from a deny rule. Those keep the plain line split, i.e. today's
748
+ * conservative behaviour.
749
+ */
750
+ export function splitSegmentsForMatching(command: string): string[] {
751
+ const lines = command.split(/\r?\n/)
752
+ // A heredoc that feeds a shell interpreter keeps the plain split for the
753
+ // whole command: its body is executable and must stay visible to deny rules.
754
+ const feedsShell = (line: string): boolean => {
755
+ if (heredocSpecs(line).length === 0) return false
756
+ const base = (effectiveCommand(line.split(/\s+/).filter(Boolean)).base || '').split('/').pop()
757
+ return !!base && SHELL_INTERPRETERS.has(base)
758
+ }
759
+ if (lines.some(feedsShell)) return splitShellSegments(command)
760
+
761
+ const out: string[] = []
762
+ // Heredoc-declaring segments still waiting for their body lines. The body
763
+ // belongs to the segment that declared it — `cat <<EOF && rm -rf /` runs `rm`
764
+ // *after* cat, so that half must stay its own segment.
765
+ const pending: Array<{ lines: string[]; delims: Array<{ delim: string; stripTabs: boolean }> }> =
766
+ []
767
+ for (const line of lines) {
768
+ if (pending.length > 0) {
769
+ const head = pending[0]!
770
+ head.lines.push(line)
771
+ const spec = head.delims[0]!
772
+ const candidate = spec.stripTabs ? line.replace(/^\t+/, '') : line
773
+ if (candidate === spec.delim) {
774
+ head.delims.shift()
775
+ if (head.delims.length === 0) {
776
+ out.push(head.lines.join('\n').trim())
777
+ pending.shift()
778
+ }
779
+ }
780
+ continue
781
+ }
782
+ for (const part of line.split(/&&|\|\||;|\||&/)) {
783
+ const seg = part.trim()
784
+ if (!seg) continue
785
+ const specs = heredocSpecs(seg)
786
+ if (specs.length > 0) pending.push({ lines: [seg], delims: specs })
787
+ else out.push(seg)
788
+ }
789
+ }
790
+ // An unterminated heredoc still has to be judged: keep what was read.
791
+ for (const p of pending) out.push(p.lines.join('\n').trim())
792
+ return out.filter((s) => s.length > 0)
793
+ }
794
+
660
795
  /** git global options that consume the next token. */
661
796
  const GIT_GLOBAL_WITH_ARG = new Set([
662
797
  '-C',
@@ -1261,8 +1396,10 @@ export function matchBashRule(
1261
1396
  */
1262
1397
  function embedsForeignCommand(segment: string): boolean {
1263
1398
  return (
1264
- // find(1): -exec / -execdir / -ok / -okdir take a command.
1265
- /\s-(?:exec|execdir|ok|okdir)(?:\s|$)/.test(segment) ||
1399
+ // find(1): -exec / -execdir / -ok / -okdir take a command; -delete removes
1400
+ // files outright. `Bash(find:*)` granted `find . -name '*.log' -delete` —
1401
+ // a deletion the rule never named (CC 2.1.113-016).
1402
+ /\s-(?:exec|execdir|ok|okdir|delete)(?:\s|$)/.test(segment) ||
1266
1403
  // git(1) / tar(1): options that name a program to run.
1267
1404
  /--(?:upload-pack|receive-pack|exec-path|to-command|checkpoint-action)(?:=|\s)/.test(segment) ||
1268
1405
  // git(1) `-c core.pager=…`-style config that ends in an executed command.
@@ -1272,16 +1409,57 @@ function embedsForeignCommand(segment: string): boolean {
1272
1409
  )
1273
1410
  }
1274
1411
 
1412
+ /**
1413
+ * Match one rule pattern against a command, **without a regex**.
1414
+ *
1415
+ * The pattern used to be compiled to a regex with every `*` becoming `.*`.
1416
+ * Nested wildcards (`git:*a*a*a*a*a*b`) then backtracked exponentially: a
1417
+ * 200-character argument held the permission prompt at 100 % CPU for minutes —
1418
+ * a freeze reachable from the command line the rule was supposed to guard
1419
+ * (CC 2.1.73-003). This is the classic two-pointer wildcard match: `*` may
1420
+ * match any run (newlines included), `?` exactly one character, and `:` one
1421
+ * colon or whitespace. It is O(pattern × input) with no backtracking tree.
1422
+ *
1423
+ * A trailing `:*` also matches the **no-argument** form: `Bash(ls:*)` grants
1424
+ * `ls` itself, not only `ls -la`.
1425
+ */
1275
1426
  export function wildcardMatch(pattern: string, input: string): boolean {
1276
- const regexStr =
1277
- '^' +
1278
- pattern
1279
- .replace(/[.+^${}()|[\]\\*?]/g, '\\$&') // escape regex specials (incl. * and ?)
1280
- .replace(/:/g, '[:\\s]') // : → match colon or whitespace
1281
- .replace(/\\\*/g, '.*') // * → .*
1282
- .replace(/\\\?/g, '.') + // ? → .
1283
- '$'
1284
- return new RegExp(regexStr).test(input)
1427
+ const chars = Array.from(pattern)
1428
+ const subject = Array.from(input)
1429
+ let p = 0
1430
+ let s = 0
1431
+ let star = -1
1432
+ let mark = 0
1433
+ while (s < subject.length) {
1434
+ if (p < chars.length && chars[p] === '*') {
1435
+ star = p
1436
+ mark = s
1437
+ p += 1
1438
+ continue
1439
+ }
1440
+ if (p < chars.length && tokenMatches(chars[p]!, subject[s]!)) {
1441
+ p += 1
1442
+ s += 1
1443
+ continue
1444
+ }
1445
+ if (star !== -1) {
1446
+ // Extend the last `*` by one and retry from just after it.
1447
+ p = star + 1
1448
+ mark += 1
1449
+ s = mark
1450
+ continue
1451
+ }
1452
+ return false
1453
+ }
1454
+ // `foo:*` also matches a bare `foo`: a separator at the very end is optional.
1455
+ while (p < chars.length && (chars[p] === '*' || chars[p] === ':')) p += 1
1456
+ return p === chars.length
1457
+ }
1458
+
1459
+ function tokenMatches(patternChar: string, inputChar: string): boolean {
1460
+ if (patternChar === '?') return true
1461
+ if (patternChar === ':') return inputChar === ':' || /\s/.test(inputChar)
1462
+ return patternChar === inputChar
1285
1463
  }
1286
1464
 
1287
1465
  /**
@@ -663,6 +663,13 @@ export class PermissionSystem {
663
663
  // 3. Check allow rules — but an org ceiling still applies (see allowRuleDecision)
664
664
  for (const rule of this.allowRules) {
665
665
  if (!this.ruleMatches(rule, tool, input)) continue
666
+ // A file *write* is the one thing plan mode exists to forbid: with
667
+ // `Edit(src/**)` allowed, plan mode wrote files — the rule sat ahead of
668
+ // the mode baseline and the mode never got a say (CC 2.1.136-008).
669
+ // Scoped to file-mutating tools so an allow rule still grants exactly
670
+ // what it did in every other category (the pinned tests for `allow('Bash')`
671
+ // and bare-name validity rely on that).
672
+ if (this.mode === 'plan' && tool.category === 'file' && !isReadOnlyTool(tool)) continue
666
673
  // In `auto`, a rule that names no program does not stand in for the safety
667
674
  // classifier. An allow rule sits *ahead* of the mode baseline, so
668
675
  // `allow: ["Bash(*)"]` would otherwise make the one mode that examines
@@ -513,7 +513,12 @@
513
513
  "skills_unavailable": " (skills info unavailable)",
514
514
  "audit_section": "── CLAUDE.md Audit ──",
515
515
  "audit_clean": " ✓ no code-derivable sections found",
516
- "audit_found": "Add the sections above to the `prompt-exclude` frontmatter to stop sending them to the model."
516
+ "audit_found": "Add the sections above to the `prompt-exclude` frontmatter to stop sending them to the model.",
517
+ "api_section": "── API ──",
518
+ "api_target": " {provider} ({model})",
519
+ "api_not_tested": " ⚪ not tested — {reason}",
520
+ "api_reachable": " 🟢 reachable — {detail}",
521
+ "api_unreachable": " 🔴 unreachable — {detail}"
517
522
  },
518
523
  "skillDoctor": {
519
524
  "title": "── Skill Doctor ──",