@miphamai/cli 0.85.1 → 0.85.3

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 (63) hide show
  1. package/bin/mipham.ts +42 -2
  2. package/package.json +1 -1
  3. package/skills/standard/mipham-code-setup.SKILL.md +9 -2
  4. package/src/agent/agent-experience.ts +3 -2
  5. package/src/agent/background-registry.ts +7 -3
  6. package/src/agent/cross-session/discovery.ts +5 -12
  7. package/src/agent/cross-session/file-inbox.ts +2 -2
  8. package/src/agent/effectiveness-tracker.ts +3 -2
  9. package/src/agent/sub-agent.ts +67 -6
  10. package/src/agent/types.ts +10 -0
  11. package/src/agent-view/agent-view-manager.ts +46 -0
  12. package/src/agent-view/dashboard.tsx +106 -16
  13. package/src/agent-view/session-view.tsx +128 -0
  14. package/src/commands/autoloop-journal.ts +6 -5
  15. package/src/commands/environment.ts +11 -8
  16. package/src/commands/project.ts +5 -3
  17. package/src/config/credential-crypto.ts +13 -1
  18. package/src/config/keys-manager.ts +7 -4
  19. package/src/config/loader.ts +144 -41
  20. package/src/config/preferences.ts +6 -3
  21. package/src/core/constitution-loader.ts +3 -2
  22. package/src/core/context.ts +35 -6
  23. package/src/core/crsi-producer.ts +4 -2
  24. package/src/core/crsi-sandbox.ts +2 -1
  25. package/src/core/dream-engine.ts +5 -11
  26. package/src/core/engine.ts +9 -4
  27. package/src/core/error-signature-db.ts +3 -2
  28. package/src/core/eval-harness.ts +3 -3
  29. package/src/core/hooks-executor.ts +60 -2
  30. package/src/core/instructions.ts +69 -48
  31. package/src/core/memory/memory-manager.ts +10 -6
  32. package/src/core/permission-audit.ts +13 -6
  33. package/src/core/permission-config.ts +28 -7
  34. package/src/core/permission-rules.ts +99 -5
  35. package/src/core/permission.ts +6 -1
  36. package/src/core/rule-engine.ts +3 -2
  37. package/src/core/session-log.ts +48 -11
  38. package/src/core/session-store.ts +64 -44
  39. package/src/daemon/attach-protocol.ts +30 -3
  40. package/src/daemon/auth.ts +4 -3
  41. package/src/daemon/index.ts +4 -3
  42. package/src/daemon/remote-engine.ts +173 -24
  43. package/src/daemon/server.ts +51 -1
  44. package/src/daemon/session-worker.ts +34 -1
  45. package/src/i18n-core/locales/en-US.json +1 -0
  46. package/src/i18n-core/locales/zh-CN.json +1 -0
  47. package/src/index.tsx +75 -17
  48. package/src/mcp/oauth.ts +47 -5
  49. package/src/mcp/token-store.ts +10 -11
  50. package/src/providers/openai-compat.ts +11 -0
  51. package/src/shared/arg-validation.ts +74 -2
  52. package/src/shared/package-info.ts +1 -1
  53. package/src/shared/regular-file.ts +63 -0
  54. package/src/shared/sanitize.ts +14 -2
  55. package/src/skills/bundled-skills.ts +1 -1
  56. package/src/tools/agent/memory.ts +4 -2
  57. package/src/tools/agent/workflow.ts +6 -3
  58. package/src/tools/exec/task.ts +82 -30
  59. package/src/tools/scheduling/cron.ts +3 -9
  60. package/src/ui/app.tsx +78 -14
  61. package/src/ui/commands.ts +73 -31
  62. package/src/ui/ctrl-c-confirm.ts +63 -0
  63. package/src/workflow/journal.ts +80 -26
package/src/mcp/oauth.ts CHANGED
@@ -3,7 +3,7 @@ import { exec } from 'node:child_process'
3
3
  import { createServer, Server } from 'node:http'
4
4
  import type { IncomingMessage, ServerResponse } from 'node:http'
5
5
  import type { McpServerConfig } from '../shared/types'
6
- import { TokenStore } from './token-store'
6
+ import { TokenStore, type TokenData } from './token-store'
7
7
  import { fetchWithRetry } from '../providers/fetch-utils'
8
8
  import { createT } from '../i18n-core/t'
9
9
  import enUS from '../i18n-core/locales/en-US.json'
@@ -23,6 +23,29 @@ interface TokenResponse {
23
23
  scopes?: string[]
24
24
  }
25
25
 
26
+ /**
27
+ * 这份凭证**绑给谁** —— 即它会流经哪几个端点、以哪个 client 身份取得。
28
+ *
29
+ * 为什么需要:`TokenStore` 只按**服务名**存(`<name>.enc`),而这个名来自
30
+ * `.mcp.json` —— 那是**从 cwd 读**的项目级配置。clone 一个仓库就等于让它给你的
31
+ * MCP 服务起名,于是「名字相同」推不出「签发方相同」:把某个常见名(如 `github`)
32
+ * 的 url / tokenUrl 指到别处,缓存里那份真凭证就会被送给新的主机 —— access token
33
+ * 被直接塞进 env 交给对面,refresh token 被 POST 给对面的令牌端点(后者更危险:
34
+ * 它能换出新的 access token)。
35
+ *
36
+ * 绑定的是**凭证会去的地方**,四者任一变化即视为另一份凭证:授权端点、令牌端点、
37
+ * client 身份、资源端点(access token 最终发给它)。
38
+ */
39
+ export function credentialBinding(config: McpServerConfig): string {
40
+ const auth = config.auth
41
+ return JSON.stringify([
42
+ auth?.authorizationUrl ?? '',
43
+ auth?.tokenUrl ?? '',
44
+ auth?.clientId ?? '',
45
+ config.url ?? '',
46
+ ])
47
+ }
48
+
26
49
  function base64url(buf: Buffer): string {
27
50
  return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
28
51
  }
@@ -127,12 +150,28 @@ export class OAuthClient {
127
150
  scopes: data.scope?.split(' '),
128
151
  }
129
152
 
130
- this.store.save(config.name, result)
153
+ this.store.save(config.name, { ...result, boundTo: credentialBinding(config) })
131
154
  return result
132
155
  }
133
156
 
134
- async getValidAccessToken(serverName: string, config: McpServerConfig): Promise<string> {
157
+ /**
158
+ * 取回该服务名下的凭证 —— **仅当它确实是当前这份配置签发的**。
159
+ *
160
+ * 绑定值不符时**不删**:把配置改回去,这份凭证仍然有效,而删除是不可逆的副作用。
161
+ * 但也**不用**它 —— 换过端点之后,「同名」不再说明任何事。
162
+ *
163
+ * 旧版本存下的凭证没有 `boundTo`(`undefined`)⇒ 一律不匹配 ⇒ 走一次 PKCE 重新
164
+ * 授权。这是认下的代价:无法核实签发方的凭证,就是不能拿出去用,而多授权一次
165
+ * 的代价远小于把一份 refresh token 交给别人的端点。
166
+ */
167
+ private loadBoundToken(serverName: string, config: McpServerConfig): TokenData | null {
135
168
  const saved = this.store.load(serverName)
169
+ if (!saved) return null
170
+ return saved.boundTo === credentialBinding(config) ? saved : null
171
+ }
172
+
173
+ async getValidAccessToken(serverName: string, config: McpServerConfig): Promise<string> {
174
+ const saved = this.loadBoundToken(serverName, config)
136
175
  if (saved && new Date(saved.expiresAt).getTime() > Date.now() + 60000) {
137
176
  return saved.accessToken
138
177
  }
@@ -144,9 +183,11 @@ export class OAuthClient {
144
183
  }
145
184
 
146
185
  async refreshAccessToken(serverName: string, config: McpServerConfig): Promise<string> {
147
- const saved = this.store.load(serverName)
186
+ const saved = this.loadBoundToken(serverName, config)
148
187
  if (!saved?.refreshToken) {
149
- throw new Error(`No refresh token available for "${serverName}"`)
188
+ throw new Error(
189
+ `No refresh token available for "${serverName}" — none stored, or the stored one was issued for a different endpoint`,
190
+ )
150
191
  }
151
192
  const auth = config.auth!
152
193
  // A single failed refresh is often a transient network/server error, not a
@@ -179,6 +220,7 @@ export class OAuthClient {
179
220
  accessToken: data.access_token,
180
221
  refreshToken: data.refresh_token || saved.refreshToken,
181
222
  expiresAt: new Date(Date.now() + (data.expires_in || 3600) * 1000).toISOString(),
223
+ boundTo: credentialBinding(config),
182
224
  })
183
225
  return data.access_token
184
226
  }
@@ -1,22 +1,21 @@
1
- import {
2
- existsSync,
3
- readFileSync,
4
- writeFileSync,
5
- mkdirSync,
6
- unlinkSync,
7
- readdirSync,
8
- chmodSync,
9
- } from 'node:fs'
1
+ import { existsSync, readFileSync, mkdirSync, unlinkSync, readdirSync, chmodSync } from 'node:fs'
2
+ import { atomicWriteFileSync } from '../shared/atomic-write'
10
3
  import { join, dirname } from 'node:path'
11
4
  import { encrypt, decrypt, getCredentialKey } from '../config/credential-crypto'
12
5
  import { miphamHome } from '../core/paths.ts'
13
6
 
14
- interface TokenData {
7
+ export interface TokenData {
15
8
  accessToken: string
16
9
  refreshToken?: string
17
10
  expiresAt: string
18
11
  createdAt?: string
19
12
  scopes?: string[]
13
+ /**
14
+ * 这份凭证绑给哪个签发方(见 `credentialBinding`)。缺失 = 绑定未知,
15
+ * 调用方必须当作**不可用** —— 凭证只按服务名存,而服务名来自可从 cwd 读的
16
+ * 项目级配置,故「同名」推不出「同一签发方」。
17
+ */
18
+ boundTo?: string
20
19
  }
21
20
 
22
21
  export class TokenStore {
@@ -36,7 +35,7 @@ export class TokenStore {
36
35
  createdAt: data.createdAt || new Date().toISOString(),
37
36
  })
38
37
  const encrypted = encrypt(json, this.key)
39
- writeFileSync(filePath, encrypted, { mode: 0o600 })
38
+ atomicWriteFileSync(filePath, encrypted, { mode: 0o600 })
40
39
  try {
41
40
  chmodSync(filePath, 0o600)
42
41
  } catch {
@@ -280,6 +280,17 @@ export class OpenAICompatProvider implements ProviderInstance {
280
280
  const msg = messages[i]!
281
281
  if (!msg) continue
282
282
 
283
+ // A `system` entry is a header, not a turn: it belongs in the first slot,
284
+ // and never alongside an already-emitted system prompt. A mid-array entry
285
+ // is a client-generated UI line — the engine stores a provider failure as
286
+ // `system` so a resumed session can render it as an ⚠ line — and passing it
287
+ // through as system role hands text that came *from a provider* the highest
288
+ // authority on the very next turn. anthropic.ts drops system entries
289
+ // outright (its protocol forbids them in the array at all); keeping the
290
+ // head is the part OpenAI-compatible endpoints genuinely accept.
291
+ const isHeader = msg.role === 'system' && i === 0 && result.length === 0
292
+ if (msg.role === 'system' && !isHeader) continue
293
+
283
294
  // ── String content ──
284
295
  if (typeof msg.content === 'string') {
285
296
  // Combine: assistant text + next assistant message with tool_use blocks
@@ -6,8 +6,16 @@
6
6
  * a leftover argument as an unknown command (positional) or unknown option
7
7
  * (leading `-`/`--`) and suggests the closest known alternative via
8
8
  * Levenshtein distance, instead of silently launching the interactive CLI.
9
+ *
10
+ * It also owns the **value** domain of the one flag whose value is a named thing:
11
+ * `parsePermissionFlag` below. Keeping the flag's spelling and its accepted values in
12
+ * one module is what stops "the flag is known" and "the flag's value is understood"
13
+ * from drifting apart.
9
14
  */
10
15
 
16
+ import { ALL_MODES } from '../core/permission-config'
17
+ import type { PermissionMode } from './types'
18
+
11
19
  export interface UnknownArgument {
12
20
  kind: 'command' | 'option'
13
21
  arg: string
@@ -38,6 +46,7 @@ const KNOWN_FLAGS = [
38
46
  '--dump-config',
39
47
  '--safe-mode',
40
48
  '--resume',
49
+ '--permission',
41
50
  ]
42
51
 
43
52
  /**
@@ -47,14 +56,21 @@ const KNOWN_FLAGS = [
47
56
  * start with `-`, concluded the user had typed a command, and reported
48
57
  * `Unknown command: mipham my session` — blaming the session name and never
49
58
  * mentioning `--resume`, the one argument that was actually wrong.
59
+ *
60
+ * `--permission` is here for the same reason and for one more: `mipham attach <id>
61
+ * --permission plan` reads the session id through `firstPositional`, and without this
62
+ * entry it would have taken `plan` for a session id.
50
63
  */
51
- const VALUE_FLAGS = ['--resume']
64
+ const VALUE_FLAGS = ['--resume', '--permission']
52
65
 
53
66
  /**
54
67
  * The first token that would be read as a command, skipping flags and the values
55
68
  * of value-taking flags. `null` when there is none.
69
+ *
70
+ * Exported for `bin/mipham.ts`'s attach path, which picks its session id the same
71
+ * way: `args[1]` alone is wrong as soon as a value-taking flag comes first.
56
72
  */
57
- function firstPositional(args: string[]): string | null {
73
+ export function firstPositional(args: string[]): string | null {
58
74
  for (let i = 0; i < args.length; i++) {
59
75
  const arg = args[i]!
60
76
  if (arg.startsWith('-')) {
@@ -111,3 +127,59 @@ export function detectUnknownArgument(args: string[]): UnknownArgument | null {
111
127
 
112
128
  return null
113
129
  }
130
+
131
+ /**
132
+ * `--permission <mode>` — the mode the session starts in.
133
+ *
134
+ * The accepted set is `ALL_MODES`, i.e. **exactly what the daemon accepts over the
135
+ * wire** (its `set_mode` whitelist, pinned equal by
136
+ * `test/integrity/permission-status-parity.test.ts` P7e). One set, three doors —
137
+ * `config.yml`, this flag, the attach protocol — so a value legal at one door cannot be
138
+ * silently illegal at another. The list itself is never written out here: it is derived
139
+ * from `ALL_MODES` in both the message and `mipham --help`, because a hand-kept copy is
140
+ * what drifts the day a mode is added.
141
+ *
142
+ * Deliberately **not** the legacy three-level spellings (`self`/`ask`/`bypass`) that
143
+ * `setDefaultLevel` still maps. A flag is typed by the person reading its error message,
144
+ * which names the spellings it takes; and `bypass` is a value the daemon rejects, so
145
+ * accepting it here would make the same flag work locally and fail under
146
+ * `mipham attach` — silently, since the daemon's answer is a correction, not an error.
147
+ *
148
+ * An unrecognized value is an **error**, never a fallback to `default`: `default` is
149
+ * *wider* than most of what a user would have meant (`plan`, `acceptEdits`), so falling
150
+ * back is a silent widening — the fail-open shape this file exists to prevent. Same
151
+ * reasoning as bin's `--resume` guard, which refuses an unknown session name rather than
152
+ * quietly starting a fresh one.
153
+ *
154
+ * Space form only (`--permission plan`), like `--resume`. The `=` form is refused **here**
155
+ * rather than left to `detectUnknownArgument`, because `mipham attach` never runs that
156
+ * scan (it returns before it) — without this line `mipham attach <id> --permission=plan`
157
+ * would attach with the flag silently doing nothing, on the one path where nothing else
158
+ * would have caught it.
159
+ */
160
+ export function parsePermissionFlag(
161
+ args: string[],
162
+ ): { kind: 'absent' } | { kind: 'ok'; mode: PermissionMode } | { kind: 'error'; message: string } {
163
+ const eqForm = args.find((a) => a.startsWith('--permission='))
164
+ if (eqForm) {
165
+ return {
166
+ kind: 'error',
167
+ message: `--permission takes its value as a separate argument: mipham --permission <mode> (got "${eqForm}")`,
168
+ }
169
+ }
170
+
171
+ const at = args.indexOf('--permission')
172
+ if (at === -1) return { kind: 'absent' }
173
+
174
+ const raw = args[at + 1]
175
+ if (!raw || raw.startsWith('-')) {
176
+ return { kind: 'error', message: `Usage: mipham --permission <${ALL_MODES.join('|')}>` }
177
+ }
178
+ if (!ALL_MODES.includes(raw as PermissionMode)) {
179
+ return {
180
+ kind: 'error',
181
+ message: `Unknown permission mode: ${raw}\nValid modes: ${ALL_MODES.join(', ')}`,
182
+ }
183
+ }
184
+ return { kind: 'ok', mode: raw as PermissionMode }
185
+ }
@@ -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.1' as const
12
+ export const PACKAGE_VERSION = '0.85.3' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -0,0 +1,63 @@
1
+ import { appendFileSync, existsSync, readFileSync, statSync } from 'node:fs'
2
+
3
+ /**
4
+ * 路径是不是**普通文件** —— 判据是文件**类型**,不是存在性。
5
+ *
6
+ * `existsSync` 对 FIFO、socket、设备节点、目录一律为真,而 `readFileSync` 读一个
7
+ * 没有写者的 FIFO 会**阻塞到有写者打开它为止**。于是 `mkfifo ~/.mipham/config.yml`
8
+ * 这一条命令(或某个崩掉的工具留在 `~/.mipham/` 下的 socket)就能让 CLI 启动**永久
9
+ * 挂住**:没有输出、没有报错,也没有任何东西能给它计时 —— 阻塞发生在同步调用里,
10
+ * 定时器与 signal handler 都排不上队。闸门只能架在文件类型上。
11
+ *
12
+ * 符号链接指向普通文件**算数**(`statSync` 跟随链接,`~/.mipham` 常被软链进
13
+ * dotfiles 仓库);指向 FIFO 的不算。
14
+ *
15
+ * 已知边界:stat 与随后的 read 之间不是原子的 —— 恰好在那道缝里把路径换成 FIFO
16
+ * 仍会阻塞。不设防:能改你配置路径的人本来就能做更坏的事。
17
+ */
18
+ export function isRegularFile(path: string): boolean {
19
+ try {
20
+ return statSync(path).isFile()
21
+ } catch {
22
+ // 不存在(ENOENT)、路径中有一段不是目录(ENOTDIR)、权限不足(EACCES)、
23
+ // 链接成环(ELOOP)—— 对调用方都是同一件事:这里没有能读的内容。
24
+ return false
25
+ }
26
+ }
27
+
28
+ /**
29
+ * 读一个**普通文件**的文本内容;没有可读的普通文件时返回 null。
30
+ *
31
+ * null 的含义是「这里没有可读的普通文件」,三种来源一视同仁:缺失、不是普通文件
32
+ * (FIFO / socket / 目录 / 设备节点)、是普通文件但读不动(权限等)。
33
+ *
34
+ * 本函数**不往 stderr 写任何东西** —— 多数调用点读的是可选覆盖层,「文件不在」是
35
+ * 常态。需要提示的调用点自己判断(见 `config/loader.ts` 的 `safeParseYaml`)。
36
+ */
37
+ export function readRegularFileSync(path: string): string | null {
38
+ if (!isRegularFile(path)) return null
39
+ try {
40
+ return readFileSync(path, 'utf-8')
41
+ } catch {
42
+ return null
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 追加写入,只在目标**是普通文件或还不存在**时才写;返回是否真的写了。
48
+ *
49
+ * `appendFileSync` 会**打开目标写** —— 目标若是 FIFO 就等到有读者为止,与读侧同一个
50
+ * 坑,只是撞在写这一侧(配置备份的 `copyFileSync` 当初也是这么挂住的)。「还不存在」
51
+ * 必须放行:追加写天然承担创建。
52
+ *
53
+ * 返回 `false` 的意思是**没写**,调用方得知道自己丢了什么 —— 别把「跳过」当成功。
54
+ */
55
+ export function appendRegularFileSync(
56
+ path: string,
57
+ content: string,
58
+ options: { mode?: number } = {},
59
+ ): boolean {
60
+ if (existsSync(path) && !isRegularFile(path)) return false
61
+ appendFileSync(path, content, { encoding: 'utf-8', mode: options.mode ?? 0o600 })
62
+ return true
63
+ }
@@ -25,16 +25,28 @@
25
25
  * applied to what tools *write to disk*, not only to what gets pattern-matched.
26
26
  * Adding them here would silently rewrite file contents.
27
27
  *
28
+ * Deliberately **not** included — the two joiners, ZWNJ (U+200C) and ZWJ (U+200D),
29
+ * for exactly the reason above. This is why the zero-width part of the set is spelled
30
+ * `\u{200B}\u{200E}-\u{200F}` and *not* the closed range `\u{200B}-\u{200F}` it used to be:
31
+ * - both are load-bearing in *visible* text. ZWNJ attaches a Persian/Arabic suffix to a
32
+ * Latin word or number (the plural of "PDF"), and ZWJ is what holds a family emoji
33
+ * together (U+1F468 U+200D U+1F469 U+200D U+1F467) rather than three separate people;
34
+ * - they buy nothing on the permission path either, since no shell ignores them —
35
+ * `bash -c 'ec<ZWJ>ho hi'` is `command not found` (same for ZWNJ and ZWSP). So removing
36
+ * them from the set costs no matching protection; it only stops the write path from
37
+ * rewriting what the user asked us to write.
38
+ *
28
39
  * The tag block (U+E0000–E007F) *is* included: it is invisible in itself, and the
29
40
  * only sequences that use it (subdivision flags, e.g. U+1F3F4 + a tag run) degrade
30
41
  * to the bare black flag — which renders the same.
31
42
  */
32
43
  const DANGEROUS_UNICODE =
33
- /[\u{061C}\u{115F}-\u{1160}\u{180E}\u{200B}-\u{200F}\u{202A}-\u{202E}\u{2060}\u{2066}-\u{2069}\u{3164}\u{FEFF}\u{FFA0}\u{E0000}-\u{E007F}]/gu
44
+ /[\u{061C}\u{115F}-\u{1160}\u{180E}\u{200B}\u{200E}-\u{200F}\u{202A}-\u{202E}\u{2060}\u{2066}-\u{2069}\u{3164}\u{FEFF}\u{FFA0}\u{E0000}-\u{E007F}]/gu
34
45
 
35
46
  /**
36
47
  * Strip dangerous invisible Unicode characters from a string.
37
- * - Zero-width: U+200B (ZWSP), U+200C (ZWNJ), U+200D (ZWJ), U+200E/F (LTR/RTL marks)
48
+ * - Zero-width: U+200B (ZWSP), U+200E/F (LTR/RTL marks) — the joiners U+200C/U+200D are
49
+ * deliberately kept, see `DANGEROUS_UNICODE`
38
50
  * - Bidi controls: U+202A-E, U+2066-9, U+061C (Arabic letter mark)
39
51
  * - Word joiner: U+2060
40
52
  * - BOM: U+FEFF
@@ -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/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" },
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 | `/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,4 +1,5 @@
1
- import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs'
1
+ import { readFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs'
2
+ import { atomicWriteFileSync } from '../../shared/atomic-write'
2
3
  import { join } from 'node:path'
3
4
  import type { ToolDefinition } from '../../shared/index.ts'
4
5
  import { MemoryManager } from '../../core/memory/memory-manager'
@@ -83,7 +84,8 @@ export const memoryTool: ToolDefinition = {
83
84
 
84
85
  if (action === 'write') {
85
86
  const body = formatMemory(name, params.content as string)
86
- writeFileSync(filePath, body, 'utf-8')
87
+ // 与 MemoryManager 写的是同一批 .md:两侧都走原子写,权限语义保持一致。
88
+ atomicWriteFileSync(filePath, body, { mode: 0o644 })
87
89
  return { success: true, content: `Memory "${name}" written` }
88
90
  }
89
91
 
@@ -111,16 +111,19 @@ export const workflowTool: ToolDefinition = {
111
111
  // Persist last-run state for /workflow save
112
112
  let persistWarning = ''
113
113
  try {
114
- const { existsSync, mkdirSync, writeFileSync } = await import('node:fs')
114
+ const { existsSync, mkdirSync } = await import('node:fs')
115
+ const { atomicWriteFileSync } = await import('../../shared/atomic-write')
115
116
  const { join } = await import('node:path')
116
117
  const workflowsDir = workflowScriptDir(process.cwd())
117
118
  if (!existsSync(workflowsDir)) {
118
119
  mkdirSync(workflowsDir, { recursive: true })
119
120
  }
120
- writeFileSync(
121
+ // 机器状态(每次 run 重写,`/workflow save` 会读回):非原子写留下的半截 JSON
122
+ // 会让那条读取抛解析错。
123
+ atomicWriteFileSync(
121
124
  join(workflowsDir, '.last-run.json'),
122
125
  JSON.stringify({ runId, script, timestamp: new Date().toISOString() }),
123
- 'utf-8',
126
+ { mode: 0o644 },
124
127
  )
125
128
  } catch (err) {
126
129
  // Persistence stays best-effort — the workflow itself succeeded, so a