homunculus-code 0.1.0 → 0.3.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.
@@ -0,0 +1,90 @@
1
+ # ch02: Subagents + Agent Teams
2
+
3
+ ## 3. Subagents 系統
4
+
5
+ ```yaml
6
+ # ~/.claude/agents/my-agent.md
7
+ ---
8
+ name: my-agent
9
+ description: Use proactively for X. Delegates Y tasks.
10
+ tools: Read, Grep, Glob, Bash
11
+ model: haiku # sonnet | opus | haiku | inherit | 完整 model ID(如 claude-opus-4-6)(v2.1.74 修復:之前完整 ID 被靜默忽略)
12
+ permissionMode: acceptEdits
13
+ maxTurns: 20
14
+ memory: user # 持久記憶到 ~/.claude/agent-memory/<name>/
15
+ background: false # true = 永遠背景執行
16
+ isolation: worktree # git worktree 隔離
17
+ skills:
18
+ - shell-automation-patterns # 啟動時完全預載入 skill 內容(full preload)
19
+ ---
20
+ You are a specialized agent...
21
+ ```
22
+
23
+ > **Skills 預載入差異**:主 session 按需載入 skills(用戶 `/invoke` 或 Claude 判斷時才讀取內容);
24
+ > Subagent 的 `skills:` 欄位在**啟動時完全預載入**(full preload),直接進入隔離 context。
25
+ > Subagent **不繼承**主 session 已載入的 skills,必須在 `skills:` 中明確列出。
26
+
27
+ > **Subagent 繼承規則**:獨立 context 但**繼承 CLAUDE.md + git status**(從 parent)。
28
+ > System prompt 與 parent **共享緩存**(節省 tokens)。對話歷史**不繼承**。
29
+
30
+ **記憶 Scopes**:
31
+
32
+ | Scope | 路徑 | 適用 |
33
+ |-------|------|------|
34
+ | `user` | `~/.claude/agent-memory/<name>/` | 跨所有專案(推薦預設)|
35
+ | `project` | `.claude/agent-memory/<name>/` | 專案特定,可 commit 分享 |
36
+ | `local` | `.claude/agent-memory-local/<name>/` | 專案特定,不 commit |
37
+
38
+ → 自動注入 `MEMORY.md` 前 200 行到 subagent context
39
+
40
+ **Session-Scoped Agents(CLI flag)**:
41
+ ```bash
42
+ claude --agents '{
43
+ "code-reviewer": {
44
+ "description": "Expert code reviewer. Use proactively after code changes.",
45
+ "prompt": "You are a senior code reviewer...",
46
+ "tools": ["Read", "Grep", "Glob", "Bash"],
47
+ "model": "sonnet"
48
+ }
49
+ }'
50
+ ```
51
+
52
+ **Resume Subagent**:Subagent 完成後可繼續(完整 context 保留):
53
+ ```text
54
+ Use the code-reviewer to review src/auth.ts
55
+ [Agent 完成]
56
+ Continue that code review and now check src/session.ts
57
+ ```
58
+ Transcripts:`~/.claude/projects/{project}/{sessionId}/subagents/agent-{id}.jsonl`
59
+
60
+ **Subagent-scoped hooks**:定義在 frontmatter 中,只在該 subagent 執行期間生效,結束後自動清理。
61
+
62
+ **Agent 管理**:`/agents`(互動式)、`claude agents`(CLI 列出)
63
+
64
+ ---
65
+
66
+
67
+ ---
68
+
69
+ ## 11. Agent Teams(實驗性)
70
+
71
+ ```bash
72
+ # 啟用
73
+ # settings.json: { "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" } }
74
+
75
+ # 建立 team(自然語言)
76
+ "Create a team with 3 teammates: security reviewer, performance reviewer, test reviewer"
77
+
78
+ # 控制
79
+ # Shift+Down → 切換 teammate
80
+ # Ctrl+T → 切換 task list
81
+ ```
82
+
83
+ **Subagents vs Agent Teams**:
84
+ - Subagents:回報給 main agent,適合快速獨立任務
85
+ - Agent Teams:teammates 互相通訊,適合需要討論/辯論的複雜研究
86
+
87
+ **最佳規模**:3-5 teammates,每人 5-6 tasks,各人負責不同檔案(避免衝突)
88
+
89
+ ---
90
+
@@ -0,0 +1,104 @@
1
+ # ch03: Hooks 系統
2
+
3
+ ## 4. Hooks 系統
4
+
5
+ ```json
6
+ // .claude/settings.json
7
+ {
8
+ "hooks": {
9
+ "PreToolUse": [
10
+ {
11
+ "matcher": "Bash",
12
+ "hooks": [{"type": "command", "command": "echo 'About to run bash'"}]
13
+ }
14
+ ],
15
+ "PostToolUse": [
16
+ {
17
+ "matcher": "Write|Edit",
18
+ "hooks": [{"type": "command", "command": "npm run lint:fix"}]
19
+ }
20
+ ],
21
+ "Stop": [
22
+ {
23
+ "hooks": [{"type": "command", "command": "./scripts/session-end.js"}]
24
+ }
25
+ ]
26
+ }
27
+ }
28
+ ```
29
+
30
+ **Hook 事件(完整,22 種)**:
31
+ `SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `PostToolUse`, `PostToolUseFailure`, `Notification`, `SubagentStart`, `SubagentStop`, `Stop`, `StopFailure`(API 錯誤時,v2.1.78), `TeammateIdle`(exit 2 = 繼續工作), `TaskCompleted`(exit 2 = 阻止完成), `InstructionsLoaded`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `PreCompact`, `PostCompact`(v2.1.76), `Elicitation`(exit 2 = deny MCP input), `ElicitationResult`(exit 2 = block), `SessionEnd`
32
+
33
+ **四種 Hook 類型**:
34
+ ```json
35
+ // 1. Shell command(最常用)
36
+ {"type": "command", "command": "bash script.sh", "async": true}
37
+
38
+ // 2. HTTP endpoint(POST JSON,非 2xx 不阻塞)
39
+ {
40
+ "type": "http",
41
+ "url": "http://localhost:3000/hooks/pre-tool-use",
42
+ "headers": {"Authorization": "Bearer $MY_TOKEN"},
43
+ "allowedEnvVars": ["MY_TOKEN"]
44
+ }
45
+
46
+ // 3. Claude model 判斷
47
+ {"type": "prompt", "prompt": "Should this tool be allowed? $ARGUMENTS"}
48
+
49
+ // 4. Subagent 驗證(可用 Read/Grep/Glob)
50
+ {"type": "agent", "prompt": "Validate: $ARGUMENTS"}
51
+ ```
52
+
53
+ **控制 Claude 行為**(exit code):
54
+ - `exit 0` = 繼續
55
+ - `exit 2` + `stdout` = 阻擋(輸出作為 Claude 的 feedback)
56
+
57
+ **額外欄位**:`async: true`(背景)、`timeout`(秒)、`statusMessage`(spinner 文字)、`once: true`(只執行一次,Skills 專用)
58
+
59
+ **進階 Hook 模式**:
60
+
61
+ ```bash
62
+ # SessionStart compact matcher — compact 後重新注入 context(高價值!)
63
+ # settings.json hooks.SessionStart[{matcher: "compact"}]
64
+
65
+ # 結構化 JSON 輸出(比 exit code 更細緻)
66
+ echo '{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Use rg instead of grep"}}'
67
+ # permissionDecision: "allow" | "deny" | "ask"
68
+
69
+ # Stop hook — 防無限迴圈
70
+ if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then exit 0; fi
71
+ echo '{"decision": "block", "reason": "Tests not passing yet"}'
72
+
73
+ # Agent-based Stop hook — spawn subagent 驗證程式碼狀態
74
+ # {"type": "agent", "prompt": "Verify all unit tests pass.", "timeout": 120}
75
+
76
+ # MCP 工具 matcher
77
+ # {"matcher": "mcp__github__.*"} {"matcher": "mcp__playwright__.*"}
78
+
79
+ # UserPromptSubmit 注入 context
80
+ echo '{"additionalContext": "Current git branch: main, last deploy: 2h ago"}'
81
+ ```
82
+
83
+ **進階 hookSpecificOutput 欄位**:
84
+ ```bash
85
+ # 1. CLAUDE_ENV_FILE(SessionStart 專用)— 持久化 env vars 到所有 Bash 呼叫
86
+ echo 'export NODE_ENV=production' >> "$CLAUDE_ENV_FILE"
87
+
88
+ # 2. updatedInput(PreToolUse)— 執行前修改工具輸入
89
+ echo '{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "allow", "updatedInput": {"command": "safe-cmd"}}}'
90
+
91
+ # 3. updatedPermissions(PermissionRequest)— 自動批准不再提示
92
+ echo '{"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": {"behavior": "allow", "updatedPermissions": [{"type": "toolAlwaysAllow", "tool": "Bash"}]}}}'
93
+
94
+ # 4. updatedMCPToolOutput(PostToolUse,MCP 工具專用)— 過濾 MCP 回應
95
+ echo '{"hookSpecificOutput": {"hookEventName": "PostToolUse", "updatedMCPToolOutput": "sanitized output"}}'
96
+ ```
97
+
98
+ **⚠️ Shell profile 陷阱**:hook 在非互動 shell 執行,`~/.zshrc` 中的 `echo` 會污染 JSON:
99
+ ```bash
100
+ if [[ $- == *i* ]]; then echo "Shell ready"; fi # 只在互動 shell echo
101
+ ```
102
+
103
+ ---
104
+
@@ -0,0 +1,78 @@
1
+ # ch04: MCP 設定 + MCP 進階設定
2
+
3
+ ## 5. MCP 設定
4
+
5
+ ```json
6
+ // .claude/settings.json (project scope,推薦)
7
+ {
8
+ "mcpServers": {
9
+ "playwright": {
10
+ "type": "stdio",
11
+ "command": "npx",
12
+ "args": ["-y", "@anthropic/mcp-playwright"]
13
+ },
14
+ "filesystem": {
15
+ "type": "stdio",
16
+ "command": "npx",
17
+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/jinx"]
18
+ },
19
+ "my-local-tool": {
20
+ "type": "stdio",
21
+ "command": "node",
22
+ "args": ["/Users/jinx/tools/my-mcp.js"]
23
+ }
24
+ }
25
+ }
26
+ ```
27
+
28
+ **Scope 層級**:
29
+ - **User(全域)**:`~/.claude/settings.json` → 所有專案可用
30
+ - **Project(專案)**:`.claude/settings.json` → 只此專案有效(推薦隔離)
31
+ - **CLI 覆蓋**:`claude --mcp-config ./custom.json`;`--strict-mcp-config` 只用指定設定
32
+
33
+ **MCP Tool Search**:預設啟用,最多載入 **10% context** 的 MCP tools,其餘延遲載入直到需要。
34
+
35
+ **MCP 精選原則**:只啟用當前任務需要的,不要全開(省 context)
36
+
37
+ ---
38
+
39
+
40
+ ---
41
+
42
+ ## 20. MCP 進階設定(2026)
43
+
44
+ ```bash
45
+ # Scope(注意:名稱已更改)
46
+ claude mcp add --scope user playwright -- npx @playwright/mcp@latest # 跨專案
47
+ claude mcp add --scope project --transport http github https://... # 共享
48
+
49
+ # Claude Code 作為 MCP server(供 Claude Desktop 連接)
50
+ claude mcp serve
51
+
52
+ # 從 Claude Desktop 匯入
53
+ claude mcp add-from-claude-desktop
54
+ ```
55
+
56
+ **.mcp.json 環境變數展開**:
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "api": {
61
+ "type": "http",
62
+ "url": "${API_BASE:-https://api.example.com}/mcp",
63
+ "headers": {"Authorization": "Bearer ${API_KEY}"}
64
+ }
65
+ }
66
+ }
67
+ ```
68
+
69
+ | 環境變數 | 用途 |
70
+ |---------|------|
71
+ | `MCP_TIMEOUT` | server 啟動 timeout(ms)|
72
+ | `MAX_MCP_OUTPUT_TOKENS` | 輸出上限(預設 25000)|
73
+ | `ENABLE_CLAUDEAI_MCP_SERVERS=false` | 不自動載入 claude.ai servers |
74
+
75
+ ⚠️ SSE transport 已棄用,改用 HTTP
76
+
77
+ ---
78
+
@@ -0,0 +1,161 @@
1
+ # ch05: UI 功能(Checkpointing / 排程 / Remote Control / Fast Mode / Keybindings)
2
+
3
+ ## 6. Checkpointing / Rewind
4
+
5
+ 每個 user prompt 自動建立 checkpoint(追蹤檔案編輯前狀態),跨 session 保存,30 天後清除。
6
+
7
+ ```
8
+ Esc + Esc 或 /rewind ← 開啟 rewind 選單
9
+ ```
10
+
11
+ | 選項 | 行為 |
12
+ |------|------|
13
+ | Restore code and conversation | 完整回退(回到該點的程式碼 + 對話)|
14
+ | Restore code only | 只回退檔案,保留對話 |
15
+ | **Summarize from here** | **壓縮該點後的對話(最常用,不改檔案)** |
16
+
17
+ 回退後,被選中的 prompt 會放回 input field,可直接重發或修改。
18
+
19
+ ### Summarize from here(關鍵技巧)
20
+
21
+ 比 `/compact` 更精準的 context 管理:
22
+ - 保留選中點之前的完整對話,只壓縮之後的部分
23
+ - **不修改磁碟檔案**,原始訊息仍在 transcript
24
+ - 最佳時機:debug 密集段結束後、切換任務前
25
+ - 效果:把佔空間的 debug session 壓縮,為新任務騰出 context
26
+
27
+ ### Checkpoint vs /fork
28
+
29
+ | | Checkpoint / Rewind | Fork |
30
+ |--|---------------------|------|
31
+ | 動作 | 回退到過去狀態(undo)| 從當前狀態分支(branch)|
32
+ | 用途 | 回到某點重試不同方案 | 平行探索不同方向,保留原 session |
33
+ | 命令 | `Esc+Esc` / `/rewind` | `claude --continue --fork-session` |
34
+
35
+ ### 限制
36
+
37
+ - Bash 指令造成的改動**不追蹤**(rm、mv、cp 等)
38
+ - 不追蹤 Claude Code 外部的手動修改
39
+ - 不是 git 替代品(checkpoint = local undo,git = permanent history)
40
+
41
+ ### 應用場景
42
+
43
+ - **Debug 死胡同** → Restore code and conversation → 重新開始
44
+ - **長 session 中段清理** → Summarize from here → 釋放 context
45
+ - **比較實作方案** → checkpoint → 嘗試 A → 不滿意 → rewind → 嘗試 B
46
+
47
+ ---
48
+
49
+ ## 7. 排程任務(Session-Scoped)
50
+
51
+ ```text
52
+ /loop 5m check if deployment finished
53
+ /loop 30m /review-pr 1234
54
+ remind me at 3pm to push release branch
55
+ ```
56
+
57
+ 底層工具:`CronCreate`, `CronList`, `CronDelete`
58
+
59
+ **限制**:session-scoped,關閉 terminal 後消失。持久排程要用 launchd 或 GitHub Actions。
60
+
61
+ ---
62
+
63
+ ## 8. Remote Control
64
+
65
+ ```bash
66
+ claude remote-control "My Project" # 新 session(自訂名稱)
67
+ /remote-control # 現有 session 中啟動
68
+ /rc # 縮寫
69
+ /rc My Project # 加自訂名稱
70
+ ```
71
+
72
+ 連接方式:terminal 按空白鍵顯示 QR code;或直接用 URL;或到 `claude.ai/code` session 列表。
73
+
74
+ | | Remote Control | Claude Code on the web |
75
+ |--|----------------|------------------------|
76
+ | 執行位置 | **本機** | Anthropic 雲端 |
77
+ | 本地 MCP/工具 | ✅ 可用 | ❌ 不可用 |
78
+ | 本地檔案系統 | ✅ 完整存取 | ❌ 不可用 |
79
+ | 適用場景 | 從桌機開始,手機繼續 | 不需要本地環境的任務 |
80
+
81
+ **技術細節**:outbound HTTPS only(不開 inbound ports)、多個短期憑證分開 scope、網路中斷後自動重連、每 session 只能一個遠端連線。
82
+
83
+ **限制**:關閉 terminal = session 結束(不繼續跑);網路中斷超過 ~10 分鐘 = timeout。
84
+
85
+ **啟用對所有 session**:`/config → Enable Remote Control for all sessions → true`
86
+
87
+ ```bash
88
+ /mobile # 顯示 Claude app 下載 QR code
89
+ /desktop # 將 session 傳送到 Desktop app
90
+ ```
91
+
92
+ ---
93
+
94
+
95
+ ---
96
+
97
+ ## 12. Fast Mode(Opus 4.6 加速)
98
+
99
+ ```
100
+ /fast # 切換 on/off,Opus 4.6 速度 2.5x,費用更高
101
+ ```
102
+
103
+ - `↯` 圖示出現 = fast mode 啟用
104
+ - 建議 session **開始**就決定,中途切換會多付整個 context 的費用
105
+ - 不適合:背景任務、CI/CD、重成本環境
106
+
107
+ ---
108
+
109
+
110
+ ---
111
+
112
+ ## 19. 自訂快捷鍵(Keybindings)
113
+
114
+ ```bash
115
+ /keybindings # 建立或開啟 ~/.claude/keybindings.json(儲存後即時套用)
116
+ ```
117
+
118
+ ```json
119
+ {
120
+ "$schema": "https://www.schemastore.org/claude-code-keybindings.json",
121
+ "bindings": [
122
+ {
123
+ "context": "Chat",
124
+ "bindings": {
125
+ "ctrl+s": "chat:stash",
126
+ "ctrl+e": "chat:externalEditor",
127
+ "ctrl+u": null
128
+ }
129
+ },
130
+ {
131
+ "context": "Global",
132
+ "bindings": {
133
+ "ctrl+k ctrl+t": "app:toggleTodos"
134
+ }
135
+ }
136
+ ]
137
+ }
138
+ ```
139
+
140
+ **常用 Actions**:
141
+
142
+ | Context | Action | 預設 | 說明 |
143
+ |---------|--------|------|------|
144
+ | Chat | `chat:stash` | Ctrl+S | 暫存 prompt,問其他問題後取回 |
145
+ | Chat | `chat:externalEditor` | Ctrl+G | 在文字編輯器編輯 prompt |
146
+ | Chat | `chat:cycleMode` | Shift+Tab | 切換 permission modes |
147
+ | Chat | `chat:submit` | Enter | 送出訊息 |
148
+ | Global | `app:toggleTodos` | Ctrl+T | 切換 task list |
149
+ | Global | `app:toggleTranscript` | Ctrl+O | 切換 verbose transcript |
150
+
151
+ **Voice Mode**(語音輸入,push-to-talk):
152
+ ```json
153
+ { "voice:pushToTalk": "meta+k" } // 自訂 keybinding
154
+ ```
155
+ 預設:Space bar 按住說話;支援 20 種語言(中/英/日/韓/俄/波/土 等)
156
+
157
+ **和絃語法**:`ctrl+k ctrl+s`(依序按兩個組合鍵)
158
+ **注意**:`Ctrl+C`/`Ctrl+D` 不可重綁;`Ctrl+B` 與 tmux 衝突(tmux 用戶按兩次)
159
+
160
+ ---
161
+