@miphamai/cli 0.83.0 → 0.84.0

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.
Files changed (83) hide show
  1. package/package.json +1 -1
  2. package/skills/standard/mipham-code-setup.SKILL.md +30 -8
  3. package/src/agent/agent-context.ts +5 -5
  4. package/src/agent/agent-experience.ts +2 -2
  5. package/src/agent/agent-registry.ts +4 -4
  6. package/src/agent/cross-session/discovery.ts +3 -2
  7. package/src/agent/cross-session/file-inbox.ts +2 -2
  8. package/src/agent/effectiveness-tracker.ts +2 -2
  9. package/src/agent/pattern-analyzer.ts +3 -4
  10. package/src/agent/sub-agent.ts +12 -2
  11. package/src/agent/types.ts +4 -1
  12. package/src/commands/autoloop-journal.ts +2 -2
  13. package/src/commands/environment.ts +2 -1
  14. package/src/commands/loop-scaffold.ts +2 -1
  15. package/src/commands/project.ts +86 -33
  16. package/src/config/keys-manager.ts +2 -2
  17. package/src/config/loader.ts +11 -10
  18. package/src/config/preferences.ts +3 -4
  19. package/src/core/auto-memory.ts +2 -3
  20. package/src/core/constitution-loader.ts +3 -4
  21. package/src/core/crsi-producer.ts +3 -3
  22. package/src/core/crsi-sandbox.ts +3 -2
  23. package/src/core/dream-engine.ts +2 -2
  24. package/src/core/engine.ts +38 -6
  25. package/src/core/error-signature-db.ts +2 -2
  26. package/src/core/eval-harness.ts +4 -3
  27. package/src/core/improvement-track.ts +5 -6
  28. package/src/core/instructions.ts +28 -4
  29. package/src/core/memory/memory-loader.ts +2 -3
  30. package/src/core/paths.ts +21 -1
  31. package/src/core/permission-audit.ts +120 -0
  32. package/src/core/permission-classifier.ts +449 -0
  33. package/src/core/permission-config.ts +106 -15
  34. package/src/core/permission.ts +369 -16
  35. package/src/core/rule-engine.ts +2 -2
  36. package/src/core/rules-loader.ts +3 -2
  37. package/src/core/session-log.ts +2 -3
  38. package/src/core/session-store.ts +2 -3
  39. package/src/core/workspace-trust.ts +4 -3
  40. package/src/daemon/database.ts +2 -2
  41. package/src/daemon/index.ts +2 -3
  42. package/src/daemon/launch.ts +3 -3
  43. package/src/daemon/server.ts +15 -0
  44. package/src/i18n-core/locales/en-US.json +3 -0
  45. package/src/i18n-core/locales/zh-CN.json +3 -0
  46. package/src/index.tsx +30 -6
  47. package/src/mcp/token-store.ts +2 -2
  48. package/src/plugin/plugin-manager.ts +2 -2
  49. package/src/shared/constants.ts +0 -1
  50. package/src/shared/package-info.ts +1 -1
  51. package/src/shared/types.ts +46 -6
  52. package/src/shared/update.ts +2 -3
  53. package/src/skills/bundled-skills.ts +1 -1
  54. package/src/skills/loader.ts +2 -3
  55. package/src/skills/marketplace.ts +2 -3
  56. package/src/skills/registry.ts +2 -2
  57. package/src/skills/skill-assets.ts +2 -2
  58. package/src/skills/usage.ts +2 -2
  59. package/src/telemetry/consent.ts +2 -3
  60. package/src/tools/agent/enter-plan.ts +3 -2
  61. package/src/tools/agent/exit-plan.ts +1 -1
  62. package/src/tools/agent/list-agents.ts +1 -1
  63. package/src/tools/agent/memory.ts +3 -3
  64. package/src/tools/agent/plan.ts +3 -2
  65. package/src/tools/agent/report-findings.ts +1 -1
  66. package/src/tools/agent/send-message.ts +1 -1
  67. package/src/tools/agent/skill.ts +1 -1
  68. package/src/tools/exec/git.ts +2 -2
  69. package/src/tools/exec/task.ts +1 -1
  70. package/src/tools/file/glob.ts +1 -1
  71. package/src/tools/file/grep.ts +1 -1
  72. package/src/tools/file/read.ts +1 -1
  73. package/src/tools/network/web-fetch.ts +1 -1
  74. package/src/tools/network/web-search.ts +1 -1
  75. package/src/tools/scheduling/cron.ts +5 -5
  76. package/src/tools/scheduling/schedule-wakeup.ts +1 -1
  77. package/src/tools/system/config.ts +2 -2
  78. package/src/tools/system/tool-search.ts +1 -1
  79. package/src/ui/app.tsx +51 -9
  80. package/src/ui/commands.ts +8 -17
  81. package/src/ui/config-wizard.tsx +2 -2
  82. package/src/ui/input.tsx +15 -3
  83. package/src/workflow/journal.ts +2 -2
@@ -63,10 +63,25 @@ interface WsData {
63
63
  sessionId: string
64
64
  }
65
65
 
66
+ /**
67
+ * Values `MIPHAM_DAEMON_PERMISSION` accepts. The **default stays `'default'`**;
68
+ * every widening is an explicit operator choice.
69
+ *
70
+ * `'auto'` is accepted, and today it means **every tool call is refused**: the
71
+ * mode's static baseline answers `'ask'` for all of them, and the daemon has no
72
+ * classifier to rule on the `'ask'` (the classifier is wired in the CLI's
73
+ * `index.tsx`, not here). Refusing with the mode named is the honest reading —
74
+ * `auto` means "there is no human to ask, let a classifier decide", and with no
75
+ * classifier there is nothing to decide with. The alternative (leaving it out of
76
+ * this set) would silently fall back to `'default'`, which is *more* permissive
77
+ * than what was asked for; a silent widening is the worse of the two ways to be
78
+ * wrong. This entry becomes useful the day the daemon builds a classifier.
79
+ */
66
80
  const DAEMON_PERMISSION_MODES: ReadonlySet<PermissionMode> = new Set<PermissionMode>([
67
81
  'default',
68
82
  'acceptEdits',
69
83
  'plan',
84
+ 'auto',
70
85
  'bypassPermissions',
71
86
  ])
72
87
 
@@ -804,6 +804,7 @@
804
804
  "manual": "manual mode",
805
805
  "accept_edits": "accept edits on",
806
806
  "plan_mode": "plan mode / read-only",
807
+ "auto_mode": "auto mode on",
807
808
  "bypass": "bypass"
808
809
  },
809
810
  "loading": {
@@ -992,6 +993,8 @@
992
993
  "tool_denied_deny_rule": "Tool \"{name}\" blocked by a deny rule (\"{pattern}\"). Deny rules override permission mode — try a different approach, or drop the rule with: /permissions remove \"{pattern}\"",
993
994
  "tool_denied_ask_rule": "Tool \"{name}\" requires approval (ask rule: \"{pattern}\"). Approve when prompted, or stop being asked with: /permissions allow \"{pattern}\"",
994
995
  "tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\")",
996
+ "tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule, or allow it outright with: /permissions allow \"{name}\"",
997
+ "tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
995
998
  "tool_blocked": "Tool \"{name}\" blocked by hook",
996
999
  "user_input_blocked": "User input blocked by hook.",
997
1000
  "dlp_blocked": "Request blocked by DLP policy.",
@@ -804,6 +804,7 @@
804
804
  "manual": "手动模式",
805
805
  "accept_edits": "接受编辑",
806
806
  "plan_mode": "计划模式 / 只读",
807
+ "auto_mode": "自动模式",
807
808
  "bypass": "绕过权限"
808
809
  },
809
810
  "loading": {
@@ -992,6 +993,8 @@
992
993
  "tool_denied_deny_rule": "工具 \"{name}\" 被拒绝规则(\"{pattern}\")阻止。拒绝规则优先于权限模式 — 请改用其他方式,或移除该规则:/permissions remove \"{pattern}\"",
993
994
  "tool_denied_ask_rule": "工具 \"{name}\" 需要批准(ask 规则:\"{pattern}\")。请在提示时批准,或不再询问:/permissions allow \"{pattern}\"",
994
995
  "tool_denied_mode": "工具 \"{name}\" 在 \"{mode}\" 模式下需要批准。按 Shift+Tab 切换权限模式,或不再询问:/permissions allow \"{name}\"(更窄的 \"{name}(arg)\" 亦可)",
996
+ "tool_denied_classifier": "工具 \"{name}\" 在 auto 模式下被权限分类器拦下({reason})。这是策略裁决、不是故障 —— 切换模式不会改变它,把同一次调用原样重发也只会得到同一个裁决。请改变这次调用使其不再触犯该规则,或直接放行:/permissions allow \"{name}\"",
997
+ "tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
995
998
  "tool_blocked": "工具 \"{name}\" 被钩子拦截",
996
999
  "user_input_blocked": "用户输入被钩子拦截。",
997
1000
  "dlp_blocked": "请求被 DLP 策略阻止。",
package/src/index.tsx CHANGED
@@ -1,6 +1,5 @@
1
1
  import React from 'react'
2
2
  import { join, basename } from 'node:path'
3
- import { homedir } from 'node:os'
4
3
  import { existsSync } from 'node:fs'
5
4
  import { render } from 'ink'
6
5
  import * as readline from 'node:readline'
@@ -33,6 +32,7 @@ import { SessionLog } from './core/session-log'
33
32
  import { SessionStore } from './core/session-store'
34
33
  import type { PermissionLevel, MiphamConfig, McpServerConfig } from './shared/types'
35
34
  import { PermissionSystem } from './core/permission'
35
+ import { LlmPermissionClassifier } from './core/permission-classifier'
36
36
  import { SkillsLoader } from './skills/loader'
37
37
  import { PluginManager } from './plugin/plugin-manager'
38
38
  import { loadPlugins } from './plugin/plugin-loader'
@@ -54,7 +54,7 @@ import { initTelemetry, enableTelemetryNow } from './telemetry/index'
54
54
  import { wasPrompted, markPrompted, isInteractive, setTelemetryEnabled } from './telemetry/consent'
55
55
  import { officialEndpointHost } from './telemetry/endpoint'
56
56
  import { getWorkspaceTrust, warnProjectHooksSkipped } from './core/workspace-trust'
57
- import { ARTIFACT_PORT } from './shared/constants'
57
+ import { ARTIFACT_PORT, MIPHAM_DIR } from './shared/constants'
58
58
  import { artifactsRoot } from './artifacts/paths'
59
59
  import { AgentViewManager } from './agent-view/agent-view-manager'
60
60
  import { AgentViewDashboard } from './agent-view/dashboard'
@@ -65,6 +65,7 @@ import { ConfigWizard } from './ui/config-wizard'
65
65
  import enUS from './i18n-core/locales/en-US.json' with { type: 'json' }
66
66
  import zhCN from './i18n-core/locales/zh-CN.json' with { type: 'json' }
67
67
  import type { TranslationMap } from './i18n-core/types'
68
+ import { miphamHome } from './core/paths.ts'
68
69
 
69
70
  // Locale bundles — defined at module level so the remote-attach branch can
70
71
  // reference them before the full bootstrap path runs.
@@ -401,6 +402,21 @@ export async function runApp(options: RunOptions): Promise<void> {
401
402
  const defaultModel = options.model || config.defaultModel
402
403
  const registry = bootstrapProviders(config.providers, defaultProvider, defaultModel)
403
404
 
405
+ // Attach `auto` mode's classifier here, where the provider registry exists —
406
+ // `PermissionSystem` itself imports no provider module, so the classifier is handed
407
+ // in rather than built inside. Doing it on the permission system instead of the
408
+ // engine is deliberate: an engine-side setter would be a new engine capability the
409
+ // daemon would then have to match or be exempted from
410
+ // (`test/integrity/daemon-capability-parity.test.ts`). Because that guard therefore
411
+ // cannot see this line, the wiring is asserted separately at the source level.
412
+ //
413
+ // The model is resolved per ruling through the thunk: capturing the active model
414
+ // here would freeze it at whatever was active at startup, so a user who switches to
415
+ // a cheaper model would keep paying for the old one with nothing on screen to say so.
416
+ permission.setClassifier(
417
+ new LlmPermissionClassifier(registry, { resolveModel: () => registry.getActiveModel() }),
418
+ )
419
+
404
420
  // Load instructions
405
421
  const instructions = new InstructionsLoader()
406
422
  instructions.loadAll(process.cwd())
@@ -529,8 +545,8 @@ export async function runApp(options: RunOptions): Promise<void> {
529
545
  // First-run setup detection: inject mipham-code-setup guidance when
530
546
  // no project or user config exists. This mirrors Claude Code's first-run
531
547
  // onboarding flow — the AI proactively offers to help configure the tool.
532
- const hasProjectConfig = existsSync(join(process.cwd(), '.mipham', 'config.yml'))
533
- const hasUserConfig = existsSync(join(homedir(), '.mipham', 'config.yml'))
548
+ const hasProjectConfig = existsSync(join(process.cwd(), MIPHAM_DIR, 'config.yml'))
549
+ const hasUserConfig = existsSync(miphamHome('config.yml'))
534
550
  const hasMiphamMd = existsSync(join(process.cwd(), 'MIPHAM.md'))
535
551
  if (!hasProjectConfig && !hasUserConfig) {
536
552
  const setupReminder = [
@@ -672,6 +688,14 @@ export async function runApp(options: RunOptions): Promise<void> {
672
688
  process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
673
689
  }
674
690
 
691
+ // Third channel: an unrecognized `permission:` value in config.yml. Until
692
+ // `setDefaultLevel` honoured real mode names, *no* value except `bypass` could
693
+ // report anything — they all just became `default`. Warnings are collected on the
694
+ // instance, so this has to run after the config was applied above.
695
+ for (const msg of engine.getPermission().getInvalidPermissionMode()) {
696
+ process.stderr.write(`⚠ Mipham Code: ${msg}\n`)
697
+ }
698
+
675
699
  // Initialize agent registry and load plugin agents/skills/MCP/hooks
676
700
  const agentRegistry = new AgentRegistry()
677
701
  agentRegistry.loadUserAgents()
@@ -815,8 +839,8 @@ export async function runApp(options: RunOptions): Promise<void> {
815
839
  })
816
840
 
817
841
  // ── First-run detection: show interactive ConfigWizard if no config exists ──
818
- const hasUserConfig = existsSync(join(homedir(), '.mipham', 'config.yml'))
819
- const hasProjectConfig = existsSync(join(process.cwd(), '.mipham', 'config.yml'))
842
+ const hasUserConfig = existsSync(miphamHome('config.yml'))
843
+ const hasProjectConfig = existsSync(join(process.cwd(), MIPHAM_DIR, 'config.yml'))
820
844
  const needsSetup = !hasUserConfig && !hasProjectConfig
821
845
 
822
846
  // Only ask when the first-run wizard is *not* about to take over the
@@ -8,8 +8,8 @@ import {
8
8
  chmodSync,
9
9
  } from 'node:fs'
10
10
  import { join, dirname } from 'node:path'
11
- import { homedir } from 'node:os'
12
11
  import { encrypt, decrypt, getCredentialKey } from '../config/credential-crypto'
12
+ import { miphamHome } from '../core/paths.ts'
13
13
 
14
14
  interface TokenData {
15
15
  accessToken: string
@@ -24,7 +24,7 @@ export class TokenStore {
24
24
  private storeDir: string
25
25
 
26
26
  constructor(storeDir?: string) {
27
- this.storeDir = storeDir || join(homedir(), '.mipham', 'mcp-tokens')
27
+ this.storeDir = storeDir || miphamHome('mcp-tokens')
28
28
  this.key = getCredentialKey(dirname(this.storeDir))
29
29
  }
30
30
 
@@ -8,12 +8,12 @@ import {
8
8
  renameSync,
9
9
  } from 'node:fs'
10
10
  import { join } from 'node:path'
11
- import { homedir } from 'node:os'
12
11
  import { execFileSync } from 'node:child_process'
13
12
  import { validatePlugin } from './plugin-validator'
14
13
  import { atomicWriteFileSync } from '../shared/atomic-write'
14
+ import { miphamHome } from '../core/paths.ts'
15
15
 
16
- const PLUGIN_DIR = join(homedir(), '.mipham', 'plugins')
16
+ const PLUGIN_DIR = miphamHome('plugins')
17
17
 
18
18
  export interface InstalledPlugin {
19
19
  name: string
@@ -539,7 +539,6 @@ export const TOOL_CATEGORIES = [
539
539
  ] as const
540
540
  export const CONFIG_FILE_NAME = 'config.yml'
541
541
  export const MIPHAM_DIR = '.mipham'
542
- export const USER_CONFIG_DIR = '.mipham'
543
542
  export const MEMORY_DIR = 'memory'
544
543
 
545
544
  /** 预置 Ollama 模型 — 与 ollama list 结果合并去重后展示 */
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.83.0' as const
12
+ export const PACKAGE_VERSION = '0.84.0' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -67,7 +67,14 @@ export interface Message {
67
67
  }
68
68
 
69
69
  // ── Tool Types ──
70
- export type ToolPermission = 'auto' | 'ask' | 'bypass'
70
+ /**
71
+ * Legacy 3-level tool permission (predates `PermissionMode`).
72
+ * `'self'` means "let the tool self-decide" — i.e. allowed, but not flagged as `'bypass'`.
73
+ * Renamed from `'auto'` (2026-09-22) so that `auto` can name the *classifier mode*
74
+ * without a second meaning living in `PermissionLevel` — see
75
+ * `docs/superpowers/specs/2026-09-22-permission-classifier-design.md` §3.1.
76
+ */
77
+ export type ToolPermission = 'self' | 'ask' | 'bypass'
71
78
  export type ToolCategory =
72
79
  'file' | 'exec' | 'agent' | 'network' | 'system' | 'artifact' | 'scheduling'
73
80
 
@@ -326,11 +333,44 @@ export interface InstructionFile {
326
333
  }
327
334
 
328
335
  // ── Permission Types ──
329
- /** Four explicit permission modes matching Claude Code's permission architecture */
330
- export type PermissionMode = 'default' | 'acceptEdits' | 'plan' | 'bypassPermissions'
331
-
332
- /** Backward-compatible alias: PermissionMode plus legacy 'auto'/'ask'/'bypass' */
333
- export type PermissionLevel = PermissionMode | 'auto' | 'ask' | 'bypass'
336
+ /**
337
+ * Permission modes, matching Claude Code's permission architecture.
338
+ *
339
+ * `bypassPermissions` is legal but **off the Shift+Tab cycle** — the cycle is the
340
+ * four slots Claude Code's own cycle array lists (`default`, `acceptEdits`,
341
+ * `plan`, `auto`), while this union is the full set the config may request. See
342
+ * `ALL_MODES` / `MODE_CYCLE` in `core/permission-config.ts` for why those two
343
+ * arrays are separate, and why merging them silently demotes
344
+ * `bypassPermissions`.
345
+ *
346
+ * `auto` behaves unlike the other four: it does not decide anything statically.
347
+ * Its baseline answers `'ask'` for **every** call, and the ruling is delegated to
348
+ * the LLM permission classifier (`core/permission-classifier.ts`). Two
349
+ * consequences worth knowing before reading code that switches on this union:
350
+ *
351
+ * - `auto` has **no static width**, so a "which mode is narrower" measurement
352
+ * taken from the static chain reads it as narrower than `plan` — a
353
+ * measurement of the wrong object, not a fact about `auto`.
354
+ * - A mode whose static baseline is `'ask'` must not be *reached* by a caller
355
+ * that never consults the classifier, or it degrades into "refuse everything".
356
+ *
357
+ * This copy is kept in step with `packages/shared/src/types.ts` mechanically:
358
+ * `test/integrity/shared-types-parity.test.ts` asserts that every declaration
359
+ * the two files share has the same member set (and, for union aliases, the same
360
+ * literal set). Member *lists* are all it covers — a stale prose default is
361
+ * still a human's to catch.
362
+ */
363
+ export type PermissionMode = 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions'
364
+
365
+ /**
366
+ * Backward-compatible alias: `PermissionMode` plus the legacy 3-level
367
+ * `'self'`/`'ask'`/`'bypass'`. The legacy level was named `'auto'` until 2026-09-22;
368
+ * that name now belongs to the classifier mode, so the two can no longer be
369
+ * confused for one another (the `fc5afd3a` incident was exactly that confusion:
370
+ * a config `permission: auto` meaning "tool self-decides" silently becoming
371
+ * "run everything").
372
+ */
373
+ export type PermissionLevel = PermissionMode | 'self' | 'ask' | 'bypass'
334
374
 
335
375
  /** Org-level restrictions that cap or forbid specific permission modes. */
336
376
  export interface PermissionRestrictions {
@@ -9,12 +9,11 @@
9
9
  import { readFileSync, existsSync, copyFileSync, mkdirSync, chmodSync } from 'node:fs'
10
10
  import { join } from 'node:path'
11
11
  import { execSync } from 'node:child_process'
12
- import { homedir } from 'node:os'
13
12
  import { PACKAGE_VERSION } from './package-info'
13
+ import { miphamHome } from '../core/paths.ts'
14
14
 
15
15
  const PACKAGE = '@miphamai/cli'
16
- const HOME = homedir()
17
- const MIPHAM_HOME = join(HOME, '.mipham')
16
+ const MIPHAM_HOME = miphamHome()
18
17
  const CONFIG_PATH = join(MIPHAM_HOME, 'config.yml')
19
18
 
20
19
  // Registry fallback chain: npm default → npmmirror (China mirror)
@@ -18,7 +18,7 @@ export const BUNDLED_SKILLS: ReadonlyArray<BundledSkill> = [
18
18
  { type: 'standard', raw: "---\nname: grill-with-docs\ndescription: A relentless interview to sharpen a plan or design, creating CONTEXT.md (shared language) and ADRs (architectural decisions) as we go. Use before any non-trivial implementation to align on requirements and terminology.\nversion: 1.0.0\nuser-invocable: true\nallowed-tools:\n - Read\n - Write\n - Edit\n - Bash\n - Glob\n - Grep\n - WebSearch\n - WebFetch\n---\n\n# Grill With Docs — Deep Requirements Alignment\n\nInspired by Matt Pocock's `grill-with-docs` and `domain-modeling` skills. Before writing code, run a structured interview to align on requirements, establish shared language, and record architectural decisions.\n\n## When to Use\n\n- Before any non-trivial feature implementation\n- When requirements are fuzzy (\"make it faster\", \"add X\")\n- When you need to establish project terminology\n- When architectural decisions need to be recorded\n- User says: \"plan X\", \"design Y\", \"what should we do about Z\"\n\n## When NOT to Use\n\n- Trivial bug fixes with clear expected behavior\n- One-line changes\n- Tasks where the requirements are already crystal clear\n\n---\n\n## The Interview Flow\n\n### Phase 1: Understand the Intent\n\nStart by understanding what the user actually wants. Don't ask \"what should I build?\" — ask about their goal.\n\n**Core Questions:**\n\n1. What problem are you solving? (Not what feature you're building)\n2. Who is this for? (End user, developer, internal tool?)\n3. What does success look like? (How will you know when it's done?)\n4. What's the deadline or priority context?\n\n**Anti-pattern**: Jumping to implementation questions (\"Do you want REST or GraphQL?\") before understanding the problem.\n\n### Phase 2: Sharpen the Language\n\nIdentify vague or overloaded terms and pin them down **immediately**. This is the single highest-leverage activity — shared language reduces token waste and prevents misunderstandings.\n\n**Technique: The Canonical Term**\n\n- When the user uses multiple words for the same thing, pick one as canonical\n- List rejected alternatives under `_Avoid_`\n- Be opinionated — the glossary is prescriptive, not descriptive\n\n```\nUser: \"We need a way for users to save articles for later.\"\nYou: \"Let's pin that down. 'Save for later' could mean bookmarking, or a reading list, or offline download. Which one?\"\nUser: \"Like a reading list — they can come back to it.\"\nYou: \"Got it. Let's call it a **Reading List**. Avoid 'bookmark', 'save', 'favorites'.\"\n→ Write to CONTEXT.md immediately.\n```\n\n**Technique: The Boundary Test**\n\n- When a term is proposed, test its boundaries with edge cases\n- \"Does X include Y? What about Z?\"\n\n**Technique: The Code Cross-Reference**\n\n- When the user describes how something works, check if existing code agrees\n- Surface contradictions immediately\n\n### Phase 3: Probe Edge Cases\n\nBefore accepting any requirement, stress-test it with edge cases.\n\n**Edge Case Inventory:**\n\n- **Empty state**: What does the user see when there's nothing yet?\n- **Error state**: What happens when things go wrong?\n- **Extreme values**: What about 0? What about 10,000?\n- **Concurrency**: What if two people do this at the same time?\n- **Permissions**: Who can do this? Who cannot?\n- **Scale**: What changes at 10x the current volume?\n\n**Technique: The 5 Whys**\nWhen a requirement seems odd, dig deeper:\n\n```\nUser: \"We need real-time updates.\"\nYou: \"Why real-time?\"\nUser: \"Because users need to see changes immediately.\"\nYou: \"Why do they need to see changes immediately?\"\nUser: \"Because they're collaborating on the same document.\"\n→ Now you know the REAL requirement is collaboration, not real-time.\n```\n\n### Phase 4: Make Architecture Decisions\n\nWhen a design decision meets ALL three criteria, offer to record it as an ADR:\n\n1. **Hard to reverse** — changing your mind later has real cost\n2. **Surprising without context** — a future reader would wonder \"why?\"\n3. **The result of a real trade-off** — there were genuine alternatives\n\n**What qualifies for an ADR:**\n\n- Architecture shape (monorepo vs polyrepo, event sourcing vs CRUD)\n- Integration patterns between contexts\n- Technology choices with lock-in (database, message bus, auth provider)\n- Deliberate deviations from convention (\"we use raw SQL because...\")\n- Constraints not visible in code (\"we can't use X because compliance\")\n\n**ADR Format** (write to `docs/adr/NNNN-slug.md`):\n\n```markdown\n# {Short title of the decision}\n\n{1-3 sentences: context, decision, and why.}\n```\n\nOnly add optional sections (Status, Considered Options, Consequences) when they add genuine value. Most ADRs are a single paragraph.\n\n### Phase 5: Write the CONTEXT.md\n\nAfter the interview, synthesize everything into `CONTEXT.md`.\n\n**Format** (`CONTEXT.md` at project root):\n\n```markdown\n# {Project Name} Context\n\n{One or two sentence description of the project domain.}\n\n## Language\n\n**{Term}**:\n{One or two sentence definition of what it IS.}\n_Avoid_: {alternative terms that should not be used}\n\n## Decisions\n\n- [ADR 0001: {Title}](docs/adr/0001-slug.md) — {one-line summary}\n```\n\n**Rules:**\n\n- Be opinionated — pick the best term, ban the rest\n- Only include domain-specific terms (not general programming concepts)\n- Keep definitions tight — one or two sentences\n- Update inline during the conversation, don't batch\n- CONTEXT.md is a glossary, NOT a spec or implementation plan\n\n---\n\n## During the Conversation\n\n### DO\n\n- Challenge the user when they use vague terms — \"What do you mean by 'fast'?\"\n- Propose canonical terms and write them down immediately\n- Invent edge cases and probe boundaries\n- Offer ADRs sparingly (only when all 3 criteria are met)\n- Cross-reference with existing code if available\n- Call out contradictions between what the user says and what the code does\n\n### DON'T\n\n- Rush to implementation questions before understanding the problem\n- Write ADRs for trivial decisions\n- Let fuzzy language slide — pin it down now or pay later\n- Treat CONTEXT.md as a spec or scratch pad\n- Ask yes/no questions when open-ended ones would reveal more\n\n---\n\n## Output\n\nAfter the interview, the user should have:\n\n1. **CONTEXT.md** — shared language glossary (created or updated)\n2. **ADRs** (if needed) — architectural decisions in `docs/adr/`\n3. **Clear requirements** — edge cases explored, assumptions surfaced\n4. **Shared understanding** — you and the user now mean the same thing by the same words\n\n---\n\n## Integration with Mipham Code\n\n- **Memory System**: Key terms go to project memory for persistence across sessions\n- **Critical Thinking Layer**: Apply the 5-dimension self-check (evidence standard, equivalence verification, counter-example search, confidence calibration, depth check) to your own interview questions\n- **Workflow**: For complex projects, the output of this skill feeds directly into `/implement`\n" },
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
- { 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/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` | Prompt for each tool | Normal development (recommended) |\n| `acceptEdits` | Auto-allow edits, prompt others | Active coding sessions |\n| `plan` | Plan-only, no tool execution | Design & architecture work |\n| `bypassPermissions` | Skip all checks | ⚠️ Only for fully trusted codebases |\n\n### 6.2 — Configure\n\nIn `.mipham/config.yml`:\n\n```yaml\npermission: default\n```\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 | `/fast on` or 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" },
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 for a project, in `.mipham/config.yml`:\n\n```yaml\npermission: default\n```\n\nAny mode name from the table above is accepted, including `bypassPermissions`.\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 | `/fast on` or 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
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" },
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" },
@@ -1,11 +1,11 @@
1
1
  import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
- import { homedir } from 'node:os'
4
3
  import { parse as parseYaml } from 'yaml'
5
4
  import type { SkillDefinition } from '../shared/index.ts'
6
5
  import type { Skills } from './seam'
7
6
  import { sanitizeSkillDescription, sanitizeSkillBody, checkSkillShadow } from './sanitizer.js'
8
7
  import { BUNDLED_SKILLS, type BundledSkill } from './bundled-skills'
8
+ import { miphamHome } from '../core/paths.ts'
9
9
 
10
10
  interface FrontmatterResult {
11
11
  data: Record<string, unknown>
@@ -240,8 +240,7 @@ export class SkillsLoader implements Skills {
240
240
 
241
241
  /** Load skills from ~/.mipham/skills/ (user home directory). */
242
242
  loadUserSkills(): void {
243
- const home = homedir()
244
- const userSkillsPath = join(home, '.mipham', 'skills')
243
+ const userSkillsPath = miphamHome('skills')
245
244
  this.loadExternal([userSkillsPath])
246
245
  }
247
246
 
@@ -5,12 +5,11 @@
5
5
  * registry so users can add any public repo as a source.
6
6
  */
7
7
  import { parse as parseYaml } from 'yaml'
8
- import { homedir } from 'node:os'
9
- import { join } from 'node:path'
10
8
  import { spawn } from 'node:child_process'
11
9
  import { URL } from 'node:url'
10
+ import { miphamHome } from '../core/paths.ts'
12
11
 
13
- export const MARKETPLACES_PATH = join(homedir(), '.mipham', 'marketplaces.json')
12
+ export const MARKETPLACES_PATH = miphamHome('marketplaces.json')
14
13
 
15
14
  export interface SkillFrontmatter {
16
15
  name: string
@@ -14,7 +14,6 @@ import {
14
14
  readFileSync,
15
15
  } from 'node:fs'
16
16
  import { join } from 'node:path'
17
- import { homedir } from 'node:os'
18
17
  import type { MiphamConfig } from '../shared/types.js'
19
18
  import communitySkills from './community-registry.json'
20
19
  import {
@@ -23,8 +22,9 @@ import {
23
22
  downloadFile,
24
23
  isValidSkillName,
25
24
  } from './marketplace'
25
+ import { miphamHome } from '../core/paths.ts'
26
26
 
27
- const SKILLS_DIR = join(homedir(), '.mipham', 'skills')
27
+ const SKILLS_DIR = miphamHome('skills')
28
28
 
29
29
  // ═══════════════════════════════════════════════════════════════
30
30
  // Community Skill Registry
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
2
2
  import { join, dirname } from 'node:path'
3
- import { homedir } from 'node:os'
4
3
  import { BUNDLED_SKILL_ASSETS, type BundledSkillAsset } from './bundled-skill-assets'
4
+ import { miphamHome } from '../core/paths.ts'
5
5
 
6
6
  export interface SkillAssetsOptions {
7
7
  /** Base dir under which assets land as `<baseDir>/<skillName>/...`. Defaults to `~/.mipham/skills`. */
@@ -20,7 +20,7 @@ export interface SkillAssetsOptions {
20
20
  */
21
21
  export function ensureSkillAssets(skillName: string, opts?: SkillAssetsOptions): string | null {
22
22
  const map = opts?.assets ?? BUNDLED_SKILL_ASSETS
23
- const base = opts?.baseDir ?? join(homedir(), '.mipham', 'skills')
23
+ const base = opts?.baseDir ?? miphamHome('skills')
24
24
  const list = map[skillName]
25
25
  if (!list) return null
26
26
  const root = join(base, skillName)
@@ -1,11 +1,11 @@
1
1
  import { readFileSync, mkdirSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
- import { homedir } from 'node:os'
4
3
  import { atomicWriteFileSync } from '../shared/atomic-write'
4
+ import { miphamHome } from '../core/paths.ts'
5
5
 
6
6
  // Skill 使用记录:name → 最近调用时间戳(epoch ms)。持久化到 ~/.mipham/skill-usage.json,
7
7
  // 供 /skill-doctor 识别「从未被调用」的 skill(跨会话累积,按证据 prune)。
8
- const USAGE_DIR = join(homedir(), '.mipham')
8
+ const USAGE_DIR = miphamHome()
9
9
  const USAGE_FILE = join(USAGE_DIR, 'skill-usage.json')
10
10
 
11
11
  /** 读 skill 使用记录。文件缺失或损坏(非法 JSON / 类型不符)→ 空 Map,绝不抛错。 */
@@ -1,8 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { join } from 'node:path'
3
- import { homedir } from 'node:os'
4
2
  import { readSettingsDoc, writeSettingsDoc, settingsPathFor } from '../config/loader'
5
3
  import { resolveEndpoint, type EndpointSource } from './endpoint'
4
+ import { miphamHome } from '../core/paths.ts'
6
5
 
7
6
  /**
8
7
  * Consent for telemetry.
@@ -205,5 +204,5 @@ export function isInteractive(
205
204
 
206
205
  /** `~/.mipham/telemetry` — the queue directory. */
207
206
  export function telemetryDir(): string {
208
- return join(homedir(), '.mipham', 'telemetry')
207
+ return miphamHome('telemetry')
209
208
  }
@@ -1,6 +1,7 @@
1
1
  import { mkdirSync, writeFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import type { ToolDefinition } from '../../shared/index.ts'
4
+ import { MIPHAM_DIR } from '../../shared/constants.ts'
4
5
 
5
6
  export const enterPlanModeTool: ToolDefinition = {
6
7
  name: 'EnterPlanMode',
@@ -10,7 +11,7 @@ export const enterPlanModeTool: ToolDefinition = {
10
11
  'Use this before writing code to design an implementation approach, ' +
11
12
  'explore the codebase, and get user approval before executing changes.',
12
13
  category: 'agent',
13
- permission: 'auto',
14
+ permission: 'self',
14
15
  parameters: {
15
16
  type: 'object',
16
17
  properties: {
@@ -26,7 +27,7 @@ export const enterPlanModeTool: ToolDefinition = {
26
27
  const description = (params.description as string) || 'Implementation Plan'
27
28
 
28
29
  // Create plan file
29
- const planDir = join(ctx.cwd, '.mipham', 'plans')
30
+ const planDir = join(ctx.cwd, MIPHAM_DIR, 'plans')
30
31
  mkdirSync(planDir, { recursive: true })
31
32
 
32
33
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
@@ -9,7 +9,7 @@ export const exitPlanModeTool: ToolDefinition = {
9
9
  'After calling this, present your plan and ask the user to confirm. ' +
10
10
  'The user can approve by saying "approved" or "/approve", or by cycling to acceptEdits mode with Shift+Tab.',
11
11
  category: 'agent',
12
- permission: 'auto',
12
+ permission: 'self',
13
13
  parameters: {
14
14
  type: 'object',
15
15
  properties: {
@@ -8,7 +8,7 @@ export const listAgentsTool: ToolDefinition = {
8
8
  'Returns session ID, name, machine, working directory, provider, and model for each session. ' +
9
9
  'Use with SendMessage to communicate across sessions.',
10
10
  category: 'agent',
11
- permission: 'auto',
11
+ permission: 'self',
12
12
  parameters: {
13
13
  type: 'object',
14
14
  properties: {
@@ -1,12 +1,12 @@
1
1
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
- import { homedir } from 'node:os'
4
3
  import type { ToolDefinition } from '../../shared/index.ts'
5
4
  import { MemoryManager } from '../../core/memory/memory-manager'
6
5
  import { renderWorkingState } from '../../core/working-memory'
7
6
  import { getTasks } from '../exec/task'
7
+ import { miphamHome } from '../../core/paths.ts'
8
8
 
9
- const MEMORY_DIR = join(homedir(), '.mipham', 'memory')
9
+ const MEMORY_DIR = miphamHome('memory')
10
10
 
11
11
  /**
12
12
  * Format a memory file with frontmatter, compatible with MemoryManager.parseMemoryFile.
@@ -29,7 +29,7 @@ export const memoryTool: ToolDefinition = {
29
29
  name: 'Memory',
30
30
  description: 'Read, write, list, and search persistent memory files in ~/.mipham/memory/.',
31
31
  category: 'agent',
32
- permission: 'auto',
32
+ permission: 'self',
33
33
  parameters: {
34
34
  type: 'object',
35
35
  properties: {