@miphamai/cli 0.85.36 → 0.85.38

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,4 +1,4 @@
1
- # Mipham Code v0.85.36
1
+ # Mipham Code v0.85.38
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.36",
3
+ "version": "0.85.38",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -66,17 +66,27 @@ You are a research agent. Your task:
66
66
  2. For every claim, follow it back to the source that owns it.
67
67
  If a secondary source makes a claim, find the primary source and cite that.
68
68
 
69
- 3. Use WebSearch to find sources.
69
+ 3. Before external search, scan the local repo and sibling project directories
70
+ for prior work. Open and read the relevant files — a glob hit is not a read.
71
+ Record what you found; if there is none, say "none" explicitly.
72
+
73
+ 4. A number, "unconditional", "record", or "first" is a claim about a theorem
74
+ under its stated assumptions, not about the numeral. Open the source's theorem
75
+ statement (not the abstract), copy the assumption it depends on, and pair the
76
+ value with that assumption wherever you write it. If the same value has several
77
+ provenances, say which one you mean.
78
+
79
+ 5. Use WebSearch to find sources.
70
80
  Use WebFetch to deep-read promising pages.
71
81
  Cross-reference critical claims across 2+ independent primary sources.
72
82
 
73
- 4. Write findings to a SINGLE Markdown file.
83
+ 6. Write findings to a SINGLE Markdown file.
74
84
  - Cite every claim with its primary source URL
75
85
  - Distinguish between facts (needs citation) and reasoning (your own)
76
86
  - Flag outdated content ("article from 2024, may be stale")
77
87
  - Note if a source is official docs vs community
78
88
 
79
- 5. Save the file where the repo already keeps such notes.
89
+ 7. Save the file where the repo already keeps such notes.
80
90
  Match existing conventions. If none exist, put it in docs/research/.
81
91
  ```
82
92
 
@@ -613,6 +613,9 @@ export function loadSettingsJson(
613
613
  ]
614
614
 
615
615
  for (const { path, readHooks, isProject } of searchPaths) {
616
+ // Kept outside the `try` so the parse-failure message can name the line and
617
+ // column, not just V8/Bun's byte offset.
618
+ let rawForError = ''
616
619
  try {
617
620
  // `readRegularFileSync` folds "absent" and "present but unreadable"
618
621
  // (EACCES, a directory, a FIFO) into the same `null`. Absent is the ordinary
@@ -622,6 +625,7 @@ export function loadSettingsJson(
622
625
  // **looser**. A security-relevant file must not fail open in silence.
623
626
  const present = existsSync(path)
624
627
  const raw = readRegularFileSync(path)
628
+ rawForError = raw ?? ''
625
629
  if (raw === null) {
626
630
  if (present) {
627
631
  process.stderr.write(
@@ -740,7 +744,7 @@ export function loadSettingsJson(
740
744
  // Malformed JSON is the other half of the same problem: the file exists and
741
745
  // declares a `deny` list we cannot see. Say so, with the parse reason, the
742
746
  // same way `safeParseYaml` does for `config.yml`.
743
- const msg = err instanceof Error ? err.message : String(err)
747
+ const msg = jsonErrorDetail(rawForError, err)
744
748
  process.stderr.write(
745
749
  `⚠ Mipham Code: failed to parse settings file (${path}): ${msg} — ignoring it.\n`,
746
750
  )
@@ -794,6 +798,70 @@ export function projectFilePath(name: string, cwd: string = process.cwd()): stri
794
798
  return resolve(dir) === resolve(MIPHAM_HOME) ? null : join(dir, name)
795
799
  }
796
800
 
801
+ /**
802
+ * Values nested deeper than this are dropped when a settings file is read.
803
+ *
804
+ * Not a style preference: `JSON.parse` accepts a value nested hundreds of
805
+ * thousands of levels, and `JSON.stringify` on the *same* value throws
806
+ * `RangeError: Maximum call stack size exceeded`. The write path
807
+ * (`readSettingsDoc` → mutate → `writeSettingsDoc`) therefore used to crash on a
808
+ * file that had parsed fine — a document we cannot rewrite, reported as an
809
+ * unhandled rejection. Nothing we read lives past a few levels, so the cap costs
810
+ * no real setting and keeps the file rewritable.
811
+ */
812
+ const MAX_SETTINGS_DEPTH = 64
813
+
814
+ const DROPPED = Symbol('dropped')
815
+
816
+ /** Drop values deeper than `MAX_SETTINGS_DEPTH`, counting what went. */
817
+ function capSettingsDepth(value: unknown): { value: unknown; dropped: number } {
818
+ let dropped = 0
819
+ const walk = (v: unknown, depth: number): unknown => {
820
+ if (depth > MAX_SETTINGS_DEPTH) {
821
+ dropped++
822
+ return DROPPED
823
+ }
824
+ if (Array.isArray(v)) {
825
+ const out: unknown[] = []
826
+ for (const item of v) {
827
+ const next = walk(item, depth + 1)
828
+ // JSON has no `undefined`, so a hole can only mean "dropped": leaving it
829
+ // in would serialize as `null` — a different value than the one removed.
830
+ if (next !== DROPPED) out.push(next)
831
+ }
832
+ return out
833
+ }
834
+ if (v && typeof v === 'object') {
835
+ const out: Record<string, unknown> = {}
836
+ for (const [key, item] of Object.entries(v)) {
837
+ const next = walk(item, depth + 1)
838
+ if (next !== DROPPED) out[key] = next
839
+ }
840
+ return out
841
+ }
842
+ return v
843
+ }
844
+ return { value: walk(value, 0), dropped }
845
+ }
846
+
847
+ /**
848
+ * `JSON.parse`'s message plus a line/column, derived from the byte offset it
849
+ * reports. Node 22 reports an offset (`… at position 14`), which locates the
850
+ * break in a multi-hundred-line settings file; Bun's message carries no offset
851
+ * at all, so there the runtime's own text is returned unchanged. The addition is
852
+ * therefore per-runtime, and deliberately says nothing it cannot compute.
853
+ */
854
+ function jsonErrorDetail(raw: string, err: unknown): string {
855
+ const message = err instanceof Error ? err.message : String(err)
856
+ const at = /position (\d+)/.exec(message)
857
+ if (!at) return message
858
+ const pos = Math.min(Number(at[1]), raw.length)
859
+ const before = raw.slice(0, pos)
860
+ const line = before.split('\n').length
861
+ const column = pos - before.lastIndexOf('\n')
862
+ return `${message} (line ${line}, column ${column})`
863
+ }
864
+
797
865
  /**
798
866
  * Read a settings.json as a plain object, preserving any key we don't model
799
867
  * (hooks, and anything a future version adds). A malformed file is an error,
@@ -805,13 +873,22 @@ export function readSettingsDoc(path: string): Record<string, unknown> {
805
873
  let parsed: unknown
806
874
  try {
807
875
  parsed = JSON.parse(raw)
808
- } catch {
809
- throw new Error(`${path} is not valid JSON. Fix or remove it, then retry.`)
876
+ } catch (err) {
877
+ throw new Error(
878
+ `${path} is not valid JSON — ${jsonErrorDetail(raw, err)}. Fix or remove it, then retry.`,
879
+ )
810
880
  }
811
881
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
812
882
  throw new Error(`${path} does not contain a JSON object. Fix or remove it, then retry.`)
813
883
  }
814
- return parsed as Record<string, unknown>
884
+ const capped = capSettingsDepth(parsed)
885
+ if (capped.dropped > 0) {
886
+ process.stderr.write(
887
+ `⚠ Mipham Code: ${path}: dropped ${capped.dropped} value(s) nested deeper than ` +
888
+ `${MAX_SETTINGS_DEPTH} levels.\n`,
889
+ )
890
+ }
891
+ return capped.value as Record<string, unknown>
815
892
  }
816
893
 
817
894
  export function writeSettingsDoc(path: string, doc: Record<string, unknown>): void {
@@ -457,6 +457,21 @@ async function executeCommand(
457
457
  }
458
458
  }
459
459
 
460
+ // Exit 127 is the shell's "command not found": the hook never started, so it
461
+ // never decided anything. Told apart from a normal non-zero exit (which *is*
462
+ // an answer) and routed through the same fail-closed path as a spawn
463
+ // failure — otherwise a missing interpreter is printed as a warning and a
464
+ // guard that never ran reads exactly like a guard that said yes.
465
+ if (result.status === 127) {
466
+ return failureResult(
467
+ cfg,
468
+ ctx,
469
+ `Hook error ${failingLabel(cfg.command, source)}: exit 127 — the hook's command or ` +
470
+ `interpreter was not found, so its check may not have run`,
471
+ 'exit 127: command or interpreter not found',
472
+ )
473
+ }
474
+
460
475
  const failure = spawnFailureCause(result, hookTimeoutSeconds(cfg))
461
476
  if (failure) {
462
477
  return failureResult(
@@ -1253,6 +1253,66 @@ export function variableWildcardWarning(pattern: string): string | undefined {
1253
1253
  )
1254
1254
  }
1255
1255
 
1256
+ /** Runners for which *every* invocation fetches and runs a package (`uvx`, `npx`…). */
1257
+ const ALWAYS_PACKAGE_RUNNERS = new Set(['npx', 'bunx', 'uvx'])
1258
+
1259
+ /** Runners that only do so through a named subcommand (`pnpm dlx`, `pipx run`…). */
1260
+ const PACKAGE_RUNNERS = new Set(['pnpm', 'yarn', 'npm', 'bun', 'pipx', ...ALWAYS_PACKAGE_RUNNERS])
1261
+
1262
+ /** Their subcommands that run a package the rule did not name. */
1263
+ const RUNNER_EXEC_SUBS = new Set(['dlx', 'exec', 'x'])
1264
+
1265
+ /** `pipx run <package>` — `run` is pipx's own spelling, not `npm run`'s script. */
1266
+ const PIPX_EXEC_SUBS = new Set(['run'])
1267
+
1268
+ /**
1269
+ * Does this **Bash allow** rule grant more than "the program it names"?
1270
+ *
1271
+ * `auto` mode hands everything it is unsure about to the safety classifier — but
1272
+ * an allow rule short-circuits *ahead* of that classifier, so a rule that names
1273
+ * no program at all (`Bash(*)`), names a **path or variable** instead of a
1274
+ * program (`Bash($HOME/bin/…)`, `Bash(/usr/bin/npm:*)`), or names a **package
1275
+ * runner** whose subcommand fetches and runs arbitrary code (`Bash(pnpm dlx *)`)
1276
+ * would silently disable the mode's one safety check for every command it
1277
+ * matches. The rule is still honored in every other mode; only `auto` declines
1278
+ * to read it as a grant, so its commands go to the classifier.
1279
+ *
1280
+ * Deliberately narrow: a rule that names a concrete program (`Bash(npm test:*)`)
1281
+ * keeps granting. The named shapes are ones where the *program* is not decided
1282
+ * by the rule.
1283
+ */
1284
+ export function isUnboundedBashAllowRule(pattern: string): boolean {
1285
+ const shape = /^Bash\((.+)\)$/.exec(pattern)
1286
+ if (!shape) return false
1287
+ const sub = shape[1]!.trim()
1288
+ if (sub === '' || sub === '*') return true
1289
+
1290
+ // A drive-letter path carries a colon of its own; judging the drive before the
1291
+ // `:`-as-separator split keeps `Bash(C:\tools\x.exe:*)` a path, not a program
1292
+ // called `C`.
1293
+ if (/^[A-Za-z]:[\\/]/.test(sub)) return true
1294
+
1295
+ const words = sub.split(/[:\s]+/).filter(Boolean)
1296
+ const first = words[0] ?? ''
1297
+ if (first === '' || first === '*') return true
1298
+
1299
+ // A variable or a path decides *where* a program lives (or which value is
1300
+ // used), not which program runs — and a shell wildcard inside it can make the
1301
+ // outer match accept a command the author never looked at.
1302
+ if (/^[$~]/.test(first)) return true
1303
+ if (/^\.{0,2}[\\/]/.test(first)) return true
1304
+ if (/^[A-Za-z]:[\\/]/.test(first)) return true
1305
+
1306
+ const program = first.toLowerCase()
1307
+ if (ALWAYS_PACKAGE_RUNNERS.has(program)) return true
1308
+ if (!PACKAGE_RUNNERS.has(program)) return false
1309
+ const second = words[1]?.toLowerCase()
1310
+ // `Bash(npx:*)` names the runner and nothing else; `Bash(pnpm dlx *)` names the
1311
+ // one subcommand whose entire job is "fetch this package and run it".
1312
+ if (second === undefined) return true
1313
+ return program === 'pipx' ? PIPX_EXEC_SUBS.has(second) : RUNNER_EXEC_SUBS.has(second)
1314
+ }
1315
+
1256
1316
  /**
1257
1317
  * Compile a rule pattern string into a PermissionRuleEntry.
1258
1318
  */
@@ -6,7 +6,12 @@ import type {
6
6
  PermissionRestrictions,
7
7
  } from '../shared/index.ts'
8
8
  import type { PermissionRuleEntry } from '../shared/index.ts'
9
- import { matchBashRule, compileRule, variableWildcardWarning } from './permission-rules'
9
+ import {
10
+ matchBashRule,
11
+ compileRule,
12
+ variableWildcardWarning,
13
+ isUnboundedBashAllowRule,
14
+ } from './permission-rules'
10
15
  import { detectDangerousRm } from '../security/dangerous-rm'
11
16
  import type { DangerousRm } from '../security/dangerous-rm'
12
17
  import { detectWorldWritableChmod } from '../security/world-writable-chmod'
@@ -637,11 +642,18 @@ export class PermissionSystem {
637
642
 
638
643
  // 3. Check allow rules — but an org ceiling still applies (see allowRuleDecision)
639
644
  for (const rule of this.allowRules) {
640
- if (this.ruleMatches(rule, tool, input)) {
641
- const result = this.allowRuleDecision(tool, input)
642
- this.checkCache.set(cacheKey, result)
643
- return result
645
+ if (!this.ruleMatches(rule, tool, input)) continue
646
+ // In `auto`, a rule that names no program does not stand in for the safety
647
+ // classifier. An allow rule sits *ahead* of the mode baseline, so
648
+ // `allow: ["Bash(*)"]` would otherwise make the one mode that examines
649
+ // commands examine none of them — the rule would be a universal bypass of
650
+ // the mode's entire check. The rule still grants in every other mode.
651
+ if (this.mode === 'auto' && tool.name === 'Bash' && isUnboundedBashAllowRule(rule.pattern)) {
652
+ continue
644
653
  }
654
+ const result = this.allowRuleDecision(tool, input)
655
+ this.checkCache.set(cacheKey, result)
656
+ return result
645
657
  }
646
658
 
647
659
  // 4. Legacy exact-name rules (backward compat)
@@ -56,24 +56,42 @@ function hasProperties(node: Record<string, unknown>): boolean {
56
56
  return isPlainObject(node.properties) && Object.keys(node.properties).length > 0
57
57
  }
58
58
 
59
+ interface ArgumentSurface {
60
+ properties: Record<string, unknown>
61
+ required?: string[]
62
+ }
63
+
64
+ function surfaceOf(node: Record<string, unknown>): ArgumentSurface {
65
+ const required = Array.isArray(node.required)
66
+ ? node.required.filter((name): name is string => typeof name === 'string')
67
+ : undefined
68
+ return {
69
+ properties: isPlainObject(node.properties) ? node.properties : {},
70
+ ...(required && required.length > 0 ? { required } : {}),
71
+ }
72
+ }
73
+
59
74
  /**
75
+ * Every argument surface a schema offers.
76
+ *
60
77
  * A server may put the union at the root (`anyOf`/`oneOf`). Reading only
61
78
  * `root.properties` made that tool reach the model with **no parameters at
62
- * all** — callable, but every argument invisible. Follow the first branch that
63
- * declares properties (nested unions included); keep the root when it declares
64
- * properties itself, so a schema that has both is not rewritten.
79
+ * all** — callable, but every argument invisible. Following only the *first*
80
+ * branch fixed that and introduced the next defect one step in: a branch that
81
+ * takes an id as a number and another that takes it as a string are two
82
+ * spellings of one argument, and showing only the first taught the model that
83
+ * the second was invalid. Every branch is surfaced; nested unions included.
84
+ * The root wins when it declares properties itself, so a schema that has both
85
+ * is not rewritten.
65
86
  */
66
- function schemaWithProperties(schema: unknown, depth = 0): Record<string, unknown> {
87
+ function collectSurfaces(schema: unknown, depth = 0): ArgumentSurface[] {
67
88
  const node = isPlainObject(schema) ? schema : {}
68
- if (hasProperties(node) || depth >= 8) return node
89
+ if (hasProperties(node)) return [surfaceOf(node)]
90
+ if (depth >= 8) return []
69
91
  const branches = (
70
92
  Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : []
71
93
  ).filter(isPlainObject)
72
- for (const branch of branches) {
73
- const resolved = schemaWithProperties(branch, depth + 1)
74
- if (hasProperties(resolved)) return resolved
75
- }
76
- return branches[0] ?? node
94
+ return branches.flatMap((branch) => collectSurfaces(branch, depth + 1))
77
95
  }
78
96
 
79
97
  /**
@@ -94,23 +112,29 @@ export function sanitizeInputSchema(schema: unknown): {
94
112
  properties: Record<string, unknown>
95
113
  required?: string[]
96
114
  } {
97
- const root = schemaWithProperties(schema)
98
- const rawProperties = isPlainObject(root.properties) ? root.properties : {}
115
+ const surfaces = collectSurfaces(schema)
99
116
  const properties: Record<string, unknown> = {}
100
- for (const [name, property] of Object.entries(rawProperties)) {
101
- if (isPlainObject(property)) properties[name] = property
117
+ for (const surface of surfaces) {
118
+ for (const [name, property] of Object.entries(surface.properties)) {
119
+ // First spelling wins on a name collision; the later branch is another
120
+ // way to say the same argument, not a second argument.
121
+ if (isPlainObject(property) && !Object.prototype.hasOwnProperty.call(properties, name)) {
122
+ properties[name] = property
123
+ }
124
+ }
102
125
  }
103
126
 
104
- const required = Array.isArray(root.required)
105
- ? [
106
- ...new Set(
107
- root.required.filter(
108
- (name): name is string =>
109
- typeof name === 'string' && Object.prototype.hasOwnProperty.call(properties, name),
110
- ),
111
- ),
112
- ]
113
- : []
127
+ // A name is required only when **every** surface that mentions requirements
128
+ // requires it. One branch needing `id` and another not is not a reason to
129
+ // demand `id` for a call the second branch accepts.
130
+ let required = surfaces[0]?.required ? [...surfaces[0].required] : []
131
+ for (const surface of surfaces.slice(1)) {
132
+ const set = new Set(surface.required ?? [])
133
+ required = required.filter((name) => set.has(name))
134
+ }
135
+ required = [...new Set(required)].filter((name) =>
136
+ Object.prototype.hasOwnProperty.call(properties, name),
137
+ )
114
138
 
115
139
  return required.length > 0 ? { properties, required } : { properties }
116
140
  }
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.36' as const
12
+ export const PACKAGE_VERSION = '0.85.38' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4928 as const
93
+ export const TEST_COUNT = 4969 as const
@@ -19,7 +19,7 @@ export const BUNDLED_SKILLS: ReadonlyArray<BundledSkill> = [
19
19
  { type: 'standard', raw: "---\nname: implement\ndescription: Build work from a spec or tickets with systematic discipline — TDD at pre-agreed seams, incremental verification, code review before commit. Use when implementing features, bugfixes, or any planned work.\nversion: 1.0.0\nuser-invocable: true\n---\n\n# Implement — Structured Build Execution\n\n融合 Superpowers executing-plans(计划审阅 + 隔离工作区)+ Matt Pocock implement(TDD 接缝 + 增量验证 + 提交前审查)。\n\n## When to Use\n\n- Implementing work from a written spec or ticket set\n- Executing a development plan with clear deliverables\n- Building a feature with predefined success criteria\n\n## When NOT to Use\n\n- Exploratory coding / prototyping → use `prototype` skill\n- Quick one-line fixes → just fix it\n- No spec or tickets exist → use `to-tickets` or `to-spec` first\n\n---\n\n## Step 1: Load and Review\n\n### 1.1 Ensure isolated workspace\n\nUse git worktree or a feature branch. Never implement on main/master without explicit consent.\n\n### 1.2 Read the plan/spec/tickets\n\nRead the full spec or ticket set. Understand:\n\n- What is being built?\n- What are the acceptance criteria?\n- What are the pre-agreed seams (where TDD should be applied)?\n\n### 1.3 Review critically\n\nBefore writing any code:\n\n- Are there gaps or ambiguities in the spec?\n- Are the success criteria testable?\n- Do you understand every instruction?\n\n**If concerns exist, raise them before starting.** Don't guess.\n\n---\n\n## Step 2: Execute Tasks\n\nFor each task in order:\n\n### 2.1 At pre-agreed seams: TDD\n\nWhere the spec specifies (or where interfaces are well-defined):\n\n1. Write a **failing test** that asserts the expected behavior\n2. Watch it fail (red)\n3. Write the **minimum code** to make it pass (green)\n4. Refactor if needed, keeping tests green\n\nUse the `tdd` skill for full red-green-refactor discipline.\n\n### 2.2 Incremental verification\n\nDuring implementation:\n\n- **Run typecheck** after each significant change: `pnpm typecheck`\n- **Run relevant test file** after each task: `pnpm test -- <file>`\n- **Don't wait** until everything is done to discover type errors\n\n### 2.3 One task at a time\n\n- Follow each step exactly — the plan has bite-sized steps for a reason\n- One change at a time. No \"while I'm here\" improvements.\n- Mark tasks as complete after verification passes\n\n---\n\n## Step 3: Final Verification\n\nAfter all tasks are complete:\n\n### 3.1 Full test suite\n\n```bash\npnpm test\n```\n\nAll tests must pass. If any fail, fix before proceeding.\n\n### 3.2 Lint and format\n\n```bash\npnpm lint\npnpm format\n```\n\nCI must be green.\n\n---\n\n## Step 4: Code Review\n\n**Before committing**, run code review:\n\nUse the `code-review` skill for a two-axis review:\n\n- **Standards**: Does the diff follow the repo's coding standards?\n- **Spec**: Does it faithfully implement the originating issue/spec?\n\nFix any findings before committing.\n\n---\n\n## Step 5: Commit\n\nCommit your work to the current branch.\n\n```bash\ngit add -A\ngit commit -m \"<type>: <description>\"\n```\n\n- Follow Conventional Commits\n- Reference the spec/ticket in the commit message\n- **Do NOT commit unless explicitly asked** (per CLAUDE.md §关键约束)\n\n---\n\n## When to Stop and Ask\n\n**STOP immediately when:**\n\n- A task is blocked (missing dependency, unclear instruction, verification fails repeatedly)\n- The spec has a critical gap that prevents starting\n- You don't understand an instruction\n- 3+ fix attempts fail — this may be an architectural issue\n\n**Ask for clarification rather than guessing.**\n\n---\n\n## Quick Reference\n\n| Step | Key Activities | Done When |\n| -------------- | ------------------------------------------------------------ | -------------------------------- |\n| **1. Review** | Load spec, isolate workspace, review critically | All concerns raised and resolved |\n| **2. Execute** | TDD at seams, incremental typecheck/test, one task at a time | All tasks complete and verified |\n| **3. Verify** | Full test suite, lint, format | CI-ready (all green) |\n| **4. Review** | Two-axis code review (standards + spec) | Findings addressed |\n| **5. Commit** | Conventional Commits, reference spec/ticket | Work committed to branch |\n" },
20
20
  { type: 'standard', raw: "---\nname: memory\ndescription: Read and write persistent memory files for context retention across sessions — one fact per file with frontmatter\nversion: 2.0.0\n---\n\n# Memory Skill\n\nManage persistent memory stored as markdown files with YAML frontmatter.\n\n## File Format\n\nEach memory is one `.md` file under the `memory/` directory:\n\n```markdown\n---\nname: <kebab-case-slug>\ndescription: <one-line summary>\nmetadata:\n type: user | feedback | project | reference\n---\n\n<the fact body>\n\n**Why:** <rationale>\n**How to apply:** <practical guidance>\n```\n\n## File Path Conventions\n\n- Directory: `~/.mipham/memory/` (user-level) or `./.mipham/memory/` (project-level)\n- Filename: `<name-slug>.md` (lowercase, hyphens)\n- Index: `MEMORY.md` — one line per memory file, maintained automatically\n\n## Operations\n\n### List Memories\n\nScan `MEMORY.md` index for available memories. The index has one line per memory:\n\n```markdown\n- [Title](file.md) — brief hook\n```\n\n### Read Memory\n\nRead the full markdown file including frontmatter. Parse YAML frontmatter for metadata.\n\n### Write Memory\n\n1. Check for existing file with same `name:` slug — update if found\n2. Create new file if no match\n3. Add/update entry in `MEMORY.md` index\n4. Never write what the repo already records (code structure, git history, CLAUDE.md)\n\n### Delete Memory\n\nRemove the file and its index entry. Use when a memory is incorrect or superseded.\n\n## Best Practices\n\n- **One fact per file** — atomic, focused, easy to find\n- **Descriptive slugs** — `npm-publish-workflow` not `memory-1`\n- **Link related memories** — use `[[slug-name]]` wikilinks in body\n- **Check before writing** — search existing memories to avoid duplicates\n- **Types matter**: `user` (who), `feedback` (corrections), `project` (goals), `reference` (external)\n\n## Example\n\n```markdown\n---\nname: api-rate-limit\ndescription: OpenAI API has 500 RPM limit on our tier\nmetadata:\n type: reference\n---\n\nThe OpenAI API key for production has a hard 500 requests/minute limit.\nExceeding it returns HTTP 429 with a Retry-After header.\n\n**Why:** We hit this in production during peak usage\n**How to apply:** Use exponential backoff; batch requests where possible\n```\n" },
21
21
  { type: 'standard', raw: "---\nname: mipham-code-setup\ndescription: Install, configure, diagnose, and troubleshoot Mipham Code — the multi-model open-core intelligent coding terminal. Covers setup wizard, API keys, providers, models, skills, permissions, workspace trust, shell/IDE integration, and first-run onboarding.\nversion: 2.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Skill\n---\n\n# Mipham Code Setup — Executable Setup Workflow\n\n**Type**: Rigid — follow the decision tree exactly. Don't skip diagnostic phases.\n\n**Purpose**: Guide users from zero to fully configured Mipham Code. This skill is BOTH:\n\n1. A self-contained diagnostic + configuration workflow the AI can execute\n2. A reference for `/setup` command behavior and slash commands\n\n**Triggers**: \"setup mipham\", \"configure mipham\", \"install mipham code\", \"mipham not working\", \"mipham setup\", \"first time using mipham\", \"help me set up\", \"getting started\", `/setup`\n\n---\n\n## Phase 0: Environment Detection (ALWAYS RUN FIRST)\n\nBefore doing anything, run these diagnostic checks. Report results in a status table.\n\n### 0.1 — Detect Installation\n\n```bash\nwhich mipham 2>/dev/null\nmipham --version 2>/dev/null\nbun --version 2>/dev/null\nnode --version 2>/dev/null\n```\n\n### 0.2 — Detect Configuration\n\n```bash\nls -la .mipham/config.yml 2>/dev/null\nls -la ~/.mipham/config.yml 2>/dev/null\nls -la MIPHAM.md 2>/dev/null\nls -la CLAUDE.md 2>/dev/null\n```\n\n### 0.3 — Detect API Keys\n\n```bash\nenv | grep -E 'ANTHROPIC_API_KEY|OPENAI_API_KEY|DEEPSEEK_API_KEY|QWEN_API_KEY|DOUBAO_API_KEY|HUNYUAN_API_KEY|GEMINI_API_KEY' | cut -d= -f1\n```\n\n### 0.4 — Detect Skills & Permissions\n\n```bash\nls .mipham/skills/ 2>/dev/null\ncat .mipham/config.yml 2>/dev/null | grep -E 'permission|trust' || echo \"no config\"\n```\n\n### 0.5 — Detect Workspace Trust\n\n```bash\ncat ~/.mipham/trusted-workspaces.json 2>/dev/null || echo \"no trust store\"\n```\n\n### Status Report Format\n\nAfter detection, present results as:\n\n```\n── Mipham Code Status ──\n\nInstallation: [✅/⬜] mipham CLI [✅/⬜] Bun [✅/⬜] Node.js\nProject: [✅/⬜] .mipham/ [✅/⬜] config.yml [✅/⬜] MIPHAM.md\nUser Config: [✅/⬜] ~/.mipham/config.yml\nAPI Keys: [N] set (list names or \"none\")\nSkills: [N] installed\nPermissions: [mode] (default/acceptEdits/plan/auto/bypassPermissions)\nTrust: [✅/⬜] workspace trusted\n```\n\nThen proceed to ONLY the phases where something is missing. Don't re-run already-configured steps unless asked.\n\n---\n\n## Phase 1: Installation\n\n**Trigger**: `mipham --version` fails.\n\n### Option A: Quick Install (recommended)\n\n```bash\ncurl -fsSL https://mipham.ai/install.sh | bash\n```\n\nThen restart the shell or run:\n\n```bash\nexport PATH=\"$HOME/.mipham/bin:$PATH\"\n```\n\n### Option B: npm Global Install\n\n```bash\nnpm install -g @miphamai/cli\nmipham\n```\n\n### Option C: From Source (developers)\n\n```bash\ngit clone https://github.com/One-Mipham/mipham-code\ncd mipham-code/apps/cli\nbun install && bun run bin/mipham\n```\n\n### ✅ Verification\n\n```bash\nmipham --version # Should print version ≥ 0.24.0\nmipham --help # Should print usage\n```\n\n---\n\n## Phase 2: Project Initialization\n\n**Trigger**: Missing `.mipham/` directory or `MIPHAM.md`.\n\n### 2.1 — Create .mipham/ directory\n\n```bash\nmkdir -p .mipham\n```\n\n### 2.2 — Create .mipham/config.yml\n\nWrite a minimal config. Ask the user which provider they want to use first, or pick a sensible default:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\npermission: default\n```\n\n**Providers available** (alphabetical):\n\n| Provider | Type | Example Models |\n| --------- | ------------- | -------------------------------------- |\n| anthropic | Native SDK | Claude Haiku 4.5, Sonnet 4.6, Opus 4.8 |\n| deepseek | OpenAI Compat | V4 Flash, V4 Pro |\n| doubao | OpenAI Compat | Seed 1.6, Seed 2.0 |\n| gemini | OpenAI Compat | 3.0 Flash, 3.0 Pro, 2.5 Pro |\n| hunyuan | OpenAI Compat | Lite, TurboS, 2.0, T1 |\n| openai | OpenAI Compat | GPT-5.4 Mini, GPT-5.4, GPT-5.5, Codex |\n| qwen | OpenAI Compat | Qwen Plus, Qwen Max |\n\n### 2.3 — Create MIPHAM.md (optional but recommended)\n\nCreate `MIPHAM.md` in project root to define AI personality:\n\n```markdown\n# MIPHAM.md\n\n## Project Context\n\n- **Project**: [name]\n- **Language**: [zh-CN / en]\n- **Stack**: [TypeScript / Python / etc.]\n\n## Preferences\n\n- Code style: [e.g., functional, OOP]\n- Comment language: [e.g., English]\n- Test framework: [e.g., Vitest]\n```\n\n### ✅ Verification\n\n```bash\nls -la .mipham/config.yml MIPHAM.md\n```\n\n---\n\n## Phase 3: API Key Configuration\n\n**Trigger**: Missing API keys in environment.\n\n### 3.1 — Identify Required Providers\n\nAsk the user which providers they plan to use. For each, set the env var.\n\n### 3.2 — Set API Keys\n\n**Recommended: Environment variables** (not in config files — avoids accidental commits):\n\n```bash\nexport ANTHROPIC_API_KEY=\"sk-ant-...\"\nexport OPENAI_API_KEY=\"sk-...\"\nexport DEEPSEEK_API_KEY=\"sk-...\"\nexport QWEN_API_KEY=\"sk-...\"\nexport DOUBAO_API_KEY=\"...\"\nexport HUNYUAN_API_KEY=\"...\"\nexport GEMINI_API_KEY=\"...\"\n```\n\nAdd these to `~/.zshrc` or `~/.bashrc` for persistence:\n\n```bash\necho 'export ANTHROPIC_API_KEY=\"sk-ant-...\"' >> ~/.zshrc\nsource ~/.zshrc\n```\n\n**Alternative**: Store in `~/.mipham/config.yml`:\n\n```yaml\nproviders:\n - id: anthropic\n apiKey: $ANTHROPIC_API_KEY\n - id: openai\n apiKey: $OPENAI_API_KEY\n```\n\n### 3.3 — Verify Keys\n\n```bash\nenv | grep API_KEY\n```\n\n### ❗Security Rules\n\n- NEVER hardcode API keys in project config files (`.mipham/config.yml` in project root should use `$ENV_VAR` references, not raw keys)\n- NEVER commit API keys to git\n- Add to `.gitignore`: `.mipham/config.yml` (if it contains keys), `.env`, `*.pem`\n\n---\n\n## Phase 4: Provider & Model Configuration\n\n**Trigger**: Need to set default or enable/disable providers.\n\n### 4.1 — Set Default Provider & Model\n\nIn `.mipham/config.yml`:\n\n```yaml\ndefaultProvider: anthropic\ndefaultModel: claude-sonnet-4-6\n```\n\nOr use slash commands:\n\n```\n/model # Interactive model picker (Ctrl+P)\n/switch # Switch provider\n/providers # List all configured providers\n```\n\n### 4.2 — Enable/Disable Providers\n\n```yaml\nproviders:\n - id: anthropic\n status: active\n - id: openai\n status: active\n - id: deepseek\n status: disabled\n```\n\n### ✅ Verification\n\n```\n/model # Should show available models\n/providers # Should list active providers\n```\n\n---\n\n## Phase 5: Skills Installation\n\n**Trigger**: No or few skills installed.\n\n### 5.1 — Built-in Skills\n\nMipham Code ships with 28 built-in skills loaded automatically:\n\n- **Standard (22)**: code-review, codebase-design, compassionate-communication, debug-loop, doc-generator, domain-modeling, github-ops, grill-with-docs, implement, memory, mipham-code-setup, research, safe-coding, security-review, self-review, superpower, tdd, to-spec, triage, trim-process-prose, web-access, web-search\n- **Mipham (6)**: doc-sync, om-artifact, om-model-optimize, om-security, save-to-wiki, self-audit\n\n### 5.2 — Community Skills\n\nInstall from the community registry:\n\n```\n/setup 4 # Guided skill browser\n```\n\nOr directly:\n\n```bash\n# Skills are loaded from:\n# - apps/cli/skills/standard/ (built-in standard)\n# - apps/cli/skills/mipham/ (built-in mipham)\n# - ~/.mipham/skills/ (user-installed)\n# - .mipham/skills/ (project-local)\n```\n\n### 5.3 — Install Specific Skills\n\n```\n/skills install <name> # Install from registry\n/skills list # List available\n/skills search <query> # Search registry\n```\n\n### ✅ Verification\n\n```\n/skills list # Should show installed skills with counts\n```\n\n---\n\n## Phase 6: Permissions Configuration\n\n**Trigger**: Permission mode not configured or wrong for use case.\n\n### 6.1 — Permission Modes\n\n| Mode | Behavior | Use Case |\n| ------------------- | -------------------------------------- | ----------------------------------------- |\n| `default` | Ask-first tools are refused (see note) | Normal development (recommended) |\n| `acceptEdits` | Auto-allow edits, ask for other tools | Active coding sessions |\n| `plan` | Plan-only, no tool execution | Design & architecture work |\n| `auto` | A classifier rules on every call | Long unattended runs you still want gated |\n| `bypassPermissions` | Skip all checks | ⚠️ Only for fully trusted codebases |\n\n**Note on `default`**: Mipham Code has no interactive approval prompt, so \"ask\"\nmeans the call is **refused** with a message naming the mode — it is not queued\nfor your answer. That makes `default` the strictest _usable_ mode for Bash and\nfile writes; `auto` is the mode that lets gated calls proceed without a human,\nby having a classifier rule on each one.\n\n**What `auto` actually gates.** Reads (Read/Grep/Glob) are never sent to the\nclassifier — gating them would make `auto` the only mode in the ladder that cannot\nopen a file without a round-trip to another model. Everything else that the static\nchain would refuse goes to the classifier, which can only **lift** a refusal: a\ndeny rule or an `ask` rule is never overridden. If the classifier cannot be reached\nor answers unusably, the call is refused (fail-closed) with a message saying the\nrefusal is _not_ a policy decision and can be retried.\n\n### 6.2 — Configure\n\nPress **Shift+Tab** to change the mode live; it cycles\n`default → acceptEdits → plan → auto` and lasts for the session only.\n`bypassPermissions` is a legal mode but is deliberately **not** on the wheel —\nit is reached by naming it in config, where the user has said what they mean.\n\nTo persist a mode, name it in `~/.mipham/config.yml`:\n\n```yaml\npermission: default\n```\n\nOr in `~/.mipham/settings.json` as `permissions.defaultMode` (the key Claude Code\nusers already have). Any mode name from the table above is accepted in either,\nincluding `bypassPermissions`.\n\nA **project-level** `.mipham/config.yml` cannot set a mode — that file arrives with\nthe code, so whoever wrote the repository would be choosing the approval gate. A\nmode found there is ignored and reported; the fix is to move the line to the user\nlevel, or to pass `--permission <mode>` for one invocation.\n\nOr via slash command:\n\n```\n/permissions # View current settings\n/setup 5 # Permission setup wizard\n```\n\n### 6.3 — CI/CD Safety\n\nFor CI/CD environments, use the `default` mode (the daemon default): headless\nsessions never prompt, so `ask`-level tools (Bash/Write/Edit) are blocked rather\nthan auto-approved.\n\n### ✅ Verification\n\n```\n/permissions # Should show current mode\n```\n\n---\n\n## Phase 7: Workspace Trust\n\n**Trigger**: Untrusted workspace (prompted on startup in v0.24.3+).\n\n### 7.1 — Understanding Workspace Trust\n\nWorkspace trust is a security mechanism that prevents AI from operating in untrusted directories. Trust is **hierarchical**: trusting `/Users/me/Projects` implicitly trusts all subdirectories.\n\n### 7.2 — Trust a Workspace\n\n**Interactive**: Accept the trust prompt when launching Mipham Code in a new directory.\n\n**Manual**:\n\n```\n/trust # Show trust status\n/trust add <dir> # Trust a directory\n/trust remove <dir> # Revoke trust\n```\n\n### 7.3 — Trust Store\n\n```\n~/.mipham/trusted-workspaces.json\n```\n\n### 7.4 — Auto-Trust for Worktrees\n\nWhen using git worktrees, Mipham Code automatically trusts worktree directories if the parent workspace is already trusted (via `EnterWorktree`).\n\n### ✅ Verification\n\n```\n/trust # Should show \"✅ Yes\" for current directory\n```\n\n---\n\n## Phase 8: Shell & IDE Integration\n\n**Trigger**: Want terminal integration, aliases, or IDE plugins.\n\n### 8.1 — Shell Alias\n\nAdd to `~/.zshrc` or `~/.bashrc`:\n\n```bash\nalias mipham='cd ~/your-project && bun run ~/path/to/mipham-code/apps/cli/bin/mipham.ts'\n# Or if installed globally:\nalias mipham='mipham'\n```\n\n### 8.2 — VS Code Integration\n\nRun `/ide` to auto-generate `.vscode/` config files:\n\n- `settings.json` — terminal profile \"mipham\" using Bun\n- `keybindings.json` — Cmd+Esc to focus terminal, Cmd+Shift+M for new terminal\n- `extensions.json` — recommends `miphamai.mipham-code` extension\n\nTo use after generation:\n\n1. Restart VS Code (or Cmd+Shift+P → Reload Window)\n2. Open terminal: Ctrl+` or Cmd+Esc\n3. Select \"mipham\" profile from terminal dropdown\n\nInstall the VS Code extension:\n\n```bash\ncode --install-extension miphamai.mipham-code\n```\n\n### 8.3 — JetBrains Integration\n\nSettings → Tools → Terminal → Shell path → `bun run mipham`\n\n### 8.4 — Terminal Setup\n\n```\n/terminal-setup # Shell & terminal config wizard\n/setup 6 # Shell integration (part of full wizard)\n```\n\n### ✅ Verification\n\n```bash\nwhich mipham # Should resolve\n# In VS Code: Ctrl+` → select \"mipham\" profile\n```\n\n---\n\n## Phase 9: Full Verification\n\nRun after all configuration phases complete.\n\n### 9.1 — System Diagnostics\n\n```\n/doctor # System diagnostics check\n```\n\n### 9.2 — End-to-End Test\n\nStart a conversation and verify:\n\n1. Model responds (not stuck on \"connecting...\")\n2. File tools work: \"read CLAUDE.md\"\n3. Bash works: \"list files in current directory\"\n4. Skills load: `/skills list`\n\n### 9.3 — Common Issues & Fixes\n\n| Symptom | Diagnosis | Fix |\n| ------------------------- | -------------------------------------- | ------------------------------------------------ |\n| \"Provider not registered\" | Missing or invalid API key | `env \\| grep API_KEY`; check key format |\n| \"Model not found\" | Model ID mismatch or disabled provider | `/models` to list available; `/switch` to change |\n| Slow responses | Large model, network, or context full | Switch to Flash model; `/compact` |\n| Context full | Too many messages in history | `/compact` to compress; `/clear` to reset |\n| Permission denied | Tool blocked by permission mode | `/permissions` to check; adjust mode |\n| \"Workspace not trusted\" | New directory, not yet trusted | Accept startup prompt or run `/trust` |\n| MCP tools not available | Server not connected | `/mcp connect <name>` or check config |\n| Update not applying | Cached binary | `mipham update --force` then restart |\n| Config changes ignored | YAML syntax error | Validate with `mipham --check-config` |\n\n### 9.4 — Get Help\n\n```\n/help # Full command reference\n/setup # Re-run setup wizard\n/doctor # Run diagnostics\n```\n\nChat-based help: \"help me configure X\" or \"why isn't Y working?\"\n\n---\n\n## Quick Reference: Essential Slash Commands\n\n| Category | Command | Purpose |\n| ------------- | ----------------- | ------------------------------------------------------ |\n| **Setup** | `/setup` | Full 6-step setup wizard |\n| | `/setup 1` | Initialize project (.mipham/ + MIPHAM.md + config.yml) |\n| | `/setup 2` | Configure providers & API keys |\n| | `/setup 3` | Choose default model |\n| | `/setup 4` | Browse & install skills |\n| | `/setup 5` | Configure permissions |\n| | `/setup 6` | Shell & IDE integration |\n| **Diagnosis** | `/doctor` | System diagnostics |\n| | `/trust` | Workspace trust status |\n| | `/permissions` | Tool permission settings |\n| **Model** | `/model` | Interactive model picker (Ctrl+P) |\n| | `/switch` | Switch provider |\n| | `/models` | List available models |\n| **Session** | `/clear` | Reset conversation |\n| | `/compact` | Compress context |\n| | `/rename` | Rename session |\n| **Workflow** | `/plan` | Enter plan mode |\n| | `/review` | Code review |\n| | `/todos` | Task list |\n| **IDE** | `/ide` | Generate VS Code integration files |\n| | `/terminal-setup` | Shell & terminal config |\n| **Skills** | `/skills list` | List installed skills |\n| | `/skills search` | Search skill registry |\n| | `/skills install` | Install a skill |\n\n---\n\n## Post-Setup: What to Do Next\n\nAfter configuration is verified:\n\n1. **Initialize your project**: \"help me understand this codebase\"\n2. **Set up CLAUDE.md**: `/init` to generate project documentation for the AI\n3. **Install relevant skills**: `/setup 4` or `/skills search`\n4. **Configure MCP servers**: `/mcp connect` for external tool integration\n5. **Start coding**: Just start a conversation — the AI will use tools and skills automatically\n" },
22
- { type: 'standard', raw: "---\nname: research\ndescription: Deep research against primary sources, executed as a background agent. Collects findings into a single cited Markdown file. Use for investigation that requires reading official docs, source code, specs, or first-party APIs — not secondary summaries.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - WebSearch\n - WebFetch\n - Agent\n - Bash\n - Write\n - Read\n---\n\n# Research — Background Deep Research\n\n融合 Mipham web-search v3.0(查询构建+验证)+ Matt Pocock research(后台代理+一手来源+Markdown 报告)。\n\n## When to Use\n\n- \"Research X for me\"\n- \"Find out everything about Y from primary sources\"\n- \"Investigate Z and write up findings\"\n- Any question where googling + reading multiple sources is the right answer\n\n## When NOT to Use\n\n- Quick fact lookup → use `/web-search` directly\n- Question answerable from code already in context\n- Pure logic/algorithmic question\n\n---\n\n## Phase 0: Route\n\n```\nResearch task is...\n├── Quick (1-2 sources, immediate answer)?\n│ └── → Use web-search skill directly (Phase 0-4)\n│\n├── Deep (multiple sources, needs synthesis)?\n│ └── → THIS SKILL — background agent\n│\n└── Login-walled / SPA-only sources?\n └── → web-access skill (ComputerUse browser)\n```\n\n---\n\n## Phase 1: Spin Up Background Agent\n\nLaunch a **background agent** to do the heavy reading, so you keep working while it researches.\n\nThe agent's instructions:\n\n```\nYou are a research agent. Your task:\n\n1. Investigate the question against PRIMARY SOURCES ONLY:\n - Official documentation (docs.*.com, *.org)\n - Source code repositories (GitHub, GitLab)\n - Technical specifications (RFCs, standards)\n - First-party API references\n - NOT: blog posts, Medium articles, forum threads, secondary summaries\n\n2. For every claim, follow it back to the source that owns it.\n If a secondary source makes a claim, find the primary source and cite that.\n\n3. Use WebSearch to find sources.\n Use WebFetch to deep-read promising pages.\n Cross-reference critical claims across 2+ independent primary sources.\n\n4. Write findings to a SINGLE Markdown file.\n - Cite every claim with its primary source URL\n - Distinguish between facts (needs citation) and reasoning (your own)\n - Flag outdated content (\"article from 2024, may be stale\")\n - Note if a source is official docs vs community\n\n5. Save the file where the repo already keeps such notes.\n Match existing conventions. If none exist, put it in docs/research/.\n```\n\n---\n\n## Phase 2: Report Format\n\nThe agent writes findings in this structure:\n\n```markdown\n# [Research Topic]\n\n**Date**: YYYY-MM-DD\n**Sources**: N primary, M cross-references\n\n## Key Findings\n\n- [Finding 1] — [Source](URL)\n- [Finding 2] — [Source](URL)\n\n## Detailed Analysis\n\n### [Subtopic A]\n\n[Claim and citation]\n\n### [Subtopic B]\n\n[Claim and citation]\n\n## Source Evaluation\n\n| Source | Type | Authority | Notes |\n| ----------- | ------------- | --------- | --------------------- |\n| [Name](URL) | Official docs | High | Current as of YYYY-MM |\n| [Name](URL) | Source code | High | Tag vX.Y.Z |\n\n## Open Questions\n\n- [Question 1]\n- [Question 2]\n\nSources:\n\n- [Title](URL) — brief note\n```\n\n---\n\n## Phase 3: Review\n\nWhen the background agent completes:\n\n1. Read the output file\n2. Spot-check: did it follow the chain back to primary sources?\n3. Flag any claims that need further verification\n4. Surface uncertainties to the user\n\n---\n\n## Research Quality Checklist\n\n- [ ] Every factual claim has a primary source citation\n- [ ] At least one critical claim is cross-referenced (2+ sources)\n- [ ] Source type is clearly identified (official docs / source code / spec / community)\n- [ ] Outdated content is flagged with publication year\n- [ ] Reasoning vs facts are clearly distinguished\n- [ ] File saved in repo-appropriate location\n" },
22
+ { type: 'standard', raw: "---\nname: research\ndescription: Deep research against primary sources, executed as a background agent. Collects findings into a single cited Markdown file. Use for investigation that requires reading official docs, source code, specs, or first-party APIs — not secondary summaries.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - WebSearch\n - WebFetch\n - Agent\n - Bash\n - Write\n - Read\n---\n\n# Research — Background Deep Research\n\n融合 Mipham web-search v3.0(查询构建+验证)+ Matt Pocock research(后台代理+一手来源+Markdown 报告)。\n\n## When to Use\n\n- \"Research X for me\"\n- \"Find out everything about Y from primary sources\"\n- \"Investigate Z and write up findings\"\n- Any question where googling + reading multiple sources is the right answer\n\n## When NOT to Use\n\n- Quick fact lookup → use `/web-search` directly\n- Question answerable from code already in context\n- Pure logic/algorithmic question\n\n---\n\n## Phase 0: Route\n\n```\nResearch task is...\n├── Quick (1-2 sources, immediate answer)?\n│ └── → Use web-search skill directly (Phase 0-4)\n│\n├── Deep (multiple sources, needs synthesis)?\n│ └── → THIS SKILL — background agent\n│\n└── Login-walled / SPA-only sources?\n └── → web-access skill (ComputerUse browser)\n```\n\n---\n\n## Phase 1: Spin Up Background Agent\n\nLaunch a **background agent** to do the heavy reading, so you keep working while it researches.\n\nThe agent's instructions:\n\n```\nYou are a research agent. Your task:\n\n1. Investigate the question against PRIMARY SOURCES ONLY:\n - Official documentation (docs.*.com, *.org)\n - Source code repositories (GitHub, GitLab)\n - Technical specifications (RFCs, standards)\n - First-party API references\n - NOT: blog posts, Medium articles, forum threads, secondary summaries\n\n2. For every claim, follow it back to the source that owns it.\n If a secondary source makes a claim, find the primary source and cite that.\n\n3. Before external search, scan the local repo and sibling project directories\n for prior work. Open and read the relevant files — a glob hit is not a read.\n Record what you found; if there is none, say \"none\" explicitly.\n\n4. A number, \"unconditional\", \"record\", or \"first\" is a claim about a theorem\n under its stated assumptions, not about the numeral. Open the source's theorem\n statement (not the abstract), copy the assumption it depends on, and pair the\n value with that assumption wherever you write it. If the same value has several\n provenances, say which one you mean.\n\n5. Use WebSearch to find sources.\n Use WebFetch to deep-read promising pages.\n Cross-reference critical claims across 2+ independent primary sources.\n\n6. Write findings to a SINGLE Markdown file.\n - Cite every claim with its primary source URL\n - Distinguish between facts (needs citation) and reasoning (your own)\n - Flag outdated content (\"article from 2024, may be stale\")\n - Note if a source is official docs vs community\n\n7. Save the file where the repo already keeps such notes.\n Match existing conventions. If none exist, put it in docs/research/.\n```\n\n---\n\n## Phase 2: Report Format\n\nThe agent writes findings in this structure:\n\n```markdown\n# [Research Topic]\n\n**Date**: YYYY-MM-DD\n**Sources**: N primary, M cross-references\n\n## Key Findings\n\n- [Finding 1] — [Source](URL)\n- [Finding 2] — [Source](URL)\n\n## Detailed Analysis\n\n### [Subtopic A]\n\n[Claim and citation]\n\n### [Subtopic B]\n\n[Claim and citation]\n\n## Source Evaluation\n\n| Source | Type | Authority | Notes |\n| ----------- | ------------- | --------- | --------------------- |\n| [Name](URL) | Official docs | High | Current as of YYYY-MM |\n| [Name](URL) | Source code | High | Tag vX.Y.Z |\n\n## Open Questions\n\n- [Question 1]\n- [Question 2]\n\nSources:\n\n- [Title](URL) — brief note\n```\n\n---\n\n## Phase 3: Review\n\nWhen the background agent completes:\n\n1. Read the output file\n2. Spot-check: did it follow the chain back to primary sources?\n3. Flag any claims that need further verification\n4. Surface uncertainties to the user\n\n---\n\n## Research Quality Checklist\n\n- [ ] Every factual claim has a primary source citation\n- [ ] At least one critical claim is cross-referenced (2+ sources)\n- [ ] Source type is clearly identified (official docs / source code / spec / community)\n- [ ] Outdated content is flagged with publication year\n- [ ] Reasoning vs facts are clearly distinguished\n- [ ] File saved in repo-appropriate location\n" },
23
23
  { type: 'standard', raw: "---\nname: safe-coding\ndescription: Safe coding rules for code generation — validate external/user input before use and throw RangeError on invalid input\nversion: 1.0.0\n---\n\n# Safe Coding\n\n处理外部/用户输入前必须校验:`null`、`undefined`、空字符串、格式非法时,抛出 `RangeError`,消息为 `'invalid input'`。\n" },
24
24
  { type: 'standard', raw: "---\nname: security-review\ndescription: Security audit skill — vulnerability scanning, OWASP Top 10, secrets detection, supply chain analysis, and compliance checking\nversion: 1.0.0\n---\n\n# Security Review\n\nComprehensive security audit for codebases. Covers vulnerability detection, compliance, and hardening recommendations.\n\n## Audit Checklist\n\n### 1. Secrets & Credentials\n\n- [ ] No hardcoded API keys, tokens, or passwords in source files\n- [ ] `.env` and `*.pem` files in `.gitignore`\n- [ ] API keys use environment variables or secret managers\n- [ ] No credentials in git history (check `git log -p`)\n- [ ] CI/CD secrets stored securely (not in workflow files)\n\n### 2. OWASP Top 10\n\n- [ ] **Injection**: SQL, NoSQL, OS command, LDAP injection points\n- [ ] **Broken Authentication**: Weak password policies, missing MFA\n- [ ] **Sensitive Data Exposure**: Unencrypted PII, missing TLS\n- [ ] **XXE**: XML external entity processing\n- [ ] **Broken Access Control**: Missing authorization checks\n- [ ] **Security Misconfiguration**: Default credentials, verbose errors\n- [ ] **XSS**: Reflected, stored, DOM-based cross-site scripting\n- [ ] **Insecure Deserialization**: Untrusted data deserialization\n- [ ] **Using Vulnerable Components**: Outdated dependencies with CVEs\n- [ ] **Insufficient Logging**: Missing audit trails for auth events\n\n### 3. Supply Chain\n\n- [ ] All dependencies have known licenses (no copyleft/GPL)\n- [ ] No dependencies with critical CVEs\n- [ ] Lock files committed (pnpm-lock.yaml, package-lock.json)\n- [ ] Dependency update policy in place\n- [ ] SBOM (Software Bill of Materials) available\n\n### 4. Network & API Security\n\n- [ ] TLS 1.3 enforced for all external communications\n- [ ] API endpoints have rate limiting\n- [ ] CORS configured with explicit origins (not `*`)\n- [ ] SSRF protections in place (URL validation, IP filtering)\n- [ ] WebSocket connections use WSS\n- [ ] GraphQL endpoints have query depth limits\n\n### 5. File System & Path Security\n\n- [ ] Path traversal protections (no `../../../etc/passwd`)\n- [ ] File upload validation (type, size, content inspection)\n- [ ] Symlink attacks prevented\n- [ ] Sensitive directories blocked (`/etc`, `/proc`, `/sys`)\n- [ ] Temporary files cleaned up after use\n\n### 6. Code-Level Security\n\n- [ ] No `eval()` or `Function()` with user input\n- [ ] No `child_process.exec()` with unsanitized input\n- [ ] Regex patterns safe from ReDoS\n- [ ] Prototype pollution prevented\n- [ ] No `dangerouslySetInnerHTML` without sanitization (React)\n- [ ] SQL queries use parameterized statements\n\n### 7. Authentication & Sessions\n\n- [ ] Passwords hashed with bcrypt/argon2 (not MD5/SHA1)\n- [ ] Session tokens use `httpOnly`, `secure`, `SameSite=Strict`\n- [ ] JWT tokens have reasonable expiration\n- [ ] Account lockout after failed attempts\n- [ ] Password reset tokens expire and are single-use\n\n### 8. Data Protection\n\n- [ ] PII data encrypted at rest (AES-256-GCM)\n- [ ] Data encrypted in transit (TLS 1.3)\n- [ ] Logs do not contain sensitive data\n- [ ] Database backups encrypted\n- [ ] Data retention policies defined\n\n### 9. Infrastructure\n\n- [ ] Infrastructure as Code (Terraform/Pulumi) used\n- [ ] Cloud resources not publicly exposed unless intended\n- [ ] Security groups / firewalls restrict inbound traffic\n- [ ] Container images scanned for vulnerabilities\n- [ ] Kubernetes pods run as non-root\n\n### 10. Logging & Monitoring\n\n- [ ] Authentication events logged\n- [ ] Failed access attempts logged and alerted\n- [ ] Structured logging format (JSON)\n- [ ] No PII in log messages\n- [ ] Alert thresholds configured for critical events\n\n## Report Format\n\n```\nSecurity Review Report\n======================\nDate: YYYY-MM-DD\nSeverity: Critical | High | Medium | Low\n\nFinding #N: [Title]\nSeverity: Critical/High/Medium/Low\nLocation: file:line\nDescription: [What was found]\nRisk: [What could happen]\nFix: [How to resolve]\n```\n\n## Compliance Standards\n\n- OWASP ASVS Level 2\n- PCI DSS (if handling payment data)\n- GDPR (if handling EU personal data)\n- SOC 2 Type II\n- ISO 27001\n" },
25
25
  { type: 'standard', raw: "---\nname: self-review\ndescription: Self-review of staged or recently changed code — reuse, simplification, efficiency, and architectural alignment\nversion: 2.0.0\n---\n\n# Self Review\n\nReview your own code changes before committing or merging. Focus on quality improvements, not bug hunting.\n\n## When to Run\n\n- Before committing changes\n- After completing a feature or fix\n- Before requesting a peer review\n- As the final step before merging\n\n## Review Passes\n\n### Pass 1: Reuse\n\n- Is there existing code that does the same thing?\n- Are there utility functions or shared libraries you missed?\n- Could this be solved with a standard library method?\n- Are you reimplementing something the framework provides?\n\n### Pass 2: Simplification\n\n- Can a complex function be split into smaller, named functions?\n- Are there unnecessary abstractions (interfaces with one impl, unused generics)?\n- Can nested conditionals be flattened with early returns?\n- Is there dead code, unused imports, or commented-out blocks?\n\n### Pass 3: Efficiency\n\n- Are you looping over data multiple times when once would suffice?\n- Are large objects being copied unnecessarily?\n- Could a synchronous operation be made async/non-blocking?\n- Are regex patterns compiled once or on every call?\n\n### Pass 4: Altitude (Architectural Alignment)\n\n- Does this code belong where it is?\n- Is it in the right layer (UI / business logic / data access)?\n- Does it follow existing patterns in the codebase?\n- Would a new developer understand where to find this?\n\n## Output\n\nAfter each pass, either:\n\n- Apply the improvement directly (for clear wins)\n- Note the observation with a recommendation (for trade-off decisions)\n\n## Anti-Patterns\n\n- ❌ Rewriting working code for style preference\n- ❌ Adding abstractions \"just in case\"\n- ❌ Changing code outside the scope of your changes\n- ❌ \"This could be a microservice\" — no it couldn't\n" },
@@ -48,6 +48,8 @@ export class SkillsLoader implements Skills {
48
48
  private skills = new Map<string, SkillDefinition>()
49
49
  /** File each loaded skill came from — so a name collision can name both sides. */
50
50
  private sources = new Map<string, string>()
51
+ /** Paths this loader has scanned, with the type they were loaded as — what `reload()` re-reads. */
52
+ private scannedDirs = new Map<string, 'standard' | 'mipham'>()
51
53
 
52
54
  loadBuiltin(basePath: string): void {
53
55
  // Load standard skills (*.SKILL.md)
@@ -97,11 +99,38 @@ export class SkillsLoader implements Skills {
97
99
  this.loadDirectory(p, 'standard')
98
100
  } else if (stat.isFile()) {
99
101
  this.tryLoad(p, 'standard')
102
+ this.scannedDirs.set(p, 'standard')
100
103
  }
101
104
  }
102
105
  }
103
106
  }
104
107
 
108
+ /**
109
+ * Re-scan every directory/file this loader already read, and return the total
110
+ * skill count.
111
+ *
112
+ * The Skill tool calls this once on a miss: a skill written **during** the
113
+ * session (by the model itself, or by a command it ran) was invisible until a
114
+ * restart or `/reload-skills`, and "not found" was the same answer whether the
115
+ * name was wrong or the file was new. Rescanning only on a miss keeps the
116
+ * happy path unchanged.
117
+ */
118
+ reload(): number {
119
+ for (const [p, type] of this.scannedDirs) {
120
+ try {
121
+ if (!existsSync(p)) continue
122
+ if (statSync(p).isDirectory()) {
123
+ this.loadDirectory(p, type)
124
+ } else {
125
+ this.tryLoad(p, type)
126
+ }
127
+ } catch {
128
+ // A path that became unreadable is not a reload failure for the rest.
129
+ }
130
+ }
131
+ return this.skills.size
132
+ }
133
+
105
134
  /** Load a single skill file by path (used by Claude plugins: `skills/<name>/SKILL.md`). */
106
135
  loadSkillFile(path: string, type: 'standard' | 'mipham' = 'standard'): void {
107
136
  this.tryLoad(path, type)
@@ -137,6 +166,7 @@ export class SkillsLoader implements Skills {
137
166
  }
138
167
 
139
168
  private loadDirectory(dir: string, type: 'standard' | 'mipham'): void {
169
+ this.scannedDirs.set(dir, type)
140
170
  try {
141
171
  const entries = readdirSync(dir)
142
172
  for (const entry of entries) {
@@ -7,6 +7,13 @@ export interface Skills {
7
7
  list(): SkillDefinition[]
8
8
  has(name: string): boolean
9
9
  buildSystemReminder(maxTokens?: number): string
10
+ /**
11
+ * Re-scan the directories this loader already knows about. Optional: the Skill
12
+ * tool calls it once when a name is not found, so a skill written during the
13
+ * session is found without restarting (`/reload-skills` still exists for a
14
+ * deliberate full reload). A provider with no on-disk sources simply omits it.
15
+ */
16
+ reload?(): number
10
17
  }
11
18
 
12
19
  /** 缝键:ctx.skills。 */
@@ -34,7 +34,7 @@ export const reportFindingsTool: ToolDefinition = {
34
34
  },
35
35
  summary: {
36
36
  type: 'string',
37
- description: 'One-sentence statement of the defect.',
37
+ description: 'Statement of the defect.',
38
38
  },
39
39
  short_summary: {
40
40
  type: 'string',
@@ -51,6 +51,14 @@ export const reportFindingsTool: ToolDefinition = {
51
51
  description:
52
52
  'Short kebab-case slug: correctness, security, performance, simplification, test-coverage, etc.',
53
53
  },
54
+ severity: {
55
+ type: 'string',
56
+ enum: ['important', 'pre_existing', 'nit'],
57
+ description:
58
+ 'Set when the review instructions ask for it. important: a bug the change adds ' +
59
+ 'or makes worse; pre_existing: a bug that was there before the change; nit: a ' +
60
+ 'minor issue.',
61
+ },
54
62
  verdict: {
55
63
  type: 'string',
56
64
  enum: ['CONFIRMED', 'PLAUSIBLE'],
@@ -104,6 +112,12 @@ export const reportFindingsTool: ToolDefinition = {
104
112
  if (f.outcome && !['fixed', 'skipped', 'no_change_needed'].includes(f.outcome as string)) {
105
113
  errors.push(`findings[${i}]: "outcome" must be fixed, skipped, or no_change_needed`)
106
114
  }
115
+ if (
116
+ f.severity !== undefined &&
117
+ !['important', 'pre_existing', 'nit'].includes(f.severity as string)
118
+ ) {
119
+ errors.push(`findings[${i}]: "severity" must be important, pre_existing, or nit`)
120
+ }
107
121
  }
108
122
 
109
123
  if (errors.length > 0) {
@@ -154,9 +168,13 @@ export const reportFindingsTool: ToolDefinition = {
154
168
  lines.push(`${icon} ${category} (${items.length}):`)
155
169
  for (const f of items) {
156
170
  const verdict = f.verdict ? ` [${f.verdict}]` : ''
171
+ // The severity is what tells a reader whether the change made this worse
172
+ // or merely inherited it; accepting it without showing it would make the
173
+ // field an inert attribute (nothing downstream reads it).
174
+ const severity = f.severity ? ` [severity: ${f.severity}]` : ''
157
175
  const outcome = f.outcome ? ` → ${f.outcome}` : ''
158
176
  const lineRef = f.line ? `:${f.line}` : ''
159
- lines.push(` • ${f.file}${lineRef}${verdict}${outcome}`)
177
+ lines.push(` • ${f.file}${lineRef}${verdict}${severity}${outcome}`)
160
178
  lines.push(` ${f.summary}`)
161
179
  if (f.failure_scenario) {
162
180
  const scenario =
@@ -26,7 +26,15 @@ export const skillTool: ToolDefinition = {
26
26
  // Try to load the skill via SkillsLoader if available
27
27
  const loader = ctx.skillsLoader
28
28
  if (loader) {
29
- const skill = loader.get(skillName)
29
+ let skill = loader.get(skillName)
30
+ if (!skill && loader.reload) {
31
+ // A skill written during this session was not in the loader's snapshot:
32
+ // before answering "not found", re-scan the directories it already
33
+ // knows. A genuinely wrong name costs one directory walk; a new file
34
+ // stops being indistinguishable from a typo.
35
+ loader.reload()
36
+ skill = loader.get(skillName)
37
+ }
30
38
  if (!skill) {
31
39
  const available = loader
32
40
  .list()
@@ -207,6 +207,49 @@ export function isBlocked(command: string): string | null {
207
207
  return null // safe
208
208
  }
209
209
 
210
+ /**
211
+ * Git commands that rewrite refs a worktree **shares with the main checkout**.
212
+ *
213
+ * A worktree is not a sandbox for `.git`: every worktree of one repository reads
214
+ * and writes the same `refs/` (and the same `packed-refs`). A subagent isolated
215
+ * in a worktree can therefore move `main` — delete it, force it, point it at a
216
+ * different commit — and the main checkout follows, without a single file in the
217
+ * worktree changing. The `cd` escape guard does not see this: the command runs
218
+ * inside the worktree and reaches out through git's own directories.
219
+ *
220
+ * Only judged for **subagents inside a worktree**: the main session in a
221
+ * worktree is the user's own checkout and keeps every command it had. This list
222
+ * is a floor of demonstrated forms; widening it costs one blocked command.
223
+ */
224
+ const SHARED_REF_REWRITES: Array<{ pattern: RegExp; description: string }> = [
225
+ { pattern: /\bupdate-ref\b/, description: 'update-ref (writes a ref directly)' },
226
+ { pattern: /\bsymbolic-ref\b/, description: 'symbolic-ref (repoints a ref)' },
227
+ {
228
+ pattern: /\bbranch\s+.*(?:-f\b|--force\b|-m\b|-M\b|--move\b|-d\b|-D\b|--delete\b)/,
229
+ description: 'branch -f/-m/-d (force-move, rename or delete a branch)',
230
+ },
231
+ { pattern: /\bcheckout\b[^;&|]*\s-B\b/, description: 'checkout -B (reset a branch)' },
232
+ { pattern: /\bswitch\b[^;&|]*\s-C\b/, description: 'switch -C (reset a branch)' },
233
+ {
234
+ pattern: /\bworktree\s+(?:remove|prune)\b/,
235
+ description: 'worktree remove/prune (removes a sibling checkout)',
236
+ },
237
+ {
238
+ pattern: /\btag\s+.*(?:-f\b|--force\b|-d\b|--delete\b)/,
239
+ description: 'tag -f/-d (force-move or delete a tag)',
240
+ },
241
+ ]
242
+
243
+ /** First shared-ref rewrite in `command`, or `null`. */
244
+ export function detectSharedRefRewrite(command: string): { description: string } | null {
245
+ // Same gate the dangerous-git scan uses: the command must actually invoke git.
246
+ if (!/(?:^|[\s;&|(])(?:sudo\s+)?git\s+/.test(command)) return null
247
+ for (const { pattern, description } of SHARED_REF_REWRITES) {
248
+ if (pattern.test(command)) return { description }
249
+ }
250
+ return null
251
+ }
252
+
210
253
  /**
211
254
  * Detect sandbox violations from stderr output.
212
255
  * Parses common OS-level error patterns indicating denied access.
@@ -604,6 +647,22 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
604
647
  `Attempted: ${escapeTarget}. Use tools within the worktree only.`,
605
648
  }
606
649
  }
650
+ // Worktrees share `refs/` with the main checkout, so "stay inside the
651
+ // directory" is not enough: `git update-ref refs/heads/main …` moves a
652
+ // branch the main checkout is standing on. A subagent gets no vote on
653
+ // shared refs; the main session in a worktree keeps its own commands.
654
+ if (ctx.isSubAgent) {
655
+ const rewrite = detectSharedRefRewrite(command)
656
+ if (rewrite) {
657
+ return {
658
+ success: false,
659
+ content: '',
660
+ error:
661
+ `Worktree isolation: "${rewrite.description}" rewrites a ref shared with the ` +
662
+ `main checkout. Ask the main session to run it if that is what you intend.`,
663
+ }
664
+ }
665
+ }
607
666
  }
608
667
 
609
668
  // Security: check command against deny list
@@ -7,6 +7,13 @@ import { validateUrl } from '../../security/url'
7
7
  /** Most characters returned in one call. Past this the caller pages with `offset`. */
8
8
  const MAX_RETURN_CHARS = 100_000
9
9
 
10
+ /**
11
+ * Longest URL accepted. 2,000 is the anchor RFC 7230 gives for "longer than any
12
+ * real address"; a URL past it is a payload, not a page, and refusing it before
13
+ * the permission prompt keeps a pathological string out of every layer below.
14
+ */
15
+ const MAX_URL_CHARS = 2_000
16
+
10
17
  interface CacheEntry {
11
18
  content: string
12
19
  timestamp: number
@@ -278,6 +285,19 @@ export const webFetchTool: ToolDefinition = {
278
285
  const rawUrl = params.url as string
279
286
  const prompt = (params.prompt as string) || ''
280
287
  const offset = Math.max(0, Number(params.offset) || 0)
288
+ // Refuse before any parsing, DNS lookup or permission prompt: past this
289
+ // length the URL is not a page address anyone can read (the length itself
290
+ // has been used to make URL parsers backtrack for minutes).
291
+ if (rawUrl.length > MAX_URL_CHARS) {
292
+ return {
293
+ success: false,
294
+ content: '',
295
+ error:
296
+ `URL is ${rawUrl.length.toLocaleString('en-US')} characters — longer than the ` +
297
+ `${MAX_URL_CHARS.toLocaleString('en-US')}-character limit. Truncate it to the address ` +
298
+ `the page actually needs (query strings can be dropped and re-added after fetching).`,
299
+ }
300
+ }
281
301
  const url = upgradeToHttps(rawUrl)
282
302
 
283
303
  // Check cache — an incomplete entry (first 100k only) cannot answer a
package/src/ui/app.tsx CHANGED
@@ -58,6 +58,7 @@ import {
58
58
  parseSlashCommand,
59
59
  unknownCommandMessage,
60
60
  handleSwitch,
61
+ runCommandHandler,
61
62
  type CommandContext,
62
63
  } from './commands'
63
64
  import { useI18n } from '../i18n-context'
@@ -1225,7 +1226,19 @@ export function App({
1225
1226
  return
1226
1227
  }
1227
1228
  if (handler) {
1228
- const result = await handler(mkCtx(), args)
1229
+ // A handler that throws is not a crash of the session — see
1230
+ // `runCommandHandler`: the failure is reported as that command's
1231
+ // answer and the session continues.
1232
+ const outcome = await runCommandHandler(handler, mkCtx(), args)
1233
+ if (!outcome.ok) {
1234
+ setMessages((prev) => [
1235
+ ...prev,
1236
+ { role: 'user', content: input },
1237
+ { role: 'system', content: `❌ ${command} failed: ${outcome.message}` },
1238
+ ])
1239
+ return
1240
+ }
1241
+ const result = outcome.result
1229
1242
  forwardToAI = result.forwardToAI
1230
1243
  // Handle API key prompt from command result
1231
1244
  if (result.needsApiKey) {
@@ -199,6 +199,31 @@ export type CommandHandler = (
199
199
  args: string[],
200
200
  ) => CommandResult | Promise<CommandResult>
201
201
 
202
+ export type CommandOutcome = { ok: true; result: CommandResult } | { ok: false; message: string }
203
+
204
+ /**
205
+ * Run a command handler, turning a throw into a value.
206
+ *
207
+ * Handlers reach the filesystem (`/permissions` writes settings.json, `/export`
208
+ * writes a file, `/resume` reads session files), so they can fail for reasons
209
+ * the user can act on — EACCES, ENOSPC, a read-only home. Before this wrapper the
210
+ * rejection escaped the submit callback: the process-wide crash handler saw an
211
+ * unhandled rejection and exited, so "the settings file could not be written"
212
+ * looked like "the command killed the CLI". A failure is that command's answer,
213
+ * and the session stays up.
214
+ */
215
+ export async function runCommandHandler(
216
+ handler: CommandHandler,
217
+ ctx: CommandContext,
218
+ args: string[],
219
+ ): Promise<CommandOutcome> {
220
+ try {
221
+ return { ok: true, result: await handler(ctx, args) }
222
+ } catch (err) {
223
+ return { ok: false, message: err instanceof Error ? err.message : String(err) }
224
+ }
225
+ }
226
+
202
227
  // ═══════════════════════════════════════════════════════════════
203
228
  // Session & Identity
204
229
  // ═══════════════════════════════════════════════════════════════