From 2d69019342e8036c54fec56573c496964d847e75 Mon Sep 17 00:00:00 2001 From: Haoran Date: Fri, 31 Jul 2026 03:15:58 +0800 Subject: [PATCH] feat: consolidate course into 21 lessons --- README-ja.md | 86 +- README-zh.md | 86 +- README.md | 85 +- s01_agent_loop/README.ja.md | 62 +- s01_agent_loop/README.md | 62 +- s01_agent_loop/README.zh.md | 62 +- s01_agent_loop/code.py | 4 +- s02_tool_use/README.ja.md | 68 +- s02_tool_use/README.md | 68 +- s02_tool_use/README.zh.md | 68 +- .../images/concurrency-comparison.en.svg | 108 -- .../images/concurrency-comparison.ja.svg | 108 -- .../images/concurrency-comparison.svg | 108 -- s03_permission/README.ja.md | 79 +- s03_permission/README.md | 79 +- s03_permission/README.zh.md | 79 +- s04_hooks/README.ja.md | 69 +- s04_hooks/README.md | 69 +- s04_hooks/README.zh.md | 69 +- s04_hooks/code.py | 2 +- s04_hooks/images/hooks-overview.en.svg | 2 +- s04_hooks/images/hooks-overview.ja.svg | 2 +- s04_hooks/images/hooks-overview.svg | 2 +- s05_todo_write/README.ja.md | 26 +- s05_todo_write/README.md | 26 +- s05_todo_write/README.zh.md | 26 +- s06_subagent/README.ja.md | 56 +- s06_subagent/README.md | 56 +- s06_subagent/README.zh.md | 56 +- s07_skill_loading/README.ja.md | 41 +- s07_skill_loading/README.md | 41 +- s07_skill_loading/README.zh.md | 41 +- s08_context_compact/README.ja.md | 88 +- s08_context_compact/README.md | 88 +- s08_context_compact/README.zh.md | 88 +- .../images/compaction-layers.en.svg | 2 +- .../images/compaction-layers.ja.svg | 2 +- .../images/compaction-layers.svg | 2 +- .../images/micro-compact.en.svg | 10 +- .../images/micro-compact.ja.svg | 10 +- s08_context_compact/images/micro-compact.svg | 10 +- s09_memory/README.ja.md | 89 +- s09_memory/README.md | 89 +- s09_memory/README.zh.md | 89 +- s10_system_prompt/README.ja.md | 6 +- s10_system_prompt/README.md | 6 +- s10_system_prompt/README.zh.md | 6 +- s10_system_prompt/code.py | 4 +- s11_error_recovery/README.ja.md | 85 +- s11_error_recovery/README.md | 85 +- s11_error_recovery/README.zh.md | 85 +- s11_error_recovery/code.py | 5 +- s12_task_system/README.ja.md | 65 +- s12_task_system/README.md | 65 +- s12_task_system/README.zh.md | 65 +- s12_task_system/code.py | 6 +- .../images/task-system-overview.en.svg | 2 +- .../images/task-system-overview.ja.svg | 2 +- .../images/task-system-overview.svg | 2 +- s13_background_tasks/README.ja.md | 53 +- s13_background_tasks/README.md | 53 +- s13_background_tasks/README.zh.md | 53 +- s13_background_tasks/code.py | 5 +- s14_cron_scheduler/README.ja.md | 54 +- s14_cron_scheduler/README.md | 54 +- s14_cron_scheduler/README.zh.md | 54 +- s14_cron_scheduler/code.py | 4 +- s15_agent_teams/README.ja.md | 403 ++-- s15_agent_teams/README.md | 401 ++-- s15_agent_teams/README.zh.md | 394 ++-- s15_agent_teams/code.py | 531 ++++-- .../images/agent-teams-overview.en.svg | 18 +- .../images/agent-teams-overview.ja.svg | 18 +- .../images/agent-teams-overview.svg | 19 +- .../images}/team-protocols-overview.en.svg | 8 +- .../images}/team-protocols-overview.ja.svg | 8 +- .../images/team-protocols-overview.svg | 8 +- s15_agent_teams/images/team-topology.en.svg | 2 +- s15_agent_teams/images/team-topology.ja.svg | 2 +- s15_agent_teams/images/team-topology.svg | 2 +- s16_autonomous_agents/README.ja.md | 204 +++ s16_autonomous_agents/README.md | 204 +++ s16_autonomous_agents/README.zh.md | 207 +++ s16_autonomous_agents/code.py | 1371 ++++++++++++++ .../images/autonomous-agents-overview.en.svg | 40 +- .../images}/autonomous-agents-overview.ja.svg | 38 +- .../images}/autonomous-agents-overview.svg | 40 +- s16_team_protocols/README.ja.md | 243 --- s16_team_protocols/README.md | 243 --- s16_team_protocols/README.zh.md | 245 --- s16_team_protocols/code.py | 882 --------- s17_autonomous_agents/README.ja.md | 273 --- s17_autonomous_agents/README.md | 273 --- s17_autonomous_agents/README.zh.md | 273 --- s17_autonomous_agents/code.py | 813 --------- .../README.ja.md | 64 +- .../README.md | 64 +- .../README.zh.md | 64 +- .../code.py | 602 +++--- .../images}/worktree-overview.en.svg | 18 +- .../images}/worktree-overview.ja.svg | 14 +- .../images/worktree-overview.svg | 18 +- s18_mcp_plugin/README.ja.md | 182 ++ s18_mcp_plugin/README.md | 182 ++ s18_mcp_plugin/README.zh.md | 182 ++ {s19_mcp_plugin => s18_mcp_plugin}/code.py | 602 ++++-- .../images/mcp-architecture.en.svg | 16 +- .../images/mcp-architecture.ja.svg | 12 +- .../images}/mcp-architecture.svg | 16 +- .../README.ja.md | 62 +- .../README.md | 64 +- .../README.zh.md | 62 +- .../code.py | 623 ++++--- .../images/system-architecture.en.svg | 10 +- .../images}/system-architecture.ja.svg | 10 +- .../images}/system-architecture.svg | 10 +- s19_mcp_plugin/README.ja.md | 282 --- s19_mcp_plugin/README.md | 282 --- s19_mcp_plugin/README.zh.md | 282 --- .../README.ja.md | 24 +- .../README.md | 24 +- .../README.zh.md | 24 +- .../code.py | 31 +- .../images/workflow-runtime-overview.svg | 0 {s22_goal_loop => s21_goal_loop}/README.ja.md | 22 +- {s22_goal_loop => s21_goal_loop}/README.md | 22 +- {s22_goal_loop => s21_goal_loop}/README.zh.md | 22 +- {s22_goal_loop => s21_goal_loop}/code.py | 11 +- .../images/goal-loop-overview.svg | 0 tests/test_agent_teams_runtime.py | 308 ++++ tests/test_chapter_readmes.py | 2 +- tests/test_compaction_tool_pairs.py | 6 +- tests/test_todo_write_string_input.py | 2 +- tests/test_workflow_goal_lessons.py | 12 +- .../concurrency-comparison.en.svg | 108 -- .../concurrency-comparison.ja.svg | 108 -- .../s02_tool_use/concurrency-comparison.svg | 108 -- .../s04_hooks/hooks-overview.en.svg | 2 +- .../s04_hooks/hooks-overview.ja.svg | 2 +- .../s04_hooks/hooks-overview.svg | 2 +- .../compaction-layers.en.svg | 2 +- .../compaction-layers.ja.svg | 2 +- .../s08_context_compact/compaction-layers.svg | 2 +- .../s08_context_compact/micro-compact.en.svg | 10 +- .../s08_context_compact/micro-compact.ja.svg | 10 +- .../s08_context_compact/micro-compact.svg | 10 +- .../task-system-overview.en.svg | 2 +- .../task-system-overview.ja.svg | 2 +- .../s12_task_system/task-system-overview.svg | 2 +- .../agent-teams-overview.en.svg | 18 +- .../agent-teams-overview.ja.svg | 18 +- .../s15_agent_teams/agent-teams-overview.svg | 19 +- .../team-protocols-overview.en.svg | 8 +- .../team-protocols-overview.ja.svg | 8 +- .../team-protocols-overview.svg | 8 +- .../s15_agent_teams/team-topology.en.svg | 2 +- .../s15_agent_teams/team-topology.ja.svg | 2 +- .../s15_agent_teams/team-topology.svg | 2 +- .../autonomous-agents-overview.en.svg | 40 +- .../autonomous-agents-overview.ja.svg | 38 +- .../autonomous-agents-overview.svg | 40 +- .../worktree-overview.en.svg | 18 +- .../worktree-overview.ja.svg | 14 +- .../worktree-overview.svg | 18 +- .../mcp-architecture.en.svg | 16 +- .../mcp-architecture.ja.svg | 12 +- .../s18_mcp_plugin}/mcp-architecture.svg | 16 +- .../system-architecture.en.svg | 10 +- .../system-architecture.ja.svg | 10 +- .../system-architecture.svg | 10 +- .../workflow-runtime-overview.svg | 0 .../goal-loop-overview.svg | 0 .../architecture/design-decisions.tsx | 2 - .../simulator/agent-loop-simulator.tsx | 1 - web/src/components/visualizations/index.tsx | 11 +- web/src/data/annotations/s06.json | 2 +- web/src/data/annotations/s13.json | 2 +- web/src/data/annotations/s15.json | 62 +- web/src/data/annotations/s16.json | 48 +- web/src/data/annotations/s17.json | 48 +- web/src/data/annotations/s18.json | 48 +- web/src/data/annotations/s19.json | 48 +- web/src/data/annotations/s20.json | 48 +- web/src/data/annotations/s21.json | 48 +- web/src/data/annotations/s22.json | 47 - web/src/data/execution-flows.ts | 91 +- web/src/data/generated/docs.json | 186 +- web/src/data/generated/versions.json | 1615 +++++++++-------- web/src/data/scenarios/s15.json | 53 +- web/src/data/scenarios/s16.json | 55 +- web/src/data/scenarios/s17.json | 49 +- web/src/data/scenarios/s18.json | 45 +- web/src/data/scenarios/s19.json | 75 +- web/src/data/scenarios/s20.json | 68 +- web/src/data/scenarios/s21.json | 48 +- web/src/data/scenarios/s22.json | 37 - web/src/i18n/messages/en.json | 34 +- web/src/i18n/messages/ja.json | 34 +- web/src/i18n/messages/zh.json | 34 +- web/src/lib/constants.ts | 51 +- 200 files changed, 7338 insertions(+), 10829 deletions(-) delete mode 100644 s02_tool_use/images/concurrency-comparison.en.svg delete mode 100644 s02_tool_use/images/concurrency-comparison.ja.svg delete mode 100644 s02_tool_use/images/concurrency-comparison.svg rename {web/public/course-assets/s16_team_protocols => s15_agent_teams/images}/team-protocols-overview.en.svg (97%) rename {web/public/course-assets/s16_team_protocols => s15_agent_teams/images}/team-protocols-overview.ja.svg (97%) rename {s16_team_protocols => s15_agent_teams}/images/team-protocols-overview.svg (97%) create mode 100644 s16_autonomous_agents/README.ja.md create mode 100644 s16_autonomous_agents/README.md create mode 100644 s16_autonomous_agents/README.zh.md create mode 100644 s16_autonomous_agents/code.py rename {s17_autonomous_agents => s16_autonomous_agents}/images/autonomous-agents-overview.en.svg (79%) rename {web/public/course-assets/s17_autonomous_agents => s16_autonomous_agents/images}/autonomous-agents-overview.ja.svg (77%) rename {web/public/course-assets/s17_autonomous_agents => s16_autonomous_agents/images}/autonomous-agents-overview.svg (79%) delete mode 100644 s16_team_protocols/README.ja.md delete mode 100644 s16_team_protocols/README.md delete mode 100644 s16_team_protocols/README.zh.md delete mode 100644 s16_team_protocols/code.py delete mode 100644 s17_autonomous_agents/README.ja.md delete mode 100644 s17_autonomous_agents/README.md delete mode 100644 s17_autonomous_agents/README.zh.md delete mode 100644 s17_autonomous_agents/code.py rename {s18_worktree_isolation => s17_worktree_isolation}/README.ja.md (59%) rename {s18_worktree_isolation => s17_worktree_isolation}/README.md (58%) rename {s18_worktree_isolation => s17_worktree_isolation}/README.zh.md (59%) rename {s18_worktree_isolation => s17_worktree_isolation}/code.py (65%) rename {web/public/course-assets/s18_worktree_isolation => s17_worktree_isolation/images}/worktree-overview.en.svg (91%) rename {web/public/course-assets/s18_worktree_isolation => s17_worktree_isolation/images}/worktree-overview.ja.svg (92%) rename {s18_worktree_isolation => s17_worktree_isolation}/images/worktree-overview.svg (91%) create mode 100644 s18_mcp_plugin/README.ja.md create mode 100644 s18_mcp_plugin/README.md create mode 100644 s18_mcp_plugin/README.zh.md rename {s19_mcp_plugin => s18_mcp_plugin}/code.py (65%) rename {s19_mcp_plugin => s18_mcp_plugin}/images/mcp-architecture.en.svg (94%) rename {s19_mcp_plugin => s18_mcp_plugin}/images/mcp-architecture.ja.svg (96%) rename {web/public/course-assets/s19_mcp_plugin => s18_mcp_plugin/images}/mcp-architecture.svg (94%) rename {s20_comprehensive => s19_comprehensive}/README.ja.md (74%) rename {s20_comprehensive => s19_comprehensive}/README.md (72%) rename {s20_comprehensive => s19_comprehensive}/README.zh.md (72%) rename {s20_comprehensive => s19_comprehensive}/code.py (81%) rename {s20_comprehensive => s19_comprehensive}/images/system-architecture.en.svg (96%) rename {web/public/course-assets/s20_comprehensive => s19_comprehensive/images}/system-architecture.ja.svg (96%) rename {web/public/course-assets/s20_comprehensive => s19_comprehensive/images}/system-architecture.svg (96%) delete mode 100644 s19_mcp_plugin/README.ja.md delete mode 100644 s19_mcp_plugin/README.md delete mode 100644 s19_mcp_plugin/README.zh.md rename {s21_workflow_runtime => s20_workflow_runtime}/README.ja.md (90%) rename {s21_workflow_runtime => s20_workflow_runtime}/README.md (90%) rename {s21_workflow_runtime => s20_workflow_runtime}/README.zh.md (89%) rename {s21_workflow_runtime => s20_workflow_runtime}/code.py (94%) rename {s21_workflow_runtime => s20_workflow_runtime}/images/workflow-runtime-overview.svg (100%) rename {s22_goal_loop => s21_goal_loop}/README.ja.md (91%) rename {s22_goal_loop => s21_goal_loop}/README.md (90%) rename {s22_goal_loop => s21_goal_loop}/README.zh.md (91%) rename {s22_goal_loop => s21_goal_loop}/code.py (96%) rename {s22_goal_loop => s21_goal_loop}/images/goal-loop-overview.svg (100%) create mode 100644 tests/test_agent_teams_runtime.py delete mode 100644 web/public/course-assets/s02_tool_use/concurrency-comparison.en.svg delete mode 100644 web/public/course-assets/s02_tool_use/concurrency-comparison.ja.svg delete mode 100644 web/public/course-assets/s02_tool_use/concurrency-comparison.svg rename {s16_team_protocols/images => web/public/course-assets/s15_agent_teams}/team-protocols-overview.en.svg (97%) rename {s16_team_protocols/images => web/public/course-assets/s15_agent_teams}/team-protocols-overview.ja.svg (97%) rename web/public/course-assets/{s16_team_protocols => s15_agent_teams}/team-protocols-overview.svg (97%) rename web/public/course-assets/{s17_autonomous_agents => s16_autonomous_agents}/autonomous-agents-overview.en.svg (79%) rename {s17_autonomous_agents/images => web/public/course-assets/s16_autonomous_agents}/autonomous-agents-overview.ja.svg (77%) rename {s17_autonomous_agents/images => web/public/course-assets/s16_autonomous_agents}/autonomous-agents-overview.svg (79%) rename {s18_worktree_isolation/images => web/public/course-assets/s17_worktree_isolation}/worktree-overview.en.svg (91%) rename {s18_worktree_isolation/images => web/public/course-assets/s17_worktree_isolation}/worktree-overview.ja.svg (92%) rename web/public/course-assets/{s18_worktree_isolation => s17_worktree_isolation}/worktree-overview.svg (91%) rename web/public/course-assets/{s19_mcp_plugin => s18_mcp_plugin}/mcp-architecture.en.svg (94%) rename web/public/course-assets/{s19_mcp_plugin => s18_mcp_plugin}/mcp-architecture.ja.svg (96%) rename {s19_mcp_plugin/images => web/public/course-assets/s18_mcp_plugin}/mcp-architecture.svg (94%) rename web/public/course-assets/{s20_comprehensive => s19_comprehensive}/system-architecture.en.svg (96%) rename {s20_comprehensive/images => web/public/course-assets/s19_comprehensive}/system-architecture.ja.svg (96%) rename {s20_comprehensive/images => web/public/course-assets/s19_comprehensive}/system-architecture.svg (96%) rename web/public/course-assets/{s21_workflow_runtime => s20_workflow_runtime}/workflow-runtime-overview.svg (100%) rename web/public/course-assets/{s22_goal_loop => s21_goal_loop}/goal-loop-overview.svg (100%) delete mode 100644 web/src/data/annotations/s22.json delete mode 100644 web/src/data/scenarios/s22.json diff --git a/README-ja.md b/README-ja.md index 49a2e7d0..3cea3f27 100644 --- a/README-ja.md +++ b/README-ja.md @@ -106,7 +106,7 @@ Claude Code = 一つの agent loop これがすべてだ。これが全アーキテクチャ。すべてのコンポーネントは Harness メカニズム -- Agent が住む世界の一部。Agent そのものは? Claude だ。モデル。Anthropic が人類の推論とコードの全幅で訓練した。Harness が Claude を賢くしたのではない。Claude は元々賢い。Harness が Claude に手と目とワークスペースを与えた。 -これが Claude Code が理想的な教材である理由だ:**モデルを信頼し、工学的努力を Harness に集中させるとどうなるかを示している。** このリポジトリの各セッション(s01-s22)は Claude Code アーキテクチャの Harness メカニズムを段階的に分解し、最後に組み直す。終了時には、Claude Code の仕組みだけでなく、あらゆるドメインのあらゆる Agent に適用される Harness 工学の普遍的原則を理解している。 +これが Claude Code を教材として扱う理由だ:**モデルを信頼し、工学的努力を Harness に集中させるとどうなるかを示している。** このリポジトリの各セッション(s01-s21)は Harness メカニズムを段階的に分解し、最後に組み直す。終了時には、一つの coding agent の仕組みだけでなく、さまざまな領域に適用できる Harness 工学の原則を理解できる。 教訓は「Claude Code をコピーせよ」ではない。教訓は:**最高の Agent プロダクトは、自分の仕事が Harness であって Intelligence ではないと理解しているエンジニアが作る。** @@ -159,7 +159,7 @@ Claude Code = 一つの agent loop Agent を特定ドメインで効果的にする Harness -- の作り方を教える。 ``` -**22 の段階的セッション、シンプルなループから目標を閉じる Harness まで。** +**21 の段階的セッション、シンプルなループから目標を閉じる Harness まで。** **各セッションは 1 つの Harness メカニズムを追加する。各メカニズムには 1 つのモットーがある。** > **s01**   *"One loop & Bash is all you need"* — 1つのツール + 1つのループ = エージェント @@ -190,21 +190,19 @@ Claude Code = 一つの agent loop > > **s14**   *"スケジュールで発火、人間の起動は不要"* — 時間になったら自動でタスクを動かす > -> **s15**   *"一人で終わらないなら、チームメイトに任せる"* — Agent Teams ランタイム実験:永続チームメイト + 非同期メールボックス +> **s15**   *"一人で扱いきれないなら、チームメイトで分担する"* — 永続チームメイト、自動メッセージ配信、型付き協調プロトコル > -> **s16**   *"チームメイト間には統一の通信ルールが必要"* — Agent Teams プロトコル実験:型付きリクエスト-返信 +> **s16**   *"待機中のチームメイトがボードを見て仕事を取る"* — 実行可能なタスクを発見し、原子的に認領する > -> **s17**   *"チームメイトが自らボードを見て、仕事を取る"* — リーダーが逐一割り振る必要はない +> **s17**   *"各自のディレクトリで作業し、互いに干渉しない"* — タスクは目標を管理、worktree はディレクトリを管理、IDで紐付け > -> **s18**   *"各自のディレクトリで作業し、互いに干渉しない"* — タスクは目標を管理、worktree はディレクトリを管理、IDで紐付け +> **s18**   *"能力不足? MCP でプラグイン"* — 外部ツールを同じツールプールに接続する > -> **s19**   *"能力不足? MCP でプラグイン"* — 外部ツールを同じツールプールに接続する +> **s19**   *"仕組みは多く、ループは一つ"* — すべての仕組みを 1 つの Harness に戻す > -> **s20**   *"仕組みは多く、ループは一つ"* — すべての仕組みを 1 つの Harness に戻す +> **s20**   *"編成の形が固定なら、コードにする"* — 再開可能なジャーナルを持つ決定的 Workflow > -> **s21**   *"編成の形が固定なら、コードにする"* — 再開可能なジャーナルを持つ決定的 Workflow -> -> **s22**   *"本当に終われる時を目標が決める"* — 信頼できる証拠が目標を満たすまで継続する +> **s21**   *"本当に終われる時を目標が決める"* — 信頼できる証拠が目標を満たすまで継続する --- @@ -241,16 +239,16 @@ def agent_loop(messages): このリポジトリには現在、2 つのチュートリアルトラックが共存している: -- **現行トラック:ルート直下の `s01-s22`** - ルート直下の `s01_*` から `s22_*` までが新しい正規版であり、現在推奨する読書経路。各セッションには既定の英語 README、中国語/日本語訳、実行可能な `code.py`、必要に応じた図が含まれる。 +- **現行トラック:ルート直下の `s01-s21`** + ルート直下の `s01_*` から `s21_*` までが新しい正規版であり、現在推奨する読書経路。各セッションには既定の英語 README、中国語/日本語訳、実行可能な `code.py`、必要に応じた図が含まれる。 - **旧版移行トラック:`docs/`、`agents/`** これらは旧 12 セッション版を保持している。既存読者と旧リンクのために移行期間中は一時的に残している。 -新しく読む場合は、ルート直下の `s01_agent_loop/` から `s22_goal_loop/` までを読む。旧版と現行版のセッション番号は常に一致しないため、番号を混同しないこと。 +新しく読む場合は、ルート直下の `s01_agent_loop/` から `s21_goal_loop/` までを読む。旧版と現行版のセッション番号は常に一致しないため、番号を混同しないこと。 ### 旧版から現行版への対応 -| 旧 12 セッション版 | 現行 22 セッション版 | トピック | +| 旧 12 セッション版 | 現行 21 セッション版 | トピック | |---|---|---| | 旧 s01 | 現行 s01 | Agent Loop | | 旧 s02 | 現行 s02 | Tool Use | @@ -261,27 +259,18 @@ def agent_loop(messages): | 旧 s07 | 現行 s12 | Task System | | 旧 s08 | 現行 s13 | Background Tasks | | 旧 s09 | 現行 s15 | Agent Teams | -| 旧 s10 | 現行 s16 | Team Protocols | -| 旧 s11 | 現行 s17 | Autonomous Agents | -| 旧 s12 | 現行 s18 | Worktree Isolation | -| 現行版のみ | s03、s04、s09、s10、s11、s14、s19、s20、s21、s22 | Permission、Hooks、Memory、Context Assembly、Error Recovery、Cron、MCP、Comprehensive Agent、Workflow Runtime、Goal Loop | +| 旧 s10 | 現行 s15 | Team Protocols | +| 旧 s11 | 現行 s16 | Autonomous Agents | +| 旧 s12 | 現行 s17 | Worktree Isolation | +| 現行版のみ | s03、s04、s09、s10、s11、s14、s18、s19、s20、s21 | Permission、Hooks、Memory、Context Assembly、Error Recovery、Cron、MCP、Comprehensive Agent、Workflow Runtime、Goal Loop | -## スコープ (重要) +## コースの範囲 -このリポジトリは Harness 工学の 0->1 学習プロジェクト -- Agent モデルを囲む環境の構築を学ぶ。 -学習を優先するため、以下の本番メカニズムは意図的に簡略化または省略している: - -- 完全なイベント / Hook バス (例: PreToolUse, SessionStart/End, ConfigChange)。 - s12 では教材用に最小の追記型ライフサイクルイベントのみ実装。 -- ルールベースの権限ガバナンスと信頼フロー -- セッションライフサイクル制御 (resume/fork) と高度な worktree ライフサイクル制御 -- MCP ランタイムの詳細 (transport/OAuth/リソース購読/ポーリング) - -このリポジトリの JSONL メールボックス方式は教材用の実装であり、特定の本番内部実装を主張するものではない。 +これは Harness 工学を 0 から組み立てるコースである。各セッションで一つの仕組みを分けて扱い、s19 で一つの Agent loop に戻す。チームランタイムは JSONL メールボックスを使い、その後のセッションで Workflow 編成と目標による継続ループを追加する。 ## クイックスタート -### 現行 22 セッション版 +### 現行 21 セッション版 ```sh git clone https://github.com/shareAI-lab/learn-claude-code @@ -291,7 +280,7 @@ cp .env.example .env # .env を編集して ANTHROPIC_API_KEY を入力 python s01_agent_loop/code.py # ここから開始 — 1ループ + bash python s08_context_compact/code.py # コンテキスト圧縮(複雑章) -python s22_goal_loop/code.py # 終点: 目標でループを閉じる +python s21_goal_loop/code.py # 終点: 目標でループを閉じる ``` ### 旧 12 セッション移行版 @@ -304,7 +293,7 @@ python agents/s_full.py ### Web プラットフォーム -Web プラットフォームはルート直下のコースから内容を生成する。s21 と s22 は読解、ソース、シミュレーター、アーキテクチャの各 view を提供し、専用 hero visualization だけを最小限に保つ。 +Web プラットフォームはルート直下のコースから内容を生成する。s20 と s21 は読解、ソース、シミュレーター、アーキテクチャの各 view を提供し、専用 hero visualization だけを最小限に保つ。 ```sh cd web && npm install && npm run dev # http://localhost:3000 @@ -344,9 +333,9 @@ flowchart TD direction LR S4["第4段階:長く動くタスク
━━━━━━━━━━━━━
s12 Task System
└─ タスクと依存関係を保存

s13 Background Tasks
└─ 遅い作業をバックグラウンドへ

s14 Cron Scheduler
└─ 時間で自動実行"]:::stage4 - S5["第5段階:複数 Agent の協作
━━━━━━━━━━━━━
Agent Teams モジュール
├─ s15 ランタイム実験:チームメイト + メールボックス
└─ s16 プロトコル実験:型付きリクエスト-返信

s17 Autonomous Agents
└─ ボードを見て仕事を取る

s18 Worktree Isolation
└─ 別ディレクトリで作業"]:::stage5 + S5["第5段階:複数 Agent の協作
━━━━━━━━━━━━━
s15 Agent Teams
└─ チームメイト + 配信 + プロトコル

s16 Autonomous Agents
└─ 実行可能な仕事をボードから認領

s17 Worktree Isolation
└─ 別ディレクトリで作業"]:::stage5 - S6["第6段階:外部能力と統合
━━━━━━━━━━━━━
s07 Skill Loading
└─ スキルを必要時に展開

s19 MCP Plugin
└─ 外部ツールを同じプールへ

s20 Comprehensive Agent
└─ すべてを1つのループへ"]:::stage6 + S6["第6段階:外部能力と統合
━━━━━━━━━━━━━
s07 Skill Loading
└─ スキルを必要時に展開

s18 MCP Plugin
└─ 外部ツールを同じプールへ

s19 Comprehensive Agent
└─ すべてを1つのループへ"]:::stage6 S4 ==> S5 ==> S6 end @@ -354,7 +343,7 @@ flowchart TD %% 第3層:編成と目標の完了 subgraph Phase3 ["第7段階:編成と目標の完了"] direction LR - S7["第7段階:編成して完了する
━━━━━━━━━━━━━
s21 Workflow Runtime
└─ 固定編成はスクリプトが担う

s22 Goal Loop
└─ 信頼できる証拠で停止を決める"]:::stage1 + S7["第7段階:編成して完了する
━━━━━━━━━━━━━
s20 Workflow Runtime
└─ 固定編成はスクリプトが担う

s21 Goal Loop
└─ 信頼できる証拠で停止を決める"]:::stage1 S6 ==> S7 end @@ -382,14 +371,13 @@ flowchart TD | [s12](./s12_task_system/) | Task System | `TaskRecord` / `blockedBy` / ディスク永続化 | | [s13](./s13_background_tasks/) | Background Tasks | スレッド実行 / 通知キュー | | [s14](./s14_cron_scheduler/) | Cron Scheduler | 永続スケジューリング / セッション限定トリガー | -| [s15](./s15_agent_teams/) | Agent Teams:ランタイム実験 | `MessageBus` / 受信箱 / 権限バブリング | -| [s16](./s16_team_protocols/) | Agent Teams:プロトコル実験 | 型付きメッセージ / シャットダウンハンドシェイク / プラン承認 | -| [s17](./s17_autonomous_agents/) | Autonomous Agents | アイドルサイクル / 自動クレーム | -| [s18](./s18_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / タスク-ディレクトリ紐付け | -| [s19](./s19_mcp_plugin/) | MCP Plugin | マルチトランスポート / チャネルルーティング / ツールプール組み立て | -| [s20](./s20_comprehensive/) | Comprehensive Agent | すべての仕組みを 1 つのループへ | -| [s21](./s21_workflow_runtime/) | Workflow Runtime | スクリプト編成 / バックグラウンド実行 / ジャーナル再開 | -| [s22](./s22_goal_loop/) | Goal Loop | 目標ゲート / 信頼できる証拠 / 自動継続 | +| [s15](./s15_agent_teams/) | Agent Teams | 永続チームメイト / 自動配信 / 型付きプロトコル / プランゲート | +| [s16](./s16_autonomous_agents/) | Autonomous Agents | タスクボード走査 / 原子的認領 / 自己組織化 | +| [s17](./s17_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / タスク-ディレクトリ紐付け | +| [s18](./s18_mcp_plugin/) | MCP Plugin | ツール発見 / 名前空間 / ツールプール組み立て | +| [s19](./s19_comprehensive/) | Comprehensive Agent | すべての仕組みを 1 つのループへ | +| [s20](./s20_workflow_runtime/) | Workflow Runtime | スクリプト編成 / バックグラウンド実行 / ジャーナル再開 | +| [s21](./s21_goal_loop/) | Goal Loop | 目標ゲート / 信頼できる証拠 / 自動継続 | ## プロジェクト構成 @@ -403,10 +391,10 @@ learn-claude-code/ images/ # SVG ダイアグラム s02_tool_use/ ... - s19_mcp_plugin/ - s20_comprehensive/ - s21_workflow_runtime/ - s22_goal_loop/ # 終点セッション + s18_mcp_plugin/ + s19_comprehensive/ + s20_workflow_runtime/ + s21_goal_loop/ # 終点セッション agents/ # 旧 12 セッションの実行可能コピー + s_full.py skills/ # s07 で使用するスキルファイル docs/ # 旧 12 セッション文書、移行期間中は保持 @@ -416,7 +404,7 @@ learn-claude-code/ ## 次のステップ -- 理解から出荷へ -22 セッションを終えれば、Harness 工学の内部構造を完全に理解している。その知識を活かす 2 つの方法: +21 セッションを終えれば、Harness 工学の内部構造を理解できる。その知識を活かす 2 つの方法: ### Kode Agent CLI -- オープンソース Coding Agent CLI diff --git a/README-zh.md b/README-zh.md index bd2eb301..c29857c1 100644 --- a/README-zh.md +++ b/README-zh.md @@ -106,7 +106,7 @@ Claude Code = 一个 agent loop 就这些。这就是全部架构。每一个组件都是 harness 机制 -- 为 agent 构建的栖居世界的一部分。Agent 本身呢?是 Claude。一个模型。由 Anthropic 在人类推理和代码的全部广度上训练而成。Harness 没有让 Claude 变聪明。Claude 本来就聪明。Harness 给了 Claude 双手、双眼和一个工作空间。 -这就是 Claude Code 作为教学标本的意义:**它展示了当你信任模型、把工程精力集中在 harness 上时会发生什么。** 本仓库的课程(s01-s22)逐步拆解并重组 Claude Code 架构中的 harness 机制。学完之后,你理解的不只是 Claude Code 怎么工作,而是适用于任何领域、任何 agent 的 harness 工程通用原则。 +这就是 Claude Code 作为教学标本的意义:**它展示了当你信任模型、把工程精力集中在 harness 上时会发生什么。** 本仓库的课程(s01-s21)逐步拆解并重组 harness 机制。学完之后,你理解的不只是一个 coding agent 怎么工作,而是适用于不同领域的 harness 工程原则。 启示不是 "复制 Claude Code"。启示是:**最好的 agent 产品,出自那些明白自己的工作是 harness 而非 intelligence 的工程师之手。** @@ -159,7 +159,7 @@ Claude Code = 一个 agent loop 让 agent 在特定领域高效工作的 harness。 ``` -**22 个递进式课程, 从简单循环到目标闭环。** +**21 个递进式课程, 从简单循环到目标闭环。** **每个课程添加一个 harness 机制。每个机制有一句格言。** > **s01**   *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent @@ -190,21 +190,19 @@ Claude Code = 一个 agent loop > > **s14**   *"定时触发, 不需要人推"* — 按时间自动触发任务 > -> **s15**   *"一个搞不定, 组队来"* — Agent Teams 运行时实验:持久化队友 + 异步邮箱 +> **s15**   *"一个 Agent 顾不过来,就让队友分工协作"* — 持久队友、自动消息投递与类型化协作协议 > -> **s16**   *"队友之间要有约定"* — Agent Teams 协议实验:带类型的请求-回复 +> **s16**   *"队友空闲时自己看板,有活就认领"* — 发现就绪任务并原子认领,不需要逐个派发 > -> **s17**   *"队友自己看板, 有活就认领"* — 不需要领导逐个分配, 自组织 +> **s17**   *"各干各的目录, 互不干扰"* — 任务管目标, worktree 管目录, 按 ID 绑定 > -> **s18**   *"各干各的目录, 互不干扰"* — 任务管目标, worktree 管目录, 按 ID 绑定 +> **s18**   *"能力不够? 插上 MCP"* — 把外部工具接进同一个工具池 > -> **s19**   *"能力不够? 插上 MCP"* — 把外部工具接进同一个工具池 +> **s19**   *"机制很多,循环一个"* — 前面所有机制回到一个完整 harness > -> **s20**   *"机制很多,循环一个"* — 前面所有机制回到一个完整 harness +> **s20**   *"编排形状固定时,就把它写进代码"* — 可恢复 journal 支撑确定性 workflow > -> **s21**   *"编排形状固定时,就把它写进代码"* — 可恢复 journal 支撑确定性 workflow -> -> **s22**   *"目标决定循环什么时候真正结束"* — 持续工作,直到可信证据满足目标 +> **s21**   *"目标决定循环什么时候真正结束"* — 持续工作,直到可信证据满足目标 --- @@ -241,16 +239,16 @@ def agent_loop(messages): 本仓库现在同时保留两条教程线: -- **新版主线:根目录 `s01-s22`** - 根目录下的 `s01_*` 到 `s22_*` 是新的主版本,也是当前推荐阅读路径。每章包含默认英文 README、中文/日文译本、可运行的 `code.py`,以及必要的图示。 +- **新版主线:根目录 `s01-s21`** + 根目录下的 `s01_*` 到 `s21_*` 是新的主版本,也是当前推荐阅读路径。每章包含默认英文 README、中文/日文译本、可运行的 `code.py`,以及必要的图示。 - **旧版过渡:`docs/`、`agents/`** 这些仍保留旧 12 章体系,暂时用于已有读者和旧链接过渡。 -新读者请从根目录 `s01_agent_loop/` 读到 `s22_goal_loop/`。旧版章节号和新版不完全一致,不要混用章节号。 +新读者请从根目录 `s01_agent_loop/` 读到 `s21_goal_loop/`。旧版章节号和新版不完全一致,不要混用章节号。 ### 旧版到新版的对应关系 -| 旧 12 章版本 | 新 22 章版本 | 主题 | +| 旧 12 章版本 | 新 21 章版本 | 主题 | |---|---|---| | 旧 s01 | 新 s01 | Agent Loop | | 旧 s02 | 新 s02 | Tool Use | @@ -261,27 +259,18 @@ def agent_loop(messages): | 旧 s07 | 新 s12 | Task System | | 旧 s08 | 新 s13 | Background Tasks | | 旧 s09 | 新 s15 | Agent Teams | -| 旧 s10 | 新 s16 | Team Protocols | -| 旧 s11 | 新 s17 | Autonomous Agents | -| 旧 s12 | 新 s18 | Worktree Isolation | -| 新版新增 | s03、s04、s09、s10、s11、s14、s19、s20、s21、s22 | Permission、Hooks、Memory、Context Assembly、Error Recovery、Cron、MCP、Comprehensive Agent、Workflow Runtime、Goal Loop | +| 旧 s10 | 新 s15 | Team Protocols | +| 旧 s11 | 新 s16 | Autonomous Agents | +| 旧 s12 | 新 s17 | Worktree Isolation | +| 新版新增 | s03、s04、s09、s10、s11、s14、s18、s19、s20、s21 | Permission、Hooks、Memory、Context Assembly、Error Recovery、Cron、MCP、Comprehensive Agent、Workflow Runtime、Goal Loop | -## 范围说明 (重要) +## 课程边界 -本仓库是一个 0->1 的 harness 工程学习项目 -- 构建围绕 agent 模型的工作环境。 -为保证学习路径清晰,仓库有意简化或省略了部分生产机制: - -- 完整事件 / Hook 总线 (例如 PreToolUse、SessionStart/End、ConfigChange)。 - s12 仅提供教学用途的最小 append-only 生命周期事件流。 -- 基于规则的权限治理与信任流程 -- 会话生命周期控制 (resume/fork) 与更完整的 worktree 生命周期控制 -- 完整 MCP 运行时细节 (transport/OAuth/资源订阅/轮询) - -仓库中的团队 JSONL 邮箱协议是教学实现,不是对任何特定生产内部实现的声明。 +这是一个从 0 到 1 的 harness 工程课程。每章先单独展开一个机制,s19 再把它们接回完整的 Agent 循环。团队运行时使用 JSONL 邮箱,后续章节继续加入 workflow 编排和由目标控制的持续循环。 ## 快速开始 -### 新版 22 章主线 +### 新版 21 章主线 ```sh git clone https://github.com/shareAI-lab/learn-claude-code @@ -291,7 +280,7 @@ cp .env.example .env # 编辑 .env 填入你的 ANTHROPIC_API_KEY python s01_agent_loop/code.py # 起点 — 一个循环 + bash python s08_context_compact/code.py # 上下文压缩(复杂章) -python s22_goal_loop/code.py # 终点章:用目标闭合循环 +python s21_goal_loop/code.py # 终点章:用目标闭合循环 ``` ### 旧版 12 章过渡线 @@ -304,7 +293,7 @@ python agents/s_full.py ### Web 平台 -Web 平台从根目录课程生成内容。s21、s22 提供阅读、源码、模拟和架构视图;仅专用首屏可视化保持精简。 +Web 平台从根目录课程生成内容。s20、s21 提供阅读、源码、模拟和架构视图;仅专用首屏可视化保持精简。 ```sh cd web && npm install && npm run dev # http://localhost:3000 @@ -344,9 +333,9 @@ flowchart TD direction LR S4["第四阶段:让任务长期运行
━━━━━━━━━━━━━
s12 Task System
└─ 任务落盘记依赖

s13 Background Tasks
└─ 慢操作丢后台

s14 Cron Scheduler
└─ 按时自动触发"]:::stage4 - S5["第五阶段:让多个 Agent 协作
━━━━━━━━━━━━━
Agent Teams 模块
├─ s15 运行时实验:队友 + 邮箱
└─ s16 协议实验:带类型的请求-回复

s17 Autonomous Agents
└─ 自己看板认领活

s18 Worktree Isolation
└─ 隔离目录"]:::stage5 + S5["第五阶段:让多个 Agent 协作
━━━━━━━━━━━━━
s15 Agent Teams
└─ 队友 + 消息投递 + 协作协议

s16 Autonomous Agents
└─ 自己看板认领就绪任务

s17 Worktree Isolation
└─ 隔离目录"]:::stage5 - S6["第六阶段:接外部能力合体
━━━━━━━━━━━━━
s07 Skill Loading
└─ 技能按需展开

s19 MCP Plugin
└─ 外部接进工具池

s20 Comprehensive Agent
└─ 全机制回单循环"]:::stage6 + S6["第六阶段:接外部能力合体
━━━━━━━━━━━━━
s07 Skill Loading
└─ 技能按需展开

s18 MCP Plugin
└─ 外部接进工具池

s19 Comprehensive Agent
└─ 全机制回单循环"]:::stage6 S4 ==> S5 ==> S6 end @@ -354,7 +343,7 @@ flowchart TD %% 第三层:编排与目标闭环 subgraph Phase3 ["🎯 第七阶段:编排与目标闭环"] direction LR - S7["第七阶段:编排并完成
━━━━━━━━━━━━━
s21 Workflow Runtime
└─ 脚本拥有固定编排

s22 Goal Loop
└─ 可信证据决定何时停止"]:::stage1 + S7["第七阶段:编排并完成
━━━━━━━━━━━━━
s20 Workflow Runtime
└─ 脚本拥有固定编排

s21 Goal Loop
└─ 可信证据决定何时停止"]:::stage1 S6 ==> S7 end @@ -383,14 +372,13 @@ flowchart TD | [s12](./s12_task_system/) | Task System | `TaskRecord` / `blockedBy` / 磁盘持久化 | | [s13](./s13_background_tasks/) | Background Tasks | 线程执行 / 通知队列 | | [s14](./s14_cron_scheduler/) | Cron Scheduler | 持久化调度 / 会话级触发 | -| [s15](./s15_agent_teams/) | Agent Teams:运行时实验 | `MessageBus` / 收件箱 / 权限冒泡 | -| [s16](./s16_team_protocols/) | Agent Teams:协议实验 | 类型消息 / 关机握手 / 计划审批 | -| [s17](./s17_autonomous_agents/) | Autonomous Agents | 空闲循环 / 自动认领 | -| [s18](./s18_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / 任务-目录绑定 | -| [s19](./s19_mcp_plugin/) | MCP Plugin | 多传输 / 通道路由 / 工具池组装 | -| [s20](./s20_comprehensive/) | Comprehensive Agent | 全部机制归到一个循环 | -| [s21](./s21_workflow_runtime/) | Workflow Runtime | 脚本编排 / 后台运行 / journal 续跑 | -| [s22](./s22_goal_loop/) | Goal Loop | 目标闸门 / 可信证据 / 自动续轮 | +| [s15](./s15_agent_teams/) | Agent Teams | 持久队友 / 自动消息投递 / 类型协议 / 计划闸门 | +| [s16](./s16_autonomous_agents/) | Autonomous Agents | 扫描任务板 / 原子认领 / 自组织 | +| [s17](./s17_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / 任务-目录绑定 | +| [s18](./s18_mcp_plugin/) | MCP Plugin | 工具发现 / 命名空间 / 工具池组装 | +| [s19](./s19_comprehensive/) | Comprehensive Agent | 全部机制归到一个循环 | +| [s20](./s20_workflow_runtime/) | Workflow Runtime | 脚本编排 / 后台运行 / journal 续跑 | +| [s21](./s21_goal_loop/) | Goal Loop | 目标闸门 / 可信证据 / 自动续轮 | ## 项目结构 @@ -404,10 +392,10 @@ learn-claude-code/ images/ # SVG 流程图 s02_tool_use/ ... - s19_mcp_plugin/ - s20_comprehensive/ - s21_workflow_runtime/ - s22_goal_loop/ # 终点章 + s18_mcp_plugin/ + s19_comprehensive/ + s20_workflow_runtime/ + s21_goal_loop/ # 终点章 agents/ # 旧 12 章可运行副本 + s_full.py skills/ # s07 使用的 skill 文件 docs/ # 旧 12 章文档,过渡期保留 @@ -417,7 +405,7 @@ learn-claude-code/ ## 学完之后 -- 从理解到落地 -22 个课程走完, 你已经从内到外理解了 harness 工程的运作原理。两种方式把知识变成产品: +21 个课程走完, 你已经从内到外理解了 harness 工程的运作原理。两种方式把知识变成产品: ### Kode Agent CLI -- 开源 Coding Agent CLI diff --git a/README.md b/README.md index 68ac8f1e..49da1fa9 100644 --- a/README.md +++ b/README.md @@ -167,16 +167,16 @@ The loop is constant. Tools, knowledge, and permissions change. Agent = Model (L This repository currently contains two tutorial tracks: -- **Current track: root-level `s01-s22`** - The root-level `s01_*` ... `s22_*` folders are the canonical version. Each chapter contains an English default README, Chinese/Japanese translations, runnable `code.py`, and diagrams where needed. +- **Current track: root-level `s01-s21`** + The root-level `s01_*` ... `s21_*` folders are the canonical version. Each chapter contains an English default README, Chinese/Japanese translations, runnable `code.py`, and diagrams where needed. - **Legacy transition track: `docs/` and `agents/`** These preserve the older 12-lesson version for existing readers and old links during migration. -If you are starting now, read the root-level `s01_agent_loop/` through `s22_goal_loop/` chapters. The legacy and current chapter numbers do not always match, so avoid mixing chapter numbers across tracks. +If you are starting now, read the root-level `s01_agent_loop/` through `s21_goal_loop/` chapters. The legacy and current chapter numbers do not always match, so avoid mixing chapter numbers across tracks. ### Legacy-to-Current Mapping -| Legacy 12-lesson track | Current 22-lesson track | Topic | +| Legacy 12-lesson track | Current 21-lesson track | Topic | |---|---|---| | old s01 | new s01 | Agent Loop | | old s02 | new s02 | Tool Use | @@ -187,28 +187,20 @@ If you are starting now, read the root-level `s01_agent_loop/` through `s22_goal | old s07 | new s12 | Task System | | old s08 | new s13 | Background Tasks | | old s09 | new s15 | Agent Teams | -| old s10 | new s16 | Team Protocols | -| old s11 | new s17 | Autonomous Agents | -| old s12 | new s18 | Worktree Isolation | -| new only | s03, s04, s09, s10, s11, s14, s19, s20, s21, s22 | Permission, Hooks, Memory, Context Assembly, Error Recovery, Cron, MCP, Comprehensive Agent, Workflow Runtime, Goal Loop | +| old s10 | new s15 | Team Protocols | +| old s11 | new s16 | Autonomous Agents | +| old s12 | new s17 | Worktree Isolation | +| new only | s03, s04, s09, s10, s11, s14, s18, s19, s20, s21 | Permission, Hooks, Memory, Context Assembly, Error Recovery, Cron, MCP, Comprehensive Agent, Workflow Runtime, Goal Loop | --- -## Scope +## Course Boundary -This repository is a 0-to-1 harness engineering learning project: it teaches how to build the working environment around an agent model. To keep the learning path clear, some production mechanisms are intentionally simplified or omitted: - -- Full event / hook bus behavior, such as `PreToolUse`, `SessionStart/End`, and `ConfigChange`. - The teaching code uses minimal lifecycle events where needed. -- Rule-based permission governance and full trust workflows. -- Session lifecycle controls such as resume/fork, plus more complete worktree lifecycle handling. -- Full MCP runtime details such as transport, OAuth, resource subscription, and polling. - -The JSONL mailbox protocol in this repository is a teaching implementation, not a claim about any specific production internal implementation. +This is a 0-to-1 harness engineering course. Each chapter isolates one mechanism, then s19 reconnects them in a complete agent loop. The team runtime uses a JSONL mailbox, and later chapters add workflow orchestration and a goal-controlled continuation loop. --- -## 22 Progressive Lessons +## 21 Progressive Lessons **Each lesson adds one harness mechanism. Each mechanism has a motto.** @@ -240,21 +232,19 @@ The JSONL mailbox protocol in this repository is a teaching implementation, not > > **s14**   *"Fire on schedule, no human kick needed"* — trigger tasks automatically by time > -> **s15**   *"Too big for one agent -- delegate to teammates"* — Agent Teams runtime lab: persistent teammates + async mailboxes +> **s15**   *"Too big for one agent -- let teammates divide the work"* — persistent teammates, automatic message delivery, and typed coordination protocols > -> **s16**   *"Teammates need shared communication rules"* — Agent Teams protocol lab: typed request-reply coordination +> **s16**   *"Idle teammates check the board and claim ready work"* — task discovery and atomic claiming without one-by-one dispatch > -> **s17**   *"Teammates check the board, claim work themselves"* — no leader assigning one by one; self-organizing +> **s17**   *"Each works in its own directory, no interference"* — tasks own goals, worktrees own directories, bound by ID > -> **s18**   *"Each works in its own directory, no interference"* — tasks own goals, worktrees own directories, bound by ID +> **s18**   *"Not enough capability? Plug in more via MCP"* — connect external tools into the same tool pool > -> **s19**   *"Not enough capability? Plug in more via MCP"* — connect external tools into the same tool pool +> **s19**   *"Many mechanisms, one loop"* — all previous mechanisms return to one complete harness > -> **s20**   *"Many mechanisms, one loop"* — all previous mechanisms return to one complete harness +> **s20**   *"When the orchestration shape is fixed, put it in code"* — deterministic workflows with resumable journals > -> **s21**   *"When the orchestration shape is fixed, put it in code"* — deterministic workflows with resumable journals -> -> **s22**   *"A goal decides when the loop may stop"* — continue until trusted evidence satisfies the goal +> **s21**   *"A goal decides when the loop may stop"* — continue until trusted evidence satisfies the goal --- @@ -292,9 +282,9 @@ flowchart TD direction LR S4["4. Run long tasks
━━━━━━━━━━━━━
s12 Task System
└─ persist tasks and deps

s13 Background Tasks
└─ send slow work background

s14 Cron Scheduler
└─ trigger by time"]:::stage4 - S5["5. Coordinate many Agents
━━━━━━━━━━━━━
Agent Teams module
├─ s15 Runtime Lab: teammates + mailboxes
└─ s16 Protocol Lab: typed request-reply

s17 Autonomous Agents
└─ claim work from the board

s18 Worktree Isolation
└─ separate directories"]:::stage5 + S5["5. Coordinate many Agents
━━━━━━━━━━━━━
s15 Agent Teams
└─ teammates + delivery + protocols

s16 Autonomous Agents
└─ claim ready work from the board

s17 Worktree Isolation
└─ separate directories"]:::stage5 - S6["6. Extend and assemble
━━━━━━━━━━━━━
s07 Skill Loading
└─ expand skills on demand

s19 MCP Plugin
└─ external tools, one pool

s20 Comprehensive Agent
└─ all mechanisms, one loop"]:::stage6 + S6["6. Extend and assemble
━━━━━━━━━━━━━
s07 Skill Loading
└─ expand skills on demand

s18 MCP Plugin
└─ external tools, one pool

s19 Comprehensive Agent
└─ all mechanisms, one loop"]:::stage6 S4 ==> S5 ==> S6 end @@ -302,7 +292,7 @@ flowchart TD %% Layer 3: orchestration and goal closure subgraph Phase3 ["🎯 Stage 7: Orchestration and goal closure"] direction LR - S7["7. Orchestrate and finish
━━━━━━━━━━━━━
s21 Workflow Runtime
└─ scripts own fixed orchestration

s22 Goal Loop
└─ trusted evidence decides when to stop"]:::stage1 + S7["7. Orchestrate and finish
━━━━━━━━━━━━━
s20 Workflow Runtime
└─ scripts own fixed orchestration

s21 Goal Loop
└─ trusted evidence decides when to stop"]:::stage1 S6 ==> S7 end @@ -332,14 +322,13 @@ flowchart TD | [s12](./s12_task_system/) | Task System | `TaskRecord` / `blockedBy` / disk persistence | | [s13](./s13_background_tasks/) | Background Tasks | threaded execution / notification queue | | [s14](./s14_cron_scheduler/) | Cron Scheduler | durable scheduling / session-scoped triggers | -| [s15](./s15_agent_teams/) | Agent Teams: Runtime Lab | `MessageBus` / inbox / permission bubbling | -| [s16](./s16_team_protocols/) | Agent Teams: Protocol Lab | typed messages / shutdown handshake / plan approval | -| [s17](./s17_autonomous_agents/) | Autonomous Agents | idle cycle / auto-claim / self-organization | -| [s18](./s18_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / task-directory binding | -| [s19](./s19_mcp_plugin/) | MCP Plugin | multi-transport / channel routing / tool pool assembly | -| [s20](./s20_comprehensive/) | Comprehensive Agent | all mechanisms around one loop | -| [s21](./s21_workflow_runtime/) | Workflow Runtime | script orchestration / background execution / journal resume | -| [s22](./s22_goal_loop/) | Goal Loop | goal gate / trusted evidence / automatic continuation | +| [s15](./s15_agent_teams/) | Agent Teams | persistent teammates / automatic delivery / typed protocols / plan gate | +| [s16](./s16_autonomous_agents/) | Autonomous Agents | task-board scan / atomic claim / self-organization | +| [s17](./s17_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / task-directory binding | +| [s18](./s18_mcp_plugin/) | MCP Plugin | tool discovery / namespaced tools / tool pool assembly | +| [s19](./s19_comprehensive/) | Comprehensive Agent | all mechanisms around one loop | +| [s20](./s20_workflow_runtime/) | Workflow Runtime | script orchestration / background execution / journal resume | +| [s21](./s21_goal_loop/) | Goal Loop | goal gate / trusted evidence / automatic continuation | --- @@ -358,13 +347,13 @@ s08_context_compact/ Read the `README.md` for the core idea and work through the code. Complex chapters have `
` folds for deep dives -- open them when you want to go deeper. Simple chapters have 0-1 diagrams, complex chapters have more. -Read from s01 through s22 in order. Each chapter assumes you've read the previous ones and ends with a hook into the next. +Read from s01 through s21 in order. Each chapter assumes you've read the previous ones and ends with a hook into the next. --- ## Quick Start -### Current 22-Lesson Track +### Current 21-Lesson Track ```sh git clone https://github.com/shareAI-lab/learn-claude-code @@ -374,7 +363,7 @@ cp .env.example .env # configure ANTHROPIC_API_KEY python s01_agent_loop/code.py # Start here -- one loop + bash python s08_context_compact/code.py # Context compaction (complex) -python s22_goal_loop/code.py # Endpoint: close the loop with a durable goal +python s21_goal_loop/code.py # Endpoint: close the loop with a durable goal ``` ### Legacy 12-Lesson Track @@ -387,7 +376,7 @@ python agents/s_full.py ### Web Platform -The web app extracts the root-level course. Lessons s21 and s22 include reading, source, simulator, and architecture views; only their dedicated hero visualizations remain intentionally minimal. +The web app extracts the root-level course. Lessons s20 and s21 include reading, source, simulator, and architecture views; only their dedicated hero visualizations remain intentionally minimal. ```sh cd web && npm install && npm run dev # http://localhost:3000 @@ -407,10 +396,10 @@ learn-claude-code/ images/ # SVG diagrams s02_tool_use/ ... - s19_mcp_plugin/ - s20_comprehensive/ - s21_workflow_runtime/ - s22_goal_loop/ # endpoint chapter + s18_mcp_plugin/ + s19_comprehensive/ + s20_workflow_runtime/ + s21_goal_loop/ # endpoint chapter agents/ # legacy 12 runnable copies + s_full.py skills/ # skill files used by s07 docs/ # legacy 12-lesson docs, kept during transition @@ -422,7 +411,7 @@ learn-claude-code/ ## What's Next -After 22 lessons, you understand harness engineering from the inside out. Two paths to turn that knowledge into product: +After 21 lessons, you understand harness engineering from the inside out. Two paths to turn that knowledge into product: ### Kode Agent CLI -- Open-Source Coding Agent CLI diff --git a/s01_agent_loop/README.ja.md b/s01_agent_loop/README.ja.md index 22b68c9f..2e24f1ed 100644 --- a/s01_agent_loop/README.ja.md +++ b/s01_agent_loop/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 → s22 +`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 > *"One loop & Bash is all you need"* — ツール一つ + ループ一つ = 一つの Agent。 > > **Harness レイヤー**: ループ — モデルと現実世界をつなぐ最初の架け橋。 @@ -113,7 +113,7 @@ def agent_loop(messages): ## 試してみよう -> **教育デモの注意**: このコードはモデルが生成したシェルコマンドを実行します。プロジェクトファイルへの影響を避けるため、一時テストディレクトリで実行してください。s03 で本格的な権限システムを説明します。 +> **安全上の注意**: このコードはモデルが生成したシェルコマンドを実行します。プロジェクトファイルへの影響を避けるため、一時テストディレクトリで実行してください。s03 で権限制御を追加します。 **準備**(初回のみ): @@ -145,63 +145,5 @@ python s01_agent_loop/code.py → s02 Tool Use:5 つの本格的なツールを与えたらどうなる? モデルは複数のツールを同時に呼び出すか? 並列実行で競合は起きないか? -
-CC ソースコードを深掘り - -> 以下は CC ソースコード `src/query.ts`(1729 行)の検証に基づく。核心的な違いは二つ:CC はループ継続の判断に `stop_reason` フィールドを頼らず、コンテンツに `tool_use` ブロックが含まれるかをチェックする(ストリーミングレスポンスでは `stop_reason` が信頼できないため)。CC には本番環境向けのより多くの終了パスとリカバリ戦略がある。 - -**教育版の 30 行 `while True` が CC の 1729 行の核心。** 以下の各項目は、すべてその核心の上に積み重ねられた保護機構である。 - -
-一、ループ構造の違い - -教育版は `response.stop_reason` をチェックする。CC はこれをループ継続の唯一の根拠として使わない — ストリーミングレスポンスでは、`stop_reason` がまだ更新されていなくても、コンテンツに既に `tool_use` ブロックが含まれている可能性がある。CC は `needsFollowUp` フラグを使用する:ストリーミングメッセージの受信時(`query.ts:830-834`)に、`tool_use` ブロックが検出されると `true` に設定される。`QueryEngine.ts` は `message_delta` から実際の `stop_reason` を取得して他の処理に利用するが、query loop 自体は `needsFollowUp` に依存する。 - -```typescript -// query.ts:554-558 -// stop_reason === 'tool_use' is unreliable. -// Set during streaming whenever a tool_use block arrives. -let needsFollowUp = false -``` - -
- -
-二、State オブジェクト 10 フィールド(教育版は messages のみ使用) - -| # | フィールド | 用途 | 対応章 | -|---|-----------|------|--------| -| 1 | `messages` | 現在のイテレーションのメッセージ配列 | s01 | -| 2 | `toolUseContext` | ツール、シグナル、権限コンテキスト | s02 | -| 3 | `autoCompactTracking` | 圧縮状態の追跡 | s08 | -| 4 | `maxOutputTokensRecoveryCount` | トークンリカバリ試行回数(上限 3) | s11 | -| 5 | `hasAttemptedReactiveCompact` | 今回のラウンドでリアクティブ圧縮を試みたか | s08 | -| 6 | `maxOutputTokensOverride` | 8K→64K へのアップグレード上書き | s11 | -| 7 | `pendingToolUseSummary` | バックグラウンド Haiku 生成のツール使用要約 | s08 | -| 8 | `stopHookActive` | 停止フックがブロッキングエラーを発生させたか | s04 | -| 9 | `turnCount` | ターン数(maxTurns チェック用) | s01 | -| 10 | `transition` | 前回の継続理由 | s11 | - -> 注:`taskBudgetRemaining`(`query.ts:291`)は loop-local のローカル変数であり、State には含まれない。ソースコメントには明確に "Loop-local (not on State)" と書かれている。 - -
- -
-三、複数の終了パスと継続パス - -教育版には 1 つの終了パスしかない(モデルがツールを呼ばなければ終了)。本番版には複数の終了・継続パスがあり、blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry など多くのシナリオをカバーしている。各シナリオには対応するリカバリまたは終了戦略がある。 - -
- -
-四、ストリーミングツール実行と QueryEngine - -CC の `StreamingToolExecutor`(`query.ts:561`)は、モデルがまだ生成中にツールの実行を開始できる(concurrency-safe なツールは並列、それ以外は排他実行)。`QueryEngine.ts` はさらに、コスト超過や構造化出力の検証失敗などの保護を追加する。教育版はこれらを実装しない — 目標は概念の明確さであり、極限のパフォーマンスではない。 - -
- -**一言で**: query.ts の 1729 行の核心は 30 行の `while True`。複雑なフィールドや終了パスはすべて保護機構だ。まず核心のループを理解すれば、その後のすべては自然に理解できる。 - -
diff --git a/s01_agent_loop/README.md b/s01_agent_loop/README.md index c168bd6f..d3c0ed9c 100644 --- a/s01_agent_loop/README.md +++ b/s01_agent_loop/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 → s22 +`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 > *"One loop & Bash is all you need"* — One tool + one loop = one Agent. > > **Harness Layer**: The Loop — the first bridge between the model and the real world. @@ -113,7 +113,7 @@ Under 30 lines — that's the minimal runnable agent harness kernel. It's not in ## Try It -> **Teaching demo notice**: The code executes shell commands generated by the model. Run it in a temporary test directory to avoid affecting your project files. s03 covers the real permission system. +> **Safety notice**: The code executes shell commands generated by the model. Run it in a temporary test directory to avoid affecting your project files. s03 adds permission controls. **Setup** (first run): @@ -145,63 +145,5 @@ Right now the model only has bash — reading files requires `cat`, writing file → s02 Tool Use: What happens when we give it 5 proper tools? Will the model call multiple tools at once? Will parallel tool executions step on each other? -
-Dive into CC Source Code - -> The following is based on a review of CC source code `src/query.ts` (1729 lines). The core differences are twofold: CC doesn't rely on the `stop_reason` field to decide whether to continue the loop — instead it checks whether the content contains `tool_use` blocks (because `stop_reason` is unreliable in streaming responses); CC has more exit paths and recovery strategies for production-grade protection. - -**The 30-line `while True` from the teaching version IS the core of CC's 1729 lines.** Everything below is a protection mechanism layered on top of that core. - -
-1. Loop Structure Differences - -The teaching version checks `response.stop_reason`. CC doesn't use it as the sole signal for loop continuation — in streaming responses, `stop_reason` may not have updated yet even though `tool_use` blocks are already present. CC uses a `needsFollowUp` flag: during streaming message reception (`query.ts:830-834`), it's set to `true` whenever a `tool_use` block is detected. `QueryEngine.ts` captures the real `stop_reason` from `message_delta` for other logic, but the query loop itself relies on `needsFollowUp`. - -```typescript -// query.ts:554-558 -// stop_reason === 'tool_use' is unreliable. -// Set during streaming whenever a tool_use block arrives. -let needsFollowUp = false -``` - -
- -
-2. State Object — 10 Fields (Teaching Version Only Uses messages) - -| # | Field | Purpose | Chapter | -|---|-------|---------|---------| -| 1 | `messages` | Message array for the current iteration | s01 | -| 2 | `toolUseContext` | Tool, signal, and permission context | s02 | -| 3 | `autoCompactTracking` | Compaction state tracking | s08 | -| 4 | `maxOutputTokensRecoveryCount` | Token recovery attempt count (max 3) | s11 | -| 5 | `hasAttemptedReactiveCompact` | Whether reactive compaction was attempted this round | s08 | -| 6 | `maxOutputTokensOverride` | 8K→64K upgrade override | s11 | -| 7 | `pendingToolUseSummary` | Background Haiku-generated tool use summary | s08 | -| 8 | `stopHookActive` | Whether the stop hook produced a blocking error | s04 | -| 9 | `turnCount` | Turn count (for maxTurns check) | s01 | -| 10 | `transition` | Last continue reason | s11 | - -> Note: `taskBudgetRemaining` (`query.ts:291`) is a loop-local variable, not on State. The source comment explicitly says "Loop-local (not on State)". - -
- -
-3. Multiple Exit and Continue Paths - -The teaching version has only 1 exit path (model doesn't call a tool → done). The production version has multiple exit and continue paths, covering blocking limit, prompt too long, model error, abort, hook stop, max turns, token budget continuation, reactive compact retry, and more. Each scenario has a corresponding recovery or exit strategy. - -
- -
-4. Streaming Tool Execution and QueryEngine - -CC's `StreamingToolExecutor` (`query.ts:561`) allows tools to begin parallel execution while the model is still generating (concurrency-safe tools run in parallel, others run exclusively). `QueryEngine.ts` adds additional protections for cost overruns, structured output validation failures, and more. The teaching version doesn't implement these — the goal is conceptual clarity, not peak performance. - -
- -**In one sentence**: The core of query.ts's 1729 lines is a 30-line `while True`. All the complex fields and exit paths are protection mechanisms. Understand the core loop first, and everything that follows unfolds naturally. - -
diff --git a/s01_agent_loop/README.zh.md b/s01_agent_loop/README.zh.md index 06ec0589..6682ca5f 100644 --- a/s01_agent_loop/README.zh.md +++ b/s01_agent_loop/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 → s22 +`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 > *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent。 > > **Harness 层**: 循环 — 模型与真实世界的第一道连接。 @@ -113,7 +113,7 @@ def agent_loop(messages): ## 试一下 -> **教学 demo 提示**:代码会执行模型生成的 shell 命令。建议在一个临时测试目录中运行,避免影响你的项目文件。s03 会讲真正的权限系统。 +> **安全提示**:代码会执行模型生成的 shell 命令。建议在一个临时测试目录中运行,避免影响你的项目文件。s03 会加入权限控制。 **准备**(首次运行): @@ -145,63 +145,5 @@ python s01_agent_loop/code.py s02 Tool Use → 给它 5 个真正的工具,会发生什么?模型会不会一次调用多个工具?几个工具同时跑会不会互相踩? -
-深入 CC 源码 - -> 以下内容基于 CC 源码 `src/query.ts`(1729 行)的核查。核心差异就两个:CC 不看 `stop_reason` 字段而是检查内容里有没有 tool_use 块(因为流式响应中 stop_reason 不可靠);CC 有更多的退出路径和恢复策略做生产级保护。 - -**教学版的 30 行 `while True` 就是 CC 1729 行的核心。** 下面每一项都是在这个核心上叠加的保护机制。 - -
-一、循环结构差异 - -教学版检查 `response.stop_reason`。CC 不把它作为循环继续的唯一依据——流式响应中 `stop_reason` 可能还没更新但内容里已经有 `tool_use` 块了。CC 用 `needsFollowUp` 标志:接收到流式消息时(`query.ts:830-834`),只要检测到 `tool_use` 块就设为 `true`;`QueryEngine.ts` 会从 `message_delta` 捕获真实 `stop_reason` 用于其他逻辑,但 query loop 本身靠 `needsFollowUp` 决定是否继续。 - -```typescript -// query.ts:554-558 -// stop_reason === 'tool_use' is unreliable. -// Set during streaming whenever a tool_use block arrives. -let needsFollowUp = false -``` - -
- -
-二、State 对象 10 字段(教学版只用 messages) - -| # | 字段 | 用途 | 对应章节 | -|---|------|------|---------| -| 1 | `messages` | 当前迭代的消息数组 | s01 | -| 2 | `toolUseContext` | 工具、信号、权限上下文 | s02 | -| 3 | `autoCompactTracking` | 压缩状态追踪 | s08 | -| 4 | `maxOutputTokensRecoveryCount` | token 恢复尝试次数(上限 3) | s11 | -| 5 | `hasAttemptedReactiveCompact` | 本轮是否已尝试响应式压缩 | s08 | -| 6 | `maxOutputTokensOverride` | 8K→64K 的升级覆盖 | s11 | -| 7 | `pendingToolUseSummary` | 后台 Haiku 生成的 tool use 摘要 | s08 | -| 8 | `stopHookActive` | 停止钩子是否产生阻塞错误 | s04 | -| 9 | `turnCount` | 轮次计数(maxTurns 检查) | s01 | -| 10 | `transition` | 上一次继续原因 | s11 | - -> 注:`taskBudgetRemaining`(`query.ts:291`)是 loop-local 局部变量,不在 State 上。源码注释明确写了 "Loop-local (not on State)"。 - -
- -
-三、多条退出和继续路径 - -教学版只有 1 条退出路径(模型不调工具就结束)。生产版有多条退出和继续路径,覆盖 blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry 等场景。每种场景都有对应的恢复或退出策略。 - -
- -
-四、流式工具执行和 QueryEngine - -CC 的 `StreamingToolExecutor`(`query.ts:561`)让工具在模型还在生成时就开始并行执行(根据工具是否 concurrency-safe 决定并发或独占)。`QueryEngine.ts` 额外加了费用超限、结构化输出验证失败等保护。教学版不实现这些——目标是概念清晰,不是性能极致。 - -
- -**一句话**:1729 行的 query.ts 核心就是 30 行 `while True`。所有复杂字段和退出路径都是保护机制。先理解核心循环,后面的一切自然展开。 - -
diff --git a/s01_agent_loop/code.py b/s01_agent_loop/code.py index 6a4459d3..d426a3da 100644 --- a/s01_agent_loop/code.py +++ b/s01_agent_loop/code.py @@ -19,8 +19,8 @@ The entire secret of an AI coding agent in one pattern: (loop continues) This is the core loop: feed tool results back to the model -until the model decides to stop. Production agents layer -policy, hooks, and lifecycle controls on top. +until the model decides to stop. Later chapters add policy, +hooks, and lifecycle controls around it. Usage: pip install anthropic python-dotenv diff --git a/s02_tool_use/README.ja.md b/s02_tool_use/README.ja.md index 1711e11e..821e03a8 100644 --- a/s02_tool_use/README.ja.md +++ b/s02_tool_use/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → `s02` → [s03](../s03_permission/) → s04 → ... → s20 → s21 → s22 +s01 → `s02` → [s03](../s03_permission/) → s04 → ... → s20 → s21 > *"ツールを一つ追加、ハンドラを一つ追加"* — ループはそのまま。新しいツールをディスパッチマップに登録するだけ。 > > **Harness レイヤー**: ツールディスパッチ — モデルが触れる範囲を拡張。 @@ -106,7 +106,7 @@ for block in response.content: モデルはよく一度に複数の tool_use を返す — 「a.py と b.py を読んで、全 .py ファイルを列挙して」。 -教育版は `response.content` の元の順序で一つずつ実行する。CC のやり方はより複雑:元の順序を保ったまま連続バッチに分割し、バッチ内の並列安全なツールを並行実行し、バッチ間は厳密に順次(付録を参照)。 +これらの呼び出しは、`response.content` に現れる元の順序で一つずつ実行する。 --- @@ -116,7 +116,7 @@ for block in response.content: |------|--------| | TOOL_HANDLERS | ツール名 → ハンドラ関数の辞書。ツール追加 = マッピング一行追加 | | ツール定義 | モデルに「何ができるか」を伝える JSON schema | -| 複数ツール呼び出し | モデルは一度に複数の tool_use を返す可能性がある。教育版は元の順序で一つずつ実行 | +| 複数ツール呼び出し | モデルは一度に複数の tool_use を返す可能性があり、元の順序で一つずつ実行する | | ループ不変 | s01 の `while True` ループ — 一行も変更なし | --- @@ -156,67 +156,5 @@ Agent は 5 つの専用ツールを持つようになった。file tools は `s → s03 Permission:ツール実行前にゲートを追加 — この操作は安全か? ユーザーの承認が必要か? -
-CC ソースコードを深掘り - -> 以下は CC ソースコード `Tool.ts`、`tools.ts`、`toolOrchestration.ts`、`toolExecution.ts`、`StreamingToolExecutor.ts` の検証に基づく。 - -### 一、ツール定義方式 - -**教育版**:`TOOLS` 配列 + `TOOL_HANDLERS` 辞書。定義と実装が分離。 -**CC**:各ツールは `buildTool()` で作成された独立オブジェクトで、schema、バリデーション、権限、実行を含む。`getAllBaseTools()` が全ツールを集約。 - -教育版の分離方式は教学に適している — 読者は「ツール追加 = 二つの定義」と一目で分かる。 - -### 二、並列安全性:isConcurrencySafe() - -![Tool Concurrency](images/concurrency-comparison.ja.svg) - -教育版は元の順序で一つずつ実行し、並列処理は行わない。CC は `isConcurrencySafe(input)` で並列可否を判断する — これは単なる「読み取り専用 vs 書き込み」ではなく、具体的な入力で判断する: - -| | isReadOnly | isConcurrencySafe | -|---|---|---| -| FileRead | true | true | -| Glob | true | true | -| Bash `ls` | true | **true** ← 重要な違い | -| Bash `rm` | false | false | -| TaskCreate | false | **true** ← 状態変更するが並列可能(s12 で紹介) | - -CC の Bash ツールの `isConcurrencySafe` は `isReadOnly` と同じ — 読み取り専用コマンドは並列可能、書き込みコマンドは不可。TaskCreate はタスクファイルを変更するが、毎回異なるファイルに書き込むため並列可能。 - -### 三、パーティションアルゴリズム - -CC の `partitionToolCalls()`(`toolOrchestration.ts:91-115`)は二つのグループに分けるのではなく、ツール呼び出しを**連続ブロックごとにバッチ化**する: - -``` -[read A, read B, glob *.py, bash "rm x", read C] - → batch1(並列): [read A, read B, glob *.py] - → batch2(直列): [bash "rm x"] - → batch3(並列): [read C] -``` - -連続する並列安全な呼び出しを同じバッチにまとめ、真の並列実行を行う(`toolOrchestration.ts:152-176`、並列数上限あり)。非並列安全な呼び出しに遭遇すると新しいバッチを開始して直列実行。バッチ間は厳密に順次。 - -### 四、バリデーションパイプライン - -CC の各ツール呼び出しは厳格な 5 段階のバリデーションを経る(`toolExecution.ts`): - -1. **Zod schema バリデーション**(`614-680`、教育版は JSON Schema で代替):パラメータの型/構造チェック -2. **ツールレベル validateInput()**(`682-733`):パラメータ値の検証(例:パスが作業ディレクトリ内か) -3. **PreToolUse フック**(`800-862`、s04 で詳解):フックはメッセージの返却、入力の変更、実行のブロックが可能 -4. **権限チェック**(`921-931`、s03 の核心):canUseTool + checkPermissions → allow/deny/ask -5. **tool.call() の実行**(`1207-1222`) - -教育版は Zod を省略(JSON Schema を使用)、validateInput を省略(安全関数を使用)、権限チェックとフック概念は保持。 - -### 五、ストリーミングツール実行 - -CC の `StreamingToolExecutor`(`StreamingToolExecutor.ts`)はモデルがまだ生成中にツールを起動する — モデルの完了を待たない。`read_file` はモデルが「分析します」と出力中に完了するかもしれない。教育版はこれを実装しない。s01 と同じ目標 — 概念の明確さ、極限のパフォーマンスではない。 - -### 六、ツール結果の永続化 - -各ツールには `maxResultSizeChars` フィールドがある。この閾値を超える結果はディスクに保存され、モデルにはプレビュー + ファイルパスが表示される。FileRead は特殊 — `Infinity` に設定され、ファイル読み出し結果の再永続化を防ぐ。具体的には、FileRead の結果が閾値を超えて永続化されると、モデルがその永続化ファイルを次に読むときにまた永続化がトリガーされ → 無限ループ(ファイル読む → 永続化 → 再読み → 再永続化 → ...)になる。 - -
diff --git a/s02_tool_use/README.md b/s02_tool_use/README.md index 3a668bfb..913d6caa 100644 --- a/s02_tool_use/README.md +++ b/s02_tool_use/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → `s02` → [s03](../s03_permission/) → s04 → ... → s20 → s21 → s22 +s01 → `s02` → [s03](../s03_permission/) → s04 → ... → s20 → s21 > *"Add a tool, add just one handler"* — The loop stays the same. Register the new tool in the dispatch map and you're done. > > **Harness Layer**: Tool Dispatch — Expanding the model's reach. @@ -106,7 +106,7 @@ Adding a tool = one entry in `TOOLS` array + one line in `TOOL_HANDLERS` dict. T The model often returns multiple tool_use calls at once — "read a.py and b.py, then list all .py files". -The teaching version executes them one by one in the original `response.content` order. CC's approach is more complex: it slices the original order into consecutive batches, where concurrency-safe tools within a batch run in parallel, and batches are strictly sequential (see appendix). +Calls are executed one by one in their original `response.content` order. --- @@ -116,7 +116,7 @@ The teaching version executes them one by one in the original `response.content` |---------|-----------| | TOOL_HANDLERS | Tool name → handler function dict. Add a tool = add one mapping line | | Tool Definition | JSON schema telling the model "what I can do" | -| Multiple tool calls | Model may return multiple tool_use at once; teaching version executes them in original order | +| Multiple tool calls | Model may return multiple tool_use at once; calls execute in their original order | | Loop Unchanged | s01's `while True` loop — not a single line changed | --- @@ -156,67 +156,5 @@ The Agent now has 5 specialized tools. File tools are protected by `safe_path`, → s03 Permission: Add a gate before tool execution — is this operation safe? Does it need user approval? -
-Dive into CC Source Code - -> The following is based on a review of CC source code `Tool.ts`, `tools.ts`, `toolOrchestration.ts`, `toolExecution.ts`, and `StreamingToolExecutor.ts`. - -### 1. Tool Definition Approach - -**Teaching version**: `TOOLS` array + `TOOL_HANDLERS` dict. Definition and implementation are separate. -**CC**: Each tool is an independent object created by `buildTool()`, containing schema, validation, permissions, and execution. `getAllBaseTools()` aggregates all tools. - -The teaching version's separation is clearer for teaching — readers immediately see "add a tool = two definitions". - -### 2. Concurrency Safety: isConcurrencySafe() - -![Tool Concurrency](images/concurrency-comparison.en.svg) - -The teaching version executes tools one by one in original order, without concurrency. CC uses `isConcurrencySafe(input)` to determine concurrency — note this isn't simply "read-only vs write", but judges by specific input: - -| | isReadOnly | isConcurrencySafe | -|---|---|---| -| FileRead | true | true | -| Glob | true | true | -| Bash `ls` | true | **true** ← key difference | -| Bash `rm` | false | false | -| TaskCreate | false | **true** ← modifies state but can be concurrent (introduced in s12) | - -CC's Bash tool's `isConcurrencySafe` equals `isReadOnly` — read-only commands can be concurrent, write commands cannot. TaskCreate modifies task files, but each writes a different file, so it can be concurrent. - -### 3. Partition Algorithm - -CC's `partitionToolCalls()` (`toolOrchestration.ts:91-115`) doesn't split into two groups — it batches tool calls **by consecutive blocks**: - -``` -[read A, read B, glob *.py, bash "rm x", read C] - → batch1(concurrent): [read A, read B, glob *.py] - → batch2(serial): [bash "rm x"] - → batch3(concurrent): [read C] -``` - -Consecutive concurrency-safe calls are grouped into the same batch for truly concurrent execution (`toolOrchestration.ts:152-176`, with a concurrency limit). When a non-concurrency-safe call is encountered, a new batch starts for serial execution. Batches are strictly sequential. - -### 4. Validation Pipeline - -Each tool call in CC goes through a strict 5-step validation (`toolExecution.ts`): - -1. **Zod schema validation** (`614-680`, teaching version uses JSON Schema): parameter type/structure check -2. **Tool-level validateInput()** (`682-733`): parameter value validation (e.g., is the path within the working directory) -3. **PreToolUse hooks** (`800-862`, covered in s04): hooks can return messages, modify input, or block execution -4. **Permission check** (`921-931`, core topic of s03): canUseTool + checkPermissions → allow/deny/ask -5. **Execute tool.call()** (`1207-1222`) - -The teaching version omits Zod (uses JSON Schema), omits validateInput (uses safety functions), but preserves the permission check and hook concepts. - -### 5. Streaming Tool Execution - -CC's `StreamingToolExecutor` (`StreamingToolExecutor.ts`) starts tools while the model is still generating — no waiting for the model to finish. `read_file` might complete while the model is still outputting "Let me analyze". The teaching version doesn't implement this, consistent with s01's goal — conceptual clarity, not peak performance. - -### 6. Tool Result Persistence - -Each tool has a `maxResultSizeChars` field. Results exceeding this threshold are persisted to disk, and the model sees a preview + file path. FileRead is special — set to `Infinity`, preventing file read output from being persisted again. Specifically, if FileRead's result exceeds the threshold and gets persisted, the model's next read of that persisted file would trigger another persistence → infinite loop (read file → persist → re-read → re-persist → ...). - -
diff --git a/s02_tool_use/README.zh.md b/s02_tool_use/README.zh.md index fee9d07e..55c2f9db 100644 --- a/s02_tool_use/README.zh.md +++ b/s02_tool_use/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → `s02` → [s03](../s03_permission/) → s04 → ... → s20 → s21 → s22 +s01 → `s02` → [s03](../s03_permission/) → s04 → ... → s20 → s21 > *"加一个工具, 只加一个 handler"* — 循环不用动, 新工具注册进 dispatch map 就行。 > > **Harness 层**: 工具分发 — 扩展模型能触达的边界。 @@ -106,7 +106,7 @@ for block in response.content: 模型经常一次返回多个 tool_use:"读一下 a.py 和 b.py,然后列出所有 .py 文件"。 -教学版按 `response.content` 原始顺序逐个执行。CC 的做法更复杂:按原始顺序切成连续 batch,batch 内并发安全的工具并行执行,batch 间严格顺序(见附录)。 +这些调用按照 `response.content` 中的原始顺序逐个执行。 --- @@ -116,7 +116,7 @@ for block in response.content: |------|--------| | TOOL_HANDLERS | 工具名 → 处理函数的字典。加工具 = 加一行映射 | | 工具定义 | 告诉模型"我能做什么"的 JSON schema | -| 多工具调用 | 模型可一次返回多个 tool_use,教学版按原始顺序逐个执行 | +| 多工具调用 | 模型可一次返回多个 tool_use,并按原始顺序逐个执行 | | 循环不变 | s01 的 `while True` 循环一行都没改 | --- @@ -156,67 +156,5 @@ python s02_tool_use/code.py s03 Permission → 在工具执行之前加一道门:这个操作安全吗?需要用户批准吗? -
-深入 CC 源码 - -> 以下基于 CC 源码 `Tool.ts`、`tools.ts`、`toolOrchestration.ts`、`toolExecution.ts`、`StreamingToolExecutor.ts` 的核查。 - -### 一、工具定义方式 - -**教学版**:`TOOLS` 数组 + `TOOL_HANDLERS` 字典。定义和实现分开。 -**CC**:每个工具是 `buildTool()` 创建的独立对象,包含 schema、验证、权限、执行。`getAllBaseTools()` 汇总所有工具。 - -教学版的分离方式对教学更清晰——读者一眼看到"加一个工具 = 两条定义"。 - -### 二、并发安全判断:isConcurrencySafe() - -![Tool Concurrency](images/concurrency-comparison.svg) - -教学版按原始顺序逐个执行,不做并发。CC 用 `isConcurrencySafe(input)` 判断能否并发——注意这不是简单的"只读 vs 写",而是按具体输入判断: - -| | isReadOnly | isConcurrencySafe | -|---|---|---| -| FileRead | true | true | -| Glob | true | true | -| Bash `ls` | true | **true** ← 关键差异 | -| Bash `rm` | false | false | -| TaskCreate | false | **true** ← 改状态但可并发(TaskCreate 在 s12 介绍) | - -CC 的 Bash tool 的 `isConcurrencySafe` 等于 `isReadOnly`——只读命令可并发,写命令不可。TaskCreate 虽然改了任务文件,但每次都写不同的文件,所以可以并发。 - -### 三、分区算法 - -CC 的 `partitionToolCalls()`(`toolOrchestration.ts:91-115`)不是分两组,而是把工具调用**按连续块分批**: - -``` -[read A, read B, glob *.py, bash "rm x", read C] - → batch1(并发): [read A, read B, glob *.py] - → batch2(串行): [bash "rm x"] - → batch3(并发): [read C] -``` - -并发安全的连续块编入同一个 batch,batch 内真正并发执行(`toolOrchestration.ts:152-176`,有并发上限)。遇到非并发安全的就开新 batch 串行执行。batch 之间严格顺序。 - -### 四、验证管线 - -CC 的每个工具调用经过严格的 5 步验证(`toolExecution.ts`): - -1. **Zod schema 验证**(`614-680`,教学版用 JSON Schema 替代):参数类型/结构检查 -2. **工具级 validateInput()**(`682-733`):参数值验证(如路径是否在工作区内) -3. **PreToolUse hooks**(`800-862`,s04 详细介绍):钩子可以返回消息、修改输入、阻止执行 -4. **权限检查**(`921-931`,s03 的核心内容):canUseTool + checkPermissions → allow/deny/ask -5. **执行 tool.call()**(`1207-1222`) - -教学版省略了 Zod(用 JSON Schema)、省略了 validateInput(用安全函数)、保留了权限检查和钩子概念。 - -### 五、流式工具执行 - -CC 的 `StreamingToolExecutor`(`StreamingToolExecutor.ts`)让工具在模型还在生成时就启动——不等模型说完。`read_file` 可能在模型还在输出"我来分析"的时候就跑完了。教学版不实现这个,目标和 s01 一致——概念清晰,不追求性能极致。 - -### 六、工具结果持久化 - -每个工具有一个 `maxResultSizeChars` 字段。结果超过这个值就落盘,模型看到的是预览 + 文件路径。FileRead 特殊——设为 `Infinity`,防止读文件的输出又被当成文件落盘。具体来说,如果 FileRead 的结果超过阈值被落盘,模型下次读那个落盘文件时又会触发落盘 → 无限循环(读文件 → 落盘 → 再读 → 再落盘 → ...)。 - -
diff --git a/s02_tool_use/images/concurrency-comparison.en.svg b/s02_tool_use/images/concurrency-comparison.en.svg deleted file mode 100644 index 04dab323..00000000 --- a/s02_tool_use/images/concurrency-comparison.en.svg +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - Tool Concurrency — Teaching Version vs Claude Code - - - - Model returns 5 tool calls at once - - - read A.py - - - glob *.py - - - bash "ls -la" - - - write B.py - - - read C.py - - - - Teaching: Original Order, One by One - - - for block in response.content: - TOOL_HANDLERS[name](**input) - - Result: 5 serial calls, no batches - - - 1. read A.py - - - 2. glob *.py - - - 3. bash "ls -la" - - - 4. write B.py - - - 5. read C.py - - Teaching focus: tool dispatch first; concurrency omitted - - - - Claude Code: isConcurrencySafe(input) - - - Each tool call judged individually: - tool.isConcurrencySafe(parsedInput) → bool - - Result: 3 batches (by consecutive blocks) - - - Batch 1 - Concurrent - read A · glob · bash "ls" - - - - - Batch 2 - Serial - write B - - - - - Batch 3 - Concurrent - read C - - bash "ls" is safe and consecutive, so it stays in Batch 1 - - ✓ Input-dependent safety, not tool-name hardcoding - ✓ Original order preserved; only safe consecutive calls run together - - - - Key Difference - • Teaching: executes response.content in original order, one tool call at a time; no concurrency or batching - • CC: checks isConcurrencySafe(input), then groups consecutive safe calls into one batch - • Key difference: teaching focuses on dispatch; CC optimizes safe concurrency while preserving order semantics - diff --git a/s02_tool_use/images/concurrency-comparison.ja.svg b/s02_tool_use/images/concurrency-comparison.ja.svg deleted file mode 100644 index f130d5b3..00000000 --- a/s02_tool_use/images/concurrency-comparison.ja.svg +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - ツール並列実行 — 教育版 vs Claude Code - - - - モデルが一度に 5 つのツール呼び出しを返す - - - read A.py - - - glob *.py - - - bash "ls -la" - - - write B.py - - - read C.py - - - - 教育版:元の順序で一つずつ実行 - - - for block in response.content: - TOOL_HANDLERS[name](**input) - - 結果:5 回の直列呼び出し、batch なし - - - 1. read A.py - - - 2. glob *.py - - - 3. bash "ls -la" - - - 4. write B.py - - - 5. read C.py - - 教育の焦点:まず tool_use 分配を理解し、並列は省略 - - - - Claude Code:isConcurrencySafe(input) - - - 各ツール呼び出しを個別に判定: - tool.isConcurrencySafe(parsedInput) → bool - - 結果:3 バッチ(連続ブロックごと) - - - Batch 1 - 並列 - read A · glob · bash "ls" - - - - - Batch 2 - 直列 - write B - - - - - Batch 3 - 並列 - read C - - bash "ls" は安全かつ連続しているため Batch 1 に入る - - ✓ 入力に基づく安全判定、ツール名ハードコードではない - ✓ 元の順序を保ち、連続する安全呼び出しだけ並列化 - - - - 核心的な違い - • 教育版:response.content の元の順序で一つずつ実行し、並列処理も batch 化もしない - • CC:isConcurrencySafe(input) で判定し、連続する安全呼び出しを同じ batch にまとめる - • 差分の要点:教育版は分配に集中し、CC は順序意味を保ったまま安全な並列を最適化する - diff --git a/s02_tool_use/images/concurrency-comparison.svg b/s02_tool_use/images/concurrency-comparison.svg deleted file mode 100644 index e6941e61..00000000 --- a/s02_tool_use/images/concurrency-comparison.svg +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - Tool Concurrency — 教学版 vs Claude Code - - - - 模型一次返回 5 个工具调用 - - - read A.py - - - glob *.py - - - bash "ls -la" - - - write B.py - - - read C.py - - - - 教学版:按原始顺序逐个执行 - - - for block in response.content: - TOOL_HANDLERS[name](**input) - - 结果:5 次串行调用,不做 batch - - - 1. read A.py - - - 2. glob *.py - - - 3. bash "ls -la" - - - 4. write B.py - - - 5. read C.py - - 教学重点:先理解 tool_use 分发,暂不引入并发执行 - - - - Claude Code:isConcurrencySafe(input) - - - 每个工具调用单独判断: - tool.isConcurrencySafe(parsedInput) → bool - - 结果:3 个 batch(按连续块分批) - - - Batch 1 - 并发 - read A · glob · bash "ls" - - - - - Batch 2 - 串行 - write B - - - - - Batch 3 - 并发 - read C - - bash "ls" 是并发安全调用,且和 read/glob 连续,所以留在 Batch 1 - - ✓ 按输入判断并发安全,不按工具名硬编码 - ✓ 保留原始顺序,只在连续安全块内部并发 - - - - 核心差异 - • 教学版:按 response.content 原始顺序逐个执行,不做并发,也不分 batch - • CC:按 isConcurrencySafe(input) 判断,并把连续的并发安全调用合成同一个 batch - • 差异重点:教学版聚焦工具分发;CC 在保持顺序语义的同时优化安全并发 - diff --git a/s03_permission/README.ja.md b/s03_permission/README.ja.md index c4362591..89b8644d 100644 --- a/s03_permission/README.ja.md +++ b/s03_permission/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 → s22 +s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 > *"ツール実行前に権限を判断"* — 権限パイプラインは、どの操作に承認が必要かを決める。 > > **Harness レイヤー**: 権限 — ツール実行前に一つのゲートを追加。 @@ -39,7 +39,7 @@ s02 のループは完全に維持される。唯一の変更は、ツール実 ![Permission Pipeline](images/permission-pipeline.ja.svg) -**ゲート 1**:ハード拒否リスト。最初に確認し、一致すればブロックメッセージを返す。(教育デモ:単純な文字列マッチングは信頼できるセキュリティ機構ではない — コマンドの変種やシェル展開で回避される可能性がある。CC のアプローチは付録を参照。) +**ゲート 1**:ハード拒否リスト。最初に確認し、一致すればブロックメッセージを返す。このリストは権限ゲートの位置を示すための単純な文字列照合であり、完全なセキュリティ境界ではない。 ```python DENY_LIST = [ @@ -153,80 +153,5 @@ python s03_permission/code.py → s04 Hooks:ループにフックを追加する。拡張ロジックはフックにぶら下げ、ループはクリーンに保つ。 -
-CC ソースコードを深掘り - -> 以下は CC ソースコード `types/permissions.ts`、`utils/permissions/permissions.ts`、`toolExecution.ts`、`utils/permissions/yoloClassifier.ts`、`tools/AgentTool/forkSubagent.ts` の検証に基づく。 - -### 一、PermissionResult:3 種ではなく、4 種 - -教育版の 3 つのゲート(deny → ask → allow)は CC と完全には対応しない。CC の `PermissionResult` には 4 つの behavior がある(`types/permissions.ts:241-266`): - -| behavior | 意味 | 教育版の対応 | -|----------|------|-------------| -| `allow` | 直接許可 | ゲート 3 通過 | -| `deny` | 直接拒否 | ゲート 1 一致 | -| `ask` | ユーザーにダイアログを表示 | ゲート 2 一致 | -| `passthrough` | ツールが意見を表明せず、汎用パイプラインに委ねる | 教育版にはなし | - -### 二、本番環境の検証段階 - -CC のツール呼び出しは 3 つのゲートを通るのではなく、`checkPermissionsAndCallTool()`(`toolExecution.ts:599-1745`)、hooks、`hasPermissionsToUseToolInner()`(`utils/permissions/permissions.ts:1158-1310`)、classifier ロジックに分散する複数の段階を経る: - -1. **Zod schema 検証**(`toolExecution.ts:614-680`)— パラメータの型チェック -2. **validateInput()**(`toolExecution.ts:682-733`)— ツールレベルの意味的検証 -3. **backfillObservableInput()**(`toolExecution.ts:784`)— レガシーフィールドの補完 -4. **PreToolUse hooks**(`toolExecution.ts:800-862`)— フックが allow/deny/ask を返す -5. **resolveHookPermissionDecision()**(`toolExecution.ts:921-931`)— フック + パイプラインの決定を調整 -6. **hasPermissionsToUseToolInner()**(`permissions.ts:1158-1310`)— 多層ルールチェック: - - ツール全体が deny rule で無効 → `deny` - - ツール全体が ask rule でマーク → `ask` - - `tool.checkPermissions()` ツール自身の判断 - - ツール自身が deny を返す → `deny` - - `requiresUserInteraction()` → `ask` - - コンテンツ関連の ask ルール → `ask`(バイパス不可) - - セキュリティチェック違反 → `ask`(バイパス不可) - - bypassPermissions モード → `allow` - - ツール全体が allow rule で許可 → `allow` - - passthrough → `ask` に変換 - -### 三、拒否リスト:1 つのファイルではなく、8 つのソース - -CC には単一の deny list はない。権限ルールは 8 つのソースから来る(`types/permissions.ts:54-62`): - -| ソース | 設定場所 | -|--------|---------| -| `userSettings` | `~/.claude/settings.json` | -| `projectSettings` | `.claude/settings.json` | -| `localSettings` | `settings.local.json` | -| `flagSettings` | フィーチャーフラグ | -| `policySettings` | 企業管理ポリシー | -| `cliArg` | `--allowedTools` / `--deniedTools` | -| `command` | インラインコマンド | -| `session` | セッション内一時承認 | - -各ルールの形式:`{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`。複数ソースのルールは統合され、高優先度ソースが低優先度を上書きする(低→高:user < project < local < flag < policy、さらに cliArg、command、session)。 - -### 四、isDestructive() とは - -CC では `isDestructive`(`Tool.ts:405-406`)は**純粋に UI 表示用** — ツール一覧に `[destructive]` ラベルを表示するだけ。権限決定には参加しない。デフォルトではすべてのツールが `false` を返す。ExitWorktree(remove 時)と MCP ツール(`annotations.destructiveHint` に依存)のみがオーバーライドする。 - -### 五、YoloClassifier(自動承認) - -CC の auto モードでは、毎回ダイアログを表示するわけではない。`classifyYoloAction`(`utils/permissions/yoloClassifier.ts:1012`)はツール呼び出し + 会話コンテキストを分類器 LLM に送って安全性を判断する。まず acceptEdits モードのシミュレーションを試み(`permissions.ts:620-656`、acceptEdits が許可すれば → 自動承認)、次にセーフツールホワイトリストを確認し(`permissions.ts:658-686`)、最後に分類器を呼び出す。分類器が連続して拒否しすぎた場合 → 手動承認にフォールバック。 - -### 六、権限バブリング - -サブ Agent(AgentTool 経由でフォークされたもの)の `permissionMode` は `'bubble'` に設定される(`forkSubagent.ts:50`)。これは権限ダイアログが**親 Agent のターミナルにバブルアップ**することを意味する。サブ Agent で黙って拒否されるのではない。Bash 分類器はこの過程で引き続き実行され — 権限ダイアログを表示しつつ、バックグラウンドで自動承認可能か判断する。 - -### 教育版の単純化は意図的 - -- 多段階パイプライン → 3 ゲート:理解のハードルが大幅に下がる -- 8 ルールソース → 1 つのローカル DENY_LIST:概念量を制御可能 -- isDestructive → 省略(教育版には UI レイヤーがなく、CC でも権限決定には参加しない) -- YoloClassifier → 省略(追加の LLM 呼び出しとテレメトリに依存) -- 権限バブリング → 省略(s15 でマルチ Agent を扱う) - -
diff --git a/s03_permission/README.md b/s03_permission/README.md index 316e7b6d..077f79fe 100644 --- a/s03_permission/README.md +++ b/s03_permission/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 → s22 +s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 > *"Check permissions before executing"* — The permission pipeline decides which operations need approval. > > **Harness Layer**: Permission — a gate before tool execution. @@ -39,7 +39,7 @@ None of the three gates match → execute directly. Most routine operations take ![Permission Pipeline](images/permission-pipeline.en.svg) -**Gate 1**: A hard deny list. Check first; if matched, return a block message. (Teaching demo: simple string matching is not a reliable security mechanism — command variants and shell expansion can bypass it. CC's approach is in the appendix.) +**Gate 1**: A hard deny list. Check first; if matched, return a block message. This list uses simple string matching to show where the permission gate sits; it is not a complete security boundary. ```python DENY_LIST = [ @@ -153,80 +153,5 @@ Permission checks are in place — but every check is hardcoded as `check_permis → s04 Hooks: Add hooks to the loop. Extension logic hangs on hooks; the loop stays clean. -
-Dive into CC Source Code - -> The following is based on a review of CC source code `types/permissions.ts`, `utils/permissions/permissions.ts`, `toolExecution.ts`, `utils/permissions/yoloClassifier.ts`, `tools/AgentTool/forkSubagent.ts`. - -### 1. PermissionResult: Not 3, but 4 - -The teaching version's three gates (deny → ask → allow) don't fully correspond to CC. CC's `PermissionResult` has 4 behaviors (`types/permissions.ts:241-266`): - -| behavior | Meaning | Teaching Version Equivalent | -|----------|---------|---------------------------| -| `allow` | Allow directly | Gate 3 passes | -| `deny` | Deny directly | Gate 1 matches | -| `ask` | Show dialog to user | Gate 2 matches | -| `passthrough` | Tool doesn't express opinion, passes to generic pipeline | Not in teaching version | - -### 2. Production Verification Stages - -CC's tool calls don't go through three gates — they go through multiple stages distributed across `checkPermissionsAndCallTool()` (`toolExecution.ts:599-1745`), hooks, `hasPermissionsToUseToolInner()` (`utils/permissions/permissions.ts:1158-1310`), and classifier logic: - -1. **Zod schema validation** (`toolExecution.ts:614-680`) — parameter type checking -2. **validateInput()** (`toolExecution.ts:682-733`) — tool-level semantic validation -3. **backfillObservableInput()** (`toolExecution.ts:784`) — backfill legacy fields -4. **PreToolUse hooks** (`toolExecution.ts:800-862`) — hooks can return allow/deny/ask -5. **resolveHookPermissionDecision()** (`toolExecution.ts:921-931`) — coordinate hook + pipeline decisions -6. **hasPermissionsToUseToolInner()** (`permissions.ts:1158-1310`) — multi-layer rule check: - - Entire tool disabled by deny rule → `deny` - - Entire tool flagged by ask rule → `ask` - - `tool.checkPermissions()` tool's own judgment - - Tool itself returns deny → `deny` - - `requiresUserInteraction()` → `ask` - - Content-related ask rules → `ask` (not bypassable) - - Security check violation → `ask` (not bypassable) - - bypassPermissions mode → `allow` - - Entire tool allowed by allow rule → `allow` - - passthrough → converted to `ask` - -### 3. Deny List: Not One File, but 8 Sources - -CC doesn't have a single deny list. Permission rules come from 8 sources (`types/permissions.ts:54-62`): - -| Source | Configuration Location | -|--------|----------------------| -| `userSettings` | `~/.claude/settings.json` | -| `projectSettings` | `.claude/settings.json` | -| `localSettings` | `settings.local.json` | -| `flagSettings` | Feature flags | -| `policySettings` | Enterprise management policy | -| `cliArg` | `--allowedTools` / `--deniedTools` | -| `command` | Inline command | -| `session` | In-session temporary authorization | - -Each rule format: `{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`. Rules from multiple sources are merged, with higher-priority sources overriding lower ones (low to high: user < project < local < flag < policy, plus cliArg, command, session). - -### 4. What is isDestructive() - -In CC, `isDestructive` (`Tool.ts:405-406`) is **purely for UI display** — showing a `[destructive]` label in the tool list. It doesn't participate in permission decisions. All tools return `false` by default. Only ExitWorktree (on remove) and MCP tools (depending on `annotations.destructiveHint`) override it. - -### 5. YoloClassifier (Auto-Approval) - -In CC's auto mode, it doesn't pop a dialog every time. `classifyYoloAction` (`utils/permissions/yoloClassifier.ts:1012`) sends the tool call + conversation context to a classifier LLM to judge safety. It first tries acceptEdits mode simulation (`permissions.ts:620-656`, if acceptEdits allows → auto-approve), then checks the safe tool whitelist (`permissions.ts:658-686`), and finally calls the classifier. If the classifier rejects too many times in a row → falls back to manual approval. - -### 6. Permission Bubbling - -A sub-Agent's (forked via AgentTool) `permissionMode` is set to `'bubble'` (`forkSubagent.ts:50`). This means permission dialogs **bubble up to the parent Agent's terminal**, rather than being silently denied in the sub-Agent. The Bash classifier continues running during this process — displaying the permission dialog while judging in the background whether auto-approval is possible. - -### The Teaching Version's Simplification Is Intentional - -- Multi-stage pipeline → 3 gates: dramatically lower barrier to understanding -- 8 rule sources → 1 local DENY_LIST: manageable concept count -- isDestructive → omitted (teaching version has no UI layer, and it doesn't participate in permission decisions in CC either) -- YoloClassifier → omitted (depends on additional LLM calls and telemetry) -- Permission bubbling → omitted (s15 covers multi-Agent) - -
diff --git a/s03_permission/README.zh.md b/s03_permission/README.zh.md index 01643121..e5f09931 100644 --- a/s03_permission/README.zh.md +++ b/s03_permission/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 → s22 +s01 → s02 → `s03` → [s04](../s04_hooks/) → s05 → ... → s20 → s21 > *"工具执行前先做权限判断"* — 权限管线决定哪些操作需要审批。 > > **Harness 层**: 权限 — 在工具执行前加一道门。 @@ -39,7 +39,7 @@ s02 的循环完全保留。唯一的变动在工具执行前插入 `check_permi ![Permission Pipeline](images/permission-pipeline.svg) -**闸门 1**:一张硬拒绝表,先查,命中就返回阻止信息。(教学示意:简单字符串匹配不是可靠安全机制,命令变体和 shell 展开可能绕过。CC 的做法见附录。) +**闸门 1**:一张硬拒绝表,先查,命中就返回阻止信息。这张表使用简单字符串匹配来说明权限闸门的位置,不能视为完整的安全边界。 ```python DENY_LIST = [ @@ -153,80 +153,5 @@ python s03_permission/code.py s04 Hooks → 给循环加钩子,扩展逻辑挂在钩子上,循环保持干净。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `types/permissions.ts`、`utils/permissions/permissions.ts`、`toolExecution.ts`、`utils/permissions/yoloClassifier.ts`、`tools/AgentTool/forkSubagent.ts` 的核查。 - -### 一、PermissionResult:不是 3 种,是 4 种 - -教学版的三道闸门(deny → ask → allow)和 CC 不完全对应。CC 的 `PermissionResult` 有 4 个 behavior(`types/permissions.ts:241-266`): - -| behavior | 含义 | 教学版对应 | -|----------|------|-----------| -| `allow` | 直接允许 | 闸门 3 通过 | -| `deny` | 直接拒绝 | 闸门 1 命中 | -| `ask` | 弹出对话框问用户 | 闸门 2 命中 | -| `passthrough` | 工具不表态,交给通用管线决定 | 教学版无 | - -### 二、生产版的验证阶段 - -CC 的工具调用不是经过三道闸门,而是经过多个阶段,分布在 `checkPermissionsAndCallTool()`(`toolExecution.ts:599-1745`)、hooks、`hasPermissionsToUseToolInner()`(`utils/permissions/permissions.ts:1158-1310`)和 classifier 逻辑里: - -1. **Zod schema 验证**(`toolExecution.ts:614-680`)— 参数类型检查 -2. **validateInput()**(`toolExecution.ts:682-733`)— 工具级语义验证 -3. **backfillObservableInput()**(`toolExecution.ts:784`)— 补全遗留字段 -4. **PreToolUse hooks**(`toolExecution.ts:800-862`)— 钩子可以返回 allow/deny/ask -5. **resolveHookPermissionDecision()**(`toolExecution.ts:921-931`)— 协调钩子+管线决策 -6. **hasPermissionsToUseToolInner()**(`permissions.ts:1158-1310`)— 多层规则检查: - - 整个工具被 deny rule 禁用 → `deny` - - 整个工具被 ask rule 标记 → `ask` - - `tool.checkPermissions()` 工具自己的判断 - - 工具自己返回 deny → `deny` - - `requiresUserInteraction()` → `ask` - - 内容相关的 ask 规则 → `ask`(不可绕过) - - 安全检查违规 → `ask`(不可绕过) - - bypassPermissions 模式 → `allow` - - 整个工具被 allow rule 放行 → `allow` - - passthrough → 转为 `ask` - -### 三、拒绝列表:不是一个文件,是 8 个来源 - -CC 没有单一的 deny list。权限规则来自 8 个来源(`types/permissions.ts:54-62`): - -| 来源 | 配置位置 | -|------|---------| -| `userSettings` | `~/.claude/settings.json` | -| `projectSettings` | `.claude/settings.json` | -| `localSettings` | `settings.local.json` | -| `flagSettings` | Feature flags | -| `policySettings` | 企业管理策略 | -| `cliArg` | `--allowedTools` / `--deniedTools` | -| `command` | 内联命令 | -| `session` | 会话内临时授权 | - -每条规则格式:`{ toolName: "Bash", ruleBehavior: "deny", ruleContent: "npm publish:*" }`。多个来源的规则合并,高优先级来源覆盖低优先级(从低到高:user < project < local < flag < policy,加上 cliArg、command、session)。 - -### 四、isDestructive() 是什么 - -CC 中 `isDestructive`(`Tool.ts:405-406`)**纯粹是 UI 展示用的**——在工具列表里显示 `[destructive]` 标签。它不参与权限决策。默认所有工具都返回 `false`。只有 ExitWorktree(remove 时)和 MCP 工具(依赖 `annotations.destructiveHint`)覆写了它。 - -### 五、YoloClassifier(自动审批) - -CC 的 auto 模式下,不会每次都弹对话框。`classifyYoloAction`(`utils/permissions/yoloClassifier.ts:1012`)把工具调用 + 对话上下文发给一个分类器 LLM 判断是否安全。先尝试 acceptEdits 模式模拟(`permissions.ts:620-656`,如果 acceptEdits 允许 → 直接批准),再查安全工具白名单(`permissions.ts:658-686`),最后才调分类器。分类器连续拒绝太多次 → 回退到人工审批。 - -### 六、权限冒泡 - -子 Agent(通过 AgentTool fork 出来的)的 `permissionMode` 设为 `'bubble'`(`forkSubagent.ts:50`)。意思是权限弹窗**冒泡到父 Agent 的终端**,而不是在子 Agent 里静默拒绝。Bash 分类器在这个过程中继续跑——给权限对话框显示的同时在后台判断是否可以自动批准。 - -### 教学版的简化是刻意的 - -- 多阶段管线 → 3 道闸门:理解门槛大幅降低 -- 8 个规则来源 → 1 个本地 DENY_LIST:概念量可控 -- isDestructive → 忽略(教学版没有 UI 层,CC 里它也不参与权限决策) -- YoloClassifier → 省略(依赖于额外的 LLM 调用和遥测系统) -- 权限冒泡 → 省略(s15 才涉及多 Agent) - -
diff --git a/s04_hooks/README.ja.md b/s04_hooks/README.ja.md index d8dafae3..c5cbb8dc 100644 --- a/s04_hooks/README.ja.md +++ b/s04_hooks/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → `s04` → [s05](../s05_todo_write/) → s06 → ... → s20 → s21 → s22 +s01 → s02 → s03 → `s04` → [s05](../s05_todo_write/) → s06 → ... → s20 → s21 > *"ループに掛ける、ループには書き込まない"* — フックがツール実行の前後に拡張ロジックを注入する。 > @@ -48,7 +48,7 @@ s03 のループと権限ロジックは完全に保持される。唯一の変 | UserPromptSubmit | ユーザー入力後、LLM に入る前 | 入力バリデーション、コンテキスト注入 | | PreToolUse | ツール実行前 | 権限チェック、ログ記録 | | PostToolUse | ツール実行後 | 副作用(自動 git add など)、出力チェック | -| Stop | ループが終了する直前 | クリーンアップ(CC は強制続行もサポート) | +| Stop | ループが終了する直前 | 後処理、ループを続行するかの判断 | 拡張は `register_hook()` で追加する。ループは `trigger_hooks()` を呼ぶだけ。 @@ -77,9 +77,9 @@ def trigger_hooks(event: str, *args): return None ``` -教学版では、PreToolUse の非 None 戻り値は実行阻止を意味し、Stop の非 None 戻り値は強制続行を意味する。UserPromptSubmit と PostToolUse の戻り値は未使用。 +`PreToolUse` が `None` 以外を返すと、現在のツール実行は中止される。`Stop` が `None` 以外を返すと、ループは続行する。`UserPromptSubmit` と `PostToolUse` の戻り値は制御フローに影響しない。 -**UserPromptSubmit**、ユーザー入力後、LLM に入る前に発火。CC では入力の横取りや変更が可能、教学版はログ出力のみ: +**UserPromptSubmit** はユーザー入力後、LLM に入る前に発火する。以下の hook は現在の作業ディレクトリを記録する: ```python def context_inject_hook(query: str) -> str | None: @@ -130,7 +130,7 @@ register_hook("PreToolUse", log_hook) register_hook("PostToolUse", large_output_hook) ``` -**Stop**、ループが終了する直前に発火(`stop_reason != "tool_use"`)。教学版ではクリーンアップ統計を印刷: +**Stop** はループが終了する直前に発火する(`stop_reason != "tool_use"`)。以下の hook は終了時の統計を出力する: ```python def summary_hook(messages: list) -> str | None: @@ -220,64 +220,5 @@ Agent は安全に操作を実行できるようになった。しかし「ま → s05 TodoWrite:Agent に計画ツールを与える。まずリストを作り、それから実行。 -
-CC ソースコードを深掘り - -> 以下は CC ソースコード `toolHooks.ts`(650 行)、`hooks.ts`、`stopHooks.ts`、`coreTypes.ts` の完全分析に基づく。 - -### 一、Hook イベント:4 つではなく 27 個 - -教育版は PreToolUse と PostToolUse のみを取り上げる。CC には実際に 27 のフックイベントがある(`coreTypes.ts:25-53`): - -| カテゴリ | イベント | -|----------|---------| -| ツール関連 | `PreToolUse`, `PostToolUse`, `PostToolUseFailure` | -| セッション関連 | `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `Setup` | -| ユーザー対話 | `UserPromptSubmit`, `Notification`, `PermissionRequest`, `PermissionDenied` | -| サブエージェント | `SubagentStart`, `SubagentStop` | -| 圧縮関連 | `PreCompact`, `PostCompact` | -| チーム関連 | `TeammateIdle`, `TaskCreated`, `TaskCompleted` | -| その他 | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded`, `CwdChanged`, `FileChanged` | - -教育版は 4 つのコアイベント(UserPromptSubmit、PreToolUse、PostToolUse、Stop)のみを取り上げる。これらで agent cycle の重要ノードを全てカバーできる。残り 23 個は同じパターン。 - -### 二、HookResult よく使うフィールド抜粋 - -CC の `HookResult`(`types/hooks.ts:260-275`)には 14 のフィールドがある。よく使うもの: - -| フィールド | 型 | 用途 | -|-----------|-----|------| -| `message` | Message | オプションの UI メッセージ | -| `blockingError` | HookBlockingError | ブロッキングエラー → 会話に注入してモデルが自己修正 | -| `outcome` | success/blocking/non_blocking_error/cancelled | 実行結果 | -| `preventContinuation` | boolean | 後続実行を阻止 | -| `stopReason` | string | 停止理由の説明 | -| `permissionBehavior` | allow/deny/ask/passthrough | フックが権限決定を返す | -| `updatedInput` | Record | ツール入力の変更 | -| `additionalContext` | string | 追加コンテキスト | -| `updatedMCPToolOutput` | unknown | MCP ツール出力の変更 | - -### 三、重要な不変条件:Hook 'allow' は deny/ask ルールをバイパスできない - -これは CC 権限システムで最も重要なセキュリティ設計(`toolHooks.ts:325-331`):**フックが allow を返しても、settings.json の deny/ask ルールをチェックする。** ユーザーのフックスクリプトが「許可」と言っても、settings.json でそのツールが無効になっていれば、操作は阻止される。 - -教育版にはこの階層がない。フックが非 None を返せば直接中断。教育目的では十分だが、本番環境ではセキュリティホールになる。 - -### 四、stopHookActive 機構 - -CC の Stop フックには無限ループ防止機構がある(`query.ts:212,1300`):`stopHookActive` 状態フィールド。Stop フックが blockingError を発生させると、ループは `stopHookActive: true` で次のラウンドに再入する。後続のイテレーションではこのフラグを見て Stop フックを再トリガーしない。これで「永久に止まらない」バグを防ぐ:モデルが自己修正 → Stop フックが再度エラー → モデルが再修正 → Stop フックが再度エラー... を防止。 - -### 五、hook_stopped_continuation - -PostToolUse フックが `preventContinuation: true` を返すと、`hook_stopped_continuation` アタッチメントが生成される(`toolHooks.ts:117-130`)。query.ts(L1388-1393)はそれを検出して `shouldPreventContinuation = true` を設定し、ループが終了する。これは「フックが Agent を優雅に停止させる」機構 — クラッシュではなく、完了。 - -### 教育版の簡略化は意図的 - -- 27 イベント → 4(UserPromptSubmit/PreToolUse/PostToolUse/Stop):agent cycle の重要ノードをカバー -- 14 フィールド → 単純な戻り値(None = 続行、非 None = 中断/続行):認知負荷を最小限に -- Hook allow vs deny/ask の不変条件 → 省略:教育版に settings.json 層はない -- stopHookActive → 省略:教育版の Stop フックは単純な続行のみ、無限ループ防止は不要 - -
diff --git a/s04_hooks/README.md b/s04_hooks/README.md index aaa6c3b1..f571a2ec 100644 --- a/s04_hooks/README.md +++ b/s04_hooks/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → `s04` → [s05](../s05_todo_write/) → s06 → ... → s20 → s21 → s22 +s01 → s02 → s03 → `s04` → [s05](../s05_todo_write/) → s06 → ... → s20 → s21 > *"Hang on the loop, don't write into it"* — Hooks inject extension logic before and after tool execution. > @@ -48,7 +48,7 @@ Four events, covering a complete agent cycle: | UserPromptSubmit | After user input, before entering LLM | Input validation, context injection | | PreToolUse | Before tool execution | Permission checks, logging | | PostToolUse | After tool execution | Side effects (auto git add etc.), output checking | -| Stop | When the loop is about to exit | Cleanup (CC also supports force continuation) | +| Stop | When the loop is about to exit | Cleanup, decide whether the loop continues | Extensions are added via `register_hook()`. The loop only calls `trigger_hooks()`. @@ -77,9 +77,9 @@ def trigger_hooks(event: str, *args): return None ``` -In the teaching version, PreToolUse returning non-None means block execution; Stop returning non-None means force continuation. UserPromptSubmit and PostToolUse return values are unused. +When `PreToolUse` returns non-None, the current tool execution is blocked. When `Stop` returns non-None, the loop continues. Return values from `UserPromptSubmit` and `PostToolUse` do not affect control flow. -**UserPromptSubmit**, triggers after user input, before entering the LLM. CC can intercept or modify input; the teaching version only logs: +**UserPromptSubmit** triggers after user input and before entering the LLM. The following hook records the current working directory: ```python def context_inject_hook(query: str) -> str | None: @@ -130,7 +130,7 @@ register_hook("PreToolUse", log_hook) register_hook("PostToolUse", large_output_hook) ``` -**Stop**, triggers when the loop is about to exit (`stop_reason != "tool_use"`). The teaching version prints a cleanup summary: +**Stop** triggers when the loop is about to exit (`stop_reason != "tool_use"`). The following hook prints a cleanup summary: ```python def summary_hook(messages: list) -> str | None: @@ -220,64 +220,5 @@ The Agent can now safely execute operations. But does it ever stop to think "wha → s05 TodoWrite: Give the Agent a planning tool. Make a list first, then execute. -
-Dive into CC Source Code - -> The following is based on a complete analysis of CC source code `toolHooks.ts` (650 lines), `hooks.ts`, `stopHooks.ts`, and `coreTypes.ts`. - -### 1. Hook Events: Not Just 4, but 27 - -The teaching version covers only PreToolUse and PostToolUse. CC actually has 27 hook events (`coreTypes.ts:25-53`): - -| Category | Events | -|----------|--------| -| Tool-related | `PreToolUse`, `PostToolUse`, `PostToolUseFailure` | -| Session-related | `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `Setup` | -| User interaction | `UserPromptSubmit`, `Notification`, `PermissionRequest`, `PermissionDenied` | -| Sub-agents | `SubagentStart`, `SubagentStop` | -| Compaction-related | `PreCompact`, `PostCompact` | -| Team-related | `TeammateIdle`, `TaskCreated`, `TaskCompleted` | -| Other | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded`, `CwdChanged`, `FileChanged` | - -The teaching version covers only 4 core events (UserPromptSubmit, PreToolUse, PostToolUse, Stop) because they cover every critical node of a complete agent cycle. The other 23 follow the same pattern. - -### 2. HookResult Common Fields - -CC's `HookResult` (`types/hooks.ts:260-275`) has 14 fields. Common ones: - -| Field | Type | Purpose | -|-------|------|---------| -| `message` | Message | Optional UI message | -| `blockingError` | HookBlockingError | Blocking error → injected into conversation for model self-correction | -| `outcome` | success/blocking/non_blocking_error/cancelled | Execution result | -| `preventContinuation` | boolean | Prevent subsequent execution | -| `stopReason` | string | Stop reason description | -| `permissionBehavior` | allow/deny/ask/passthrough | Hook returns permission decision | -| `updatedInput` | Record | Modify tool input | -| `additionalContext` | string | Additional context | -| `updatedMCPToolOutput` | unknown | MCP tool output modification | - -### 3. Key Invariant: Hook 'allow' Cannot Bypass deny/ask Rules - -This is the most important security design in CC's permission system (`toolHooks.ts:325-331`): **when a hook returns allow, it still checks settings.json deny/ask rules.** Even if the user's hook script says "allow", if the tool is disabled in settings.json, the operation is still blocked. - -The teaching version doesn't have this layer; hooks returning non-None directly interrupt. This is sufficient for teaching, but would create a security vulnerability in production. - -### 4. stopHookActive Mechanism - -CC's Stop hooks have an infinite-loop prevention mechanism (`query.ts:212,1300`): the `stopHookActive` state field. When stop hooks produce a blockingError, the loop re-enters with `stopHookActive: true`. Subsequent iterations see this flag and don't trigger stop hooks again. This prevents a never-stopping bug: model self-corrects → stop hook errors again → model self-corrects again → stop hook errors again... - -### 5. hook_stopped_continuation - -When PostToolUse hooks return `preventContinuation: true`, a `hook_stopped_continuation` attachment is produced (`toolHooks.ts:117-130`). query.ts (L1388-1393) detects it and sets `shouldPreventContinuation = true`, causing the loop to exit. This is the mechanism for "hooks gracefully shut down the Agent" — not a crash, but a completion. - -### Teaching Version Simplifications Are Intentional - -- 27 events → 4 (UserPromptSubmit/PreToolUse/PostToolUse/Stop): covers agent cycle critical nodes -- 14 fields → simple return values (None = continue, non-None = interrupt/continue): minimal cognitive load -- Hook allow vs deny/ask invariant → omitted: teaching version has no settings.json layer -- stopHookActive → omitted: teaching version Stop hook only does simple continuation, no infinite-loop prevention needed - -
diff --git a/s04_hooks/README.zh.md b/s04_hooks/README.zh.md index d465ff35..719ac8f9 100644 --- a/s04_hooks/README.zh.md +++ b/s04_hooks/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → `s04` → [s05](../s05_todo_write/) → s06 → ... → s20 → s21 → s22 +s01 → s02 → s03 → `s04` → [s05](../s05_todo_write/) → s06 → ... → s20 → s21 > *"挂在循环上, 不写进循环里"* — hook 在工具执行前后注入扩展逻辑。 > @@ -48,7 +48,7 @@ s03 的循环和权限逻辑完全保留。唯一的变动是把 `check_permissi | UserPromptSubmit | 用户输入提交后、进入 LLM 前 | 输入验证、注入上下文 | | PreToolUse | 工具执行前 | 权限检查、日志记录 | | PostToolUse | 工具执行后 | 副作用(自动 git add 等)、输出检查 | -| Stop | 循环即将退出时 | 收尾清理(CC 还支持强制续跑) | +| Stop | 循环即将退出时 | 收尾清理、决定是否继续循环 | 扩展通过 `register_hook()` 添加,循环只调用 `trigger_hooks()`。 @@ -77,9 +77,9 @@ def trigger_hooks(event: str, *args): return None ``` -教学版中,PreToolUse 的非 None 返回值会阻止本次工具执行,Stop 的非 None 返回值会强制续跑。UserPromptSubmit 和 PostToolUse 的返回值未被使用。 +`PreToolUse` 返回非 `None` 时,本次工具执行被阻止;`Stop` 返回非 `None` 时,循环继续。`UserPromptSubmit` 和 `PostToolUse` 的返回值不参与控制流。 -**UserPromptSubmit**,用户输入提交后、进入 LLM 前触发。CC 中可以拦截或修改输入,教学版只做日志演示: +**UserPromptSubmit** 在用户输入提交后、进入 LLM 前触发。以下 hook 记录当前工作目录: ```python def context_inject_hook(query: str) -> str | None: @@ -130,7 +130,7 @@ register_hook("PreToolUse", log_hook) register_hook("PostToolUse", large_output_hook) ``` -**Stop**,循环即将退出时触发(`stop_reason != "tool_use"`)。教学版用于打印收尾统计: +**Stop** 在循环即将退出时触发(`stop_reason != "tool_use"`)。以下 hook 打印收尾统计: ```python def summary_hook(messages: list) -> str | None: @@ -220,64 +220,5 @@ Agent 现在能安全执行操作了。但它有没有停下来想过"我应该 s05 TodoWrite → 给 Agent 一个计划工具。先列清单,再做。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `toolHooks.ts`(650 行)、`hooks.ts`、`stopHooks.ts`、`coreTypes.ts` 的完整分析。 - -### 一、Hook 事件:不止这 4 个,而是 27 个 - -教学版只讲了 PreToolUse 和 PostToolUse。CC 实际有 27 个 hook 事件(`coreTypes.ts:25-53`): - -| 类别 | 事件 | -|------|------| -| 工具相关 | `PreToolUse`, `PostToolUse`, `PostToolUseFailure` | -| 会话相关 | `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `Setup` | -| 用户交互 | `UserPromptSubmit`, `Notification`, `PermissionRequest`, `PermissionDenied` | -| 子 Agent | `SubagentStart`, `SubagentStop` | -| 压缩相关 | `PreCompact`, `PostCompact` | -| 团队相关 | `TeammateIdle`, `TaskCreated`, `TaskCompleted` | -| 其他 | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded`, `CwdChanged`, `FileChanged` | - -教学版只讲 4 个核心事件(UserPromptSubmit、PreToolUse、PostToolUse、Stop),因为它们覆盖了一个完整 agent cycle 的关键节点。其他 23 个都是同样的模式。 - -### 二、HookResult 常用字段摘录 - -CC 的 `HookResult`(`types/hooks.ts:260-275`)有 14 个字段,以下是常用字段: - -| 字段 | 类型 | 用途 | -|------|------|------| -| `message` | Message | 可选 UI 消息 | -| `blockingError` | HookBlockingError | 阻塞错误 → 注入对话让模型自纠 | -| `outcome` | success/blocking/non_blocking_error/cancelled | 执行结果 | -| `preventContinuation` | boolean | 阻止后续执行 | -| `stopReason` | string | 停止原因描述 | -| `permissionBehavior` | allow/deny/ask/passthrough | hook 返回权限决策 | -| `updatedInput` | Record | 修改工具输入 | -| `additionalContext` | string | 附加上下文 | -| `updatedMCPToolOutput` | unknown | MCP 工具输出修改 | - -### 三、关键不变式:Hook 'allow' 不能绕过 deny/ask 规则 - -这是 CC 权限系统最重要的安全设计(`toolHooks.ts:325-331`):**hook 返回 allow 时,仍然要检查 settings.json 的 deny/ask 规则**。即使用户的 hook 脚本说"允许",如果在 settings.json 中禁用了这个工具,操作仍然会被阻止。 - -教学版没有这个层次,只把 PreToolUse 的非 None 返回值解释为阻止本次工具执行。这在教学场景中够了,但在生产环境中会形成安全漏洞。 - -### 四、stopHookActive 机制 - -CC 的 Stop hooks 有一个防无限循环机制(`query.ts:212,1300`):`stopHookActive` 状态字段。当 stop hooks 产生 blockingError 时,循环带 `stopHookActive: true` 重入下一轮。后续迭代中 stop hooks 看到这个标志就不会再次触发。这防止了一个永不停机的 bug:模型自纠后 stop hook 再次报错 → 模型再自纠 → stop hook 再报错... - -### 五、hook_stopped_continuation - -PostToolUse hooks 返回 `preventContinuation: true` 时,会产生一个 `hook_stopped_continuation` 附件(`toolHooks.ts:117-130`)。query.ts(L1388-1393)检测到后设置 `shouldPreventContinuation = true`,循环退出。这是 "hook 优雅地让 Agent 停机" 的机制,不是崩溃,是完成。 - -### 教学版的简化是刻意的 - -- 27 个事件 → 4 个(UserPromptSubmit/PreToolUse/PostToolUse/Stop):覆盖 agent cycle 关键节点 -- 14 个字段 → 简单的返回值(None = 继续,非 None = 阻止/续跑):心智负担降到最低 -- Hook allow vs deny/ask 不变式 → 省略:教学版没有 settings.json 层 -- stopHookActive → 省略:教学版 Stop hook 只做简单续跑,不涉及防无限循环机制 - -
diff --git a/s04_hooks/code.py b/s04_hooks/code.py index b676c31e..cbdf94f1 100644 --- a/s04_hooks/code.py +++ b/s04_hooks/code.py @@ -159,7 +159,7 @@ def register_hook(event: str, callback): def trigger_hooks(event: str, *args): for callback in HOOKS[event]: result = callback(*args) - if result is not None: # teaching shortcut: block this tool call + if result is not None: # A hook result blocks this tool call. return result return None diff --git a/s04_hooks/images/hooks-overview.en.svg b/s04_hooks/images/hooks-overview.en.svg index 87afdc0c..14f725e8 100644 --- a/s04_hooks/images/hooks-overview.en.svg +++ b/s04_hooks/images/hooks-overview.en.svg @@ -57,7 +57,7 @@ PreToolUse permission_hook · log_hook - Teaching: non-None → block + non-None → block diff --git a/s04_hooks/images/hooks-overview.ja.svg b/s04_hooks/images/hooks-overview.ja.svg index d1addf60..5f00d1c5 100644 --- a/s04_hooks/images/hooks-overview.ja.svg +++ b/s04_hooks/images/hooks-overview.ja.svg @@ -57,7 +57,7 @@ PreToolUse permission_hook · log_hook - 教育版: 非 None → ブロック + 非 None → ブロック diff --git a/s04_hooks/images/hooks-overview.svg b/s04_hooks/images/hooks-overview.svg index 410593af..934df956 100644 --- a/s04_hooks/images/hooks-overview.svg +++ b/s04_hooks/images/hooks-overview.svg @@ -57,7 +57,7 @@ PreToolUse permission_hook · log_hook - 教学版:非 None → 阻止 + 非 None → 阻止 diff --git a/s05_todo_write/README.ja.md b/s05_todo_write/README.ja.md index c242fb48..92122b34 100644 --- a/s05_todo_write/README.ja.md +++ b/s05_todo_write/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → `s05` → [s06](../s06_subagent/) → s07 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → `s05` → [s06](../s06_subagent/) → s07 → ... → s20 → s21 > *"計画なき agent は風の向くままに"* — まず手順を列挙してから実行。長いタスクで見落としが減る。 > @@ -81,7 +81,7 @@ TOOLS = [ TOOL_HANDLERS["todo_write"] = run_todo_write ``` -**Nag リマインダー**、モデルが連続 3 ラウンド `todo_write` を呼び出さないとき、リマインダーが自動的に注入される(教育用機構、CC ソースコードに固定ラウンド数のロジックはない): +**Nag リマインダー**:モデルが 3 ラウンド連続で `todo_write` を呼び出さなかった場合、リマインダーが自動的に注入される: ```python if rounds_since_todo >= 3 and messages: @@ -132,27 +132,5 @@ Agent は計画できるようになった。しかしタスクが大きすぎ → s06 Subagent:大きなタスクをサブタスクに分割し、それぞれを独立した Agent に任せる。それぞれが独自のクリーンなコンテキストを持ち、相互汚染がない。 -
-CC ソースコードを深掘り - -Claude Code には、目的は近いがストレージとツール契約が独立した二つの計画機構がある: - -- **TodoWrite**:現在のセッション向けの軽量チェックリスト。呼び出しごとにリスト全体を置き換え、教育版もプロセスメモリに保持して終了時に消える -- **Task ツール(s12)**:安定 ID を持つ個別タスクレコードで、依存関係、ownership、永続化を扱う - -現在の対話型セッションは構造化 Task ツールを既定で使い、TodoWrite は非対話型や Agent SDK などの互換サーフェスに残る。公開範囲はリリースや設定で変わり得る。同じ schema のインプレース更新ではなく独立した機構であり、s05 は軽量なチェックリスト契約だけを扱う。 - -教育版は実際のソースコードにある `activeForm` フィールドを省略している(`utils/todo/types.ts:8-15`)。CC は UI スピナーに「何をしているか」を表示するために使用するが、教育版は端末出力のみでこのフィールドは不要。 - -教育版の Nag リマインダー(3 ラウンド未更新で注入)は教育用機構。CC ソースコードに固定「3 ラウンド」のロジックはなく、最も近いのは `TodoWriteTool.ts:72-107` で 3 つ以上の todo が全て完了しているのに verification 項目がない場合に verification nudge を追加する処理。 - -Task System の TodoWrite に対する核心的な増分: -- メモリリストではなくファイル永続化(Claude 設定ディレクトリ下 `tasks/{taskListId}/{taskId}.json`) -- 平坦なリストではなく `blockedBy` 依存グラフ -- ロックなしではなく `proper-lockfile` による並行安全性 -- 一つのツールではなく四つの独立ツール(Create/Get/Update/List) -- TaskCreated / TaskCompleted フック(`TaskCreateTool.ts:80-129`、`TaskUpdateTool.ts:231-260`)による外部システム統合 - -
diff --git a/s05_todo_write/README.md b/s05_todo_write/README.md index 8d94bc45..029e53fe 100644 --- a/s05_todo_write/README.md +++ b/s05_todo_write/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → `s05` → [s06](../s06_subagent/) → s07 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → `s05` → [s06](../s06_subagent/) → s07 → ... → s20 → s21 > *"An agent without a plan goes wherever the wind blows"* — List the steps first, then execute. Complex tasks are less likely to miss steps. > @@ -81,7 +81,7 @@ TOOLS = [ TOOL_HANDLERS["todo_write"] = run_todo_write ``` -**Nag reminder**, when the model hasn't called `todo_write` for 3 consecutive rounds, a reminder is automatically injected (teaching mechanism; CC source has no fixed round-count logic): +**Nag reminder**: when the model has not called `todo_write` for 3 consecutive rounds, a reminder is automatically injected: ```python if rounds_since_todo >= 3 and messages: @@ -132,27 +132,5 @@ The Agent can plan now. But if a task is too large, say "refactor the entire aut → s06 Subagent: Break large tasks into subtasks, each handled by an independent Agent with its own clean context, no cross-contamination. -
-Dive into CC Source Code - -Claude Code has two planning surfaces with a shared intent but independent storage and tool contracts: - -- **TodoWrite**: A session checklist. Each call replaces the whole list, and the teaching version likewise keeps it in process memory and clears it on exit. -- **Task tools (covered in s12)**: Individually addressable task records with stable IDs, dependency fields, ownership, and persistence. - -Current interactive sessions use the structured Task tools by default, while TodoWrite remains available on compatibility surfaces such as non-interactive and Agent SDK usage. Exact exposure can vary by release and configuration. Do not model this as one schema being upgraded in place: they are separate mechanisms, and s05 teaches the lighter checklist contract. - -The teaching version omits the `activeForm` field from the real source (`utils/todo/types.ts:8-15`). CC uses it for the UI spinner to show "what's being done"; the teaching version only has terminal output and doesn't need this field. - -The teaching version's nag reminder (3 rounds without update triggers injection) is an educational mechanism. The CC source has no fixed "3 rounds" logic; the closest is `TodoWriteTool.ts:72-107` which appends a verification nudge when 3+ todos are all completed without a verification item. - -Core increments of the Task System over TodoWrite: -- File persistence (Claude config directory `tasks/{taskListId}/{taskId}.json`) instead of in-memory list -- `blockedBy` dependency graph instead of flat list -- `proper-lockfile` concurrency safety instead of no locking -- Four separate tools (Create/Get/Update/List) instead of one -- TaskCreated / TaskCompleted hooks (`TaskCreateTool.ts:80-129`, `TaskUpdateTool.ts:231-260`) for external system integration - -
diff --git a/s05_todo_write/README.zh.md b/s05_todo_write/README.zh.md index 60034320..1b1bb2a0 100644 --- a/s05_todo_write/README.zh.md +++ b/s05_todo_write/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → `s05` → [s06](../s06_subagent/) → s07 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → `s05` → [s06](../s06_subagent/) → s07 → ... → s20 → s21 > *"没有计划的 agent 走哪算哪"* — 先列步骤再动手,长任务更不容易漏项。 > @@ -81,7 +81,7 @@ TOOLS = [ TOOL_HANDLERS["todo_write"] = run_todo_write ``` -**Nag reminder**,模型连续 3 轮没调 `todo_write` 时,自动注入一条提醒(教学版机制,CC 源码中没有这个固定轮数逻辑): +**Nag reminder**:模型连续 3 轮未调用 `todo_write` 时,自动注入提醒: ```python if rounds_since_todo >= 3 and messages: @@ -132,27 +132,5 @@ Agent 能计划了。但如果一个任务太大,比如"重构整个认证模 s06 Subagent → 把大任务拆成子任务,每个子任务派一个独立的 Agent。它们有自己的干净上下文,不会互相污染。 -
-深入 CC 源码 - -Claude Code 有两种目标相近、但存储与工具契约相互独立的规划机制: - -- **TodoWrite**:当前会话的轻量清单。每次调用替换整个列表;教学版同样保存在进程内存,退出后清空 -- **Task 工具(s12)**:带稳定 ID 的独立任务记录,支持依赖、ownership 与持久化 - -当前交互式会话默认使用结构化 Task 工具;TodoWrite 仍保留在非交互式、Agent SDK 等兼容表面。具体暴露方式会随版本与配置变化。不要把它理解成同一个 schema 原地升级:两者是独立机制,s05 只教授较轻的清单契约。 - -教学版省略了真实源码中的 `activeForm` 字段(`utils/todo/types.ts:8-15`)。CC 用它给 UI spinner 展示"正在做什么",教学版只有终端输出,不需要这个字段。 - -教学版的 nag reminder(3 轮未更新就注入提醒)是教学机制。CC 源码中没有固定的"3 轮"逻辑,更接近的是 `TodoWriteTool.ts:72-107` 中当 3 个以上 todo 全部完成但没有 verification 项时,追加 verification nudge。 - -Task System 相比 TodoWrite 的核心增量: -- 文件持久化(Claude 配置目录下 `tasks/{taskListId}/{taskId}.json`)而非内存列表 -- `blockedBy` 依赖图而非平铺列表 -- `proper-lockfile` 并发安全而非无锁 -- 四个独立工具(Create/Get/Update/List)而非一个 -- TaskCreated / TaskCompleted hooks(`TaskCreateTool.ts:80-129`、`TaskUpdateTool.ts:231-260`)供外部系统集成 - -
diff --git a/s06_subagent/README.ja.md b/s06_subagent/README.ja.md index 55dc167c..de706a14 100644 --- a/s06_subagent/README.ja.md +++ b/s06_subagent/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → `s06` → [s07](../s07_skill_loading/) → s08 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → `s06` → [s07](../s07_skill_loading/) → s08 → ... → s20 → s21 > *"大きなタスクは小さく、小さなタスクごとにクリーンなコンテキスト"* — Subagent は独立した messages[] を使い、メイン会話を汚染しない。 > @@ -131,59 +131,5 @@ Agent はタスクを分割できるようになった。しかし各タスク → s07 Skill Loading:スキルをオンデマンドで注入する。system prompt にドキュメントを積み上げるのではなく、必要なときだけ読み込む。ファイルを読むのと同じくらい自然に。 -
-CC ソースコードを深掘り - -> 以下は CC ソースコード `AgentTool.tsx`、`runAgent.ts`、`forkSubagent.ts`、`forkedAgent.ts` の完全分析に基づく。 - -### 一、一つのパターンではなく三つ - -教育版は「新規 messages[]」のみを取り上げる。CC には実際に三つの実行モードがある: - -| モード | トリガー | コンテキスト | -|--------|---------|-------------| -| **Normal Subagent** | `subagent_type` 指定時(normal path) | 新規 messages[]、プロンプトのみ | -| **Fork Subagent** | `subagent_type` 未指定、fork gate 有効時 | `buildForkedMessages()` でキャッシュフレンドリーなプレフィックスを構築、プロンプトキャッシュを共有 | -| **General-Purpose** | `subagent_type` 未指定、fork gate 無効時 | Normal と同じ | - -### 二、Fork モード:プロンプトキャッシュの共有のため - -これは教育版にはない核心概念。Fork モード(`forkSubagent.ts:60-71`)は新規コンテキストを作成せず、`buildForkedMessages()`(`forkSubagent.ts:107-168`)でキャッシュフレンドリーなメッセージプレフィックスを構築する。親の assistant message を保持し、placeholder tool results を生成する。目的は隔離ではなく、Anthropic API のプロンプトキャッシュをヒットさせること:親子 Agent の system prompt、tools、messages プレフィックスがバイトレベルで一致するため、API 側で再計算が不要になる。 - -キャッシュヒットの五つの重要コンポーネント(`forkedAgent.ts:57-68`):system prompt、tools、model、messages プレフィックス、thinking config、バイトレベルで一致する必要がある。 - -### 三、コンテキスト隔離の精密な粒度 - -`createSubagentContext()`(`forkedAgent.ts:345-462`)はサブエージェントの `ToolUseContext` を作成: - -| フィールド | 挙動 | -|-----------|------| -| `abortController` | 新しい子コントローラ、親の abort は下に伝播 | -| `setAppState` | デフォルトは no-op、ただし sync agent は `shareSetAppState` で共有(`runAgent.ts:697-714`) | -| `readFileState` | **親からクローン**(同じファイルの再読み込みを回避) | -| `queryTracking` | 新しい chainId、`depth = parentDepth + 1` | - -サブエージェントは完全に隔離されているわけではない。ファイル読み取り状態は共有される。UI と通知の隔離度は実行パスにより異なる(sync/async/fork/teammate でそれぞれ異なる)。 - -### 四、再帰 Fork 防護 - -教育版は「サブエージェントに task ツールなし」で再帰防止を表現する。実際の実装はより精密:`isInForkChild()`(`forkSubagent.ts:78-89`)が会話履歴内の `FORK_BOILERPLATE_TAG` をチェックする。しかし `constants/tools.ts:36-46` では `Agent` ツールが全エージェントの無効セットにデフォルト設定(`USER_TYPE === 'ant'` 時は例外)、`forkSubagent.ts:73-89` は fork child 向けの専用再帰保護があり、`agentToolUtils.ts:100-110` は teammate シナリオで特別な許可がある。単純な「サブエージェントの再 spawn 禁止」ではない。 - -### 五、Permission Bubbling - -Fork Agent の `permissionMode: 'bubble'`(`forkSubagent.ts:67`)は、サブエージェントの権限プロンプトが親ターミナルにバブルアップすることを意味する。ユーザーはメインターミナルでサブエージェントの操作を承認する。 - -### 六、Async vs Sync - -教育版は同期サブエージェントのみ(親が子の完了を待つ)を示す。CC は非同期パスもサポート(`AgentTool.tsx:686-764`):`run_in_background: true` の場合、サブエージェントは非同期で起動し、`{ status: 'async_launched' }` を直ちに親に返し、完了時に通知機構で親に知らせる。実際のトリガーは `run_in_background` だけでなく、auto-background、assistant force async、coordinator/proactive パスもある。 - -### 教育版の簡略化は意図的 - -- 三つのモード → 一つ(新規 messages):概念的に明確 -- プロンプトキャッシュ共有 → 省略:教育版は API 層の最適化を扱わない -- 再帰 fork 防護 → 「サブエージェントに task ツールなし」に簡略化 -- Async → 省略(s13 に委ねる):s06 はまず同期モデルを理解する - -
diff --git a/s06_subagent/README.md b/s06_subagent/README.md index 456727ac..3f000446 100644 --- a/s06_subagent/README.md +++ b/s06_subagent/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → `s06` → [s07](../s07_skill_loading/) → s08 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → `s06` → [s07](../s07_skill_loading/) → s08 → ... → s20 → s21 > *"Break large tasks small, each with clean context"* — Subagent uses an independent messages[], no pollution in the main conversation. > @@ -131,59 +131,5 @@ The Agent can now break tasks apart. But different tasks require different knowl → s07 Skill Loading: Inject skills on demand instead of piling documents into the system prompt. Load only when needed, as natural as reading a file. -
-Dive into CC Source Code - -> The following is based on a complete analysis of CC source code `AgentTool.tsx`, `runAgent.ts`, `forkSubagent.ts`, and `forkedAgent.ts`. - -### 1. Not One Pattern, but Three - -The teaching version covers only "fresh messages[]". CC actually has three execution modes: - -| Mode | Trigger | Context | -|------|---------|---------| -| **Normal Subagent** | `subagent_type` specified (normal path) | Truly fresh messages[], only the prompt | -| **Fork Subagent** | No `subagent_type`, fork gate enabled | Constructs cache-friendly prefix via `buildForkedMessages()`, shares prompt cache | -| **General-Purpose** | No `subagent_type`, fork gate disabled | Same as Normal | - -### 2. Fork Mode: Sharing Prompt Cache - -This is a core concept the teaching version omits. Fork mode (`forkSubagent.ts:60-71`) doesn't create a fresh context. Instead, it constructs a cache-friendly message prefix via `buildForkedMessages()` (`forkSubagent.ts:107-168`), preserving the parent assistant message and generating placeholder tool results. The goal isn't isolation, but making the Anthropic API's prompt cache hit: parent and child Agent's system prompt, tools, and message prefix are byte-identical, so the API doesn't need to recompute. - -Five key components for cache hit (`forkedAgent.ts:57-68`): system prompt, tools, model, message prefix, thinking config, must be byte-identical. - -### 3. Context Isolation's Precise Granularity - -`createSubagentContext()` (`forkedAgent.ts:345-462`) creates the sub-Agent's `ToolUseContext`: - -| Field | Behavior | -|-------|----------| -| `abortController` | New child controller; parent abort propagates down | -| `setAppState` | Default no-op; but sync agents share via `shareSetAppState` (`runAgent.ts:697-714`) | -| `readFileState` | **Cloned from parent** (avoids re-reading same files) | -| `queryTracking` | New chainId, `depth = parentDepth + 1` | - -The sub-Agent isn't fully isolated: file read state is shared. The degree of UI and notification isolation varies by execution path (sync/async/fork/teammate differ). - -### 4. Recursive Fork Protection - -The teaching version uses "sub-Agent has no task tool" for recursion protection. The real implementation is more nuanced: `isInForkChild()` (`forkSubagent.ts:78-89`) checks for `FORK_BOILERPLATE_TAG` in history. But `constants/tools.ts:36-46` defaults `Agent` to all agents' disabled set (with `USER_TYPE === 'ant'` exception); `forkSubagent.ts:73-89` has fork-child-specific recursion protection; `agentToolUtils.ts:100-110` has special allowances in teammate scenarios. Not simply "no further sub-Agents." - -### 5. Permission Bubbling - -Fork Agent's `permissionMode: 'bubble'` (`forkSubagent.ts:67`) means the sub-Agent's permission prompts bubble up to the parent terminal: the user approves sub-Agent operations in the main terminal. - -### 6. Async vs Sync - -The teaching version only shows synchronous sub-Agents (parent waits for child to finish). CC also supports async paths (`AgentTool.tsx:686-764`): when `run_in_background: true`, the sub-Agent launches asynchronously, returning `{ status: 'async_launched' }` immediately to the parent, and notifies the parent when complete. Actual triggers go beyond `run_in_background`, including auto-background, assistant force async, and coordinator/proactive paths. - -### Teaching Version Simplifications Are Intentional - -- Three modes → one (fresh messages): conceptually clear -- Prompt cache sharing → omitted: teaching version doesn't involve API-layer optimization -- Recursive fork protection → simplified to "sub-Agent has no task tool" -- Async → omitted (left for s13): s06 focuses on the synchronous model first - -
diff --git a/s06_subagent/README.zh.md b/s06_subagent/README.zh.md index a921fff4..2dc3fa22 100644 --- a/s06_subagent/README.zh.md +++ b/s06_subagent/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → `s06` → [s07](../s07_skill_loading/) → s08 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → `s06` → [s07](../s07_skill_loading/) → s08 → ... → s20 → s21 > *"大任务拆小, 每个小任务干净的上下文"* — Subagent 用独立 messages[], 不污染主对话。 > @@ -135,59 +135,5 @@ Agent 现在能拆任务了。但每个任务需要的知识不一样:改前 s07 Skill Loading → 技能按需注入,不在 system prompt 里堆文档。用到的时候才加载,和读文件一样自然。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `AgentTool.tsx`、`runAgent.ts`、`forkSubagent.ts`、`forkedAgent.ts` 的完整分析。 - -### 一、不是一种模式,是三种 - -教学版只讲了"全新的 messages[]"。CC 实际有三种执行模式: - -| 模式 | 触发条件 | 上下文 | -|------|---------|--------| -| **Normal Subagent** | 指定了 `subagent_type`(normal path) | 全新 messages[],只有 prompt | -| **Fork Subagent** | 没指定 `subagent_type`,fork gate 开启 | 通过 `buildForkedMessages()` 构造 cache-friendly 前缀,共享 prompt cache | -| **General-Purpose** | 没指定 `subagent_type`,fork gate 关闭 | 同 Normal | - -### 二、Fork 模式:为了共享 Prompt Cache - -这是教学版没有的核心概念。Fork 模式(`forkSubagent.ts:60-71`)不创建全新上下文,而是通过 `buildForkedMessages()`(`forkSubagent.ts:107-168`)构造 cache-friendly 消息前缀,保留父 assistant message 并生成 placeholder tool results。目的不是隔离,而是让 Anthropic API 的 prompt cache 命中:父子 Agent 的 system prompt、tools、messages 前缀完全一致,API 端不需要重算。 - -缓存命中的五个关键组件(`forkedAgent.ts:57-68`):system prompt、tools、model、messages 前缀、thinking config,必须字节级一致。 - -### 三、Context Isolation 的精确粒度 - -`createSubagentContext()`(`forkedAgent.ts:345-462`)创建子 Agent 的 `ToolUseContext`: - -| 字段 | 行为 | -|------|------| -| `abortController` | 新的 child controller,父 abort 向下传播 | -| `setAppState` | 默认 no-op;但 sync agent 通过 `shareSetAppState` 共享(`runAgent.ts:697-714`) | -| `readFileState` | **从父克隆**(避免重复读相同文件) | -| `queryTracking` | 新 chainId,`depth = parentDepth + 1` | - -子 Agent 不是完全隔离的:文件读取状态是共享的。UI 和通知的隔离程度取决于执行路径(sync/async/fork/teammate 各不同)。 - -### 四、递归 Fork 防护 - -教学版用"子 Agent 不给 task 工具"表达递归保护。真实实现更精细:`isInForkChild()`(`forkSubagent.ts:78-89`)检查对话历史中是否有 `FORK_BOILERPLATE_TAG`,有就拒绝。但 `constants/tools.ts:36-46` 中 `Agent` 工具默认在所有 agent 的禁用集合里,`USER_TYPE === 'ant'` 时例外;`forkSubagent.ts:73-89` 针对 fork child 有专门的递归保护;`agentToolUtils.ts:100-110` 在 teammate 场景下有特殊放行。不是简单的"禁止新的子 Agent"。 - -### 五、Permission Bubbling - -Fork Agent 的 `permissionMode: 'bubble'`(`forkSubagent.ts:67`)意味着子 Agent 的权限弹窗冒泡到父终端,用户在主终端里审批子 Agent 的操作。 - -### 六、Async vs Sync - -教学版只展示了同步子 Agent(父等着子跑完)。CC 还支持异步路径(`AgentTool.tsx:686-764`):`run_in_background: true` 时异步启动,返回 `{ status: 'async_launched' }` 立即给父 Agent,子 Agent 完成后通过通知机制告知父 Agent。实际触发条件不止 `run_in_background`,还有 auto-background、assistant force async、coordinator/proactive 等路径。 - -### 教学版的简化是刻意的 - -- 三种模式 → 一种(fresh messages):概念清晰 -- Prompt cache 共享 → 省略:教学版不涉及 API 层优化 -- 递归 fork 防护 → 简化为"子 Agent 无 task 工具" -- Async → 省略(留给 s13):s06 先理解同步模型 - -
diff --git a/s07_skill_loading/README.ja.md b/s07_skill_loading/README.ja.md index d458137e..5f702a51 100644 --- a/s07_skill_loading/README.ja.md +++ b/s07_skill_loading/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](../s08_context_compact/) → s09 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](../s08_context_compact/) → s09 → ... → s20 → s21 > *"Load when needed, don't stuff the prompt"* — tool_result で注入、system prompt には詰め込まない。 > > **Harness レイヤー**: 知識 — 必要に応じて読み込み、コンテキストに詰め込まない。 @@ -139,44 +139,5 @@ python s07_skill_loading/code.py → s08 Context Compact:4 層圧縮戦略。安価な層を先に実行、高価な層を後に実行。 -
-CC ソースコードを深掘り - -> 以下は CC ソースコード `loadSkillsDir.ts`、`SkillTool.ts`、`bundledSkills.ts`、`commands.ts` の分析に基づく。 - -### 一、スキルソース:skills/ ディレクトリだけではない - -教育版はすべてのスキルが `skills/` ディレクトリにあると想定している。CC は実際に複数のファイルに分散したソースから読み込む:`loadSkillsDir.ts` は user/project/`--add-dir` ディレクトリと legacy commands(`.claude/commands/`)を担当、`bundledSkills.ts` は組み込みスキル、`SkillTool.ts` は MCP リモートスキル、`commands.ts` はコマンド集約を担当。タイプには managed/policy skills、user skills(`~/.claude/skills/`)、project skills(`.claude/skills/`)、`--add-dir` skills、legacy commands、dynamic skills、conditional skills(`paths` frontmatter を持ち、ファイルパスでアクティベート)、bundled skills、plugin skills、MCP skills が含まれる。 - -### 二、SKILL.md Frontmatter の一般的なフィールド - -CC の SKILL.md YAML frontmatter は `parseSkillFrontmatterFields()`(`loadSkillsDir.ts`)で解析される。一般的なフィールド: - -| フィールド | 用途 | -|-----------|------| -| `name` / `description` | 表示名と説明 | -| `when_to_use` | モデルにいつ呼び出すかを指導 | -| `allowed-tools` | スキルが使用可能なツールの自動許可リスト | -| `context` | `inline`(デフォルト)または `fork`(サブ Agent として実行) | -| `model` | モデルオーバーライド(haiku/sonnet/opus/inherit) | -| `hooks` | スキルレベルのフック設定 | -| `paths` | 条件付きアクティベーションの glob パターン | -| `user-invocable` | ユーザーが `/name` で呼び出し可能 | - -完全なフィールドリストはバージョンによって変動する。上記は教育版に関連するコアフィールドのみ。 - -### 三、2 層読み込みの正確な実装 - -1. **カタログ(起動時)**:`getSkillDirCommands()` がディレクトリをスキャン → メタデータのみを含む `Command` オブジェクトとして登録。`getSkillListingAttachments()` がスキルリストを添付ファイルとしてフォーマット、コンテキストウィンドウの ~1% を予算とする(上限 8000 文字)。 -2. **読み込み(呼び出し時)**:モデルが `Skill` ツールを呼び出す(入力フィールドは `skill` + オプションの `args`、教育版は `name` を使用)→ `getPromptForCommand()` が完全な SKILL.md 内容を展開 → `SkillTool` が返す tool_result の表示テキストは `"Launching skill: {name}"` のみ、実際のスキル内容は `newMessages` を通じて注入される。教育版では両者を「tool_result を通じて注入」として簡略化している。読み込まれた SKILL.md は、モデルが後続で既存の file/bash ツールから関連リソースへアクセスする際の手がかりにもなる。 - -### 教育版の単純化は意図的 - -- 複数ファイル・複数ソース → 1 つの `skills/` ディレクトリ:2 層読み込みの核心概念を示すのに十分 -- 複数の frontmatter フィールド → name/description のみ解析:解析の複雑さを削減 -- forked skills(`context: 'fork'`)→ 省略:教育版では inline skill loading のみ展開する -- `Skill` ツールの入力 `skill`+`args` → 教育版は `name` を使用:追加の引数解析の複雑さを回避 - -
diff --git a/s07_skill_loading/README.md b/s07_skill_loading/README.md index a5c09d13..93d304d2 100644 --- a/s07_skill_loading/README.md +++ b/s07_skill_loading/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](../s08_context_compact/) → s09 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](../s08_context_compact/) → s09 → ... → s20 → s21 > *"Load when needed, don't stuff the prompt"* — Inject via tool_result, not system prompt. > > **Harness Layer**: Knowledge — load on demand, don't fill the context. @@ -139,44 +139,5 @@ On-demand loading solved "don't carry what you shouldn't." But another problem l → s08 Context Compact: A four-layer compaction strategy. Cheap layers run first, expensive layers run last. -
-Dive into CC Source Code - -> The following is based on analysis of CC source code `loadSkillsDir.ts`, `SkillTool.ts`, `bundledSkills.ts`, `commands.ts`. - -### 1. Skill Sources: Not Just One skills/ Directory - -The teaching version assumes all skills live in a `skills/` directory. CC loads from multiple sources spread across multiple files: `loadSkillsDir.ts` handles user/project/`--add-dir` directories and legacy commands (`.claude/commands/`); `bundledSkills.ts` handles built-in skills; `SkillTool.ts` handles MCP remote skills; `commands.ts` handles command aggregation. Types include managed/policy skills, user skills (`~/.claude/skills/`), project skills (`.claude/skills/`), `--add-dir` skills, legacy commands, dynamic skills, conditional skills (with `paths` frontmatter, activated by file path), bundled skills, plugin skills, MCP skills. - -### 2. SKILL.md Frontmatter — Common Fields - -CC's SKILL.md YAML frontmatter is parsed by `parseSkillFrontmatterFields()` in `loadSkillsDir.ts`. Common fields include: - -| Field | Purpose | -|-------|---------| -| `name` / `description` | Display name and description | -| `when_to_use` | Guides the model on when to invoke | -| `allowed-tools` | Auto-allow list of tools available to the skill | -| `context` | `inline` (default) or `fork` (run as sub-Agent) | -| `model` | Model override (haiku/sonnet/opus/inherit) | -| `hooks` | Skill-level hook configuration | -| `paths` | Glob patterns for conditional activation | -| `user-invocable` | Users can invoke via `/name` | - -The complete field list changes across versions; above are the core fields relevant to the teaching version. - -### 3. Precise Implementation of Two-Level Loading - -1. **Catalog (at startup)**: `getSkillDirCommands()` scans directory → registers as `Command` objects containing only metadata. `getSkillListingAttachments()` formats the skill list as attachments, budgeted at ~1% of the context window (cap 8000 characters). -2. **Load (on invocation)**: Model calls `Skill` tool (input fields are `skill` + optional `args`; teaching version uses `name`) → `getPromptForCommand()` expands full SKILL.md content → `SkillTool` returns a tool_result with display text `"Launching skill: {name}"`, while the actual skill content is injected via `newMessages`. The teaching version merges both into "injected via tool_result" as a simplification; the loaded SKILL.md can still guide later access to referenced resources through existing file/bash tools. - -### The Teaching Version's Simplification Is Intentional - -- Multiple files and sources → 1 `skills/` directory: sufficient to demonstrate the core concept of two-level loading -- Multiple frontmatter fields → only parse name/description: reduces parsing complexity -- Forked skills (`context: 'fork'`) → omitted: the teaching version only expands inline skill loading -- `Skill` tool input `skill`+`args` → teaching version uses `name`: avoids extra argument parsing complexity - -
diff --git a/s07_skill_loading/README.zh.md b/s07_skill_loading/README.zh.md index abb94546..01f87d04 100644 --- a/s07_skill_loading/README.zh.md +++ b/s07_skill_loading/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](../s08_context_compact/) → s09 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](../s08_context_compact/) → s09 → ... → s20 → s21 > *"用到时再加载, 别全塞 prompt 里"* — 通过 tool_result 注入, 不塞 system prompt。 > > **Harness 层**: 知识 — 按需加载, 不堆满上下文。 @@ -139,44 +139,5 @@ python s07_skill_loading/code.py s08 Context Compact → 四层压缩策略。便宜的先跑,贵的后跑。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `loadSkillsDir.ts`、`SkillTool.ts`、`bundledSkills.ts`、`commands.ts` 的分析。 - -### 一、技能来源:不是只有一个 skills/ 目录 - -教学版假设所有技能在 `skills/` 目录下。CC 实际从多个来源加载,分布在多个文件中:`loadSkillsDir.ts` 负责从 user/project/`--add-dir` 目录和 legacy commands(`.claude/commands/`)加载;`bundledSkills.ts` 负责内置技能;`SkillTool.ts` 处理 MCP 远程技能;`commands.ts` 负责命令聚合。类型包括 managed/policy skills、user skills(`~/.claude/skills/`)、project skills(`.claude/skills/`)、`--add-dir` skills、legacy commands、dynamic skills、conditional skills(带 `paths` frontmatter,按文件路径激活)、bundled skills、plugin skills、MCP skills。 - -### 二、SKILL.md Frontmatter 常见字段 - -CC 的 SKILL.md YAML frontmatter 由 `parseSkillFrontmatterFields()` 解析(`loadSkillsDir.ts`),常见字段包括: - -| 字段 | 用途 | -|------|------| -| `name` / `description` | 显示名称和描述 | -| `when_to_use` | 指导模型何时调用 | -| `allowed-tools` | 技能可用工具的自动允许列表 | -| `context` | `inline`(默认)或 `fork`(作为子 Agent 运行) | -| `model` | 模型覆盖(haiku/sonnet/opus/inherit) | -| `hooks` | 技能级别的 hook 配置 | -| `paths` | 条件激活的 glob 模式 | -| `user-invocable` | 用户可以通过 `/name` 调用 | - -完整字段列表随版本迭代会变化,以上仅列出教学版涉及的核心字段。 - -### 三、两级加载的精确实现 - -1. **Catalog(启动时)**:`getSkillDirCommands()` 扫描目录 → 注册为 `Command` 对象,只包含元数据。`getSkillListingAttachments()` 把技能列表格式化为附件,预算为上下文窗口的 ~1%(上限 8000 字符)。 -2. **Load(调用时)**:模型调 `Skill` 工具(输入字段是 `skill` + 可选 `args`,教学版用 `name`)→ `getPromptForCommand()` 展开完整 SKILL.md 内容 → `SkillTool` 返回的 tool_result 展示文本只是 `"Launching skill: {name}"`,真正的技能内容通过 `newMessages` 注入对话。教学版把两者合并为"通过 tool_result 注入"是一种简化;加载后的 SKILL.md 仍可作为指引,帮助模型后续通过现有 file/bash 工具访问相关资源。 - -### 教学版的简化是刻意的 - -- 多文件多来源 → 1 个 `skills/` 目录:足以展示两级加载的核心概念 -- 多个 frontmatter 字段 → 只解析 name/description:减少解析复杂度 -- forked skills(`context: 'fork'`)→ 省略:教学版只展开 inline 技能加载 -- `Skill` 工具输入 `skill`+`args` → 教学版用 `name`:避免参数解析的额外复杂度 - -
diff --git a/s08_context_compact/README.ja.md b/s08_context_compact/README.ja.md index 967039c1..43fba673 100644 --- a/s08_context_compact/README.ja.md +++ b/s08_context_compact/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](../s09_memory/) → s10 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](../s09_memory/) → s10 → ... → s20 → s21 > *"Context will fill up — have a way to make room"* — 4層圧縮戦略、安価なものを先に、高価なものを後に実行。 > > **Harness レイヤー**: 圧縮 — クリーンな記憶、無限のセッション。 @@ -120,9 +120,9 @@ def tool_result_budget(messages, max_bytes=200_000): 3 ステップのフロー: -1. **transcript を保存**:完全な会話を `.transcripts/` に JSONL 形式で書き出す。transcript は回復可能な記録として保存されるが、モデルのアクティブなコンテキストには要約しか残らない。モデルの現在の推論にとって、詳細はすでにコンテキストにない。教学コードは transcript 検索ツールを提供しない。 +1. **transcript を保存**:完全な会話を `.transcripts/` に JSONL 形式で書き出す。transcript は完全な記録を保持する。メッセージリストには要約だけが残り、元の詳細は以降のモデル呼び出しに入らない。 2. **LLM で要約を生成**:会話履歴を LLM に送り、現在の目標、重要な発見、変更済みファイル、残りの作業、ユーザーの制約などの重要な情報を保持するよう指示。 -3. **メッセージリストを置換**:すべての古いメッセージが 1 件の要約に置き換えられる。教学版は要約のみを保持する。実際の Claude Code は compact 後に直近のファイル、計画、agent/skill/tool などのコンテキストを再付加する。 +3. **メッセージリストを置換**:すべての古いメッセージを 1 件の要約に置き換える。 ```python def compact_history(messages): @@ -189,7 +189,7 @@ def agent_loop(messages): break # 現在のターンを終了し、圧縮後のコンテキストで新しく開始 ``` -**順序は変えられない。** L3(budget)が L2(micro)の前に実行される理由:micro は古い大きな tool_result を 1 行のプレースホルダに置換するため、budget はその前に完全な内容を退避させる必要がある。CC ソースが `applyToolResultBudget` を最初に配置する理由も同じ。 +**順序は変えられない。** L3(budget)は L2(micro)より先に実行する。micro が古い大きな `tool_result` を 1 行のプレースホルダに置き換える前に、budget が完全な内容を保存する必要があるためだ。 --- @@ -228,85 +228,5 @@ python s08_context_compact/code.py s09 Memory → 3 つのサブシステム:何を記憶するかの選択、重要情報の抽出、整理と統合。圧縮を越え、セッションを越えて。 -
-CC ソースコードの詳細 - -> 以下は CC ソースコード `compact.ts`、`autoCompact.ts`、`microCompact.ts`、`query.ts` の分析に基づく。 - -### 実行順序の対応 - -教学版は説明の便宜上 L1/L2/L3/L4 と番号を振っているが、実際の実行順序は番号と完全には一致しない: - -| 項目 | 教学版 | Claude Code | -|------|--------|-------------| -| 実行順序 | budget → snip → micro → auto | budget → snip → micro → collapse → auto(`query.ts:379-468`) | -| snip_compact | 先頭 3 + 末尾 47 を保持 | CC はメインスレッドのみ有効;実装はオープンソースリポジトリにない(`HISTORY_SNIP` feature gate)、インターフェースは確認可能:`snipCompactIfNeeded(messages)` → `{ messages, tokensFreed, boundaryMessage? }`、`SnipTool` もモデルが能動的に呼び出し可能。教学版の 3/47 は簡略パラメータ | -| micro_compact | テキストプレースホルダで置換 | 2 つのパス:time-based は直接内容をクリア、cached は API の `cache_edits` を使用(legacy パスは削除済み) | -| micro_compact ホワイトリスト | 位置による(直近 3 件) | time-based は時間閾値でトリガー、cached はカウントでトリガー(`microCompact.ts`) | -| tool_result_budget | 200KB 文字 | 200,000 文字(`toolLimits.ts:49`) | -| compact_history 閾値 | 文字数で推定 | 精密な token 数:`contextWindow - maxOutputTokens - 13_000` | -| 要約の要求 | 5 種類の情報 | 9 つのセクション + ``/`` デュアルタグ | -| 圧縮プロンプト | シンプルなプロンプト | 先頭と末尾に二重の安全ガードでツール呼び出しを禁止 | -| PTL retry | あり(簡略版) | `truncateHeadForPTLRetry()` がメッセージグループ単位でロールバック(`compact.ts:243-290`) | -| 圧縮後のリカバリ | なし(教学版は要約のみ保持) | 直近のファイル、計画、agent/skill/tool などの自動再付加 | -| サーキットブレーカー | 3 回 | 3 回(`autoCompact.ts:70`) | -| reactive リトライ | 1 回 | CC にはより精緻な段階別リトライがある | - -### 実行順序の詳細 - -CC ソース `query.ts` での実際の順序: - -1. `applyToolResultBudget`(L379):まず大きな結果を処理し、完全な内容を退避 -2. `snipCompact`(L403):中間メッセージを切り捨て -3. `microcompact`(L414):古い結果のプレースホルダ化 -4. `contextCollapse`(L441):独立したコンテキスト管理システム(教学版にはなし) -5. `autoCompact`(L454):LLM 全量要約 - -教学版の budget → snip → micro の順序はこれと一致する。教学版には contextCollapse メカニズムがない。 - -### read_file のトレードオフ - -教学版の `micro_compact` は、古い `tool_result` を一律にプレースホルダへ置き換える。`read_file` も例外ではない。これは通常、機能的な正しさには影響しない。後でファイル内容が必要になれば、モデルはもう一度そのファイルを読めばよい。代償は、追加のツール呼び出しが発生し得ることと、prompt cache のヒット率が下がり得ること。 - -Claude Code は、この問題を教学版のような単純なルールでは処理していない。`Read` も microcompact 可能なツール集合に入れる一方で、別途 `readFileState` を維持している。変更されていないファイルの再読込では `FILE_UNCHANGED_STUB` を返し、compact 後には予算内で直近に読んだファイル内容を復元する(例:最大 5 ファイル、1 ファイル 5K token、合計 50K token)。これは本番実装向けのキャッシュと復元メカニズムである。教学版ではそこまで展開せず、「古い結果を圧縮し、必要なら再読込する」という単純な trade-off を残している。 - -### 完全な定数リファレンス - -| 定数 | 値 | ソースファイル | -|------|-----|--------| -| `AUTOCOMPACT_BUFFER_TOKENS` | 13,000 | `autoCompact.ts:62` | -| `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` | 3 | `autoCompact.ts:70` | -| `MAX_OUTPUT_TOKENS_FOR_SUMMARY` | 20,000 | `autoCompact.ts:30` | -| `POST_COMPACT_TOKEN_BUDGET` | 50,000 | `compact.ts:123` | -| `POST_COMPACT_MAX_FILES_TO_RESTORE` | 5 | `compact.ts:122` | -| `POST_COMPACT_MAX_TOKENS_PER_FILE` | 5,000 | `compact.ts:124` | -| 時間ベース micro_compact 間隔 | 60 分 | `timeBasedMCConfig.ts` | -| `MAX_COMPACT_STREAMING_RETRIES` | 2 | `compact.ts:131` | - -### contextCollapse と sessionMemoryCompact - -CC ソースコードには、この教学版では展開していない 2 つのメカニズムが存在する: - -- **contextCollapse**:独立したコンテキスト管理システム。有効時には proactive autocompact を抑制し(`autoCompact.ts:215-222`)、collapse の commit/blocking フローがコンテキスト管理を引き継ぐ。ただし manual `/compact` と reactive fallback は独立パスのままで、contextCollapse の影響を受けない。 -- **sessionMemoryCompact**:compact_history の前に、CC は既存の session memory(s09 で解説)を使った軽量要約を先に試みる。LLM を呼び出さない。このメカニズムは s09 を学んだ後に振り返るとより理解しやすい。 - -### 圧縮プロンプトの中身 - -CC の圧縮プロンプトには 2 つの厳格な要件がある: - -1. **ツール呼び出しの絶対禁止**:冒頭が `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.` で、末尾にも再度 REMINDER がある -2. **先に分析してから要約**:モデルはまず `` タグで思考を整理し、その後 `` タグで正式な要約を出力する。analysis はフォーマット時に除去される - -### 教学版の簡略化は意図的 - -- micro_compact でテキストプレースホルダを使用 → API 層の `cache_edits` 権限がないため -- read_file は特別扱いしない → 教学版では必要時の再読込を受け入れ、readFileState と圧縮後復元の仕組みを導入しない -- token を文字数で推定 → 精密な tokenizer は教学の対象外 -- 圧縮後のリカバリを省略 → 教学版は要約のみを保持し、ファイルの自動再付加を行わない -- 2 つの補助メカニズムを展開しない → 10% の細部に属する - -コア設計思想、安価なものを先に高価なものを後に、は完全に保持されている。 - -
diff --git a/s08_context_compact/README.md b/s08_context_compact/README.md index b6ba6e2b..cc89ebe7 100644 --- a/s08_context_compact/README.md +++ b/s08_context_compact/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](../s09_memory/) → s10 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](../s09_memory/) → s10 → ... → s20 → s21 > *"Context will fill up — have a way to make room"* — Four-layer compression pipeline: cheap first, expensive last. > > **Harness Layer**: Compression — clean memory, unlimited sessions. @@ -120,9 +120,9 @@ All three previous layers have run, but after 30 minutes of continuous work on a Three-step process: -1. **Save transcript**: Write the full conversation to `.transcripts/` in JSONL format. The transcript preserves a recoverable record, but the model's active context only contains the summary. For the model's current reasoning, the details are no longer in context. The teaching code does not provide a transcript retrieval tool. +1. **Save transcript**: Write the full conversation to `.transcripts/` in JSONL format. The transcript keeps a complete record; the message list keeps only the summary, so the original details no longer enter later model calls. 2. **LLM generates summary**: Send conversation history to the LLM, asking it to preserve key information: current goals, important findings, modified files, remaining work, user constraints, etc. -3. **Replace message list**: All old messages are replaced with a single summary. The teaching version only keeps the summary; the real Claude Code re-attaches some recent files, plans, agent/skill/tool context after compaction. +3. **Replace message list**: All old messages are replaced with a single summary. ```python def compact_history(messages): @@ -189,7 +189,7 @@ def agent_loop(messages): break # end current turn, start fresh with compacted context ``` -**The order must not be swapped.** L3 (budget) runs before L2 (micro) because micro replaces old large tool_results with one-line placeholders — budget must persist the full content before that happens. This is why CC source puts `applyToolResultBudget` first. +**The order must not be swapped.** L3 (budget) runs before L2 (micro) because micro replaces old large tool_results with one-line placeholders, so budget must persist the full content first. --- @@ -228,85 +228,5 @@ Context compression lets an agent run for a long time without crashing. But afte s09 Memory → three subsystems: choosing what to remember, extracting key information, consolidating and organizing. Across compressions, across sessions. -
-Deep Dive Into CC Source Code - -> The following is based on analysis of CC source code `compact.ts`, `autoCompact.ts`, `microCompact.ts`, and `query.ts`. - -### Execution Order Comparison - -The teaching version labels layers L1/L2/L3/L4 for pedagogical clarity, but actual execution order does not match the numbering: - -| Dimension | Teaching Version | Claude Code | -|-----------|-----------------|-------------| -| Execution order | budget → snip → micro → auto | budget → snip → micro → collapse → auto (`query.ts:379-468`) | -| snip_compact | Keep head 3 + tail 47 | CC only enables on main thread; implementation not in open-source repo (`HISTORY_SNIP` feature gate), but interface is visible: `snipCompactIfNeeded(messages)` → `{ messages, tokensFreed, boundaryMessage? }`, also exposes `SnipTool` for model-initiated snipping. Teaching version's 3/47 are simplified parameters | -| micro_compact | Text placeholder replacement | Two paths: time-based clears content directly, cached uses API `cache_edits` (legacy path removed) | -| micro_compact whitelist | By position (most recent 3) | time-based triggers by time threshold; cached triggers by count (`microCompact.ts`) | -| tool_result_budget | 200KB characters | 200,000 characters (`toolLimits.ts:49`) | -| compact_history threshold | Character count estimate | Precise tokens: `contextWindow - maxOutputTokens - 13_000` | -| Summary requirements | 5 categories of info | 9 sections + ``/`` dual tags | -| Compression prompt | Simple prompt | Double-ended hard guardrails forbidding tool calls | -| PTL retry | Yes (simplified) | `truncateHeadForPTLRetry()` retreats by message groups (`compact.ts:243-290`) | -| Post-compaction recovery | None (teaching version only keeps summary) | Auto re-read recent files, plans, agent/skill/tool context | -| Circuit breaker | 3 times | 3 times (`autoCompact.ts:70`) | -| Reactive retry | 1 time | CC has more granular tiered retries | - -### Execution Order Details - -The real order in CC source `query.ts`: - -1. `applyToolResultBudget` (L379): persist large results first, ensuring full content is saved -2. `snipCompact` (L403): trim middle messages -3. `microcompact` (L414): old result placeholders -4. `contextCollapse` (L441): independent context management system (not in teaching version) -5. `autoCompact` (L454): LLM full summary - -The teaching version's budget → snip → micro order matches this. The teaching version does not have the contextCollapse mechanism. - -### read_file Trade-off - -The teaching version's `micro_compact` replaces old `tool_result` blocks with placeholders uniformly, including `read_file`. This usually does not affect functional correctness: if the model needs the file contents later, it can read the file again. The cost is an extra tool call and potentially lower prompt cache hit rates. - -Claude Code does not solve this with the teaching version's simple rule. It also puts `Read` in the microcompactable tool set, but maintains a separate `readFileState`: repeated reads of unchanged files return `FILE_UNCHANGED_STUB`, and after compaction it restores recently read file contents within a budget (for example, up to 5 files, 5K tokens per file, 50K tokens total). That is a production-level cache and recovery mechanism. The teaching version does not expand into that machinery; it keeps the simpler trade-off of compacting old results and re-reading when needed. - -### Full Constant Reference - -| Constant | Value | Source File | -|----------|-------|-------------| -| `AUTOCOMPACT_BUFFER_TOKENS` | 13,000 | `autoCompact.ts:62` | -| `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` | 3 | `autoCompact.ts:70` | -| `MAX_OUTPUT_TOKENS_FOR_SUMMARY` | 20,000 | `autoCompact.ts:30` | -| `POST_COMPACT_TOKEN_BUDGET` | 50,000 | `compact.ts:123` | -| `POST_COMPACT_MAX_FILES_TO_RESTORE` | 5 | `compact.ts:122` | -| `POST_COMPACT_MAX_TOKENS_PER_FILE` | 5,000 | `compact.ts:124` | -| Time micro_compact interval | 60 minutes | `timeBasedMCConfig.ts` | -| `MAX_COMPACT_STREAMING_RETRIES` | 2 | `compact.ts:131` | - -### contextCollapse and sessionMemoryCompact - -CC source code has two additional mechanisms not covered in this teaching version: - -- **contextCollapse**: An independent context management system that, when enabled, suppresses proactive autocompact (`autoCompact.ts:215-222`), with collapse's commit/blocking flow taking over context management. Manual `/compact` and reactive fallback remain independent paths, unaffected by contextCollapse. -- **sessionMemoryCompact**: Before compact_history, CC first attempts a lightweight summary using existing session memory (covered in s09) without calling the LLM. This mechanism becomes clearer after learning s09. - -### What Does the Compression Prompt Look Like? - -CC's compression prompt has two hard requirements: - -1. **Absolutely no tool calls**: It begins with `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.`, and appends another REMINDER at the end -2. **Analyze first, then summarize**: The model must first reason in an `` tag, then output the formal summary in a `` tag. The analysis is stripped during formatting - -### Teaching Version Simplifications Are Intentional - -- micro_compact uses text placeholders → we don't have API-level `cache_edits` access -- read_file is not special-cased → the teaching version accepts re-reading when needed instead of introducing readFileState and post-compaction recovery -- Tokens estimated via character count → precise tokenizers are out of scope -- Post-compaction recovery omitted → teaching version only keeps summary, does not auto re-attach files -- Two auxiliary mechanisms not covered → they fall in the 10% detail category - -The core design principle, cheap first, expensive last, is fully preserved. - -
diff --git a/s08_context_compact/README.zh.md b/s08_context_compact/README.zh.md index f53026b0..1f65ee78 100644 --- a/s08_context_compact/README.zh.md +++ b/s08_context_compact/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](../s09_memory/) → s10 → ... → s20 → s21 → s22 +s01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](../s09_memory/) → s10 → ... → s20 → s21 > *"上下文总会满, 要有办法腾地方"* — 四层压缩策略, 便宜的先跑贵的后跑。 > > **Harness 层**: 压缩 — 干净的记忆, 无限的会话。 @@ -120,9 +120,9 @@ def tool_result_budget(messages, max_bytes=200_000): 三步流程: -1. **保存 transcript**:完整对话写入 `.transcripts/`,JSONL 格式。transcript 保留了可恢复记录,但模型的活跃上下文里只剩摘要。对模型当下推理来说,细节已经不在上下文中了。教学代码没有提供 transcript 检索工具。 +1. **保存 transcript**:完整对话写入 `.transcripts/`,JSONL 格式。transcript 保留完整记录;消息列表只保留摘要,原始细节不再进入后续模型调用。 2. **LLM 生成摘要**:把对话历史发给 LLM,要求保留当前目标、重要发现、已改文件、剩余工作、用户约束等关键信息。 -3. **替换消息列表**:所有旧消息被替换为一条摘要。教学版只保留摘要;真实 Claude Code 会在 compact 后重新附加部分最近文件、计划、agent/skill/tool 等上下文。 +3. **替换消息列表**:所有旧消息被替换为一条摘要。 ```python def compact_history(messages): @@ -189,7 +189,7 @@ def agent_loop(messages): break # 结束当前 turn,用压缩后的上下文开始新一轮 ``` -**顺序不能换。** L3(budget)在 L2(micro)前面,因为 micro 会把旧的大 tool_result 替换成一行占位符,budget 必须在那之前把完整内容落盘。这也是为什么 CC 源码把 `applyToolResultBudget` 放在最前面。 +**顺序不能换。** L3(budget)在 L2(micro)前面,因为 micro 会把旧的大 `tool_result` 替换成一行占位符,budget 必须在那之前保存完整内容。 --- @@ -228,85 +228,5 @@ python s08_context_compact/code.py s09 Memory → 三个子系统:选择记什么、提取关键信息、整理巩固。跨压缩、跨会话。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `compact.ts`、`autoCompact.ts`、`microCompact.ts`、`query.ts` 的分析。 - -### 执行顺序对照 - -教学版为了讲解方便按 L1/L2/L3/L4 编号,但实际执行顺序和编号不完全对应: - -| 维度 | 教学版 | Claude Code | -|------|--------|-------------| -| 执行顺序 | budget → snip → micro → auto | budget → snip → micro → collapse → auto(`query.ts:379-468`) | -| snip_compact | 保留头 3 + 尾 47 | CC 仅主线程启用;实现不在开源仓库中(`HISTORY_SNIP` feature gate),但接口可见:`snipCompactIfNeeded(messages)` → `{ messages, tokensFreed, boundaryMessage? }`,还暴露了 `SnipTool` 工具让模型主动调用。教学版的 3/47 是简化参数 | -| micro_compact | 文本占位符替换 | 两条路径:time-based 直接清内容,cached 走 API `cache_edits`(legacy path 已移除) | -| micro_compact 白名单 | 按位置(最近 3 条) | time-based 按时间阈值触发;cached 按计数触发(`microCompact.ts`) | -| tool_result_budget | 200KB 字符 | 200,000 字符(`toolLimits.ts:49`) | -| compact_history 阈值 | 字符数估算 | 精确 token:`contextWindow - maxOutputTokens - 13_000` | -| 摘要要求 | 5 类信息 | 9 个部分 + ``/`` 双标签 | -| 压缩 prompt | 简单 prompt | 首尾双重防呆禁止调工具 | -| PTL retry | 有(简化) | `truncateHeadForPTLRetry()` 按消息组回退(`compact.ts:243-290`) | -| 后压缩恢复 | 无(教学版只保留摘要) | 自动重新读取最近文件、计划、agent/skill/tool 等 | -| 熔断器 | 3 次 | 3 次(`autoCompact.ts:70`) | -| reactive 重试 | 1 次 | CC 有更精细的分级重试 | - -### 执行顺序详解 - -CC 源码 `query.ts` 中的真实顺序: - -1. `applyToolResultBudget`(L379):先处理大结果,确保完整内容落盘 -2. `snipCompact`(L403):裁中间消息 -3. `microcompact`(L414):旧结果占位 -4. `contextCollapse`(L441):独立的上下文管理系统(教学版无) -5. `autoCompact`(L454):LLM 全量摘要 - -教学版的 budget → snip → micro 顺序与此一致。教学版没有 contextCollapse 机制。 - -### read_file 的取舍 - -教学版的 `micro_compact` 会把旧 `tool_result` 统一替换成占位符,包括 `read_file`。这通常不影响功能正确性:如果后续还需要文件内容,模型可以重新读一次。代价是可能多一次工具调用,也可能降低 prompt cache 命中率。 - -Claude Code 没有用教学版这种简单规则解决这个问题。它把 `Read` 也放进可 microcompact 的工具集合,但同时维护 `readFileState`:重复读取未变化文件时返回 `FILE_UNCHANGED_STUB`,compact 后再按预算恢复最近读过的文件内容(例如最多 5 个文件、每个 5K token、总预算 50K token)。这是生产级实现里的缓存和恢复机制,教学版不展开,保留“压缩旧结果,必要时重新读取”的简单 trade-off。 - -### 完整常量参考 - -| 常量 | 值 | 源文件 | -|------|-----|--------| -| `AUTOCOMPACT_BUFFER_TOKENS` | 13,000 | `autoCompact.ts:62` | -| `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` | 3 | `autoCompact.ts:70` | -| `MAX_OUTPUT_TOKENS_FOR_SUMMARY` | 20,000 | `autoCompact.ts:30` | -| `POST_COMPACT_TOKEN_BUDGET` | 50,000 | `compact.ts:123` | -| `POST_COMPACT_MAX_FILES_TO_RESTORE` | 5 | `compact.ts:122` | -| `POST_COMPACT_MAX_TOKENS_PER_FILE` | 5,000 | `compact.ts:124` | -| 时间 micro_compact 间隔 | 60 分钟 | `timeBasedMCConfig.ts` | -| `MAX_COMPACT_STREAMING_RETRIES` | 2 | `compact.ts:131` | - -### contextCollapse 和 sessionMemoryCompact - -CC 源码中还有两个机制本教学版没有展开: - -- **contextCollapse**:独立的上下文管理系统,启用时抑制 proactive autocompact(`autoCompact.ts:215-222`),由 collapse 的 commit/blocking 流程接管上下文管理。但 manual `/compact` 和 reactive fallback 仍是独立路径,不受 contextCollapse 影响。 -- **sessionMemoryCompact**:compact_history 之前,CC 会先尝试用已有的 session memory(s09 会讲到)做轻量摘要,不调 LLM。这个机制等学完 s09 之后回头看会更清楚。 - -### 压缩 prompt 长什么样? - -CC 的压缩 prompt 有两个硬性要求: - -1. **绝对禁止调用工具**:开头就是 `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.`,末尾还会再 REMINDER 一次 -2. **先分析再总结**:模型需要先在 `` 标签里理清思路,然后在 `` 标签里输出正式摘要。analysis 在格式化时被剥离 - -### 教学版的简化是刻意的 - -- micro_compact 用文本占位 → 我们没有 API 层的 `cache_edits` 权限 -- read_file 不特殊处理 → 教学版接受必要时重新读取,避免引入 readFileState 和后压缩恢复机制 -- token 用字符数估算 → 精确 tokenizer 不在教学范围内 -- 后压缩恢复省略 → 教学版只保留摘要,不自动重新附加文件 -- 两个辅助机制不展开 → 属于 10% 的细节 - -核心设计思想,便宜的先跑贵的后跑,完整保留。 - -
diff --git a/s08_context_compact/images/compaction-layers.en.svg b/s08_context_compact/images/compaction-layers.en.svg index 5a27e96d..f8eae9a0 100644 --- a/s08_context_compact/images/compaction-layers.en.svg +++ b/s08_context_compact/images/compaction-layers.en.svg @@ -69,7 +69,7 @@ microCompact old tool_result → placeholder (keep latest 3) compact old - Trigger: every turn automatically; tutorial uses text placeholder + Trigger: every turn; replace older results with text placeholders diff --git a/s08_context_compact/images/compaction-layers.ja.svg b/s08_context_compact/images/compaction-layers.ja.svg index 85190548..5a8ca2de 100644 --- a/s08_context_compact/images/compaction-layers.ja.svg +++ b/s08_context_compact/images/compaction-layers.ja.svg @@ -69,7 +69,7 @@ microCompact 古い tool_result → プレースホルダー(最新 3 件保持) 旧結果を圧縮 - トリガー:毎ターン自動実行、チュートリアル版はテキストプレースホルダーで模擬 + トリガー:毎ターン、古い結果をテキストプレースホルダーに置換 diff --git a/s08_context_compact/images/compaction-layers.svg b/s08_context_compact/images/compaction-layers.svg index 818b44e5..f82bdd44 100644 --- a/s08_context_compact/images/compaction-layers.svg +++ b/s08_context_compact/images/compaction-layers.svg @@ -69,7 +69,7 @@ microCompact 旧 tool_result → 占位符(保留最近 3 条) 压旧结果 - 触发:每轮自动,教学版用文本占位符模拟 + 触发:每轮自动,把较旧结果替换为文本占位符 diff --git a/s08_context_compact/images/micro-compact.en.svg b/s08_context_compact/images/micro-compact.en.svg index 8f5c5dc8..4c8d049b 100644 --- a/s08_context_compact/images/micro-compact.en.svg +++ b/s08_context_compact/images/micro-compact.en.svg @@ -50,9 +50,9 @@ - How (teaching version) - Iterate through tool_result, keep only latest 3 complete, replace older ones with placeholders. - Real CC - Clears old results via API cache_edits (without breaking prompt cache prefix), only for COMPACTABLE_TOOLS: - Read, Bash, Grep, Glob, WebSearch, WebFetch, Edit, Write. Teaching version uses text placeholders to simulate the same effect. + Rule + Keep the latest 3 tool results complete and replace older results with placeholders. + Placeholder + Explain that the result was compacted and that the tool can be run again if needed. + The message structure remains valid for the next loop iteration. diff --git a/s08_context_compact/images/micro-compact.ja.svg b/s08_context_compact/images/micro-compact.ja.svg index a418c544..f54339fa 100644 --- a/s08_context_compact/images/micro-compact.ja.svg +++ b/s08_context_compact/images/micro-compact.ja.svg @@ -50,9 +50,9 @@ - 方法(教学版) - tool_result を走査し、最新 3 件のみ完全保持、古いものはプレースホルダーに置換。 - 実際の CC - API cache_edits で旧結果をクリア(prompt cache プレフィックスを破壊しない)、COMPACTABLE_TOOLS のみ対象: - Read, Bash, Grep, Glob, WebSearch, WebFetch, Edit, Write。教学版はテキストプレースホルダーで同様の効果を模擬。 + 処理規則 + 最新 3 件の tool_result を完全保持し、古い結果をプレースホルダーに置換する。 + プレースホルダー + 結果が圧縮済みで、必要ならツールを再実行できることを示す。 + メッセージ構造を保ったまま次のループへ進める。 diff --git a/s08_context_compact/images/micro-compact.svg b/s08_context_compact/images/micro-compact.svg index e1728f7d..fd979840 100644 --- a/s08_context_compact/images/micro-compact.svg +++ b/s08_context_compact/images/micro-compact.svg @@ -49,9 +49,9 @@ - 怎么做(教学版) - 遍历 tool_result,只保留最近 3 条完整,更旧的替换为占位符。 - 真实 CC - 通过 API cache_edits 清除旧结果(不破坏 prompt cache 前缀),仅对 COMPACTABLE_TOOLS 生效: - Read, Bash, Grep, Glob, WebSearch, WebFetch, Edit, Write。教学版用文本占位模拟同样效果。 + 处理规则 + 遍历 tool_result,只保留最近 3 条完整,更旧的替换为占位符。 + 占位内容 + 说明原结果已压缩,并提示需要时重新运行对应工具。 + 消息结构保持不变,后续循环仍可继续处理。 diff --git a/s09_memory/README.ja.md b/s09_memory/README.ja.md index 96864f40..4f83b6cc 100644 --- a/s09_memory/README.ja.md +++ b/s09_memory/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s07 → s08 → `s09` → [s10](../s10_system_prompt/) → s11 → ... → s20 → s21 → s22 +s01 → ... → s07 → s08 → `s09` → [s10](../s10_system_prompt/) → s11 → ... → s20 → s21 > *"圧縮は詳細を失う、失わない層が必要"* — ファイルストア + インデックス + オンデマンド読み込み。圧縮を越え、セッションを越えて。 > > **Harness レイヤー**: 記憶 — 圧縮とセッションを越える知識の蓄積。 @@ -146,8 +146,6 @@ def consolidate_memories(): # Replace all files with consolidated results ``` -CC はこのプロセスを **Dream** と呼び、実際には 4 層のゲートがある:時間間隔、スキャンスロットル、セッション数、ファイルロック。教学版はファイル数閾値に簡略化。 - ### Memory に保存するもの Memory はセッションを越えて有用な情報を保存する:ユーザーの好み、繰り返し出るフィードバック、プロジェクト背景、よく使う入口、調査の手がかりなど。「あとでまた使うもの」を対象にし、インデックス + オンデマンド読み込みで現在の会話に戻す。 @@ -192,90 +190,5 @@ python s09_memory/code.py s10 System Prompt → セグメント + 実行時組み立て。異なるプロジェクト、異なるツール、異なるプロンプト。 -
-CC ソースコードの詳細 - -> 以下は CC ソースコード `src/` 下の `memdir/`、`services/`、`utils/`、`query/` の分析に基づく。行番号はソースコードと照合済み。 - -### ソースコードパス - -| ファイル | 行数 | 職責 | -|------|------|------| -| `memdir/memdir.ts` | 507 | 核心:MEMORY.md 定義(`34-38`)、記憶動作指示で memory/plan/tasks を区別(`199-266`)、`loadMemoryPrompt()` 3 パス(`419-490`) | -| `memdir/findRelevantMemories.ts` | 141 | Sonnet side-query で記憶選択(`18-24` システムプロンプト、`97-122` 呼び出しロジック) | -| `memdir/memoryTypes.ts` | 271 | 型定義、frontmatter フィールド | -| `memdir/memoryScan.ts` | — | .md ファイルをスキャン、MEMORY.md を除外、frontmatter を読み取り、最大 200 ファイル、mtime 降順(`35-94`) | -| `services/extractMemories/extractMemories.ts` | 615 | forked agent で記憶を抽出、制限付き権限、`skipTranscript: true`、`maxTurns: 5`(`371-427`) | -| `services/autoDream/autoDream.ts` | 324 | Dream 整理、4 層ゲート(`63-66` デフォルト値、`130-190` ゲート、`224-233` forked agent) | -| `services/SessionMemory/sessionMemory.ts` | 495 | セッションレベルの記憶管理 | -| `services/compact/sessionMemoryCompact.ts` | — | session memory 軽量サマリ、閾値 10K/5/40K(`56-61`) | -| `utils/attachments.ts` | — | 注入予算:200 行 / 4096 バイト/ファイル、60KB/セッション(`269-288`);query で関連記憶を検索(`2196-2241`) | -| `query.ts` | — | memory prefetch を毎ターン開始時に起動(`301-304`)、非ブロッキング収集(`1592-1614`) | -| `query/stopHooks.ts` | — | stop hook fire-and-forget で抽出と Dream をトリガー(`141-155`) | - -### 記憶選択:embedding ではなく LLM - -CC は **Sonnet 自身で選択**(`findRelevantMemories.ts`)、embedding ベクトル類似度ではない: - -1. `memoryScan.ts` が `.memory/` 下のすべての `.md` ファイルをスキャン(MEMORY.md を除外)、最大 200 ファイル、mtime 降順 -2. `name` + `description` をカタログとしてリスト化 -3. Sonnet side-query に送信:「名前と説明から本当に有用な記憶を選択(最大 5 件)。不明ならスキップ。」 -4. Sonnet が `{ selected_memories: ["file1.md", ...] }` を返却 -5. 選択されたファイルの完全な内容を読み込み(≤ 200 行 / 4096 バイト/ファイル)、注入。セッション総予算:60KB - -毎ターンのユーザー turn 開始時、`query.ts:301-304` が memory prefetch を起動(非同期);ツール実行後、`1592-1614` が非ブロッキングで結果を収集。 - -### 抽出タイミング:stop hook、autoCompact 後ではない - -トリガー位置(`stopHooks.ts:141-155`):`handleStopHooks()` 内で、fire-and-forget で抽出と Dream をトリガー。教学版は `stop_reason != "tool_use"` 分岐に抽出を配置、方向は一致。 - -CC の抽出は forked agent で実行(`extractMemories.ts:371-427`):制限付き権限、`skipTranscript: true`、`maxTurns: 5`。重複保護もある:メイン Agent が既に記憶ファイルを書き込んだ場合、抽出をスキップ。 - -### 記憶ファイル形式 - -CC は Markdown + YAML frontmatter を使用、教学版と一致。4 種類:`user`、`feedback`、`project`、`reference`。 - -`memdir.ts:34-38` がインデックス制約を定義:`MEMORY.md` 最大 200 行 / 25KB。`memdir.ts:199-266` が記憶動作指示を構築、memory と plan と tasks を明確に区別。保存場所:`~/.claude/projects//memory/`。 - -### Dream:4 層ゲート - -「アイドル時にトリガー」や「数が足りたら統合」ではなく、4 層のゲート(`autoDream.ts`、デフォルト値 `63-66`、ゲートロジック `130-190`): - -1. **時間ゲート**:前回の統合から ≥ 24 時間 -2. **スキャンスロットル**:頻繁なファイルシステムスキャンを回避 -3. **セッションゲート**:前回の統合以降 ≥ 5 セッションの transcript が変更された -4. **ロックゲート**:他のプロセスが統合中でない(`.consolidate-lock` ファイル) - -統合自体は forked agent で実行(`224-233`):定位 → 直近のシグナル収集 → 統合してファイル書き込み → 剪定してインデックス更新。ロックファイルの mtime が lastConsolidatedAt。クラッシュリカバリ:1 時間後にロックが自動期限切れ。 - -### User Memory vs Session Memory - -| | User Memory | Session Memory | -|---|---|---| -| 永続性 | セッション間 | 単一セッション | -| ストレージ | `memory/` 下の複数 .md ファイル | `session-memory//memory.md` | -| 注入先 | system prompt | compact サマリ | -| 目的 | セッション間の知識蓄積 | compact を越えたコンテキストの連続性 | - -sessionMemoryCompact(s08 で触れた仕組み)は Session Memory を活用:autoCompact の前に session memory ファイルを読み込み、内容が十分であれば(≥ 10K token、≥ 5 テキストメッセージ、≤ 40K token、`sessionMemoryCompact.ts:56-61`)、LLM を呼び出さずにサマリとして使用。 - -### 実際の実装が教学版より複雑な点 - -- **Feature flags**:記憶関連機能には複数の feature gate 層がある -- **Team memory**:チーム共有記憶、`loadMemoryPrompt()` に専用パスあり(教学版では未カバー) -- **KAIROS**:タイミング認識型の記憶抽出戦略、`loadMemoryPrompt()` の daily-log モード -- **Prompt cache**:記憶注入は prompt cache の TTL を考慮する必要があり、毎ターン system prompt の大部分を書き直すことを避ける -- **ファイルロック**:マルチプロセス時の並行制御 -- **Memory prefetch**:非同期プレフェッチ、メインフローをブロックしない - -### 教学版の簡略化は意図的 - -- LLM side-query → LLM side-query + キーワードフォールバック:教学版は LLM 選択を維持し、フォールバックパスを追加 -- 記憶 JSON → Markdown + frontmatter:教学版は CC と一致 -- stop hook トリガー → `stop_reason != "tool_use"` 分岐:方向は一致 -- 4 層ゲート → ファイル数閾値:教学版には transcript システムやマルチセッションの概念がない -- forked agent + 制限付き権限 → 直接呼び出し:教学版にはサブプロセス分離がない - -
diff --git a/s09_memory/README.md b/s09_memory/README.md index 79a592b4..8da5ac66 100644 --- a/s09_memory/README.md +++ b/s09_memory/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s07 → s08 → `s09` → [s10](../s10_system_prompt/) → s11 → ... → s20 → s21 → s22 +s01 → ... → s07 → s08 → `s09` → [s10](../s10_system_prompt/) → s11 → ... → s20 → s21 > *"Compression loses details, keep a layer that doesn't"* — File store + index + on-demand loading, across compactions, across sessions. > > **Harness Layer**: Memory — knowledge that survives compaction and sessions. @@ -146,8 +146,6 @@ def consolidate_memories(): # Replace all files with consolidated results ``` -CC calls this process **Dream**, with four gates in practice: time interval, scan throttle, session count, file lock. The teaching version simplifies to a file-count threshold. - ### What Memory Stores Memory stores information that remains useful across sessions: user preferences, recurring feedback, project background, common entry points, and investigation clues. It focuses on "what will be useful later" and brings that information back through an index plus on-demand loading. @@ -192,90 +190,5 @@ Memory, compression, and tools are all in place. But the system prompt is still s10 System Prompt → segments + runtime assembly. Different projects, different tools, different prompts. -
-Deep Dive Into CC Source Code - -> The following is based on analysis of CC source code under `src/` in `memdir/`, `services/`, `utils/`, `query/`. Line numbers verified against source. - -### Source Code Paths - -| File | Lines | Responsibility | -|------|-------|---------------| -| `memdir/memdir.ts` | 507 | Core: MEMORY.md definition (`34-38`), memory behavior instructions distinguishing memory/plan/tasks (`199-266`), `loadMemoryPrompt()` three paths (`419-490`) | -| `memdir/findRelevantMemories.ts` | 141 | Sonnet side-query memory selection (`18-24` system prompt, `97-122` call logic) | -| `memdir/memoryTypes.ts` | 271 | Type definitions, frontmatter fields | -| `memdir/memoryScan.ts` | — | Scan .md files, exclude MEMORY.md, read frontmatter, max 200 files, sorted by mtime desc (`35-94`) | -| `services/extractMemories/extractMemories.ts` | 615 | Forked agent extraction, restricted permissions, `skipTranscript: true`, `maxTurns: 5` (`371-427`) | -| `services/autoDream/autoDream.ts` | 324 | Dream consolidation, four-layer gating (`63-66` defaults, `130-190` gating, `224-233` forked agent) | -| `services/SessionMemory/sessionMemory.ts` | 495 | Session-level memory management | -| `services/compact/sessionMemoryCompact.ts` | — | Session memory lightweight summary, thresholds 10K/5/40K (`56-61`) | -| `utils/attachments.ts` | — | Injection budget: 200 lines / 4096 bytes per file, 60KB per session (`269-288`); find relevant memory by query (`2196-2241`) | -| `query.ts` | — | Memory prefetch at start of each user turn (`301-304`), non-blocking collection (`1592-1614`) | -| `query/stopHooks.ts` | — | Stop hook fire-and-forget triggers extraction and Dream (`141-155`) | - -### Memory Selection: LLM, Not Embedding - -CC uses **Sonnet itself to select** (`findRelevantMemories.ts`), not embedding vector similarity: - -1. `memoryScan.ts` scans all `.md` files in `.memory/` (excluding MEMORY.md), max 200 files, sorted by mtime descending -2. Lists all memory files' `name` + `description` as a catalog -3. Sends to Sonnet side-query: "Select truly useful memories by name and description (max 5). Skip if unsure." -4. Sonnet returns `{ selected_memories: ["file1.md", ...] }` -5. Selected files' full contents are read (≤ 200 lines / 4096 bytes per file) and injected. Total session budget: 60KB - -At the start of each user turn, `query.ts:301-304` starts memory prefetch (async); after tool execution, `1592-1614` collects completed results non-blocking. - -### Extraction Timing: Stop Hook, Not After autoCompact - -Trigger location (`stopHooks.ts:141-155`): inside `handleStopHooks()`, fire-and-forget triggers extraction and Dream. The teaching version places extraction in the `stop_reason != "tool_use"` branch, matching the direction. - -CC's extraction runs via forked agent (`extractMemories.ts:371-427`): restricted permissions, `skipTranscript: true`, `maxTurns: 5`. Also has overlap protection: if the main Agent already wrote memory files, extraction is skipped. - -### Memory File Format - -CC uses Markdown + YAML frontmatter, consistent with the teaching version. Four types: `user`, `feedback`, `project`, `reference`. - -`memdir.ts:34-38` defines index constraints: `MEMORY.md` max 200 lines / 25KB. `memdir.ts:199-266` builds memory behavior instructions, explicitly distinguishing memory from plan and tasks. Storage location: `~/.claude/projects//memory/`. - -### Dream: Four-Layer Gating - -Not "triggered when idle" or "consolidate when count is enough", but four gates (`autoDream.ts`, defaults `63-66`, gating logic `130-190`): - -1. **Time gate**: ≥ 24 hours since last consolidation -2. **Scan throttle**: Avoid frequent filesystem scans -3. **Session gate**: ≥ 5 session transcripts modified since last consolidation -4. **Lock gate**: No other process currently consolidating (`.consolidate-lock` file) - -The merge itself runs via forked agent (`224-233`): locate → collect recent signals → merge and write files → prune and update index. Lock file mtime serves as lastConsolidatedAt. Crash recovery: lock auto-expires after 1 hour. - -### User Memory vs Session Memory - -| | User Memory | Session Memory | -|---|---|---| -| Persistence | Cross-session | Single session | -| Storage | Multiple .md files in `memory/` | `session-memory//memory.md` | -| Loaded into | system prompt | compact summary | -| Purpose | Cross-session knowledge accumulation | Cross-compact context continuity | - -sessionMemoryCompact (mentioned in s08) uses Session Memory: before autoCompact, it reads the session memory file and, if sufficient (≥ 10K tokens, ≥ 5 text messages, ≤ 40K tokens, `sessionMemoryCompact.ts:56-61`), uses it as a summary without calling the LLM. - -### Where the Real Implementation Is More Complex - -- **Feature flags**: Memory features have multiple feature gate layers -- **Team memory**: Shared team memories, `loadMemoryPrompt()` has a dedicated path (not covered in teaching version) -- **KAIROS**: Timing-aware memory extraction strategy, daily-log mode in `loadMemoryPrompt()` -- **Prompt cache**: Memory injection must account for prompt cache TTL, avoiding full system prompt rewrites each turn -- **File locks**: Concurrency control for multi-process scenarios -- **Memory prefetch**: Async prefetch, non-blocking main flow - -### Teaching Version Simplifications Are Intentional - -- LLM side-query → LLM side-query + keyword fallback: teaching version keeps LLM selection, adds fallback path -- Memory JSON → Markdown + frontmatter: teaching version matches CC -- Stop hook trigger → `stop_reason != "tool_use"` branch: same direction -- Four-layer gating → file-count threshold: teaching version lacks transcript system and multi-session concepts -- Forked agent + restricted permissions → direct call: teaching version has no subprocess isolation - -
diff --git a/s09_memory/README.zh.md b/s09_memory/README.zh.md index 0f21c69f..d8fe07d5 100644 --- a/s09_memory/README.zh.md +++ b/s09_memory/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s07 → s08 → `s09` → [s10](../s10_system_prompt/) → s11 → ... → s20 → s21 → s22 +s01 → ... → s07 → s08 → `s09` → [s10](../s10_system_prompt/) → s11 → ... → s20 → s21 > *"压缩会丢细节, 要有一层不丢的"* — 文件仓库 + 索引 + 按需加载,跨压缩、跨会话。 > > **Harness 层**: 记忆 — 跨压缩、跨会话的知识积累。 @@ -147,8 +147,6 @@ def consolidate_memories(): # Replace all files with consolidated results ``` -CC 把这个过程叫 Dream,实际有四层门控:时间间隔、扫描节流、会话数、文件锁。教学版简化为文件数阈值。 - ### Memory 适合保存什么 Memory 保存跨会话仍然有用的信息:用户偏好、反复出现的反馈、项目背景、常用入口和排查线索。它关注“以后还会用到什么”,并通过索引 + 按需加载把这些信息带回当前对话。 @@ -193,90 +191,5 @@ python s09_memory/code.py s10 System Prompt → 分段 + 运行时组装。不同项目、不同工具,拼出不同的 prompt。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `src/` 下 `memdir/`、`services/`、`utils/`、`query/` 的分析,行号已对照核实。 - -### 源码路径 - -| 文件 | 行数 | 职责 | -|------|------|------| -| `memdir/memdir.ts` | 507 | 核心:MEMORY.md 定义(`34-38`)、记忆行为指令区分 memory/plan/tasks(`199-266`)、`loadMemoryPrompt()` 三条路径(`419-490`) | -| `memdir/findRelevantMemories.ts` | 141 | Sonnet side-query 选记忆(`18-24` 系统提示、`97-122` 调用逻辑) | -| `memdir/memoryTypes.ts` | 271 | 类型定义,frontmatter 字段 | -| `memdir/memoryScan.ts` | — | 扫描 .md 文件,排除 MEMORY.md,读 frontmatter,最多 200 个,按 mtime 降序(`35-94`) | -| `services/extractMemories/extractMemories.ts` | 615 | forked agent 提取记忆,受限权限,`skipTranscript: true`,`maxTurns: 5`(`371-427`) | -| `services/autoDream/autoDream.ts` | 324 | Dream 整理,四层门控(`63-66` 默认值、`130-190` 门控、`224-233` forked agent) | -| `services/SessionMemory/sessionMemory.ts` | 495 | 会话级记忆管理 | -| `services/compact/sessionMemoryCompact.ts` | — | session memory 轻量摘要,阈值 10K/5/40K(`56-61`) | -| `utils/attachments.ts` | — | 注入预算:200 行 / 4096 字节每文件,60KB 每 session(`269-288`);按 query 找相关 memory(`2196-2241`) | -| `query.ts` | — | memory prefetch 每轮启动(`301-304`),非阻塞收集(`1592-1614`) | -| `query/stopHooks.ts` | — | stop hook fire-and-forget 触发提取和 Dream(`141-155`) | - -### 记忆选择:LLM 选,不是 embedding - -CC 用 **Sonnet 本身来选**(`findRelevantMemories.ts`),不是 embedding 向量相似度: - -1. `memoryScan.ts` 扫描 `.memory/` 下所有 `.md` 文件(排除 MEMORY.md),最多 200 个,按 mtime 降序 -2. 把 `name` + `description` 列成清单 -3. 发给 Sonnet side-query:"根据名称和描述选出真正有用的记忆(最多 5 个)。不确定就不要选。" -4. Sonnet 返回 `{ selected_memories: ["file1.md", ...] }` -5. 选中文件读取完整内容(每文件 ≤ 200 行 / 4096 字节),注入上下文。单 session 总预算 60KB - -每轮用户 turn 开始时,`query.ts:301-304` 启动 memory prefetch(异步);工具执行后 `1592-1614` 非阻塞收集结果,不卡主流程。 - -### 提取时机:stop hook,不是 autoCompact 后 - -触发位置(`stopHooks.ts:141-155`):在 `handleStopHooks()` 中,fire-and-forget 触发提取和 Dream。教学版把提取放在 `stop_reason != "tool_use"` 分支里,方向一致。 - -CC 的提取通过 forked agent 执行(`extractMemories.ts:371-427`):受限权限、`skipTranscript: true`、`maxTurns: 5`。还有重叠保护:如果主 Agent 已经写入了记忆文件,跳过提取。 - -### 记忆文件格式 - -CC 用 Markdown + YAML frontmatter,和教学版一致。四种类型:`user`、`feedback`、`project`、`reference`。 - -`memdir.ts:34-38` 定义索引约束:`MEMORY.md` 最多 200 行 / 25KB。`memdir.ts:199-266` 构建记忆行为指令,明确区分 memory、plan、tasks。存储位置:`~/.claude/projects//memory/`。 - -### Dream:四层门控 - -不是"空闲时触发"或"数量够了就合并",而是四层门控(`autoDream.ts`,默认值 `63-66`,门控逻辑 `130-190`): - -1. **时间门控**:距上次合并 ≥ 24 小时 -2. **扫描节流**:避免频繁扫描文件系统 -3. **会话门控**:自上次合并以来修改了 ≥ 5 个会话 transcript -4. **锁门控**:没有其他进程正在合并(`.consolidate-lock` 文件) - -合并本身通过 forked agent 执行(`224-233`):定位 → 收集近期信号 → 合并写文件 → 剪枝更新索引。锁文件 mtime 就是 lastConsolidatedAt。崩溃恢复:1 小时后锁自动过期。 - -### User Memory vs Session Memory - -| | User Memory | Session Memory | -|---|---|---| -| 持久性 | 跨会话 | 单会话 | -| 存储 | `memory/` 下多个 .md 文件 | `session-memory//memory.md` | -| 加载到 | system prompt | compact 摘要 | -| 用途 | 跨会话的知识积累 | 跨 compact 的上下文连续性 | - -sessionMemoryCompact(s08 中提到的机制)正是使用了 Session Memory:autoCompact 前先读 session memory 文件,如果内容足够(≥ 10K token、≥ 5 条文本消息、≤ 40K token,`sessionMemoryCompact.ts:56-61`),就用它做摘要,不调 LLM。 - -### 真实实现比教学版复杂的地方 - -- **Feature flags**:记忆相关功能有多层 feature gate 控制 -- **Team memory**:团队共享记忆,`loadMemoryPrompt()` 有专门路径(教学版未涉及) -- **KAIROS**:时机感知的记忆提取策略,`loadMemoryPrompt()` 中 daily-log 模式 -- **Prompt cache**:记忆注入需要考虑 prompt cache 的 TTL,避免每次都重写 system prompt 的大段内容 -- **文件锁**:多进程并发时的锁机制 -- **Memory prefetch**:异步预取,不阻塞主流程 - -### 教学版的简化是刻意的 - -- LLM side-query → LLM side-query + 关键词降级:教学版保留了 LLM 选择,加了降级路径 -- 记忆 JSON → Markdown + frontmatter:教学版与 CC 一致 -- stop hook 触发 → `stop_reason != "tool_use"` 分支:方向一致 -- 四层门控 → 文件数阈值:教学版没有 transcript 系统和多会话概念 -- forked agent + 受限权限 → 直接调用:教学版没有子进程隔离 - -
diff --git a/s10_system_prompt/README.ja.md b/s10_system_prompt/README.ja.md index 69db8117..6990bda1 100644 --- a/s10_system_prompt/README.ja.md +++ b/s10_system_prompt/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s08 → s09 → `s10` → [s11](../s11_error_recovery/) → s12 → ... → s20 → s21 → s22 +s01 → ... → s08 → s09 → `s10` → [s11](../s11_error_recovery/) → s12 → ... → s20 → s21 > *"モデル入力は組み立てるもの、固定するものではない"* — 安定セクション + 実行時状態 + キャッシュ。 > > **Harness レイヤー**: コンテキスト組み立て — 安定した指示と動的状態をモデル入力にまとめる。 @@ -119,8 +119,6 @@ def get_system_prompt(context: dict) -> str: `hash()` ではなく `json.dumps` を使用:Python 組み込みの `hash()` にはプロセスランダム化があり(安定したキャッシュキーに不適切)、list/dict で `unhashable type` エラーになる。 -注意:このキャッシュは「プロセス内での文字列再組み立ての回避」のみ。CC の API prompt cache とは別物。CC の prompt cache は `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` で静的/動的部分を分離し、静的部分が global cache に命中する。動的内容が変化しても静的部分は無効化されない。 - ### context: 実際の状態、キーワード推測ではない context は現在の実行時状態の実際の状態を反映: @@ -178,7 +176,7 @@ cd learn-claude-code python s10_system_prompt/code.py ``` -安全上の注意:この集中教材はモデルが渡す `bash` 文字列を `shell=True` で実行し、s03 の permission gate を省略している。破棄可能な workspace だけで実行し、本番 harness では permission と sandbox の境界を戻すこと。 +**安全上の注意**:このスクリプトはモデルが生成した `bash` 文字列を `shell=True` で実行し、s03 の permission gate を含まない。破棄可能な workspace でのみ実行すること。 観察のポイント: diff --git a/s10_system_prompt/README.md b/s10_system_prompt/README.md index 67bf59e5..d539e412 100644 --- a/s10_system_prompt/README.md +++ b/s10_system_prompt/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s08 → s09 → `s10` → [s11](../s11_error_recovery/) → s12 → ... → s20 → s21 → s22 +s01 → ... → s08 → s09 → `s10` → [s11](../s11_error_recovery/) → s12 → ... → s20 → s21 > *"Model input is assembled, not hardcoded"* — Stable sections + runtime state + caching. > > **Harness Layer**: Context assembly — turn stable instructions and dynamic state into model input. @@ -119,8 +119,6 @@ def get_system_prompt(context: dict) -> str: `json.dumps` instead of `hash()`: Python's built-in `hash()` has process randomization (unsuitable for stable cache keys) and throws `unhashable type` on nested dicts/lists. -Note: this cache only avoids redundant string assembly within a process. It's not the same as CC's API prompt cache, which uses `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` to separate static and dynamic parts — the static parts hit global cache and don't invalidate when dynamic content changes. - ### context: Real State, Not Keyword Guessing Context reflects the actual runtime state: @@ -178,7 +176,7 @@ cd learn-claude-code python s10_system_prompt/code.py ``` -Safety note: this focused teaching script still executes the model's `bash` string with `shell=True` and omits s03's permission gate. Run it only in a disposable workspace; production harnesses must restore permission and sandbox boundaries. +**Safety note**: The script executes model-generated `bash` strings with `shell=True` and does not include the permission gate from s03. Run it only in a disposable workspace. What to watch for: diff --git a/s10_system_prompt/README.zh.md b/s10_system_prompt/README.zh.md index 0f6519ba..dd4b6733 100644 --- a/s10_system_prompt/README.zh.md +++ b/s10_system_prompt/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s08 → s09 → `s10` → [s11](../s11_error_recovery/) → s12 → ... → s20 → s21 → s22 +s01 → ... → s08 → s09 → `s10` → [s11](../s11_error_recovery/) → s12 → ... → s20 → s21 > *"模型输入是组装出来的,不是写死的"* — 稳定分段 + 运行时状态 + 缓存。 > > **Harness 层**: 上下文组装 — 把稳定指令和动态状态组成模型输入。 @@ -119,8 +119,6 @@ def get_system_prompt(context: dict) -> str: 用 `json.dumps` 而不是 `hash()`:Python 内置 `hash()` 有进程随机化,不适合做稳定 cache key,而且遇到 list/dict 会报 `unhashable type`。 -注意:这里的缓存只是"避免重复拼接字符串",和 CC 的 API prompt cache 不是一回事。CC 的 prompt cache 通过 `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` 分隔静态和动态部分,静态部分命中 global cache,不因动态内容变化而失效。 - ### context: 真实状态,不是关键词猜测 context 反映当前运行态的真实状态: @@ -178,7 +176,7 @@ cd learn-claude-code python s10_system_prompt/code.py ``` -安全说明:这份聚焦教学脚本仍用 `shell=True` 执行模型给出的 `bash` 字符串,并省略了 s03 的权限闸门。只在可丢弃工作区运行;生产 harness 必须恢复权限与沙箱边界。 +**安全说明**:脚本使用 `shell=True` 执行模型生成的 `bash` 字符串,并未接入 s03 的权限闸门。请只在可丢弃的工作区中运行。 观察重点: diff --git a/s10_system_prompt/code.py b/s10_system_prompt/code.py index 3dba1c4d..da41fa47 100644 --- a/s10_system_prompt/code.py +++ b/s10_system_prompt/code.py @@ -74,9 +74,7 @@ def get_system_prompt(context: dict) -> str: Uses json.dumps for deterministic serialization, not Python's hash() which has process randomization and fails on nested dicts/lists. - This cache only avoids redundant string assembly within a process. - Real Claude Code additionally protects API-level prompt cache via - stable section ordering and SYSTEM_PROMPT_DYNAMIC_BOUNDARY. + Stable serialization lets identical context reuse the assembled prompt. """ global _last_context_key, _last_prompt key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str) diff --git a/s11_error_recovery/README.ja.md b/s11_error_recovery/README.ja.md index cde9d586..9bfa8255 100644 --- a/s11_error_recovery/README.ja.md +++ b/s11_error_recovery/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s09 → s10 → `s11` → [s12](../s12_task_system/) → s13 → ... → s20 → s21 → s22 +s01 → ... → s09 → s10 → `s11` → [s12](../s12_task_system/) → s13 → ... → s20 → s21 > *"エラーは終わりではなく、リトライの始まり"* — トークン拡張、コンテキスト圧縮、モデル切り替え。 > > **Harness 層**: 耐障害性 — メインループのエラーを分類し復旧。 @@ -19,7 +19,7 @@ Error: 529 overloaded Agent がクラッシュした。リトライもしない、モデルも切り替えない、コンテキストも減らさない——そのままクラッシュ。 -本番環境では API エラーが日常茶飯事。最も一般的な 3 つの障害パターン:**出力の切り詰め**(モデルが途中まで出力して token が尽きた)、**コンテキスト超過**(圧縮後も長すぎる)、**一時的障害**(429 レート制限 / 529 過負荷)。エラーを処理しない Agent は、一度触れただけで止まる車のようなものだ。 +LLM API の呼び出しは失敗することがある。この章では、出力の切り詰め、コンテキスト超過、一時的障害(429/529)の 3 つを扱う。 --- @@ -29,7 +29,7 @@ Agent がクラッシュした。リトライもしない、モデルも切り s10 のループ、prompt 組み立てはすべてそのまま。唯一の変更点:LLM 呼び出しを try/except で包み、エラータイプに応じて異なる復旧パスに振り分ける。復旧後は `continue` でループ先頭に戻り、再度 LLM を呼び出す。 -最も一般的な 3 つの復旧パターン(教学版は 429/529 のみ対応;実際のシステムは接続エラー、タイムアウト、クラウドベンダーの認証キャッシュ等もカバー。CC には実際 13 以上の reason code があるが、残りは Deep dive で解説): +この章では 3 つの復旧パターンを実装する: | パターン | トリガー | 復旧アクション | |----------|----------|---------------| @@ -73,7 +73,7 @@ messages.append({"role": "assistant", "content": response.content}) LLM が「コンテキストが長すぎる」と返す(`prompt_too_long`)。s08 の 4 層圧縮をすべて実行したのに、まだ超えている。 -reactive compact をトリガー——auto compact よりも積極的。教学版は最後の 5 メッセージだけを残して圧縮をシミュレート;実際の CC は LLM で compact サマリを生成してからリトライする。圧縮後にリトライ。ただし、一度圧縮してもまだ超過している場合は終了するしかない——再度圧縮しても小さくはならない: +reactive compact を実行し、最後の 5 メッセージを残して 1 回だけ再試行する。それでも上限を超える場合は終了する: ```python except PromptTooLongError: @@ -196,82 +196,5 @@ Agent に**タスクリスト**を管理させられないだろうか——依 s12 Task System → タスクとは依存関係があり、状態があり、永続化されたグラフだ。これはマルチ Agent 協調の基盤となる。 -
-CC ソースコード深掘り - -> 以下は CC ソースコード `query.ts`(1729 行)、`services/api/withRetry.ts`(822 行)、`query/tokenBudget.ts`(93 行)、`utils/tokenBudget.ts`(73 行)の分析に基づく。 - -### 一、十数種の reason/transition(3 つだけではない) - -教学版では最も一般的な 3 つの復旧パターンを解説した。CC には実際十数種の reason/transition があり、毎回の LLM 呼び出し後に判定される: - -| reason/transition | 教学版の対応 | CC の動作 | -|---|---|---| -| `completed` | 正常終了 | 結果を返す | -| `next_turn` | 通常のツール呼び出し | 次のツール実行ラウンドへ | -| `max_output_tokens_escalate` | パス 1 | 8K→64K に拡張 | -| `max_output_tokens_recovery` | パス 1 続き出力 | 続きのプロンプト注入(最大 3 回) | -| `reactive_compact_retry` | パス 2 | reactive compact → リトライ | -| `prompt_too_long` | パス 2 | 同上 | -| `collapse_drain_retry` | 未展開 | context collapse 時にまず保留中の内容をコミット | -| `model_error` | 未展開 | リトライ | -| `image_error` | 未展開 | `ImageSizeError` / `ImageResizeError` の専用処理 | -| `aborted_streaming` | 未展開 | ストリーミング中断の復旧 | -| `aborted_tools` | 未展開 | ツール中断 | -| `stop_hook_blocking` | 未展開 | blocking error を注入 → モデルが自己修正 | -| `stop_hook_prevented` | 未展開 | hooks によるブロック | -| `hook_stopped` | 未展開 | hook による実行停止 | -| `token_budget_continuation` | 未展開 | token 使用量 < 90% の時に継続 | -| `blocking_limit` | 未展開 | ブロック制限 | -| `max_turns` | 未展開 | 最大ターン数に到達 | - -教学版では最初の 5 つ(最も一般的なもの)だけを展開した。残りはそれぞれ専用の処理ロジックを持つ。 - -### 二、指数バックオフの正確な公式 - -CC のバックオフ遅延(`withRetry.ts:530-548`): - -``` -delay = min(500 × 2^(attempt-1), 32000) + random(0~25%) -``` - -| 試行 | 基本遅延 | + ジッター | -|------|---------|-----------| -| 1 | 500ms | 0-125ms | -| 2 | 1000ms | 0-250ms | -| 4 | 4000ms | 0-1000ms | -| 7+ | 32000ms(上限) | 0-8000ms | - -サーバーが `Retry-After` ヘッダーを返した場合、その値を優先して使用する。 - -### 三、CONTINUATION プロンプト原文 - -CC の続き出力プロンプト(`query.ts:1225-1227`): - -``` -Output token limit hit. Resume directly — no apology, no recap of what -you were doing. Pick up mid-thought if that is where the cut happened. -Break remaining work into smaller pieces. -``` - -Token budget のナッジプロンプト(`tokenBudget.ts:72`): - -``` -Stopped at {pct}% of token target. Keep working — do not summarize. -``` - -### 四、ストリーミングエラー処理 - -CC のストリーミングパスでは、復旧可能なエラー(413、max_tokens、media error)はストリーミング中**表示を保留される**(`query.ts:788-822`)——SDK コンシューマーには見えず、復旧ロジックだけが認識できる。ストリーミング終了後に復旧が必要かどうかを判断する。 - -### 五、529 → フォールバックモデル切り替え - -3 回連続で 529 過負荷エラーが発生した後(`MAX_529_RETRIES = 3`)、CC は自動的にフォールバックモデルに切り替える(例:Opus → Sonnet)。切り替え時にすべての保留中のメッセージと tool 結果をクリアし、ユーザーに "Switched to {model} due to high demand" と表示する。 - -### 六、収穫逓減の検出 - -Token budget の「継続」は無限ではない。連続 3 回の continuation で token 増分が 500 未満の場合、システムは「続けても実質的な出力は得られない」と判断し、continuation を停止する(`tokenBudget.ts:60-62`)。 - -
diff --git a/s11_error_recovery/README.md b/s11_error_recovery/README.md index d216b3fc..cbb82084 100644 --- a/s11_error_recovery/README.md +++ b/s11_error_recovery/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s09 → s10 → `s11` → [s12](../s12_task_system/) → s13 → ... → s20 → s21 → s22 +s01 → ... → s09 → s10 → `s11` → [s12](../s12_task_system/) → s13 → ... → s20 → s21 > *"Errors aren't the end, they're the start of a retry"* — escalate tokens, compact context, switch models. > > **Harness layer**: Resilience — classify and recover when the main loop hits errors. @@ -19,7 +19,7 @@ Error: 529 overloaded The Agent crashes. It doesn't retry, doesn't switch models, doesn't reduce context — it just crashes. -In production, API errors are the norm. The three most common failure modes: **truncated output** (the model runs out of tokens mid-sentence), **context overflow** (still too long even after compaction), and **transient failures** (429 rate limiting / 529 overload). An Agent that doesn't handle errors is like a car that stalls at the slightest touch. +LLM API calls can fail. This chapter handles three cases: truncated output, context overflow, and transient failures (429/529). --- @@ -29,7 +29,7 @@ In production, API errors are the norm. The three most common failure modes: **t The loop and prompt assembly from s10 are fully preserved. The only change: the LLM call is wrapped in try/except, with different recovery paths based on error type. After recovery, `continue` loops back to the top to call the LLM again. -The three most common recovery patterns (the teaching version only handles 429/529; real systems also cover connection errors, timeouts, cloud vendor credential caches, etc. CC actually has 13+ reason codes; see the Deep Dive for the rest): +This chapter implements three recovery patterns: | Pattern | Trigger | Recovery Action | |----------|---------|-----------------| @@ -73,7 +73,7 @@ Escalation gets one chance; continuation gets up to 3. After that, exit — furt The LLM says "your context is too long" (`prompt_too_long`). All four compaction layers from s08 have already run, and it's still over the limit. -Trigger reactive compact — more aggressive than auto compact. The teaching version keeps only the last 5 messages to simulate compaction; real CC generates a compact summary via LLM, then retries with the compacted message list. Retry after compacting. But if it's still over the limit after one compaction, the only option is to exit — compacting again won't make it any smaller: +Trigger reactive compact: keep the last 5 messages and retry once. If the context is still over the limit, exit: ```python except PromptTooLongError: @@ -196,82 +196,5 @@ What if the Agent could manage a **task list** — with dependencies, persisted s12 Task System → Tasks form a dependency graph with state and persistence. This is the foundation for multi-Agent collaboration. -
-Deep Dive into CC Source - -> The following is based on CC source code: `query.ts` (1729 lines), `services/api/withRetry.ts` (822 lines), `query/tokenBudget.ts` (93 lines), and `utils/tokenBudget.ts` (73 lines). - -### 1. A Dozen-Plus Reason/Transition Codes (Not Just 3) - -The teaching version covers 3 of the most common recovery patterns. CC actually has a dozen-plus reason/transition codes, evaluated after every LLM call: - -| Reason/Transition | Teaching Version | CC Behavior | -|---|---|---| -| `completed` | Normal completion | Return result | -| `next_turn` | Normal tool call | Continue to next tool execution round | -| `max_output_tokens_escalate` | Path 1 | 8K→64K escalation | -| `max_output_tokens_recovery` | Path 1 continuation | Continuation prompt (up to 3 times) | -| `reactive_compact_retry` | Path 2 | Reactive compact → retry | -| `prompt_too_long` | Path 2 | Same as above | -| `collapse_drain_retry` | Not covered | Context collapse — commit staged content first | -| `model_error` | Not covered | Retry | -| `image_error` | Not covered | `ImageSizeError` / `ImageResizeError` handled specifically | -| `aborted_streaming` | Not covered | Streaming abort recovery | -| `aborted_tools` | Not covered | Tool abort | -| `stop_hook_blocking` | Not covered | Inject blocking error → model self-corrects | -| `stop_hook_prevented` | Not covered | Hooks prevent execution | -| `hook_stopped` | Not covered | Hook stopped execution | -| `token_budget_continuation` | Not covered | Continue when token usage < 90% | -| `blocking_limit` | Not covered | Blocking limit reached | -| `max_turns` | Not covered | Maximum turns reached | - -The teaching version only expands on the first 5 (most common); each of the rest has its own dedicated handling logic. - -### 2. Precise Exponential Backoff Formula - -CC's backoff delay (`withRetry.ts:530-548`): - -``` -delay = min(500 × 2^(attempt-1), 32000) + random(0~25%) -``` - -| Attempt | Base Delay | + Jitter | -|---------|-----------|----------| -| 1 | 500ms | 0-125ms | -| 2 | 1000ms | 0-250ms | -| 4 | 4000ms | 0-1000ms | -| 7+ | 32000ms (cap) | 0-8000ms | - -If the server returns a `Retry-After` header, that value takes priority. - -### 3. Original CONTINUATION Prompt - -CC's continuation prompt (`query.ts:1225-1227`): - -``` -Output token limit hit. Resume directly — no apology, no recap of what -you were doing. Pick up mid-thought if that is where the cut happened. -Break remaining work into smaller pieces. -``` - -Token budget nudge prompt (`tokenBudget.ts:72`): - -``` -Stopped at {pct}% of token target. Keep working — do not summarize. -``` - -### 4. Streaming Error Handling - -In CC's streaming path, recoverable errors (413, max_tokens, media errors) are **withheld from display** during streaming (`query.ts:788-822`) — SDK consumers don't see them, only the recovery logic does. After streaming ends, the system determines whether recovery is needed. - -### 5. 529 → Fallback Model Switch - -After 3 consecutive 529 overload errors (`MAX_529_RETRIES = 3`), CC automatically switches to the fallback model (e.g., Opus → Sonnet). On switch, all pending messages and tool results are cleared, and the user sees "Switched to {model} due to high demand". - -### 6. Diminishing Returns Detection - -Token budget "continuations" aren't unlimited. When there are 3 consecutive continuations with a token increment < 500, the system determines "continuing won't produce meaningful output" and stops continuation (`tokenBudget.ts:60-62`). - -
diff --git a/s11_error_recovery/README.zh.md b/s11_error_recovery/README.zh.md index 7898cc95..da3ffcb0 100644 --- a/s11_error_recovery/README.zh.md +++ b/s11_error_recovery/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s09 → s10 → `s11` → [s12](../s12_task_system/) → s13 → ... → s20 → s21 → s22 +s01 → ... → s09 → s10 → `s11` → [s12](../s12_task_system/) → s13 → ... → s20 → s21 > *"错误不是终点, 是重试的起点"* — 升级 token、压缩上下文、切换模型。 > > **Harness 层**: 韧性 — 主循环遇到错误时分类并恢复。 @@ -19,7 +19,7 @@ Error: 529 overloaded Agent 崩溃了。它没有重试,没有换模型,没有减少上下文——直接崩溃。 -生产环境中 API 错误是常态。三种最常见的故障模式:**输出被截断**(模型话说一半 token 用完了)、**上下文超限**(压缩后还是太长)、**临时故障**(429 限流 / 529 过载)。一个不处理错误的 Agent 就像一个一碰就熄火的车。 +LLM API 调用可能失败。本章处理三种情况:输出截断、上下文超限和临时故障(429/529)。 --- @@ -29,7 +29,7 @@ Agent 崩溃了。它没有重试,没有换模型,没有减少上下文— s10 的循环、prompt 组装全部保留。唯一的变动:LLM 调用包裹在 try/except 里,根据错误类型走不同的恢复路径。恢复后 `continue` 回到循环开头重新调用 LLM。 -三种最常见的恢复模式(教学版只处理 429/529;真实系统还覆盖连接错误、超时、云厂商认证缓存等。CC 实际有 13+ reason code,其余见 Deep dive): +本章实现三种恢复模式: | 模式 | 触发 | 恢复动作 | |------|------|---------| @@ -73,7 +73,7 @@ messages.append({"role": "assistant", "content": response.content}) LLM 说"你的上下文太长了"(`prompt_too_long`)。s08 的四层压缩全跑过了,还是超。 -触发 reactive compact——比 auto compact 更激进。教学版只保留最后 5 条消息模拟压缩效果;真实实现会调用 LLM 生成 compact 摘要再重试。压缩后重试。但如果压缩过一次还是超限,只能退出——再压缩也不会变小: +触发 reactive compact:保留最后 5 条消息后重试一次。如果仍然超限,则退出: ```python except PromptTooLongError: @@ -196,82 +196,5 @@ Agent 现在能在错误中自动恢复了。但它处理的任务仍然是"一 s12 Task System → 任务是有依赖、有状态、持久化的图。这是多 Agent 协作的基础。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `query.ts`(1729 行)、`services/api/withRetry.ts`(822 行)、`query/tokenBudget.ts`(93 行)、`utils/tokenBudget.ts`(73 行)的分析。 - -### 一、十几种 reason/transition(不只是 3 条) - -教学版讲了 3 种最常见的恢复模式。CC 实际有十几种 reason/transition,每轮 LLM 调用后都会判断: - -| reason/transition | 教学版对应 | CC 行为 | -|---|---|---| -| `completed` | 正常完成 | 返回结果 | -| `next_turn` | 正常工具调用 | 继续下一轮工具执行 | -| `max_output_tokens_escalate` | 路径 1 | 8K→64K 升级 | -| `max_output_tokens_recovery` | 路径 1 续写 | 续写提示(最多 3 次) | -| `reactive_compact_retry` | 路径 2 | reactive compact → 重试 | -| `prompt_too_long` | 路径 2 | 同上 | -| `collapse_drain_retry` | 未展开 | context collapse 先提交暂存 | -| `model_error` | 未展开 | 重试 | -| `image_error` | 未展开 | `ImageSizeError` / `ImageResizeError` 专门处理 | -| `aborted_streaming` | 未展开 | 流式中止恢复 | -| `aborted_tools` | 未展开 | 工具中止 | -| `stop_hook_blocking` | 未展开 | 注入 blocking error → 模型自纠 | -| `stop_hook_prevented` | 未展开 | hooks 阻止 | -| `hook_stopped` | 未展开 | hook 停止执行 | -| `token_budget_continuation` | 未展开 | token 用量 < 90% 时继续 | -| `blocking_limit` | 未展开 | 阻塞限制 | -| `max_turns` | 未展开 | 达到最大轮次 | - -教学版只展开了前 5 种(最常见的),其余各有专门处理逻辑。 - -### 二、指数退避的精确公式 - -CC 的退避延迟(`withRetry.ts:530-548`): - -``` -delay = min(500 × 2^(attempt-1), 32000) + random(0~25%) -``` - -| 尝试 | 基础延迟 | + 抖动 | -|------|---------|--------| -| 1 | 500ms | 0-125ms | -| 2 | 1000ms | 0-250ms | -| 4 | 4000ms | 0-1000ms | -| 7+ | 32000ms(上限) | 0-8000ms | - -如果服务器返回 `Retry-After` header,优先用那个值。 - -### 三、CONTINUATION 提示原文 - -CC 的续写提示(`query.ts:1225-1227`): - -``` -Output token limit hit. Resume directly — no apology, no recap of what -you were doing. Pick up mid-thought if that is where the cut happened. -Break remaining work into smaller pieces. -``` - -Token budget 的 nudge 提示(`tokenBudget.ts:72`): - -``` -Stopped at {pct}% of token target. Keep working — do not summarize. -``` - -### 四、流式错误处理 - -CC 的流式路径中,可恢复的错误(413、max_tokens、media error)在 streaming 期间**被暂扣不展示**(`query.ts:788-822`)——SDK 消费者看不到,只有恢复逻辑能看到。等 streaming 结束后才判断是否需要恢复。 - -### 五、529 → Fallback Model 切换 - -连续 3 次 529 过载错误后(`MAX_529_RETRIES = 3`),CC 自动切换到 fallback model(如 Opus → Sonnet)。切换时清除所有 pending 消息和 tool 结果,给用户展示 "Switched to {model} due to high demand"。 - -### 六、Diminishing Returns 检测 - -Token budget 的"继续"不是无限的。当连续 3 次 continuation 且 token 增量 < 500 时,系统判断"继续也没有实质性产出",停止 continuation(`tokenBudget.ts:60-62`)。 - -
diff --git a/s11_error_recovery/code.py b/s11_error_recovery/code.py index f54fe28c..c40882a5 100644 --- a/s11_error_recovery/code.py +++ b/s11_error_recovery/code.py @@ -233,10 +233,7 @@ def is_prompt_too_long_error(e: Exception) -> bool: def reactive_compact(messages: list) -> list: - """Emergency compact — teaching version keeps last N messages. - Real CC generates a compact summary via LLM, then retries with - the compacted message list. Teaching version simplifies to tail - retention since s08/s09 already cover LLM-based compact.""" + """Emergency compact: keep the latest messages, then retry.""" print(" \033[31m[reactive compact] trimming to last 5 messages\033[0m") tail = messages[-5:] return [{"role": "user", diff --git a/s12_task_system/README.ja.md b/s12_task_system/README.ja.md index ac20a05a..a5851043 100644 --- a/s12_task_system/README.ja.md +++ b/s12_task_system/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s14 → ... → s20 → s21 → s22 +s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s14 → ... → s20 → s21 > *"大きな目標を小さなタスクに分け、順序付け、永続化"* — ファイル永続化タスクグラフ、マルチ Agent 協調の基盤。 > @@ -14,7 +14,7 @@ s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s1 Agent がプロジェクトを受けた:データベース構築、API 実装、テスト追加。s05 の TodoWrite でリストを作り、まず API を書き始め、途中でデータベーステーブルがないことに気づいて戻る。テスト追加時に API インターフェースのシグネチャがまた変わっている... -屋根を先に建てて基礎を後から打つことはできない。タスクには順序がある。タスクの依存関係は有向非巡回グラフ(DAG)を形成すべき;教学版は `blockedBy` チェックのみをデモし、循環検出は実装していない。 +屋根を先に建てて基礎を後から打つことはできない。タスクには順序がある。タスク間の前提依存関係は有向非巡回グラフ(DAG)として表現でき、この章では `blockedBy` でそれらを記録する。 s05 の TodoWrite は現在のタスクの実行チェックリストで、セッションメモリに保持される。ここで必要なのは**タスクシステム**:各タスクは JSON ファイル、タスク間に `blockedBy` 依存関係、ディスク上でセッションをまたいで永続化。 @@ -24,7 +24,7 @@ s05 の TodoWrite は現在のタスクの実行チェックリストで、セ ![Task System Overview](images/task-system-overview.ja.svg) -教育版は基本 agent loop を維持し、タスクシステムに集中するため S11 の完全なエラーリカバリ(RecoveryState、バックオフ、エスカレーション、reactive compact、フォールバックモデル)を省略。追加:5 つの教育用ツール + `.tasks/` ディレクトリによる永続化 + `blockedBy` 依存チェック。タスクシステムとエラーリカバリは独立したレイヤーで、タスクモジュールは状態を、query recovery はモデル呼び出し失敗を扱う。 +この章では、5 つのタスクツール、`.tasks/` ディレクトリへの永続化、`blockedBy` の依存チェックを追加する。 TodoWrite vs Task System: @@ -39,8 +39,6 @@ TodoWrite vs Task System: | 粒度 | Agent 自身の手順 | 認識・追跡・アンロックできるタスク | | 更新契約 | リスト全体を置換 | 個別レコードを作成・取得・更新・一覧 | -教育用 API は `create_task`、`list_tasks`、`get_task`、`claim_task`、`complete_task` としてライフサイクルを明示する。Claude Code の製品サーフェスはこれらを `TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList` の 4 ツールにまとめ、認識と完了は独立した公式ツールではなく更新操作として扱う。 - --- ## 仕組み @@ -62,7 +60,7 @@ class Task: blockedBy: list[str] # 依存タスク ID のリスト ``` -ID は `timestamp + random hex` で生成、シンプルだが十分。CC は順次 ID + highwatermark ファイルで ID 再利用を防止する、より厳密な設計。 +ID は `timestamp + random hex` で生成する。 ### create_task: タスク作成 @@ -162,8 +160,6 @@ pending ──claim──→ in_progress ──complete──→ completed - **claim_task**: `pending` → `in_progress`。owner を設定し、作業を開始。 - **complete_task**: `in_progress` → `completed`。タスクを完了済みにし、下流をアンロック。 -CC には `in_progress → pending` の release パスがない。teammate が終了または shutdown した場合、CC は未完了タスクの owner をクリアし、status を `pending` にリセットし、他の agent が再認識できるようにする。教学版はこの復旧パスを省略。 - ### 組み合わせて実行 ```python @@ -228,58 +224,5 @@ python s12_task_system/code.py s13 Background Tasks → 遅い操作はバックグラウンドへ。Agent は他のタスクの処理を続け、バックグラウンドの完了を通知で受け取る。 -
-CC ソースコード深掘り - -> 以下は CC ソースコード `utils/tasks.ts`(862 行)、`tools/TaskCreateTool/TaskCreateTool.ts`(138 行)、`tools/TaskUpdateTool/TaskUpdateTool.ts`(406 行)、`tools/TaskGetTool/TaskGetTool.ts`(128 行)、`tools/TaskListTool/TaskListTool.ts`(116 行)、`hooks/useTaskListWatcher.ts`(221 行)の完全分析に基づく。 - -### 一、TaskRecord の完全フィールド - -チュートリアルでは id、subject、status、owner、blockedBy のみ解説。CC は実際に 9 フィールドを持つ(`utils/tasks.ts:76-89`): - -| フィールド | 型 | 用途 | -|------|------|------| -| `id` | string | 昇順整数 ID | -| `subject` | string | 短いタイトル | -| `description` | string | 自由形式の説明 | -| `activeForm` | string? | 現在進行形、in_progress 時にスピナーに表示 | -| `owner` | string? | 割り当てられた agent ID | -| `status` | pending/in_progress/completed | ライフサイクル | -| `blocks` | string[] | このタスクがブロックするタスク ID(下流) | -| `blockedBy` | string[] | このタスクをブロックするタスク ID(上流) | -| `metadata` | Record? | 任意の拡張キーバリューペア | - -保存場所:`~/.claude/tasks/{taskListId}/{id}.json`。タスクごとに 1 ファイル。 - -### 二、目的は近いが、機構は独立 - -Task ツールと TodoWrite は共存できるが、同じストレージモデルを共有しない。現在の対話型セッションは構造化 Task ツールを既定で使い、TodoWrite は非対話型や Agent SDK などの互換サーフェスに残る。公開範囲はリリースや設定で変わり得る。Task レコードはファイルロック、依存関係、ownership、リアクティブ監視、ライフサイクルフックを追加し、TodoWrite はリスト全体を置換するセッションチェックリストである。 - -### 三、並行認識のロック機構 - -`claimTask()`(`utils/tasks.ts:541-612`)は二重ロックで競合を防止: - -**タスクファイルロック**:`proper-lockfile` で `{taskId}.json` をロック(最大 30 リトライ、指数バックオフ 5-100ms)。ロック内: -1. タスクを再読込(TOCTOU 防止) -2. 既に他者が認識済み → `already_claimed` -3. 既に完了済み → `already_resolved` -4. 上流が未完了 → `blocked` -5. owner を設定 - -**リストレベルロック**(agent busy チェック時):`.lock` ファイル、全タスクを原子的に走査し該当 agent が他の open task を持つか確認。 - -注意:教学版は認識と作業開始を 1 ステップに統合(claim = owner 設定 + in_progress);実際の CC の `claimTask` は主に owner 競合を解決し、owner のみを設定して status は変更しない。status の更新は `TaskUpdate` が担当。 - -### 四、高水位標による ID 再利用防止 - -`.highwatermark` ファイルが過去に割り当てられた最大タスク ID を記録。タスクが削除されても ID は再利用されない。 - -### 五、4 つの Task ツール - -CC のタスクシステムは 4 つのツールを持つ(チュートリアルの汎用 Task ツールとは異なる):`TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList`。すべて `isConcurrencySafe: true` と `shouldDefer: true` が設定(ツールスキーマは初期プロンプトに含まれず、ToolSearch 後にのみ可視)。 - -教学版の `create_task(blockedBy=...)` は作成時に直接依存を宣言する合理な簡略化。実際の CC の `TaskCreate` は subject/description/activeForm/metadata のみを受け付け、依存関係は `TaskUpdate` の `addBlocks/addBlockedBy` で管理される。 - -
diff --git a/s12_task_system/README.md b/s12_task_system/README.md index 439ff298..96b57daa 100644 --- a/s12_task_system/README.md +++ b/s12_task_system/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s14 → ... → s20 → s21 → s22 +s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s14 → ... → s20 → s21 > *"Break big goals into small tasks, order them, persist"* — File-persisted task graph, the foundation for multi-agent collaboration. > @@ -14,7 +14,7 @@ s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s1 The agent receives a project: set up a database, write APIs, add tests. It uses s05's TodoWrite to create a checklist, then starts writing the API first, gets halfway through and realizes there are no database tables, goes back to fix them; when adding tests, discovers the API interface signatures have changed again... -You can't build the roof before laying the foundation. Tasks have ordering. Task dependencies should form a Directed Acyclic Graph (DAG); the teaching version only demonstrates `blockedBy` checking, without cycle detection. +You can't build the roof before laying the foundation. Tasks have ordering. Task prerequisites can be represented as a Directed Acyclic Graph (DAG); this chapter records them with `blockedBy`. s05's TodoWrite is an execution checklist for the current task, kept in session memory. What you need here is a **task system**: each task is a JSON file, tasks have `blockedBy` dependencies, and they persist across sessions on disk. @@ -24,7 +24,7 @@ s05's TodoWrite is an execution checklist for the current task, kept in session ![Task System Overview](images/task-system-overview.en.svg) -Teaching code keeps a basic agent loop, omitting S11's full error recovery (RecoveryState, backoff, escalation, reactive compact, fallback model) to stay focused on the task system. Added: 5 teaching tools + `.tasks/` directory for persistence + `blockedBy` dependency checking. The task system and error recovery are independent layers: in CC source, `utils/tasks.ts` handles task state while query recovery handles model-call failures. +This chapter adds 5 task tools, persistence in the `.tasks/` directory, and `blockedBy` dependency checks. TodoWrite vs Task System: @@ -39,8 +39,6 @@ TodoWrite vs Task System: | Granularity | The agent's own steps | Tasks that can be claimed, tracked, and unblocked | | Update contract | Replace the whole checklist | Create/get/update/list individual records | -The teaching API spells the lifecycle out as `create_task`, `list_tasks`, `get_task`, `claim_task`, and `complete_task`. Claude Code's product surface groups those operations into four tools: `TaskCreate`, `TaskGet`, `TaskUpdate`, and `TaskList`; claiming and completion are updates, not separate official tools. - --- ## How It Works @@ -62,7 +60,7 @@ class Task: blockedBy: list[str] # List of dependency task IDs ``` -IDs are generated with `timestamp + random hex`, simple but sufficient. CC uses sequential IDs + a highwatermark file to prevent ID reuse, which is a more rigorous design. +IDs are generated with `timestamp + random hex`. ### create_task: Create Tasks @@ -162,8 +160,6 @@ Here `claim` / `complete` are actions, while `pending` / `in_progress` / `comple - **claim_task**: `pending` → `in_progress`. Sets owner, begins work. - **complete_task**: `in_progress` → `completed`. Marks the task done and unblocks downstream. -CC has no `in_progress → pending` release path. If a teammate terminates or shuts down, CC unassigns its unfinished tasks (clears owner) and resets status to `pending`, allowing other agents to reclaim them. The teaching version omits this recovery path. - ### Putting It Together ```python @@ -228,58 +224,5 @@ The task graph is in place. But some tasks take a long time — like running ful s13 Background Tasks → Slow operations go to the background. The agent continues processing other tasks, and gets notified when the background work is done. -
-Deep Dive into CC Source - -> The following is a complete analysis based on CC source code `utils/tasks.ts` (862 lines), `tools/TaskCreateTool/TaskCreateTool.ts` (138 lines), `tools/TaskUpdateTool/TaskUpdateTool.ts` (406 lines), `tools/TaskGetTool/TaskGetTool.ts` (128 lines), `tools/TaskListTool/TaskListTool.ts` (116 lines), `hooks/useTaskListWatcher.ts` (221 lines). - -### 1. TaskRecord's Full Fields - -The tutorial only covers id, subject, status, owner, blockedBy. CC actually has 9 fields (`utils/tasks.ts:76-89`): - -| Field | Type | Purpose | -|------|------|---------| -| `id` | string | Incrementing integer ID | -| `subject` | string | Short title | -| `description` | string | Free-form description | -| `activeForm` | string? | Present tense form, shown in spinner when in_progress | -| `owner` | string? | Assigned agent ID | -| `status` | pending/in_progress/completed | Lifecycle | -| `blocks` | string[] | Task IDs blocked by this task (downstream) | -| `blockedBy` | string[] | Task IDs blocking this task (upstream) | -| `metadata` | Record? | Arbitrary extension key-value pairs | - -Storage location: `~/.claude/tasks/{taskListId}/{id}.json`. One file per task. - -### 2. Same Intent, Independent Mechanisms - -Task tools and TodoWrite can coexist, but they do not share one storage model. Current interactive sessions default to structured Task tools, while TodoWrite remains on compatibility surfaces such as non-interactive and Agent SDK usage; exact exposure varies by release and configuration. Task records add file-lock concurrency protection, dependency enforcement, ownership, reactive monitoring, and lifecycle hooks. TodoWrite remains a whole-list session checklist. - -### 3. Concurrent Claim Locking - -`claimTask()` (`utils/tasks.ts:541-612`) uses dual locking to prevent races: - -**Task file lock**: `proper-lockfile` locks `{taskId}.json` (up to 30 retries, exponential backoff 5-100ms). Inside the lock: -1. Re-read task (prevent TOCTOU) -2. Check already claimed by another → `already_claimed` -3. Check already completed → `already_resolved` -4. Check upstream not completed → `blocked` -5. Set owner - -**List-level lock** (agent busy check): `.lock` file, atomic scan of all tasks to check if the agent already has other open tasks. - -Note: The teaching version combines claiming and starting work into one step (claim = set owner + in_progress); real CC's `claimTask` primarily resolves owner competition — it only sets owner without changing status. Status updates are handled by `TaskUpdate`. - -### 4. High-Water Mark to Prevent ID Reuse - -The `.highwatermark` file records the highest task ID ever assigned. Even if a task is deleted, its ID won't be reused. - -### 5. Four Task Tools - -CC's task system has four tools (not the tutorial's single generic Task tool): `TaskCreate`, `TaskGet`, `TaskUpdate`, `TaskList`. All set `isConcurrencySafe: true` and `shouldDefer: true` (tool schemas aren't in the initial prompt; only visible after ToolSearch). - -The teaching version's `create_task(blockedBy=...)` declares dependencies at creation time, which is a reasonable simplification. Real CC's `TaskCreate` only accepts subject/description/activeForm/metadata — dependencies are maintained via `TaskUpdate`'s `addBlocks/addBlockedBy`. - -
diff --git a/s12_task_system/README.zh.md b/s12_task_system/README.zh.md index 10473d6d..9caf1472 100644 --- a/s12_task_system/README.zh.md +++ b/s12_task_system/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s14 → ... → s20 → s21 → s22 +s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s14 → ... → s20 → s21 > *"大目标拆成小任务, 排好序, 持久化"* — 文件持久化的任务图, 多 agent 协作的基础。 > @@ -14,7 +14,7 @@ s01 → ... → s10 → s11 → `s12` → [s13](../s13_background_tasks/) → s1 Agent 接到一个项目:搭数据库、写 API、加测试。它用 s05 的 TodoWrite 列了一张清单,然后开始写 API,写到一半发现没数据库表,回头补;加测试时发现 API 接口签名又变了... -盖房子不能先盖屋顶再打地基。任务之间有先后。任务依赖应该形成有向无环图(DAG);教学版只演示 `blockedBy` 检查,没有实现环检测。 +盖房子不能先盖屋顶再打地基。任务之间有先后。任务之间的前置依赖可以表示为有向无环图(DAG),本章用 `blockedBy` 记录这些依赖。 s05 的 TodoWrite 是当前任务的执行清单,保存在会话内存中。这里需要的是**任务系统**:每个任务是一个 JSON 文件,任务之间有 `blockedBy` 依赖,跨会话持久化在磁盘上。 @@ -24,7 +24,7 @@ s05 的 TodoWrite 是当前任务的执行清单,保存在会话内存中。 ![Task System Overview](images/task-system-overview.svg) -教学代码保留基础 agent loop,为聚焦任务系统省略了 S11 的完整错误恢复(RecoveryState、退避、升级、reactive compact、fallback model)。新增 5 个教学工具 + `.tasks/` 目录持久化 + `blockedBy` 依赖检查。任务系统与错误恢复是独立层:CC 源码中的任务模块管理任务状态,query recovery 管理模型调用失败。 +本章新增 5 个任务工具、`.tasks/` 目录持久化和 `blockedBy` 依赖检查。 TodoWrite vs Task System: @@ -39,8 +39,6 @@ TodoWrite vs Task System: | 粒度 | Agent 自己的步骤 | 可被认领、追踪、解锁的任务 | | 更新契约 | 整表替换 | 对单条记录执行创建、读取、更新、列举 | -教学 API 用 `create_task`、`list_tasks`、`get_task`、`claim_task`、`complete_task` 把生命周期展开。Claude Code 的产品表面把这些操作归入四个工具:`TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList`;认领与完成属于更新,不是独立的官方工具。 - --- ## 工作原理 @@ -62,7 +60,7 @@ class Task: blockedBy: list[str] # 依赖的任务 ID 列表 ``` -ID 用 `timestamp + random hex` 生成,简单但够用。CC 用顺序 ID + highwatermark 文件防止 ID 重用,是更严谨的设计。 +ID 使用 `timestamp + random hex` 生成。 ### create_task: 创建任务 @@ -162,8 +160,6 @@ pending ──claim──→ in_progress ──complete──→ completed - **claim_task**: `pending` → `in_progress`。设置 owner,开始工作。 - **complete_task**: `in_progress` → `completed`。把任务标记为完成,并解锁下游。 -CC 没有 `in_progress → pending` 的 release 路径。如果 teammate 终止或 shutdown,CC 会把它未完成的任务 unassign(清除 owner),并将 status 重置为 `pending`,方便其他 agent 重新认领。教学版省略了这一恢复路径。 - ### 合起来跑 ```python @@ -228,58 +224,5 @@ python s12_task_system/code.py s13 Background Tasks → 慢操作放后台。Agent 继续处理其他任务,后台跑完了通知它。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `utils/tasks.ts`(862 行)、`tools/TaskCreateTool/TaskCreateTool.ts`(138 行)、`tools/TaskUpdateTool/TaskUpdateTool.ts`(406 行)、`tools/TaskGetTool/TaskGetTool.ts`(128 行)、`tools/TaskListTool/TaskListTool.ts`(116 行)、`hooks/useTaskListWatcher.ts`(221 行)的分析。 - -### 一、TaskRecord 的完整字段 - -教学版只讲了 id、subject、status、owner、blockedBy。CC 实际有 9 个字段(`utils/tasks.ts:76-89`): - -| 字段 | 类型 | 用途 | -|------|------|------| -| `id` | string | 递增整数 ID | -| `subject` | string | 简短标题 | -| `description` | string | 自由格式描述 | -| `activeForm` | string? | 进行时态,in_progress 时在 spinner 显示 | -| `owner` | string? | 分配的 agent ID | -| `status` | pending/in_progress/completed | 生命周期 | -| `blocks` | string[] | 此任务阻塞的任务 ID(下游) | -| `blockedBy` | string[] | 阻塞此任务的任务 ID(上游) | -| `metadata` | Record? | 任意扩展键值对 | - -存储位置:`~/.claude/tasks/{taskListId}/{id}.json`。每个任务一个文件。 - -### 二、目标相近,机制独立 - -Task 工具与 TodoWrite 可以同时存在,但不共享一套存储模型。当前交互式会话默认使用结构化 Task 工具;TodoWrite 仍位于非交互式、Agent SDK 等兼容表面,具体暴露方式会随版本和配置变化。Task 记录增加了文件锁并发保护、依赖强制执行、ownership、响应式监听和生命周期 hooks;TodoWrite 仍是整表替换的会话清单。 - -### 三、并发认领的锁机制 - -`claimTask()`(`utils/tasks.ts:541-612`)用双重锁防竞争: - -**任务文件锁**:`proper-lockfile` 锁住 `{taskId}.json`(最多重试 30 次,指数退避 5-100ms)。锁内: -1. 重新读取任务(防 TOCTOU) -2. 检查已被他人认领 → `already_claimed` -3. 检查已完成 → `already_resolved` -4. 检查上游未完成 → `blocked` -5. 设置 owner - -**列表级锁**(agent busy 检查时):`.lock` 文件,原子性扫描所有任务并检查该 agent 是否已有其他 open task。 - -注意:教学版把 claim 和开始工作合成一步(claim = set owner + in_progress);真实 CC 的 `claimTask` 主要解决 owner 竞争,只设 owner 不改 status,状态更新由 `TaskUpdate` 完成。 - -### 四、高水位标防 ID 重用 - -`.highwatermark` 文件记录曾分配过的最高任务 ID。即使任务被删除,ID 也不会被重用。 - -### 五、四个 Task 工具 - -CC 的任务系统有四个工具(不是教学版的一个通用 Task 工具):`TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList`。全部设置 `isConcurrencySafe: true` 和 `shouldDefer: true`(工具 schema 不在初始 prompt 中,需 ToolSearch 后才可见)。 - -教学版的 `create_task(blockedBy=...)` 在创建时直接声明依赖,是合理简化。真实 CC 的 `TaskCreate` 只接受 subject/description/activeForm/metadata,依赖关系由 `TaskUpdate` 的 `addBlocks/addBlockedBy` 维护。 - -
diff --git a/s12_task_system/code.py b/s12_task_system/code.py index 7f442ebf..eba42501 100644 --- a/s12_task_system/code.py +++ b/s12_task_system/code.py @@ -14,10 +14,8 @@ Changes from s11: - complete_task: set completed + report unblocked downstream - 5 new tools: create_task, list_tasks, get_task, claim_task, complete_task -Note: Teaching code keeps a basic agent loop to stay focused on the task -system. S11's full error recovery (RecoveryState, backoff, escalation, -reactive compact, fallback model) is omitted — in real CC, tasks.ts and -withRetry are independent layers that compose naturally. +This chapter keeps the agent loop focused on the task system. Error recovery +remains the independent layer introduced in s11. """ import os, subprocess, json, time, random diff --git a/s12_task_system/images/task-system-overview.en.svg b/s12_task_system/images/task-system-overview.en.svg index b4a74b6c..4337f6eb 100644 --- a/s12_task_system/images/task-system-overview.en.svg +++ b/s12_task_system/images/task-system-overview.en.svg @@ -57,7 +57,7 @@ .tasks/ — Cross-session Persistence task_xxx.json · task_yyy.json · task_zzz.json {id, subject, description, status, owner, blockedBy} - Tutorial ID: timestamp + random | CC: sequential ID + highwatermark + ID: timestamp + random diff --git a/s12_task_system/images/task-system-overview.ja.svg b/s12_task_system/images/task-system-overview.ja.svg index 906a0dbf..68b56a5c 100644 --- a/s12_task_system/images/task-system-overview.ja.svg +++ b/s12_task_system/images/task-system-overview.ja.svg @@ -57,7 +57,7 @@ .tasks/ — セッション横断永続化 task_xxx.json · task_yyy.json · task_zzz.json {id, subject, description, status, owner, blockedBy} - チュートリアル ID: timestamp + random | CC: 順次 ID + highwatermark + ID: timestamp + random diff --git a/s12_task_system/images/task-system-overview.svg b/s12_task_system/images/task-system-overview.svg index 097b61f3..5dbfb11f 100644 --- a/s12_task_system/images/task-system-overview.svg +++ b/s12_task_system/images/task-system-overview.svg @@ -57,7 +57,7 @@ .tasks/ — 跨会话持久化 task_xxx.json · task_yyy.json · task_zzz.json {id, subject, description, status, owner, blockedBy} - 教学版 ID: timestamp + random | CC: 顺序 ID + highwatermark + ID: timestamp + random diff --git a/s13_background_tasks/README.ja.md b/s13_background_tasks/README.ja.md index 8941f78f..35a66589 100644 --- a/s13_background_tasks/README.ja.md +++ b/s13_background_tasks/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 → s22 +s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 > *"遅い操作はバックグラウンドへ、agent は処理を継続"* — バックグラウンドスレッドでコマンドを実行、完了時に通知を注入。 > @@ -24,7 +24,7 @@ Agent の bash ツールも同じ。`pip install torch` は 10 分、`npm run bu ![Background Tasks Overview](images/background-tasks-overview.ja.svg) -教学版は S12 の簡易タスクシステムとプロンプト組み立てを踏襲。バックグラウンドタスクに集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。唯一の変更:遅い操作をバックグラウンドスレッドに投げ、Agent はループを継続、バックグラウンド完了時に通知を注入。 +この章では、時間のかかる操作をバックグラウンドスレッドに送り、Agent はループを続行する。タスクが完了すると、結果が通知として会話に注入される。 同期 vs バックグラウンド: @@ -41,7 +41,7 @@ Agent の bash ツールも同じ。`pip install torch` は 10 分、`npm run bu ### should_run_background: 明示的リクエスト優先、ヒューリスティックフォールバック -モデルは bash ツールの `run_in_background` パラメータで明示的にバックグラウンド実行をリクエストする。モデルが指定しない場合、教学版はキーワードヒューリスティックにフォールバック: +モデルは bash ツールの `run_in_background` パラメータで明示的にバックグラウンド実行をリクエストする。指定がない場合は、キーワードヒューリスティックで判断する: ```python def is_slow_operation(tool_name: str, tool_input: dict) -> bool: @@ -61,8 +61,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool: return is_slow_operation(tool_name, tool_input) ``` -CC の bash ツールスキーマには `run_in_background: boolean` パラメータがある(`BashTool.tsx:241`)。モデルがどのコマンドをバックグラウンドにするかを決定、キーワード推測ではない。教学版はヒューリスティックをフォールバックとして残すが、主パスはモデルの明示的リクエスト。 - ### start_background_task: バックグラウンド実行とライフサイクル ツール呼び出しをワーカー関数にラップし、daemon スレッドにディスパッチ。各バックグラウンドタスクは一意 ID を持ち、`background_tasks` 辞書で状態を追跡: @@ -96,7 +94,7 @@ def start_background_task(block) -> str: return bg_id ``` -`[Running in background...]` ではなく `bg_id` を返す。`daemon=True` で Agent プロセス終了時にスレッドも終了。教学版はメモリ内辞書で追跡。実際の CC は `LocalShellTaskState` を持ち、出力をファイルにリダイレクト、タスク停止や継続出力読み取りを含む完全なライフサイクルを備える。 +`start_background_task()` は `bg_id` を返す。`daemon=True` により、Agent プロセスの終了時にスレッドも終了する。 ### collect_background_results: 通知収集 @@ -157,8 +155,6 @@ messages.append({"role": "user", "content": user_content}) 遅い操作は `bg_id` 付きプレースホルダー tool_result を返し、LLM はコマンドがまだ実行中だと知り、先に他のことをできる。バックグラウンド完了時、通知は独立した text block として現在のターンの tool_result と一緒に 1 つの user メッセージを構成する。 -教学版は agent loop が継続実行中にバックグラウンド結果をポーリングする。実際の CC は通知キュー(`messageQueueManager.ts`)でバックグラウンド完了イベントを後続ターンに配信、ツールループを待つ必要はない。 - ### 組み合わせて実行 ``` @@ -216,46 +212,5 @@ python s13_background_tasks/code.py s14 Cron Scheduler → Agent にアラームクロックを付ける。 -
-CC ソースコード深掘り - -> 以下は CC ソースコード `query.ts`(211, 1054-1060, 1411-1482 行)、`services/toolUseSummary/toolUseSummaryGenerator.ts`(L15 プロンプトテキスト)、`LocalShellTask.tsx`(L24-25 定数, L59-98 ウォッチドッグロジック)、`messageQueueManager.ts`(通知キュー)、`utils/task/framework.ts`(L267 `enqueueTaskNotification`)の完全分析に基づく。 - -### 一、pendingToolUseSummary:Haiku バックグラウンド生成 - -CC は各ツール実行バッチの後、Haiku サイドクエリを開始してツール使用サマリを生成。開始コードは `query.ts:1411-1482`、プロンプトテキストは `services/toolUseSummary/toolUseSummaryGenerator.ts:15`(変数 `TOOL_USE_SUMMARY_SYSTEM_PROMPT`)。プロンプトは "Write a short summary label... think git-commit-subject, not sentence"、過去形、約 30 文字。 - -Haiku サマリ(~1s)はメインモデルのストリーミング出力(5-30s)中に完了。次のターン開始前にサマリを yield。SDK コンシューマーはこれらのサマリをモバイル進捗表示に使用。 - -### 二、スレッドモデル:本当のスレッドはない - -CC は Node.js/Bun のシングルスレッドイベントループで動作。「バックグラウンド」は単に「await しない」こと。`ShellCommand.background(taskId)` は stdout/stderr をファイルにリダイレクトし、プロセスを独立実行。 - -### 三、7 種のバックグラウンドタスク型 - -CC は 7 種のバックグラウンドタスク型を定義(`Task.ts:7-13`):`local_bash`、`local_agent`、`remote_agent`、`in_process_teammate`、`local_workflow`、`monitor_mcp`、`dream`。それぞれ独自の登録、ライフサイクル、通知メカニズムを持つ。 - -### 四、通知注入:コマンドキュー - -バックグラウンドタスク完了時、`enqueueTaskNotification`(`utils/task/framework.ts:267`)または `enqueuePendingNotification`(`messageQueueManager.ts`)で共有コマンドキューにエンキュー。通知形式は構造化 XML: - -```xml - - completed - Background command "npm test" completed (exit code 0) - -``` - -優先度は `next` > `later`(`messageQueueManager.ts`)。バックグラウンドタスクはデフォルト `later`(ユーザー入力をブロックしない)。消費点は `query.ts:1566-1593`。 - -### 五、停滞ウォッチドッグ - -バックグラウンド bash タスクにはウォッチドッグがある(`LocalShellTask.tsx` L24-25 定数, L59-98 ロジック)。出力の停滞を定期チェックし、45 秒間増加がない場合にインタラクティブプロンプト(`(y/n)` 等)を検出、バックグラウンドタスクが無応答のインタラクティブダイアログでスタックするのを防ぐ。 - -### 六、同時実行制限 - -フォアグラウンドツール呼び出し:`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`(デフォルト 10 同時実行安全ツール)。バックグラウンド bash タスク:ハードリミットなし、独立したサブプロセス。 - -
diff --git a/s13_background_tasks/README.md b/s13_background_tasks/README.md index f8735738..311ae19a 100644 --- a/s13_background_tasks/README.md +++ b/s13_background_tasks/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 → s22 +s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 > *"Slow operations go to the background, agent continues processing"* — Background threads run commands, inject notifications when done. > @@ -24,7 +24,7 @@ Reading files is milliseconds, no wait. `git status` returns in under a second, ![Background Tasks Overview](images/background-tasks-overview.en.svg) -Teaching code carries forward S12's simplified task system and prompt assembly; to stay focused on background tasks, it omits full error recovery, memory, and skill systems. The only change: slow operations go to background threads, the agent continues running the loop, and background results are injected as notifications. +This chapter sends slow operations to background threads so the agent can keep running the loop. When a task finishes, its result is injected as a notification. Sync vs Background: @@ -41,7 +41,7 @@ Sync vs Background: ### should_run_background: Explicit Request First, Heuristic Fallback -The model explicitly requests background execution via the bash tool's `run_in_background` parameter. If the model doesn't specify, the teaching version falls back to keyword heuristics: +The model explicitly requests background execution via the bash tool's `run_in_background` parameter. If the model does not specify it, keyword heuristics decide: ```python def is_slow_operation(tool_name: str, tool_input: dict) -> bool: @@ -61,8 +61,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool: return is_slow_operation(tool_name, tool_input) ``` -CC's bash tool schema has a `run_in_background: boolean` parameter (`BashTool.tsx:241`). The model decides which commands go to background, no keyword guessing. The teaching version keeps heuristics as fallback, but the primary path is explicit model request. - ### start_background_task: Background Execution and Lifecycle Wraps the tool call in a worker function, dispatches to a daemon thread. Each background task gets a unique ID, with state tracked in the `background_tasks` dict: @@ -96,7 +94,7 @@ def start_background_task(block) -> str: return bg_id ``` -Returns `bg_id` instead of just `[Running in background...]`. `daemon=True` ensures threads exit when the agent process exits. The teaching version uses in-memory dicts for tracking; real CC has `LocalShellTaskState`, output redirected to files, with full lifecycle including stopping tasks and reading subsequent output. +`start_background_task()` returns `bg_id`. `daemon=True` ensures the thread exits with the agent process. ### collect_background_results: Notification Collection @@ -157,8 +155,6 @@ messages.append({"role": "user", "content": user_content}) Slow operations get a placeholder tool_result with `bg_id`, so the LLM knows this command is still running and can do other things first. When background completes, the notification is injected as an independent text block alongside the current turn's tool_results in one user message. -The teaching version polls background results while the agent loop continues running. Real CC uses a notification queue (`messageQueueManager.ts`) to deliver background completion events to subsequent turns, without waiting for the tool loop. - ### Putting It Together ``` @@ -216,46 +212,5 @@ Background tasks solved "slow operations don't block." But what if you want to d s14 Cron Scheduler → Give the agent an alarm clock. -
-Deep Dive into CC Source - -> The following is a complete analysis based on CC source code `query.ts` (lines 211, 1054-1060, 1411-1482), `services/toolUseSummary/toolUseSummaryGenerator.ts` (L15 prompt text), `LocalShellTask.tsx` (L24-25 constants, L59-98 watchdog logic), `messageQueueManager.ts` (notification queue), `utils/task/framework.ts` (L267 `enqueueTaskNotification`). - -### 1. pendingToolUseSummary: Haiku Background Generation - -CC starts a Haiku side-query after each batch of tool executions to generate a tool use summary. Initiated at `query.ts:1411-1482`, prompt text defined at `services/toolUseSummary/toolUseSummaryGenerator.ts:15` (variable `TOOL_USE_SUMMARY_SYSTEM_PROMPT`). The prompt is "Write a short summary label... think git-commit-subject, not sentence", past tense, ~30 characters. - -Haiku summary (~1s) completes during the main model's streaming output (5-30s). Before the next turn starts, the summary is yielded. SDK consumers use these summaries for mobile progress display. - -### 2. Thread Model: No Real Threads - -CC runs on Node.js/Bun's single-threaded event loop. "Background" just means "don't await". `ShellCommand.background(taskId)` redirects stdout/stderr to files, letting the process run independently. - -### 3. Seven Background Task Types - -CC defines 7 background task types (`Task.ts:7-13`): `local_bash`, `local_agent`, `remote_agent`, `in_process_teammate`, `local_workflow`, `monitor_mcp`, `dream`. Each has its own registration, lifecycle, and notification mechanism. - -### 4. Notification Injection: Command Queue - -When a background task completes, it's enqueued via `enqueueTaskNotification` (`utils/task/framework.ts:267`) or `enqueuePendingNotification` (`messageQueueManager.ts`) into a shared command queue. The notification format is structured XML: - -```xml - - completed - Background command "npm test" completed (exit code 0) - -``` - -Priority is `next` > `later` (`messageQueueManager.ts`). Background tasks default to `later` (don't block user input). Consumption point at `query.ts:1566-1593`. - -### 5. Stall Watchdog - -Background bash tasks have a watchdog (`LocalShellTask.tsx` L24-25 constants, L59-98 logic) that periodically checks if output has stalled. After 45 seconds with no growth, it detects interactive prompts (`(y/n)` etc.), preventing background tasks from getting stuck on unanswered interactive dialogs. - -### 6. Concurrency Limits - -Foreground tool calls: `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` (default 10 concurrent safe tools). Background bash tasks: no hard limit, they're independent subprocesses. - -
diff --git a/s13_background_tasks/README.zh.md b/s13_background_tasks/README.zh.md index 99b9bad2..ce615334 100644 --- a/s13_background_tasks/README.zh.md +++ b/s13_background_tasks/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 → s22 +s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 > *"慢操作丢后台, agent 继续处理"* — 后台线程跑命令, 完成后注入通知。 > @@ -24,7 +24,7 @@ Agent 的 bash 工具也一样。`pip install torch` 要 10 分钟,`npm run bu ![Background Tasks Overview](images/background-tasks-overview.svg) -教学代码沿用 S12 的简化任务系统和 prompt 组装;为了聚焦后台任务,省略完整错误恢复、记忆和技能系统。唯一的变动:慢操作扔到后台线程,Agent 继续跑循环,后台完成后把通知注入到对话里。 +本章把慢操作放入后台线程,Agent 继续运行循环;任务完成后,结果以通知形式注入对话。 同步 vs 后台: @@ -41,7 +41,7 @@ Agent 的 bash 工具也一样。`pip install torch` 要 10 分钟,`npm run bu ### should_run_background: 显式请求优先,启发式兜底 -模型通过 bash 工具的 `run_in_background` 参数显式请求后台执行。如果模型没指定,教学版用关键词启发式兜底: +模型通过 bash 工具的 `run_in_background` 参数显式请求后台执行。如果模型没有指定,则使用关键词启发式判断: ```python def is_slow_operation(tool_name: str, tool_input: dict) -> bool: @@ -61,8 +61,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool: return is_slow_operation(tool_name, tool_input) ``` -CC 的 bash 工具 schema 里有 `run_in_background: boolean` 参数(`BashTool.tsx:241`)。模型自己决定哪些命令丢后台,不靠关键词猜。教学版保留启发式作为兜底,但主路径是模型显式请求。 - ### start_background_task: 后台执行与生命周期 把工具调用包装成 worker 函数,扔到 daemon 线程里执行。每个后台任务有唯一 ID,状态存在 `background_tasks` 字典里: @@ -96,7 +94,7 @@ def start_background_task(block) -> str: return bg_id ``` -返回 `bg_id` 而不是只返回 `[Running in background...]`。`daemon=True` 确保 Agent 进程退出时线程跟着退出。教学版用内存字典追踪状态;真实 CC 有 `LocalShellTaskState`,输出重定向到文件,支持停止任务、读取后续输出等完整生命周期。 +`start_background_task()` 返回 `bg_id`。`daemon=True` 确保 Agent 进程退出时线程一起退出。 ### collect_background_results: 通知收集 @@ -157,8 +155,6 @@ messages.append({"role": "user", "content": user_content}) 慢操作先回一个带 `bg_id` 的占位 tool_result,LLM 知道这个命令还在跑,可以先做别的事。后台完成后,通知作为独立 text block 和当前轮的 tool_result 一起组成 user 消息。 -教学版在 agent loop 继续运行时轮询后台结果。真实 CC 通过通知队列(`messageQueueManager.ts`)把后台完成事件送入后续 turn,不需要等工具循环。 - ### 合起来跑 ``` @@ -216,46 +212,5 @@ python s13_background_tasks/code.py s14 Cron Scheduler → 给 Agent 装一个闹钟。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `query.ts`(211, 1054-1060, 1411-1482 行)、`services/toolUseSummary/toolUseSummaryGenerator.ts`(L15 prompt 文本)、`LocalShellTask.tsx`(L24-25 常量, L59-98 看门狗逻辑)、`messageQueueManager.ts`(通知队列)、`utils/task/framework.ts`(L267 `enqueueTaskNotification`)的完整分析。 - -### 一、pendingToolUseSummary:Haiku 后台生成 - -CC 在每批工具执行完后,启动一个 Haiku side-query 生成工具使用摘要。发起代码在 `query.ts:1411-1482`,prompt 文本定义在 `services/toolUseSummary/toolUseSummaryGenerator.ts:15`(变量名 `TOOL_USE_SUMMARY_SYSTEM_PROMPT`)。提示是 "Write a short summary label... think git-commit-subject, not sentence",过去时态,约 30 字符。 - -Haiku 摘要(~1s)在主模型流式生成(5-30s)期间完成。下一轮开始前,把摘要 yield 出去。SDK 消费这些摘要做移动端进度展示。 - -### 二、线程模型:没有真正的线程 - -CC 运行在 Node.js/Bun 单线程事件循环中。"后台"只是 "不 await"。`ShellCommand.background(taskId)` 把 stdout/stderr 重定向到文件,让进程独立运行。 - -### 三、七种后台任务类型 - -CC 定义了 7 种后台任务(`Task.ts:7-13`):`local_bash`、`local_agent`、`remote_agent`、`in_process_teammate`、`local_workflow`、`monitor_mcp`、`dream`。每种有自己的注册、生命周期和通知机制。 - -### 四、通知注入:命令队列 - -后台任务完成后通过 `enqueueTaskNotification`(`utils/task/framework.ts:267`)或 `enqueuePendingNotification`(`messageQueueManager.ts`)入队到共享命令队列。通知格式是结构化的 XML: - -```xml - - completed - Background command "npm test" completed (exit code 0) - -``` - -优先级分 `next` > `later`(`messageQueueManager.ts`)。后台任务默认 `later`(不阻塞用户输入)。消费点在 `query.ts:1566-1593`。 - -### 五、停滞看门狗 - -后台 bash 任务有一个看门狗(`LocalShellTask.tsx` L24-25 常量, L59-98 逻辑),定期检查输出是否停滞,45 秒无增长后检测交互式提示(`(y/n)` 等),防止后台任务卡在无人响应的交互式对话框。 - -### 六、并发限制 - -前台工具调用:`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`(默认 10 个并发安全工具)。后台 bash 任务:没有硬性限制,它们是独立的子进程。 - -
diff --git a/s13_background_tasks/code.py b/s13_background_tasks/code.py index a96eabca..c6c53b03 100644 --- a/s13_background_tasks/code.py +++ b/s13_background_tasks/code.py @@ -16,9 +16,8 @@ Changes from s12: - agent_loop: slow ops → background + placeholder, inject notifications - Notifications use format, not reused tool_use_id -Note: Teaching code keeps a basic agent loop to stay focused on background -tasks. S11's full error recovery (RecoveryState, backoff, escalation, -reactive compact, fallback model) is omitted. +This chapter keeps the agent loop focused on background tasks. Error recovery +remains the independent layer introduced in s11. """ import os, subprocess, json, time, random, threading diff --git a/s14_cron_scheduler/README.ja.md b/s14_cron_scheduler/README.ja.md index d97d475d..95e56c33 100644 --- a/s14_cron_scheduler/README.ja.md +++ b/s14_cron_scheduler/README.ja.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s12 → s13 → `s14` → [s15](../s15_agent_teams/) → s16 → ... → s20 → s21 → s22 +s01 → ... → s12 → s13 → `s14` → [s15](../s15_agent_teams/) → s16 → ... → s20 → s21 > *"スケジュールに従って作業を生産、スケジューリングと実行を分離"* — cron スケジューリング、永続またはセッションレベル。 > > **Harness 層**: スケジューリング — 独立スレッドが時刻を判定、キューがトリガーを配信。 @@ -21,7 +21,7 @@ s13 で Agent は遅い操作をバックグラウンドで実行できるよう ![Cron Scheduler Overview](images/cron-scheduler-overview.ja.svg) -教学版は S13 の簡易タスクシステム、バックグラウンド実行、プロンプト組み立てを踏襲。スケジューラに集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。追加:独立した cron スケジューラスレッド、1 秒ごとにポーリング、時間が来たらタスクを `cron_queue` に投入し、queue processor が Agent のアイドル時に自動配信。 +この章では独立した cron スケジューラスレッドを追加する。1 秒ごとに確認し、期限に達したジョブを `cron_queue` に書き込み、queue processor が Agent のアイドル時に自動配信する。 手動 vs スケジュール: @@ -45,8 +45,6 @@ cron スケジューリングは 4 層に分かれる: 3. **Queue Processor**:キューが空でなく Agent がアイドルなら、一回の agent_loop を開始 4. **Consumer**:agent_loop がキューから消費、messages に注入 -教学版は最小の queue processor を実装する。`agent_lock` で Agent がアイドルかを判定し、キューに入った cron 作業を自動配信する。実際の CC の `useQueueProcessor.ts` はさらに UI ブロック、キュープライオリティ、メッセージモードを扱う。 - ### CronJob: データ構造 各 cron タスクは `CronJob` オブジェクト: @@ -253,53 +251,5 @@ python s14_cron_scheduler/code.py s15 Agent Teams → 一人の Agent では足りない、チームを組もう。永続的なチームメイト + 非同期受信箱。 -
-CC ソースコード深掘り - -> 以下は CC ソースコード `CronCreateTool.ts`、`cronScheduler.ts`、`cron.ts`、`cronTasks.ts`、`cronTasksLock.ts`、`useScheduledTasks.ts`(139 行)の完全分析に基づく。 - -### 一、3 つの Cron ツール - -CC はモデルに 3 つの cron ツールを公開:`CronCreate`、`CronDelete`、`CronList`。すべてコンパイル時ゲート `feature('AGENT_TRIGGERS')` とランタイム GrowthBook フラグ `tengu_kairos_cron` で制御。`CLAUDE_CODE_DISABLE_CRON` 環境変数でローカル上書きも可能。 - -### 二、ストレージ:`.claude/scheduled_tasks.json` - -```json -{ "tasks": [{ "id": "abc12345", "cron": "0 9 * * *", "prompt": "...", "recurring": true, "durable": true, "createdAt": 1714567890000 }] } -``` - -durable タスクはディスクに書き込み。session-only タスクは `STATE.sessionCronTasks` メモリ配列に格納(プロセス再起動で消失)。`.scheduled_tasks.lock` ファイルで同じプロジェクトの複数セッション間の重複発火を防止。 - -### 三、スケジューラ:1 秒ポーリング - -`cronScheduler.ts` は毎秒チェック(`CHECK_INTERVAL_MS = 1000`)。ロックを保持しているセッションがファイルタスクをトリガー。すべてのセッションが session-only タスクをトリガー。`chokidar` ファイルウォッチャーが `scheduled_tasks.json` の変更を監視。 - -### 四、cron 式:標準 5 フィールド - -分 時 日 月 曜日。`*`、`*/N`、`N`、`N-M`、`N-M/S`、`N,M,...` をサポート。`L`、`W`、`?` は非サポート。すべての時間はローカルタイムゾーンで解釈。day-of-month と day-of-week が両方制約されている場合は OR セマンティクス。 - -### 五、ジッター(サンダリングハード防止) - -- 定期タスク:トリガー遅延は期間の最大 10%(上限 15 分)、タスク ID ベースの決定的ハッシュ -- 一回限りタスク:発火時刻が `:00` または `:30` の場合、最大 90 秒早く発火 -- ジッター設定は GrowthBook でリアルタイム調整可能、60 秒ごとにリフレッシュ - -### 六、自動期限切れ - -定期タスクは 7 日後に自動期限切れ(設定可能、上限 30 日)。期限切れ前に最後の一回を発火、その後自動削除。 - -### 七、ジョブ数上限 - -`MAX_JOBS = 50`(`CronCreateTool.ts:25`)。超過時はエラーを返す:"Too many scheduled jobs (max 50). Cancel one first." - -### 八、トリガー注入 - -発火後、`enqueuePendingNotification()` で `priority: 'later'` としてコマンドキューにエンキュー。`workload: WORKLOAD_CRON` タグ付き、API は容量が逼迫している時に cron 発信リクエストを低い QoS で処理。 - -### 九、Queue Processor:自動配信 - -実際の CC は `useQueueProcessor.ts:48-60` により、アクティブな query がなく、UI がブロックされておらず、キューが空でない場合に自動的に処理をトリガーする。`queueProcessor.ts:52-87` がキュープライオリティに従ってコマンドを `handlePromptSubmit()` にディスパッチ。教学版は `queue_processor_loop` で核心動作を保つ:キューに作業があり Agent がアイドルなら、自動的に一回の agent_loop を開始する。 - -
diff --git a/s14_cron_scheduler/README.md b/s14_cron_scheduler/README.md index 5e9122ff..7a22e065 100644 --- a/s14_cron_scheduler/README.md +++ b/s14_cron_scheduler/README.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s12 → s13 → `s14` → [s15](../s15_agent_teams/) → s16 → ... → s20 → s21 → s22 +s01 → ... → s12 → s13 → `s14` → [s15](../s15_agent_teams/) → s16 → ... → s20 → s21 > *"Produce work on a schedule, decouple scheduling from execution"* — Cron scheduling, durable or session-level. > > **Harness Layer**: Scheduling — Independent thread checks time, queue delivers triggers. @@ -21,7 +21,7 @@ s13 lets the agent run slow operations in the background, but every operation is ![Cron Scheduler Overview](images/cron-scheduler-overview.en.svg) -Teaching code carries forward S13's simplified task system, background execution, and prompt assembly; to stay focused on the scheduler, it omits full error recovery, memory, and skill systems. Added: an independent cron scheduler thread that polls every second, queues matching jobs into `cron_queue`, and a queue processor that delivers them when the agent is idle. +This chapter adds an independent cron scheduler thread: it checks once per second, writes due jobs to `cron_queue`, and a queue processor delivers them when the agent is idle. Manual vs Scheduled: @@ -45,8 +45,6 @@ Cron scheduling has four layers: 3. **Queue Processor**: sees non-empty queue and idle agent, starts one agent_loop turn 4. **Consumer**: agent_loop consumes queue and injects into messages -The teaching version implements a minimal queue processor: `agent_lock` tells whether the agent is idle, and queued cron work is delivered automatically. Real CC's `useQueueProcessor.ts` also handles UI blocking, queue priority, and different message modes. - ### CronJob: Data Structure Each cron task is a `CronJob` object: @@ -253,53 +251,5 @@ One agent can do a lot now: plan, compress, background, schedule. But some tasks s15 Agent Teams → One agent isn't enough, form a team. Persistent teammates + async inboxes. -
-Deep Dive into CC Source - -> The following is a complete analysis based on CC source code `CronCreateTool.ts`, `cronScheduler.ts`, `cron.ts`, `cronTasks.ts`, `cronTasksLock.ts`, `useScheduledTasks.ts` (139 lines). - -### 1. Three Cron Tools - -CC exposes three cron tools to the model: `CronCreate`, `CronDelete`, `CronList`. All controlled by compile-time gate `feature('AGENT_TRIGGERS')` and runtime GrowthBook flag `tengu_kairos_cron`. There's also a `CLAUDE_CODE_DISABLE_CRON` env var for local override. - -### 2. Storage: `.claude/scheduled_tasks.json` - -```json -{ "tasks": [{ "id": "abc12345", "cron": "0 9 * * *", "prompt": "...", "recurring": true, "durable": true, "createdAt": 1714567890000 }] } -``` - -Durable tasks write to disk; session-only tasks live in `STATE.sessionCronTasks` memory array (lost on process restart). A `.scheduled_tasks.lock` file prevents duplicate firing across multiple sessions of the same project. - -### 3. Scheduler: 1-Second Polling - -`cronScheduler.ts` checks every second (`CHECK_INTERVAL_MS = 1000`). Whoever holds the lock triggers file tasks; all sessions trigger session-only tasks. A `chokidar` file watcher monitors `scheduled_tasks.json` changes. - -### 4. Cron Expression: Standard 5 Fields - -Minute hour day month weekday. Supports `*`, `*/N`, `N`, `N-M`, `N-M/S`, `N,M,...`. Doesn't support `L`, `W`, `?`. All times interpreted in local timezone. Day-of-month and day-of-week use OR semantics when both are constrained. - -### 5. Jitter (Thundering Herd Prevention) - -- Recurring tasks: trigger delay up to 10% of period (max 15 min), deterministic hash based on task ID -- One-shot tasks: up to 90s early when firing time falls on `:00` or `:30` -- Jitter config adjustable via GrowthBook, refreshed every 60 seconds - -### 6. Auto-Expiration - -Recurring tasks auto-expire after 7 days (configurable, max 30 days). Fire one last time before expiry, then auto-delete. - -### 7. Job Limit - -`MAX_JOBS = 50` (`CronCreateTool.ts:25`). Returns error when exceeded: "Too many scheduled jobs (max 50). Cancel one first." - -### 8. Trigger Injection - -After firing, enqueued via `enqueuePendingNotification()` with `priority: 'later'` into the command queue. Tagged `workload: WORKLOAD_CRON` — API serves cron-initiated requests at lower QoS when capacity is tight. - -### 9. Queue Processor: Automatic Delivery - -Real CC auto-triggers processing through `useQueueProcessor.ts:48-60` when no query is active, UI isn't blocked, and queue is non-empty. `queueProcessor.ts:52-87` dispatches commands to `handlePromptSubmit()` by queue priority. The teaching version keeps the core behavior with `queue_processor_loop`: when queued work exists and the agent is idle, it starts one agent_loop turn automatically. - -
diff --git a/s14_cron_scheduler/README.zh.md b/s14_cron_scheduler/README.zh.md index 997fdb2f..8e586f2f 100644 --- a/s14_cron_scheduler/README.zh.md +++ b/s14_cron_scheduler/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s12 → s13 → `s14` → [s15](../s15_agent_teams/) → s16 → ... → s20 → s21 → s22 +s01 → ... → s12 → s13 → `s14` → [s15](../s15_agent_teams/) → s16 → ... → s20 → s21 > *"按时间表生产工作, 调度与执行解耦"* — cron 调度, 持久化或会话级。 > > **Harness 层**: 调度 — 独立线程判断时间, 队列传递触发。 @@ -21,7 +21,7 @@ s13 让 Agent 能后台执行慢操作,但所有操作仍然是你手动触发 ![Cron Scheduler Overview](images/cron-scheduler-overview.svg) -教学代码沿用 S13 的简化任务系统、后台执行和 prompt 组装;为了聚焦调度器,省略完整错误恢复、记忆和技能系统。新增:独立的 cron 调度线程,每秒检查一次,时间到了把任务塞进 `cron_queue`;再由 queue processor 在 Agent 空闲时自动交付。 +本章新增独立的 cron 调度线程:每秒检查一次,把到期任务写入 `cron_queue`,再由 queue processor 在 Agent 空闲时自动交付。 手动 vs 定时: @@ -45,8 +45,6 @@ Cron 调度分四层: 3. **Queue Processor**:发现队列非空且 Agent 空闲,启动一轮 agent_loop 4. **Consumer**:agent_loop 从队列消费,注入到 messages -教学版实现的是最小 queue processor:用 `agent_lock` 判断 Agent 是否空闲,空闲时自动交付定时任务。真实 CC 的 `useQueueProcessor.ts` 还会处理 UI 阻塞、队列优先级和不同消息模式。 - ### CronJob: 数据结构 每个 cron 任务是一个 `CronJob` 对象: @@ -253,53 +251,5 @@ python s14_cron_scheduler/code.py s15 Agent Teams → 一个 Agent 不够,组队吧。持久队友 + 异步收件箱。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `CronCreateTool.ts`、`cronScheduler.ts`、`cron.ts`、`cronTasks.ts`、`cronTasksLock.ts`、`useScheduledTasks.ts`(139 行)的完整分析。 - -### 一、三个 Cron 工具 - -CC 暴露了三个 cron 工具给模型:`CronCreate`、`CronDelete`、`CronList`。全部由编译时门控 `feature('AGENT_TRIGGERS')` 和运行时 GrowthBook 标志 `tengu_kairos_cron` 控制。还有一个 `CLAUDE_CODE_DISABLE_CRON` 环境变量做本地覆盖。 - -### 二、存储:`.claude/scheduled_tasks.json` - -```json -{ "tasks": [{ "id": "abc12345", "cron": "0 9 * * *", "prompt": "...", "recurring": true, "durable": true, "createdAt": 1714567890000 }] } -``` - -Durable 任务写磁盘;session-only 任务存于 `STATE.sessionCronTasks` 内存数组(进程重启丢失)。还有一个 `.scheduled_tasks.lock` 文件防止同项目的多个 session 重复触发。 - -### 三、调度器:1 秒轮询 - -`cronScheduler.ts` 每秒检查一次(`CHECK_INTERVAL_MS = 1000`)。谁持有锁谁触发文件任务;所有 session 都触发仅 session 任务。还有一个 `chokidar` 文件观察者监视 `scheduled_tasks.json` 变更。 - -### 四、Cron 表达式:标准 5 字段 - -分钟 小时 日 月 星期。支持 `*`、`*/N`、`N`、`N-M`、`N-M/S`、`N,M,...`。不支持 `L`、`W`、`?`。所有时间以本地时区解释。Day-of-month 和 day-of-week 同时约束时用 OR 语义。 - -### 五、抖动(防惊群效应) - -- 重复性任务:触发延迟最多可达期间的 10%(上限 15 分钟),基于任务 ID 的确定性哈希 -- 一次性任务:当触发时间落在 `:00` 或 `:30` 时,最多提前 90 秒触发 -- 抖动配置可通过 GrowthBook 实时调整,60 秒刷新一次 - -### 六、自动过期 - -重复性任务 7 天后自动过期(可配置,上限 30 天)。过期前最后一次触发,触发后自动删除。 - -### 七、作业数上限 - -`MAX_JOBS = 50`(`CronCreateTool.ts:25`)。超限时返回错误:"Too many scheduled jobs (max 50). Cancel one first." - -### 八、触发注入 - -触发后通过 `enqueuePendingNotification()` 以 `priority: 'later'` 入队命令队列。标记 `workload: WORKLOAD_CRON`,API 在容量紧张时以更低的 QoS 为 cron 发起的请求服务。 - -### 九、Queue Processor:自动交付 - -真实 CC 通过 `useQueueProcessor.ts:48-60` 在无 query、无阻塞 UI、队列非空时自动触发处理。`queueProcessor.ts:52-87` 按队列优先级把命令交给 `handlePromptSubmit()`。教学版用 `queue_processor_loop` 保留核心行为:队列有任务且 Agent 空闲时,自动启动一轮 agent_loop。 - -
diff --git a/s14_cron_scheduler/code.py b/s14_cron_scheduler/code.py index 7fd36324..ee45af24 100644 --- a/s14_cron_scheduler/code.py +++ b/s14_cron_scheduler/code.py @@ -678,8 +678,8 @@ def update_context(context: dict, messages: list) -> dict: } -# ── Agent Loop (simplified, focused on cron scheduler) ── -# Teaching code keeps a basic agent loop. S11's full error recovery is omitted. +# ── Agent Loop (focused on cron scheduling) ── +# Error recovery remains the independent layer introduced in s11. # cron_scheduler_loop produces work; queue_processor_loop wakes this loop when # queued work exists and no other agent turn is running. diff --git a/s15_agent_teams/README.ja.md b/s15_agent_teams/README.ja.md index 76e2b16a..161ad244 100644 --- a/s15_agent_teams/README.ja.md +++ b/s15_agent_teams/README.ja.md @@ -1,155 +1,251 @@ -# s15: Agent Teams — ランタイム実験:永続チームメイト +# s15: Agent Teams — チームランタイムと協調プロトコル [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s13 → s14 → `s15` → [s16](../s16_team_protocols/) → s17 → s18 → s19 → s20 → s21 → s22 -> *"一人では無理、チームを組もう"* — ファイル受信箱 + チームメイトスレッド。 +s01 → ... → s13 → s14 → `s15` → [s16](../s16_autonomous_agents/) → s17 → s18 → s19 → s20 → s21 + +> *「1 つの Agent だけでは扱いきれないなら、チームメイトで分担する。」* — 永続チームメイト、メッセージ配信、協調プロトコル。 > -> **Harness 層**: チーム — マルチ Agent 協調、メッセージバス。 - -> **モジュール 1/2:** s15 と s16 は一つの Agent Teams モジュールに含まれる二つの集中実験。この章でランタイムを構築し、s16 はランタイムを繰り返さず型付き協調プロトコルを追加する。 +> **Harness レイヤー**:チーム — 複数 Agent を並行動作させながら制御を保つ。 --- -## 課題 +## 問題 -「バックエンド全体をリファクタリング」は認証モジュール、データベース層、API ルート、テストに及ぶ。一つの Agent が API ルートを修正中、認証モジュールの詳細はコンテキストから外れている。コンテキストウィンドウには限界があり、単一 Agent の注意は全モジュールをカバーできない。 +Agent にバックエンド全体のリファクタリングを頼む場合、設定読み込み、認証、テストを同時に扱うことになる。1 つの Agent が順番に処理することもできるが、時間がかかり、初期の詳細は徐々にコンテキストから抜けていく。 -s06 のサブ Agent は臨時スタッフ、一つの仕事を終えたら去る。だが、通信でき、協力できるチームメイトが必要なタスクもある。 +このような仕事は並列化に向いている。しかし、通常のユーザーはチーム構成ではなく目的だけを伝える: + +```text +このサンプルバックエンドをリファクタリングしてください。 +設定読み込み、認証ロジック、テストを整理し、 +既存インターフェースを保ったままテストを通してください。 +``` + +そのため Harness は、単に Agent を増やすだけでなく、次の 4 点を解決する必要がある: + +1. 並列化が有効かを誰が判断し、追加 Agent の起動を誰が確認するか。 +2. チームメイトが複数の依頼にまたがって、どう身元とコンテキストを保つか。 +3. モデルに受信箱を繰り返し確認させず、結果をどう Lead へ戻すか。 +4. 終了と計画承認を、どう追跡可能で強制可能なプロトコルにするか。 --- -## ソリューション +## 解決策 ![Agent Teams Overview](images/agent-teams-overview.ja.svg) -教学版は S14 の能力(プロンプト組み立て、タスクシステム、バックグラウンド実行、cron スケジューリング)を踏襲。チーム機構に集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。追加:**MessageBus**(ファイル受信箱)、**spawn_teammate_thread**(チームメイトスレッド起動)、**inbox 注入**(Lead がチームメイトメッセージを受信し history に注入)。 +s15 は単一 Agent の Harness の外側に、Lead が管理するチームランタイムを追加する: -サブ Agent vs チームメイト: +- **Lead** はユーザーとの会話を維持し、分担案を提示して確認を待つ。 +- **チームメイト** は独立した Agent Loop をバックグラウンドスレッドで実行し、作業後は IDLE になる。 +- **MessageBus** はファイル受信箱を通して、通常メッセージ、結果、制御イベントを運ぶ。 +- **ランタイム配信** は Lead の受信箱を消費し、チームイベントを次のターンへ注入する。 +- **協調プロトコル** は `type`、`request_id`、状態遷移で終了と計画承認を扱う。 +- **計画ゲート** は、必要な計画が承認されるまで `bash` と `write_file` を遮断する。 -| | s06 サブ Agent | s15 チームメイト | -|---|---|---| -| ライフサイクル | 一回きり、終了後に破棄 | マルチターン(教学版は 10 ラウンド制限、真实 CC は idle loop) | -| 通信 | 結果のみ返却 | 非同期受信箱、いつでも通信可能 | -| コンテキスト | 完全に隔離 | メッセージで情報共有 | -| 数 | メイン Agent + たまにサブ Agent | 1 Lead + 複数チームメイト | +モデルはタスクを理解して分担を決める。コードは配信、ライフサイクル、プロトコル制約を担う。 --- ## 仕組み -![Team Topology](images/team-topology.ja.svg) +### 1. Lead はチーム案を示し、確認を待つ -### MessageBus: ファイル受信箱 +チームメイトの起動は、コスト、並行度、ワークスペースを書き換える主体を変える。この境界を通常のツール呼び出しの中に隠してはいけない。Lead の system prompt は次のように定める: -各 Agent(Lead とチームメイトを含む)には `.jsonl` 受信箱がある。メッセージ送信 = 相手のファイルに 1 行 JSON を append。メッセージ読み取り = ファイル読み込み + 削除(消費式): +```python +"When parallel work would help, first propose a small team with clear " +"responsibilities and wait for the user's confirmation. Do not call " +"spawn_teammate before the user confirms." +``` + +最初の依頼に対して、Lead はまず分担案だけを返す: + +```text +次の 3 方向で並行処理することを提案します。 +- config:設定読み込みの整理 +- auth:認証ロジックのリファクタリング +- tests:回帰テストの追加 + +確認後にチームメイトを起動します。 +``` + +ユーザーが「始めてください」と返した後で、Lead は `spawn_teammate` を呼ぶ。ユーザーが目的を示し、Lead がチームを設計し、ユーザーが実行境界を確認する。 + +### 2. 各チームメイトは独立したループを持つ + +s06 の Subagent は 1 回限りの呼び出しだが、チームメイトは永続する実行単位である: + +| | s06 Subagent | s15 チームメイト | +|---|---|---| +| ライフサイクル | 1 回の呼び出し後に終了 | 終了要求まで `WORK → IDLE → WORK` | +| コンテキスト | 1 つのタスクだけ | 複数の依頼をまたいで保持 | +| 通信 | 1 回だけ結果を返す | メッセージを受け取り、イベントを送る | +| 協調 | 一方向の委任 | Lead との双方向協調 | + +`spawn_teammate_thread()` はチームメイトごとに system prompt、messages、ツールを作り、daemon thread でループを実行する。Lead はチームメイトの終了を待たずに、別の依頼や結果を調整できる。 + +### 3. MessageBus は通信をモデルのコンテキスト外に置く + +Lead とチームメイトが同じ messages 配列を共有すると、あるチームメイトのツール結果が別のチームメイトの推論へ混ざる。`MessageBus` は各 Agent に `.mailboxes/.jsonl` 受信箱を与える: ```python class MessageBus: - def send(self, from_agent: str, to_agent: str, - content: str, msg_type: str = "message"): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time()} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") + def send(self, from_agent, to_agent, content, + msg_type="message", metadata=None): + msg = { + "from": from_agent, + "to": to_agent, + "content": content, + "type": msg_type, + "metadata": metadata or {}, + } + with self._changed: + append_jsonl(self._path(to_agent), msg) + self._changed.notify_all() - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" - if not inbox.exists(): - return [] - msgs = [json.loads(line) for line in inbox.read_text().splitlines()] - inbox.unlink() # 消費式:読んだら削除 - return msgs + def wait_for_messages(self, agent): + with self._changed: + while not self.peek(agent): + self._changed.wait() + return self._read_unlocked(agent) ``` -なぜファイルか、メモリキューではなく?教学版がファイルを選ぶ理由は、直感的でスレッドをまたいで観察可能だから。真实 CC もファイル受信箱(`~/.claude/teams/{team}/inboxes/`)を使うが、`proper-lockfile` で並行書き込みの安全性を確保。教学版の `read_inbox` には read + unlink の競合状態があり、マルチスレッド同時読みでメッセージを損失する可能性があるが、教学目的には許容範囲。 +ロックは複数スレッドによる受信箱ファイルの破損を防ぐ。`Condition` により、IDLE のチームメイトはポーリングせずイベント到着まで待機できる。 -### spawn_teammate_thread: チームメイト起動 +### 4. 受信イベントはランタイムが自動配信する -Lead が `spawn_teammate` ツールを呼び出してチームメイトを起動。チームメイトは独自の daemon スレッドで動作、独自の system prompt、messages、簡易ツールセットを持つ: +`read_inbox()` はメッセージを読み、受信箱ファイルを削除する。そのため Lead の消費入口は `consume_lead_inbox()` だけにする: ```python -def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - system = f"You are '{name}', a {role}. Use tools to complete tasks." - - def run(): - messages = [{"role": "user", "content": prompt}] - sub_tools = [bash, read_file, write_file, send_message] - for _ in range(10): # 最大 10 ラウンド - inbox = BUS.read_inbox(name) - if inbox: - messages.append({"role": "user", - "content": f"{json.dumps(inbox)}"}) - response = client.messages.create( - model=MODEL, system=system, messages=messages[-20:], - tools=sub_tools, max_tokens=8000) - # ... ツール実行、結果処理 - # 完了後 summary を Lead に送信 - BUS.send(name, "lead", summary, "result") - - threading.Thread(target=run, daemon=True).start() +def consume_lead_inbox(): + messages = BUS.read_inbox("lead") + for message in messages: + if message["type"].endswith("_response"): + match_response(...) + return messages ``` -重要な設計: -- **チームメイトの簡易ツールセット**:bash、read、write、send_message。教学版は通信機構に集中するためタスクと cron を省略。真实 CC のチームメイトには TaskCreate、TaskUpdate 等のツールもあり、タスクシステムはチーム全体で共有 -- **教学版は 10 ラウンド制限**:無限ループを防止。真实 CC は idle loop:1 ラウンド終了後に `idle_notification` を送信、inbox メッセージを待機、到着後に再開、`shutdown_request` でのみ終了 -- **完了時自動報告**:`BUS.send(name, "lead", summary)` で最終結果を Lead の受信箱に送信 +メインループのイベントスレッドは、新しいメッセージが届くと Lead を起こす: -### Lead の inbox 注入 +```text +MessageBus → consume_lead_inbox + → プロトコル状態を更新 + → [Team events] を history へ注入 + → Lead の次ターンを開始 +``` -Lead はメインループの各反復後に受信箱を確認。チームメイトからのメッセージを history に注入し、LLM が確認して反応できるようにする: +`check_inbox` はモデルのツールではない。メッセージの到着はランタイムの責務であり、モデルはコンテキストへ配信済みのイベントだけを処理する。 + +### 5. 結果と IDLE は別のイベント + +チームメイトが 1 件の作業を終えると、ランタイムは次の順序で 2 つのイベントを送る: + +```text +result: "認証をリファクタリングし、関連テストが通りました。" +idle_notification: "Waiting for more work." +``` + +`result` は「今回の作業で何が得られたか」、`idle_notification` は「新しい仕事を受けられるか」を表す。1 つの曖昧な「done」では両者を区別できない。 + +IDLE になったチームメイトは終了しない。通常メッセージで WORK に戻り、`shutdown_request` で終了ハンドシェイクを始める。 + +### 6. 制御メッセージには型と request_id を使う + +通常の協調は自由文でよいが、終了と承認を意図の推測に任せてはいけない。制御イベントは構造化する: + +![Team Protocols](images/team-protocols-overview.ja.svg) ```python -# メインループ反復後 -inbox = BUS.read_inbox("lead") -if inbox: - inbox_text = "\n".join( - f"From {m['from']}: {m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) +@dataclass +class ProtocolState: + request_id: str + type: str + sender: str + target: str + status: str + payload: str + + +pending_requests: dict[str, ProtocolState] = {} ``` -教学版はユーザー入力ループ内で注入。真实 CC はより精密、Lead の `useInboxPoller` が毎秒チェックし、ユーザー入力を待たずにメッセージを新しい turn として送信。 +終了プロトコルは次の経路を通る: -### 権限バブリング - -教学版は権限バブリングを省略。真实 CC のフロー(`permissionSync.ts`、`useSwarmPermissionPoller.ts`): - -1. チームメイトが承認が必要な操作に遭遇 → `permission_request` を Lead の受信箱に送信 -2. Lead の `useInboxPoller` がリクエストを検出 → 承認キューにルーティング -3. ユーザーが承認 → Lead が `permission_response` をチームメイトに返信 -4. チームメイトの `useSwarmPermissionPoller`(500ms ごとにポーリング)が返信を受信 → 続行または拒否 - -### 組み合わせて実行 - -``` -1. Lead: "バックエンド構築:一人では無理、チームを組もう" -2. Lead → spawn_teammate("alice", "backend dev", "データベーススキーマを作成") -3. Lead → spawn_teammate("bob", "frontend dev", "API クライアントを作成") -4. alice スレッド起動 → 独自の LLM 呼び出し → bash "python manage.py migrate" -5. bob スレッド起動 → 独自の LLM 呼び出し → write_file("client.ts", ...) -6. alice 完了 → BUS.send("alice", "lead", "Schema done: users, orders tables") -7. bob 完了 → BUS.send("bob", "lead", "Client written with types") -8. Lead 次回反復 → inbox を history に注入 → LLM が alice と bob の結果を確認 +```text +Lead が pending の shutdown request を作る + → shutdown_request(request_id) をチームメイトへ送る + → チームメイトが現在の手順を終える + → shutdown_response(request_id) を Lead へ返す + → request_id で元の要求を特定する + → pending が approved になり、チームメイトループが終了する ``` -2 人のチームメイトが並行作業。 +ID は要求と応答を対応付け、型は誤った応答による状態変更を防ぎ、状態は重複応答の再適用を防ぐ。 + +### 7. 計画承認は実行も制約する + +計画プロトコルは逆方向に流れる: + +```text +Lead → plan_request +チームメイト → plan_approval_request(request_id, plan) +Lead → plan_approval_response(request_id, approve, feedback) +``` + +「承認まで待つ」と伝えるだけでは確実なゲートにならない。そこでツール dispatch が計画状態を検査する: + +```python +def _run_teammate_tool(name, block, handlers): + gate = plan_gates.get(name, "not_required") + if block.name in {"bash", "write_file"} and gate not in { + "not_required", "approved" + }: + return f"Blocked: plan status is {gate}." + return handlers[block.name](**block.input) +``` + +状態が `required`、`pending`、`rejected` の間、チームメイトはファイルを読み、計画を提出または修正できるが、Shell 実行やファイル書き込みはできない。承認応答で `approved` になった後にだけツールが解放される。 + +--- + +## 一連の実行例 + +```text +s15 >> このサンプルバックエンドをリファクタリングしてください。 + 設定読み込み、認証、テストを整理し、 + 既存インターフェースを保ってテストを通してください。 + +Lead: config、auth、tests の 3 方向で並行処理することを提案します。 + チームを開始しますか? + +s15 >> 始めてください + +[teammate] config spawned +[teammate] auth spawned +[teammate] tests spawned +[bus] auth → lead (result) ... +[bus] auth → lead (idle_notification) ... +[wake: 2 team events → new turn] +Lead: 認証の結果を受け取りました。残りの作業も調整します。 +``` + +端末には、ユーザー要求、Lead の分担、起動、メッセージ、結果、IDLE、終了イベントが表示される。ユーザーが Lead を指名したり、受信箱の確認を頼んだりする必要はない。 --- ## s14 からの変更 -| コンポーネント | 変更前 (s14) | 変更後 (s15) | -|--------------|------------|------------| -| Agent 数 | 1 | 1 Lead + N チームメイトスレッド | -| 通信 | なし | MessageBus + .mailboxes/*.jsonl | -| 新規クラス | — | MessageBus, active_teammates dict | -| 新規関数 | — | spawn_teammate_thread, run_send_message, run_check_inbox | -| Lead ツール | 11 (s14) | + spawn_teammate, send_message, check_inbox (14) | -| チームメイトツール | — | bash, read_file, write_file, send_message (4) | -| 権限 | ローカル判断 | 教学版は省略(真实 CC はバブリング機構あり) | +| コンポーネント | s14 | s15 | +|---|---|---| +| Agent | 1 つ | 1 つの Lead + 永続チームメイト | +| ユーザーフロー | 依頼を直接実行 | チーム案を提示してから起動を確認 | +| 通信 | なし | ファイル受信箱 + 自動イベント配信 | +| ライフサイクル | 1 つのループ | チームメイトの `WORK / IDLE / shutdown` | +| 結果通知 | 現在の Agent の出力 | `result` と `idle_notification` を分離 | +| 制御 | なし | 終了と計画承認プロトコル | +| 強制 | チーム制約なし | 必須計画が変更系ツールをゲート | --- @@ -160,97 +256,28 @@ cd learn-claude-code python s15_agent_teams/code.py ``` -以下のプロンプトを試してください: +まず通常の依頼を入力する: -1. `Spawn alice as a backend developer. Ask her to create a file called schema.sql with a users table.` -2. `Check your inbox for alice's result.` -3. `Spawn bob as a tester. Ask him to check if schema.sql exists and list its contents.` +```text +このサンプルバックエンドをリファクタリングしてください。 +設定読み込み、認証ロジック、テストを整理し、 +既存インターフェースを保ったままテストを通してください。 +``` -観察ポイント:Lead はチームメイトをどう起動するか?`.mailboxes/` ディレクトリの JSONL ファイルの中身は?チームメイト完了後、Lead の inbox は history に注入されているか? +Lead がチーム案を示したら、次のように返す: + +```text +始めてください +``` + +`spawned`、`result`、`idle_notification`、`plan_approval_*`、`shutdown_*` の各イベントと、`.mailboxes/` のファイルが生成・消費される流れを確認する。 --- -## 次の章 +## 次へ -チームメイトは仕事をし、通信できる。しかし、Lead が Alice にシャットダウンを頼む場合、スレッドを強制終了すると書きかけのファイルが残る。丁寧なシャットダウンプロトコルが必要:Lead が shutdown_request を送信、チームメイトは收尾後に終了。 +s15 では、Lead が各チームメイトへ明示的に仕事を割り当てる。次のセッションでは共有タスクボードを IDLE のチームメイトに公開し、実行可能な仕事を自ら見つけて claim できるようにする。 -s16 Agent Teams プロトコル実験 → このランタイムにシャットダウンハンドシェイク、計画承認、型付きリクエスト-返信を追加する。 +次へ:[s16 Autonomous Agents](../s16_autonomous_agents/)。 -
-CC ソースコード深掘り - -> 以下は CC ソースコード `spawnMultiAgent.ts`、`useInboxPoller.ts`(969 行)、`useSwarmPermissionPoller.ts`(330 行)、`teammateMailbox.ts`、`teamHelpers.ts` の完全分析に基づく。 - -### 一、中央メッセージバスはない、ファイルシステム - -教学版は `MessageBus` クラスでメッセージを送受信。真实 CC はもっと直接的、各 Agent が他の Agent の受信箱ファイルに直接書き込む。 - -受信箱パス:`~/.claude/teams/{teamName}/inboxes/{agentName}.json` - -書き込み時は `proper-lockfile` で並行安全性を確保(最大 10 回リトライ)。各ファイルは JSON 配列、append 時に読み取り→追加→書き戻し。 - -### 二、15 種のメッセージ型 - -CC のチーム通信には 15 種の構造化メッセージ(`teammateMailbox.ts`)がある: - -| 型 | 方向 | 用途 | -|------|------|------| -| `plain text` | 双方向 | 通常のチームメイト間通信 | -| `idle_notification` | チームメイト→Lead | チームメイトが 1 ターン完了、アイドル状態に | -| `permission_request` | チームメイト→Lead | 操作承認が必要 | -| `permission_response` | Lead→チームメイト | Lead の承認結果 | -| `plan_approval_request` | チームメイト→Lead | 計画提出、審査待ち | -| `plan_approval_response` | Lead→チームメイト | Lead の計画審査 | -| `shutdown_request` | Lead→チームメイト | 丁寧なシャットダウン要求 | -| `shutdown_approved` | チームメイト→Lead | シャットダウン確認 | -| `shutdown_rejected` | チームメイト→Lead | シャットダウン拒否(理由付き) | -| `task_assignment` | Lead→チームメイト | タスク割り当て | -| `team_permission_update` | Lead→チームメイト | 権限変更のブロードキャスト | -| `mode_set_request` | Lead→チームメイト | チームメイトの権限モード変更 | -| `sandbox_permission_*` | 双方向 | ネットワーク権限リクエスト/返信 | -| `teammate_terminated` | システム | チームメイト削除通知 | - -テキストメッセージは `` XML タグでラップされモデルに配信。 - -### 三、権限バブリング:双方向ポーリング - -教学版は権限バブリングを省略。真实 CC のフロー(`permissionSync.ts`): - -1. **チームメイト**が承認が必要な操作に遭遇 → `permission_request` を Lead の受信箱に送信 -2. **Lead** の `useInboxPoller`(1 秒ごとにポーリング)がリクエストを検出 → `ToolUseConfirmQueue` にルーティング -3. Lead の UI にチームメイト名と色付きの承認ダイアログを表示 -4. ユーザー承認後 → Lead が `permission_response` をチームメイトの受信箱に返信 -5. **チームメイト**の `useSwarmPermissionPoller`(500ms ごとにポーリング)が返信を受信 → 続行または拒否 - -### 四、チームメイトライフサイクル - -CC のチームメイトは `spawnTeammate()`(`spawnMultiAgent.ts`)で作成: - -1. **Spawn**:tmux ペイン(またはプロセス内)を作成、色を割り当て、team config に書き込み -2. **Work**:`useInboxPoller` が毎秒受信箱をチェック → メッセージ到着時に新しい turn として送信 -3. **Idle**:Stop hook 発火 → `idle_notification` を Lead に送信 -4. **Shutdown**:Lead が `shutdown_request` を送信 → チームメイトが `shutdown_approved` で返信 → Lead がクリーンアップ - -### 五、Team Config - -チーム登録は `~/.claude/teams/{teamName}/config.json`(`teamHelpers.ts`): - -```json -{ - "name": "my-team", - "leadAgentId": "lead@my-team", - "members": [{ - "agentId": "researcher@my-team", - "name": "researcher", - "agentType": "general-purpose", - "color": "blue", - "isActive": true - }] -} -``` - -チームメイトのネストは禁止(`AgentTool.tsx:273` で "teammates spawning other teammates" を明示的に禁止)。 - -
- - + diff --git a/s15_agent_teams/README.md b/s15_agent_teams/README.md index 3d035fb2..3eb9bd6f 100644 --- a/s15_agent_teams/README.md +++ b/s15_agent_teams/README.md @@ -1,21 +1,33 @@ -# s15: Agent Teams — Runtime Lab: Persistent Teammates +# s15: Agent Teams — Runtime and Coordination Protocols [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s13 → s14 → `s15` → [s16](../s16_team_protocols/) → s17 → s18 → s19 → s20 → s21 → s22 -> *"One agent isn't enough, form a team"* — File-based inboxes + teammate threads. -> -> **Harness Layer**: Teams — Multi-agent collaboration, message bus. +s01 → ... → s13 → s14 → `s15` → [s16](../s16_autonomous_agents/) → s17 → s18 → s19 → s20 → s21 -> **Module 1 of 2:** s15 and s16 are two focused labs in one Agent Teams module. This lab builds the runtime; s16 adds typed coordination protocols without repeating the runtime. +> *"When one agent cannot hold the whole job, let teammates divide the work."* — Persistent teammates, message delivery, and coordination protocols. +> +> **Harness layer**: Team — how multiple agents work in parallel without losing control. --- ## The Problem -"Refactor the entire backend" touches auth, database layer, API routes, and tests. One agent working on API routes no longer has auth module details in context. The context window is limited, a single agent can't cover every module. +Suppose we ask an agent to refactor an entire backend. The work may cover configuration loading, authentication, and tests. One agent can process those areas sequentially, but it takes longer and earlier details gradually leave its context. -s06's sub-agents are temps, called in for one job, then gone. Some tasks need teammates that can communicate and collaborate. +This is a good candidate for parallel work, yet users normally describe the goal rather than design the team: + +```text +Refactor this sample backend. Clean up configuration loading, +authentication, and tests, preserve the existing interfaces, +and make sure the tests pass. +``` + +The harness therefore has to solve four connected problems: + +1. Who decides that parallel work is useful, and who confirms the extra agents? +2. How does each teammate keep its identity and context across assignments? +3. How do results return to Lead automatically, without asking the model to poll an inbox? +4. How do shutdown and plan approval become traceable, enforceable protocols? --- @@ -23,133 +35,217 @@ s06's sub-agents are temps, called in for one job, then gone. Some tasks need te ![Agent Teams Overview](images/agent-teams-overview.en.svg) -Teaching code carries forward S14's capabilities (prompt assembly, task system, background execution, cron scheduling). To stay focused on the team mechanism, it omits full error recovery, memory, and skill systems. Added: **MessageBus** (file-based inboxes), **spawn_teammate_thread** (launch teammate threads), **inbox injection** (Lead receives teammate messages and injects into history). +s15 adds a Lead-managed team runtime around the single-agent harness: -Sub-agent vs Teammate: +- **Lead** owns the user conversation, proposes a division of work, and waits for confirmation. +- **Teammates** run independent agent loops in background threads and become idle after an assignment. +- **MessageBus** carries ordinary messages, results, and control events through file-backed mailboxes. +- **Runtime delivery** consumes Lead's mailbox and injects team events into the next turn. +- **Coordination protocols** use `type`, `request_id`, and state transitions for shutdown and plan approval. +- **A plan gate** blocks teammate `bash` and `write_file` calls until a required plan is approved. -| | s06 Sub-agent | s15 Teammate | -|---|---|---| -| Lifetime | One-shot, destroyed after use | Multi-turn (teaching: 10 rounds; real CC: idle loop) | -| Communication | Only returns conclusion | Async inbox, communicate anytime | -| Context | Fully isolated | Shared via messages | -| Count | One lead + occasional sub-agent | One Lead + multiple teammates | +The model understands tasks and chooses a useful division of work. Code owns delivery, lifecycle, and protocol constraints. --- ## How It Works -![Team Topology](images/team-topology.en.svg) +### 1. Lead proposes a team and waits for confirmation -### MessageBus: File-Based Inboxes +Starting teammates changes cost, concurrency, and the set of actors that may edit the workspace. That boundary should not be hidden inside an ordinary tool call. Lead's system prompt says: -Each agent (including Lead and teammates) has a `.jsonl` inbox. Send = append a JSON line to the target's file. Read = read file + delete (consumption): +```python +"When parallel work would help, first propose a small team with clear " +"responsibilities and wait for the user's confirmation. Do not call " +"spawn_teammate before the user confirms." +``` + +For the first request, Lead only proposes a split: + +```text +I suggest three parallel areas: +- config: clean up configuration loading +- auth: refactor authentication +- tests: add regression coverage + +I will start the teammates after you confirm. +``` + +After the user says "Go ahead," Lead can call `spawn_teammate`. The user states the goal, Lead designs the team, and the user confirms the execution boundary. + +### 2. Every teammate owns an independent loop + +An s06 subagent is a one-shot call. A teammate is a persistent execution unit: + +| | s06 Subagent | s15 Teammate | +|---|---|---| +| Lifecycle | Ends after one call | `WORK → IDLE → WORK` until shutdown | +| Context | Exists for one task | Persists across assignments | +| Communication | Returns one result | Receives messages and emits events | +| Coordination | One-way delegation | Two-way collaboration with Lead | + +`spawn_teammate_thread()` gives each teammate its own system prompt, messages, and tools, then runs its loop in a daemon thread. Lead can keep coordinating while teammates work. + +### 3. MessageBus keeps communication outside model context + +Lead and teammates cannot share one messages array. Otherwise one teammate's tool results would leak into another teammate's reasoning. `MessageBus` gives each agent a `.mailboxes/.jsonl` inbox: ```python class MessageBus: - def send(self, from_agent: str, to_agent: str, - content: str, msg_type: str = "message"): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time()} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") + def send(self, from_agent, to_agent, content, + msg_type="message", metadata=None): + msg = { + "from": from_agent, + "to": to_agent, + "content": content, + "type": msg_type, + "metadata": metadata or {}, + } + with self._changed: + append_jsonl(self._path(to_agent), msg) + self._changed.notify_all() - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" - if not inbox.exists(): - return [] - msgs = [json.loads(line) for line in inbox.read_text().splitlines()] - inbox.unlink() # consume: read + delete - return msgs + def wait_for_messages(self, agent): + with self._changed: + while not self.peek(agent): + self._changed.wait() + return self._read_unlocked(agent) ``` -Why files instead of in-memory queues? Teaching code uses files because they're intuitive and observable across threads. Real CC also uses file inboxes (`~/.claude/teams/{team}/inboxes/`) but adds `proper-lockfile` for concurrent write safety. The teaching version's `read_inbox` has a read + unlink race, concurrent reads could lose messages, acceptable for teaching purposes. +A lock protects mailbox files from concurrent teammate access. A `Condition` lets idle teammates sleep until an event arrives instead of polling continuously. -### spawn_teammate_thread: Launching a Teammate +### 4. The runtime delivers inbox events automatically -Lead calls the `spawn_teammate` tool to start a teammate. The teammate runs in its own daemon thread with its own system prompt, messages, and simplified tool set: +`read_inbox()` consumes messages by reading and deleting the mailbox file, so Lead keeps a single consumer, `consume_lead_inbox()`: ```python -def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - system = f"You are '{name}', a {role}. Use tools to complete tasks." - - def run(): - messages = [{"role": "user", "content": prompt}] - sub_tools = [bash, read_file, write_file, send_message] - for _ in range(10): # max 10 rounds - inbox = BUS.read_inbox(name) - if inbox: - messages.append({"role": "user", - "content": f"{json.dumps(inbox)}"}) - response = client.messages.create( - model=MODEL, system=system, messages=messages[-20:], - tools=sub_tools, max_tokens=8000) - # ... execute tools, process results - # Send final summary to Lead - BUS.send(name, "lead", summary, "result") - - threading.Thread(target=run, daemon=True).start() +def consume_lead_inbox(): + messages = BUS.read_inbox("lead") + for message in messages: + if message["type"].endswith("_response"): + match_response(...) + return messages ``` -Key design: -- **Simplified tool set**: bash, read, write, send_message. Teaching code omits tasks and cron to focus on communication. Real CC teammates also have TaskCreate, TaskUpdate, etc., the task system is shared across the team -- **Teaching: 10 rounds max**: prevents infinite loops. Real CC uses idle loop: after each round, send `idle_notification`, wait for inbox messages, resume on arrival, exit only on `shutdown_request` -- **Auto-report on completion**: `BUS.send(name, "lead", summary)` sends the final result to Lead's inbox +An event thread beside the main loop wakes Lead when a new message arrives: -### Lead's Inbox Injection +```text +MessageBus → consume_lead_inbox + → update protocol state + → inject [Team events] into history + → start another Lead turn +``` -Lead checks inbox after each main loop iteration. Teammate messages are injected into history so the LLM can see and react to them: +`check_inbox` is not a model tool. Message arrival belongs to the runtime; the model only handles events that have already been delivered into its context. + +### 5. Result and idle are separate events + +When a teammate finishes one assignment, the runtime sends two events in order: + +```text +result: "Authentication refactored; related tests pass." +idle_notification: "Waiting for more work." +``` + +`result` answers "What did this assignment produce?" `idle_notification` answers "Can this teammate accept more work?" A single vague "done" cannot represent both facts. + +An idle teammate does not exit. An ordinary message returns it to WORK; a `shutdown_request` starts a graceful shutdown handshake. + +### 6. Control messages use types and request IDs + +Free-form text is fine for ordinary collaboration, but shutdown and approval should not depend on guessing intent. They use structured messages: + +![Team Protocols](images/team-protocols-overview.en.svg) ```python -# After main loop iteration -inbox = BUS.read_inbox("lead") -if inbox: - inbox_text = "\n".join( - f"From {m['from']}: {m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) +@dataclass +class ProtocolState: + request_id: str + type: str + sender: str + target: str + status: str + payload: str + + +pending_requests: dict[str, ProtocolState] = {} ``` -Teaching code injects in the user input loop. Real CC is more refined, Lead's `useInboxPoller` checks every 1 second, submitting messages as new turns without waiting for user input. +The shutdown path is: -### Permission Bubbling - -Teaching code omits permission bubbling. Real CC's flow (`permissionSync.ts`, `useSwarmPermissionPoller.ts`): - -1. Teammate encounters an operation needing approval → sends `permission_request` to Lead's inbox -2. Lead's `useInboxPoller` detects the request → routes to approval queue -3. User approves → Lead sends `permission_response` back to teammate -4. Teammate's `useSwarmPermissionPoller` (polls every 500ms) receives reply → continue or reject - -### Putting It Together - -``` -1. Lead: "Build the backend: one agent isn't enough, form a team" -2. Lead → spawn_teammate("alice", "backend dev", "Create database schema") -3. Lead → spawn_teammate("bob", "frontend dev", "Write API client") -4. Alice thread starts → her own LLM call → bash "python manage.py migrate" -5. Bob thread starts → his own LLM call → write_file("client.ts", ...) -6. Alice done → BUS.send("alice", "lead", "Schema done: users, orders tables") -7. Bob done → BUS.send("bob", "lead", "Client written with types") -8. Lead next iteration → inbox injected into history → LLM sees both results +```text +Lead creates a pending shutdown request + → shutdown_request(request_id) enters the teammate inbox + → the teammate finishes its current step + → shutdown_response(request_id) returns to Lead + → request_id locates the original request + → pending becomes approved and the teammate loop exits ``` -Two teammates work in parallel. +The ID correlates one reply with one request, the type prevents a mismatched reply from changing state, and the status prevents duplicate responses from being applied twice. + +### 7. Plan approval constrains execution + +The plan protocol runs in the opposite direction: + +```text +Lead → plan_request +teammate → plan_approval_request(request_id, plan) +Lead → plan_approval_response(request_id, approve, feedback) +``` + +Merely telling a teammate to wait is not a reliable gate, so tool dispatch checks the plan state: + +```python +def _run_teammate_tool(name, block, handlers): + gate = plan_gates.get(name, "not_required") + if block.name in {"bash", "write_file"} and gate not in { + "not_required", "approved" + }: + return f"Blocked: plan status is {gate}." + return handlers[block.name](**block.input) +``` + +While the state is `required`, `pending`, or `rejected`, the teammate can read files and submit or revise a plan, but it cannot run Shell commands or write files. The tools are released only after an approval response changes the state to `approved`. --- -## Changes from s14 +## One Complete Run -| Component | Before (s14) | After (s15) | -|-----------|-------------|-------------| -| Agent count | 1 | 1 Lead + N teammate threads | -| Communication | None | MessageBus + .mailboxes/*.jsonl | -| New classes | — | MessageBus, active_teammates dict | -| New functions | — | spawn_teammate_thread, run_send_message, run_check_inbox | -| Lead tools | 11 (s14) | + spawn_teammate, send_message, check_inbox (14) | -| Teammate tools | — | bash, read_file, write_file, send_message (4) | -| Permissions | Local decisions | Teaching code omits (real CC has bubbling) | +```text +s15 >> Refactor this sample backend. Clean up configuration loading, + authentication, and tests, preserve existing interfaces, + and make sure the tests pass. + +Lead: I suggest config, auth, and tests as three parallel areas. + Shall I start the team? + +s15 >> Go ahead. + +[teammate] config spawned +[teammate] auth spawned +[teammate] tests spawned +[bus] auth → lead (result) ... +[bus] auth → lead (idle_notification) ... +[wake: 2 team events → new turn] +Lead: I received the authentication result and will coordinate the rest. +``` + +The terminal exposes the user request, Lead's split, teammate startup, messages, results, idle transitions, and shutdown events. The user does not have to name a Lead or ask it to check an inbox. + +--- + +## What Changed from s14 + +| Component | s14 | s15 | +|---|---|---| +| Agents | One agent | One Lead plus persistent teammates | +| User flow | Execute the request | Propose a team, then confirm startup | +| Communication | None | File mailboxes plus automatic delivery | +| Lifecycle | One loop | Teammate `WORK / IDLE / shutdown` | +| Reporting | Current agent output | Separate `result` and `idle_notification` | +| Control | None | Shutdown and plan approval protocols | +| Enforcement | No team constraint | Required plans gate mutating tools | --- @@ -160,97 +256,28 @@ cd learn-claude-code python s15_agent_teams/code.py ``` -Try these prompts: +Start with an ordinary request: -1. `Spawn alice as a backend developer. Ask her to create a file called schema.sql with a users table.` -2. `Check your inbox for alice's result.` -3. `Spawn bob as a tester. Ask him to check if schema.sql exists and list its contents.` +```text +Refactor this sample backend. Clean up configuration loading, +authentication, and tests, preserve the existing interfaces, +and make sure the tests pass. +``` -What to observe: How does Lead spawn teammates? What do the `.mailboxes/` JSONL files look like? After teammates finish, is Lead's inbox injected into history? +After Lead proposes the team, reply: + +```text +Go ahead. +``` + +Watch for `spawned`, `result`, `idle_notification`, `plan_approval_*`, and `shutdown_*` events, along with mailbox files appearing and being consumed under `.mailboxes/`. --- -## What's Next +## Next -Teammates can work and communicate. But if Lead wants Alice to shut down, killing the thread outright could leave half-written files. A graceful shutdown protocol is needed: Lead sends shutdown_request, teammate wraps up and exits. +In s15, Lead still assigns each teammate explicitly. The next lesson gives idle teammates access to the shared task board so they can discover and claim ready work themselves. -s16 Agent Teams Protocol Lab → keep this runtime and add shutdown handshakes, plan approval, and typed request-reply messages. +Next: [s16 Autonomous Agents](../s16_autonomous_agents/). -
-Deep Dive into CC Source - -> The following is a complete analysis based on CC source code `spawnMultiAgent.ts`, `useInboxPoller.ts` (969 lines), `useSwarmPermissionPoller.ts` (330 lines), `teammateMailbox.ts`, `teamHelpers.ts`. - -### 1. No Central Message Bus, It's the Filesystem - -Teaching code uses a `MessageBus` class to send and receive messages. Real CC is more direct, each agent writes directly to other agents' inbox files. - -Inbox path: `~/.claude/teams/{teamName}/inboxes/{agentName}.json` - -Writes use `proper-lockfile` for concurrent write safety (up to 10 retries). Each file is a JSON array; appending reads → appends → writes back. - -### 2. 15 Message Types - -CC team communication has 15 structured message types (`teammateMailbox.ts`): - -| Type | Direction | Purpose | -|------|-----------|---------| -| `plain text` | Both ways | Normal inter-teammate communication | -| `idle_notification` | Teammate→Lead | Teammate finished a turn, now idle | -| `permission_request` | Teammate→Lead | Teammate needs operation approval | -| `permission_response` | Lead→Teammate | Lead's approval result | -| `plan_approval_request` | Teammate→Lead | Teammate submits plan for review | -| `plan_approval_response` | Lead→Teammate | Lead's plan review | -| `shutdown_request` | Lead→Teammate | Request graceful shutdown | -| `shutdown_approved` | Teammate→Lead | Confirm shutdown | -| `shutdown_rejected` | Teammate→Lead | Reject shutdown (with reason) | -| `task_assignment` | Lead→Teammate | Assign a task | -| `team_permission_update` | Lead→Teammate | Broadcast permission changes | -| `mode_set_request` | Lead→Teammate | Change teammate's permission mode | -| `sandbox_permission_*` | Both ways | Network permission request/reply | -| `teammate_terminated` | System | Teammate removed notification | - -Text messages are wrapped in `` XML tags for delivery to the model. - -### 3. Permission Bubbling: Bidirectional Polling - -Teaching code omits permission bubbling. Real CC's flow (`permissionSync.ts`): - -1. **Teammate** encounters operation needing approval → sends `permission_request` to Lead's inbox -2. **Lead's** `useInboxPoller` (polls every 1s) detects request → routes to `ToolUseConfirmQueue` -3. Lead's UI shows approval dialog with teammate name and color -4. User approves → Lead sends `permission_response` back to teammate's inbox -5. **Teammate's** `useSwarmPermissionPoller` (polls every 500ms) receives reply → continue or reject - -### 4. Teammate Lifecycle - -CC teammates are created by `spawnTeammate()` (`spawnMultiAgent.ts`): - -1. **Spawn**: Create tmux pane (or in-process), assign color, write team config -2. **Work**: `useInboxPoller` checks inbox every 1s → submit as new turn when messages arrive -3. **Idle**: Stop hook fires → send `idle_notification` to Lead -4. **Shutdown**: Lead sends `shutdown_request` → teammate replies `shutdown_approved` → Lead cleans up - -### 5. Team Config - -Team registry at `~/.claude/teams/{teamName}/config.json` (`teamHelpers.ts`): - -```json -{ - "name": "my-team", - "leadAgentId": "lead@my-team", - "members": [{ - "agentId": "researcher@my-team", - "name": "researcher", - "agentType": "general-purpose", - "color": "blue", - "isActive": true - }] -} -``` - -Teammates cannot be nested (`AgentTool.tsx:273` explicitly forbids "teammates spawning other teammates"). - -
- - + diff --git a/s15_agent_teams/README.zh.md b/s15_agent_teams/README.zh.md index e7400999..b00592a1 100644 --- a/s15_agent_teams/README.zh.md +++ b/s15_agent_teams/README.zh.md @@ -1,21 +1,32 @@ -# s15: Agent Teams — 运行时实验:持久队友 +# s15: Agent Teams — 团队运行时与协作协议 [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s13 → s14 → `s15` → [s16](../s16_team_protocols/) → s17 → s18 → s19 → s20 → s21 → s22 -> *"一个搞不定, 组队来"* — 文件收件箱 + 队友线程。 -> -> **Harness 层**: 团队 — 多 Agent 协作, 消息总线。 +s01 → ... → s13 → s14 → `s15` → [s16](../s16_autonomous_agents/) → s17 → s18 → s19 → s20 → s21 -> **模块 1/2:** s15 与 s16 是同一个 Agent Teams 模块中的两次聚焦实验。本章搭建运行时;s16 在不重复运行时的前提下增加带类型的协作协议。 +> *"一个 Agent 顾不过来,就让队友分工协作。"* — 持久队友、消息投递与协作协议。 +> +> **Harness 层**:团队 — 多个 Agent 如何并行工作,又如何保持可控。 --- ## 问题 -"重构整个后端"涉及认证模块、数据库层、API 路由、测试。一个 Agent 在修 API 路由时,认证模块的细节已经不在上下文里了。上下文窗口就那么大,单个 Agent 的注意力覆盖不了所有模块。 +当我们需要 Agent 帮助我们重构整个后端时,任务可能同时涉及配置加载、认证逻辑和测试。一个 Agent 依次处理所有模块,不但耗时更长,早期细节也会逐渐退出上下文。 -s06 的子 Agent 是临时工,叫来干一件事就走了。但有些任务需要能通信、能协作的队友。 +这类任务适合拆给多个 Agent,但用户通常只会描述需求,不会先设计一套团队: + +```text +请重构这个示例后端,分别整理配置加载、认证逻辑和测试, +保持现有接口兼容,并确保测试通过。 +``` + +因此,Harness 需要解决的不只是“再启动几个 Agent”,而是四个连续问题: + +1. 谁判断任务是否值得并行,以及如何征得用户确认? +2. 队友如何保留自己的身份和上下文,持续接收工作? +3. 队友的结果如何自动回到 Lead,而不是依赖模型反复检查邮箱? +4. 关机与计划审批如何变成可追踪、可执行的协议? --- @@ -23,133 +34,214 @@ s06 的子 Agent 是临时工,叫来干一件事就走了。但有些任务需 ![Agent Teams Overview](images/agent-teams-overview.svg) -教学代码沿用 S14 的能力(prompt 组装、任务系统、后台执行、cron 调度)。为了聚焦团队机制,省略了完整错误恢复、记忆和技能系统。新增三样:**MessageBus**(文件收件箱)、**spawn_teammate_thread**(启动队友线程)、**inbox 注入**(Lead 接收队友消息并注入 history)。 +s15 在单 Agent Harness 外增加一个由 Lead 管理的团队运行时: -子 Agent vs 队友: +- **Lead** 保持用户对话,判断是否需要团队,提出分工并等待确认。 +- **队友** 在独立线程中运行自己的 Agent Loop,完成工作后进入空闲。 +- **MessageBus** 用文件邮箱传递普通消息、结果和控制事件。 +- **运行时投递** 自动消费 Lead 的邮箱,把团队事件注入下一轮上下文。 +- **协作协议** 用 `type`、`request_id` 和状态机处理关机与计划审批。 +- **计划闸门** 在计划未批准时拦截队友的 `bash` 和 `write_file`。 -| | s06 子 Agent | s15 队友 | -|---|---|---| -| 生命周期 | 一次性,用完销毁 | 多轮(教学版限 10 轮,真实 CC 用 idle loop) | -| 通信 | 只回传结论 | 异步收件箱,随时通信 | -| 上下文 | 完全隔离 | 通过消息共享信息 | -| 数量 | 一个主 Agent + 偶尔子 Agent | 一个 Lead + 多个队友 | +模型负责理解任务与分工,代码负责消息投递、生命周期和协议约束。 --- ## 工作原理 -![Team Topology](images/team-topology.svg) +### 1. Lead 先提出团队,再等待用户确认 -### MessageBus: 文件收件箱 +是否创建团队会改变成本、并发度和可写入范围,不应该被隐藏在一次普通工具调用里。Lead 的 system prompt 明确规定: -每个 Agent(包括 Lead 和队友)有一个 `.jsonl` 邮箱。发消息 = 往对方的文件里 append 一行 JSON。读消息 = 读文件 + 删除(消费式): +```python +"When parallel work would help, first propose a small team with clear " +"responsibilities and wait for the user's confirmation. Do not call " +"spawn_teammate before the user confirms." +``` + +第一次输入需求时,Lead 只需要说明建议的拆分: + +```text +我建议分成三个方向并行处理: +- config:整理配置加载 +- auth:重构认证逻辑 +- tests:补齐回归测试 + +确认后我会启动队友并协调结果。 +``` + +用户回复“开始吧”后,Lead 才调用 `spawn_teammate`。用户表达目标,Lead 设计团队,用户确认执行边界;三者的职责不会混在一起。 + +### 2. 每个队友拥有独立循环 + +s06 的子 Agent 是一次性调用,返回结果后就结束。队友则是持久执行单元: + +| | s06 子 Agent | s15 队友 | +|---|---|---| +| 生命周期 | 完成一次调用后结束 | `WORK → IDLE → WORK`,直到收到关机请求 | +| 上下文 | 只服务当前任务 | 在多轮协作中保留 | +| 通信 | 返回一次结果 | 持续接收消息并上报事件 | +| 协调 | 主 Agent 单向委派 | Lead 与队友双向协作 | + +`spawn_teammate_thread()` 为队友创建独立的 system prompt、messages 和工具集,并把循环放入 daemon 线程。Lead 不必等待某个队友结束,仍可继续派发任务或处理其他结果。 + +### 3. MessageBus 把通信放在上下文之外 + +Lead 和队友不能共享同一份 messages,否则一个队友的工具结果会混入另一个队友的推理。`MessageBus` 为每个 Agent 建立 `.mailboxes/.jsonl`: ```python class MessageBus: - def send(self, from_agent: str, to_agent: str, - content: str, msg_type: str = "message"): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time()} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") + def send(self, from_agent, to_agent, content, + msg_type="message", metadata=None): + msg = { + "from": from_agent, + "to": to_agent, + "content": content, + "type": msg_type, + "metadata": metadata or {}, + } + with self._changed: + append_jsonl(self._path(to_agent), msg) + self._changed.notify_all() - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" - if not inbox.exists(): - return [] - msgs = [json.loads(line) for line in inbox.read_text().splitlines()] - inbox.unlink() # 消费式:读完删除 - return msgs + def wait_for_messages(self, agent): + with self._changed: + while not self.peek(agent): + self._changed.wait() + return self._read_unlocked(agent) ``` -为什么用文件而不是内存队列?教学版选文件是因为直观、跨线程可观察。真实 CC 也用文件收件箱(`~/.claude/teams/{team}/inboxes/`),但加了 `proper-lockfile` 防并发写冲突。教学版的 `read_inbox` 有 read + unlink 竞态,多线程同时读可能丢消息,对教学场景可以接受。 +锁保证同一进程中的多个队友不会同时破坏邮箱文件,`Condition` 让空闲队友等待事件,而不是持续轮询。 -### spawn_teammate_thread: 启动队友 +### 4. 收件箱由运行时自动投递 -Lead 调用 `spawn_teammate` 工具启动一个队友。队友跑在自己的 daemon 线程里,有自己的 system prompt、自己的 messages、自己的简化工具集: +`read_inbox()` 是消费式读取:读出后删除邮箱文件。因此,Lead 只保留一个消费入口 `consume_lead_inbox()`: ```python -def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - system = f"You are '{name}', a {role}. Use tools to complete tasks." - - def run(): - messages = [{"role": "user", "content": prompt}] - sub_tools = [bash, read_file, write_file, send_message] - for _ in range(10): # 最多 10 轮 - inbox = BUS.read_inbox(name) - if inbox: - messages.append({"role": "user", - "content": f"{json.dumps(inbox)}"}) - response = client.messages.create( - model=MODEL, system=system, messages=messages[-20:], - tools=sub_tools, max_tokens=8000) - # ... 执行工具、处理结果 - # 完成后发 summary 给 Lead - BUS.send(name, "lead", summary, "result") - - threading.Thread(target=run, daemon=True).start() +def consume_lead_inbox(): + messages = BUS.read_inbox("lead") + for message in messages: + if message["type"].endswith("_response"): + match_response(...) + return messages ``` -关键设计: -- **队友有简化工具集**:bash、read、write、send_message。教学版省略了任务和 cron,聚焦通信机制。真实 CC 的队友也有 TaskCreate、TaskUpdate 等工具,任务系统是团队共享的 -- **教学版限 10 轮**:防止队友无限循环。真实 CC 用 idle loop:跑完一轮后发 `idle_notification`,等 inbox 消息,收到后继续,直到 `shutdown_request` 才退出 -- **完成后自动汇报**:`BUS.send(name, "lead", summary)` 把最终结果发到 Lead 的收件箱 +主循环旁的事件线程发现新消息后,会唤醒 Lead: -### Lead 的 inbox 注入 +```text +MessageBus → consume_lead_inbox + → 更新协议状态 + → [Team events] 注入 history + → Lead 开始新一轮 +``` -Lead 在每轮主循环结束后检查收件箱。队友发来的消息注入到 history 里,让 LLM 能看到并做出反应: +`check_inbox` 不再是模型工具。消息何时到达属于运行时职责;模型只需要处理已经送入上下文的事件。 + +### 5. 结果与空闲是两个不同事件 + +队友完成一项工作时,运行时依次发送: + +```text +result: "认证逻辑已重构,相关测试通过。" +idle_notification: "Waiting for more work." +``` + +`result` 回答“这次工作产出了什么”,`idle_notification` 表示“这个队友现在可以接新任务”。如果把两者合成一个模糊的“done”,Lead 就无法区分任务结果和资源状态。 + +队友进入 IDLE 后不会退出。新普通消息会让它回到 WORK;`shutdown_request` 则让它完成关机握手并结束线程。 + +### 6. 控制消息使用类型和 request_id + +普通消息可以交给模型理解,关机和审批不能依赖自由文本猜测。它们使用结构化消息: + +![Team Protocols](images/team-protocols-overview.svg) ```python -# 主循环结束后 -inbox = BUS.read_inbox("lead") -if inbox: - inbox_text = "\n".join( - f"From {m['from']}: {m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) +@dataclass +class ProtocolState: + request_id: str + type: str + sender: str + target: str + status: str + payload: str + + +pending_requests: dict[str, ProtocolState] = {} ``` -教学版在用户输入循环外注入。CC 更精细,Lead 的 `useInboxPoller` 每 1 秒检查一次,有消息就提交为新的 turn,不需要等用户输入。 +关机协议的完整路径是: -### 权限冒泡 - -教学版省略了权限冒泡。真实 CC 的流程(`permissionSync.ts`、`useSwarmPermissionPoller.ts`): - -1. 队友遇到需要审批的操作 → 发 `permission_request` 到 Lead 收件箱 -2. Lead 的 `useInboxPoller` 检测到请求 → 路由到审批队列 -3. 用户审批后 → Lead 发 `permission_response` 回队友 -4. 队友的 `useSwarmPermissionPoller`(每 500ms 轮询)收到回复 → 继续或拒绝 - -### 合起来跑 - -``` -1. Lead: "搭建后端:一个人搞不定,组队吧" -2. Lead → spawn_teammate("alice", "backend dev", "创建数据库 schema") -3. Lead → spawn_teammate("bob", "frontend dev", "写 API 客户端") -4. alice 线程启动 → 自己的 LLM 调用 → bash "python manage.py migrate" -5. bob 线程启动 → 自己的 LLM 调用 → write_file("client.ts", ...) -6. alice 完成 → BUS.send("alice", "lead", "Schema done: users, orders tables") -7. bob 完成 → BUS.send("bob", "lead", "Client written with types") -8. Lead 下次循环 → inbox 注入 history → LLM 看到 alice 和 bob 的结果 +```text +Lead 创建 shutdown 请求,状态为 pending + → shutdown_request(request_id) 发给队友 + → 队友完成当前步骤并回复 shutdown_response(request_id) + → Lead 用 request_id 找到原请求 + → pending 变为 approved,队友线程退出 ``` -两个队友并行工作。 +`request_id` 负责关联请求与回复,`type` 防止错误类型的回复修改状态,`status` 防止重复响应被再次处理。 + +### 7. 计划审批不仅传消息,还约束执行 + +计划协议沿相反方向流动: + +```text +Lead → plan_request +队友 → plan_approval_request(request_id, plan) +Lead → plan_approval_response(request_id, approve, feedback) +``` + +只告诉队友“请等待批准”并不可靠,所以工具分发器检查计划状态: + +```python +def _run_teammate_tool(name, block, handlers): + gate = plan_gates.get(name, "not_required") + if block.name in {"bash", "write_file"} and gate not in { + "not_required", "approved" + }: + return f"Blocked: plan status is {gate}." + return handlers[block.name](**block.input) +``` + +当状态为 `required`、`pending` 或 `rejected` 时,队友仍可读取文件、提交或修改计划,但不能执行 Shell 或写文件。批准消息到达后,状态变为 `approved`,工具才会放行。 --- -## 相对 s14 的变更 +## 一次完整运行 -| 组件 | 之前 (s14) | 之后 (s15) | -|------|-----------|-----------| -| Agent 数量 | 1 | 1 Lead + N 队友线程 | -| 通信 | 无 | MessageBus + .mailboxes/*.jsonl | -| 新类 | — | MessageBus, active_teammates dict | -| 新函数 | — | spawn_teammate_thread, run_send_message, run_check_inbox | -| Lead 工具 | 11 (s14) | + spawn_teammate, send_message, check_inbox (14) | -| 队友工具 | — | bash, read_file, write_file, send_message (4) | -| 权限 | 本地决策 | 教学版省略(真实 CC 有冒泡机制) | +```text +s15 >> 请重构这个示例后端,分别整理配置加载、认证逻辑和测试, + 保持现有接口兼容,并确保测试通过。 + +Lead: 建议由 config、auth、tests 三个方向并行处理,是否开始? + +s15 >> 开始吧 + +[teammate] config spawned +[teammate] auth spawned +[teammate] tests spawned +[bus] auth → lead (result) ... +[bus] auth → lead (idle_notification) ... +[wake: 2 team events → new turn] +Lead: 已收到认证部分结果,继续等待并协调其他队友。 +``` + +终端中显示的是用户需求、Lead 分工、队友启动、消息流、结果、空闲和关机事件。用户不需要在提示词里指定谁是 Lead,也不需要手动要求检查邮箱。 + +--- + +## 相对 s14 的变化 + +| 组件 | s14 | s15 | +|---|---|---| +| Agent 数量 | 一个 Agent | 一个 Lead + 多个持久队友 | +| 用户交互 | 直接执行任务 | 先提出团队方案,再确认启动 | +| 通信 | 无 | 文件邮箱 + 自动事件投递 | +| 生命周期 | 单循环 | 队友 `WORK / IDLE / shutdown` | +| 结果上报 | 当前 Agent 输出 | `result` 与 `idle_notification` 分离 | +| 控制协议 | 无 | 关机与计划审批 | +| 执行约束 | 无团队约束 | 未批准计划会拦截写入类工具 | --- @@ -160,97 +252,27 @@ cd learn-claude-code python s15_agent_teams/code.py ``` -试试这些 prompt: +先输入一个自然需求: -1. `Spawn alice as a backend developer. Ask her to create a file called schema.sql with a users table.` -2. `Check your inbox for alice's result.` -3. `Spawn bob as a tester. Ask him to check if schema.sql exists and list its contents.` +```text +请重构这个示例后端,分别整理配置加载、认证逻辑和测试, +保持现有接口兼容,并确保测试通过。 +``` -观察重点:Lead 如何启动队友?`.mailboxes/` 目录下的 JSONL 文件长什么样?队友完成后 Lead 的 inbox 有没有注入到 history? +看到 Lead 给出分工后,再回复: + +```text +开始吧 +``` + +观察终端中的 `spawned`、`result`、`idle_notification`、`plan_approval_*` 和 `shutdown_*` 事件,以及 `.mailboxes/` 中消息写入和消费的过程。 --- ## 接下来 -队友能干活、能通信。但如果 Lead 想让 Alice 关机,直接杀线程会留下写到一半的文件。需要一个体面的关机协议:Lead 发 shutdown_request,队友收尾后退出。 +s15 中,Lead 仍然要明确告诉每个队友做什么。下一章把共享任务看板交给空闲队友,让它们自己发现并认领可执行任务。 -s16 Agent Teams 协议实验 → 沿用本章运行时,加入关机握手、计划审批与带类型的请求-回复消息。 +下一章:[s16 Autonomous Agents](../s16_autonomous_agents/)。 -
-深入 CC 源码 - -> 以下基于 CC 源码 `spawnMultiAgent.ts`、`useInboxPoller.ts`(969 行)、`useSwarmPermissionPoller.ts`(330 行)、`teammateMailbox.ts`、`teamHelpers.ts` 的完整分析。 - -### 一、没有中央消息总线,是文件系统 - -教学版用 `MessageBus` 类收发消息。CC 的做法更直接,每个 Agent 直接写其他 Agent 的收件箱文件。 - -收件箱路径:`~/.claude/teams/{teamName}/inboxes/{agentName}.json` - -写入时用 `proper-lockfile` 文件锁保证并发安全(最多重试 10 次)。每个文件是一个 JSON 数组,append 新消息时读→追加→写回。 - -### 二、15 种消息类型 - -CC 的团队通信有 15 种结构化消息(`teammateMailbox.ts`): - -| 类型 | 方向 | 用途 | -|------|------|------| -| `plain text` | 双向 | 普通队友间通信 | -| `idle_notification` | 队友→Lead | 队友完成一轮工作,进入空闲 | -| `permission_request` | 队友→Lead | 队友需要操作审批 | -| `permission_response` | Lead→队友 | Lead 审批结果 | -| `plan_approval_request` | 队友→Lead | 队友提交计划待审 | -| `plan_approval_response` | Lead→队友 | Lead 审批计划 | -| `shutdown_request` | Lead→队友 | 请求体面关机 | -| `shutdown_approved` | 队友→Lead | 确认关机 | -| `shutdown_rejected` | 队友→Lead | 拒绝关机(附原因) | -| `task_assignment` | Lead→队友 | 分配任务 | -| `team_permission_update` | Lead→队友 | 广播权限变更 | -| `mode_set_request` | Lead→队友 | 修改队友的权限模式 | -| `sandbox_permission_*` | 双向 | 网络权限请求/回复 | -| `teammate_terminated` | 系统 | 队友被移除通知 | - -文本消息被包装在 `` XML 标签中交付给模型。 - -### 三、权限冒泡:双向轮询 - -教学版省略了权限冒泡。CC 的实际流程(`permissionSync.ts`): - -1. **队友**遇到需要审批的操作 → 发 `permission_request` 到 Lead 的收件箱 -2. **Lead** 的 `useInboxPoller`(每 1 秒轮询)检测到请求 → 路由到 `ToolUseConfirmQueue` -3. Lead 的 UI 显示审批对话框,带队友名字和颜色 -4. 用户审批后 → Lead 发 `permission_response` 回队友的收件箱 -5. **队友**的 `useSwarmPermissionPoller`(每 500ms 轮询)收到回复 → 继续或拒绝执行 - -### 四、队友生命周期 - -CC 的队友由 `spawnTeammate()`(`spawnMultiAgent.ts`)创建: - -1. **Spawn**:创建 tmux 窗格(或进程内),分配颜色,写入 team config -2. **Work**:`useInboxPoller` 每 1 秒检查收件箱 → 有消息就提交为新的 turn -3. **Idle**:Stop hook 触发 → 发 `idle_notification` 给 Lead -4. **Shutdown**:Lead 发 `shutdown_request` → 队友回复 `shutdown_approved` → Lead 清理 - -### 五、Team Config - -团队注册表在 `~/.claude/teams/{teamName}/config.json`(`teamHelpers.ts`): - -```json -{ - "name": "my-team", - "leadAgentId": "lead@my-team", - "members": [{ - "agentId": "researcher@my-team", - "name": "researcher", - "agentType": "general-purpose", - "color": "blue", - "isActive": true - }] -} -``` - -队友之间不能嵌套(`AgentTool.tsx:273` 明确禁止 "teammates spawning other teammates")。 - -
- - + diff --git a/s15_agent_teams/code.py b/s15_agent_teams/code.py index 143a73e8..55911573 100644 --- a/s15_agent_teams/code.py +++ b/s15_agent_teams/code.py @@ -1,29 +1,27 @@ #!/usr/bin/env python3 """ -s15: Agent Teams — MessageBus + spawn_teammate_thread + inbox injection. +s15: Agent Teams — persistent teammates, mailboxes, and typed protocols. Run: python s15_agent_teams/code.py Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY Changes from s14: - - MessageBus class: file-based mailboxes (.mailboxes/*.jsonl) - - spawn_teammate_thread: creates teammate in background thread - - Teammate runs own simplified agent_loop (bash, read, write, send_message) - - Lead tools: spawn_teammate, send_message, check_inbox (3 new) - - Lead inbox: teammate messages injected into history (not just printed) - - Teaching version: teammates limited to 10 rounds (real CC uses idle loop) + - MessageBus: thread-safe, file-backed mailboxes (.mailboxes/*.jsonl) + - Persistent teammate loops with WORK and IDLE states + - Runtime delivery of teammate results and idle notifications to Lead + - Typed shutdown and plan-approval protocols with request_id matching + - Plan approval gates bash and write_file until Lead approves ASCII flow: - Lead: cron_queue → messages → prompt → LLM → TOOLS ────→ loop - ↑ ↓ | - └── inbox ← MessageBus ← teammate.send_message ←┘ - Teammate: inbox → LLM → bash/read/write/send → loop (max 10 turns) + User → Lead → spawn_teammate → teammate WORK → result → IDLE + ↑ ↓ | + └──────── MessageBus + typed protocol ┘ """ -import os, subprocess, json, time, random, threading, queue +import os, subprocess, json, time, random, threading, queue, re from pathlib import Path from datetime import datetime -from dataclasses import dataclass, asdict +from dataclasses import dataclass, asdict, field try: import readline @@ -145,7 +143,15 @@ PROMPT_SECTIONS = { "tools": "Available tools: bash, read_file, write_file, " "get_task, create_task, list_tasks, claim_task, complete_task, " "schedule_cron, list_crons, cancel_cron, " - "spawn_teammate, send_message, check_inbox.", + "spawn_teammate, send_message, request_shutdown, " + "request_plan, review_plan.", + "teams": ( + "When parallel work would help, first propose a small team with clear " + "responsibilities and wait for the user's confirmation. Do not call " + "spawn_teammate before the user confirms. After confirmation, delegate " + "independent work, react to team events delivered by the runtime, and " + "shut teammates down when coordination is complete." + ), "workspace": f"Working directory: {WORKDIR}", "memory": "Relevant memories are injected below when available.", } @@ -154,6 +160,7 @@ PROMPT_SECTIONS = { def assemble_system_prompt(context: dict) -> str: sections = [PROMPT_SECTIONS["identity"], PROMPT_SECTIONS["tools"], + PROMPT_SECTIONS["teams"], PROMPT_SECTIONS["workspace"]] memories = context.get("memories", "") if memories: @@ -290,7 +297,10 @@ def execute_tool(block) -> str: "schedule_cron": run_schedule_cron, "list_crons": run_list_crons, "cancel_cron": run_cancel_cron, "spawn_teammate": run_spawn_teammate, - "send_message": run_send_message, "check_inbox": run_check_inbox, + "send_message": run_send_message, + "request_shutdown": run_request_shutdown, + "request_plan": run_request_plan, + "review_plan": run_review_plan, }.get(block.name) if handler: return handler(**block.input) @@ -591,66 +601,275 @@ def run_cancel_cron(job_id: str) -> str: return cancel_job(job_id) -# ── MessageBus (s15 new) ── -# Teaching version uses simple file append + unlink. -# Real CC uses proper-lockfile for concurrent write safety. +# ── MessageBus + Team Protocols (s15 new) ── MAILBOX_DIR = WORKDIR / ".mailboxes" MAILBOX_DIR.mkdir(exist_ok=True) +MAILBOX_ROOT = MAILBOX_DIR.resolve() +VALID_AGENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$") + + +def is_valid_agent_name(name: str) -> bool: + return bool(VALID_AGENT_NAME.fullmatch(name)) class MessageBus: - """File-based message bus. Each agent has a .jsonl inbox. - Read is destructive: read_text + unlink (consumes messages). - Teaching version: no file locking; real CC uses proper-lockfile.""" + """Thread-safe file mailboxes with destructive reads.""" - def send(self, from_agent: str, to_agent: str, content: str, - msg_type: str = "message"): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time()} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") - print(f" \033[33m[bus] {from_agent} → {to_agent}: " - f"{content[:50]}\033[0m") + def __init__(self): + self._lock = threading.RLock() + self._changed = threading.Condition(self._lock) - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" + def _path(self, agent: str) -> Path: + if not is_valid_agent_name(agent): + raise ValueError(f"Invalid mailbox recipient: {agent!r}") + path = (MAILBOX_DIR / f"{agent}.jsonl").resolve() + if not path.is_relative_to(MAILBOX_ROOT): + raise ValueError(f"Mailbox path escapes directory: {agent!r}") + return path + + def _read_unlocked(self, agent: str) -> list[dict]: + inbox = self._path(agent) if not inbox.exists(): return [] msgs = [json.loads(line) for line in inbox.read_text().splitlines() if line.strip()] - inbox.unlink() # consume: read + delete + inbox.unlink() return msgs + def send(self, from_agent: str, to_agent: str, content: str, + msg_type: str = "message", metadata: dict | None = None): + msg = {"from": from_agent, "to": to_agent, + "content": content, "type": msg_type, + "ts": time.time(), "metadata": metadata or {}} + with self._changed: + with open(self._path(to_agent), "a") as f: + f.write(json.dumps(msg, ensure_ascii=False) + "\n") + self._changed.notify_all() + print(f" \033[33m[bus] {from_agent} → {to_agent}: " + f"({msg_type}) {content[:50]}\033[0m") + + def read_inbox(self, agent: str) -> list[dict]: + with self._lock: + return self._read_unlocked(agent) + def peek(self, agent: str) -> bool: - """Non-destructive: True if the agent has unread inbox messages. - The Lead's inbox poller uses this to decide whether to wake a turn - without consuming the mailbox.""" - inbox = MAILBOX_DIR / f"{agent}.jsonl" - return inbox.exists() and inbox.stat().st_size > 0 + with self._lock: + inbox = self._path(agent) + return inbox.exists() and inbox.stat().st_size > 0 + + def wait_for_messages(self, agent: str, + timeout: float | None = None) -> list[dict]: + """Block until the agent has messages or timeout expires.""" + deadline = None if timeout is None else time.monotonic() + timeout + with self._changed: + while not self.peek(agent): + remaining = (None if deadline is None + else deadline - time.monotonic()) + if remaining is not None and remaining <= 0: + return [] + self._changed.wait(remaining) + return self._read_unlocked(agent) BUS = MessageBus() -# Track spawned teammates -active_teammates: dict[str, bool] = {} +# working | waiting_approval | idle | stopping +active_teammates: dict[str, str] = {} +plan_gates: dict[str, str] = {} +plan_request_ids: dict[str, str] = {} +team_lock = threading.RLock() -# ── Teammate Thread (s15 new) ── +@dataclass +class ProtocolState: + request_id: str + type: str + sender: str + target: str + status: str + payload: str + created_at: float = field(default_factory=time.time) + + +pending_requests: dict[str, ProtocolState] = {} + + +def new_request_id() -> str: + while True: + request_id = f"req_{random.randint(0, 999999):06d}" + if request_id not in pending_requests: + return request_id + + +def match_response(response_type: str, request_id: str, approve: bool, + from_agent: str, to_agent: str) -> bool: + """Match one protocol response to one pending request.""" + with team_lock: + state = pending_requests.get(request_id) + if not state: + print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") + return False + expected = { + "shutdown": "shutdown_response", + "plan_approval": "plan_approval_response", + }[state.type] + if response_type != expected: + print(f" \033[31m[protocol] expected {expected}, " + f"got {response_type}\033[0m") + return False + if from_agent != state.target or to_agent != state.sender: + print(f" \033[31m[protocol] {request_id} responder mismatch\033[0m") + return False + if state.status != "pending": + print(f" \033[33m[protocol] {request_id} already " + f"{state.status}\033[0m") + return False + state.status = "approved" if approve else "rejected" + print(f" \033[35m[protocol] {request_id} → {state.status}\033[0m") + return True + + +def consume_lead_inbox() -> list[dict]: + """Consume Lead events and update protocol state before model delivery.""" + msgs = BUS.read_inbox("lead") + for msg in msgs: + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + if request_id and msg.get("type", "").endswith("_response"): + match_response(msg["type"], request_id, + metadata.get("approve", False), + msg.get("from", ""), msg.get("to", "")) + return msgs + + +def format_team_events(msgs: list[dict]) -> str: + lines = [] + for msg in msgs: + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id") + suffix = f" request_id={request_id}" if request_id else "" + lines.append( + f"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}" + ) + return "[Team events]\n" + "\n".join(lines) + + +def _last_assistant_text(content) -> str: + for block in content: + if getattr(block, "type", None) == "text": + return block.text.strip() + if isinstance(block, dict) and block.get("type") == "text": + return str(block.get("text", "")).strip() + return "" + + +def _teammate_submit_plan(from_name: str, plan: str) -> str: + with team_lock: + if plan_gates.get(from_name) == "pending": + return "A plan is already waiting for review." + request_id = new_request_id() + pending_requests[request_id] = ProtocolState( + request_id=request_id, + type="plan_approval", + sender=from_name, + target="lead", + status="pending", + payload=plan, + ) + plan_gates[from_name] = "pending" + plan_request_ids[from_name] = request_id + active_teammates[from_name] = "waiting_approval" + BUS.send(from_name, "lead", plan, "plan_approval_request", + {"request_id": request_id}) + return f"Plan submitted ({request_id}). Wait for Lead's decision." + + +def _run_teammate_tool(name: str, block, handlers: dict) -> str: + gate = plan_gates.get(name, "not_required") + if block.name in {"bash", "write_file"} and gate != "not_required": + if gate != "approved": + return (f"Blocked: plan status is {gate}. Submit or revise the " + "plan and wait for approval before changing the workspace.") + handler = handlers.get(block.name) + return str(handler(**block.input)) if handler else f"Unknown tool: {block.name}" + + +def apply_plan_response(name: str, msg: dict) -> tuple[bool, str]: + """Apply only the Lead response for this teammate's current plan.""" + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + expected_id = plan_request_ids.get(name) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and request_id == expected_id + and state is not None + and state.type == "plan_approval" + and state.sender == name + and state.target == "lead" + and state.status in {"approved", "rejected"} + and metadata.get("approve", False) + == (state.status == "approved") + ) + if not valid: + return False, "[Ignored plan response: request mismatch]" + plan_gates[name] = state.status + active_teammates[name] = "working" + plan_request_ids.pop(name, None) + outcome = state.status + return True, f"[Plan {outcome}] {msg['content']}" + + +def apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]: + """Accept only a pending shutdown request sent by Lead to this teammate.""" + request_id = msg.get("metadata", {}).get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and state is not None + and state.type == "shutdown" + and state.sender == "lead" + and state.target == name + and state.status == "pending" + and active_teammates.get(name) != "stopping" + ) + if not valid: + return False, "[Ignored shutdown request: request mismatch]" + active_teammates[name] = "stopping" + return True, request_id + + +def _teammate_send_message(from_name: str, to: str, content: str) -> str: + with team_lock: + if to != "lead" and to not in active_teammates: + return f"Agent '{to}' is not active" + BUS.send(from_name, to, content) + return f"Sent to {to}" + + +# ── Teammate Thread ── def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - """Spawn a teammate agent in a background thread. - Teaching version: max 10 rounds per teammate. - Real CC: teammates use idle loop (wait for inbox, work, repeat) - until shutdown_request.""" - if name in active_teammates: - return f"Teammate '{name}' already exists" + """Spawn a persistent teammate that alternates between WORK and IDLE.""" + if not is_valid_agent_name(name): + return ("Invalid teammate name: use 1-64 letters, digits, " + "underscores, or dashes") + with team_lock: + if name in active_teammates: + return f"Teammate '{name}' already exists" + active_teammates[name] = "working" + plan_gates[name] = "not_required" system = (f"You are '{name}', a {role}. " - f"Use tools to complete tasks. " - f"Send results via send_message to 'lead'.") + "Use tools to complete assigned work. " + "When asked for a plan, call submit_plan before bash or " + "write_file and wait for approval. End each assignment with a " + "concise result; the runtime delivers it to Lead.") def run(): messages = [{"role": "user", "content": prompt}] @@ -674,77 +893,166 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: "properties": {"to": {"type": "string"}, "content": {"type": "string"}}, "required": ["to", "content"]}}, + {"name": "submit_plan", + "description": "Submit a work plan for Lead approval.", + "input_schema": {"type": "object", + "properties": {"plan": {"type": "string"}}, + "required": ["plan"]}}, ] sub_handlers = { "bash": run_bash, "read_file": run_read, "write_file": run_write, - "send_message": lambda to, content: (BUS.send(name, to, content), - "Sent")[1], + "send_message": lambda to, content: _teammate_send_message( + name, to, content), + "submit_plan": lambda plan: _teammate_submit_plan(name, plan), } - for _ in range(10): - inbox = BUS.read_inbox(name) - if inbox: + def handle_messages(inbox: list[dict]) -> bool: + """Return True when a shutdown request ends the teammate.""" + work_messages = [] + for msg in inbox: + msg_type = msg.get("type", "message") + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + if msg_type == "shutdown_request": + accepted, notice = apply_shutdown_request(name, msg) + if not accepted: + work_messages.append(notice) + continue + request_id = notice + BUS.send(name, "lead", "Shutdown acknowledged.", + "shutdown_response", + {"request_id": request_id, "approve": True}) + return True + if msg_type == "plan_approval_response": + _, notice = apply_plan_response(name, msg) + work_messages.append(notice) + continue + if msg_type == "plan_request": + work_messages.append( + f"[Plan required] {msg['content']}" + ) + continue + work_messages.append( + f"[Message from {msg['from']}] {msg['content']}" + ) + if work_messages: messages.append({"role": "user", - "content": f"{json.dumps(inbox)}"}) + "content": "\n".join(work_messages)}) + return False + + should_stop = False + while not should_stop: + with team_lock: + active_teammates[name] = "working" try: response = client.messages.create( model=MODEL, system=system, messages=messages[-20:], tools=sub_tools, max_tokens=8000) - except Exception: + except Exception as exc: + BUS.send(name, "lead", + f"{type(exc).__name__}: {exc}", "error") break messages.append({"role": "assistant", "content": response.content}) - if response.stop_reason != "tool_use": - break - results = [] - for block in response.content: - if block.type == "tool_use": - handler = sub_handlers.get(block.name) - output = handler(**block.input) if handler else "Unknown" + if response.stop_reason == "tool_use": + results = [] + for block in response.content: + if block.type != "tool_use": + continue + output = _run_teammate_tool(name, block, sub_handlers) results.append({"type": "tool_result", "tool_use_id": block.id, - "content": str(output)}) - messages.append({"role": "user", "content": results}) + "content": output}) + messages.append({"role": "user", "content": results}) + continue - # Send final summary to Lead - summary = "Done." - for msg in reversed(messages): - if msg["role"] == "assistant" and isinstance(msg["content"], list): - for b in msg["content"]: - if getattr(b, "type", None) == "text": - summary = b.text - break - else: - continue - break - BUS.send(name, "lead", summary, "result") - active_teammates.pop(name, None) + summary = _last_assistant_text(response.content) + gate = plan_gates.get(name, "not_required") + if gate != "pending" and summary: + BUS.send(name, "lead", summary, "result") + if gate == "pending": + with team_lock: + active_teammates[name] = "waiting_approval" + else: + with team_lock: + active_teammates[name] = "idle" + BUS.send(name, "lead", "Waiting for more work.", + "idle_notification") + + while True: + inbox = BUS.wait_for_messages(name) + should_stop = handle_messages(inbox) + if should_stop or messages[-1]["role"] == "user": + break + + with team_lock: + active_teammates.pop(name, None) + plan_gates.pop(name, None) + plan_request_ids.pop(name, None) print(f" \033[32m[teammate] {name} finished\033[0m") - active_teammates[name] = True threading.Thread(target=run, daemon=True).start() print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") return f"Teammate '{name}' spawned as {role}" -# ── Team Tool Handlers (s15 new) ── +# ── Lead Team Tools ── def run_spawn_teammate(name: str, role: str, prompt: str) -> str: return spawn_teammate_thread(name, role, prompt) def run_send_message(to: str, content: str) -> str: + if to not in active_teammates: + return f"Teammate '{to}' is not active" BUS.send("lead", to, content) return f"Sent to {to}" -def run_check_inbox() -> str: - msgs = BUS.read_inbox("lead") - if not msgs: - return "(inbox empty)" - lines = [] - for m in msgs: - lines.append(f" [{m['from']}] {m['content'][:200]}") - return "\n".join(lines) +def run_request_shutdown(teammate: str) -> str: + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + request_id = new_request_id() + pending_requests[request_id] = ProtocolState( + request_id=request_id, + type="shutdown", + sender="lead", + target=teammate, + status="pending", + payload="", + ) + BUS.send("lead", teammate, "Finish the current step and shut down.", + "shutdown_request", {"request_id": request_id}) + return f"Shutdown requested from {teammate} ({request_id})" + + +def run_request_plan(teammate: str, task: str) -> str: + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + plan_gates[teammate] = "required" + BUS.send("lead", teammate, task, "plan_request") + return f"Plan requested from {teammate}" + + +def run_review_plan(request_id: str, approve: bool, + feedback: str = "") -> str: + with team_lock: + state = pending_requests.get(request_id) + if not state: + return f"Request {request_id} not found" + if state.type != "plan_approval": + return f"Request {request_id} is not a plan" + if state.status != "pending": + return f"Request {request_id} already {state.status}" + if plan_request_ids.get(state.sender) != request_id: + return f"Request {request_id} is not the current plan" + state.status = "approved" if approve else "rejected" + content = feedback or ("Plan approved." if approve + else "Revise the plan and submit it again.") + BUS.send("lead", state.sender, content, "plan_approval_response", + {"request_id": request_id, "approve": approve}) + return f"Plan {state.status} ({request_id})" # ── Tool Definitions ── @@ -820,7 +1128,10 @@ TOOLS = [ "description": "Spawn a teammate agent in a background thread.", "input_schema": {"type": "object", "properties": { - "name": {"type": "string"}, + "name": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$", + }, "role": {"type": "string"}, "prompt": {"type": "string"}}, "required": ["name", "role", "prompt"]}}, @@ -830,10 +1141,25 @@ TOOLS = [ "properties": {"to": {"type": "string"}, "content": {"type": "string"}}, "required": ["to", "content"]}}, - {"name": "check_inbox", - "description": "Check Lead's inbox for teammate messages.", - "input_schema": {"type": "object", "properties": {}, - "required": []}}, + {"name": "request_shutdown", + "description": "Ask an active teammate to shut down gracefully.", + "input_schema": {"type": "object", + "properties": {"teammate": {"type": "string"}}, + "required": ["teammate"]}}, + {"name": "request_plan", + "description": "Require a teammate to submit a plan before changing files.", + "input_schema": {"type": "object", + "properties": {"teammate": {"type": "string"}, + "task": {"type": "string"}}, + "required": ["teammate", "task"]}}, + {"name": "review_plan", + "description": "Approve or reject a submitted plan by request_id.", + "input_schema": {"type": "object", + "properties": { + "request_id": {"type": "string"}, + "approve": {"type": "boolean"}, + "feedback": {"type": "string"}}, + "required": ["request_id", "approve"]}}, ] @@ -854,9 +1180,8 @@ def update_context(context: dict, messages: list) -> dict: # ── Agent Loop ── -# Teaching code keeps a basic agent loop. S11's full error recovery is omitted. -# Cron queue is consumed when agent_loop is called; real CC auto-wakes via -# queue processor (useQueueProcessor.ts) when items arrive. +# Keep the loop focused on the mechanisms introduced in this chapter. +# Fired cron entries are injected at the start of each model turn. def agent_loop(messages: list, context: dict): system = get_system_prompt(context) @@ -955,16 +1280,16 @@ if __name__ == "__main__": history.append({"role": "user", "content": payload}) else: # "wake": teammate inbox or background results are ready parts = [] - inbox = BUS.read_inbox("lead") + inbox = consume_lead_inbox() if inbox: - parts.append("[Inbox]\n" + "\n".join( - f"From {m['from']}: {m['content'][:200]}" for m in inbox)) + parts.append(format_team_events(inbox)) bg = collect_background_results() parts.extend(bg) if not parts: continue # already drained by an earlier wake (idempotent) history.append({"role": "user", "content": "\n".join(parts)}) - print(f"\n\033[33m[wake: {len(inbox)} inbox + {len(bg)} background " + print(f"\n\033[33m[wake: {len(inbox)} team events + " + f"{len(bg)} background " f"-> new turn]\033[0m") # One turn for whichever source woke us. @@ -976,10 +1301,10 @@ if __name__ == "__main__": elif isinstance(block, dict) and block.get("type") == "text": print(block.get("text", "")) - # Announce once when every teammate has finished and its output drained. + # Announce once after all requested shutdowns have completed. if active_teammates: had_teammates = True elif had_teammates and not BUS.peek("lead") and not has_pending_background(): - print("\033[32m[all teammates done]\033[0m") + print("\033[32m[all teammates shut down]\033[0m") had_teammates = False print() diff --git a/s15_agent_teams/images/agent-teams-overview.en.svg b/s15_agent_teams/images/agent-teams-overview.en.svg index f87995ad..2eca1728 100644 --- a/s15_agent_teams/images/agent-teams-overview.en.svg +++ b/s15_agent_teams/images/agent-teams-overview.en.svg @@ -32,7 +32,7 @@ Teammate - Real CC detail + Protocol gate @@ -58,7 +58,7 @@ TOOL DISPATCH bash · read · write · task(4) · cron(3) - ★ spawn_teammate · send_message · check_inbox + ★ spawn · send · shutdown · plan review @@ -90,7 +90,7 @@ Teammate: alice (Backend) inbox → LLM → bash/read/write/send - Max 10 rounds → summary → BUS.send + WORK → result → IDLE → next message Teammate: bob (Frontend) @@ -100,21 +100,21 @@ Teammate: charlie (QA) Cannot spawn other teammates - spawn → work → summary + spawn → work → result → idle - + - permission_request + plan_request - Permission Bubbling (real CC; omitted in teaching code) - ① Teammate needs approval → MessageBus sends permission_request ② Lead receives → user approval → approve/deny + Plan Approval Gate + ① Teammate submits plan ② Lead approves or rejects ③ bash / write_file stay blocked until approved s10-s14: prompt assembly, error recovery, task graph, background threads, cron scheduling - s15: MessageBus + spawn_teammate_thread + send_message + check_inbox (permission bubbling is a real CC detail) + s15: MessageBus + persistent teammates + event delivery + typed protocols + plan gate diff --git a/s15_agent_teams/images/agent-teams-overview.ja.svg b/s15_agent_teams/images/agent-teams-overview.ja.svg index 47c96654..5fdc98a1 100644 --- a/s15_agent_teams/images/agent-teams-overview.ja.svg +++ b/s15_agent_teams/images/agent-teams-overview.ja.svg @@ -32,7 +32,7 @@ チームメイト - 真实 CC 補足 + プロトコルゲート @@ -58,7 +58,7 @@ TOOL DISPATCH bash · read · write · task(4) · cron(3) - ★ spawn_teammate · send_message · check_inbox + ★ spawn · send · shutdown · plan review @@ -90,7 +90,7 @@ チームメイト: alice (Backend) inbox → LLM → bash/read/write/send - 最大 10 ラウンド → summary → BUS.send + WORK → result → IDLE → next message チームメイト: bob (Frontend) @@ -100,21 +100,21 @@ チームメイト: charlie (QA) 他のチームメイトを spawn 不可 - spawn → work → summary + spawn → work → result → idle - + - permission_request + plan_request - 権限バブリング(真实 CC、教学版は省略) - ① 承認が必要 → MessageBus が permission_request 送信 ② Lead が受信 → ユーザー承認 → approve/deny + プラン承認ゲート + ① プラン提出 ② Lead が承認または却下 ③ approved まで bash / write_file を遮断 s10-s14:プロンプト組み立て、エラーリカバリ、タスクグラフ、バックグラウンドスレッド、cron - s15:MessageBus + spawn_teammate_thread + send_message + check_inbox(権限バブリングは真实 CC 補足) + s15:MessageBus + 永続チームメイト + イベント配信 + 型付きプロトコル + プランゲート diff --git a/s15_agent_teams/images/agent-teams-overview.svg b/s15_agent_teams/images/agent-teams-overview.svg index e708a334..689bfa9a 100644 --- a/s15_agent_teams/images/agent-teams-overview.svg +++ b/s15_agent_teams/images/agent-teams-overview.svg @@ -32,7 +32,7 @@ Teammate - 真实 CC 补充 + 协议闸门 @@ -60,7 +60,7 @@ TOOL DISPATCH bash · read · write · task(4) · cron(3) - ★ spawn_teammate · send_message · check_inbox + ★ spawn · send · shutdown · plan review @@ -99,7 +99,7 @@ Teammate: alice (Backend) inbox → LLM → bash/read/write/send - 最多 10 轮 → summary → BUS.send + WORK → result → IDLE → next message @@ -111,22 +111,21 @@ Teammate: charlie (QA) 不能 spawn 其他 teammate - spawn → work → summary + spawn → work → result → idle - - + - permission_request + plan_request - 权限冒泡(真实 CC,教学版省略) - ① 队友需审批 → MessageBus 发送 permission_request ② Lead 收到 → 用户审批 → 回复 approve/deny + 计划审批闸门 + ① 队友提交计划 ② Lead 批准或拒绝 ③ approved 前 bash / write_file 被拦截 s10-s14: prompt 组装、错误恢复、任务图、后台线程、cron 调度 - s15: MessageBus + spawn_teammate_thread + send_message + check_inbox(权限冒泡见真实 CC 补充) + s15: MessageBus + 持久队友 + 自动事件投递 + 类型化协议 + 计划闸门 diff --git a/web/public/course-assets/s16_team_protocols/team-protocols-overview.en.svg b/s15_agent_teams/images/team-protocols-overview.en.svg similarity index 97% rename from web/public/course-assets/s16_team_protocols/team-protocols-overview.en.svg rename to s15_agent_teams/images/team-protocols-overview.en.svg index 36e335ba..ca48820d 100644 --- a/web/public/course-assets/s16_team_protocols/team-protocols-overview.en.svg +++ b/s15_agent_teams/images/team-protocols-overview.en.svg @@ -24,9 +24,9 @@ Team Protocols — Request-Response + request_id Correlation + State Machine - s15 Preserved + Team runtime - s16 New + Protocols @@ -135,7 +135,7 @@ - s15: MessageBus + spawn_teammate + inbox + Runtime: MessageBus + persistent teammates + automatic delivery - s16: request_id protocol + dispatch + pending_requests + state machine + Protocol: request_id + dispatch + pending_requests + plan gate diff --git a/web/public/course-assets/s16_team_protocols/team-protocols-overview.ja.svg b/s15_agent_teams/images/team-protocols-overview.ja.svg similarity index 97% rename from web/public/course-assets/s16_team_protocols/team-protocols-overview.ja.svg rename to s15_agent_teams/images/team-protocols-overview.ja.svg index f4a34f4e..e932d05a 100644 --- a/web/public/course-assets/s16_team_protocols/team-protocols-overview.ja.svg +++ b/s15_agent_teams/images/team-protocols-overview.ja.svg @@ -24,9 +24,9 @@ Team Protocols — リクエスト・レスポンス + request_id 紐付け + 状態機械 - s15 維持 + チームランタイム - s16 新規 + 協調プロトコル @@ -135,7 +135,7 @@ - s15: MessageBus + spawn_teammate + inbox + Runtime: MessageBus + 永続チームメイト + 自動イベント配信 - s16: request_id プロトコル + dispatch + pending_requests + 状態機械 + Protocol: request_id + dispatch + pending_requests + プランゲート diff --git a/s16_team_protocols/images/team-protocols-overview.svg b/s15_agent_teams/images/team-protocols-overview.svg similarity index 97% rename from s16_team_protocols/images/team-protocols-overview.svg rename to s15_agent_teams/images/team-protocols-overview.svg index dcc53a0d..3cda2396 100644 --- a/s16_team_protocols/images/team-protocols-overview.svg +++ b/s15_agent_teams/images/team-protocols-overview.svg @@ -24,9 +24,9 @@ Team Protocols — 请求-响应协议 + request_id 关联 + 状态机 - s15 保留 + 团队运行时 - s16 新增 + 协作协议 @@ -135,7 +135,7 @@ - s15: MessageBus + spawn_teammate + inbox + 运行时: MessageBus + 持久队友 + 自动事件投递 - s16: request_id 协议 + dispatch + pending_requests + 状态机 + 协议: request_id + dispatch + pending_requests + 计划闸门 diff --git a/s15_agent_teams/images/team-topology.en.svg b/s15_agent_teams/images/team-topology.en.svg index 7540db7c..62377e4b 100644 --- a/s15_agent_teams/images/team-topology.en.svg +++ b/s15_agent_teams/images/team-topology.en.svg @@ -23,7 +23,7 @@ Lead Agent Main loop + spawn + inbox handling - check_inbox receives teammate messages + runtime delivers team events automatically diff --git a/s15_agent_teams/images/team-topology.ja.svg b/s15_agent_teams/images/team-topology.ja.svg index 77c8709e..1f132290 100644 --- a/s15_agent_teams/images/team-topology.ja.svg +++ b/s15_agent_teams/images/team-topology.ja.svg @@ -23,7 +23,7 @@ Lead Agent メインループ + spawn + inbox 処理 - check_inbox でチームメイトのメッセージ受信 + ランタイムがチームイベントを自動配信 diff --git a/s15_agent_teams/images/team-topology.svg b/s15_agent_teams/images/team-topology.svg index 9272e1b6..79937068 100644 --- a/s15_agent_teams/images/team-topology.svg +++ b/s15_agent_teams/images/team-topology.svg @@ -26,7 +26,7 @@ Lead Agent 主循环 + spawn + inbox 处理 - check_inbox 接收队友消息 + 运行时自动投递团队事件 diff --git a/s16_autonomous_agents/README.ja.md b/s16_autonomous_agents/README.ja.md new file mode 100644 index 00000000..0fc5fee7 --- /dev/null +++ b/s16_autonomous_agents/README.ja.md @@ -0,0 +1,204 @@ +# s16: Autonomous Agents — ボードを見て、自分で Claim する + +[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) + +s01 → ... → s14 → s15 → `s16` → [s17](../s17_worktree_isolation/) → s18 → s19 → s20 → s21 + +> *「IDLE はメッセージを待つだけでなく、開始可能な仕事を探す時間でもある。」* — 共有タスクボード、自動発見、原子的な Claim。 +> +> **Harness レイヤー**:自律 — Lead は目標を管理し、チームメイトは共有状態から次の仕事を見つける。 + +--- + +## 問題 + +s15 のチームメイトは作業後に IDLE へ入り、Lead から次の依頼を待つ。タスクボードに 10 件の pending task があっても、Lead はチームメイトを選び、メッセージを送り、結果を待つ操作を 10 回繰り返す必要がある。 + +仕事がすでに分解され、依存関係もタスクボードに記録されているなら、次の ready task の割り当てに毎回モデル判断は要らない。IDLE のチームメイト自身が共有状態を読み、前提条件を満たした仕事を Claim できる。 + +--- + +## 解決策 + +![Autonomous Agents Overview](images/autonomous-agents-overview.ja.svg) + +s16 は s15 のチームライフサイクルを変えず、IDLE の動作だけを拡張する: + +```text +s15: WORK → result → IDLE → メッセージを待つ +s16: WORK → result → IDLE → メッセージを待つ + └→ ボード走査 → Claim → WORK +``` + +追加する関数は 2 つ: + +- `scan_unclaimed_tasks()`:現在開始できるタスクを探す。 +- `claim_next_task(name)`:候補の 1 件を原子的に Claim する。 + +チームメイトのツールにも `list_tasks`、`claim_task`、`complete_task` を加え、同じループ内で作業を完了できるようにする。 + +--- + +## 仕組み + +### 1. 発見と所有権を分離する + +走査は状態を変更せず、読み取りだけを行う: + +```python +def scan_unclaimed_tasks() -> list[Task]: + return [ + task for task in list_tasks() + if ( + task.status == "pending" + and task.owner is None + and can_start(task.id) + ) + ] +``` + +候補は `pending` で、owner がなく、すべての `blockedBy` が完了していなければならない。 + +ただし候補一覧は一時点のスナップショットにすぎない。直後に別のチームメイトが同じタスクを Claim する可能性があるため、「発見した」と「所有した」を同じ意味にしてはいけない。 + +### 2. Claim はロック内で読み取り、確認、書き込みを行う + +`claim_task()` は状態遷移全体を `task_lock` で保護する: + +```python +def claim_task(task_id: str, owner: str) -> str: + with task_lock: + task = load_task(task_id) + if task.status != "pending" or task.owner: + return "Task is no longer available" + if not can_start(task_id): + return "Task is blocked" + + task.owner = owner + task.status = "in_progress" + save_task(task) + return f"Claimed {task.id}" +``` + +`claim_next_task()` は成功する候補が見つかるまで順に試す: + +```python +def claim_next_task(name: str) -> Task | None: + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None +``` + +複数のチームメイトが同時にボードを観察しても、最終的な owner は Claim 関数によって 1 人に決まる。 + +### 3. メッセージを優先し、その後にタスクを探す + +IDLE に入ったチームメイトは、まず短時間だけ受信イベントを待つ: + +```python +while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + handle_messages(inbox) + break + + task = claim_next_task(name) + if task: + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}" + ), + }) + break +``` + +この順序にする理由は明確だ: + +- shutdown、計画承認、Lead からの直接メッセージにはすぐ応答する。 +- メッセージがない IDLE 時間だけを、共有タスクの探索に使う。 + +メッセージも ready task もなければ IDLE を続ける。候補が空なのは、依存タスクがまだ完了していないだけかもしれない。 + +### 4. Claim 後は同じ WORK ループを再利用する + +Claim に成功すると、ランタイムはタスク ID、件名、説明をチームメイトの messages へ追加する。ファイルツール、Shell、計画ゲート、結果通知、終了プロトコルはすべて s15 の仕組みをそのまま使う。 + +```text +ready task が現れる + → IDLE のチームメイトが発見 + → claim_task が owner と in_progress を記録 + → タスクが messages に入る + → WORK + → complete_task + → result + idle_notification + → 再び走査 +``` + +自律のために別の Agent Loop を作る必要はない。既存ループへ共有状態から入る入口を追加すればよい。 + +--- + +## この設計を選ぶ理由 + +**Lead が毎回割り当てないのはなぜか。** + +`status`、`owner`、`blockedBy` が実行可能性をすでに表している。同じ状態を Lead に毎回解釈させても、調整ターンが増えるだけである。 + +**走査時に owner を設定しないのはなぜか。** + +走査は並行実行され得る。所有権変更を 1 つのロック付き関数に集めれば、すべての呼び出し元が同じ規則に従う。 + +**ready task がない時に終了しないのはなぜか。** + +依存タスクが完了すれば、後続タスクが ready になる。IDLE を維持すれば、その瞬間に次の仕事を引き継げる。 + +--- + +## s15 からの変更 + +| コンポーネント | s15 | s16 | +|---|---|---| +| IDLE | チームメッセージを待つ | メッセージ待機後にボードを走査 | +| 割り当て | Lead が明示的に送る | チームメイトが自動 Claim 可能 | +| 所有権 | 呼び出し元が Claim | `task_lock` で Claim を原子的にする | +| チームメイトツール | ファイル、Shell、メッセージ、計画 | list / claim / complete task を追加 | +| 結果と終了 | `result`、`idle_notification`、shutdown protocol | 変更なし | + +--- + +## 試してみる + +```sh +cd learn-claude-code +python s16_autonomous_agents/code.py +``` + +通常の要求を入力する: + +```text +バックエンド改修を共有タスクボードへ分解し、依存関係が許す範囲で +設定、認証、テストを並行実行してください。既存インターフェースを +維持し、最後に結果をまとめてください。 +``` + +Lead がチーム案を示したら、次のように返す: + +```text +始めてください +``` + +`.tasks/` のタスクが `pending`、`in_progress`、`completed` と変化する様子を確認する。2 人の IDLE チームメイトは別々のタスクを Claim し、`blockedBy` のあるタスクは前提完了後にだけ候補になるはずだ。 + +--- + +## 次へ + +チームメイトは仕事を自分で見つけられるようになったが、まだ同じディレクトリでファイルを変更する。次のセッションではタスク所有権を分離された作業ディレクトリへ結び付ける。 + +次へ:[s17 Worktree Isolation](../s17_worktree_isolation/)。 + + diff --git a/s16_autonomous_agents/README.md b/s16_autonomous_agents/README.md new file mode 100644 index 00000000..2429dc5f --- /dev/null +++ b/s16_autonomous_agents/README.md @@ -0,0 +1,204 @@ +# s16: Autonomous Agents — Check the Board, Claim the Work + +[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) + +s01 → ... → s14 → s15 → `s16` → [s17](../s17_worktree_isolation/) → s18 → s19 → s20 → s21 + +> *"Idle does not only mean waiting for a message; it can also mean looking for ready work."* — Shared task board, automatic discovery, and atomic claims. +> +> **Harness layer**: Autonomy — Lead owns the goal while teammates discover the next step from shared state. + +--- + +## The Problem + +In s15, a teammate enters IDLE after finishing an assignment and waits for Lead to send more work. If the task board already contains ten pending tasks, Lead still has to choose a teammate, send a message, and wait for a result ten times. + +Once work has been decomposed and dependencies are recorded on the task board, assigning the next ready task does not always need another model decision. An idle teammate can read shared state and claim work whose prerequisites are complete. + +--- + +## The Solution + +![Autonomous Agents Overview](images/autonomous-agents-overview.en.svg) + +s16 keeps the s15 team lifecycle and extends only the IDLE state: + +```text +s15: WORK → result → IDLE → wait for a message +s16: WORK → result → IDLE → wait for a message + └→ scan board → claim → WORK +``` + +It adds two functions: + +- `scan_unclaimed_tasks()` finds tasks that can start now. +- `claim_next_task(name)` attempts to claim one candidate atomically. + +Teammates also receive `list_tasks`, `claim_task`, and `complete_task`, allowing the claimed work to close inside the same loop. + +--- + +## How It Works + +### 1. Discovery and ownership are separate steps + +Scanning reads state without changing it: + +```python +def scan_unclaimed_tasks() -> list[Task]: + return [ + task for task in list_tasks() + if ( + task.status == "pending" + and task.owner is None + and can_start(task.id) + ) + ] +``` + +A candidate must be `pending`, have no owner, and have every `blockedBy` dependency completed. + +The resulting list is only a snapshot. Another teammate may claim the same task immediately afterward, so "discovered" must never mean "owned." + +### 2. Claim performs read, validation, and write under one lock + +`claim_task()` protects the full state transition with `task_lock`: + +```python +def claim_task(task_id: str, owner: str) -> str: + with task_lock: + task = load_task(task_id) + if task.status != "pending" or task.owner: + return "Task is no longer available" + if not can_start(task_id): + return "Task is blocked" + + task.owner = owner + task.status = "in_progress" + save_task(task) + return f"Claimed {task.id}" +``` + +`claim_next_task()` tries candidates until one claim succeeds: + +```python +def claim_next_task(name: str) -> Task | None: + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None +``` + +Many teammates may observe the board at once, but the claim function gives each task one final owner. + +### 3. Messages take priority over board scans + +In IDLE, a teammate first waits briefly for mailbox events: + +```python +while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + handle_messages(inbox) + break + + task = claim_next_task(name) + if task: + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}" + ), + }) + break +``` + +This ordering matters: + +- Shutdown, plan approval, and direct Lead messages should be handled promptly. +- Only otherwise idle time is used to look for shared work. + +If there is neither a message nor a ready task, the teammate stays idle. An empty scan is not a reason to exit because a blocked task may become ready later. + +### 4. A claimed task reuses the same WORK loop + +After a successful claim, the runtime injects the task ID, subject, and description into the teammate's messages. The existing file tools, Shell, plan gate, result reporting, and shutdown protocol all remain unchanged. + +```text +ready task appears + → idle teammate discovers it + → claim_task writes owner and in_progress + → task enters teammate messages + → WORK + → complete_task + → result + idle_notification + → scan again +``` + +Autonomy does not require another agent loop. It adds a shared-state entry point to the loop that already exists. + +--- + +## Why This Design + +**Why not ask Lead to assign every task?** + +The task's `status`, `owner`, and `blockedBy` already encode whether it can run. Reinterpreting that same state through Lead adds coordination turns without adding judgment. + +**Why not set the owner during scanning?** + +Scans may overlap. Keeping ownership changes in one locked function gives every caller the same rule. + +**Why keep teammates alive when no task is ready?** + +An empty candidate list may only mean that prerequisites are still running. IDLE teammates can pick up downstream work as soon as it becomes ready. + +--- + +## What Changed from s15 + +| Component | s15 | s16 | +|---|---|---| +| IDLE behavior | Wait for team messages | Wait for messages, then scan the board | +| Assignment | Lead sends work explicitly | Teammates may auto-claim | +| Ownership | Caller initiates claim | `task_lock` makes claim atomic | +| Teammate tools | Files, Shell, messages, plans | Adds list / claim / complete task | +| Result and shutdown | `result`, `idle_notification`, shutdown protocol | Unchanged | + +--- + +## Try It + +```sh +cd learn-claude-code +python s16_autonomous_agents/code.py +``` + +Enter an ordinary request: + +```text +Put the backend refactor on a shared task board. Complete configuration, +authentication, and tests in parallel where dependencies allow, preserve +existing interfaces, and summarize the result. +``` + +After Lead proposes a team, reply: + +```text +Go ahead. +``` + +Watch tasks move from `pending` to `in_progress` and `completed` under `.tasks/`. Two idle teammates should claim different tasks, and a task with `blockedBy` should become a candidate only after its prerequisites finish. + +--- + +## Next + +Teammates can now discover work, but they still edit files in the same directory. The next lesson binds task ownership to isolated working directories. + +Next: [s17 Worktree Isolation](../s17_worktree_isolation/). + + diff --git a/s16_autonomous_agents/README.zh.md b/s16_autonomous_agents/README.zh.md new file mode 100644 index 00000000..e29bfdc1 --- /dev/null +++ b/s16_autonomous_agents/README.zh.md @@ -0,0 +1,207 @@ +# s16: Autonomous Agents — 自己看板,自己认领 + +[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) + +s01 → ... → s14 → s15 → `s16` → [s17](../s17_worktree_isolation/) → s18 → s19 → s20 → s21 + +> *"空闲时不只等消息,也主动寻找可以开始的工作。"* — 共享任务板、自动发现与原子认领。 +> +> **Harness 层**:自治 — Lead 管目标,队友从任务状态中发现下一步。 + +--- + +## 问题 + +s15 的队友会在完成一项工作后进入 IDLE,等待 Lead 继续派发。如果任务板上已经有十个待办任务,Lead 仍然要逐个选择队友、发送消息,再等待结果。 + +当任务已经被拆分,并且依赖关系也写进了任务板,谁来执行下一项工作不一定需要 Lead 再做一次模型决策。空闲队友可以直接读取共享状态,找到已经满足条件的任务并认领它。 + +--- + +## 解决方案 + +![Autonomous Agents Overview](images/autonomous-agents-overview.svg) + +s16 不改变 s15 的团队生命周期,只扩展 IDLE 状态: + +```text +s15: WORK → result → IDLE → 等待消息 +s16: WORK → result → IDLE → 等待消息 + └→ 扫描任务板 → 认领 → WORK +``` + +新增两个函数: + +- `scan_unclaimed_tasks()`:找出当前可以开始的任务。 +- `claim_next_task(name)`:尝试原子认领其中一个任务。 + +队友工具集同时增加 `list_tasks`、`claim_task` 和 `complete_task`,让认领后的工作能在同一个循环中闭合。 + +--- + +## 工作原理 + +### 1. 发现任务和认领任务是两步 + +扫描只读取状态,不修改任务: + +```python +def scan_unclaimed_tasks() -> list[Task]: + return [ + task for task in list_tasks() + if ( + task.status == "pending" + and task.owner is None + and can_start(task.id) + ) + ] +``` + +一个任务必须同时满足三个条件: + +- 状态是 `pending`; +- 还没有 `owner`; +- `blockedBy` 中的任务都已经完成。 + +扫描得到的只是候选列表。另一个队友可能在下一瞬间认领同一任务,因此不能把“扫描到”当成“已经拥有”。 + +### 2. claim 在锁内完成读、检查和写入 + +`claim_task()` 使用同一把 `task_lock` 包住完整的读改写过程: + +```python +def claim_task(task_id: str, owner: str) -> str: + with task_lock: + task = load_task(task_id) + if task.status != "pending" or task.owner: + return "Task is no longer available" + if not can_start(task_id): + return "Task is blocked" + + task.owner = owner + task.status = "in_progress" + save_task(task) + return f"Claimed {task.id}" +``` + +`claim_next_task()` 依次尝试候选任务。某次认领失败时,它会继续尝试下一个,而不是把失败误当成成功: + +```python +def claim_next_task(name: str) -> Task | None: + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None +``` + +扫描负责发现,claim 负责所有权。把两者分开后,多个队友可以同时观察任务板,但每个任务只能有一个最终 owner。 + +### 3. 消息优先,任务扫描其次 + +队友进入 IDLE 后,先等待一小段时间的收件箱事件: + +```python +while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + handle_messages(inbox) + break + + task = claim_next_task(name) + if task: + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}" + ), + }) + break +``` + +这样安排有两个原因: + +- 关机、计划审批和 Lead 的直接消息应该尽快响应; +- 没有消息时,空闲时间才用于寻找共享任务。 + +如果既没有消息也没有可认领任务,队友继续保持 IDLE,不会因为一次扫描为空就退出。 + +### 4. 自动认领后复用同一个 WORK 循环 + +认领成功后,运行时把任务 ID、标题和描述写入队友 messages。对模型来说,它只是收到了一项新工作;文件、Shell、计划闸门、结果上报都继续使用 s15 的机制。 + +```text +任务板出现 ready task + → 空闲队友扫描到候选 + → claim_task 写入 owner 和 in_progress + → 任务进入队友 messages + → WORK + → complete_task + → result + idle_notification + → 再次扫描 +``` + +自治不是再造一个 Agent Loop,而是给既有循环增加一个由共享状态触发的入口。 + +--- + +## 为什么这样设计 + +**为什么不是 Lead 每次分配?** + +任务依赖已经编码在 `status`、`owner` 和 `blockedBy` 中。让 Lead 反复解释同一状态,只会增加协调轮次。 + +**为什么不是扫描时直接改 owner?** + +扫描可能并发发生。把认领集中到带锁的函数中,所有调用方共享同一个所有权规则。 + +**为什么不在没有任务时关闭队友?** + +暂时没有 ready task 可能只是因为依赖尚未完成。保持 IDLE 后,前置任务完成时队友可以自动接上后续工作。 + +--- + +## 相对 s15 的变化 + +| 组件 | s15 | s16 | +|---|---|---| +| IDLE 行为 | 等待团队消息 | 先等消息,再扫描任务板 | +| 任务分配 | Lead 明确派发 | 队友可自动认领 | +| 任务所有权 | 调用方发起 claim | `task_lock` 保证认领原子性 | +| 队友工具 | 文件、Shell、消息、计划 | 增加 list / claim / complete task | +| 结果与关机 | `result`、`idle_notification`、shutdown 协议 | 保持不变 | + +--- + +## 试一下 + +```sh +cd learn-claude-code +python s16_autonomous_agents/code.py +``` + +输入一个自然需求: + +```text +请把后端改造拆到共享任务板,按依赖关系并行完成配置、认证和测试, +保持现有接口兼容,并在最后汇总结果。 +``` + +Lead 提出团队方案后回复: + +```text +开始吧 +``` + +观察 `.tasks/` 中任务如何从 `pending` 进入 `in_progress` 和 `completed`,以及两个空闲队友是否会认领不同任务。带 `blockedBy` 的任务应该只在前置任务完成后出现为候选。 + +--- + +## 接下来 + +队友已经能自己找到任务,但仍然在同一个工作目录里修改文件。下一章把任务所有权和工作目录绑定起来,让并行工作彼此隔离。 + +下一章:[s17 Worktree Isolation](../s17_worktree_isolation/)。 + + diff --git a/s16_autonomous_agents/code.py b/s16_autonomous_agents/code.py new file mode 100644 index 00000000..71984a62 --- /dev/null +++ b/s16_autonomous_agents/code.py @@ -0,0 +1,1371 @@ +#!/usr/bin/env python3 +""" +s16: Autonomous Agents — idle teammates discover and claim ready tasks. + +Run: python s16_autonomous_agents/code.py +Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY + +Changes from s15: + - scan_unclaimed_tasks finds pending, unowned, unblocked tasks + - Idle teammates periodically scan the shared task board + - claim_next_task atomically assigns one ready task to a teammate + - Teammates can list, claim, and complete tasks + +ASCII flow: + WORK → result → IDLE → scan board → claim ready task → WORK + └→ inbox or shutdown event +""" + +import os, subprocess, json, time, random, threading, queue, re +from pathlib import Path +from datetime import datetime +from dataclasses import dataclass, asdict, field + +try: + import readline + readline.parse_and_bind('set bind-tty-special-chars off') +except ImportError: + pass + +from anthropic import Anthropic +from dotenv import load_dotenv + +load_dotenv(override=True) +if os.getenv("ANTHROPIC_BASE_URL"): + os.environ.pop("ANTHROPIC_AUTH_TOKEN", None) + +WORKDIR = Path.cwd() +MEMORY_DIR = WORKDIR / ".memory" +MEMORY_INDEX = MEMORY_DIR / "MEMORY.md" +client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) +MODEL = os.environ["MODEL_ID"] + +# ── Task System (from s12, synced) ── + +TASKS_DIR = WORKDIR / ".tasks" +TASKS_DIR.mkdir(exist_ok=True) +task_lock = threading.RLock() + + +@dataclass +class Task: + id: str + subject: str + description: str + status: str # pending | in_progress | completed + owner: str | None + blockedBy: list[str] + + +def _task_path(task_id: str) -> Path: + return TASKS_DIR / f"{task_id}.json" + + +def create_task(subject: str, description: str = "", + blockedBy: list[str] | None = None) -> Task: + task = Task( + id=f"task_{int(time.time())}_{random.randint(0, 9999):04d}", + subject=subject, description=description, + status="pending", owner=None, + blockedBy=blockedBy or [], + ) + save_task(task) + return task + + +def save_task(task: Task): + _task_path(task.id).write_text(json.dumps(asdict(task), indent=2)) + + +def load_task(task_id: str) -> Task: + return Task(**json.loads(_task_path(task_id).read_text())) + + +def list_tasks() -> list[Task]: + return [Task(**json.loads(p.read_text())) + for p in sorted(TASKS_DIR.glob("task_*.json"))] + + +def get_task(task_id: str) -> str: + """Return full task details as JSON.""" + task = load_task(task_id) + return json.dumps(asdict(task), indent=2) + + +def can_start(task_id: str) -> bool: + """Check if all blockedBy dependencies are completed. + Missing dependencies are treated as blocked.""" + task = load_task(task_id) + for dep_id in task.blockedBy: + if not _task_path(dep_id).exists(): + return False + if load_task(dep_id).status != "completed": + return False + return True + + +def claim_task(task_id: str, owner: str = "agent") -> str: + with task_lock: + task = load_task(task_id) + if task.status != "pending": + return f"Task {task_id} is {task.status}, cannot claim" + if task.owner: + return f"Task {task_id} is already owned by {task.owner}" + if not can_start(task_id): + deps = [d for d in task.blockedBy + if (not _task_path(d).exists() + or load_task(d).status != "completed")] + return f"Blocked by: {deps}" + task.owner = owner + task.status = "in_progress" + save_task(task) + print(f" \033[36m[claim] {task.subject} → in_progress (owner: {owner})\033[0m") + return f"Claimed {task.id} ({task.subject})" + + +def complete_task(task_id: str) -> str: + task = load_task(task_id) + if task.status != "in_progress": + return f"Task {task_id} is {task.status}, cannot complete" + task.status = "completed" + save_task(task) + unblocked = [t.subject for t in list_tasks() + if t.status == "pending" and t.blockedBy and can_start(t.id)] + print(f" \033[32m[complete] {task.subject} ✓\033[0m") + msg = f"Completed {task.id} ({task.subject})" + if unblocked: + msg += f"\nUnblocked: {', '.join(unblocked)}" + print(f" \033[33m[unblocked] {', '.join(unblocked)}\033[0m") + return msg + + +# ── Prompt Assembly (from s10, synced) ── + +PROMPT_SECTIONS = { + "identity": "You are a coding agent. Act, don't explain.", + "tools": "Available tools: bash, read_file, write_file, " + "get_task, create_task, list_tasks, claim_task, complete_task, " + "schedule_cron, list_crons, cancel_cron, " + "spawn_teammate, send_message, request_shutdown, " + "request_plan, review_plan.", + "teams": ( + "When parallel work would help, first propose a small team with clear " + "responsibilities and wait for the user's confirmation. Do not call " + "spawn_teammate before the user confirms. After confirmation, delegate " + "independent work, react to team events delivered by the runtime, and " + "shut teammates down when coordination is complete." + ), + "workspace": f"Working directory: {WORKDIR}", + "memory": "Relevant memories are injected below when available.", +} + + +def assemble_system_prompt(context: dict) -> str: + sections = [PROMPT_SECTIONS["identity"], + PROMPT_SECTIONS["tools"], + PROMPT_SECTIONS["teams"], + PROMPT_SECTIONS["workspace"]] + memories = context.get("memories", "") + if memories: + sections.append(f"Relevant memories:\n{memories}") + return "\n\n".join(sections) + + +_last_context_key, _last_prompt = None, None + + +def get_system_prompt(context: dict) -> str: + global _last_context_key, _last_prompt + key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str) + if key == _last_context_key and _last_prompt: + return _last_prompt + _last_context_key = key + _last_prompt = assemble_system_prompt(context) + return _last_prompt + + +# ── Tools ── + +def safe_path(p: str) -> Path: + path = (WORKDIR / p).resolve() + if not path.is_relative_to(WORKDIR): + raise ValueError(f"Path escapes workspace: {p}") + return path + + +def run_bash(command: str, run_in_background: bool = False) -> str: + # run_in_background is handled by agent_loop dispatch, not here + try: + r = subprocess.run(command, shell=True, cwd=WORKDIR, + capture_output=True, text=True, timeout=120) + out = (r.stdout + r.stderr).strip() + return out[:50000] if out else "(no output)" + except subprocess.TimeoutExpired: + return "Error: Timeout (120s)" + + +def run_read(path: str, limit: int | None = None) -> str: + try: + lines = safe_path(path).read_text().splitlines() + if limit and limit < len(lines): + lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"] + return "\n".join(lines) + except Exception as e: + return f"Error: {e}" + + +def run_write(path: str, content: str) -> str: + try: + fp = safe_path(path) + fp.parent.mkdir(parents=True, exist_ok=True) + fp.write_text(content) + return f"Wrote {len(content)} bytes to {path}" + except Exception as e: + return f"Error: {e}" + + +# Task tools + +def run_create_task(subject: str, description: str = "", + blockedBy: list[str] | None = None) -> str: + task = create_task(subject, description, blockedBy) + deps = f" (blockedBy: {', '.join(blockedBy)})" if blockedBy else "" + print(f" \033[34m[create] {task.subject}{deps}\033[0m") + return f"Created {task.id}: {task.subject}{deps}" + + +def run_list_tasks() -> str: + tasks = list_tasks() + if not tasks: + return "No tasks. Use create_task to add some." + lines = [] + for t in tasks: + icon = {"pending": "○", "in_progress": "●", + "completed": "✓"}.get(t.status, "?") + deps = f" (blockedBy: {', '.join(t.blockedBy)})" if t.blockedBy else "" + owner = f" [{t.owner}]" if t.owner else "" + lines.append(f" {icon} {t.id}: {t.subject} " + f"[{t.status}]{owner}{deps}") + return "\n".join(lines) + + +def run_get_task(task_id: str) -> str: + try: + return get_task(task_id) + except FileNotFoundError: + return f"Error: Task {task_id} not found" + + +def run_claim_task(task_id: str) -> str: + return claim_task(task_id, owner="agent") + + +def run_complete_task(task_id: str) -> str: + return complete_task(task_id) + + +# ── Background Tasks (from s13, synced) ── + +_bg_counter = 0 +background_tasks: dict[str, dict] = {} +background_results: dict[str, str] = {} +background_lock = threading.Lock() + + +def is_slow_operation(tool_name: str, tool_input: dict) -> bool: + """Fallback heuristic: commands likely to take > 30s.""" + if tool_name != "bash": + return False + cmd = tool_input.get("command", "").lower() + slow_keywords = ["install", "build", "test", "deploy", "compile", + "docker build", "pip install", "npm install", + "cargo build", "pytest", "make"] + return any(kw in cmd for kw in slow_keywords) + + +def should_run_background(tool_name: str, tool_input: dict) -> bool: + """Model explicit request takes priority; fallback to heuristic.""" + if tool_input.get("run_in_background"): + return True + return is_slow_operation(tool_name, tool_input) + + +def execute_tool(block) -> str: + """Execute a tool call block, return output.""" + handler = { + "bash": run_bash, "read_file": run_read, "write_file": run_write, + "create_task": run_create_task, "list_tasks": run_list_tasks, + "get_task": run_get_task, "claim_task": run_claim_task, + "complete_task": run_complete_task, + "schedule_cron": run_schedule_cron, "list_crons": run_list_crons, + "cancel_cron": run_cancel_cron, + "spawn_teammate": run_spawn_teammate, + "send_message": run_send_message, + "request_shutdown": run_request_shutdown, + "request_plan": run_request_plan, + "review_plan": run_review_plan, + }.get(block.name) + if handler: + return handler(**block.input) + return f"Unknown tool: {block.name}" + + +def start_background_task(block) -> str: + """Run tool in a daemon thread. Returns background task ID.""" + global _bg_counter + _bg_counter += 1 + bg_id = f"bg_{_bg_counter:04d}" + cmd = block.input.get("command", block.name) + + def worker(): + result = execute_tool(block) + with background_lock: + background_tasks[bg_id]["status"] = "completed" + background_results[bg_id] = result + + with background_lock: + background_tasks[bg_id] = { + "tool_use_id": block.id, + "command": cmd, + "status": "running", + } + threading.Thread(target=worker, daemon=True).start() + print(f" \033[33m[background] dispatched {bg_id}: {cmd[:40]}\033[0m") + return bg_id + + +def collect_background_results() -> list[str]: + """Collect completed background results as task_notification messages.""" + with background_lock: + ready_ids = [bid for bid, task in background_tasks.items() + if task["status"] == "completed"] + notifications = [] + for bg_id in ready_ids: + with background_lock: + task = background_tasks.pop(bg_id) + output = background_results.pop(bg_id, "") + summary = output[:200] if len(output) > 200 else output + notifications.append( + f"\n" + f" {bg_id}\n" + f" completed\n" + f" {task['command']}\n" + f" {summary}\n" + f"") + print(f" \033[32m[background done] {bg_id}: " + f"{task['command'][:40]} ({len(output)} chars)\033[0m") + return notifications + + +def has_pending_background() -> bool: + """Non-destructive: True if any background task has completed and is + waiting to be collected. The inbox poller uses this in its wake condition.""" + with background_lock: + return any(t["status"] == "completed" for t in background_tasks.values()) + + +# ── Cron Scheduler (from s14, synced) ── + +DURABLE_PATH = WORKDIR / ".scheduled_tasks.json" + + +@dataclass +class CronJob: + id: str + cron: str # "0 9 * * *" + prompt: str # message to inject when fired + recurring: bool # True = recurring, False = one-shot + durable: bool # True = persist to disk + + +scheduled_jobs: dict[str, CronJob] = {} +cron_queue: list[CronJob] = [] +cron_lock = threading.Lock() +_last_fired: dict[str, str] = {} # job_id → "YYYY-MM-DD HH:MM" + + +def _cron_field_matches(field: str, value: int) -> bool: + """Match a single cron field against a value.""" + if field == "*": + return True + if field.startswith("*/"): + step = int(field[2:]) + return step > 0 and value % step == 0 + if "," in field: + return any(_cron_field_matches(f.strip(), value) + for f in field.split(",")) + if "-" in field: + lo, hi = field.split("-", 1) + return int(lo) <= value <= int(hi) + return value == int(field) + + +def cron_matches(cron_expr: str, dt: datetime) -> bool: + """Check if a 5-field cron expression matches the given datetime. + Standard cron semantics: DOM and DOW use OR when both are constrained.""" + fields = cron_expr.strip().split() + if len(fields) != 5: + return False + minute, hour, dom, month, dow = fields + dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0 + + m = _cron_field_matches(minute, dt.minute) + h = _cron_field_matches(hour, dt.hour) + dom_ok = _cron_field_matches(dom, dt.day) + month_ok = _cron_field_matches(month, dt.month) + dow_ok = _cron_field_matches(dow, dow_val) + + # Minute, hour, month must all match + if not (m and h and month_ok): + return False + # DOM and DOW: if both constrained, either matching is enough (OR) + dom_unconstrained = dom == "*" + dow_unconstrained = dow == "*" + if dom_unconstrained and dow_unconstrained: + return True + if dom_unconstrained: + return dow_ok + if dow_unconstrained: + return dom_ok + return dom_ok or dow_ok + + +def _validate_cron_field(field: str, lo: int, hi: int) -> str | None: + """Validate a single cron field value is within [lo, hi].""" + if field == "*": + return None + if field.startswith("*/"): + step_str = field[2:] + if not step_str.isdigit(): + return f"Invalid step: {field}" + step = int(step_str) + if step <= 0: + return f"Step must be > 0: {field}" + return None + if "," in field: + for part in field.split(","): + err = _validate_cron_field(part.strip(), lo, hi) + if err: return err + return None + if "-" in field: + parts = field.split("-", 1) + if not parts[0].isdigit() or not parts[1].isdigit(): + return f"Invalid range: {field}" + a, b = int(parts[0]), int(parts[1]) + if a < lo or a > hi or b < lo or b > hi: + return f"Range {field} out of bounds [{lo}-{hi}]" + if a > b: + return f"Range start > end: {field}" + return None + if not field.isdigit(): + return f"Invalid field: {field}" + val = int(field) + if val < lo or val > hi: + return f"Value {val} out of bounds [{lo}-{hi}]" + return None + + +def validate_cron(cron_expr: str) -> str | None: + """Validate a cron expression. Returns error message or None.""" + fields = cron_expr.strip().split() + if len(fields) != 5: + return f"Expected 5 fields, got {len(fields)}" + bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)] + names = ["minute", "hour", "day-of-month", "month", "day-of-week"] + for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)): + err = _validate_cron_field(field, lo, hi) + if err: + return f"{name}: {err}" + return None + + +def save_durable_jobs(): + """Persist durable jobs to .scheduled_tasks.json.""" + durable = [asdict(j) for j in scheduled_jobs.values() if j.durable] + DURABLE_PATH.write_text(json.dumps(durable, indent=2)) + + +def load_durable_jobs(): + """Load durable jobs from disk on startup.""" + if not DURABLE_PATH.exists(): + return + try: + jobs = json.loads(DURABLE_PATH.read_text()) + for j in jobs: + job = CronJob(**j) + err = validate_cron(job.cron) + if err: + print(f" \033[31m[cron] skipping invalid job {job.id}: {err}\033[0m") + continue + scheduled_jobs[job.id] = job + valid = [j for j in jobs if j["id"] in scheduled_jobs] + if valid: + print(f" \033[35m[cron] loaded {len(valid)} durable job(s)\033[0m") + except Exception: + pass + + +def schedule_job(cron: str, prompt: str, recurring: bool = True, + durable: bool = True) -> CronJob | str: + """Register a new cron job. Returns CronJob or error string.""" + err = validate_cron(cron) + if err: + return err + job = CronJob( + id=f"cron_{random.randint(0, 999999):06d}", + cron=cron, prompt=prompt, + recurring=recurring, durable=durable, + ) + with cron_lock: + scheduled_jobs[job.id] = job + if durable: + save_durable_jobs() + print(f" \033[35m[cron register] {job.id} '{cron}' → {prompt[:40]}\033[0m") + return job + + +def cancel_job(job_id: str) -> str: + """Cancel a cron job.""" + with cron_lock: + job = scheduled_jobs.pop(job_id, None) + if not job: + return f"Job {job_id} not found" + if job.durable: + save_durable_jobs() + print(f" \033[31m[cron cancel] {job_id}\033[0m") + return f"Cancelled {job_id}" + + +def cron_scheduler_loop(): + """Independent daemon thread: poll every 1s, fire matching jobs. + Individual job errors are caught to prevent one bad job from + killing the entire scheduler thread.""" + while True: + time.sleep(1) + now = datetime.now() + # Date-aware marker prevents daily jobs from skipping on day 2+ + minute_marker = now.strftime("%Y-%m-%d %H:%M") + with cron_lock: + for job in list(scheduled_jobs.values()): + try: + if cron_matches(job.cron, now): + if _last_fired.get(job.id) != minute_marker: + cron_queue.append(job) + _last_fired[job.id] = minute_marker + print(f" \033[35m[cron fire] {job.id} → " + f"{job.prompt[:40]}\033[0m") + if not job.recurring: + scheduled_jobs.pop(job.id, None) + if job.durable: + save_durable_jobs() + except Exception as e: + print(f" \033[31m[cron error] {job.id}: {e}\033[0m") + + +def consume_cron_queue() -> list[CronJob]: + """Consume fired jobs from cron_queue (called by agent_loop).""" + with cron_lock: + fired = list(cron_queue) + cron_queue.clear() + return fired + + +# Load durable jobs on startup, then start scheduler thread +load_durable_jobs() +threading.Thread(target=cron_scheduler_loop, daemon=True).start() +print(" \033[35m[cron] scheduler thread started\033[0m") + + +# Cron tool handlers + +def run_schedule_cron(cron: str, prompt: str, + recurring: bool = True, durable: bool = True) -> str: + result = schedule_job(cron, prompt, recurring, durable) + if isinstance(result, str): + return f"Error: {result}" + return f"Scheduled {result.id}: '{cron}' → {prompt}" + + +def run_list_crons() -> str: + with cron_lock: + jobs = list(scheduled_jobs.values()) + if not jobs: + return "No cron jobs. Use schedule_cron to add one." + lines = [] + for j in jobs: + tag = "recurring" if j.recurring else "one-shot" + dur = "durable" if j.durable else "session" + lines.append(f" {j.id}: '{j.cron}' → {j.prompt[:40]} " + f"[{tag}, {dur}]") + return "\n".join(lines) + + +def run_cancel_cron(job_id: str) -> str: + return cancel_job(job_id) + + +# ── MessageBus + Team Protocols (s15 new) ── + +MAILBOX_DIR = WORKDIR / ".mailboxes" +MAILBOX_DIR.mkdir(exist_ok=True) +MAILBOX_ROOT = MAILBOX_DIR.resolve() +VALID_AGENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$") + + +def is_valid_agent_name(name: str) -> bool: + return bool(VALID_AGENT_NAME.fullmatch(name)) + + +class MessageBus: + """Thread-safe file mailboxes with destructive reads.""" + + def __init__(self): + self._lock = threading.RLock() + self._changed = threading.Condition(self._lock) + + def _path(self, agent: str) -> Path: + if not is_valid_agent_name(agent): + raise ValueError(f"Invalid mailbox recipient: {agent!r}") + path = (MAILBOX_DIR / f"{agent}.jsonl").resolve() + if not path.is_relative_to(MAILBOX_ROOT): + raise ValueError(f"Mailbox path escapes directory: {agent!r}") + return path + + def _read_unlocked(self, agent: str) -> list[dict]: + inbox = self._path(agent) + if not inbox.exists(): + return [] + msgs = [json.loads(line) for line in inbox.read_text().splitlines() + if line.strip()] + inbox.unlink() + return msgs + + def send(self, from_agent: str, to_agent: str, content: str, + msg_type: str = "message", metadata: dict | None = None): + msg = {"from": from_agent, "to": to_agent, + "content": content, "type": msg_type, + "ts": time.time(), "metadata": metadata or {}} + with self._changed: + with open(self._path(to_agent), "a") as f: + f.write(json.dumps(msg, ensure_ascii=False) + "\n") + self._changed.notify_all() + print(f" \033[33m[bus] {from_agent} → {to_agent}: " + f"({msg_type}) {content[:50]}\033[0m") + + def read_inbox(self, agent: str) -> list[dict]: + with self._lock: + return self._read_unlocked(agent) + + def peek(self, agent: str) -> bool: + with self._lock: + inbox = self._path(agent) + return inbox.exists() and inbox.stat().st_size > 0 + + def wait_for_messages(self, agent: str, + timeout: float | None = None) -> list[dict]: + """Block until the agent has messages or timeout expires.""" + deadline = None if timeout is None else time.monotonic() + timeout + with self._changed: + while not self.peek(agent): + remaining = (None if deadline is None + else deadline - time.monotonic()) + if remaining is not None and remaining <= 0: + return [] + self._changed.wait(remaining) + return self._read_unlocked(agent) + + +BUS = MessageBus() + +# working | waiting_approval | idle | stopping +active_teammates: dict[str, str] = {} +plan_gates: dict[str, str] = {} +plan_request_ids: dict[str, str] = {} +team_lock = threading.RLock() + + +@dataclass +class ProtocolState: + request_id: str + type: str + sender: str + target: str + status: str + payload: str + created_at: float = field(default_factory=time.time) + + +pending_requests: dict[str, ProtocolState] = {} + + +def new_request_id() -> str: + while True: + request_id = f"req_{random.randint(0, 999999):06d}" + if request_id not in pending_requests: + return request_id + + +def match_response(response_type: str, request_id: str, approve: bool, + from_agent: str, to_agent: str) -> bool: + """Match one protocol response to one pending request.""" + with team_lock: + state = pending_requests.get(request_id) + if not state: + print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") + return False + expected = { + "shutdown": "shutdown_response", + "plan_approval": "plan_approval_response", + }[state.type] + if response_type != expected: + print(f" \033[31m[protocol] expected {expected}, " + f"got {response_type}\033[0m") + return False + if from_agent != state.target or to_agent != state.sender: + print(f" \033[31m[protocol] {request_id} responder mismatch\033[0m") + return False + if state.status != "pending": + print(f" \033[33m[protocol] {request_id} already " + f"{state.status}\033[0m") + return False + state.status = "approved" if approve else "rejected" + print(f" \033[35m[protocol] {request_id} → {state.status}\033[0m") + return True + + +def consume_lead_inbox() -> list[dict]: + """Consume Lead events and update protocol state before model delivery.""" + msgs = BUS.read_inbox("lead") + for msg in msgs: + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + if request_id and msg.get("type", "").endswith("_response"): + match_response(msg["type"], request_id, + metadata.get("approve", False), + msg.get("from", ""), msg.get("to", "")) + return msgs + + +def format_team_events(msgs: list[dict]) -> str: + lines = [] + for msg in msgs: + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id") + suffix = f" request_id={request_id}" if request_id else "" + lines.append( + f"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}" + ) + return "[Team events]\n" + "\n".join(lines) + + +def _last_assistant_text(content) -> str: + for block in content: + if getattr(block, "type", None) == "text": + return block.text.strip() + if isinstance(block, dict) and block.get("type") == "text": + return str(block.get("text", "")).strip() + return "" + + +def _teammate_submit_plan(from_name: str, plan: str) -> str: + with team_lock: + if plan_gates.get(from_name) == "pending": + return "A plan is already waiting for review." + request_id = new_request_id() + pending_requests[request_id] = ProtocolState( + request_id=request_id, + type="plan_approval", + sender=from_name, + target="lead", + status="pending", + payload=plan, + ) + plan_gates[from_name] = "pending" + plan_request_ids[from_name] = request_id + active_teammates[from_name] = "waiting_approval" + BUS.send(from_name, "lead", plan, "plan_approval_request", + {"request_id": request_id}) + return f"Plan submitted ({request_id}). Wait for Lead's decision." + + +def _run_teammate_tool(name: str, block, handlers: dict) -> str: + gate = plan_gates.get(name, "not_required") + if block.name in {"bash", "write_file"} and gate != "not_required": + if gate != "approved": + return (f"Blocked: plan status is {gate}. Submit or revise the " + "plan and wait for approval before changing the workspace.") + handler = handlers.get(block.name) + return str(handler(**block.input)) if handler else f"Unknown tool: {block.name}" + + +def apply_plan_response(name: str, msg: dict) -> tuple[bool, str]: + """Apply only the Lead response for this teammate's current plan.""" + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + expected_id = plan_request_ids.get(name) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and request_id == expected_id + and state is not None + and state.type == "plan_approval" + and state.sender == name + and state.target == "lead" + and state.status in {"approved", "rejected"} + and metadata.get("approve", False) + == (state.status == "approved") + ) + if not valid: + return False, "[Ignored plan response: request mismatch]" + plan_gates[name] = state.status + active_teammates[name] = "working" + plan_request_ids.pop(name, None) + outcome = state.status + return True, f"[Plan {outcome}] {msg['content']}" + + +def apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]: + """Accept only a pending shutdown request sent by Lead to this teammate.""" + request_id = msg.get("metadata", {}).get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and state is not None + and state.type == "shutdown" + and state.sender == "lead" + and state.target == name + and state.status == "pending" + and active_teammates.get(name) != "stopping" + ) + if not valid: + return False, "[Ignored shutdown request: request mismatch]" + active_teammates[name] = "stopping" + return True, request_id + + +def _teammate_send_message(from_name: str, to: str, content: str) -> str: + with team_lock: + if to != "lead" and to not in active_teammates: + return f"Agent '{to}' is not active" + BUS.send(from_name, to, content) + return f"Sent to {to}" + + +# ── Autonomous Task Discovery (s16 new) ── + +IDLE_SCAN_INTERVAL = 2.0 + + +def scan_unclaimed_tasks() -> list[Task]: + """Return ready tasks without changing ownership.""" + return [ + task for task in list_tasks() + if (task.status == "pending" + and task.owner is None + and can_start(task.id)) + ] + + +def claim_next_task(name: str) -> Task | None: + """Claim the first ready task that is still available.""" + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None + + +# ── Teammate Thread ── + +def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: + """Spawn a persistent teammate that alternates between WORK and IDLE.""" + if not is_valid_agent_name(name): + return ("Invalid teammate name: use 1-64 letters, digits, " + "underscores, or dashes") + with team_lock: + if name in active_teammates: + return f"Teammate '{name}' already exists" + active_teammates[name] = "working" + plan_gates[name] = "not_required" + + system = (f"You are '{name}', a {role}. " + "Use tools to complete assigned work. " + "When idle, the runtime may assign a ready task from the shared " + "board. " + "When asked for a plan, call submit_plan before bash or " + "write_file and wait for approval. End each assignment with a " + "concise result; the runtime delivers it to Lead.") + + def run(): + messages = [{"role": "user", "content": prompt}] + sub_tools = [ + {"name": "bash", "description": "Run a shell command.", + "input_schema": {"type": "object", + "properties": {"command": {"type": "string"}}, + "required": ["command"]}}, + {"name": "read_file", "description": "Read file contents.", + "input_schema": {"type": "object", + "properties": {"path": {"type": "string"}}, + "required": ["path"]}}, + {"name": "write_file", "description": "Write content to a file.", + "input_schema": {"type": "object", + "properties": {"path": {"type": "string"}, + "content": {"type": "string"}}, + "required": ["path", "content"]}}, + {"name": "send_message", + "description": "Send a message to another agent.", + "input_schema": {"type": "object", + "properties": {"to": {"type": "string"}, + "content": {"type": "string"}}, + "required": ["to", "content"]}}, + {"name": "submit_plan", + "description": "Submit a work plan for Lead approval.", + "input_schema": {"type": "object", + "properties": {"plan": {"type": "string"}}, + "required": ["plan"]}}, + {"name": "list_tasks", + "description": "List tasks on the shared board.", + "input_schema": {"type": "object", "properties": {}, + "required": []}}, + {"name": "claim_task", + "description": "Claim a ready task from the shared board.", + "input_schema": {"type": "object", + "properties": {"task_id": {"type": "string"}}, + "required": ["task_id"]}}, + {"name": "complete_task", + "description": "Mark an owned task completed.", + "input_schema": {"type": "object", + "properties": {"task_id": {"type": "string"}}, + "required": ["task_id"]}}, + ] + sub_handlers = { + "bash": run_bash, "read_file": run_read, "write_file": run_write, + "send_message": lambda to, content: _teammate_send_message( + name, to, content), + "submit_plan": lambda plan: _teammate_submit_plan(name, plan), + "list_tasks": run_list_tasks, + "claim_task": lambda task_id: claim_task(task_id, owner=name), + "complete_task": complete_task, + } + + def handle_messages(inbox: list[dict]) -> bool: + """Return True when a shutdown request ends the teammate.""" + work_messages = [] + for msg in inbox: + msg_type = msg.get("type", "message") + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + if msg_type == "shutdown_request": + accepted, notice = apply_shutdown_request(name, msg) + if not accepted: + work_messages.append(notice) + continue + request_id = notice + BUS.send(name, "lead", "Shutdown acknowledged.", + "shutdown_response", + {"request_id": request_id, "approve": True}) + return True + if msg_type == "plan_approval_response": + _, notice = apply_plan_response(name, msg) + work_messages.append(notice) + continue + if msg_type == "plan_request": + work_messages.append( + f"[Plan required] {msg['content']}" + ) + continue + work_messages.append( + f"[Message from {msg['from']}] {msg['content']}" + ) + if work_messages: + messages.append({"role": "user", + "content": "\n".join(work_messages)}) + return False + + should_stop = False + while not should_stop: + with team_lock: + active_teammates[name] = "working" + try: + response = client.messages.create( + model=MODEL, system=system, messages=messages[-20:], + tools=sub_tools, max_tokens=8000) + except Exception as exc: + BUS.send(name, "lead", + f"{type(exc).__name__}: {exc}", "error") + break + messages.append({"role": "assistant", "content": response.content}) + if response.stop_reason == "tool_use": + results = [] + for block in response.content: + if block.type != "tool_use": + continue + output = _run_teammate_tool(name, block, sub_handlers) + results.append({"type": "tool_result", + "tool_use_id": block.id, + "content": output}) + messages.append({"role": "user", "content": results}) + continue + + summary = _last_assistant_text(response.content) + gate = plan_gates.get(name, "not_required") + if gate != "pending" and summary: + BUS.send(name, "lead", summary, "result") + if gate == "pending": + with team_lock: + active_teammates[name] = "waiting_approval" + else: + with team_lock: + active_teammates[name] = "idle" + BUS.send(name, "lead", "Waiting for more work.", + "idle_notification") + + while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + should_stop = handle_messages(inbox) + if should_stop or messages[-1]["role"] == "user": + break + continue + + task = claim_next_task(name) + if task: + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}" + ), + }) + print(f" \033[32m[idle] {name} claimed " + f"{task.id}: {task.subject}\033[0m") + break + + with team_lock: + active_teammates.pop(name, None) + plan_gates.pop(name, None) + plan_request_ids.pop(name, None) + print(f" \033[32m[teammate] {name} finished\033[0m") + + threading.Thread(target=run, daemon=True).start() + print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") + return f"Teammate '{name}' spawned as {role} (autonomous)" + + +# ── Lead Team Tools ── + +def run_spawn_teammate(name: str, role: str, prompt: str) -> str: + return spawn_teammate_thread(name, role, prompt) + + +def run_send_message(to: str, content: str) -> str: + if to not in active_teammates: + return f"Teammate '{to}' is not active" + BUS.send("lead", to, content) + return f"Sent to {to}" + + +def run_request_shutdown(teammate: str) -> str: + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + request_id = new_request_id() + pending_requests[request_id] = ProtocolState( + request_id=request_id, + type="shutdown", + sender="lead", + target=teammate, + status="pending", + payload="", + ) + BUS.send("lead", teammate, "Finish the current step and shut down.", + "shutdown_request", {"request_id": request_id}) + return f"Shutdown requested from {teammate} ({request_id})" + + +def run_request_plan(teammate: str, task: str) -> str: + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + plan_gates[teammate] = "required" + BUS.send("lead", teammate, task, "plan_request") + return f"Plan requested from {teammate}" + + +def run_review_plan(request_id: str, approve: bool, + feedback: str = "") -> str: + with team_lock: + state = pending_requests.get(request_id) + if not state: + return f"Request {request_id} not found" + if state.type != "plan_approval": + return f"Request {request_id} is not a plan" + if state.status != "pending": + return f"Request {request_id} already {state.status}" + if plan_request_ids.get(state.sender) != request_id: + return f"Request {request_id} is not the current plan" + state.status = "approved" if approve else "rejected" + content = feedback or ("Plan approved." if approve + else "Revise the plan and submit it again.") + BUS.send("lead", state.sender, content, "plan_approval_response", + {"request_id": request_id, "approve": approve}) + return f"Plan {state.status} ({request_id})" + + +# ── Tool Definitions ── + +TOOLS = [ + {"name": "bash", "description": "Run a shell command.", + "input_schema": {"type": "object", + "properties": { + "command": {"type": "string"}, + "run_in_background": {"type": "boolean"}}, + "required": ["command"]}}, + {"name": "read_file", "description": "Read file contents.", + "input_schema": {"type": "object", + "properties": {"path": {"type": "string"}, + "limit": {"type": "integer"}}, + "required": ["path"]}}, + {"name": "write_file", "description": "Write content to a file.", + "input_schema": {"type": "object", + "properties": {"path": {"type": "string"}, + "content": {"type": "string"}}, + "required": ["path", "content"]}}, + {"name": "create_task", + "description": "Create a new task with optional blockedBy dependencies.", + "input_schema": {"type": "object", + "properties": { + "subject": {"type": "string"}, + "description": {"type": "string"}, + "blockedBy": {"type": "array", + "items": {"type": "string"}}}, + "required": ["subject"]}}, + {"name": "list_tasks", + "description": "List all tasks with status, owner, and dependencies.", + "input_schema": {"type": "object", "properties": {}, + "required": []}}, + {"name": "get_task", + "description": "Get full details of a specific task by ID.", + "input_schema": {"type": "object", + "properties": {"task_id": {"type": "string"}}, + "required": ["task_id"]}}, + {"name": "claim_task", + "description": "Claim a pending task. Sets owner, changes status to in_progress.", + "input_schema": {"type": "object", + "properties": {"task_id": {"type": "string"}}, + "required": ["task_id"]}}, + {"name": "complete_task", + "description": "Complete an in-progress task. Reports unblocked downstream tasks.", + "input_schema": {"type": "object", + "properties": {"task_id": {"type": "string"}}, + "required": ["task_id"]}}, + {"name": "schedule_cron", + "description": "Schedule a cron job. cron is 5-field: min hour dom month dow.", + "input_schema": {"type": "object", + "properties": { + "cron": {"type": "string", + "description": "5-field cron expression"}, + "prompt": {"type": "string", + "description": "Message to inject when fired"}, + "recurring": {"type": "boolean", + "description": "True=recurring, False=one-shot"}, + "durable": {"type": "boolean", + "description": "True=persist to disk"}}, + "required": ["cron", "prompt"]}}, + {"name": "list_crons", + "description": "List all registered cron jobs.", + "input_schema": {"type": "object", "properties": {}, + "required": []}}, + {"name": "cancel_cron", + "description": "Cancel a cron job by ID.", + "input_schema": {"type": "object", + "properties": {"job_id": {"type": "string"}}, + "required": ["job_id"]}}, + {"name": "spawn_teammate", + "description": "Spawn a teammate agent in a background thread.", + "input_schema": {"type": "object", + "properties": { + "name": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$", + }, + "role": {"type": "string"}, + "prompt": {"type": "string"}}, + "required": ["name", "role", "prompt"]}}, + {"name": "send_message", + "description": "Send a message to a teammate via MessageBus.", + "input_schema": {"type": "object", + "properties": {"to": {"type": "string"}, + "content": {"type": "string"}}, + "required": ["to", "content"]}}, + {"name": "request_shutdown", + "description": "Ask an active teammate to shut down gracefully.", + "input_schema": {"type": "object", + "properties": {"teammate": {"type": "string"}}, + "required": ["teammate"]}}, + {"name": "request_plan", + "description": "Require a teammate to submit a plan before changing files.", + "input_schema": {"type": "object", + "properties": {"teammate": {"type": "string"}, + "task": {"type": "string"}}, + "required": ["teammate", "task"]}}, + {"name": "review_plan", + "description": "Approve or reject a submitted plan by request_id.", + "input_schema": {"type": "object", + "properties": { + "request_id": {"type": "string"}, + "approve": {"type": "boolean"}, + "feedback": {"type": "string"}}, + "required": ["request_id", "approve"]}}, +] + + +# ── Context ── + +def update_context(context: dict, messages: list) -> dict: + """Derive context from real state.""" + memories = "" + if MEMORY_INDEX.exists(): + content = MEMORY_INDEX.read_text().strip() + if content: + memories = content + return { + "enabled_tools": [t["name"] for t in TOOLS], + "workspace": str(WORKDIR), + "memories": memories, + } + + +# ── Agent Loop ── +# Keep the loop focused on the mechanisms introduced in this chapter. +# Fired cron entries are injected at the start of each model turn. + +def agent_loop(messages: list, context: dict): + system = get_system_prompt(context) + while True: + # Consume fired cron jobs → inject as messages + fired = consume_cron_queue() + for job in fired: + messages.append({"role": "user", + "content": f"[Scheduled] {job.prompt}"}) + print(f" \033[35m[inject cron] {job.prompt[:50]}\033[0m") + + try: + response = client.messages.create( + model=MODEL, system=system, messages=messages, + tools=TOOLS, max_tokens=8000) + except Exception as e: + messages.append({"role": "assistant", "content": [ + {"type": "text", + "text": f"[Error] {type(e).__name__}: {e}"}]}) + return + + messages.append({"role": "assistant", "content": response.content}) + if response.stop_reason != "tool_use": + return + + results = [] + for block in response.content: + if block.type != "tool_use": + continue + print(f"\033[36m> {block.name}\033[0m") + + if should_run_background(block.name, block.input): + bg_id = start_background_task(block) + results.append({"type": "tool_result", + "tool_use_id": block.id, + "content": f"[Background task {bg_id} started] " + f"Result will be available when complete."}) + else: + output = execute_tool(block) + print(str(output)[:300]) + results.append({"type": "tool_result", + "tool_use_id": block.id, + "content": output}) + + # Merge background tool results + notifications into one user message + user_content = list(results) + bg_notifications = collect_background_results() + if bg_notifications: + for notif in bg_notifications: + user_content.append({"type": "text", "text": notif}) + messages.append({"role": "user", "content": user_content}) + context = update_context(context, messages) + system = get_system_prompt(context) + + +if __name__ == "__main__": + print("s16: autonomous agents") + print("Enter a question, press Enter to send. Type q to quit.\n") + history = [] + context = update_context({}, []) + + # input() and a 1s poller (teammate inbox or background results) feed one + # event queue (issues #291, #46). + events = queue.Queue() + + def input_reader(): + while True: + try: + line = input("\033[36ms16 >> \033[0m") + except (EOFError, KeyboardInterrupt): + events.put(("quit", None)) + return + events.put(("user", line)) + + def inbox_poller(): + # Poll ~1s and wake the Lead when async results are ready: teammate + # inbox messages or completed background tasks. Don't gate on + # active_teammates: a teammate sends its result and then removes itself, + # so the final message can outlive its registry entry. + while True: + time.sleep(1) + if BUS.peek("lead") or has_pending_background(): + events.put(("wake", None)) + + threading.Thread(target=input_reader, daemon=True).start() + threading.Thread(target=inbox_poller, daemon=True).start() + + had_teammates = False + while True: + kind, payload = events.get() + if kind == "quit": + break + if kind == "user": + if payload.strip().lower() in ("q", "exit", ""): + break + history.append({"role": "user", "content": payload}) + else: # "wake": teammate inbox or background results are ready + parts = [] + inbox = consume_lead_inbox() + if inbox: + parts.append(format_team_events(inbox)) + bg = collect_background_results() + parts.extend(bg) + if not parts: + continue # already drained by an earlier wake (idempotent) + history.append({"role": "user", "content": "\n".join(parts)}) + print(f"\n\033[33m[wake: {len(inbox)} team events + " + f"{len(bg)} background " + f"-> new turn]\033[0m") + + # One turn for whichever source woke us. + agent_loop(history, context) + context = update_context(context, history) + for block in history[-1]["content"]: + if getattr(block, "type", None) == "text": + print(block.text) + elif isinstance(block, dict) and block.get("type") == "text": + print(block.get("text", "")) + + # Announce once after all requested shutdowns have completed. + if active_teammates: + had_teammates = True + elif had_teammates and not BUS.peek("lead") and not has_pending_background(): + print("\033[32m[all teammates shut down]\033[0m") + had_teammates = False + print() diff --git a/s17_autonomous_agents/images/autonomous-agents-overview.en.svg b/s16_autonomous_agents/images/autonomous-agents-overview.en.svg similarity index 79% rename from s17_autonomous_agents/images/autonomous-agents-overview.en.svg rename to s16_autonomous_agents/images/autonomous-agents-overview.en.svg index 709676b6..2ba87548 100644 --- a/s17_autonomous_agents/images/autonomous-agents-overview.en.svg +++ b/s16_autonomous_agents/images/autonomous-agents-overview.en.svg @@ -19,15 +19,15 @@ - Autonomous Agents — Idle Loop + Auto-Claim + WORK/IDLE Lifecycle + Autonomous Agents — Idle Task Discovery + Atomic Claim - s16 Preserved + s15 Preserved - s17 New + s16 New - + turn @@ -49,28 +49,28 @@ - TOOL DISPATCH (all s16 preserved) - bash · read · write · task(4) · send · inbox + TOOL DISPATCH (all s15 preserved) + bash · read · write · task tools · send · protocols ★ request_shutdown · request_plan · review_plan - + - same inner LLM/tool loop inside WORK + idle teammates look for ready work - + - Teammate Lifecycle (s17 new: WORK → IDLE → SHUTDOWN) + s15 Lifecycle + s16 Task-Board Entry WORK Phase - inner loop: inbox → LLM → bash / read / write + runtime-delivered messages → LLM → tool calls stop_reason == tool_use → loop stop_reason != tool_use → IDLE - Max 10 rounds / interruptible by shutdown_request + send result, then enter IDLE @@ -82,11 +82,11 @@ - IDLE Phase (poll every 5s) - ├ Check inbox → has message → back to WORK + IDLE Phase + ├ Wait for runtime delivery → back to WORK ├ scan_unclaimed_tasks → claim → back to WORK - └ 60s timeout → SHUTDOWN ↓ - idle_poll() + claim_task() + └ No ready task → remain IDLE + wait_for_messages() + claim_next_task() @@ -94,16 +94,16 @@ - 60s timeout + shutdown_request - s16: MessageBus + protocols + request_shutdown + plan approval + s15: MessageBus + protocols + request_shutdown + plan approval - s17: idle_poll + scan_unclaimed_tasks + auto_claim + identity re-injection + s16: scan_unclaimed_tasks + claim_next_task + task_lock - Lead tools unchanged (14) · Teammate tools 5 → 8 (+3 task tools) · Teammates self-claim, Lead only creates tasks + Lead creates the task graph · teammates gain 3 task tools and atomically claim ready work diff --git a/web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.ja.svg b/s16_autonomous_agents/images/autonomous-agents-overview.ja.svg similarity index 77% rename from web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.ja.svg rename to s16_autonomous_agents/images/autonomous-agents-overview.ja.svg index 65d9a764..34123b86 100644 --- a/web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.ja.svg +++ b/s16_autonomous_agents/images/autonomous-agents-overview.ja.svg @@ -19,13 +19,13 @@ - Autonomous Agents — アイドルポーリング + 自動認領 + WORK/IDLE ライフサイクル + Autonomous Agents — アイドル時のタスク発見 + 原子的な認領 - s16 保持 + s15 保持 - s17 新規 + s16 新規 @@ -49,28 +49,28 @@ - TOOL DISPATCH(s16 全保持) - bash · read · write · task(4) · send · inbox + TOOL DISPATCH(s15 全保持) + bash · read · write · task tools · send · protocols ★ request_shutdown · request_plan · review_plan - + - 同じ内側 LLM/tool loop を WORK に入れる + 待機中に実行可能な仕事を探す - + - チームメイトライフサイクル(s17 新規:WORK → IDLE → SHUTDOWN) + s15 ライフサイクル + s16 タスクボード入口 WORK フェーズ - 内側ループ:inbox → LLM → bash / read / write + ランタイム配信メッセージ → LLM → ツール呼び出し stop_reason == tool_use → ループ stop_reason != tool_use → IDLE - 最大 10 ラウンド / shutdown_request で中断可能 + result を送り、IDLE に入る @@ -82,11 +82,11 @@ - IDLE フェーズ(5 秒ごとにポーリング) - ├ inbox チェック → メッセージあり → WORK に戻る + IDLE フェーズ + ├ ランタイム配信を待つ → WORK に戻る ├ scan_unclaimed_tasks → 認領 → WORK に戻る - └ 60 秒タイムアウト → SHUTDOWN ↓ - idle_poll() + claim_task() + └ 実行可能なタスクなし → IDLE を維持 + wait_for_messages() + claim_next_task() @@ -94,16 +94,16 @@ - 60 秒タイムアウト + shutdown_request - s16: MessageBus + protocols + request_shutdown + plan approval + s15: MessageBus + protocols + request_shutdown + plan approval - s17: idle_poll + scan_unclaimed_tasks + auto_claim + identity re-injection + s16: scan_unclaimed_tasks + claim_next_task + task_lock - Lead ツール不変(14) · チームメイトツール 5 → 8(+3 task tools) · チームメイトが自己認領、Lead はタスク作成のみ + Lead が依存グラフを作成 · チームメイトは 3 つのタスクツールで仕事を原子的に認領 diff --git a/web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.svg b/s16_autonomous_agents/images/autonomous-agents-overview.svg similarity index 79% rename from web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.svg rename to s16_autonomous_agents/images/autonomous-agents-overview.svg index df99675a..48d34b80 100644 --- a/web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.svg +++ b/s16_autonomous_agents/images/autonomous-agents-overview.svg @@ -19,15 +19,15 @@ - Autonomous Agents — 空闲循环 + 自动认领 + WORK/IDLE 生命周期 + Autonomous Agents — 空闲任务发现 + 原子认领 - s16 保留 + s15 保留 - s17 新增 + s16 新增 - + turn @@ -49,28 +49,28 @@ - TOOL DISPATCH (s16 全保留) - bash · read · write · task(4) · send · inbox + TOOL DISPATCH (s15 全保留) + bash · read · write · task tools · send · protocols ★ request_shutdown · request_plan · review_plan - + - 同一个内层 LLM/tool loop 放进 WORK + 空闲时从任务板寻找可执行工作 - + - 队友生命周期(s17 新增:WORK → IDLE → SHUTDOWN) + s15 生命周期 + s16 任务板入口 WORK 阶段 - 内层循环:inbox → LLM → bash / read / write + 消息自动进入上下文 → LLM → 工具调用 stop_reason == tool_use → loop stop_reason != tool_use → IDLE - 最多 10 轮 / 可被 shutdown_request 中断 + 完成后发送 result,再进入 IDLE @@ -82,11 +82,11 @@ - IDLE 阶段(每 5s 轮询) - ├ 检查 inbox → 有消息 → 回 WORK + IDLE 阶段 + ├ 等待运行时投递消息 → 回 WORK ├ scan_unclaimed_tasks → 认领 → 回 WORK - └ 60s 超时 → SHUTDOWN ↓ - idle_poll() + claim_task() + └ 没有就绪任务 → 保持 IDLE + wait_for_messages() + claim_next_task() @@ -94,16 +94,16 @@ - 60s 超时 + shutdown_request - s16: MessageBus + protocols + request_shutdown + plan approval + s15: MessageBus + protocols + request_shutdown + plan approval - s17: idle_poll + scan_unclaimed_tasks + auto_claim + identity re-injection + s16: scan_unclaimed_tasks + claim_next_task + task_lock - Lead 工具不变(14) · 队友工具 5 → 8(+3 task tools) · 队友自主认领,Lead 只创建任务 + Lead 创建任务依赖图 · 队友获得 3 个任务工具并原子认领就绪工作 diff --git a/s16_team_protocols/README.ja.md b/s16_team_protocols/README.ja.md deleted file mode 100644 index e89eb302..00000000 --- a/s16_team_protocols/README.ja.md +++ /dev/null @@ -1,243 +0,0 @@ -# s16: Agent Teams — プロトコル実験:型付き協調 - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s14 → s15 → `s16` → [s17](../s17_autonomous_agents/) → s18 → s19 → s20 → s21 → s22 -> *"チームメイト間には取り決めが必要"* — request-response パターンが全てのネゴシエーションを駆動。 -> -> **Harness 層**: プロトコル — Agent 間の構造化ハンドシェイク。 - -> **モジュール 2/2:** s15 でチームメイトランタイムとメールボックスを構築した。この章で変えるのは協調契約だけであり、リクエスト、返信、相関 ID、状態遷移を扱う。 - ---- - -## 課題 - -s15 のチームメイトは仕事ができるが、連携は緩い:Lead がメッセージを送り、チームメイトが返信するだけで、構造化されたプロトコルがない。2 つのシナリオで問題が露呈する: - -**シャットダウン**:Lead が Alice にシャットダウンを頼む。スレッドを強制終了すると、書きかけのファイルがディスクに残る。ハンドシェイクが必要:Lead がリクエストを送信、Alice が收尾後に確認。 - -**計画承認**:Bob が認証モジュールのリファクタリングを提案、高リスク操作。Lead が Bob の計画を確認し、承認後に実行すべき。 - -これら 2 つのシナリオは同じ構造:一方がリクエストを送信、もう一方が返信、両者は同じ ID で関連付けられる。状態機械が追跡:pending → approved / rejected。 - ---- - -## ソリューション - -![Team Protocols Overview](images/team-protocols-overview.ja.svg) - -教学版は前章までの Agent 能力の流れを受け継ぎ、S15 のチーム通信の上に構造化プロトコルを追加する。プロトコル機構に集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。追加:**ProtocolState**(リクエスト状態追跡)、**dispatch_message**(メッセージタイプ別ルーティング)、**match_response**(request_id でリクエストとレスポンスを関連付け、型検証付き)。 - -2 つのプロトコル、1 つの仕組み: - -| プロトコル | 方向 | 用途 | -|-----------|------|------| -| shutdown_request / response | Lead → チームメイト | 丁寧なシャットダウンハンドシェイク | -| plan_approval_request / response | チームメイト → Lead | 計画承認プロトコルの例 | - -> 教学版は計画承認の request-response メッセージフローをデモするが、実行ゲーティング(未承認時の bash/write_file 拦截)は未実装。真实 CC にはチームメイト向けの permission gating 機構がある。 - ---- - -## 仕組み - -### ProtocolState: リクエスト状態 - -各プロトコルリクエストは、送信者、受信者、現在の状態、ペイロードを記録する状態レコードを作成: - -```python -@dataclass -class ProtocolState: - request_id: str # 一意 ID、例 "req_004281" - type: str # "shutdown" | "plan_approval" - sender: str # 送信者 - target: str # 受信者 - status: str # pending | approved | rejected - payload: str # 計画テキストまたはシャットダウン理由 - created_at: float # タイムスタンプ - -pending_requests: dict[str, ProtocolState] = {} -``` - -リクエスト送信時にレコードを作成、レスポンス受信時に `request_id` で該当レコードを見つけて状態を更新。 - -### 4 ステッププロトコルフロー - -シャットダウンを例にした完全な流れ: - -``` -1. Lead がリクエスト送信 - req_id = new_request_id() # "req_004281" - pending_requests[req_id] = ProtocolState(type="shutdown", status="pending", ...) - BUS.send("lead", "alice", "shutdown_request", metadata={"request_id": req_id}) - -2. チームメイト受信 → dispatch - inbox = BUS.read_inbox("alice") - msg_type = msg["type"] # "shutdown_request" - → handle_shutdown_request() にルーティング - -3. チームメイト返信 - BUS.send("alice", "lead", "shutdown_response", - metadata={"request_id": req_id, "approve": True}) - -4. Lead がレスポンス受信 → match - match_response("shutdown_response", req_id, approve=True) - pending_requests[req_id].status = "approved" -``` - -`request_id` はチェーン全体を貫く関連キー、リクエストが持ち出し、レスポンスが持ち帰る。 - -### dispatch_message: タイプ別ルーティング - -チームメイトの inbox は通常メッセージとプロトコルメッセージの両方を受信。`handle_inbox_message` がメッセージタイプで振り分け: - -```python -def handle_inbox_message(name, msg, messages): - msg_type = msg.get("type", "message") - req_id = msg.get("metadata", {}).get("request_id", "") - - if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down.", "shutdown_response", - {"request_id": req_id, "approve": True}) - return True # ループ停止 - - if msg_type == "plan_approval_response": - approve = msg["metadata"].get("approve", False) - messages.append({"role": "user", - "content": "[Plan approved]" if approve else "[Plan rejected]"}) - return False # 継続 -``` - -新しいプロトコルタイプの追加は新しい `if` 分岐を追加するだけ。 - -### match_response: 型検証 - -`match_response` は `request_id` で状態を見つけるだけでなく、レスポンスタイプがリクエストタイプと一致するか検証: - -```python -def match_response(response_type, request_id, approve): - state = pending_requests.get(request_id) - if not state: - return - if state.type == "shutdown" and response_type != "shutdown_response": - return # タイプ不一致、スキップ - if state.type == "plan_approval" and response_type != "plan_approval_response": - return - if state.status != "pending": - return # 既に解決済み、重複をスキップ - state.status = "approved" if approve else "rejected" -``` - -shutdown_response が誤って plan_approval リクエストを承認することはない。 - -### 統一 inbox コンシューマ:consume_lead_inbox - -`check_inbox` ツールとメインループ末尾の両方が同じ `consume_lead_inbox()` 関数を呼び出す。プロトコルメッセージを先にルーティングしてから残りの内容を返す。メッセージが消費されてもプロトコル状態が更新されない問題を防ぐ: - -```python -def consume_lead_inbox(route_protocol=True) -> list[dict]: - msgs = BUS.read_inbox("lead") - if route_protocol: - for msg in msgs: - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - msg_type = msg.get("type", "") - if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) - return msgs -``` - -メインループは inbox メッセージを `history` に注入し、LLM が確認して反応できるようにする。 - -### チームメイト idle loop:終了ではなく待機 - -s15 のチームメイトは 10 ラウンドで終了。s16 のチームメイトは LLM が非 tool_use を返した後 idle 待機に入る:inbox をポーリング、shutdown_request に応答して終了、または新メッセージで作業継続。 - -``` -LLM が非 tool_use を返す - → idle: 毎秒 inbox をポーリング - → shutdown_request 受信 → shutdown_response 返信 → 終了 - → 新メッセージ受信 → messages に注入 → LLM ターン継続 -``` - -教学版は Lead への idle_notification を省略。真实 CC は idle 時に `idle_notification` を送信、Lead はチームメイトが空いていることを知り、新しいタスクを割り当て可能。 - -### 組み合わせて実行 - -``` -1. Lead: "Alice にファイルを作成させ、その後シャットダウン" -2. Lead → spawn_teammate("alice", "backend", "config.py を作成") -3. alice スレッド起動 → write_file("config.py", "...") → 完了 → idle -4. Lead → request_shutdown("alice") - → BUS.send("shutdown_request", {request_id: "req_000142"}) -5. alice idle ポーリング受信 → handle_shutdown_request - → BUS.send("shutdown_response", {request_id: "req_000142", approve: True}) -6. Lead consume_lead_inbox → match_response("req_000142", approve=True) - → pending_requests["req_000142"].status = "approved" - → inbox メッセージが history に注入、LLM がシャットダウン結果を確認 -``` - -シャットダウンハンドシェイク完了:リクエスト → 確認 → シャットダウン。各ステップは `request_id` で追跡。 - ---- - -## s15 からの変更 - -| コンポーネント | 変更前 (s15) | 変更後 (s16) | -|--------------|------------|------------| -| 連携方法 | 緩いテキストメッセージ | 構造化 request-response プロトコル | -| リクエスト追跡 | なし | ProtocolState + pending_requests dict | -| メッセージルーティング | 全てテキストとして処理 | dispatch_message がタイプ別にルーティング | -| シャットダウン | 自然終了またはスレッド強制終了 | request_id ハンドシェイク機構 | -| 計画承認 | なし | メッセージフローの例(実行ゲーティングなし) | -| 新規メッセージ型 | message, result | + shutdown_request/response, plan_approval_request/response | -| チームメイトライフサイクル | 最大 10 ラウンド | idle loop(inbox メッセージを待機) | -| Lead inbox | check_inbox とメインループが別々に読み取り | 統一 consume_lead_inbox | -| Lead ツール | 14 (s15) | 14(コアツールセットに request_shutdown、request_plan、review_plan を追加) | -| チームメイトツール | 4 (s15) | + submit_plan (5) | - ---- - -## 試してみる - -```sh -cd learn-claude-code -python s16_team_protocols/code.py -``` - -以下のプロンプトを試してください: - -1. `Spawn alice as a backend dev. Ask her to create a file. Then request her shutdown.` -2. `Spawn bob with a refactoring task. Have him submit a plan first. Then review and approve it.` - -観察ポイント:シャットダウンハンドシェイクは完了しているか(リクエスト → 確認 → シャットダウン)?`pending_requests` の状態は正しく遷移しているか?`request_id` はリクエストとレスポンス間で一貫しているか?idle チームメイトは shutdown_request を受信できるか? - ---- - -## 次の章 - -s15-s16 では、Lead が各チームメイトにタスクを割り当てる必要がある。"Alice はこれ、Bob はあれ"。ボードに 10 個の未認領タスクがあれば、Lead が手動で assign しなければならない。 - -チームメイトが自分でボードを見て認領できたらどうか?Lead はタスクを作成するだけで、チームメイトが自分で発見、認領、完了する。 - -s17 Autonomous Agents → チームメイトの自己組織化、リーダーの割り当て不要。 - -
-CC ソースコード深掘り - -CC のチームプロトコル実装(`teammateMailbox.ts`、1184 行)は教学版と同じコア構造:request_id + approve/reject の request-response パターン。違いは以下の通り: - -**シャットダウンプロトコル**:CC のシャットダウンは三方向通信(`teammateMailbox.ts:720-763`、`SendMessageTool.ts:268-430`)。Lead が `shutdown_request` を送信、チームメイトが `shutdown_approved`(または理由付き `shutdown_rejected`)で返信、システムが `teammate_terminated` で全関係者に通知。確認後、システムが自動的に pane(tmux/iTerm2)をクリーンアップ、タスクを unassign、team config からメンバーを削除(`useInboxPoller.ts:677-800`)。教学版は `shutdown_response` で統一命名、真实源码は `shutdown_approved` と `shutdown_rejected` の 2 つの独立したメッセージ型に分割。 - -**計画承認**:真实源码では plan approval request は `ExitPlanModeV2Tool.ts:263-312` で plan-mode-required チームメイトが plan mode を終了する際に生成される。`useInboxPoller.ts:599-661` は現在自動的に approval を書き戻し、リクエストを Lead にコンテキスト(regular message)として渡す。`SendMessageTool.ts:434-518` は明示的な approve/reject response 能力を保持、承認時に同時に `permissionMode` を設定可能(例:"承認するが plan mode で実行")、レスポンスにはチームメイトが修正して再提出するための `feedback` 文字列を含めることができる。単純な「Lead が手動で review_plan ツールを使う」フローではない。 - -**メッセージ形式**:CC のプロトコルメッセージは構造化 JSON(Zod schema 検証付き)、教学版はシンプルな type + metadata dict。フィールド名も統一されていない:permission は `request_id`(`teammateMailbox.ts:453-462`)、shutdown と plan approval は `requestId`(`teammateMailbox.ts:684-763`)。 - -**実行ゲーティング**:CC のチームメイトには完全な permission gating がある。未承認の高リスク操作は拦截され、オプションではない。教学版はメッセージフローのみをデモ。 - -**汎用性**:教学版の 1 つの FSM(pending → approved | rejected)が 2 つのプロトコルに対応する簡略化は正しい。CC の全プロトコルメッセージは同じ request id 関連機構を共有。 - -
- - diff --git a/s16_team_protocols/README.md b/s16_team_protocols/README.md deleted file mode 100644 index 7713a538..00000000 --- a/s16_team_protocols/README.md +++ /dev/null @@ -1,243 +0,0 @@ -# s16: Agent Teams — Protocol Lab: Typed Coordination - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s14 → s15 → `s16` → [s17](../s17_autonomous_agents/) → s18 → s19 → s20 → s21 → s22 -> *"Teammates need agreements"* — request-response pattern drives all negotiation. -> -> **Harness Layer**: Protocols — Structured handshakes between agents. - -> **Module 2 of 2:** s15 built the teammate runtime and mailbox. This lab changes only the coordination contract: requests, replies, correlation IDs, and state transitions. - ---- - -## The Problem - -s15's teammates can work, but coordination is loose: Lead sends a message, teammate replies, no structured protocol. Two scenarios expose the gap: - -**Shutdown**: Lead wants Alice to shut down. Killing the thread outright leaves half-written files on disk. A handshake is needed: Lead sends a request, Alice confirms after wrapping up. - -**Plan approval**: Bob wants to refactor the auth module, a high-risk operation. Lead should review Bob's plan first, approve before Bob proceeds. - -Both scenarios share the same structure: one side sends a request, the other replies, both linked by the same ID. A state machine tracks: pending → approved / rejected. - ---- - -## The Solution - -![Team Protocols Overview](images/team-protocols-overview.en.svg) - -Teaching code continues the agent capability arc from earlier chapters and adds structured protocols on top of S15's team communication. To stay focused on the protocol mechanism, it omits full error recovery, memory, and skill systems. Added: **ProtocolState** (request state tracking), **dispatch_message** (routes incoming messages by type to handlers), **match_response** (correlates response to request via request_id, with type validation). - -Two protocols, one mechanism: - -| Protocol | Direction | Purpose | -|----------|-----------|---------| -| shutdown_request / response | Lead → Teammate | Graceful shutdown handshake | -| plan_approval_request / response | Teammate → Lead | Plan approval protocol example | - -> Teaching version demonstrates the request-response message flow for plan approval, but does not implement execution gating (intercepting bash/write_file when not approved). Real CC has a permission gating mechanism for teammates. - ---- - -## How It Works - -### ProtocolState: Request State - -Each protocol request creates a state record tracking who sent it, to whom, current status, and payload: - -```python -@dataclass -class ProtocolState: - request_id: str # Unique ID, e.g. "req_004281" - type: str # "shutdown" | "plan_approval" - sender: str # Sender - target: str # Recipient - status: str # pending | approved | rejected - payload: str # Plan text or shutdown reason - created_at: float # Timestamp - -pending_requests: dict[str, ProtocolState] = {} -``` - -A record is created when sending a request, found via `request_id` when receiving a response, and its status updated. - -### Four-Step Protocol Flow - -Using shutdown as an example, the full chain: - -``` -1. Lead sends request - req_id = new_request_id() # "req_004281" - pending_requests[req_id] = ProtocolState(type="shutdown", status="pending", ...) - BUS.send("lead", "alice", "shutdown_request", metadata={"request_id": req_id}) - -2. Teammate receives → dispatch - inbox = BUS.read_inbox("alice") - msg_type = msg["type"] # "shutdown_request" - → routed to handle_shutdown_request() - -3. Teammate replies - BUS.send("alice", "lead", "shutdown_response", - metadata={"request_id": req_id, "approve": True}) - -4. Lead receives response → match - match_response("shutdown_response", req_id, approve=True) - pending_requests[req_id].status = "approved" -``` - -`request_id` is the correlation key across the entire chain: the request carries it out, the response carries it back. - -### dispatch_message: Route by Type - -A teammate's inbox receives both plain messages and protocol messages. `handle_inbox_message` dispatches by message type: - -```python -def handle_inbox_message(name, msg, messages): - msg_type = msg.get("type", "message") - req_id = msg.get("metadata", {}).get("request_id", "") - - if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down.", "shutdown_response", - {"request_id": req_id, "approve": True}) - return True # Stop the loop - - if msg_type == "plan_approval_response": - approve = msg["metadata"].get("approve", False) - messages.append({"role": "user", - "content": "[Plan approved]" if approve else "[Plan rejected]"}) - return False # Continue -``` - -Adding a new protocol type means adding a new `if` branch. - -### match_response: Type Validation - -`match_response` doesn't just find state by `request_id`, it also validates that the response type matches the request type: - -```python -def match_response(response_type, request_id, approve): - state = pending_requests.get(request_id) - if not state: - return - if state.type == "shutdown" and response_type != "shutdown_response": - return # type mismatch, skip - if state.type == "plan_approval" and response_type != "plan_approval_response": - return - if state.status != "pending": - return # already resolved, skip duplicate - state.status = "approved" if approve else "rejected" -``` - -A shutdown_response cannot accidentally approve a plan_approval request. - -### Unified Inbox Consumer: consume_lead_inbox - -Both the `check_inbox` tool and the main loop call the same `consume_lead_inbox()` function, routing protocol messages before returning remaining content. This prevents messages from being consumed without protocol state updates: - -```python -def consume_lead_inbox(route_protocol=True) -> list[dict]: - msgs = BUS.read_inbox("lead") - if route_protocol: - for msg in msgs: - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - msg_type = msg.get("type", "") - if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) - return msgs -``` - -The main loop also injects inbox messages into `history` so the LLM can see and react to them. - -### Teammate Idle Loop: Wait Instead of Exit - -s15's teammates exit after 10 rounds. s16's teammates enter idle waiting after the LLM returns a non-tool_use response: poll inbox, respond to shutdown_request and exit, or continue working on new messages. - -``` -LLM returns non-tool_use - → idle: poll inbox every second - → receives shutdown_request → reply shutdown_response → exit - → receives new message → inject into messages → continue LLM turn -``` - -Teaching version omits idle_notification to Lead. Real CC sends `idle_notification` when idle, so Lead knows the teammate is free for new tasks. - -### Putting It Together - -``` -1. Lead: "Have Alice create a file, then shut her down" -2. Lead → spawn_teammate("alice", "backend", "Create config.py") -3. alice thread starts → write_file("config.py", "...") → done → idle -4. Lead → request_shutdown("alice") - → BUS.send("shutdown_request", {request_id: "req_000142"}) -5. alice idle poll receives → handle_shutdown_request - → BUS.send("shutdown_response", {request_id: "req_000142", approve: True}) -6. Lead consume_lead_inbox → match_response("req_000142", approve=True) - → pending_requests["req_000142"].status = "approved" - → inbox message injected into history, LLM sees shutdown result -``` - -Shutdown handshake complete: request → confirm → shutdown. Every step tracked by `request_id`. - ---- - -## Changes from s15 - -| Component | Before (s15) | After (s16) | -|-----------|-------------|-------------| -| Coordination | Loose text messages | Structured request-response protocol | -| Request tracking | None | ProtocolState + pending_requests dict | -| Message routing | All treated as text | dispatch_message routes by type | -| Shutdown | Natural exit or kill thread | request_id handshake mechanism | -| Plan approval | None | Message flow example (no execution gating) | -| New message types | message, result | + shutdown_request/response, plan_approval_request/response | -| Teammate lifecycle | Max 10 rounds | Idle loop (waits for inbox messages) | -| Lead inbox | check_inbox and main loop read separately | Unified consume_lead_inbox | -| Lead tools | 14 (s15) | 14 (core tool set plus request_shutdown, request_plan, review_plan) | -| Teammate tools | 4 (s15) | + submit_plan (5) | - ---- - -## Try It - -```sh -cd learn-claude-code -python s16_team_protocols/code.py -``` - -Try these prompts: - -1. `Spawn alice as a backend dev. Ask her to create a file. Then request her shutdown.` -2. `Spawn bob with a refactoring task. Have him submit a plan first. Then review and approve it.` - -What to observe: Is the shutdown handshake complete (request → confirm → shutdown)? Does `pending_requests` state transition correctly? Is `request_id` consistent between request and response? Can the idle teammate receive shutdown_request? - ---- - -## What's Next - -In s15-s16, Lead must assign tasks to each teammate. "Alice does this, Bob does that." With 10 unclaimed tasks on the board, Lead has to manually assign each one. - -What if teammates could check the board and claim tasks themselves? Lead only needs to create tasks; teammates discover, claim, and complete them on their own. - -s17 Autonomous Agents → Self-organizing teammates, no leader assignment needed. - -
-Deep Dive into CC Source - -CC's team protocol implementation (`teammateMailbox.ts`, 1184 lines) shares the same core structure as the teaching version: request_id + approve/reject request-response pattern. Differences: - -**Shutdown protocol**: CC's shutdown is three-way communication (`teammateMailbox.ts:720-763`, `SendMessageTool.ts:268-430`). Lead sends `shutdown_request`, teammate replies `shutdown_approved` (or `shutdown_rejected` with reason), system sends `teammate_terminated` to notify all parties. After confirmation, system cleans up pane (tmux/iTerm2), unassigns tasks, removes member from team config (`useInboxPoller.ts:677-800`). Teaching version uses `shutdown_response` as a unified name; real source splits into `shutdown_approved` and `shutdown_rejected` as two separate message types. - -**Plan approval**: In the real source, plan approval request is generated by `ExitPlanModeV2Tool.ts:263-312` when a plan-mode-required teammate exits plan mode. `useInboxPoller.ts:599-661` currently auto-writes approval and passes the request to Lead as context (regular message). `SendMessageTool.ts:434-518` retains explicit approve/reject response capability — approval can simultaneously set `permissionMode` (e.g. "approved but run in plan mode"), response can include `feedback` string for teammate to revise and resubmit. Not a simple "Lead manually uses review_plan tool" flow. - -**Message format**: CC's protocol messages are structured JSON (with Zod schema validation), teaching version uses simple type + metadata dict. Field names are also inconsistent: permission uses `request_id` (`teammateMailbox.ts:453-462`), shutdown and plan approval use `requestId` (`teammateMailbox.ts:684-763`). - -**Execution gating**: CC's teammates have full permission gating. Unapproved high-risk operations are intercepted, not optional. Teaching version only demonstrates the message flow without execution interception. - -**Generality**: Teaching version's single FSM (pending → approved | rejected) maps to two protocols. This simplification is correct. CC's protocol messages all share the same request id correlation mechanism. - -
- - diff --git a/s16_team_protocols/README.zh.md b/s16_team_protocols/README.zh.md deleted file mode 100644 index 8218927f..00000000 --- a/s16_team_protocols/README.zh.md +++ /dev/null @@ -1,245 +0,0 @@ -# s16: Agent Teams — 协议实验:带类型的协作 - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s14 → s15 → `s16` → [s17](../s17_autonomous_agents/) → s18 → s19 → s20 → s21 → s22 -> *"队友之间要有约定"* — request-response 模式驱动协商。 -> -> **Harness 层**: 协议 — Agent 之间的结构化握手。 - -> **模块 2/2:** s15 已经搭好队友运行时与邮箱。本章只改变协作契约:请求、回复、关联 ID 和状态迁移。 - ---- - -## 问题 - -s15 的队友能干活了,但协调是松散的:Lead 发消息,队友回复,没有结构化的协议。两个场景暴露了问题: - -**关机**:Lead 想让 Alice 关机。直接杀线程,Alice 写了一半的文件留在磁盘上。需要握手:Lead 发请求,Alice 确认收尾后关机。 - -**计划审批**:Bob 想重构认证模块,属于高风险操作。应该先让 Lead 看 Bob 的计划,审批通过后再动手。 - -这两个场景结构完全一样:一方发请求,另一方给回复,请求和回复通过同一个 ID 关联。有状态机追踪:pending → approved / rejected。 - ---- - -## 解决方案 - -![Team Protocols Overview](images/team-protocols-overview.svg) - -教学代码承接前面章节的 Agent 能力脉络,在 S15 团队通信基础上加入结构化协议。为了聚焦协议机制,省略了完整错误恢复、记忆和技能系统。新增三样:**ProtocolState**(请求状态追踪)、**dispatch_message**(按消息类型路由到处理器)、**match_response**(通过 request_id 关联回复与请求,含类型校验)。 - -两种协议,一套机制: - -| 协议 | 方向 | 用途 | -|------|------|------| -| shutdown_request / response | Lead → 队友 | 体面关机握手 | -| plan_approval_request / response | 队友 → Lead | 计划审批协议示例 | - -> 教学版演示了计划审批的请求-响应消息流程,没有实现执行门控(未 approved 时拦截 bash/write_file)。真实 CC 的队友有 permission gating 机制。 - ---- - -## 工作原理 - -### ProtocolState: 请求状态 - -每个协议请求创建一条状态记录,记录谁发的、发给谁、当前状态、附带内容: - -```python -@dataclass -class ProtocolState: - request_id: str # 唯一 ID,如 "req_004281" - type: str # "shutdown" | "plan_approval" - sender: str # 发起方 - target: str # 接收方 - status: str # pending | approved | rejected - payload: str # 计划文本或关机原因 - created_at: float # 时间戳 - -pending_requests: dict[str, ProtocolState] = {} -``` - -发请求时创建记录,收回复时通过 `request_id` 找到对应记录,更新状态。 - -### 四步协议流程 - -以关机为例,完整链路: - -``` -① Lead 发请求 - req_id = new_request_id() # "req_004281" - pending_requests[req_id] = ProtocolState(type="shutdown", status="pending", ...) - BUS.send("lead", "alice", "shutdown_request", metadata={"request_id": req_id}) - -② 队友收到 → dispatch - inbox = BUS.read_inbox("alice") - msg_type = msg["type"] # "shutdown_request" - → 路由到 handle_shutdown_request() - -③ 队友回复 - BUS.send("alice", "lead", "shutdown_response", - metadata={"request_id": req_id, "approve": True}) - -④ Lead 收响应 → match - match_response("shutdown_response", req_id, approve=True) - pending_requests[req_id].status = "approved" -``` - -`request_id` 是贯穿全链路的关联键,请求带着它出去,回复带着它回来。 - -> 教学版用 `shutdown_response` 统一命名(approve 字段区分同意/拒绝)。真实源码拆成 `shutdown_approved` 和 `shutdown_rejected` 两种独立消息类型(`teammateMailbox.ts:720-763`)。 - -### dispatch_message: 按类型路由 - -队友的 inbox 不只收普通消息,还收协议消息。`handle_inbox_message` 按消息类型分发: - -```python -def handle_inbox_message(name, msg, messages): - msg_type = msg.get("type", "message") - req_id = msg.get("metadata", {}).get("request_id", "") - - if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down.", "shutdown_response", - {"request_id": req_id, "approve": True}) - return True # 停止循环 - - if msg_type == "plan_approval_response": - approve = msg["metadata"].get("approve", False) - messages.append({"role": "user", - "content": "[Plan approved]" if approve else "[Plan rejected]"}) - return False # 继续循环 -``` - -新增协议类型只需加新的 `if` 分支。 - -### match_response: 类型校验 - -`match_response` 不只按 `request_id` 找状态,还会校验响应类型是否匹配请求类型: - -```python -def match_response(response_type, request_id, approve): - state = pending_requests.get(request_id) - if not state: - return - if state.type == "shutdown" and response_type != "shutdown_response": - return # type mismatch, skip - if state.type == "plan_approval" and response_type != "plan_approval_response": - return - if state.status != "pending": - return # already resolved, skip duplicate - state.status = "approved" if approve else "rejected" -``` - -一个 shutdown_response 不会意外 approve 一个 plan_approval 请求。 - -### 统一 inbox 消费:consume_lead_inbox - -`check_inbox` 工具和主循环末尾都调用同一个 `consume_lead_inbox()` 函数,先路由协议消息再返回剩余内容,避免消息被读走但协议状态没更新: - -```python -def consume_lead_inbox(route_protocol=True) -> list[dict]: - msgs = BUS.read_inbox("lead") - if route_protocol: - for msg in msgs: - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - msg_type = msg.get("type", "") - if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) - return msgs -``` - -主循环末尾还会把 inbox 消息注入到 `history`,让 LLM 能看到并做出反应。 - -### 队友 idle loop:等待而不是退出 - -s15 的队友跑完 10 轮就退出。s16 的队友在 LLM 返回非 tool_use 后进入 idle 等待:轮询 inbox,收到 shutdown_request 就响应退出,收到新消息就继续工作。 - -``` -LLM 返回非 tool_use - → idle: 每秒轮询 inbox - → 收到 shutdown_request → 回复 shutdown_response → 退出 - → 收到新消息 → 注入 messages → 继续 LLM turn -``` - -教学版省略了 idle_notification 给 Lead 的通知。真实 CC 在 idle 时发 `idle_notification`,Lead 收到后知道队友空闲,可以分配新任务。 - -### 合起来跑 - -``` -1. Lead: "让 Alice 创建一个文件,然后关机" -2. Lead → spawn_teammate("alice", "backend", "创建 config.py") -3. alice 线程启动 → write_file("config.py", "...") → 完成 → idle -4. Lead → request_shutdown("alice") - → BUS.send("shutdown_request", {request_id: "req_000142"}) -5. alice idle 轮询收到 → handle_shutdown_request - → BUS.send("shutdown_response", {request_id: "req_000142", approve: True}) -6. Lead consume_lead_inbox → match_response("req_000142", approve=True) - → pending_requests["req_000142"].status = "approved" - → inbox 消息注入 history,LLM 看到关机结果 -``` - -关机握手完整:请求 → 确认 → 关机。每一步有 `request_id` 追溯。 - ---- - -## 相对 s15 的变更 - -| 组件 | 之前 (s15) | 之后 (s16) | -|------|-----------|-----------| -| 协调方式 | 松散文本消息 | 结构化请求-响应协议 | -| 请求追踪 | 无 | ProtocolState + pending_requests dict | -| 消息路由 | 全部当文本处理 | dispatch_message 按类型分发 | -| 关机 | 自然退出或杀线程 | request_id 握手机制 | -| 计划审批 | 无 | 消息流程示例(未实现执行门控) | -| 新消息类型 | message, result | + shutdown_request/response, plan_approval_request/response | -| 队友生命周期 | 最多 10 轮 | idle loop(等待 inbox 消息) | -| Lead inbox | check_inbox 和主循环分别读 | 统一 consume_lead_inbox | -| Lead 工具 | 14 (s15) | 14(核心工具集加入 request_shutdown, request_plan, review_plan) | -| 队友工具 | 4 (s15) | + submit_plan (5) | - ---- - -## 试一下 - -```sh -cd learn-claude-code -python s16_team_protocols/code.py -``` - -试试这些 prompt: - -1. `Spawn alice as a backend dev. Ask her to create a file. Then request her shutdown.` -2. `Spawn bob with a refactoring task. Have him submit a plan first. Then review and approve it.` - -观察重点:关机握手是否完整(请求 → 确认 → 关机)?`pending_requests` 的状态是否正确转换?`request_id` 是否在请求和响应之间保持一致?队友 idle 后是否能收到 shutdown_request? - ---- - -## 接下来 - -s15-s16 中,Lead 必须给每个队友分配任务。"Alice 做这个,Bob 做那个"。任务看板上有 10 个未认领的任务,Lead 得手动 assign。 - -能不能让队友自己看板、自己认领?Lead 只需要创建任务,队友自己发现、自己认领、自己完成。 - -s17 Autonomous Agents → 队友自组织,不需要领导分配。 - -
-深入 CC 源码 - -CC 的团队协议实现(`teammateMailbox.ts`,1184 行)和教学版在核心结构上一致:request_id + approve/reject 的请求-响应模式。差异在于: - -**关机协议**:CC 的 shutdown 是三向通信(`teammateMailbox.ts:720-763`、`SendMessageTool.ts:268-430`)。Lead 发 `shutdown_request`,队友回复 `shutdown_approved`(或 `shutdown_rejected` 附原因),系统发送 `teammate_terminated` 通知所有相关方。关机确认后系统自动清理 pane(tmux/iTerm2)、unassign 任务、从 team config 移除成员(`useInboxPoller.ts:677-800`)。教学版用 `shutdown_response` 统一命名,真实源码拆成 approved/rejected 两种独立消息。 - -**计划审批**:真实源码里 plan approval request 由 `ExitPlanModeV2Tool.ts:263-312` 在 plan-mode-required 队友退出 plan mode 时产生。`useInboxPoller.ts:599-661` 当前会自动回写 approval,并把请求交给 Lead 作为上下文(regular message)。`SendMessageTool.ts:434-518` 仍保留显式 approve/reject response 能力,审批时可同时设置 `permissionMode`(如"批准但以 plan mode 运行"),响应中可包含 `feedback` 字符串供队友修正后重新提交。不是简单的"Lead 手动 review_plan 工具"流程。 - -**消息格式**:CC 的协议消息是结构化的 JSON(有 Zod schema 验证),教学版用简单的 type + metadata 字典。字段名也不统一:permission 用 `request_id`(`teammateMailbox.ts:453-462`),shutdown 和 plan approval 用 `requestId`(`teammateMailbox.ts:684-763`)。 - -**执行门控**:CC 的队友有完整的 permission gating。未获批准的高风险操作会被拦截,不是可选的。教学版只演示了消息流程,没有实现执行拦截。 - -**通用性**:教学版的一个 FSM(pending → approved | rejected)对应两种协议,这个简化完全正确。CC 的所有协议消息共用同一个 request id 关联机制。 - -
- - diff --git a/s16_team_protocols/code.py b/s16_team_protocols/code.py deleted file mode 100644 index d7993fb9..00000000 --- a/s16_team_protocols/code.py +++ /dev/null @@ -1,882 +0,0 @@ -#!/usr/bin/env python3 -""" -s16: Team Protocols — request-response protocol + request_id + dispatch + state machine. - -Run: python s16_team_protocols/code.py -Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY - -Changes from s15: - - ProtocolState dataclass (request_id, type, sender, status, created_at) - - pending_requests dict: tracks in-flight protocol requests - - dispatch_message: routes incoming messages by type to handlers - - request_shutdown: Lead sends shutdown protocol request - - request_plan: Lead asks teammate to submit plan - - handle_shutdown_request / handle_plan_response: teammate receives & responds - - match_response: Lead correlates response to request via request_id (with type validation) - - Teammate idle loop: waits for inbox messages instead of exiting after 10 rounds - - Unified consume_lead_inbox: protocol routing + injection into history - - 3 new Lead tools: request_shutdown, request_plan, review_plan - - 1 new teammate tool: submit_plan - -ASCII flow: - Lead: BUS.send("shutdown_request", {request_id}) ──────→ teammate inbox - Teammate: dispatch → handler → BUS.send("shutdown_response", {request_id}) ─→ Lead inbox - Lead: consume_lead_inbox → match_response(request_id) → pending_requests[req_id].status = approved -""" - -import os, subprocess, json, time, random, threading -from pathlib import Path -from datetime import datetime -from dataclasses import dataclass, asdict, field - -try: - import readline - readline.parse_and_bind('set bind-tty-special-chars off') -except ImportError: - pass - -from anthropic import Anthropic -from dotenv import load_dotenv - -load_dotenv(override=True) -if os.getenv("ANTHROPIC_BASE_URL"): - os.environ.pop("ANTHROPIC_AUTH_TOKEN", None) - -WORKDIR = Path.cwd() -MEMORY_DIR = WORKDIR / ".memory" -MEMORY_INDEX = MEMORY_DIR / "MEMORY.md" -client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) -MODEL = os.environ["MODEL_ID"] - -# ── Task System (from s12, synced) ── - -TASKS_DIR = WORKDIR / ".tasks" -TASKS_DIR.mkdir(exist_ok=True) - - -@dataclass -class Task: - id: str - subject: str - description: str - status: str # pending | in_progress | completed - owner: str | None - blockedBy: list[str] - - -def _task_path(task_id: str) -> Path: - return TASKS_DIR / f"{task_id}.json" - - -def create_task(subject: str, description: str = "", - blockedBy: list[str] | None = None) -> Task: - task = Task( - id=f"task_{int(time.time())}_{random.randint(0, 9999):04d}", - subject=subject, description=description, - status="pending", owner=None, - blockedBy=blockedBy or [], - ) - save_task(task) - return task - - -def save_task(task: Task): - _task_path(task.id).write_text(json.dumps(asdict(task), indent=2)) - - -def load_task(task_id: str) -> Task: - return Task(**json.loads(_task_path(task_id).read_text())) - - -def list_tasks() -> list[Task]: - return [Task(**json.loads(p.read_text())) - for p in sorted(TASKS_DIR.glob("task_*.json"))] - - -def get_task(task_id: str) -> str: - """Return full task details as JSON.""" - task = load_task(task_id) - return json.dumps(asdict(task), indent=2) - - -def can_start(task_id: str) -> bool: - """Check if all blockedBy dependencies are completed. - Missing dependencies are treated as blocked.""" - task = load_task(task_id) - for dep_id in task.blockedBy: - if not _task_path(dep_id).exists(): - return False - if load_task(dep_id).status != "completed": - return False - return True - - -def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if not can_start(task_id): - deps = [d for d in task.blockedBy - if not _task_path(d).exists() or load_task(d).status != "completed"] - return f"Blocked by: {deps}" - task.owner = owner - task.status = "in_progress" - save_task(task) - print(f" \033[36m[claim] {task.subject} → in_progress (owner: {owner})\033[0m") - return f"Claimed {task.id} ({task.subject})" - - -def complete_task(task_id: str) -> str: - task = load_task(task_id) - if task.status != "in_progress": - return f"Task {task_id} is {task.status}, cannot complete" - task.status = "completed" - save_task(task) - unblocked = [t.subject for t in list_tasks() - if t.status == "pending" and t.blockedBy and can_start(t.id)] - print(f" \033[32m[complete] {task.subject} ✓\033[0m") - msg = f"Completed {task.id} ({task.subject})" - if unblocked: - msg += f"\nUnblocked: {', '.join(unblocked)}" - print(f" \033[33m[unblocked] {', '.join(unblocked)}\033[0m") - return msg - - -# ── Prompt Assembly (from s10, synced) ── - -PROMPT_SECTIONS = { - "identity": "You are a coding agent. Act, don't explain.", - "tools": "Available tools: bash, read_file, write_file, " - "get_task, create_task, list_tasks, claim_task, complete_task, " - "spawn_teammate, send_message, check_inbox, " - "request_shutdown, request_plan, review_plan.", - "workspace": f"Working directory: {WORKDIR}", - "memory": "Relevant memories are injected below when available.", -} - - -def assemble_system_prompt(context: dict) -> str: - sections = [PROMPT_SECTIONS["identity"], - PROMPT_SECTIONS["tools"], - PROMPT_SECTIONS["workspace"]] - memories = context.get("memories", "") - if memories: - sections.append(f"Relevant memories:\n{memories}") - return "\n\n".join(sections) - - -_last_context_key, _last_prompt = None, None - - -def get_system_prompt(context: dict) -> str: - global _last_context_key, _last_prompt - key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str) - if key == _last_context_key and _last_prompt: - return _last_prompt - _last_context_key = key - _last_prompt = assemble_system_prompt(context) - return _last_prompt - - -# ── Tools ── - -def safe_path(p: str) -> Path: - path = (WORKDIR / p).resolve() - if not path.is_relative_to(WORKDIR): - raise ValueError(f"Path escapes workspace: {p}") - return path - - -def run_bash(command: str, run_in_background: bool = False) -> str: - # run_in_background is handled by agent_loop dispatch, not here - try: - r = subprocess.run(command, shell=True, cwd=WORKDIR, - capture_output=True, text=True, timeout=120) - out = (r.stdout + r.stderr).strip() - return out[:50000] if out else "(no output)" - except subprocess.TimeoutExpired: - return "Error: Timeout (120s)" - - -def run_read(path: str, limit: int | None = None) -> str: - try: - lines = safe_path(path).read_text().splitlines() - if limit and limit < len(lines): - lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"] - return "\n".join(lines) - except Exception as e: - return f"Error: {e}" - - -def run_write(path: str, content: str) -> str: - try: - fp = safe_path(path) - fp.parent.mkdir(parents=True, exist_ok=True) - fp.write_text(content) - return f"Wrote {len(content)} bytes to {path}" - except Exception as e: - return f"Error: {e}" - - -# Task tools - -def run_create_task(subject: str, description: str = "", - blockedBy: list[str] | None = None) -> str: - task = create_task(subject, description, blockedBy) - deps = f" (blockedBy: {', '.join(blockedBy)})" if blockedBy else "" - print(f" \033[34m[create] {task.subject}{deps}\033[0m") - return f"Created {task.id}: {task.subject}{deps}" - - -def run_list_tasks() -> str: - tasks = list_tasks() - if not tasks: - return "No tasks. Use create_task to add some." - lines = [] - for t in tasks: - icon = {"pending": "○", "in_progress": "●", - "completed": "✓"}.get(t.status, "?") - deps = f" (blockedBy: {', '.join(t.blockedBy)})" if t.blockedBy else "" - owner = f" [{t.owner}]" if t.owner else "" - lines.append(f" {icon} {t.id}: {t.subject} " - f"[{t.status}]{owner}{deps}") - return "\n".join(lines) - - -def run_get_task(task_id: str) -> str: - try: - return get_task(task_id) - except FileNotFoundError: - return f"Error: Task {task_id} not found" - - -def run_claim_task(task_id: str) -> str: - return claim_task(task_id, owner="agent") - - -def run_complete_task(task_id: str) -> str: - return complete_task(task_id) - - -# ── Background Tasks (from s13, synced) ── - -_bg_counter = 0 -background_tasks: dict[str, dict] = {} -background_results: dict[str, str] = {} -background_lock = threading.Lock() - - -def is_slow_operation(tool_name: str, tool_input: dict) -> bool: - """Fallback heuristic: commands likely to take > 30s.""" - if tool_name != "bash": - return False - cmd = tool_input.get("command", "").lower() - slow_keywords = ["install", "build", "test", "deploy", "compile", - "docker build", "pip install", "npm install", - "cargo build", "pytest", "make"] - return any(kw in cmd for kw in slow_keywords) - - -def should_run_background(tool_name: str, tool_input: dict) -> bool: - """Model explicit request takes priority; fallback to heuristic.""" - if tool_input.get("run_in_background"): - return True - return is_slow_operation(tool_name, tool_input) - - -def start_background_task(block) -> str: - """Run tool in a daemon thread. Returns background task ID.""" - global _bg_counter - _bg_counter += 1 - bg_id = f"bg_{_bg_counter:04d}" - cmd = block.input.get("command", block.name) - - def worker(): - result = execute_tool(block) - with background_lock: - background_tasks[bg_id]["status"] = "completed" - background_results[bg_id] = result - - with background_lock: - background_tasks[bg_id] = { - "tool_use_id": block.id, - "command": cmd, - "status": "running", - } - threading.Thread(target=worker, daemon=True).start() - print(f" \033[33m[background] dispatched {bg_id}: {cmd[:40]}\033[0m") - return bg_id - - -def collect_background_results() -> list[str]: - """Collect completed background results as task_notification messages.""" - with background_lock: - ready_ids = [bid for bid, task in background_tasks.items() - if task["status"] == "completed"] - notifications = [] - for bg_id in ready_ids: - with background_lock: - task = background_tasks.pop(bg_id) - output = background_results.pop(bg_id, "") - summary = output[:200] if len(output) > 200 else output - notifications.append( - f"\n" - f" {bg_id}\n" - f" completed\n" - f" {task['command']}\n" - f" {summary}\n" - f"") - print(f" \033[32m[background done] {bg_id}: " - f"{task['command'][:40]} ({len(output)} chars)\033[0m") - return notifications - - -# ── MessageBus (from s15) ── - -MAILBOX_DIR = WORKDIR / ".mailboxes" -MAILBOX_DIR.mkdir(exist_ok=True) - - -class MessageBus: - """File-based message bus. Each agent has a .jsonl inbox. - Read is destructive: read_text + unlink (consumes messages). - Teaching version: no file locking; real CC uses proper-lockfile.""" - - def send(self, from_agent: str, to_agent: str, content: str, - msg_type: str = "message", metadata: dict = None): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time(), "metadata": metadata or {}} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") - print(f" \033[33m[bus] {from_agent} → {to_agent}: " - f"({msg_type}) {content[:50]}\033[0m") - - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" - if not inbox.exists(): - return [] - msgs = [json.loads(line) for line in inbox.read_text().splitlines() - if line.strip()] - inbox.unlink() # consume: read + delete - return msgs - - -BUS = MessageBus() -active_teammates: dict[str, bool] = {} - -# ── Protocol State (s16 new) ── - -@dataclass -class ProtocolState: - request_id: str - type: str # "shutdown" | "plan_approval" - sender: str - target: str - status: str # pending | approved | rejected - payload: str # plan text or shutdown reason - created_at: float = field(default_factory=time.time) - - -pending_requests: dict[str, ProtocolState] = {} - - -def new_request_id() -> str: - return f"req_{random.randint(0, 999999):06d}" - - -def match_response(response_type: str, request_id: str, approve: bool): - """Correlate a response to the original request via request_id. - Validates that response_type matches the request type.""" - state = pending_requests.get(request_id) - if not state: - print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") - return - # Validate response type matches request type - if state.type == "shutdown" and response_type != "shutdown_response": - print(f" \033[31m[protocol] type mismatch: expected shutdown_response, " - f"got {response_type}\033[0m") - return - if state.type == "plan_approval" and response_type != "plan_approval_response": - print(f" \033[31m[protocol] type mismatch: expected plan_approval_response, " - f"got {response_type}\033[0m") - return - if state.status != "pending": - print(f" \033[33m[protocol] {request_id} already {state.status}, " - f"ignoring duplicate\033[0m") - return - state.status = "approved" if approve else "rejected" - icon = "✓" if approve else "✗" - color = "32" if approve else "31" - print(f" \033[{color}m[protocol] {state.type} {icon} " - f"({request_id}: {state.status})\033[0m") - - -# ── Unified Lead Inbox Consumer (s16 fix) ── -# Both check_inbox tool and main loop call this function. -# Protocol responses are routed via match_response before returning. - -def consume_lead_inbox(route_protocol: bool = True) -> list[dict]: - """Read Lead's inbox. Route protocol responses, return all messages. - Called by both run_check_inbox() and main loop to avoid - messages being consumed without protocol routing.""" - msgs = BUS.read_inbox("lead") - if not msgs: - return [] - if route_protocol: - for msg in msgs: - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - msg_type = msg.get("type", "") - if req_id and msg_type.endswith("_response"): - approve = meta.get("approve", False) - match_response(msg_type, req_id, approve) - return msgs - - -# ── Teammate Thread (s16: idle loop + dispatch) ── - -def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - """Spawn a teammate agent in a background thread. - Uses idle loop: after each LLM turn, waits for inbox messages - (shutdown_request, new task) instead of exiting.""" - if name in active_teammates: - return f"Teammate '{name}' already exists" - - system = (f"You are '{name}', a {role}. " - f"Use tools to complete tasks. " - f"Check inbox for protocol messages (shutdown_request, etc).") - - def handle_inbox_message(name: str, msg: dict, messages: list) -> bool: - """Dispatch incoming protocol messages by type. - Returns True if teammate should stop.""" - msg_type = msg.get("type", "message") - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - - if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down gracefully.", - "shutdown_response", - {"request_id": req_id, "approve": True}) - print(f" \033[35m[protocol] {name} approved shutdown " - f"({req_id})\033[0m") - return True # stop the loop - - if msg_type == "plan_approval_response": - approve = meta.get("approve", False) - if approve: - messages.append({"role": "user", - "content": f"[Plan approved] Proceed with the task."}) - else: - messages.append({"role": "user", - "content": f"[Plan rejected] Feedback: {msg['content']}"}) - - return False # continue - - def run(): - messages = [{"role": "user", "content": prompt}] - sub_tools = [ - {"name": "bash", "description": "Run a shell command.", - "input_schema": {"type": "object", - "properties": {"command": {"type": "string"}}, - "required": ["command"]}}, - {"name": "read_file", "description": "Read file.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}}, - "required": ["path"]}}, - {"name": "write_file", "description": "Write file.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["path", "content"]}}, - {"name": "send_message", - "description": "Send message to another agent.", - "input_schema": {"type": "object", - "properties": {"to": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["to", "content"]}}, - {"name": "submit_plan", - "description": "Submit a plan for Lead approval.", - "input_schema": {"type": "object", - "properties": {"plan": {"type": "string"}}, - "required": ["plan"]}}, - ] - sub_handlers = { - "bash": run_bash, "read_file": run_read, "write_file": run_write, - "send_message": lambda to, content: (BUS.send(name, to, content), - "Sent")[1], - "submit_plan": lambda plan: _teammate_submit_plan(name, plan), - } - - shutdown_requested = False - while not shutdown_requested: - # Check inbox for protocol messages - inbox = BUS.read_inbox(name) - should_stop = False - non_protocol = [] - for msg in inbox: - if msg.get("type") in ("shutdown_request", "plan_approval_response"): - should_stop = handle_inbox_message(name, msg, messages) - if should_stop: - break - else: - non_protocol.append(msg) - if should_stop: - shutdown_requested = True - break - if non_protocol: - inbox_json = json.dumps(non_protocol) - messages.append({"role": "user", - "content": "" + inbox_json + ""}) - - # LLM turn - try: - response = client.messages.create( - model=MODEL, system=system, messages=messages[-20:], - tools=sub_tools, max_tokens=8000) - except Exception: - break - - messages.append({"role": "assistant", "content": response.content}) - if response.stop_reason != "tool_use": - # Idle: wait for inbox messages instead of exiting - # Real CC sends idle_notification to Lead here - while not shutdown_requested: - time.sleep(1) - inbox = BUS.read_inbox(name) - if not inbox: - continue - for msg in inbox: - if msg.get("type") in ("shutdown_request", "plan_approval_response"): - should_stop = handle_inbox_message(name, msg, messages) - if should_stop: - shutdown_requested = True - break - else: - non_protocol.append(msg) - if shutdown_requested: - break - if non_protocol: - inbox_json = json.dumps(non_protocol) - messages.append({"role": "user", - "content": "" + inbox_json + ""}) - break # back to LLM turn with new messages - - # Execute tool calls - results = [] - for block in response.content: - if block.type == "tool_use": - handler = sub_handlers.get(block.name) - output = handler(**block.input) if handler else "Unknown" - results.append({"type": "tool_result", - "tool_use_id": block.id, - "content": str(output)}) - messages.append({"role": "user", "content": results}) - - # Send final summary to Lead - summary = "Done." - for msg in reversed(messages): - if msg["role"] == "assistant" and isinstance(msg["content"], list): - for b in msg["content"]: - if getattr(b, "type", None) == "text": - summary = b.text - break - else: - continue - break - BUS.send(name, "lead", summary, "result") - active_teammates.pop(name, None) - print(f" \033[32m[teammate] {name} finished\033[0m") - - active_teammates[name] = True - threading.Thread(target=run, daemon=True).start() - print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") - return f"Teammate '{name}' spawned as {role}" - - -def _teammate_submit_plan(from_name: str, plan: str) -> str: - """Teammate submits a plan to Lead for approval. - - Note: This is a protocol-level request, not a code-level gate. - After submitting, the teammate's thread continues running — it can - still call bash/write/etc. Real enforcement relies on the model - waiting for the approval response before acting. Code-level tool - gating would require blocking the teammate's tool dispatch until - approval arrives. - """ - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="plan_approval", - sender=from_name, target="lead", - status="pending", payload=plan) - BUS.send(from_name, "lead", plan, - "plan_approval_request", - {"request_id": req_id}) - return f"Plan submitted ({req_id}). Waiting for approval..." - - -# ── Lead Protocol Tools (s16 new) ── - -def run_request_shutdown(teammate: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="shutdown", - sender="lead", target=teammate, - status="pending", payload="") - BUS.send("lead", teammate, "Please shut down gracefully.", - "shutdown_request", - {"request_id": req_id}) - print(f" \033[35m[protocol] shutdown_request → {teammate} " - f"({req_id})\033[0m") - return f"Shutdown request sent to {teammate} (req: {req_id})" - - -def run_request_plan(teammate: str, task: str) -> str: - """Lead asks a teammate to submit a plan for a task.""" - BUS.send("lead", teammate, f"Please submit a plan for: {task}", - "message") - return f"Asked {teammate} to submit a plan" - - -def run_review_plan(request_id: str, approve: bool, feedback: str = "") -> str: - state = pending_requests.get(request_id) - if not state: - return f"Request {request_id} not found" - if state.status != "pending": - return f"Request {request_id} already {state.status}" - state.status = "approved" if approve else "rejected" - BUS.send("lead", state.sender, feedback or ("Approved" if approve else "Rejected"), - "plan_approval_response", - {"request_id": request_id, "approve": approve}) - icon = "✓" if approve else "✗" - print(f" \033[32m[protocol] plan {icon} ({request_id})\033[0m") - return f"Plan {'approved' if approve else 'rejected'} ({request_id})" - - -# ── Other Lead Tool Handlers ── - -def run_spawn_teammate(name: str, role: str, prompt: str) -> str: - return spawn_teammate_thread(name, role, prompt) - - -def run_send_message(to: str, content: str) -> str: - BUS.send("lead", to, content) - return f"Sent to {to}" - - -def run_check_inbox() -> str: - """Check Lead's inbox. Routes protocol responses via match_response.""" - msgs = consume_lead_inbox(route_protocol=True) - if not msgs: - return "(inbox empty)" - lines = [] - for m in msgs: - meta = m.get("metadata", {}) - req_id = meta.get("request_id", "") - tag = f" [{m['type']} req:{req_id}]" if req_id else f" [{m['type']}]" - lines.append(f" [{m['from']}]{tag} {m['content'][:200]}") - return "\n".join(lines) - - -# ── Tool Dispatch ── - -def execute_tool(block) -> str: - """Execute a tool call block, return output.""" - handler = { - "bash": run_bash, "read_file": run_read, "write_file": run_write, - "create_task": run_create_task, "list_tasks": run_list_tasks, - "get_task": run_get_task, "claim_task": run_claim_task, - "complete_task": run_complete_task, - "spawn_teammate": run_spawn_teammate, - "send_message": run_send_message, "check_inbox": run_check_inbox, - "request_shutdown": run_request_shutdown, - "request_plan": run_request_plan, "review_plan": run_review_plan, - }.get(block.name) - if handler: - return handler(**block.input) - return f"Unknown tool: {block.name}" - - -# ── Tool Definitions ── - -TOOLS = [ - {"name": "bash", "description": "Run a shell command.", - "input_schema": {"type": "object", - "properties": { - "command": {"type": "string"}, - "run_in_background": {"type": "boolean"}}, - "required": ["command"]}}, - {"name": "read_file", "description": "Read file contents.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "limit": {"type": "integer"}}, - "required": ["path"]}}, - {"name": "write_file", "description": "Write content to a file.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["path", "content"]}}, - {"name": "create_task", - "description": "Create a new task with optional blockedBy dependencies.", - "input_schema": {"type": "object", - "properties": { - "subject": {"type": "string"}, - "description": {"type": "string"}, - "blockedBy": {"type": "array", - "items": {"type": "string"}}}, - "required": ["subject"]}}, - {"name": "list_tasks", - "description": "List all tasks with status, owner, and dependencies.", - "input_schema": {"type": "object", "properties": {}, - "required": []}}, - {"name": "get_task", - "description": "Get full details of a specific task by ID.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "claim_task", - "description": "Claim a pending task. Sets owner, changes status to in_progress.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "complete_task", - "description": "Complete an in-progress task. Reports unblocked downstream tasks.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "spawn_teammate", - "description": "Spawn a teammate agent in a background thread.", - "input_schema": {"type": "object", - "properties": { - "name": {"type": "string"}, - "role": {"type": "string"}, - "prompt": {"type": "string"}}, - "required": ["name", "role", "prompt"]}}, - {"name": "send_message", - "description": "Send message to a teammate via MessageBus.", - "input_schema": {"type": "object", - "properties": {"to": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["to", "content"]}}, - {"name": "check_inbox", - "description": "Check Lead's inbox. Routes protocol responses automatically.", - "input_schema": {"type": "object", "properties": {}, - "required": []}}, - {"name": "request_shutdown", - "description": "Request a teammate to shut down gracefully.", - "input_schema": {"type": "object", - "properties": {"teammate": {"type": "string"}}, - "required": ["teammate"]}}, - {"name": "request_plan", - "description": "Ask a teammate to submit a plan for review.", - "input_schema": {"type": "object", - "properties": {"teammate": {"type": "string"}, - "task": {"type": "string"}}, - "required": ["teammate", "task"]}}, - {"name": "review_plan", - "description": "Approve or reject a submitted plan by request_id.", - "input_schema": {"type": "object", - "properties": { - "request_id": {"type": "string"}, - "approve": {"type": "boolean"}, - "feedback": {"type": "string"}}, - "required": ["request_id", "approve"]}}, -] - - -# ── Context ── - -def update_context(context: dict, messages: list) -> dict: - """Derive context from real state.""" - memories = "" - if MEMORY_INDEX.exists(): - content = MEMORY_INDEX.read_text().strip() - if content: - memories = content - return { - "enabled_tools": [t["name"] for t in TOOLS], - "workspace": str(WORKDIR), - "memories": memories, - } - - -# ── Agent Loop ── - -def agent_loop(messages: list, context: dict): - system = get_system_prompt(context) - while True: - try: - response = client.messages.create( - model=MODEL, system=system, messages=messages, - tools=TOOLS, max_tokens=8000) - except Exception as e: - messages.append({"role": "assistant", "content": [ - {"type": "text", - "text": f"[Error] {type(e).__name__}: {e}"}]}) - return - - messages.append({"role": "assistant", "content": response.content}) - if response.stop_reason != "tool_use": - return - - results = [] - for block in response.content: - if block.type != "tool_use": - continue - print(f"\033[36m> {block.name}\033[0m") - - if should_run_background(block.name, block.input): - bg_id = start_background_task(block) - results.append({"type": "tool_result", - "tool_use_id": block.id, - "content": f"[Background task {bg_id} started] " - f"Result will be available when complete."}) - else: - output = execute_tool(block) - print(str(output)[:300]) - results.append({"type": "tool_result", - "tool_use_id": block.id, - "content": output}) - - # Merge background tool results + notifications into one user message - user_content = list(results) - bg_notifications = collect_background_results() - if bg_notifications: - for notif in bg_notifications: - user_content.append({"type": "text", "text": notif}) - messages.append({"role": "user", "content": user_content}) - context = update_context(context, messages) - system = get_system_prompt(context) - - -if __name__ == "__main__": - print("s16: team protocols") - print("Enter a question, press Enter to send. Type q to quit.\n") - history = [] - context = update_context({}, []) - while True: - try: - query = input("\033[36ms16 >> \033[0m") - except (EOFError, KeyboardInterrupt): - break - if query.strip().lower() in ("q", "exit", ""): - break - history.append({"role": "user", "content": query}) - agent_loop(history, context) - context = update_context(context, history) - for block in history[-1]["content"]: - if getattr(block, "type", None) == "text": - print(block.text) - elif isinstance(block, dict) and block.get("type") == "text": - print(block.get("text", "")) - - # Check inbox → route protocol + inject into history - inbox_msgs = consume_lead_inbox(route_protocol=True) - if inbox_msgs: - inbox_text = "\n".join( - f"From {m['from']}: {m['content'][:200]}" for m in inbox_msgs) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) - print(f"\n\033[33m[Inbox: {len(inbox_msgs)} messages injected]\033[0m") - print() diff --git a/s17_autonomous_agents/README.ja.md b/s17_autonomous_agents/README.ja.md deleted file mode 100644 index 3762fc22..00000000 --- a/s17_autonomous_agents/README.ja.md +++ /dev/null @@ -1,273 +0,0 @@ -# s17: Autonomous Agents — ボードを見て、自分で認領 - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s15 → s16 → `s17` → [s18](../s18_worktree_isolation/) → s19 → s20 → s21 → s22 - -> *"ボードを見て、自分で認領"* — 空き時にポーリング、仕事があれば開始。 -> -> **Harness 層**: 自治 — チームメイトが自己組織化、リーダーの割り当て不要。 - -> **コアと任意項目:** アイドル時の仕事発見と原子的な claim が本章の中心。アイデンティティ再注入は教育版の高度な補助で、初回は読み飛ばしてよい。 - ---- - -## 課題 - -s16 のチームメイトは通信でき、シャットダウンハンドシェイクもできる。しかし各チームメイトは Lead がタスクを割り当てるのを待つ——ボードに 10 個の未認領タスクがあれば、Lead は 10 回手動で assign しなければならない。これはスケールしない。チームメイトは自分でタスクボードを見て、未認領のタスクを見つけて認領し、終わったら次を探すべき。 - ---- - -## ソリューション - -![Autonomous Agents Overview](images/autonomous-agents-overview.ja.svg) - -S16 の教学版 MessageBus とプロトコルツールを踏襲。本章の追加:**idle_poll**(空き時に 5 秒ごとにポーリング)、**scan_unclaimed_tasks**(ボード上の認領可能なタスクをスキャン)、**自動認領**(見つけたら即座に claim、Lead 不要)。 - -チームメイトのライフサイクルは 2 フェーズから 3 フェーズに: - -| フェーズ | 動作 | 終了条件 | -|----------|------|---------| -| WORK | inbox → LLM → ツールループ | `stop_reason != tool_use` | -| IDLE | 5s ポーリング inbox + タスクボード | 60s タイムアウト | -| SHUTDOWN | summary を送信、終了 | — | - ---- - -## 仕組み - -### idle_poll: 空き時ポーリング - -チームメイトはタスク完了後も終了せず、IDLE フェーズに入る——5 秒ごとに新しい仕事がないか確認: - -```python -IDLE_POLL_INTERVAL = 5 # seconds -IDLE_TIMEOUT = 60 # seconds - -def idle_poll(name, messages, role) -> str: - """Return 'work', 'shutdown', or 'timeout'.""" - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - - # ① 受信箱確認(優先) - inbox = BUS.read_inbox(name) - if inbox: - # shutdown_request は即座に処理 - for msg in inbox: - if msg.get("type") == "shutdown_request": - # ... shutdown_response 返信 - return "shutdown" - # 通常メッセージ:コンテキストに注入、WORK に戻る - messages.append(...) - return "work" - - # ② タスクボードスキャン - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task = unclaimed[0] - result = claim_task(task["id"], name) - if "Claimed" in result: - messages.append(...) - return "work" - return "timeout" -``` - -inbox を優先(shutdown_request 等のプロトコルメッセージの可能性)、タスクボードが次。IDLE フェーズで shutdown_request を受信すると即座に返信して終了し、次の WORK を待つ必要がない。 - -### scan_unclaimed_tasks: タスクボードスキャン - -pending 状態、owner なし、全依存関係完了(`can_start`)のタスクを検索: - -```python -def scan_unclaimed_tasks() -> list[dict]: - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed -``` - -3 つの条件:pending であること、owner がないこと、全 blockedBy 依存が完了していること。`can_start` は依存タスクの状態を確認——依存があるからといってタスクを開始できないわけではなく、未解決の依存のみがブロックする。教学版はファイル名順で最初のものを選択、CC はファイルロックで複数チームメイトの同時認領を防止。 - -### claim_task: owner チェック - -自動認領時に claim 結果を確認し、失敗を成功として扱わない: - -```python -def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - return f"Blocked by: {deps}" - task.owner = owner - task.status = "in_progress" - save_task(task) - return f"Claimed {task.id} ({task.subject})" -``` - -教学版にはファイルロックがないため、並行認領で競合する可能性がある。しかし `task.owner` チェックで最も明白な「後書き上書き」問題を回避。CC は `proper-lockfile` でタスクファイルを保護、`claimTask` はファイルロック内で read-modify-write を実行(`utils/tasks.ts:541-612`)。 - -### チームメイトライフサイクル: WORK → IDLE → SHUTDOWN - -s16 のチームメイトはタスク完了後に終了。s17 は IDLE フェーズを追加——外側ループで WORK → IDLE を繰り返す: - -```python -# 外側ループ: WORK → IDLE サイクル -while True: - # WORK フェーズ: 内側ループ(最大 10 ラウンド LLM 呼び出し) - for _ in range(10): - # inbox 確認、プロトコルメッセージ処理、LLM 呼び出し、ツール実行 - ... - if response.stop_reason != "tool_use": - break # WORK フェーズ終了 - - # IDLE フェーズ - idle_result = idle_poll(name, messages, role) - if idle_result == "shutdown": - break - if idle_result == "timeout": - break # 60s タイムアウト → SHUTDOWN - -# SHUTDOWN: summary を Lead に送信 -BUS.send(name, "lead", summary, "result") -``` - -主要設計: -- **外側 while True**:WORK と IDLE がタイムアウトまたはシャットダウン要求まで交互に続く -- **内側 for 10**:WORK フェーズは最大 10 ラウンドの LLM 呼び出し(無限ループ防止) -- **IDLE タイムアウト 60 秒**:12 回ポーリング × 5 秒 = 60 秒。タイムアウト後 summary を送信して終了 -- **shutdown_request は両フェーズで応答**:WORK フェーズは `handle_inbox_message` でディスパッチ、IDLE フェーズは `idle_poll` が直接確認して返信 - -### 発展(任意):アイデンティティ再注入 - -autoCompact(s08)後、チームメイトの messages リストが要約に圧縮される可能性がある。新しい WORK フェーズに入るたびに確認: - -```python -if len(messages) <= 3: - messages.insert(0, {"role": "user", - "content": f"You are '{name}', role: {role}. " - f"Continue your work."}) -``` - -メッセージが短い場合、圧縮が発生したことを示す——身份情報を再注入。真实 CC では context compaction が system prompt を保持、教学版の簡略実装は手動処理が必要。 - -### consume_lead_inbox: 統一 inbox コンシューマ - -`check_inbox` ツールとメインループ末尾の両方が同じ `consume_lead_inbox()` 関数を呼び出す:プロトコル response を先にルーティングして状態を更新し、全メッセージを Lead の会話履歴に注入。チームメイトからの summary/result は端末に表示されるだけでなく、Lead の LLM も確認して次のステップを調整可能。 - -### 組み合わせて実行 - -``` -1. Lead: "バックエンド構築——タスクが多すぎる、チームメイトに自己認領させる" -2. Lead → create_task("データベーススキーマを作成") -3. Lead → create_task("API ルートを書く") -4. Lead → create_task("ユニットテストを書く") -5. Lead → spawn_teammate("alice", "backend", "あなたはバックエンド開発者") -6. Lead → spawn_teammate("bob", "backend", "あなたはバックエンド開発者") - -7. alice スレッド起動 → WORK: 初期 inbox なし → 空転 → IDLE -8. bob スレッド起動 → WORK: 初期 inbox なし → 空転 → IDLE - -9. alice IDLE ポーリング 1 回目 → scan_unclaimed → "データベーススキーマを作成" を発見 -10. alice → claim_task → "データベーススキーマを作成" → WORK に戻る -11. bob IDLE ポーリング 1 回目 → scan_unclaimed → "API ルートを書く" を発見 -12. bob → claim_task → "API ルートを書く" → WORK に戻る - -13. alice WORK: write_file("schema.sql", ...) → complete_task → WORK 終了 -14. alice IDLE → scan → "ユニットテストを書く" → claim → WORK -15. alice WORK: write_file("test_api.py", ...) → complete_task → WORK 終了 -16. alice IDLE → 60s 新しいタスクなし → SHUTDOWN - -17. bob も同様のフロー → 完了 → SHUTDOWN -18. Lead consume_lead_inbox → alice と bob の summary を確認 -``` - -2 人のチームメイトが並行して認領・作業。Lead はタスクを作成してチームメイトを起動するだけで、手動割り当て不要。 - ---- - -## s16 からの変更 - -| コンポーネント | 変更前 (s16) | 変更後 (s17) | -|--------------|------------|------------| -| タスク割り当て | Lead が手動 assign | チームメイトが自動認領(can_start で依存確認) | -| チームメイト状態 | WORK → IDLE(1s 間隔で inbox をポーリング)→ WORK / SHUTDOWN | WORK → IDLE(5s 間隔で inbox + タスクボードをポーリング、60s タイムアウト)→ WORK / SHUTDOWN | -| claim_task | owner チェックなし | 既に owner があるタスクを拒否 | -| IDLE フェーズシャットダウン | shutdown_request を受信後に終了 | 即座にシャットダウンをディスパッチして終了 | -| Lead inbox | consume_lead_inbox がプロトコル応答をルーティングしコンテキストに注入 | consume_lead_inbox 機構を踏襲 | -| 新規関数 | consume_lead_inbox は既存 | idle_poll, scan_unclaimed_tasks(consume_lead_inbox を踏襲) | -| 身份保持 | system prompt のみ | 圧縮後に自動再注入 | -| Lead ツール | 14 | 14(変更なし) | -| チームメイトツール | 5 | 8(+ list_tasks, claim_task, complete_task) | -| チームメイト終了条件 | WORK 完了後 IDLE に入り、shutdown_request を待って終了(タイムアウトなし) | 60s アイドルタイムアウトまたは shutdown_request 受信で終了 | - ---- - -## 試してみる - -```sh -cd learn-claude-code -python s17_autonomous_agents/code.py -``` - -以下のプロンプトを試してください: - -`Create 3 tasks on the board, then spawn alice and bob. Watch them auto-claim and work.` - -観察ポイント:チームメイトは未割り当てのタスクを自動認領したか?blockedBy 依存のあるタスクは依存完了後に正しく認領されたか?アイドルタイムアウトでシャットダウンしたか?IDLE フェーズで shutdown_request に即座に応答したか?`.tasks/` ディレクトリのタスク状態はどう変化したか? - ---- - -## 次の章 - -チームメイトが自己組織化した。しかし Alice も Bob も同じディレクトリで作業——Alice が `config.py` を編集し、Bob も `config.py` を編集して互いに上書きしてしまう。 - -s18 Worktree Isolation → 各タスクに専用の作業ディレクトリ、競合なし。 - -
-CC ソースコード深掘り - -> 教学注記:本章の idle_poll + auto-claim 機構は教学設計であり、統一ポーリング関数で「空き時に仕事を探す」をデモ。CC の実際の実装は複数機構の組み合わせだが、目標は同じ——Lead の手動割り当て負担を軽減。 - -### 一、CC の空き機構:組み合わせ路径、単一ポーリングではない - -教学版は 1 つの `idle_poll()` で空き時の inbox 確認とタスク認領を統一処理。CC の実際の実装は 4 つの機構の組み合わせ: - -**idle_notification**:チームメイトが 1 ラウンドの作業を完了後、`sendIdleNotification()`(`inProcessRunner.ts:569-589`)が Lead に空き通知を送信。Lead はチームメイトが利用可能であることを知り、新しいタスクを割り当てたりシャットダウンを要求可能。 - -**mailbox ポーリング**:`waitForNextPromptOrShutdown()`(`inProcessRunner.ts:689-868`)は **500ms ポーリングループ**で、3 つのソースを継続チェック:pending user messages、mailbox ファイルメッセージ、task list。shutdown_request は優先処理(`inProcessRunner.ts:768-804`)、通常メッセージによる飢餓を防止。 - -**task watcher**:`useTaskListWatcher`(`hooks/useTaskListWatcher.ts:34-189`)が `fs.watch()` で `.claude/tasks/` ディレクトリの変化を監視、1 秒 debounce で新タスク作成や依存アンロック時にチェックをトリガー。依存判断(`L197-207`)は「blockedBy に未完了タスクがない」で、「blockedBy が空」ではない。 - -**能動 claim**:ポーリングループ内でも `tryClaimNextTask()`(`inProcessRunner.ts:853-860`)を呼び出し——待機中に task list から能動的にタスクを認領。したがって「チームメイトは能動的にタスクをポーリングしない」は不正確、CC は受動通知と能動認領の両方を持つ。 - -### 二、タスク認領:ファイルロック + 原子操作 - -`claimTask()`(`utils/tasks.ts:541-612`)は `proper-lockfile` のタスクファイルロックを使用、ロック内で read-check-modify-write を実行。チェック項目:owner が既に存在(`L575-576`)、完了済み(`L580-581`)、blockedBy に未完了タスクがあるか(`L585-594`)。`claimTaskWithBusyCheck()`(`utils/tasks.ts:614-692`)はタスクリストレベルロックを使用、busy check と claim を原子操作にして TOCTOU を回避。 - -`findAvailableTask()`(`inProcessRunner.ts:595-604`)の依存判断も「全 blockedBy 完了」で、`task.blockedBy.every(id => !unresolvedTaskIds.has(id))` で実装。`tryClaimNextTask()`(`inProcessRunner.ts:624-657`)は認領後 status を `in_progress` に更新、UI に即座に反映。 - -### 三、教学版 vs CC 対比 - -| 次元 | 教学版 (s17) | CC | -|------|-------------|-----| -| 空き機構 | idle_poll 統一ポーリング(5s) | idle_notification + 500ms mailbox ポーリング + task watcher | -| タスク発見 | scan_unclaimed_tasks(ポーリング) | useTaskListWatcher(ファイル監視)+ tryClaimNextTask(能動ポーリング) | -| 依存チェック | can_start(全 blockedBy 完了) | findAvailableTask(同じセマンティクス) | -| 並行安全性 | owner チェック(ファイルロックなし) | proper-lockfile タスクロック + タスクリストロック | -| shutdown 処理 | IDLE 直接ディスパッチ、WORK は handle_inbox_message | 500ms ポーリングループで shutdown_request を優先 | -| タイムアウト終了 | 60s 新しいタスクなし | 固定タイムアウトなし、Lead 手動 shutdown | -| 身份保持 | messages 長さ検出 | context compaction が system prompt を保持 | -| claim 失敗処理 | 戻り値を確認、失敗時はスキップ | ファイルロックで原子性を保証 | - -教学版の `idle_poll()` は CC の 4 つの機構を 1 つのポーリング関数に統合——核心セマンティクス(空き時に仕事を探す、依存アンロック後に認領、shutdown 優先)が一致するため、合理的な簡略化。 - -
- - diff --git a/s17_autonomous_agents/README.md b/s17_autonomous_agents/README.md deleted file mode 100644 index 7d46633e..00000000 --- a/s17_autonomous_agents/README.md +++ /dev/null @@ -1,273 +0,0 @@ -# s17: Autonomous Agents — Check the Board, Claim the Task - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s15 → s16 → `s17` → [s18](../s18_worktree_isolation/) → s19 → s20 → s21 → s22 - -> *"Check the board, claim the task"* — poll when idle, work when found. -> -> **Harness Layer**: Autonomy — Self-organizing teammates, no leader assignment needed. - -> **Core vs optional:** idle work discovery and atomic claiming are the lesson's core. Identity re-injection is an advanced teaching workaround and may be skipped on a first pass. - ---- - -## The Problem - -s16's teammates can communicate and handshake shutdown. But each teammate waits for Lead to assign tasks — with 10 unclaimed tasks on the board, Lead has to manually assign 10 times. This doesn't scale. Teammates should check the task board themselves, claim unowned tasks, and look for the next one when done. - ---- - -## The Solution - -![Autonomous Agents Overview](images/autonomous-agents-overview.en.svg) - -Carries forward S16's teaching-version MessageBus and protocol tools. This chapter adds: **idle_poll** (poll every 5 seconds when idle), **scan_unclaimed_tasks** (scan the board for claimable tasks), **auto-claim** (claim on sight, no Lead needed). - -Teammate lifecycle expands from two phases to three: - -| Phase | Behavior | Exit condition | -|-------|----------|----------------| -| WORK | inbox → LLM → tool loop | `stop_reason != tool_use` | -| IDLE | 5s poll inbox + task board | 60s timeout | -| SHUTDOWN | Send summary, exit | — | - ---- - -## How It Works - -### idle_poll: Idle Polling - -After completing a task, the teammate doesn't exit. It enters the IDLE phase — checking every 5 seconds for new work: - -```python -IDLE_POLL_INTERVAL = 5 # seconds -IDLE_TIMEOUT = 60 # seconds - -def idle_poll(name, messages, role) -> str: - """Return 'work', 'shutdown', or 'timeout'.""" - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - - # ① Check inbox (priority) - inbox = BUS.read_inbox(name) - if inbox: - # shutdown_request handled immediately - for msg in inbox: - if msg.get("type") == "shutdown_request": - # ... reply shutdown_response - return "shutdown" - # Regular messages: inject into context, return to WORK - messages.append(...) - return "work" - - # ② Scan task board - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task = unclaimed[0] - result = claim_task(task["id"], name) - if "Claimed" in result: - messages.append(...) - return "work" - return "timeout" -``` - -Inbox takes priority (may contain protocol messages like shutdown_request), task board second. A shutdown_request received during IDLE is dispatched immediately — no need to wait for the next WORK phase. - -### scan_unclaimed_tasks: Scan the Task Board - -Find tasks that are pending, unowned, with all dependencies completed (`can_start`): - -```python -def scan_unclaimed_tasks() -> list[dict]: - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed -``` - -Three conditions: must be pending, no owner, all blockedBy dependencies completed. `can_start` checks dependency task status — having dependencies doesn't mean the task can't start, only unresolved dependencies block it. Teaching version picks the first by filename; CC uses file locks to prevent multiple teammates from claiming the same task. - -### claim_task: Owner Check - -Auto-claim checks the claim result, not treating failure as success: - -```python -def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - return f"Blocked by: {deps}" - task.owner = owner - task.status = "in_progress" - save_task(task) - return f"Claimed {task.id} ({task.subject})" -``` - -Teaching version has no file locks, so concurrent claims may still race. But the `task.owner` check avoids the most obvious "last writer wins" problem. CC uses `proper-lockfile` to protect task files, with `claimTask` doing read-modify-write inside a file lock (`utils/tasks.ts:541-612`). - -### Teammate Lifecycle: WORK → IDLE → SHUTDOWN - -s16's teammates exit after finishing. s17 adds the IDLE phase — teammates cycle through WORK → IDLE in an outer loop: - -```python -# Outer loop: WORK → IDLE cycle -while True: - # WORK phase: inner loop (max 10 LLM rounds) - for _ in range(10): - # Check inbox, dispatch protocol, call LLM, execute tools - ... - if response.stop_reason != "tool_use": - break # WORK phase ends - - # IDLE phase - idle_result = idle_poll(name, messages, role) - if idle_result == "shutdown": - break - if idle_result == "timeout": - break # 60s timeout → SHUTDOWN - -# SHUTDOWN: send summary to Lead -BUS.send(name, "lead", summary, "result") -``` - -Key design: -- **Outer while True**: WORK and IDLE alternate until timeout or shutdown request -- **Inner for 10**: WORK phase caps at 10 LLM rounds (prevents infinite loops) -- **IDLE timeout 60s**: 12 polls × 5s = 60s. Timeout sends summary and exits -- **shutdown_request works in both phases**: WORK phase dispatches via `handle_inbox_message`; IDLE phase's `idle_poll` checks and replies directly - -### Advanced (Optional): Identity Re-injection - -After autoCompact (s08), a teammate's messages list may be compressed into a summary. On each new WORK phase entry, check: - -```python -if len(messages) <= 3: - messages.insert(0, {"role": "user", - "content": f"You are '{name}', role: {role}. " - f"Continue your work."}) -``` - -Short messages suggest compression happened — re-inject identity. In real CC, context compaction preserves the system prompt; the teaching version's simplified implementation needs manual handling. - -### consume_lead_inbox: Unified Inbox Consumer - -Both the `check_inbox` tool and the main loop call the same `consume_lead_inbox()` function: route protocol responses to update state first, then inject all messages into Lead's conversation history. Teammates' summaries and results don't just print to terminal — Lead's LLM can see them and coordinate next steps. - -### Putting It Together - -``` -1. Lead: "Build the backend — too many tasks, let teammates self-claim" -2. Lead → create_task("Create database schema") -3. Lead → create_task("Write API routes") -4. Lead → create_task("Write unit tests") -5. Lead → spawn_teammate("alice", "backend", "You are a backend developer") -6. Lead → spawn_teammate("bob", "backend", "You are a backend developer") - -7. alice thread starts → WORK: no initial inbox → spins → IDLE -8. bob thread starts → WORK: no initial inbox → spins → IDLE - -9. alice IDLE poll 1 → scan_unclaimed → finds "Create database schema" -10. alice → claim_task → "Create database schema" → back to WORK -11. bob IDLE poll 1 → scan_unclaimed → finds "Write API routes" -12. bob → claim_task → "Write API routes" → back to WORK - -13. alice WORK: write_file("schema.sql", ...) → complete_task → WORK ends -14. alice IDLE → scan → "Write unit tests" → claim → WORK -15. alice WORK: write_file("test_api.py", ...) → complete_task → WORK ends -16. alice IDLE → 60s no new tasks → SHUTDOWN - -17. bob similar flow → done → SHUTDOWN -18. Lead consume_lead_inbox → sees alice and bob's summaries -``` - -Two teammates claim and work in parallel. Lead only creates tasks and spawns teammates — no manual assignment needed. - ---- - -## Changes from s16 - -| Component | Before (s16) | After (s17) | -|-----------|-------------|-------------| -| Task assignment | Lead manually assigns | Teammates auto-claim (can_start checks deps) | -| Teammate state | WORK → IDLE (1s inbox poll) → WORK / SHUTDOWN | WORK → IDLE (5s inbox + task board poll, 60s timeout) → WORK / SHUTDOWN | -| claim_task | No owner check | Rejects tasks that already have an owner | -| IDLE phase shutdown | Exits after receiving shutdown_request | Dispatches shutdown immediately and exits | -| Lead inbox | consume_lead_inbox routes protocol responses and injects into context | Reuses consume_lead_inbox mechanism | -| New functions | consume_lead_inbox already exists | idle_poll, scan_unclaimed_tasks (reuses consume_lead_inbox) | -| Identity persistence | System prompt only | Auto re-inject after compression | -| Lead tools | 14 | 14 (unchanged) | -| Teammate tools | 5 | 8 (+ list_tasks, claim_task, complete_task) | -| Teammate exit | WORK ends → enters IDLE, waits for shutdown_request (no timeout) | Exits after 60s idle timeout or receiving shutdown_request | - ---- - -## Try It - -```sh -cd learn-claude-code -python s17_autonomous_agents/code.py -``` - -Try this prompt: - -`Create 3 tasks on the board, then spawn alice and bob. Watch them auto-claim and work.` - -What to observe: Do teammates auto-claim unassigned tasks? Are tasks with blockedBy dependencies claimed only after their dependencies complete? Does idle timeout trigger shutdown? Does a shutdown_request in IDLE phase get an immediate response? How do task states change in `.tasks/`? - ---- - -## What's Next - -Teammates self-organize now. But Alice and Bob both work in the same directory — Alice edits `config.py`, Bob also edits `config.py`, overwriting each other. - -s18 Worktree Isolation → Each task gets its own working directory, no conflicts. - -
-Deep Dive into CC Source - -> Teaching note: This chapter's idle_poll + auto-claim mechanism is a teaching design, using a unified polling function to demonstrate "find work when idle." CC's actual implementation combines multiple mechanisms, but shares the same goal — reducing Lead's manual assignment burden. - -### 1. CC's Idle Mechanism: Combined Approach, Not Single Polling - -Teaching version uses a single `idle_poll()` to handle both inbox checking and task claiming during idle. CC's actual implementation combines four mechanisms: - -**idle_notification**: After completing a round of work, `sendIdleNotification()` (`inProcessRunner.ts:569-589`) sends an idle notification to Lead. Lead knows the teammate is available and can assign new tasks or request shutdown. - -**mailbox polling**: `waitForNextPromptOrShutdown()` (`inProcessRunner.ts:689-868`) is a **500ms polling loop** that continuously checks three sources: pending user messages, mailbox file messages, and task list. Shutdown requests are prioritized (`inProcessRunner.ts:768-804`), preventing starvation by regular messages. - -**task watcher**: `useTaskListWatcher` (`hooks/useTaskListWatcher.ts:34-189`) uses `fs.watch()` to monitor the `.claude/tasks/` directory with 1-second debounce, triggering checks when new tasks are created or dependencies unblock. The dependency check (`L197-207`) verifies "no incomplete tasks in blockedBy", not "blockedBy is empty". - -**active claiming**: The polling loop also calls `tryClaimNextTask()` (`inProcessRunner.ts:853-860`) — actively claiming tasks from the task list while waiting. So "teammates don't actively poll for tasks" is inaccurate; CC has both passive notification and active claiming. - -### 2. Task Claiming: File Locks + Atomic Operations - -`claimTask()` (`utils/tasks.ts:541-612`) uses `proper-lockfile` task-level locks, performing read-check-modify-write within the lock. Checks: owner already exists (`L575-576`), already completed (`L580-581`), unresolved blockers in blockedBy (`L585-594`). `claimTaskWithBusyCheck()` (`utils/tasks.ts:614-692`) uses task-list level locks, making busy check and claim atomic to avoid TOCTOU. - -`findAvailableTask()` (`inProcessRunner.ts:595-604`) checks "all blockedBy completed" using `task.blockedBy.every(id => !unresolvedTaskIds.has(id))`. `tryClaimNextTask()` (`inProcessRunner.ts:624-657`) updates status to `in_progress` after claiming, so the UI immediately reflects the change. - -### 3. Teaching Version vs CC Comparison - -| Dimension | Teaching (s17) | CC | -|-----------|----------------|-----| -| Idle mechanism | idle_poll unified polling (5s) | idle_notification + 500ms mailbox polling + task watcher | -| Task discovery | scan_unclaimed_tasks (polling) | useTaskListWatcher (file watching) + tryClaimNextTask (active polling) | -| Dependency check | can_start (all blockedBy completed) | findAvailableTask (same semantics) | -| Concurrency safety | Owner check (no file lock) | proper-lockfile task lock + task-list lock | -| Shutdown handling | IDLE dispatches directly, WORK via handle_inbox_message | 500ms polling loop prioritizes shutdown_request | -| Timeout exit | 60s with no new tasks | No fixed timeout, Lead manual shutdown | -| Identity persistence | Messages length detection | Context compaction preserves system prompt | -| Claim failure handling | Check return value, skip on failure | File locks guarantee atomicity | - -Teaching version's `idle_poll()` merges CC's four mechanisms into one polling function — a reasonable simplification since the core semantics (find work when idle, claim after deps resolve, prioritize shutdown) are consistent. - -
- - diff --git a/s17_autonomous_agents/README.zh.md b/s17_autonomous_agents/README.zh.md deleted file mode 100644 index 49255b68..00000000 --- a/s17_autonomous_agents/README.zh.md +++ /dev/null @@ -1,273 +0,0 @@ -# s17: Autonomous Agents — 自己看板,自己认领 - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s15 → s16 → `s17` → [s18](../s18_worktree_isolation/) → s19 → s20 → s21 → s22 - -> *"自己看板,自己认领"* — 空闲时轮询,有活就干。 -> -> **Harness 层**: 自治 — 队友自组织,不依赖 Lead 分配。 - -> **核心与选学:** 空闲发现工作与原子认领是本章核心;身份重注入只是教学版的进阶补丁,第一次学习可以跳过。 - ---- - -## 问题 - -s16 的队友能通信、能握手关机。但每个队友等 Lead 分配任务——如果任务看板上有 10 个未认领任务,Lead 得手动 assign 10 次。这不能扩展。队友应该自己看任务看板,发现没人做的任务就认领,做完再找下一个。 - ---- - -## 解决方案 - -![Autonomous Agents Overview](images/autonomous-agents-overview.svg) - -沿用 S16 的教学版 MessageBus 和协议工具。本章新增:**idle_poll**(空闲时每 5 秒轮询一次)、**scan_unclaimed_tasks**(扫描看板上可认领的任务)、**自动认领**(找到任务就 claim,不用 Lead 操心)。 - -队友生命周期从两阶段变成三阶段: - -| 阶段 | 行为 | 退出条件 | -|------|------|---------| -| WORK | inbox → LLM → 工具循环 | `stop_reason != tool_use` | -| IDLE | 每 5s 轮询 inbox + 任务板 | 60s 超时 | -| SHUTDOWN | 发 summary,退出 | — | - ---- - -## 工作原理 - -### idle_poll: 空闲轮询 - -队友完成当前任务后不退出,进入 IDLE 阶段——每 5 秒检查一次有没有新工作: - -```python -IDLE_POLL_INTERVAL = 5 # seconds -IDLE_TIMEOUT = 60 # seconds - -def idle_poll(name, messages, role) -> str: - """Return 'work', 'shutdown', or 'timeout'.""" - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - - # ① 检查收件箱(优先) - inbox = BUS.read_inbox(name) - if inbox: - # shutdown_request 立即处理 - for msg in inbox: - if msg.get("type") == "shutdown_request": - # ... 回复 shutdown_response - return "shutdown" - # 普通消息注入上下文,回到 WORK - messages.append(...) - return "work" - - # ② 扫描任务看板 - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task = unclaimed[0] - result = claim_task(task["id"], name) - if "Claimed" in result: - messages.append(...) - return "work" - return "timeout" -``` - -inbox 优先(可能包含 shutdown_request 等协议消息),任务板其次。IDLE 阶段收到 shutdown_request 会直接回复并退出,不等到下一轮 WORK。 - -### scan_unclaimed_tasks: 扫描任务看板 - -找 pending 状态、无 owner、所有依赖已完成(`can_start`)的任务: - -```python -def scan_unclaimed_tasks() -> list[dict]: - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed -``` - -三个条件:必须是 pending、没有 owner、所有 blockedBy 依赖已完成。`can_start` 检查依赖任务的状态——有依赖不代表不能做,只有被未完成的任务阻塞才不能做。教学版按文件名排序取第一个;CC 用文件锁防止多个队友同时认领同一个任务。 - -### claim_task: owner 检查 - -自动认领时检查 claim 结果,不把失败当成功: - -```python -def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - return f"Blocked by: {deps}" - task.owner = owner - task.status = "in_progress" - save_task(task) - return f"Claimed {task.id} ({task.subject})" -``` - -教学版没有文件锁,并发认领可能出现竞争。但至少 `task.owner` 检查避免了最明显的"后写覆盖"问题。CC 用 `proper-lockfile` 保护任务文件,`claimTask` 在文件锁内完成读-改-写(`utils/tasks.ts:541-612`)。 - -### 队友生命周期: WORK → IDLE → SHUTDOWN - -s16 的队友做完任务就退出。s17 加了 IDLE 阶段,队友在外层循环中反复 WORK → IDLE: - -```python -# Outer loop: WORK → IDLE cycle -while True: - # WORK phase: 内层循环(最多 10 轮 LLM 调用) - for _ in range(10): - # 检查 inbox、处理协议消息、调 LLM、执行工具 - ... - if response.stop_reason != "tool_use": - break # WORK 阶段结束 - - # IDLE phase - idle_result = idle_poll(name, messages, role) - if idle_result == "shutdown": - break - if idle_result == "timeout": - break # 60s 超时 → SHUTDOWN - -# SHUTDOWN: 发 summary 给 Lead -BUS.send(name, "lead", summary, "result") -``` - -关键设计: -- **外层 while True**:WORK 和 IDLE 交替进行,直到超时或收到关机请求 -- **内层 for 10**:WORK 阶段最多 10 轮 LLM 调用(防止无限循环) -- **IDLE 超时 60 秒**:12 次轮询 × 5 秒 = 60 秒。超时后发送 summary 并退出 -- **shutdown_request 两阶段都能响应**:WORK 阶段通过 `handle_inbox_message` 分发;IDLE 阶段 `idle_poll` 直接检查并回复 - -### 进阶(选学):身份重注入 - -autoCompact(s08)之后,队友的 messages 列表可能被压缩成一段摘要。每次进入新的 WORK 阶段时检查: - -```python -if len(messages) <= 3: - messages.insert(0, {"role": "user", - "content": f"You are '{name}', role: {role}. " - f"Continue your work."}) -``` - -消息过短说明发生了压缩,此时重新注入身份信息。真实 CC 中 context compaction 会保留 system prompt,教学版的简化实现需要手动处理。 - -### consume_lead_inbox: 统一 inbox 消费 - -`check_inbox` 工具和主循环末尾都调用同一个 `consume_lead_inbox()` 函数:先路由协议 response 更新状态,再把所有消息注入 Lead 的对话历史。队友发来的 summary/result 不会只打印在终端,Lead 的 LLM 能看到并协调下一步。 - -### 合起来跑 - -``` -1. Lead: "搭建后端——任务太多,让队友自己认领" -2. Lead → create_task("创建数据库 schema") -3. Lead → create_task("写 API 路由") -4. Lead → create_task("写单元测试") -5. Lead → spawn_teammate("alice", "backend", "你是后端开发者") -6. Lead → spawn_teammate("bob", "backend", "你是后端开发者") - -7. alice 线程启动 → WORK: 没有初始 inbox → 空转 → IDLE -8. bob 线程启动 → WORK: 没有初始 inbox → 空转 → IDLE - -9. alice IDLE 第 1 次轮询 → scan_unclaimed → 发现"创建数据库 schema" -10. alice → claim_task → "创建数据库 schema" → 回到 WORK -11. bob IDLE 第 1 次轮询 → scan_unclaimed → 发现"写 API 路由" -12. bob → claim_task → "写 API 路由" → 回到 WORK - -13. alice WORK: write_file("schema.sql", ...) → complete_task → WORK 结束 -14. alice IDLE → scan → "写单元测试" → claim → WORK -15. alice WORK: write_file("test_api.py", ...) → complete_task → WORK 结束 -16. alice IDLE → 60s 无新任务 → SHUTDOWN - -17. bob 类似流程 → 做完 → SHUTDOWN -18. Lead consume_lead_inbox → 看到 alice 和 bob 的 summary -``` - -两个队友并行认领、并行工作。Lead 只需要创建任务和启动队友,不需要手动分配。 - ---- - -## 相对 s16 的变更 - -| 组件 | 之前 (s16) | 之后 (s17) | -|------|-----------|-----------| -| 任务分配 | Lead 手动 assign | 队友自动认领(can_start 检查依赖) | -| 队友状态 | WORK → IDLE(每 1s 轮询 inbox)→ WORK / SHUTDOWN | WORK → IDLE(每 5s 轮询 inbox + 任务板,60s 超时)→ WORK / SHUTDOWN | -| claim_task | 无 owner 检查 | 拒绝已有 owner 的任务 | -| IDLE 阶段关机 | 收到 shutdown_request 后退出 | 直接 dispatch shutdown 并退出 | -| Lead inbox | consume_lead_inbox 路由协议响应并注入上下文 | 沿用 consume_lead_inbox 机制 | -| 新函数 | 已有 consume_lead_inbox | idle_poll, scan_unclaimed_tasks(沿用 consume_lead_inbox) | -| 身份保持 | 仅 system prompt | 压缩后自动重注入 | -| Lead 工具 | 14 | 14(不变) | -| 队友工具 | 5 | 8(+ list_tasks, claim_task, complete_task) | -| 队友退出条件 | WORK 完进入 IDLE,等待 shutdown_request 后退出(无超时) | 60s 无新任务或收到 shutdown_request 后退出 | - ---- - -## 试一下 - -```sh -cd learn-claude-code -python s17_autonomous_agents/code.py -``` - -试试这个 prompt: - -`Create 3 tasks on the board, then spawn alice and bob. Watch them auto-claim and work.` - -观察重点:队友是否自动认领了未分配的任务?有 blockedBy 依赖的任务是否在前置完成后被正确认领?空闲超时后是否自动关机?IDLE 阶段收到 shutdown_request 是否立即响应?`.tasks/` 目录下的任务状态如何变化? - ---- - -## 接下来 - -队友自组织了。但 Alice 和 Bob 都在同一个目录下工作——Alice 改 `config.py`,Bob 也改 `config.py`,互相覆盖。 - -s18 Worktree Isolation → 每个任务有自己的工作目录,互不干扰。 - -
-深入 CC 源码 - -> 教学说明:本章的 idle_poll + auto-claim 机制是教学设计,用统一的轮询函数演示"空闲后找活干"。CC 的实际实现是多个机制的组合,但目标一致——减少 Lead 的手动分配负担。 - -### 一、CC 的空闲机制:组合路径,不是单一轮询 - -教学版用一个 `idle_poll()` 统一处理空闲时的 inbox 检查和任务认领。CC 的实际实现是四个机制的组合: - -**idle_notification**:队友完成一轮工作后,`sendIdleNotification()`(`inProcessRunner.ts:569-589`)向 Lead 发送空闲通知。Lead 知道队友可用了,可以分配新任务或请求关机。 - -**mailbox 轮询**:`waitForNextPromptOrShutdown()`(`inProcessRunner.ts:689-868`)是一个 **500ms 轮询循环**,持续检查三类来源:pending user messages、mailbox 文件消息、task list。shutdown_request 被优先处理(`inProcessRunner.ts:768-804`),不会被普通消息饿死。 - -**task watcher**:`useTaskListWatcher`(`hooks/useTaskListWatcher.ts:34-189`)用 `fs.watch()` 监听 `.claude/tasks/` 目录变化,1 秒 debounce,当新任务创建或依赖解锁时触发检查。依赖判断(`L197-207`)是"blockedBy 中没有未完成的任务",不是"blockedBy 为空"。 - -**主动 claim**:轮询循环内部也会调用 `tryClaimNextTask()`(`inProcessRunner.ts:853-860`)——在等待期间主动从 task list 领取任务。所以"队友不主动轮询任务"不准确,CC 同时有被动通知和主动认领。 - -### 二、任务认领:文件锁 + 原子操作 - -`claimTask()`(`utils/tasks.ts:541-612`)用 `proper-lockfile` 的任务文件锁,在锁内完成读-检查-改-写。检查项:owner 是否已存在(`L575-576`)、是否已完成(`L580-581`)、blockedBy 中是否有未完成任务(`L585-594`)。`claimTaskWithBusyCheck()`(`utils/tasks.ts:614-692`)用 task-list 级别锁,把 busy check 和 claim 做成原子操作,避免 TOCTOU。 - -`findAvailableTask()`(`inProcessRunner.ts:595-604`)的依赖判断也是"所有 blockedBy 已完成",用 `task.blockedBy.every(id => !unresolvedTaskIds.has(id))` 实现。`tryClaimNextTask()`(`inProcessRunner.ts:624-657`)在认领后把状态更新为 `in_progress`,让 UI 立即反映变化。 - -### 三、教学版 vs CC 对比 - -| 维度 | 教学版 (s17) | CC | -|------|-------------|-----| -| 空闲机制 | idle_poll 统一轮询(5s) | idle_notification + 500ms mailbox 轮询 + task watcher | -| 任务发现 | scan_unclaimed_tasks(轮询) | useTaskListWatcher(文件监听)+ tryClaimNextTask(主动轮询) | -| 依赖判断 | can_start(所有 blockedBy 已完成) | findAvailableTask(同样语义) | -| 并发安全 | owner 检查(无文件锁) | proper-lockfile 任务锁 + task-list 锁 | -| shutdown 处理 | IDLE 直接分发,WORK 通过 handle_inbox_message | 500ms 轮询中优先处理 shutdown_request | -| 超时退出 | 60s 无新任务 | 无固定超时,Lead 手动 shutdown | -| 身份保持 | messages 长度检测 | context compaction 保留 system prompt | -| claim 失败处理 | 检查返回值,失败不注入 | 文件锁保证原子性 | - -教学版的 `idle_poll()` 把 CC 的四个机制合并成一个轮询函数——简化合理,因为核心语义(空闲时找活干、依赖解锁后可认领、shutdown 优先)是一致的。 - -
- - diff --git a/s17_autonomous_agents/code.py b/s17_autonomous_agents/code.py deleted file mode 100644 index 71d97beb..00000000 --- a/s17_autonomous_agents/code.py +++ /dev/null @@ -1,813 +0,0 @@ -#!/usr/bin/env python3 -""" -s17: Autonomous Agents — idle poll + auto-claim + WORK/IDLE lifecycle. - -Run: python s17_autonomous_agents/code.py -Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY - -Changes from s16: - - scan_unclaimed_tasks: find pending, unowned tasks with deps completed - - idle_poll: 60s polling loop (inbox + task board), dispatches shutdown in IDLE - - claim_task: owner check + return value verification - - Teammate lifecycle: WORK → IDLE → SHUTDOWN - - Teammate tools: + list_tasks, claim_task, complete_task (5→8) - - consume_lead_inbox: unified inbox consumer for protocol + context injection - - Identity re-injection after context compression - -ASCII lifecycle: - WORK: inbox → LLM → tools → (tool_use? loop) → (done? → IDLE) - IDLE: 5s poll → inbox? → WORK / unclaimed? → claim → WORK / 60s? → SHUTDOWN -""" - -import os, subprocess, json, time, random, threading -from pathlib import Path -from datetime import datetime -from dataclasses import dataclass, asdict, field - -try: - import readline - readline.parse_and_bind('set bind-tty-special-chars off') -except ImportError: - pass - -from anthropic import Anthropic -from dotenv import load_dotenv - -load_dotenv(override=True) -if os.getenv("ANTHROPIC_BASE_URL"): - os.environ.pop("ANTHROPIC_AUTH_TOKEN", None) - -WORKDIR = Path.cwd() -client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) -MODEL = os.environ["MODEL_ID"] - -# ── Task System (from s12) ── - -TASKS_DIR = WORKDIR / ".tasks" -TASKS_DIR.mkdir(exist_ok=True) - - -@dataclass -class Task: - id: str - subject: str - description: str - status: str - owner: str | None - blockedBy: list[str] - - -def _task_path(task_id: str) -> Path: - return TASKS_DIR / f"{task_id}.json" - - -def create_task(subject: str, description: str = "", - blockedBy: list[str] | None = None) -> Task: - task = Task( - id=f"task_{int(time.time())}_{random.randint(0, 9999):04d}", - subject=subject, description=description, - status="pending", owner=None, - blockedBy=blockedBy or [], - ) - save_task(task) - return task - - -def save_task(task: Task): - _task_path(task.id).write_text(json.dumps(asdict(task), indent=2)) - - -def load_task(task_id: str) -> Task: - return Task(**json.loads(_task_path(task_id).read_text())) - - -def list_tasks() -> list[Task]: - return [Task(**json.loads(p.read_text())) - for p in sorted(TASKS_DIR.glob("task_*.json"))] - - -def get_task(task_id: str) -> str: - task = load_task(task_id) - return json.dumps(asdict(task), indent=2) - - -def can_start(task_id: str) -> bool: - task = load_task(task_id) - for dep_id in task.blockedBy: - if not _task_path(dep_id).exists(): - return False - if load_task(dep_id).status != "completed": - return False - return True - - -def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - deps = [d for d in task.blockedBy - if _task_path(d).exists() and load_task(d).status != "completed"] - missing = [d for d in task.blockedBy if not _task_path(d).exists()] - parts = [] - if deps: parts.append(f"blocked by: {deps}") - if missing: parts.append(f"missing deps: {missing}") - return "Cannot start — " + ", ".join(parts) - task.owner = owner - task.status = "in_progress" - save_task(task) - print(f" \033[36m[claim] {task.subject} → in_progress\033[0m") - return f"Claimed {task.id} ({task.subject})" - - -def complete_task(task_id: str) -> str: - task = load_task(task_id) - if task.status != "in_progress": - return f"Task {task_id} is {task.status}, cannot complete" - task.status = "completed" - save_task(task) - unblocked = [t.subject for t in list_tasks() - if t.status == "pending" and t.blockedBy and can_start(t.id)] - print(f" \033[32m[complete] {task.subject} ✓\033[0m") - msg = f"Completed {task.id} ({task.subject})" - if unblocked: - msg += f"\nUnblocked: {', '.join(unblocked)}" - return msg - - -# ── Prompt Assembly (from s10) ── - -PROMPT_SECTIONS = { - "identity": "You are a coding agent. Act, don't explain.", - "tools": "Available tools: bash, read_file, write_file, " - "create_task, list_tasks, get_task, claim_task, complete_task, " - "spawn_teammate, send_message, check_inbox, " - "request_shutdown, request_plan, review_plan.", - "workspace": f"Working directory: {WORKDIR}", - "memory": "Relevant memories are injected below when available.", -} - - -def assemble_system_prompt(context: dict) -> str: - sections = [PROMPT_SECTIONS["identity"], - PROMPT_SECTIONS["tools"], - PROMPT_SECTIONS["workspace"]] - if context.get("memories"): - sections.append(f"Relevant memories:\n{context['memories']}") - return "\n\n".join(sections) - - -_last_context_hash, _last_prompt = None, None - - -def get_system_prompt(context: dict) -> str: - global _last_context_hash, _last_prompt - h = json.dumps(context, sort_keys=True) - if h == _last_context_hash and _last_prompt: - return _last_prompt - _last_context_hash, _last_prompt = h, assemble_system_prompt(context) - return _last_prompt - - -# ── Tools (from s15) ── - -def safe_path(p: str) -> Path: - path = (WORKDIR / p).resolve() - if not path.is_relative_to(WORKDIR): - raise ValueError(f"Path escapes workspace: {p}") - return path - - -def run_bash(command: str) -> str: - try: - r = subprocess.run(command, shell=True, cwd=WORKDIR, - capture_output=True, text=True, timeout=120) - out = (r.stdout + r.stderr).strip() - return out[:50000] if out else "(no output)" - except subprocess.TimeoutExpired: - return "Error: Timeout (120s)" - - -def run_read(path: str, limit: int | None = None) -> str: - try: - lines = safe_path(path).read_text().splitlines() - if limit and limit < len(lines): - lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"] - return "\n".join(lines) - except Exception as e: - return f"Error: {e}" - - -def run_write(path: str, content: str) -> str: - try: - fp = safe_path(path) - fp.parent.mkdir(parents=True, exist_ok=True) - fp.write_text(content) - return f"Wrote {len(content)} bytes to {path}" - except Exception as e: - return f"Error: {e}" - - -# ── MessageBus (from s15) ── - -MAILBOX_DIR = WORKDIR / ".mailboxes" -MAILBOX_DIR.mkdir(exist_ok=True) - - -class MessageBus: - def send(self, from_agent: str, to_agent: str, content: str, - msg_type: str = "message", metadata: dict = None): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time(), "metadata": metadata or {}} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") - print(f" \033[33m[bus] {from_agent} → {to_agent}: " - f"({msg_type}) {content[:50]}\033[0m") - - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" - if not inbox.exists(): - return [] - msgs = [json.loads(line) for line in inbox.read_text().splitlines() - if line.strip()] - inbox.unlink() - return msgs - - -BUS = MessageBus() -active_teammates: dict[str, bool] = {} - - -# ── Protocol State (from s16) ── - -@dataclass -class ProtocolState: - request_id: str - type: str - sender: str - target: str - status: str - payload: str - created_at: float = field(default_factory=time.time) - - -pending_requests: dict[str, ProtocolState] = {} - - -def new_request_id() -> str: - return f"req_{random.randint(0, 999999):06d}" - - -def match_response(response_type: str, request_id: str, approve: bool): - """Correlate a response to the original request via request_id.""" - state = pending_requests.get(request_id) - if not state: - print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") - return - if state.type == "shutdown" and response_type != "shutdown_response": - print(f" \033[31m[protocol] type mismatch: expected shutdown_response, " - f"got {response_type}\033[0m") - return - if state.type == "plan_approval" and response_type != "plan_approval_response": - print(f" \033[31m[protocol] type mismatch: expected plan_approval_response, " - f"got {response_type}\033[0m") - return - state.status = "approved" if approve else "rejected" - icon = "✓" if approve else "✗" - color = "32" if approve else "31" - print(f" \033[{color}m[protocol] {state.type} {icon} " - f"({request_id}: {state.status})\033[0m") - - -# ── Autonomous Agent (s17 new) ── - -IDLE_POLL_INTERVAL = 5 # seconds -IDLE_TIMEOUT = 60 # seconds - - -def scan_unclaimed_tasks() -> list[dict]: - """Find pending, unowned tasks with all dependencies completed.""" - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed - - -def idle_poll(name: str, messages: list, role: str) -> str: - """Poll for 60s. Return 'work', 'shutdown', or 'timeout'.""" - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - - # Check inbox — dispatch protocol messages first - inbox = BUS.read_inbox(name) - if inbox: - # Check for shutdown_request - for msg in inbox: - if msg.get("type") == "shutdown_request": - req_id = msg.get("metadata", {}).get("request_id", "") - BUS.send(name, "lead", "Shutting down gracefully.", - "shutdown_response", - {"request_id": req_id, "approve": True}) - print(f" \033[35m[protocol] {name} approved shutdown " - f"in idle ({req_id})\033[0m") - return "shutdown" - - # Non-protocol inbox: inject and resume work - messages.append({"role": "user", - "content": "" + json.dumps(inbox) + ""}) - print(f" \033[36m[idle] {name} found inbox messages\033[0m") - return "work" - - # Scan task board - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task = unclaimed[0] - result = claim_task(task["id"], name) - if "Claimed" in result: - messages.append({"role": "user", - "content": f"Task {task['id']}: " - f"{task['subject']}"}) - print(f" \033[32m[idle] {name} auto-claimed: " - f"{task['subject']}\033[0m") - return "work" - print(f" \033[33m[idle] {name} claim failed: " - f"{result}\033[0m") - - print(f" \033[31m[idle] {name} timeout ({IDLE_TIMEOUT}s)\033[0m") - return "timeout" - - -# ── Teammate Thread (from s15 + s16 + s17) ── - -def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - if name in active_teammates: - return f"Teammate '{name}' already exists" - - system = (f"You are '{name}', a {role}. " - f"Use tools to complete tasks. " - f"You can list and claim tasks from the board. " - f"Check inbox for protocol messages.") - - def handle_inbox_message(name: str, msg: dict, messages: list): - """Dispatch incoming protocol messages by type.""" - msg_type = msg.get("type", "message") - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - - if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down gracefully.", - "shutdown_response", - {"request_id": req_id, "approve": True}) - print(f" \033[35m[protocol] {name} approved shutdown " - f"({req_id})\033[0m") - return True - - if msg_type == "plan_approval_response": - approve = meta.get("approve", False) - if approve: - messages.append({"role": "user", - "content": "[Plan approved] Proceed with the task."}) - else: - messages.append({"role": "user", - "content": f"[Plan rejected] Feedback: {msg['content']}"}) - return False - - def run(): - messages = [{"role": "user", "content": prompt}] - sub_tools = [ - {"name": "bash", "description": "Run a shell command.", - "input_schema": {"type": "object", - "properties": {"command": {"type": "string"}}, - "required": ["command"]}}, - {"name": "read_file", "description": "Read file.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}}, - "required": ["path"]}}, - {"name": "write_file", "description": "Write file.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["path", "content"]}}, - {"name": "send_message", - "description": "Send message to another agent.", - "input_schema": {"type": "object", - "properties": {"to": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["to", "content"]}}, - {"name": "submit_plan", - "description": "Submit a plan for Lead approval.", - "input_schema": {"type": "object", - "properties": {"plan": {"type": "string"}}, - "required": ["plan"]}}, - # s17 new: teammates can list, claim, and complete tasks - {"name": "list_tasks", - "description": "List all tasks on the board.", - "input_schema": {"type": "object", "properties": {}, - "required": []}}, - {"name": "claim_task", - "description": "Claim a pending task.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "complete_task", - "description": "Mark an in-progress task as completed.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - ] - - def _run_list_tasks(): - tasks = list_tasks() - if not tasks: - return "No tasks." - return "\n".join( - f" {t.id}: {t.subject} [{t.status}]" - for t in tasks) - - def _run_claim_task(task_id: str): - return claim_task(task_id, owner=name) - - def _run_complete_task(task_id: str): - return complete_task(task_id) - - sub_handlers = { - "bash": run_bash, "read_file": run_read, "write_file": run_write, - "send_message": lambda to, content: (BUS.send(name, to, content), - "Sent")[1], - "submit_plan": lambda plan: _teammate_submit_plan(name, plan), - "list_tasks": _run_list_tasks, - "claim_task": _run_claim_task, - "complete_task": _run_complete_task, - } - - # Outer loop: WORK → IDLE cycle - while True: - # Identity re-injection (s17) - if len(messages) <= 3: - messages.insert(0, {"role": "user", - "content": f"You are '{name}', role: {role}. " - f"Continue your work."}) - - # WORK phase - should_shutdown = False - for _ in range(10): - inbox = BUS.read_inbox(name) - for msg in inbox: - stopped = handle_inbox_message(name, msg, messages) - if stopped: - should_shutdown = True - break - if should_shutdown: - break - if inbox and not should_shutdown: - non_protocol = [m for m in inbox - if m.get("type") == "message"] - if non_protocol: - messages.append({"role": "user", - "content": f"{json.dumps(non_protocol)}"}) - - try: - response = client.messages.create( - model=MODEL, system=system, messages=messages[-20:], - tools=sub_tools, max_tokens=8000) - except Exception: - break - messages.append({"role": "assistant", "content": response.content}) - if response.stop_reason != "tool_use": - break - results = [] - for block in response.content: - if block.type == "tool_use": - handler = sub_handlers.get(block.name) - output = handler(**block.input) if handler else "Unknown" - results.append({"type": "tool_result", - "tool_use_id": block.id, - "content": str(output)}) - messages.append({"role": "user", "content": results}) - - if should_shutdown: - break - - # IDLE phase (s17 new) - idle_result = idle_poll(name, messages, role) - if idle_result == "shutdown": - break - if idle_result == "timeout": - break - - # Summary - summary = "Done." - for msg in reversed(messages): - if msg["role"] == "assistant" and isinstance(msg["content"], list): - for b in msg["content"]: - if getattr(b, "type", None) == "text": - summary = b.text - break - else: - continue - break - BUS.send(name, "lead", summary, "result") - active_teammates.pop(name, None) - print(f" \033[32m[teammate] {name} finished\033[0m") - - active_teammates[name] = True - threading.Thread(target=run, daemon=True).start() - print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") - return f"Teammate '{name}' spawned as {role} (autonomous)" - - -def _teammate_submit_plan(from_name: str, plan: str) -> str: - """Teammate submits a plan to Lead for approval.""" - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="plan_approval", - sender=from_name, target="lead", - status="pending", payload=plan) - BUS.send(from_name, "lead", plan, - "plan_approval_request", - {"request_id": req_id}) - return f"Plan submitted ({req_id}). Waiting for approval..." - - -# ── Lead Protocol Tools (from s16) ── - -def run_request_shutdown(teammate: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="shutdown", - sender="lead", target=teammate, - status="pending", payload="") - BUS.send("lead", teammate, "Please shut down gracefully.", - "shutdown_request", - {"request_id": req_id}) - print(f" \033[35m[protocol] shutdown_request → {teammate} " - f"({req_id})\033[0m") - return f"Shutdown request sent to {teammate} (req: {req_id})" - - -def run_request_plan(teammate: str, task: str) -> str: - """Lead asks a teammate to submit a plan.""" - BUS.send("lead", teammate, f"Please submit a plan for: {task}", - "message") - return f"Asked {teammate} to submit a plan" - - -def run_review_plan(request_id: str, approve: bool, - feedback: str = "") -> str: - state = pending_requests.get(request_id) - if not state: - return f"Request {request_id} not found" - if state.status != "pending": - return f"Request {request_id} already {state.status}" - state.status = "approved" if approve else "rejected" - BUS.send("lead", state.sender, - feedback or ("Approved" if approve else "Rejected"), - "plan_approval_response", - {"request_id": request_id, "approve": approve}) - icon = "✓" if approve else "✗" - print(f" \033[32m[protocol] plan {icon} ({request_id})\033[0m") - return f"Plan {'approved' if approve else 'rejected'} ({request_id})" - - -# ── Basic tool handlers ── - -def run_create_task(subject: str, description: str = "", - blockedBy: list[str] | None = None) -> str: - task = create_task(subject, description, blockedBy) - deps = f" (blockedBy: {', '.join(blockedBy)})" if blockedBy else "" - print(f" \033[34m[create] {task.subject}{deps}\033[0m") - return f"Created {task.id}: {task.subject}{deps}" - - -def run_list_tasks() -> str: - tasks = list_tasks() - if not tasks: - return "No tasks." - return "\n".join( - f" {t.id}: {t.subject} [{t.status}]" - for t in tasks) - - -def run_get_task(task_id: str) -> str: - return get_task(task_id) - - -def run_claim_task(task_id: str) -> str: - return claim_task(task_id, owner="agent") - - -def run_complete_task(task_id: str) -> str: - return complete_task(task_id) - - -def run_spawn_teammate(name: str, role: str, prompt: str) -> str: - return spawn_teammate_thread(name, role, prompt) - - -def run_send_message(to: str, content: str) -> str: - BUS.send("lead", to, content) - return f"Sent to {to}" - - -def consume_lead_inbox(route_protocol=True) -> list[dict]: - """Read Lead inbox: route protocol responses, return all messages.""" - msgs = BUS.read_inbox("lead") - if route_protocol: - for msg in msgs: - meta = msg.get("metadata", {}) - req_id = meta.get("request_id", "") - msg_type = msg.get("type", "") - if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) - return msgs - - -def run_check_inbox() -> str: - msgs = consume_lead_inbox(route_protocol=True) - if not msgs: - return "(inbox empty)" - lines = [] - for m in msgs: - meta = m.get("metadata", {}) - req_id = meta.get("request_id", "") - tag = f" [{m['type']} req:{req_id}]" if req_id else f" [{m['type']}]" - lines.append(f" [{m['from']}]{tag} {m['content'][:200]}") - return "\n".join(lines) - - -# ── Tool Definitions ── - -TOOLS = [ - {"name": "bash", "description": "Run a shell command.", - "input_schema": {"type": "object", - "properties": {"command": {"type": "string"}}, - "required": ["command"]}}, - {"name": "read_file", "description": "Read file contents.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "limit": {"type": "integer"}}, - "required": ["path"]}}, - {"name": "write_file", "description": "Write content to a file.", - "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["path", "content"]}}, - {"name": "create_task", - "description": "Create a task.", - "input_schema": {"type": "object", - "properties": {"subject": {"type": "string"}, - "description": {"type": "string"}, - "blockedBy": {"type": "array", - "items": {"type": "string"}}}, - "required": ["subject"]}}, - {"name": "list_tasks", - "description": "List all tasks.", - "input_schema": {"type": "object", "properties": {}, "required": []}}, - {"name": "get_task", - "description": "Get full details of a specific task.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "claim_task", - "description": "Claim a pending task.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "complete_task", - "description": "Complete an in-progress task.", - "input_schema": {"type": "object", - "properties": {"task_id": {"type": "string"}}, - "required": ["task_id"]}}, - {"name": "spawn_teammate", - "description": "Spawn an autonomous teammate agent.", - "input_schema": {"type": "object", - "properties": {"name": {"type": "string"}, - "role": {"type": "string"}, - "prompt": {"type": "string"}}, - "required": ["name", "role", "prompt"]}}, - {"name": "send_message", - "description": "Send message to a teammate.", - "input_schema": {"type": "object", - "properties": {"to": {"type": "string"}, - "content": {"type": "string"}}, - "required": ["to", "content"]}}, - {"name": "check_inbox", - "description": "Check inbox for messages and protocol responses.", - "input_schema": {"type": "object", "properties": {}, "required": []}}, - {"name": "request_shutdown", - "description": "Request a teammate to shut down gracefully.", - "input_schema": {"type": "object", - "properties": {"teammate": {"type": "string"}}, - "required": ["teammate"]}}, - {"name": "request_plan", - "description": "Ask a teammate to submit a plan for review.", - "input_schema": {"type": "object", - "properties": {"teammate": {"type": "string"}, - "task": {"type": "string"}}, - "required": ["teammate", "task"]}}, - {"name": "review_plan", - "description": "Approve or reject a submitted plan.", - "input_schema": {"type": "object", - "properties": { - "request_id": {"type": "string"}, - "approve": {"type": "boolean"}, - "feedback": {"type": "string"}}, - "required": ["request_id", "approve"]}}, -] - -TOOL_HANDLERS = { - "bash": run_bash, "read_file": run_read, "write_file": run_write, - "create_task": run_create_task, "list_tasks": run_list_tasks, - "get_task": run_get_task, - "claim_task": run_claim_task, "complete_task": run_complete_task, - "spawn_teammate": run_spawn_teammate, - "send_message": run_send_message, "check_inbox": run_check_inbox, - "request_shutdown": run_request_shutdown, - "request_plan": run_request_plan, "review_plan": run_review_plan, -} - - -# ── Context ── - -MEMORY_DIR = WORKDIR / ".memory" -MEMORY_INDEX = MEMORY_DIR / "MEMORY.md" - - -def update_context(context: dict, messages: list) -> dict: - memories = "" - if MEMORY_INDEX.exists(): - memories = MEMORY_INDEX.read_text()[:2000] - return {"memories": memories} - - -# ── Agent Loop ── - -def agent_loop(messages: list, context: dict): - system = get_system_prompt(context) - while True: - try: - response = client.messages.create( - model=MODEL, system=system, messages=messages, - tools=TOOLS, max_tokens=8000) - except Exception as e: - messages.append({"role": "assistant", "content": [ - {"type": "text", "text": f"[Error] {type(e).__name__}: {e}"}]}) - return - - messages.append({"role": "assistant", "content": response.content}) - if response.stop_reason != "tool_use": - return - - results = [] - for block in response.content: - if block.type != "tool_use": - continue - print(f"\033[36m> {block.name}\033[0m") - handler = TOOL_HANDLERS.get(block.name) - output = handler(**block.input) if handler else "Unknown" - print(str(output)[:300]) - results.append({"type": "tool_result", - "tool_use_id": block.id, "content": output}) - messages.append({"role": "user", "content": results}) - context = update_context(context, messages) - system = get_system_prompt(context) - - -if __name__ == "__main__": - print("s17: autonomous agents") - print("Enter a question, press Enter to send. Type q to quit.\n") - history = [] - context = {"memories": ""} - while True: - try: - query = input("\033[36ms17 >> \033[0m") - except (EOFError, KeyboardInterrupt): - break - if query.strip().lower() in ("q", "exit", ""): - break - history.append({"role": "user", "content": query}) - agent_loop(history, context) - context = update_context(context, history) - for block in history[-1]["content"]: - if getattr(block, "type", None) == "text": - print(block.text) - elif isinstance(block, dict) and block.get("type") == "text": - print(block.get("text", "")) - - # Consume lead inbox: route protocol + inject into history - inbox = consume_lead_inbox(route_protocol=True) - if inbox: - inbox_text = "\n".join( - f"From {m['from']} [{m.get('type', 'message')}]: " - f"{m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) - print() diff --git a/s18_worktree_isolation/README.ja.md b/s17_worktree_isolation/README.ja.md similarity index 59% rename from s18_worktree_isolation/README.ja.md rename to s17_worktree_isolation/README.ja.md index 86da2305..121ed54d 100644 --- a/s18_worktree_isolation/README.ja.md +++ b/s17_worktree_isolation/README.ja.md @@ -1,8 +1,8 @@ -# s18: Worktree Isolation — それぞれのディレクトリ、互いに干渉しない +# s17: Worktree Isolation — それぞれのディレクトリ、互いに干渉しない [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s16 → s17 → `s18` → [s19](../s19_mcp_plugin/) → s20 → s21 → s22 +s01 → ... → s15 → s16 → `s17` → [s18](../s18_mcp_plugin/) → s19 → s20 → s21 > *"それぞれのディレクトリ、互いに干渉しない"* — タスクは目標を管理、worktree はディレクトリを管理、ID で紐付け。 > @@ -12,11 +12,11 @@ s01 → ... → s16 → s17 → `s18` → [s19](../s19_mcp_plugin/) → s20 → ## 課題 -s17 では、Alice も Bob も同じディレクトリで作業。Alice のタスクは「認証モジュールのリファクタリング」、Bob のタスクは「UI ログインページのリファクタリング」。 +s16 では、Alice も Bob も同じディレクトリで作業。Alice のタスクは「認証モジュールのリファクタリング」、Bob のタスクは「UI ログインページのリファクタリング」。 Alice が `write_file("config.py", ...)` を呼び出し、Bob も `write_file("config.py", ...)` を呼び出す。両者が同じファイルを編集し、互いに上書き。クリーンなロールバックもできない——どの変更が誰のものか区別できない。 -s15-s17 は「誰が何をするか」(タスクシステム)と「どう通信するか」(メッセージバス)を解決したが、「どこで作業するか」は未解決。 +s15-s16 は「誰が何をするか」(タスクシステム)と「どう通信するか」(メッセージバス)を解決したが、「どこで作業するか」は未解決。 --- @@ -26,7 +26,7 @@ s15-s17 は「誰が何をするか」(タスクシステム)と「どう通 Git worktree を使うと、同じリポジトリ内に複数の独立した作業ディレクトリを作成でき、それぞれが独自のブランチを持つ。Alice は `.worktrees/auth-refactor/` で作業、Bob は `.worktrees/ui-login/` で作業——互いに干渉しない。 -S17 の教学版 MessageBus、プロトコル、自治認領機構を踏襲。本章の追加: +s16 の MessageBus、プロトコル、自動認領を引き継ぐ。本章では次を追加する: | 機能 | 目的 | |------|------| @@ -63,7 +63,7 @@ def bind_task_to_worktree(task_id: str, worktree_name: str): ### チームメイトツールの cwd 切り替え -教学版は各チームメイトに `wt_ctx` 辞書を維持し、現在の worktree パスを追跡。チームメイトが worktree 紐付けタスクを認領すると、`wt_ctx` が自動的に worktree パスに設定され、チームメイトの `bash`、`read_file`、`write_file` は worktree ディレクトリで実行される: +各チームメイトは、現在の worktree パスを記録する `wt_ctx` 辞書を持つ。worktree に紐付いたタスクを認領すると、ランタイムが `wt_ctx` を更新し、そのチームメイトの `bash`、`read_file`、`write_file` は対応する worktree ディレクトリで実行される: ```python # チームメイトスレッド内部 @@ -81,8 +81,6 @@ def _run_bash(command): return run_bash(command, cwd=wt_ctx["path"]) # worktree で実行 ``` -これは教学簡略化。真实 CC の EnterWorktree は `process.chdir()` でプロセス全体のディレクトリを切り替え、AgentTool isolation は `cwdOverride` でサブエージェント実行をラップする。 - ### クリーンアップ:Keep または Remove タスク完了後、2 つの選択肢: @@ -118,7 +116,7 @@ def log_event(event_type: str, worktree_name: str, task_id: str = ""): # .worktrees/events.jsonl に append ``` -イベントタイプ:`create`、`remove`、`keep`。教学版はイベントを記録するだけで手動監査用。完全な復元には index または `git worktree list` スキャンが必要。 +イベントタイプは `create`、`remove`、`keep`。ログは手動監査に使い、復元時は `git worktree list` から現在の worktree 一覧を再構築できる。 ### run_git:成功/失敗を返す @@ -132,9 +130,9 @@ def run_git(args: list[str]) -> tuple[bool, str]: --- -## s17 からの変更 +## s16 からの変更 -| コンポーネント | 変更前 (s17) | 変更後 (s18) | +| コンポーネント | 変更前 (s16) | 変更後 (s17) | |--------------|------------|------------| | 作業ディレクトリ | 全 Agent が WORKDIR を共有 | 各タスクが git worktree に紐付け可能 | | タスクデータ | id/subject/status/owner/blockedBy | + worktree フィールド | @@ -142,8 +140,8 @@ def run_git(args: list[str]) -> tuple[bool, str]: | 新規関数 | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name | | worktree 安全性 | なし | name 検証 + 変更ありの場合削除拒否 | | イベントログ | なし | events.jsonl ライフサイクル監査 | -| Lead ツール | 14 (s17) | + create_worktree, remove_worktree, keep_worktree (17) | -| チームメイトツール | 8 (s17) | 8(bash/read/write が worktree cwd で実行) | +| Lead ツール | チーム・タスクツール | + create_worktree、remove_worktree、keep_worktree | +| チームメイトツール | タスク・ファイルツール | ツールは同じ。bash/read/write は認領した worktree の cwd を使う | --- @@ -151,12 +149,12 @@ def run_git(args: list[str]) -> tuple[bool, str]: ```sh cd learn-claude-code -python s18_worktree_isolation/code.py +python s17_worktree_isolation/code.py ``` 以下のプロンプトを試してください: -`Create two tasks, then create worktrees for each (bind with task_id). Spawn alice and bob. Watch them auto-claim and work in isolated directories.` +`認証モジュールとログインページを並行してリファクタリングし、変更が互いに干渉しないようにしてください。` 観察ポイント:2 つの worktree の `git status` 出力は異なるブランチを表示しているか?チームメイトが worktree 紐付けタスクを認領後、bash コマンドは worktree ディレクトリで実行されているか?`remove_worktree` は変更がある場合に拒否するか?紐付け後のタスク状態は `pending` のままか? @@ -168,41 +166,7 @@ Agent チームが隔離されたワークスペースで自己組織化でき もしユーザーが独自のツールを持っていたら?例えば社内 Jira API や独自デプロイシステム? -s19 MCP Plugin → Agent にプラグインシステムを追加。外部ツールが標準プロトコルで接続、Agent は誰が書いたか知る必要がない。 +s18 MCP Plugin → Agent にプラグインシステムを追加。外部ツールが標準プロトコルで接続、Agent は誰が書いたか知る必要がない。 -
-CC ソースコード深掘り - -CC の worktree システムには 2 つのパスがある:**EnterWorktree**(現在のセッションが切り替え)と **AgentTool isolation**(サブエージェント隔離)。 - -### EnterWorktree:現在のセッション切り替え - -`EnterWorktreeTool.ts:92-97` worktree 作成後、直ちに `process.chdir(worktreePath)`、`setCwd()`、`setOriginalCwd()`、`saveWorktreeState()` を呼び出し。現在のセッションの作業ディレクトリが直接 worktree に切り替わる——プロンプトのヒントではなく、プロセスレベルのディレクトリ変更。 - -`ExitWorktreeTool.ts:261-320` keep/remove どちらも `restoreSessionToOriginalCwd()` で元のディレクトリに復元。Remove は未コミット変更をチェック(`ExitWorktreeTool.ts:190-220`)、`discard_changes: true` なしでは拒否。 - -### AgentTool Isolation:サブエージェント隔離 - -`AgentTool.tsx:590-641` `isolation: "worktree"` の場合、`createAgentWorktree()` を呼び出して worktree を作成し、`cwdOverridePath` でサブエージェント実行をラップ。サブエージェントの全操作が自動的に worktree ディレクトリで実行される。`AgentTool/prompt.ts:272` はモデルに伝える:これは一時的な worktree、変更なしで自動クリーンアップ、変更ありの場合はパスとブランチを返す。 - -`worktree.ts:902-951` `createAgentWorktree()` はグローバル session cwd を変更せず、サブエージェント専用。`worktree.ts:961-1020` `removeAgentWorktree()` はメインリポジトリルートから削除。 - -### name 検証 - -`worktree.ts:76-84` slug を検証:`.`/`..` を拒否、`[a-zA-Z0-9._-]` を許可。`worktree.ts:48` で `VALID_WORKTREE_SLUG_SEGMENT` を定義。教学版の `validate_worktree_name` も同じルールを使用。 - -### パスとブランチ命名 - -実際のパスは `.claude/worktrees/`、ブランチ名は `worktree-{slug}`(`worktree.ts:204-227`、スラッシュは `+` に置換)。教学版は `.worktrees/` と `wt/{name}` で簡略化。 - -作成時は `git worktree add -B`(`worktree.ts:326-328`)を使用し、現在の HEAD より `origin/` を優先。 - -### 状態管理 - -CC にはタスク-worktree 紐付けがない。Worktree 状態は `PersistedWorktreeSession`(`worktree.ts:756-768`)で管理、フィールドは `originalCwd`、`worktreePath`、`worktreeName`、`worktreeBranch`、`originalBranch`、`originalHeadCommit`、`sessionId` 等を含む——taskId フィールドはない。`saveWorktreeState()`(`sessionStorage.ts:2883-2920`)は `type: 'worktree-state'` で session transcript に書き込み。 - -教学版はタスクの `worktree` フィールドで紐付けを行う教学簡略化。CC は worktree とタスクを 2 つの独立システムとして扱い、Agent のコンテキスト理解で関連付ける。 - -
diff --git a/s18_worktree_isolation/README.md b/s17_worktree_isolation/README.md similarity index 58% rename from s18_worktree_isolation/README.md rename to s17_worktree_isolation/README.md index e7339cab..31da68af 100644 --- a/s18_worktree_isolation/README.md +++ b/s17_worktree_isolation/README.md @@ -1,8 +1,8 @@ -# s18: Worktree Isolation — Separate Directories, No Conflicts +# s17: Worktree Isolation — Separate Directories, No Conflicts [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s16 → s17 → `s18` → [s19](../s19_mcp_plugin/) → s20 → s21 → s22 +s01 → ... → s15 → s16 → `s17` → [s18](../s18_mcp_plugin/) → s19 → s20 → s21 > *"Separate directories, no conflicts"* — Tasks own the goal, worktrees own the directory, bound by ID. > @@ -12,11 +12,11 @@ s01 → ... → s16 → s17 → `s18` → [s19](../s19_mcp_plugin/) → s20 → ## The Problem -In s17, Alice and Bob both work in the same directory. Alice's task is "refactor auth module", Bob's task is "refactor UI login page". +In s16, Alice and Bob both work in the same directory. Alice's task is "refactor auth module", Bob's task is "refactor UI login page". Alice calls `write_file("config.py", ...)`. Bob also calls `write_file("config.py", ...)`. Both edit the same file, overwriting each other. And there's no clean rollback — you can't tell whose changes are whose. -s15-s17 solved "who does what" (task system) and "how to communicate" (message bus), but not "where to work". +s15-s16 solved "who does what" (task system) and "how to communicate" (message bus), but not "where to work". --- @@ -26,7 +26,7 @@ s15-s17 solved "who does what" (task system) and "how to communicate" (message b Git worktree lets you create multiple independent working directories in the same repo, each with its own branch. Alice works in `.worktrees/auth-refactor/`, Bob in `.worktrees/ui-login/` — no conflicts. -Carries forward S17's teaching-version MessageBus, protocols, and autonomous claiming. This chapter adds: +Carries forward s16's MessageBus, protocols, and autonomous claiming. This chapter adds: | Capability | Purpose | |------------|---------| @@ -63,7 +63,7 @@ Binding rule: one task binds to one worktree. Binding does NOT change task statu ### Teammate Tool Cwd Switching -Teaching version maintains a `wt_ctx` dict per teammate, tracking the current worktree path. When a teammate claims a task with a worktree, `wt_ctx` is automatically set to the worktree path; the teammate's `bash`, `read_file`, `write_file` execute in the worktree directory: +Each teammate keeps a `wt_ctx` dictionary with its current worktree path. When a teammate claims a task bound to a worktree, the runtime updates `wt_ctx`; that teammate's `bash`, `read_file`, and `write_file` calls then run in the worktree directory: ```python # Inside teammate thread @@ -81,8 +81,6 @@ def _run_bash(command): return run_bash(command, cwd=wt_ctx["path"]) # Execute in worktree ``` -This is a teaching simplification. Real CC's EnterWorktree uses `process.chdir()` to switch the entire process directory, and AgentTool isolation uses `cwdOverride` to wrap sub-agent execution. - ### Cleanup: Keep or Remove After task completion, two choices: @@ -118,7 +116,7 @@ def log_event(event_type: str, worktree_name: str, task_id: str = ""): # append to .worktrees/events.jsonl ``` -Event types: `create`, `remove`, `keep`. Teaching version logs events for manual auditing; full recovery would need an index or `git worktree list` scanning. +Event types are `create`, `remove`, and `keep`. The log supports manual auditing; a recovery flow can rebuild the current set from `git worktree list`. ### run_git: Returns Success/Failure @@ -132,9 +130,9 @@ def run_git(args: list[str]) -> tuple[bool, str]: --- -## Changes from s17 +## Changes from s16 -| Component | Before (s17) | After (s18) | +| Component | Before (s16) | After (s17) | |-----------|-------------|-------------| | Working directory | All agents share WORKDIR | Each task can bind to a git worktree | | Task data | id/subject/status/owner/blockedBy | + worktree field | @@ -142,8 +140,8 @@ def run_git(args: list[str]) -> tuple[bool, str]: | New functions | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name | | Worktree safety | None | Name validation + refuse removal with changes | | Event log | None | events.jsonl lifecycle auditing | -| Lead tools | 14 (s17) | + create_worktree, remove_worktree, keep_worktree (17) | -| Teammate tools | 8 (s17) | 8 (bash/read/write execute in worktree cwd) | +| Lead tools | Team and task tools | + create_worktree, remove_worktree, keep_worktree | +| Teammate tools | Task and file tools | Same tools; bash/read/write use the claimed worktree cwd | --- @@ -151,12 +149,12 @@ def run_git(args: list[str]) -> tuple[bool, str]: ```sh cd learn-claude-code -python s18_worktree_isolation/code.py +python s17_worktree_isolation/code.py ``` Try this prompt: -`Create two tasks, then create worktrees for each (bind with task_id). Spawn alice and bob. Watch them auto-claim and work in isolated directories.` +`Refactor the authentication module and the login page in parallel without letting the changes interfere with each other.` What to observe: Do both worktrees show different branches in `git status`? After claiming a worktree-bound task, does the teammate's bash run in the worktree directory? Does `remove_worktree` refuse when there are changes? Is task status still `pending` after binding? @@ -168,41 +166,7 @@ Agent teams can now self-organize in isolated workspaces. But Agent capabilities What if users already have their own tools? Like an internal Jira API, or a custom deployment system? -s19 MCP Plugin → Give Agent a plugin system. External tools connect via standard protocol; Agent doesn't need to know who wrote them. +s18 MCP Plugin → Give Agent a plugin system. External tools connect via standard protocol; Agent doesn't need to know who wrote them. -
-Deep Dive into CC Source - -CC's worktree system has two paths: **EnterWorktree** (current session switches in) and **AgentTool isolation** (sub-agent isolation). - -### EnterWorktree: Current Session Switch - -`EnterWorktreeTool.ts:92-97` after creating the worktree, immediately calls `process.chdir(worktreePath)`, `setCwd()`, `setOriginalCwd()`, `saveWorktreeState()`. The current session's working directory switches directly to the worktree — not a prompt hint, but a process-level directory change. - -`ExitWorktreeTool.ts:261-320` both keep and remove call `restoreSessionToOriginalCwd()` to restore the original directory. Remove checks for uncommitted changes (`ExitWorktreeTool.ts:190-220`), refusing without `discard_changes: true`. - -### AgentTool Isolation: Sub-Agent Isolation - -`AgentTool.tsx:590-641` when `isolation: "worktree"`, calls `createAgentWorktree()` to create a worktree, uses `cwdOverridePath` to wrap sub-agent execution. All sub-agent operations automatically run in the worktree directory. `AgentTool/prompt.ts:272` tells the model: this is a temporary worktree, auto-cleanup if no changes, return path and branch if changes exist. - -`worktree.ts:902-951` `createAgentWorktree()` does NOT modify global session cwd, only for sub-agent use. `worktree.ts:961-1020` `removeAgentWorktree()` deletes from the main repo root. - -### Name Validation - -`worktree.ts:76-84` validates slug: rejects `.`/`..`, allows `[a-zA-Z0-9._-]`. `worktree.ts:48` defines `VALID_WORKTREE_SLUG_SEGMENT`. Teaching version's `validate_worktree_name` uses the same rule. - -### Path and Branch Naming - -Real path is `.claude/worktrees/`, branch name `worktree-{slug}` (`worktree.ts:204-227`, slashes replaced with `+`). Teaching version uses `.worktrees/` and `wt/{name}` for simplicity. - -Creation uses `git worktree add -B` (`worktree.ts:326-328`), preferring `origin/` over current HEAD. - -### State Management - -CC has no task-worktree binding. Worktree state is managed through `PersistedWorktreeSession` (`worktree.ts:756-768`), with fields including `originalCwd`, `worktreePath`, `worktreeName`, `worktreeBranch`, `originalBranch`, `originalHeadCommit`, `sessionId`, etc. — no taskId field. `saveWorktreeState()` (`sessionStorage.ts:2883-2920`) writes to session transcript with `type: 'worktree-state'`. - -Teaching version uses the task's `worktree` field for binding, a teaching simplification. CC treats worktree and task as two independent systems, connected through the Agent's context understanding. - -
diff --git a/s18_worktree_isolation/README.zh.md b/s17_worktree_isolation/README.zh.md similarity index 59% rename from s18_worktree_isolation/README.zh.md rename to s17_worktree_isolation/README.zh.md index 0cc17529..16329707 100644 --- a/s18_worktree_isolation/README.zh.md +++ b/s17_worktree_isolation/README.zh.md @@ -1,8 +1,8 @@ -# s18: Worktree Isolation — 各干各的,互不干扰 +# s17: Worktree Isolation — 各干各的,互不干扰 [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s16 → s17 → `s18` → [s19](../s19_mcp_plugin/) → s20 → s21 → s22 +s01 → ... → s15 → s16 → `s17` → [s18](../s18_mcp_plugin/) → s19 → s20 → s21 > *"各干各的目录, 互不干扰"* — 任务管目标, worktree 管目录, 按 ID 绑定。 > @@ -12,11 +12,11 @@ s01 → ... → s16 → s17 → `s18` → [s19](../s19_mcp_plugin/) → s20 → ## 问题 -s17 中,Alice 和 Bob 都在同一个目录下工作。Alice 的任务是"重构认证模块",Bob 的任务是"重构 UI 登录页"。 +s16 中,Alice 和 Bob 都在同一个目录下工作。Alice 的任务是"重构认证模块",Bob 的任务是"重构 UI 登录页"。 Alice `write_file("config.py", ...)`。Bob 也 `write_file("config.py", ...)`。两个人改同一个文件,互相覆盖。而且无法干净地回滚——分不清哪些改动是谁的。 -s15-s17 解决了"谁干什么"(任务系统)和"怎么通信"(消息总线),但没解决"在哪干"。 +s15-s16 解决了"谁干什么"(任务系统)和"怎么通信"(消息总线),但没解决"在哪干"。 --- @@ -26,7 +26,7 @@ s15-s17 解决了"谁干什么"(任务系统)和"怎么通信"(消息总 Git worktree 让你在同一仓库中创建多个独立的工作目录,每个有自己的分支。Alice 在 `.worktrees/auth-refactor/` 下工作,Bob 在 `.worktrees/ui-login/` 下工作——互不干扰。 -沿用 S17 的教学版 MessageBus、协议和自治认领机制。本章新增: +沿用 s16 的 MessageBus、协议和自治认领机制。本章新增: | 能力 | 作用 | |------|------| @@ -63,7 +63,7 @@ def bind_task_to_worktree(task_id: str, worktree_name: str): ### 队友工具的 cwd 切换 -教学版给每个队友维护一个 `wt_ctx` 字典,记录当前 worktree 路径。队友认领带 worktree 的任务时,`wt_ctx` 自动设置为 worktree 路径;队友的 `bash`、`read_file`、`write_file` 在 worktree 目录下执行: +每个队友都有一个 `wt_ctx` 字典,用来记录当前 worktree 路径。队友认领绑定了 worktree 的任务后,运行时会更新 `wt_ctx`;该队友的 `bash`、`read_file`、`write_file` 随后都在对应的 worktree 目录下执行: ```python # 队友线程内部 @@ -81,8 +81,6 @@ def _run_bash(command): return run_bash(command, cwd=wt_ctx["path"]) # 在 worktree 下执行 ``` -这是教学简化。真实 CC 的 EnterWorktree 用 `process.chdir()` 切换整个进程目录,AgentTool isolation 用 `cwdOverride` 包住子 agent 执行。 - ### 收尾:Keep 还是 Remove 任务完成后,两个选择: @@ -118,7 +116,7 @@ def log_event(event_type: str, worktree_name: str, task_id: str = ""): # append to .worktrees/events.jsonl ``` -事件类型:`create`(创建)、`remove`(删除)、`keep`(保留)。教学版只记录事件用于人工排查;完整恢复还需要 index 或 `git worktree list` 扫描。 +事件类型包括 `create`(创建)、`remove`(删除)和 `keep`(保留)。日志用于人工排查;恢复流程可以通过 `git worktree list` 重建当前 worktree 集合。 ### run_git:返回成功/失败 @@ -132,9 +130,9 @@ def run_git(args: list[str]) -> tuple[bool, str]: --- -## 相对 s17 的变更 +## 相对 s16 的变更 -| 组件 | 之前 (s17) | 之后 (s18) | +| 组件 | 之前 (s16) | 之后 (s17) | |------|-----------|-----------| | 工作目录 | 所有 Agent 共享 WORKDIR | 每个任务可绑定独立 git worktree | | Task 数据 | id/subject/status/owner/blockedBy | + worktree 字段 | @@ -142,8 +140,8 @@ def run_git(args: list[str]) -> tuple[bool, str]: | 新函数 | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name | | worktree 安全 | 无 | name 校验 + 有改动时拒绝删除 | | 事件日志 | 无 | events.jsonl 生命周期审计 | -| Lead 工具 | 14 (s17) | + create_worktree, remove_worktree, keep_worktree (17) | -| 队友工具 | 8 (s17) | 8(bash/read/write 在 worktree cwd 执行) | +| Lead 工具 | 团队与任务工具 | + create_worktree、remove_worktree、keep_worktree | +| 队友工具 | 任务与文件工具 | 工具不变,bash/read/write 使用已认领任务的 worktree cwd | --- @@ -151,12 +149,12 @@ def run_git(args: list[str]) -> tuple[bool, str]: ```sh cd learn-claude-code -python s18_worktree_isolation/code.py +python s17_worktree_isolation/code.py ``` 试试这个 prompt: -`Create two tasks, then create worktrees for each (bind with task_id). Spawn alice and bob. Watch them auto-claim and work in isolated directories.` +`请并行重构认证模块和登录页面,确保两部分改动不会互相干扰。` 观察重点:两个 worktree 的 `git status` 输出是否显示不同的分支?队友认领带 worktree 的任务后,bash 命令是否在 worktree 目录下执行?`remove_worktree` 对有改动的 worktree 是否拒绝?`.tasks/` 中的任务在绑定后状态是否仍为 `pending`? @@ -168,41 +166,7 @@ Agent 团队能在隔离的工作空间中自组织了。但 Agent 的能力受 如果用户已经有了自己的工具怎么办?比如一个公司内部的 Jira API、一个自建的部署系统? -s19 MCP Plugin → 给 Agent 装一个插件系统。外部工具通过标准协议接入,Agent 不需要知道它们是谁写的。 +s18 MCP Plugin → 给 Agent 装一个插件系统。外部工具通过标准协议接入,Agent 不需要知道它们是谁写的。 -
-深入 CC 源码 - -CC 的 worktree 系统有两条路径:**EnterWorktree**(当前会话切入)和 **AgentTool isolation**(子 agent 隔离)。 - -### EnterWorktree:当前会话切换 - -`EnterWorktreeTool.ts:92-97` 创建 worktree 后立即 `process.chdir(worktreePath)`、`setCwd()`、`setOriginalCwd()`、`saveWorktreeState()`。当前会话的工作目录直接切换到 worktree——不是 prompt 提醒,而是进程级目录变更。 - -`ExitWorktreeTool.ts:261-320` 的 keep/remove 都会 `restoreSessionToOriginalCwd()` 恢复原目录。Remove 时检查未提交改动(`ExitWorktreeTool.ts:190-220`),没有 `discard_changes: true` 就拒绝删除。 - -### AgentTool isolation:子 agent 隔离 - -`AgentTool.tsx:590-641` 在 `isolation: "worktree"` 时调用 `createAgentWorktree()` 创建 worktree,用 `cwdOverridePath` 包住子 agent 执行。子 agent 的所有操作自动在 worktree 目录下进行。`AgentTool/prompt.ts:272` 告诉模型:这是临时 worktree,无改动自动清理,有改动返回路径和分支。 - -`worktree.ts:902-951` 的 `createAgentWorktree()` 不修改全局 session cwd,只给子 agent 用。`worktree.ts:961-1020` 的 `removeAgentWorktree()` 从主 repo root 删除。 - -### name 校验 - -`worktree.ts:76-84` 校验 slug:拒绝 `.`/`..`,允许 `[a-zA-Z0-9._-]`。`worktree.ts:48` 定义 `VALID_WORKTREE_SLUG_SEGMENT`。教学版的 `validate_worktree_name` 用同样的规则。 - -### 路径和分支命名 - -真实路径是 `.claude/worktrees/`,分支名 `worktree-{slug}`(`worktree.ts:204-227`,斜杠用 `+` 替代)。教学版用 `.worktrees/` 和 `wt/{name}` 简化。 - -创建时用 `git worktree add -B`(`worktree.ts:326-328`),优先基于 `origin/` 而非当前 HEAD。 - -### 状态管理 - -CC 没有 task-worktree 绑定。Worktree 状态通过 `PersistedWorktreeSession`(`worktree.ts:756-768`)管理,字段包括 `originalCwd`、`worktreePath`、`worktreeName`、`worktreeBranch`、`originalBranch`、`originalHeadCommit`、`sessionId` 等——没有 taskId。`saveWorktreeState()`(`sessionStorage.ts:2883-2920`)以 `type: 'worktree-state'` 写入 session transcript。 - -教学版用 task 的 `worktree` 字段做绑定,是教学简化。CC 把 worktree 和 task 作为两个独立系统,通过 Agent 理解上下文来关联。 - -
diff --git a/s18_worktree_isolation/code.py b/s17_worktree_isolation/code.py similarity index 65% rename from s18_worktree_isolation/code.py rename to s17_worktree_isolation/code.py index d64a18c5..af8c9ba0 100644 --- a/s18_worktree_isolation/code.py +++ b/s17_worktree_isolation/code.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 """ -s18: Worktree Isolation — git worktree + task-directory binding + event log. +s17: Worktree Isolation — git worktree + task-directory binding + event log. -Run: python s18_worktree_isolation/code.py +Run: python s17_worktree_isolation/code.py Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY -Changes from s17: +Changes from s16: - Task dataclass gains worktree field (str | None) - validate_worktree_name: reject path traversal and illegal chars - create_worktree: validate name, git worktree add, optional task binding @@ -14,7 +14,7 @@ Changes from s17: - run_git returns (ok, output), events only on success - Teammate tools: + complete_task, run in worktree cwd when bound - scan_unclaimed_tasks: uses can_start() for dependency checking - - idle_poll: checks claim result, dispatches shutdown in IDLE + - Idle teammates wait for messages, then scan and claim ready tasks - consume_lead_inbox: unified inbox consumer - 3 new Lead tools: create_worktree, remove_worktree, keep_worktree @@ -26,7 +26,7 @@ ASCII topology: └── .worktrees/events.jsonl """ -import os, subprocess, json, time, random, threading, re +import os, subprocess, json, time, random, threading, queue, re from pathlib import Path from datetime import datetime from dataclasses import dataclass, asdict, field @@ -48,10 +48,11 @@ WORKDIR = Path.cwd() client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL")) MODEL = os.environ["MODEL_ID"] -# ── Task System (from s12 + s18 worktree field) ── +# ── Task System (from s12 + s17 worktree field) ── TASKS_DIR = WORKDIR / ".tasks" TASKS_DIR.mkdir(exist_ok=True) +task_lock = threading.RLock() @dataclass @@ -62,7 +63,7 @@ class Task: status: str owner: str | None blockedBy: list[str] - worktree: str | None = None # s18: bound worktree name + worktree: str | None = None # s17: bound worktree name def _task_path(task_id: str) -> Path: @@ -110,22 +111,27 @@ def can_start(task_id: str) -> bool: def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - deps = [d for d in task.blockedBy - if _task_path(d).exists() and load_task(d).status != "completed"] - missing = [d for d in task.blockedBy if not _task_path(d).exists()] - parts = [] - if deps: parts.append(f"blocked by: {deps}") - if missing: parts.append(f"missing deps: {missing}") - return "Cannot start — " + ", ".join(parts) - task.owner = owner - task.status = "in_progress" - save_task(task) + with task_lock: + task = load_task(task_id) + if task.status != "pending": + return f"Task {task_id} is {task.status}, cannot claim" + if task.owner: + return f"Task {task_id} already owned by {task.owner}" + if not can_start(task_id): + deps = [d for d in task.blockedBy + if (_task_path(d).exists() + and load_task(d).status != "completed")] + missing = [d for d in task.blockedBy + if not _task_path(d).exists()] + parts = [] + if deps: + parts.append(f"blocked by: {deps}") + if missing: + parts.append(f"missing deps: {missing}") + return "Cannot start: " + ", ".join(parts) + task.owner = owner + task.status = "in_progress" + save_task(task) print(f" \033[36m[claim] {task.subject} → in_progress\033[0m") return f"Claimed {task.id} ({task.subject})" @@ -145,7 +151,7 @@ def complete_task(task_id: str) -> str: return msg -# ── Worktree System (s18 new) ── +# ── Worktree System (s17 new) ── WORKTREES_DIR = WORKDIR / ".worktrees" WORKTREES_DIR.mkdir(exist_ok=True) @@ -269,9 +275,14 @@ PROMPT_SECTIONS = { "identity": "You are a coding agent. Act, don't explain.", "tools": "Available tools: bash, read_file, write_file, " "create_task, list_tasks, get_task, claim_task, complete_task, " - "spawn_teammate, send_message, check_inbox, " + "spawn_teammate, send_message, " "request_shutdown, request_plan, review_plan, " "create_worktree, remove_worktree, keep_worktree.", + "teams": ( + "When parallel work would help, first propose a small team with clear " + "responsibilities and wait for the user's confirmation. Do not call " + "spawn_teammate before the user confirms." + ), "workspace": f"Working directory: {WORKDIR}", "memory": "Relevant memories are injected below when available.", } @@ -280,6 +291,7 @@ PROMPT_SECTIONS = { def assemble_system_prompt(context: dict) -> str: sections = [PROMPT_SECTIONS["identity"], PROMPT_SECTIONS["tools"], + PROMPT_SECTIONS["teams"], PROMPT_SECTIONS["workspace"]] if context.get("memories"): sections.append(f"Relevant memories:\n{context['memories']}") @@ -342,22 +354,29 @@ def run_write(path: str, content: str, cwd: Path = None) -> str: MAILBOX_DIR = WORKDIR / ".mailboxes" MAILBOX_DIR.mkdir(exist_ok=True) +MAILBOX_ROOT = MAILBOX_DIR.resolve() +VALID_AGENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$") + + +def is_valid_agent_name(name: str) -> bool: + return bool(VALID_AGENT_NAME.fullmatch(name)) class MessageBus: - def send(self, from_agent: str, to_agent: str, content: str, - msg_type: str = "message", metadata: dict = None): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time(), "metadata": metadata or {}} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") - print(f" \033[33m[bus] {from_agent} → {to_agent}: " - f"({msg_type}) {content[:50]}\033[0m") + def __init__(self): + self._lock = threading.RLock() + self._changed = threading.Condition(self._lock) - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" + def _path(self, agent: str) -> Path: + if not is_valid_agent_name(agent): + raise ValueError(f"Invalid mailbox recipient: {agent!r}") + path = (MAILBOX_DIR / f"{agent}.jsonl").resolve() + if not path.is_relative_to(MAILBOX_ROOT): + raise ValueError(f"Mailbox path escapes directory: {agent!r}") + return path + + def _read_unlocked(self, agent: str) -> list[dict]: + inbox = self._path(agent) if not inbox.exists(): return [] msgs = [json.loads(line) for line in inbox.read_text().splitlines() @@ -365,11 +384,47 @@ class MessageBus: inbox.unlink() return msgs + def send(self, from_agent: str, to_agent: str, content: str, + msg_type: str = "message", metadata: dict | None = None): + msg = {"from": from_agent, "to": to_agent, + "content": content, "type": msg_type, + "ts": time.time(), "metadata": metadata or {}} + with self._changed: + with open(self._path(to_agent), "a") as f: + f.write(json.dumps(msg, ensure_ascii=False) + "\n") + self._changed.notify_all() + print(f" \033[33m[bus] {from_agent} → {to_agent}: " + f"({msg_type}) {content[:50]}\033[0m") + + def read_inbox(self, agent: str) -> list[dict]: + with self._lock: + return self._read_unlocked(agent) + + def peek(self, agent: str) -> bool: + with self._lock: + inbox = self._path(agent) + return inbox.exists() and inbox.stat().st_size > 0 + + def wait_for_messages(self, agent: str, + timeout: float | None = None) -> list[dict]: + deadline = None if timeout is None else time.monotonic() + timeout + with self._changed: + while not self.peek(agent): + remaining = (None if deadline is None + else deadline - time.monotonic()) + if remaining is not None and remaining <= 0: + return [] + self._changed.wait(remaining) + return self._read_unlocked(agent) + BUS = MessageBus() -active_teammates: dict[str, bool] = {} +active_teammates: dict[str, str] = {} +plan_gates: dict[str, str] = {} +plan_request_ids: dict[str, str] = {} +team_lock = threading.RLock() -# ── Protocol State (from s16) ── +# ── Protocol State (from s15) ── @dataclass class ProtocolState: @@ -386,27 +441,38 @@ pending_requests: dict[str, ProtocolState] = {} def new_request_id() -> str: - return f"req_{random.randint(0, 999999):06d}" + while True: + request_id = f"req_{random.randint(0, 999999):06d}" + if request_id not in pending_requests: + return request_id -def match_response(response_type: str, request_id: str, approve: bool): - state = pending_requests.get(request_id) - if not state: - print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") - return - if state.type == "shutdown" and response_type != "shutdown_response": - print(f" \033[31m[protocol] type mismatch: expected shutdown_response, " - f"got {response_type}\033[0m") - return - if state.type == "plan_approval" and response_type != "plan_approval_response": - print(f" \033[31m[protocol] type mismatch: expected plan_approval_response, " - f"got {response_type}\033[0m") - return - state.status = "approved" if approve else "rejected" +def match_response(response_type: str, request_id: str, approve: bool, + from_agent: str, to_agent: str) -> bool: + with team_lock: + state = pending_requests.get(request_id) + if not state: + print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") + return False + expected = { + "shutdown": "shutdown_response", + "plan_approval": "plan_approval_response", + }[state.type] + if response_type != expected: + print(f" \033[31m[protocol] expected {expected}, " + f"got {response_type}\033[0m") + return False + if from_agent != state.target or to_agent != state.sender: + print(f" \033[31m[protocol] {request_id} responder mismatch\033[0m") + return False + if state.status != "pending": + return False + state.status = "approved" if approve else "rejected" icon = "✓" if approve else "✗" color = "32" if approve else "31" print(f" \033[{color}m[protocol] {state.type} {icon} " f"({request_id}: {state.status})\033[0m") + return True def consume_lead_inbox(route_protocol=True) -> list[dict]: @@ -417,83 +483,137 @@ def consume_lead_inbox(route_protocol=True) -> list[dict]: req_id = meta.get("request_id", "") msg_type = msg.get("type", "") if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) + match_response(msg_type, req_id, meta.get("approve", False), + msg.get("from", ""), msg.get("to", "")) return msgs -# ── Autonomous Agent (from s17, + worktree cwd) ── - -IDLE_POLL_INTERVAL = 5 -IDLE_TIMEOUT = 60 +def format_team_events(msgs: list[dict]) -> str: + lines = [] + for msg in msgs: + request_id = msg.get("metadata", {}).get("request_id") + suffix = f" request_id={request_id}" if request_id else "" + lines.append( + f"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}" + ) + return "[Team events]\n" + "\n".join(lines) -def scan_unclaimed_tasks() -> list[dict]: - """Find pending, unowned tasks with all dependencies completed.""" - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed +# ── Autonomous Agent (from s16, + worktree cwd) ── + +IDLE_SCAN_INTERVAL = 2.0 -def idle_poll(agent_name: str, messages: list, - name: str, role: str) -> tuple[str, str | None]: - """Poll for 60s. Return (result, auto_claimed_task_id).""" - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - - inbox = BUS.read_inbox(agent_name) - if inbox: - for msg in inbox: - if msg.get("type") == "shutdown_request": - req_id = msg.get("metadata", {}).get("request_id", "") - BUS.send(name, "lead", "Shutting down gracefully.", - "shutdown_response", - {"request_id": req_id, "approve": True}) - print(f" \033[35m[protocol] {name} approved shutdown " - f"in idle ({req_id})\033[0m") - return "shutdown", None - - messages.append({"role": "user", - "content": "" + json.dumps(inbox) + ""}) - print(f" \033[36m[idle] {name} found inbox messages\033[0m") - return "work", None - - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task_data = unclaimed[0] - result = claim_task(task_data["id"], agent_name) - if "Claimed" in result: - wt_info = "" - if task_data.get("worktree"): - wt_path = WORKTREES_DIR / task_data["worktree"] - wt_info = f"\nWork directory: {wt_path}" - messages.append({"role": "user", - "content": f"Task {task_data['id']}: " - f"{task_data['subject']}{wt_info}"}) - print(f" \033[32m[idle] {name} auto-claimed: " - f"{task_data['subject']}\033[0m") - return "work", task_data["id"] - print(f" \033[33m[idle] {name} claim failed: " - f"{result}\033[0m") - - print(f" \033[31m[idle] {name} timeout ({IDLE_TIMEOUT}s)\033[0m") - return "timeout", None +def scan_unclaimed_tasks() -> list[Task]: + return [ + task for task in list_tasks() + if (task.status == "pending" + and task.owner is None + and can_start(task.id)) + ] -# ── Teammate Thread (from s15 + s16 + s17 + s18) ── +def claim_next_task(name: str) -> Task | None: + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None + + +def _last_assistant_text(content) -> str: + for block in content: + if getattr(block, "type", None) == "text": + return block.text.strip() + if isinstance(block, dict) and block.get("type") == "text": + return str(block.get("text", "")).strip() + return "" + + +def _run_teammate_tool(name: str, block, handlers: dict) -> str: + gate = plan_gates.get(name, "not_required") + if (block.name in {"bash", "write_file"} + and gate not in {"not_required", "approved"}): + return f"Blocked: plan status is {gate}." + handler = handlers.get(block.name) + return str(handler(**block.input)) if handler else f"Unknown tool: {block.name}" + + +def apply_plan_response(name: str, msg: dict) -> tuple[bool, str]: + """Apply only the Lead response for this teammate's current plan.""" + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + expected_id = plan_request_ids.get(name) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and request_id == expected_id + and state is not None + and state.type == "plan_approval" + and state.sender == name + and state.target == "lead" + and state.status in {"approved", "rejected"} + and metadata.get("approve", False) + == (state.status == "approved") + ) + if not valid: + return False, "[Ignored plan response: request mismatch]" + plan_gates[name] = state.status + active_teammates[name] = "working" + plan_request_ids.pop(name, None) + outcome = state.status + return True, f"[Plan {outcome}] {msg['content']}" + + +def apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]: + """Accept only a pending shutdown request sent by Lead to this teammate.""" + request_id = msg.get("metadata", {}).get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and state is not None + and state.type == "shutdown" + and state.sender == "lead" + and state.target == name + and state.status == "pending" + and active_teammates.get(name) != "stopping" + ) + if not valid: + return False, "[Ignored shutdown request: request mismatch]" + active_teammates[name] = "stopping" + return True, request_id + + +def _teammate_send_message(from_name: str, to: str, content: str) -> str: + with team_lock: + if to != "lead" and to not in active_teammates: + return f"Agent '{to}' is not active" + BUS.send(from_name, to, content) + return f"Sent to {to}" + + +# ── Teammate Thread ── def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - if name in active_teammates: - return f"Teammate '{name}' already exists" + if not is_valid_agent_name(name): + return ("Invalid teammate name: use 1-64 letters, digits, " + "underscores, or dashes") + with team_lock: + if name in active_teammates: + return f"Teammate '{name}' already exists" + active_teammates[name] = "working" + plan_gates[name] = "not_required" system = (f"You are '{name}', a {role}. " - f"Use tools to complete tasks. " - f"You can list and claim tasks from the board. " - f"If a task has a worktree, work in that directory.") + "Use tools to complete tasks. " + "You can list and claim tasks from the board. " + "If a task has a worktree, work in that directory. " + "When asked for a plan, submit it before bash or write_file " + "and wait for approval.") def handle_inbox_message(name: str, msg: dict, messages: list): msg_type = msg.get("type", "message") @@ -501,6 +621,11 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: req_id = meta.get("request_id", "") if msg_type == "shutdown_request": + accepted, notice = apply_shutdown_request(name, msg) + if not accepted: + messages.append({"role": "user", "content": notice}) + return False + req_id = notice BUS.send(name, "lead", "Shutting down gracefully.", "shutdown_response", {"request_id": req_id, "approve": True}) @@ -509,13 +634,15 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: return True if msg_type == "plan_approval_response": - approve = meta.get("approve", False) - if approve: - messages.append({"role": "user", - "content": "[Plan approved] Proceed with the task."}) - else: - messages.append({"role": "user", - "content": f"[Plan rejected] Feedback: {msg['content']}"}) + _, notice = apply_plan_response(name, msg) + messages.append({"role": "user", + "content": notice}) + elif msg_type == "plan_request": + messages.append({"role": "user", + "content": f"[Plan required] {msg['content']}"}) + elif msg_type == "message": + messages.append({"role": "user", + "content": f"[Message from {msg['from']}] {msg['content']}"}) return False def run(): @@ -605,8 +732,8 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: sub_handlers = { "bash": _run_bash, "read_file": _run_read, "write_file": _run_write, - "send_message": lambda to, content: (BUS.send(name, to, content), - "Sent")[1], + "send_message": lambda to, content: _teammate_send_message( + name, to, content), "submit_plan": lambda plan: _teammate_submit_plan(name, plan), "list_tasks": _run_list_tasks, "claim_task": _run_claim_task, @@ -631,13 +758,6 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: break if should_shutdown: break - if inbox and not should_shutdown: - non_protocol = [m for m in inbox - if m.get("type") == "message"] - if non_protocol: - messages.append({"role": "user", - "content": "" + json.dumps(non_protocol) + ""}) - try: response = client.messages.create( model=MODEL, system=system, messages=messages[-20:], @@ -646,12 +766,23 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: break messages.append({"role": "assistant", "content": response.content}) if response.stop_reason != "tool_use": + summary = _last_assistant_text(response.content) + gate = plan_gates.get(name, "not_required") + if gate != "pending" and summary: + BUS.send(name, "lead", summary, "result") + if gate == "pending": + with team_lock: + active_teammates[name] = "waiting_approval" + else: + with team_lock: + active_teammates[name] = "idle" + BUS.send(name, "lead", "Waiting for more work.", + "idle_notification") break results = [] for block in response.content: if block.type == "tool_use": - handler = sub_handlers.get(block.name) - output = handler(**block.input) if handler else "Unknown" + output = _run_teammate_tool(name, block, sub_handlers) results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(output)}) @@ -660,60 +791,78 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: if should_shutdown: break - # IDLE phase - idle_result, claimed_task_id = idle_poll(name, messages, name, role) - if idle_result == "shutdown": - break - if idle_result == "timeout": - break - if idle_result == "work" and claimed_task_id: - task = load_task(claimed_task_id) - if task.get("worktree"): - wt_ctx["path"] = str(WORKTREES_DIR / task["worktree"]) - else: - wt_ctx["path"] = None - - # Summary - summary = "Done." - for msg in reversed(messages): - if msg["role"] == "assistant" and isinstance(msg["content"], list): - for b in msg["content"]: - if getattr(b, "type", None) == "text": - summary = b.text + # IDLE phase: messages take priority, then scan the task board. + while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + for msg in inbox: + if handle_inbox_message(name, msg, messages): + should_shutdown = True + break + if should_shutdown or messages[-1]["role"] == "user": break - else: continue + + task = claim_next_task(name) + if not task: + continue + wt_ctx["path"] = (str(WORKTREES_DIR / task.worktree) + if task.worktree else None) + workdir = (f"\nWork directory: {wt_ctx['path']}" + if wt_ctx["path"] else "") + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}{workdir}" + ), + }) + print(f" \033[32m[idle] {name} claimed " + f"{task.id}: {task.subject}\033[0m") break - BUS.send(name, "lead", summary, "result") - active_teammates.pop(name, None) + if should_shutdown: + break + + with team_lock: + active_teammates.pop(name, None) + plan_gates.pop(name, None) + plan_request_ids.pop(name, None) print(f" \033[32m[teammate] {name} finished\033[0m") - active_teammates[name] = True threading.Thread(target=run, daemon=True).start() print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") return f"Teammate '{name}' spawned as {role} (autonomous)" def _teammate_submit_plan(from_name: str, plan: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="plan_approval", - sender=from_name, target="lead", - status="pending", payload=plan) + with team_lock: + if plan_gates.get(from_name) == "pending": + return "A plan is already waiting for review." + req_id = new_request_id() + pending_requests[req_id] = ProtocolState( + request_id=req_id, type="plan_approval", + sender=from_name, target="lead", + status="pending", payload=plan) + plan_gates[from_name] = "pending" + plan_request_ids[from_name] = req_id + active_teammates[from_name] = "waiting_approval" BUS.send(from_name, "lead", plan, "plan_approval_request", {"request_id": req_id}) return f"Plan submitted ({req_id}). Waiting for approval..." -# ── Lead Protocol Tools (from s16) ── +# ── Lead Protocol Tools (from s15) ── def run_request_shutdown(teammate: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="shutdown", - sender="lead", target=teammate, - status="pending", payload="") + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + req_id = new_request_id() + pending_requests[req_id] = ProtocolState( + request_id=req_id, type="shutdown", + sender="lead", target=teammate, + status="pending", payload="") BUS.send("lead", teammate, "Please shut down gracefully.", "shutdown_request", {"request_id": req_id}) @@ -723,19 +872,27 @@ def run_request_shutdown(teammate: str) -> str: def run_request_plan(teammate: str, task: str) -> str: - BUS.send("lead", teammate, f"Please submit a plan for: {task}", - "message") + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + plan_gates[teammate] = "required" + BUS.send("lead", teammate, task, "plan_request") return f"Asked {teammate} to submit a plan" def run_review_plan(request_id: str, approve: bool, feedback: str = "") -> str: - state = pending_requests.get(request_id) - if not state: - return f"Request {request_id} not found" - if state.status != "pending": - return f"Request {request_id} already {state.status}" - state.status = "approved" if approve else "rejected" + with team_lock: + state = pending_requests.get(request_id) + if not state: + return f"Request {request_id} not found" + if state.type != "plan_approval": + return f"Request {request_id} is not a plan" + if state.status != "pending": + return f"Request {request_id} already {state.status}" + if plan_request_ids.get(state.sender) != request_id: + return f"Request {request_id} is not the current plan" + state.status = "approved" if approve else "rejected" BUS.send("lead", state.sender, feedback or ("Approved" if approve else "Rejected"), "plan_approval_response", @@ -745,7 +902,7 @@ def run_review_plan(request_id: str, approve: bool, return f"Plan {'approved' if approve else 'rejected'} ({request_id})" -# ── Lead Worktree Tools (s18 new) ── +# ── Lead Worktree Tools (s17 new) ── def run_create_worktree(name: str, task_id: str = "") -> str: return create_worktree(name, task_id) @@ -796,23 +953,12 @@ def run_spawn_teammate(name: str, role: str, prompt: str) -> str: def run_send_message(to: str, content: str) -> str: + if to not in active_teammates: + return f"Teammate '{to}' is not active" BUS.send("lead", to, content) return f"Sent to {to}" -def run_check_inbox() -> str: - msgs = consume_lead_inbox(route_protocol=True) - if not msgs: - return "(inbox empty)" - lines = [] - for m in msgs: - meta = m.get("metadata", {}) - req_id = meta.get("request_id", "") - tag = f" [{m['type']} req:{req_id}]" if req_id else f" [{m['type']}]" - lines.append(f" [{m['from']}]{tag} {m['content'][:200]}") - return "\n".join(lines) - - # ── Tool Definitions ── TOOLS = [ @@ -859,7 +1005,10 @@ TOOLS = [ {"name": "spawn_teammate", "description": "Spawn an autonomous teammate agent.", "input_schema": {"type": "object", - "properties": {"name": {"type": "string"}, + "properties": {"name": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$", + }, "role": {"type": "string"}, "prompt": {"type": "string"}}, "required": ["name", "role", "prompt"]}}, @@ -869,9 +1018,6 @@ TOOLS = [ "properties": {"to": {"type": "string"}, "content": {"type": "string"}}, "required": ["to", "content"]}}, - {"name": "check_inbox", - "description": "Check inbox for messages and protocol responses.", - "input_schema": {"type": "object", "properties": {}, "required": []}}, {"name": "request_shutdown", "description": "Request a teammate to shut down gracefully.", "input_schema": {"type": "object", @@ -891,7 +1037,7 @@ TOOLS = [ "approve": {"type": "boolean"}, "feedback": {"type": "string"}}, "required": ["request_id", "approve"]}}, - # s18 new: worktree tools + # s17 new: worktree tools {"name": "create_worktree", "description": "Create an isolated git worktree with its own branch.", "input_schema": {"type": "object", @@ -917,7 +1063,7 @@ TOOL_HANDLERS = { "get_task": run_get_task, "claim_task": run_claim_task, "complete_task": run_complete_task, "spawn_teammate": run_spawn_teammate, - "send_message": run_send_message, "check_inbox": run_check_inbox, + "send_message": run_send_message, "request_shutdown": run_request_shutdown, "request_plan": run_request_plan, "review_plan": run_review_plan, "create_worktree": run_create_worktree, @@ -973,18 +1119,49 @@ def agent_loop(messages: list, context: dict): if __name__ == "__main__": - print("s18: worktree isolation") + print("s17: worktree isolation") print("Enter a question, press Enter to send. Type q to quit.\n") history = [] context = {"memories": ""} + + events = queue.Queue() + + def input_reader(): + while True: + try: + line = input("\033[36ms17 >> \033[0m") + except (EOFError, KeyboardInterrupt): + events.put(("quit", None)) + return + events.put(("user", line)) + + def inbox_poller(): + while True: + time.sleep(1) + if BUS.peek("lead"): + events.put(("wake", None)) + + threading.Thread(target=input_reader, daemon=True).start() + threading.Thread(target=inbox_poller, daemon=True).start() + + had_teammates = False while True: - try: - query = input("\033[36ms18 >> \033[0m") - except (EOFError, KeyboardInterrupt): + kind, payload = events.get() + if kind == "quit": break - if query.strip().lower() in ("q", "exit", ""): - break - history.append({"role": "user", "content": query}) + if kind == "user": + if payload.strip().lower() in ("q", "exit", ""): + break + history.append({"role": "user", "content": payload}) + else: + inbox = consume_lead_inbox(route_protocol=True) + if not inbox: + continue + history.append({"role": "user", + "content": format_team_events(inbox)}) + print(f"\n\033[33m[wake: {len(inbox)} team events " + f"-> new turn]\033[0m") + agent_loop(history, context) context = update_context(context, history) for block in history[-1]["content"]: @@ -993,12 +1170,9 @@ if __name__ == "__main__": elif isinstance(block, dict) and block.get("type") == "text": print(block.get("text", "")) - # Consume lead inbox: route protocol + inject into history - inbox = consume_lead_inbox(route_protocol=True) - if inbox: - inbox_text = "\n".join( - f"From {m['from']} [{m.get('type', 'message')}]: " - f"{m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) + if active_teammates: + had_teammates = True + elif had_teammates and not BUS.peek("lead"): + print("\033[32m[all teammates shut down]\033[0m") + had_teammates = False print() diff --git a/web/public/course-assets/s18_worktree_isolation/worktree-overview.en.svg b/s17_worktree_isolation/images/worktree-overview.en.svg similarity index 91% rename from web/public/course-assets/s18_worktree_isolation/worktree-overview.en.svg rename to s17_worktree_isolation/images/worktree-overview.en.svg index 57c915f7..87ab6bee 100644 --- a/web/public/course-assets/s18_worktree_isolation/worktree-overview.en.svg +++ b/s17_worktree_isolation/images/worktree-overview.en.svg @@ -23,11 +23,11 @@ - s17 Preserved + s16 Preserved - s18 New + s17 New - + turn @@ -49,7 +49,7 @@ - TOOL DISPATCH (s17 + s18) + TOOL DISPATCH (s16 + s17) bash · read · write · task(4) · send · inbox request_shutdown · request_plan · review_plan ★ create_worktree · remove_worktree · keep_worktree @@ -57,9 +57,9 @@ - + - Worktree Isolation (s18 new: each task gets its own directory + branch) + Worktree Isolation (s17 new: each task gets its own directory + branch) @@ -92,12 +92,12 @@ Event log: .worktrees/events.jsonl → create / remove / keep - Cleanup: keep (preserve branch for review) / remove (delete + mark done) + Cleanup: keep (preserve for review) / remove (delete worktree) - s17: idle_poll + auto_claim + protocols + WORK/IDLE lifecycle + s16: scan_unclaimed_tasks + claim_next_task + task_lock - s18: create_worktree + bind_task + remove/keep + events.jsonl (Lead 14→17) + s17: create_worktree + bind_task + remove/keep + events.jsonl diff --git a/web/public/course-assets/s18_worktree_isolation/worktree-overview.ja.svg b/s17_worktree_isolation/images/worktree-overview.ja.svg similarity index 92% rename from web/public/course-assets/s18_worktree_isolation/worktree-overview.ja.svg rename to s17_worktree_isolation/images/worktree-overview.ja.svg index 2a26071d..e8b8d75c 100644 --- a/web/public/course-assets/s18_worktree_isolation/worktree-overview.ja.svg +++ b/s17_worktree_isolation/images/worktree-overview.ja.svg @@ -23,9 +23,9 @@ - s17 保持 + s16 保持 - s18 新規 + s17 新規 @@ -49,7 +49,7 @@ - TOOL DISPATCH(s17 + s18) + TOOL DISPATCH(s16 + s17) bash · read · write · task(4) · send · inbox request_shutdown · request_plan · review_plan ★ create_worktree · remove_worktree · keep_worktree @@ -59,7 +59,7 @@ - Worktree 隔離(s18 新規:各タスクに独立ディレクトリ + 独立ブランチ) + Worktree 隔離(s17 新規:各タスクに独立ディレクトリ + 独立ブランチ) @@ -92,12 +92,12 @@ イベントログ: .worktrees/events.jsonl → create / remove / keep - 片付け: keep(ブランチ保持 review)/ remove(削除+完了マーク) + 片付け: keep(review 用に保持)/ remove(worktree を削除) - s17: idle_poll + auto_claim + protocols + WORK/IDLE ライフサイクル + s16: scan_unclaimed_tasks + claim_next_task + task_lock - s18: create_worktree + bind_task + remove/keep + events.jsonl(Lead 14→17) + s17: create_worktree + bind_task + remove/keep + events.jsonl diff --git a/s18_worktree_isolation/images/worktree-overview.svg b/s17_worktree_isolation/images/worktree-overview.svg similarity index 91% rename from s18_worktree_isolation/images/worktree-overview.svg rename to s17_worktree_isolation/images/worktree-overview.svg index 2b88a75c..402eef74 100644 --- a/s18_worktree_isolation/images/worktree-overview.svg +++ b/s17_worktree_isolation/images/worktree-overview.svg @@ -23,11 +23,11 @@ - s17 保留 + s16 保留 - s18 新增 + s17 新增 - + turn @@ -49,7 +49,7 @@ - TOOL DISPATCH (s17 + s18) + TOOL DISPATCH (s16 + s17) bash · read · write · task(4) · send · inbox request_shutdown · request_plan · review_plan ★ create_worktree · remove_worktree · keep_worktree @@ -57,9 +57,9 @@ - + - Worktree 隔离(s18 新增:每个任务独立目录 + 独立分支) + Worktree 隔离(s17 新增:每个任务独立目录 + 独立分支) @@ -92,12 +92,12 @@ 事件日志: .worktrees/events.jsonl → create / remove / keep - 收尾: keep (保留分支 review) / remove (删除+标记完成) + 收尾: keep (保留分支 review) / remove (删除 worktree) - s17: idle_poll + auto_claim + protocols + WORK/IDLE lifecycle + s16: scan_unclaimed_tasks + claim_next_task + task_lock - s18: create_worktree + bind_task + remove/keep + events.jsonl (Lead 14→17) + s17: create_worktree + bind_task + remove/keep + events.jsonl diff --git a/s18_mcp_plugin/README.ja.md b/s18_mcp_plugin/README.ja.md new file mode 100644 index 00000000..7cf2a918 --- /dev/null +++ b/s18_mcp_plugin/README.ja.md @@ -0,0 +1,182 @@ +# s18: MCP Tools — 外部ツール、標準プロトコル + +[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) + +s01 → ... → s16 → s17 → `s18` → [s19](../s19_comprehensive/) → s20 → s21 + +> *"外部ツール、標準プロトコル"* — 発見、組み立て、呼び出し。Agent はツールを誰が書いたか知る必要がない。 +> +> **Harness 層**: プラグイン — 外部能力を標準プロトコルで接続。 + +--- + +## 課題 + +s01 から s17 まで、Agent の全ツールは手書き — bash、read、write、task、worktree。入力検証、実行ロジック、エラーハンドリング、全て一行ずつ書いた。 + +今、統合したい外部サービスが 3 つある:社内の Jira API(issue 検索、ticket 作成)、独自のデプロイシステム(deploy トリガー、ログ閲覧)、チームの Notion ナレッジベース(ドキュメント検索、ページ作成)。各サービスのためにツールコードを書き直したくない。 + +標準プロトコルが必要 — 外部サービスがこのプロトコルを実装していれば、サービスが何の言語で書かれていても、Agent は直接そのツールを呼び出せる。 + +--- + +## ソリューション + +![MCP Architecture](images/mcp-architecture.ja.svg) + +MCP(Model Context Protocol)は、Agent が外部ツールを発見・呼び出しする方法を定義。核心概念: + +| 概念 | 目的 | +|------|------| +| MCPClient | Agent 側のクライアント — server に接続、ツールを発見、ツールを呼び出し | +| MCP Server | 外部サービス側 — `tools/list` + `tools/call` を実装 | +| assemble_tool_pool | 組み込みツールと MCP ツールを一つのツールプールに組み立てる | +| mcp\_\_server\_\_tool 命名 | 異なる server 間のツール名衝突を防止 | + +s17 の worktree 分離、自動認領、チームプロトコルを引き継ぐ。本章では `connect_mcp` ツールを追加し、サービスへの接続、ツール発見、ツールプールへの追加を行う。 + +本章はプロセス内の server handler を登録し、発見から呼び出しまでをオフラインで実行する。各 handler はクライアントが必要とする `tools/list` と `tools/call` を提供する。 + +--- + +## 仕組み + +### MCPClient:発見 + 呼び出し + +```python +class MCPClient: + def __init__(self, name: str): + self.name = name + self.tools: list[dict] = [] + self._handlers: dict[str, callable] = {} + + def register(self, tool_defs, handlers): + """Simulates tools/list discovery.""" + self.tools = tool_defs + self._handlers = handlers + + def call_tool(self, tool_name: str, args: dict) -> str: + """Simulates tools/call.""" + handler = self._handlers.get(tool_name) + if not handler: + return f"MCP error: unknown tool '{tool_name}'" + return handler(**args) +``` + +登録した Python 関数が、`tools/call` から呼ばれる server 側のツール実装になる。 + +### connect_mcp:接続 + 発見 + +```python +def connect_mcp(name: str) -> str: + if name in mcp_clients: + return f"MCP server '{name}' already connected" + factory = MOCK_SERVERS.get(name) + if not factory: + return f"Unknown server '{name}'. Available: ..." + mcp_client = factory() + mcp_clients[name] = mcp_client + return f"Connected to '{name}'. Discovered: ..." +``` + +接続後、server が提供するツールが即座に利用可能。 + +### normalize_mcp_name:名前の正規化 + +```python +_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]') + +def normalize_mcp_name(name: str) -> str: + return _DISALLOWED_CHARS.sub('_', name) +``` + +`[a-zA-Z0-9_-]` 以外の全文字を `_` に置換。server 名やツール名の特殊文字による名前衝突やインジェクション問題を防止。 + +### assemble_tool_pool:ツールプールの組み立て + +```python +def assemble_tool_pool() -> tuple[list[dict], dict]: + tools = list(BUILTIN_TOOLS) + handlers = dict(BUILTIN_HANDLERS) + for server_name, mcp_client in mcp_clients.items(): + safe_server = normalize_mcp_name(server_name) + for tool_def in mcp_client.tools: + safe_tool = normalize_mcp_name(tool_def["name"]) + prefixed = f"mcp__{safe_server}__{safe_tool}" + tools.append(...) + handlers[prefixed] = ( + lambda *, c=mcp_client, t=tool_def["name"], **kw: + c.call_tool(t, kw)) + return tools, handlers +``` + +プレフィックス `mcp__{server}__{tool}` で異なる server 間のツール名衝突を防止。名前は `normalize_mcp_name` で正規化。 + +MCP ツールの description に `(readOnly)` または `(destructive)` を付け、読み取りと変更の区別をツールメタデータ上で明示する。 + +### キャッシュなし:ツールプールが変われば、プロンプトも変わる + +s10-s17 の agent_loop は prompt cache で再シリアライズを回避。s18 はキャッシュを削除: + +```python +def agent_loop(messages, context): + tools, handlers = assemble_tool_pool() # 毎回再構築 + system = assemble_system_prompt(context) # 毎回再生成 + ... + if any(b.name == "connect_mcp" ...): + tools, handlers = assemble_tool_pool() # 接続後に再構築 + system = assemble_system_prompt(context) +``` + +`connect_mcp` の後には `mcp__docs__search` などがツールプールへ加わる。古いシリアライズ済みツール一覧を再利用するとモデルから新しいツールが見えないため、接続後にツールプールと system prompt を再構築する。 + +### MCP ツールは Lead のみ利用可能 + +`connect_mcp` は Lead のツールであり、`assemble_tool_pool` も Lead の agent loop に使われる。チームメイトはタスク、ファイル、メッセージ、プランの各ツールを保持し、Lead が外部サービスを呼び出して得た仕事を割り当てる。 + +--- + +## s17 からの変更 + +| コンポーネント | 変更前 (s17) | 変更後 (s18) | +|--------------|------------|------------| +| ツールソース | 全て手書き builtin | 手書き + MCP 外部ツール動的発見 | +| ツールプール | 固定 BUILTIN_TOOLS | assemble_tool_pool が動的に mcp\_\_ プレフィックスツールを組み立てる | +| 名前の安全性 | なし | normalize_mcp_name 正規化 | +| 新規タイプ | — | MCPClient クラス(tools/list + tools/call をシミュレート) | +| 名前空間 | — | mcp\_\_server\_\_tool 衝突防止 | +| ツール説明 | アノテーションなし | (readOnly)/(destructive) アノテーション | +| プロンプトキャッシュ | あり(s10 から) | 削除 — ツールプールが動的、キャッシュが陳腐化 | +| Lead ツール | worktree・チームツール | + connect_mcp と動的に発見した MCP ツール | +| チームメイトツール | タスク、ファイル、メッセージ、プランのツール | 変更なし | +| 拡張方法 | ツール追加のコードを書く | 標準プロトコル、任意言語で server を実装 | + +--- + +## 試してみる + +```sh +cd learn-claude-code +python s18_mcp_plugin/code.py +``` + +以下のプロンプトを試してください: + +1. `ドキュメントから worktree のクリーンアップ方針を調べてください。` +2. `現在のプロジェクトをデプロイし、結果を報告してください。` +3. `現在実行できるドキュメント操作とデプロイ操作を教えてください。` + +観察ポイント:MCP server 接続後、ツール名に `mcp__docs__` や `mcp__deploy__` プレフィックスが付いているか?両方の server のツールが同時に利用可能か?MCP ツールの description に (readOnly)/(destructive) アノテーションが付いているか? + +--- + +## 次の章 + +Agent は標準プロトコルで外部ツールに接続できるようになった。前 18 章では、各境界を観察できるように仕組みを一つずつ追加してきた。 + +tools、permissions、hooks、todo、task graph、memory、compact、background work、cron、teams、worktree、MCP は、別々の例ではなく同じ loop に接続されるべきです。 + +s19 Comprehensive Agent → s01-s18 の仕組みを 1 つの完全な harness に統合。仕組みは多く、loop は 1 つ。 + + + diff --git a/s18_mcp_plugin/README.md b/s18_mcp_plugin/README.md new file mode 100644 index 00000000..bdcc86d1 --- /dev/null +++ b/s18_mcp_plugin/README.md @@ -0,0 +1,182 @@ +# s18: MCP Tools — External Tools, Standard Protocol + +[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) + +s01 → ... → s16 → s17 → `s18` → [s19](../s19_comprehensive/) → s20 → s21 + +> *"External tools, standard protocol"* — Discover, assemble, invoke. Agent doesn't need to know who wrote them. +> +> **Harness layer**: Plugins — External capabilities via a standard protocol. + +--- + +## The Problem + +From s01 through s17, every tool the agent uses was hand-written — bash, read, write, task, worktree. Input validation, execution logic, error handling — all written line by line. + +Now you have 3 external services to integrate: the company's Jira API (query issues, create tickets), an in-house deployment system (trigger deploys, view logs), and the team's Notion knowledge base (search docs, create pages). You don't want to rewrite tool code for every service. + +You need a standard protocol — as long as an external service implements it, the agent can call its tools directly, regardless of what language the service is written in. + +--- + +## The Solution + +![MCP Architecture](images/mcp-architecture.en.svg) + +MCP (Model Context Protocol) defines how agents discover and invoke external tools. Core concepts: + +| Concept | Purpose | +|------|------| +| MCPClient | The agent-side client — connects to servers, discovers tools, invokes tools | +| MCP Server | The external service — implements `tools/list` + `tools/call` | +| assemble_tool_pool | Assembles built-in tools and MCP tools into one tool pool | +| mcp\_\_server\_\_tool naming | Prevents tool name collisions across different servers | + +Carries forward s17's worktree isolation, autonomous claiming, and team protocols. This chapter adds the `connect_mcp` tool, which connects to a service, discovers its tools, and adds them to the tool pool. + +The chapter registers in-process server handlers so the full discovery and invocation flow runs offline. Each handler exposes the two operations the client needs: `tools/list` and `tools/call`. + +--- + +## How It Works + +### MCPClient: Discovery + Invocation + +```python +class MCPClient: + def __init__(self, name: str): + self.name = name + self.tools: list[dict] = [] + self._handlers: dict[str, callable] = {} + + def register(self, tool_defs, handlers): + """Simulates tools/list discovery.""" + self.tools = tool_defs + self._handlers = handlers + + def call_tool(self, tool_name: str, args: dict) -> str: + """Simulates tools/call.""" + handler = self._handlers.get(tool_name) + if not handler: + return f"MCP error: unknown tool '{tool_name}'" + return handler(**args) +``` + +The registered Python functions provide the server-side tool implementations used by `tools/call`. + +### connect_mcp: Connect + Discover + +```python +def connect_mcp(name: str) -> str: + if name in mcp_clients: + return f"MCP server '{name}' already connected" + factory = MOCK_SERVERS.get(name) + if not factory: + return f"Unknown server '{name}'. Available: ..." + mcp_client = factory() + mcp_clients[name] = mcp_client + return f"Connected to '{name}'. Discovered: ..." +``` + +After connecting, the server's tools are immediately available. + +### normalize_mcp_name: Name Normalization + +```python +_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]') + +def normalize_mcp_name(name: str) -> str: + return _DISALLOWED_CHARS.sub('_', name) +``` + +All non-`[a-zA-Z0-9_-]` characters are replaced with `_`. Prevents special characters in server or tool names from causing naming conflicts or injection issues. + +### assemble_tool_pool: Assemble Tool Pool + +```python +def assemble_tool_pool() -> tuple[list[dict], dict]: + tools = list(BUILTIN_TOOLS) + handlers = dict(BUILTIN_HANDLERS) + for server_name, mcp_client in mcp_clients.items(): + safe_server = normalize_mcp_name(server_name) + for tool_def in mcp_client.tools: + safe_tool = normalize_mcp_name(tool_def["name"]) + prefixed = f"mcp__{safe_server}__{safe_tool}" + tools.append(...) + handlers[prefixed] = ( + lambda *, c=mcp_client, t=tool_def["name"], **kw: + c.call_tool(t, kw)) + return tools, handlers +``` + +The prefix `mcp__{server}__{tool}` prevents tool name collisions across different servers. Names are normalized through `normalize_mcp_name`. + +MCP tool descriptions include `(readOnly)` or `(destructive)` labels, making the distinction visible in the tool metadata. + +### No Cache: Tool Pool Changes, Prompt Changes Too + +s10-s17's agent_loop used prompt caching to avoid re-serialization. s18 removes the cache: + +```python +def agent_loop(messages, context): + tools, handlers = assemble_tool_pool() # Rebuild every time + system = assemble_system_prompt(context) # Regenerate every time + ... + if any(b.name == "connect_mcp" ...): + tools, handlers = assemble_tool_pool() # Rebuild after connection + system = assemble_system_prompt(context) +``` + +After `connect_mcp`, the tool pool gains entries such as `mcp__docs__search`. Reusing the old serialized tool list would hide those entries from the model, so the loop rebuilds the pool and system prompt after every connection. + +### MCP Tools: Lead Only + +`connect_mcp` belongs to the Lead, and `assemble_tool_pool` serves the Lead's agent loop. Teammates keep their task, file, message, and plan tools; the Lead invokes external services and dispatches the resulting work. + +--- + +## Changes from s17 + +| Component | Before (s17) | After (s18) | +|------|-----------|-----------| +| Tool source | All hand-written built-in | Hand-written + MCP external tools with dynamic discovery | +| Tool pool | Fixed BUILTIN_TOOLS | assemble_tool_pool dynamically assembles mcp\_\_ prefixed tools | +| Name safety | None | normalize_mcp_name normalization | +| New type | — | MCPClient class (simulates tools/list + tools/call) | +| Namespace | — | mcp\_\_server\_\_tool prevents collisions | +| Tool descriptions | No annotations | (readOnly)/(destructive) annotations | +| Prompt cache | Yes (since s10) | Removed — tool pool is dynamic, cache goes stale | +| Lead tools | Worktree and team tools | + connect_mcp and dynamically discovered MCP tools | +| Teammate tools | Task, file, message, and plan tools | Unchanged | +| Extension method | Write code to add tools | Standard protocol, implement servers in any language | + +--- + +## Try It Out + +```sh +cd learn-claude-code +python s18_mcp_plugin/code.py +``` + +Try these prompts: + +1. `Search the docs for the worktree cleanup policy.` +2. `Deploy the current project and report the result.` +3. `What documentation and deployment actions can you perform?` + +What to observe: After connecting to an MCP server, do tool names have `mcp__docs__` or `mcp__deploy__` prefixes? Are both servers' tools available simultaneously? Do MCP tool descriptions include (readOnly)/(destructive) annotations? + +--- + +## What's Next + +The Agent can now connect external tools through a standard protocol. The first 18 chapters introduced these mechanisms one at a time so each boundary stayed visible. + +Tools, permissions, hooks, todo, task graph, memory, compact, background work, cron, teams, worktrees, and MCP should all attach to the same loop, not live in separate examples. + +s19 Comprehensive Agent → Combine the mechanisms from s01-s18 into one complete harness. Many mechanisms, one loop. + + + diff --git a/s18_mcp_plugin/README.zh.md b/s18_mcp_plugin/README.zh.md new file mode 100644 index 00000000..9431e152 --- /dev/null +++ b/s18_mcp_plugin/README.zh.md @@ -0,0 +1,182 @@ +# s18: MCP Tools — 外接工具,标准协议 + +[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) + +s01 → ... → s16 → s17 → `s18` → [s19](../s19_comprehensive/) → s20 → s21 + +> *"外接工具, 标准协议"* — 发现、组装、调用,Agent 不需要知道工具是谁写的。 +> +> **Harness 层**: 插件 — 外部能力通过标准协议接入。 + +--- + +## 问题 + +s01 到 s17,Agent 的所有工具都是手写的——bash、read、write、task、worktree。每个工具的输入验证、执行逻辑、错误处理,都是你一行行写的。 + +现在你有 3 个外部服务想接入:公司的 Jira API(查 issue、建 ticket)、自建的部署系统(触发 deploy、看日志)、团队的 Notion 知识库(搜文档、建页面)。你不想为每个服务重写一套工具代码。 + +你需要一个标准协议——外部服务只要实现它,Agent 就能直接调用,不管服务用什么语言写的。 + +--- + +## 解决方案 + +![MCP Architecture](images/mcp-architecture.svg) + +MCP(Model Context Protocol)定义了 Agent 如何发现和调用外部工具。核心概念: + +| 概念 | 作用 | +|------|------| +| MCPClient | Agent 端的客户端,连接 server、发现工具、调用工具 | +| MCP Server | 外部服务,实现 `tools/list` + `tools/call` | +| assemble_tool_pool | 把内置工具和 MCP 工具组装成一个工具池 | +| mcp\_\_server\_\_tool 命名 | 避免不同 server 的工具名冲突 | + +沿用 s17 的 worktree 隔离、自主认领和团队协议。本章新增 `connect_mcp` 工具,用于连接服务、发现工具并加入工具池。 + +本章注册进程内 server handler,让工具发现和调用流程可以离线运行。每个 handler 都提供客户端需要的 `tools/list` 和 `tools/call` 两个操作。 + +--- + +## 工作原理 + +### MCPClient:发现 + 调用 + +```python +class MCPClient: + def __init__(self, name: str): + self.name = name + self.tools: list[dict] = [] + self._handlers: dict[str, callable] = {} + + def register(self, tool_defs, handlers): + """Simulates tools/list discovery.""" + self.tools = tool_defs + self._handlers = handlers + + def call_tool(self, tool_name: str, args: dict) -> str: + """Simulates tools/call.""" + handler = self._handlers.get(tool_name) + if not handler: + return f"MCP error: unknown tool '{tool_name}'" + return handler(**args) +``` + +注册的 Python 函数提供 `tools/call` 所调用的 server 端工具实现。 + +### connect_mcp:连接 + 发现 + +```python +def connect_mcp(name: str) -> str: + if name in mcp_clients: + return f"MCP server '{name}' already connected" + factory = MOCK_SERVERS.get(name) + if not factory: + return f"Unknown server '{name}'. Available: ..." + mcp_client = factory() + mcp_clients[name] = mcp_client + return f"Connected to '{name}'. Discovered: ..." +``` + +连接后,server 提供的工具立即可用。 + +### normalize_mcp_name:名称规范化 + +```python +_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]') + +def normalize_mcp_name(name: str) -> str: + return _DISALLOWED_CHARS.sub('_', name) +``` + +所有非 `[a-zA-Z0-9_-]` 的字符替换为 `_`。防止 server 名或工具名中包含特殊字符导致命名冲突或注入问题。 + +### assemble_tool_pool:组装工具池 + +```python +def assemble_tool_pool() -> tuple[list[dict], dict]: + tools = list(BUILTIN_TOOLS) + handlers = dict(BUILTIN_HANDLERS) + for server_name, mcp_client in mcp_clients.items(): + safe_server = normalize_mcp_name(server_name) + for tool_def in mcp_client.tools: + safe_tool = normalize_mcp_name(tool_def["name"]) + prefixed = f"mcp__{safe_server}__{safe_tool}" + tools.append(...) + handlers[prefixed] = ( + lambda *, c=mcp_client, t=tool_def["name"], **kw: + c.call_tool(t, kw)) + return tools, handlers +``` + +前缀 `mcp__{server}__{tool}` 避免不同 server 的工具名冲突。名称经过 `normalize_mcp_name` 规范化。 + +MCP 工具的 description 带 `(readOnly)` 或 `(destructive)` 标注,让只读操作和修改操作在工具元数据中直接可见。 + +### 无缓存:工具池变了,prompt 也变 + +s10-s17 的 agent_loop 用 prompt cache 避免重复序列化。s18 去掉了缓存: + +```python +def agent_loop(messages, context): + tools, handlers = assemble_tool_pool() # 每次重新构建 + system = assemble_system_prompt(context) # 每次重新生成 + ... + if any(b.name == "connect_mcp" ...): + tools, handlers = assemble_tool_pool() # 连接后重建 + system = assemble_system_prompt(context) +``` + +`connect_mcp` 之后,工具池会新增 `mcp__docs__search` 等条目。继续复用旧的序列化工具列表,模型就看不到这些工具,所以每次连接后都要重建工具池和 system prompt。 + +### MCP 工具只有 Lead 可用 + +`connect_mcp` 属于 Lead,`assemble_tool_pool` 也服务于 Lead 的 agent loop。Teammate 保留任务、文件、消息和计划工具,由 Lead 调用外部服务,再把得到的工作分派下去。 + +--- + +## 相对 s17 的变更 + +| 组件 | 之前 (s17) | 之后 (s18) | +|------|-----------|-----------| +| 工具来源 | 全部手写 builtin | 手写 + MCP 外部工具动态发现 | +| 工具池 | 固定 BUILTIN_TOOLS | assemble_tool_pool 动态组装 mcp\_\_ 前缀工具 | +| 名称安全 | 无 | normalize_mcp_name 规范化 | +| 新类型 | — | MCPClient 类(模拟 tools/list + tools/call) | +| 命名空间 | — | mcp\_\_server\_\_tool 避免冲突 | +| 工具描述 | 无标注 | (readOnly)/(destructive) 标注 | +| prompt 缓存 | 有(s10 起) | 去掉——工具池动态变化后缓存失效 | +| Lead 工具 | worktree 与团队工具 | + connect_mcp 和动态发现的 MCP 工具 | +| Teammate 工具 | 任务、文件、消息与计划工具 | 不变 | +| 扩展方式 | 写代码加工具 | 标准协议,任意语言实现 server | + +--- + +## 试一下 + +```sh +cd learn-claude-code +python s18_mcp_plugin/code.py +``` + +试试这些 prompt: + +1. `查一下文档里的 worktree 清理策略。` +2. `部署当前项目,并告诉我结果。` +3. `你现在可以执行哪些文档和部署操作?` + +观察重点:连接 MCP server 后,工具名是否带 `mcp__docs__` 或 `mcp__deploy__` 前缀?两个 server 的工具是否同时可用?MCP 工具的 description 是否带 (readOnly)/(destructive) 标注? + +--- + +## 接下来 + +现在 Agent 可以通过标准协议接入外部工具了。前 18 章逐个引入这些机制,让每个边界都能单独观察。 + +工具、权限、hooks、todo、任务图、记忆、压缩、后台、cron、团队、worktree、MCP 这些机制应该挂在同一个循环上,而不是散在 19 个 demo 里。 + +s19 Comprehensive Agent → 把 s01-s18 的机制合回一个完整 harness。机制很多,循环一个。 + + + diff --git a/s19_mcp_plugin/code.py b/s18_mcp_plugin/code.py similarity index 65% rename from s19_mcp_plugin/code.py rename to s18_mcp_plugin/code.py index eed5acec..0194891a 100644 --- a/s19_mcp_plugin/code.py +++ b/s18_mcp_plugin/code.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 """ -s19: MCP Tools — MCPClient + tool discovery + assemble_tool_pool. +s18: MCP Tools — MCPClient + tool discovery + assemble_tool_pool. -Run: python s19_mcp_plugin/code.py +Run: python s18_mcp_plugin/code.py Need: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY -Changes from s18: +Changes from s17: - MCPClient class: discovers tools, calls tools via mock handler - normalize_mcp_name: normalize tool/server names - assemble_tool_pool: assembles builtin + MCP tools into one pool @@ -13,7 +13,7 @@ Changes from s18: - Tool naming: mcp__{server}__{tool} with normalization - MCP tools have readOnly/destructive annotations - agent_loop uses dynamic tool pool (builtin + MCP), no prompt cache - - Teammate tools: complete_task, worktree cwd (from s17/s18 fixes) + - Teammate tools: complete_task, worktree cwd (from s16/s17 fixes) ASCII flow: connect_mcp("docs") → MCPClient discovers tools → @@ -21,7 +21,7 @@ ASCII flow: agent_loop uses assembled pool """ -import os, subprocess, json, time, random, threading, re +import os, subprocess, json, time, random, threading, queue, re from pathlib import Path from datetime import datetime from dataclasses import dataclass, asdict, field @@ -47,6 +47,7 @@ MODEL = os.environ["MODEL_ID"] TASKS_DIR = WORKDIR / ".tasks" TASKS_DIR.mkdir(exist_ok=True) +task_lock = threading.RLock() @dataclass @@ -104,22 +105,27 @@ def can_start(task_id: str) -> bool: def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - deps = [d for d in task.blockedBy - if _task_path(d).exists() and load_task(d).status != "completed"] - missing = [d for d in task.blockedBy if not _task_path(d).exists()] - parts = [] - if deps: parts.append(f"blocked by: {deps}") - if missing: parts.append(f"missing deps: {missing}") - return "Cannot start — " + ", ".join(parts) - task.owner = owner - task.status = "in_progress" - save_task(task) + with task_lock: + task = load_task(task_id) + if task.status != "pending": + return f"Task {task_id} is {task.status}, cannot claim" + if task.owner: + return f"Task {task_id} already owned by {task.owner}" + if not can_start(task_id): + deps = [d for d in task.blockedBy + if (_task_path(d).exists() + and load_task(d).status != "completed")] + missing = [d for d in task.blockedBy + if not _task_path(d).exists()] + parts = [] + if deps: + parts.append(f"blocked by: {deps}") + if missing: + parts.append(f"missing deps: {missing}") + return "Cannot start: " + ", ".join(parts) + task.owner = owner + task.status = "in_progress" + save_task(task) print(f" \033[36m[claim] {task.subject} → in_progress\033[0m") return f"Claimed {task.id} ({task.subject})" @@ -249,10 +255,15 @@ PROMPT_SECTIONS = { "identity": "You are a coding agent. Act, don't explain.", "tools": "Available tools: bash, read_file, write_file, " "create_task, list_tasks, get_task, claim_task, complete_task, " - "spawn_teammate, send_message, check_inbox, " + "spawn_teammate, send_message, " "request_shutdown, request_plan, review_plan, " "create_worktree, remove_worktree, keep_worktree, " "connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.", + "teams": ( + "When parallel work would help, first propose a small team with clear " + "responsibilities and wait for the user's confirmation. Do not call " + "spawn_teammate before the user confirms." + ), "workspace": f"Working directory: {WORKDIR}", "memory": "Relevant memories are injected below when available.", } @@ -261,6 +272,7 @@ PROMPT_SECTIONS = { def assemble_system_prompt(context: dict) -> str: sections = [PROMPT_SECTIONS["identity"], PROMPT_SECTIONS["tools"], + PROMPT_SECTIONS["teams"], PROMPT_SECTIONS["workspace"]] if context.get("memories"): sections.append(f"Relevant memories:\n{context['memories']}") @@ -310,26 +322,33 @@ def run_write(path: str, content: str, cwd: Path = None) -> str: return f"Error: {e}" -# ── MessageBus ── +# ── MessageBus (from s15) ── MAILBOX_DIR = WORKDIR / ".mailboxes" MAILBOX_DIR.mkdir(exist_ok=True) +MAILBOX_ROOT = MAILBOX_DIR.resolve() +VALID_AGENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$") + + +def is_valid_agent_name(name: str) -> bool: + return bool(VALID_AGENT_NAME.fullmatch(name)) class MessageBus: - def send(self, from_agent: str, to_agent: str, content: str, - msg_type: str = "message", metadata: dict = None): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time(), "metadata": metadata or {}} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") - print(f" \033[33m[bus] {from_agent} → {to_agent}: " - f"({msg_type}) {content[:50]}\033[0m") + def __init__(self): + self._lock = threading.RLock() + self._changed = threading.Condition(self._lock) - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" + def _path(self, agent: str) -> Path: + if not is_valid_agent_name(agent): + raise ValueError(f"Invalid mailbox recipient: {agent!r}") + path = (MAILBOX_DIR / f"{agent}.jsonl").resolve() + if not path.is_relative_to(MAILBOX_ROOT): + raise ValueError(f"Mailbox path escapes directory: {agent!r}") + return path + + def _read_unlocked(self, agent: str) -> list[dict]: + inbox = self._path(agent) if not inbox.exists(): return [] msgs = [json.loads(line) for line in inbox.read_text().splitlines() @@ -337,11 +356,47 @@ class MessageBus: inbox.unlink() return msgs + def send(self, from_agent: str, to_agent: str, content: str, + msg_type: str = "message", metadata: dict | None = None): + msg = {"from": from_agent, "to": to_agent, + "content": content, "type": msg_type, + "ts": time.time(), "metadata": metadata or {}} + with self._changed: + with open(self._path(to_agent), "a") as f: + f.write(json.dumps(msg, ensure_ascii=False) + "\n") + self._changed.notify_all() + print(f" \033[33m[bus] {from_agent} → {to_agent}: " + f"({msg_type}) {content[:50]}\033[0m") + + def read_inbox(self, agent: str) -> list[dict]: + with self._lock: + return self._read_unlocked(agent) + + def peek(self, agent: str) -> bool: + with self._lock: + inbox = self._path(agent) + return inbox.exists() and inbox.stat().st_size > 0 + + def wait_for_messages(self, agent: str, + timeout: float | None = None) -> list[dict]: + deadline = None if timeout is None else time.monotonic() + timeout + with self._changed: + while not self.peek(agent): + remaining = (None if deadline is None + else deadline - time.monotonic()) + if remaining is not None and remaining <= 0: + return [] + self._changed.wait(remaining) + return self._read_unlocked(agent) + BUS = MessageBus() -active_teammates: dict[str, bool] = {} +active_teammates: dict[str, str] = {} +plan_gates: dict[str, str] = {} +plan_request_ids: dict[str, str] = {} +team_lock = threading.RLock() -# ── Protocol State ── +# ── Protocol State (from s15) ── @dataclass class ProtocolState: @@ -358,18 +413,38 @@ pending_requests: dict[str, ProtocolState] = {} def new_request_id() -> str: - return f"req_{random.randint(0, 999999):06d}" + while True: + request_id = f"req_{random.randint(0, 999999):06d}" + if request_id not in pending_requests: + return request_id -def match_response(response_type: str, request_id: str, approve: bool): - state = pending_requests.get(request_id) - if not state: - return - if state.type == "shutdown" and response_type != "shutdown_response": - return - if state.type == "plan_approval" and response_type != "plan_approval_response": - return - state.status = "approved" if approve else "rejected" +def match_response(response_type: str, request_id: str, approve: bool, + from_agent: str, to_agent: str) -> bool: + with team_lock: + state = pending_requests.get(request_id) + if not state: + print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") + return False + expected = { + "shutdown": "shutdown_response", + "plan_approval": "plan_approval_response", + }[state.type] + if response_type != expected: + print(f" \033[31m[protocol] expected {expected}, " + f"got {response_type}\033[0m") + return False + if from_agent != state.target or to_agent != state.sender: + print(f" \033[31m[protocol] {request_id} responder mismatch\033[0m") + return False + if state.status != "pending": + return False + state.status = "approved" if approve else "rejected" + icon = "✓" if approve else "✗" + color = "32" if approve else "31" + print(f" \033[{color}m[protocol] {state.type} {icon} " + f"({request_id}: {state.status})\033[0m") + return True def consume_lead_inbox(route_protocol=True) -> list[dict]: @@ -380,88 +455,173 @@ def consume_lead_inbox(route_protocol=True) -> list[dict]: req_id = meta.get("request_id", "") msg_type = msg.get("type", "") if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) + match_response(msg_type, req_id, meta.get("approve", False), + msg.get("from", ""), msg.get("to", "")) return msgs -# ── Autonomous Agent ── - -IDLE_POLL_INTERVAL = 5 -IDLE_TIMEOUT = 60 +def format_team_events(msgs: list[dict]) -> str: + lines = [] + for msg in msgs: + request_id = msg.get("metadata", {}).get("request_id") + suffix = f" request_id={request_id}" if request_id else "" + lines.append( + f"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}" + ) + return "[Team events]\n" + "\n".join(lines) -def scan_unclaimed_tasks() -> list[dict]: - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed +# ── Autonomous Agent (from s16, + worktree cwd) ── + +IDLE_SCAN_INTERVAL = 2.0 -def idle_poll(agent_name: str, messages: list, - name: str, role: str) -> str: - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - inbox = BUS.read_inbox(agent_name) - if inbox: - for msg in inbox: - if msg.get("type") == "shutdown_request": - req_id = msg.get("metadata", {}).get("request_id", "") - BUS.send(name, "lead", "Shutting down.", - "shutdown_response", - {"request_id": req_id, "approve": True}) - return "shutdown" - messages.append({"role": "user", - "content": "" + json.dumps(inbox) + ""}) - return "work" - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task_data = unclaimed[0] - result = claim_task(task_data["id"], agent_name) - if "Claimed" in result: - wt_info = "" - if task_data.get("worktree"): - wt_info = f"\nWork directory: {WORKTREES_DIR / task_data['worktree']}" - messages.append({"role": "user", - "content": f"Task {task_data['id']}: " - f"{task_data['subject']}{wt_info}"}) - return "work" - return "timeout" +def scan_unclaimed_tasks() -> list[Task]: + return [ + task for task in list_tasks() + if (task.status == "pending" + and task.owner is None + and can_start(task.id)) + ] + + +def claim_next_task(name: str) -> Task | None: + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None + + +def _last_assistant_text(content) -> str: + for block in content: + if getattr(block, "type", None) == "text": + return block.text.strip() + if isinstance(block, dict) and block.get("type") == "text": + return str(block.get("text", "")).strip() + return "" + + +def _run_teammate_tool(name: str, block, handlers: dict) -> str: + gate = plan_gates.get(name, "not_required") + if (block.name in {"bash", "write_file"} + and gate not in {"not_required", "approved"}): + return f"Blocked: plan status is {gate}." + handler = handlers.get(block.name) + return str(handler(**block.input)) if handler else f"Unknown tool: {block.name}" + + +def apply_plan_response(name: str, msg: dict) -> tuple[bool, str]: + """Apply only the Lead response for this teammate's current plan.""" + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + expected_id = plan_request_ids.get(name) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and request_id == expected_id + and state is not None + and state.type == "plan_approval" + and state.sender == name + and state.target == "lead" + and state.status in {"approved", "rejected"} + and metadata.get("approve", False) + == (state.status == "approved") + ) + if not valid: + return False, "[Ignored plan response: request mismatch]" + plan_gates[name] = state.status + active_teammates[name] = "working" + plan_request_ids.pop(name, None) + outcome = state.status + return True, f"[Plan {outcome}] {msg['content']}" + + +def apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]: + """Accept only a pending shutdown request sent by Lead to this teammate.""" + request_id = msg.get("metadata", {}).get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and state is not None + and state.type == "shutdown" + and state.sender == "lead" + and state.target == name + and state.status == "pending" + and active_teammates.get(name) != "stopping" + ) + if not valid: + return False, "[Ignored shutdown request: request mismatch]" + active_teammates[name] = "stopping" + return True, request_id + + +def _teammate_send_message(from_name: str, to: str, content: str) -> str: + with team_lock: + if to != "lead" and to not in active_teammates: + return f"Agent '{to}' is not active" + BUS.send(from_name, to, content) + return f"Sent to {to}" # ── Teammate Thread ── def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - if name in active_teammates: - return f"Teammate '{name}' already exists" + if not is_valid_agent_name(name): + return ("Invalid teammate name: use 1-64 letters, digits, " + "underscores, or dashes") + with team_lock: + if name in active_teammates: + return f"Teammate '{name}' already exists" + active_teammates[name] = "working" + plan_gates[name] = "not_required" system = (f"You are '{name}', a {role}. " - f"Use tools to complete tasks. " - f"If a task has a worktree, work in that directory.") + "Use tools to complete tasks. " + "You can list and claim tasks from the board. " + "If a task has a worktree, work in that directory. " + "When asked for a plan, submit it before bash or write_file " + "and wait for approval.") def handle_inbox_message(name: str, msg: dict, messages: list): msg_type = msg.get("type", "message") meta = msg.get("metadata", {}) req_id = meta.get("request_id", "") + if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down.", + accepted, notice = apply_shutdown_request(name, msg) + if not accepted: + messages.append({"role": "user", "content": notice}) + return False + req_id = notice + BUS.send(name, "lead", "Shutting down gracefully.", "shutdown_response", {"request_id": req_id, "approve": True}) + print(f" \033[35m[protocol] {name} approved shutdown " + f"({req_id})\033[0m") return True + if msg_type == "plan_approval_response": - approve = meta.get("approve", False) + _, notice = apply_plan_response(name, msg) messages.append({"role": "user", - "content": "[Plan approved]" if approve - else f"[Plan rejected] {msg['content']}"}) + "content": notice}) + elif msg_type == "plan_request": + messages.append({"role": "user", + "content": f"[Plan required] {msg['content']}"}) + elif msg_type == "message": + messages.append({"role": "user", + "content": f"[Message from {msg['from']}] {msg['content']}"}) return False def run(): + # Track current worktree for this teammate's cwd wt_ctx = {"path": None} - def _wt_cwd(): + def _wt_cwd() -> Path | None: p = wt_ctx["path"] return Path(p) if p else None @@ -486,9 +646,12 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: def _run_claim_task(task_id: str): result = claim_task(task_id, owner=name) if "Claimed" in result: + # Set worktree cwd if task has one task = load_task(task_id) - wt_ctx["path"] = (str(WORKTREES_DIR / task.worktree) - if task.worktree else None) + if task.worktree: + wt_ctx["path"] = str(WORKTREES_DIR / task.worktree) + else: + wt_ctx["path"] = None return result def _run_complete_task(task_id: str): @@ -523,7 +686,7 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, {"name": "list_tasks", - "description": "List all tasks.", + "description": "List all tasks on the board.", "input_schema": {"type": "object", "properties": {}, "required": []}}, {"name": "claim_task", @@ -541,19 +704,22 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: sub_handlers = { "bash": _run_bash, "read_file": _run_read, "write_file": _run_write, - "send_message": lambda to, content: (BUS.send(name, to, content), - "Sent")[1], + "send_message": lambda to, content: _teammate_send_message( + name, to, content), "submit_plan": lambda plan: _teammate_submit_plan(name, plan), "list_tasks": _run_list_tasks, "claim_task": _run_claim_task, "complete_task": _run_complete_task, } + # Outer loop: WORK → IDLE cycle while True: if len(messages) <= 3: messages.insert(0, {"role": "user", "content": f"You are '{name}', role: {role}. " f"Continue your work."}) + + # WORK phase should_shutdown = False for _ in range(10): inbox = BUS.read_inbox(name) @@ -564,12 +730,6 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: break if should_shutdown: break - if inbox and not should_shutdown: - non_protocol = [m for m in inbox - if m.get("type") == "message"] - if non_protocol: - messages.append({"role": "user", - "content": "" + json.dumps(non_protocol) + ""}) try: response = client.messages.create( model=MODEL, system=system, messages=messages[-20:], @@ -578,87 +738,146 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: break messages.append({"role": "assistant", "content": response.content}) if response.stop_reason != "tool_use": + summary = _last_assistant_text(response.content) + gate = plan_gates.get(name, "not_required") + if gate != "pending" and summary: + BUS.send(name, "lead", summary, "result") + if gate == "pending": + with team_lock: + active_teammates[name] = "waiting_approval" + else: + with team_lock: + active_teammates[name] = "idle" + BUS.send(name, "lead", "Waiting for more work.", + "idle_notification") break results = [] for block in response.content: if block.type == "tool_use": - handler = sub_handlers.get(block.name) - output = handler(**block.input) if handler else "Unknown" + output = _run_teammate_tool(name, block, sub_handlers) results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(output)}) messages.append({"role": "user", "content": results}) + if should_shutdown: break - idle_result = idle_poll(name, messages, name, role) - if idle_result in ("shutdown", "timeout"): - break - summary = "Done." - for msg in reversed(messages): - if msg["role"] == "assistant" and isinstance(msg["content"], list): - for b in msg["content"]: - if getattr(b, "type", None) == "text": - summary = b.text + # IDLE phase: messages take priority, then scan the task board. + while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + for msg in inbox: + if handle_inbox_message(name, msg, messages): + should_shutdown = True + break + if should_shutdown or messages[-1]["role"] == "user": break - else: continue - break - BUS.send(name, "lead", summary, "result") - active_teammates.pop(name, None) - active_teammates[name] = True + task = claim_next_task(name) + if not task: + continue + wt_ctx["path"] = (str(WORKTREES_DIR / task.worktree) + if task.worktree else None) + workdir = (f"\nWork directory: {wt_ctx['path']}" + if wt_ctx["path"] else "") + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}{workdir}" + ), + }) + print(f" \033[32m[idle] {name} claimed " + f"{task.id}: {task.subject}\033[0m") + break + if should_shutdown: + break + + with team_lock: + active_teammates.pop(name, None) + plan_gates.pop(name, None) + plan_request_ids.pop(name, None) + print(f" \033[32m[teammate] {name} finished\033[0m") + threading.Thread(target=run, daemon=True).start() - return f"Teammate '{name}' spawned as {role}" + print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") + return f"Teammate '{name}' spawned as {role} (autonomous)" def _teammate_submit_plan(from_name: str, plan: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="plan_approval", - sender=from_name, target="lead", - status="pending", payload=plan) + with team_lock: + if plan_gates.get(from_name) == "pending": + return "A plan is already waiting for review." + req_id = new_request_id() + pending_requests[req_id] = ProtocolState( + request_id=req_id, type="plan_approval", + sender=from_name, target="lead", + status="pending", payload=plan) + plan_gates[from_name] = "pending" + plan_request_ids[from_name] = req_id + active_teammates[from_name] = "waiting_approval" BUS.send(from_name, "lead", plan, "plan_approval_request", {"request_id": req_id}) - return f"Plan submitted ({req_id})" + return f"Plan submitted ({req_id}). Waiting for approval..." -# ── Lead Protocol Tools ── +# ── Lead Protocol Tools (from s15) ── def run_request_shutdown(teammate: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="shutdown", - sender="lead", target=teammate, - status="pending", payload="") - BUS.send("lead", teammate, "Shut down.", "shutdown_request", + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + req_id = new_request_id() + pending_requests[req_id] = ProtocolState( + request_id=req_id, type="shutdown", + sender="lead", target=teammate, + status="pending", payload="") + BUS.send("lead", teammate, "Please shut down gracefully.", + "shutdown_request", {"request_id": req_id}) - return f"Shutdown request sent to {teammate}" + print(f" \033[35m[protocol] shutdown_request → {teammate} " + f"({req_id})\033[0m") + return f"Shutdown request sent to {teammate} (req: {req_id})" def run_request_plan(teammate: str, task: str) -> str: - BUS.send("lead", teammate, f"Submit plan for: {task}", "message") + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + plan_gates[teammate] = "required" + BUS.send("lead", teammate, task, "plan_request") return f"Asked {teammate} to submit a plan" def run_review_plan(request_id: str, approve: bool, feedback: str = "") -> str: - state = pending_requests.get(request_id) - if not state: - return f"Request {request_id} not found" - state.status = "approved" if approve else "rejected" + with team_lock: + state = pending_requests.get(request_id) + if not state: + return f"Request {request_id} not found" + if state.type != "plan_approval": + return f"Request {request_id} is not a plan" + if state.status != "pending": + return f"Request {request_id} already {state.status}" + if plan_request_ids.get(state.sender) != request_id: + return f"Request {request_id} is not the current plan" + state.status = "approved" if approve else "rejected" BUS.send("lead", state.sender, feedback or ("Approved" if approve else "Rejected"), "plan_approval_response", {"request_id": request_id, "approve": approve}) - return f"Plan {'approved' if approve else 'rejected'}" + icon = "✓" if approve else "✗" + print(f" \033[32m[protocol] plan {icon} ({request_id})\033[0m") + return f"Plan {'approved' if approve else 'rejected'} ({request_id})" -# ── MCP System (s19 new) ── +# ── MCP System (s18 new) ── class MCPClient: - """Discovers and calls tools on an MCP server (mock for teaching).""" + """Discovers and calls tools on an in-process MCP server.""" def __init__(self, name: str): self.name = name @@ -714,7 +933,7 @@ def _mock_server_deploy(): client.register( tool_defs=[ {"name": "trigger", - "description": "Trigger a deployment. (destructive — requires approval in real CC)", + "description": "Trigger a deployment. (destructive)", "inputSchema": {"type": "object", "properties": {"service": {"type": "string"}}, "required": ["service"]}}, @@ -815,21 +1034,11 @@ def run_spawn_teammate(name: str, role: str, prompt: str) -> str: return spawn_teammate_thread(name, role, prompt) def run_send_message(to: str, content: str) -> str: + if to not in active_teammates: + return f"Teammate '{to}' is not active" BUS.send("lead", to, content) return f"Sent to {to}" -def run_check_inbox() -> str: - msgs = consume_lead_inbox(route_protocol=True) - if not msgs: - return "(inbox empty)" - lines = [] - for m in msgs: - meta = m.get("metadata", {}) - req_id = meta.get("request_id", "") - tag = f" [{m['type']} req:{req_id}]" if req_id else f" [{m['type']}]" - lines.append(f" [{m['from']}]{tag} {m['content'][:200]}") - return "\n".join(lines) - def run_connect_mcp(name: str) -> str: return connect_mcp(name) @@ -874,7 +1083,10 @@ BUILTIN_TOOLS = [ "required": ["task_id"]}}, {"name": "spawn_teammate", "description": "Spawn an autonomous teammate.", "input_schema": {"type": "object", - "properties": {"name": {"type": "string"}, + "properties": {"name": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$", + }, "role": {"type": "string"}, "prompt": {"type": "string"}}, "required": ["name", "role", "prompt"]}}, @@ -883,9 +1095,6 @@ BUILTIN_TOOLS = [ "properties": {"to": {"type": "string"}, "content": {"type": "string"}}, "required": ["to", "content"]}}, - {"name": "check_inbox", - "description": "Check inbox for messages and protocol responses.", - "input_schema": {"type": "object", "properties": {}, "required": []}}, {"name": "request_shutdown", "description": "Request a teammate to shut down.", "input_schema": {"type": "object", @@ -934,7 +1143,7 @@ BUILTIN_HANDLERS = { "get_task": run_get_task, "claim_task": run_claim_task, "complete_task": run_complete_task, "spawn_teammate": run_spawn_teammate, - "send_message": run_send_message, "check_inbox": run_check_inbox, + "send_message": run_send_message, "request_shutdown": run_request_shutdown, "request_plan": run_request_plan, "review_plan": run_review_plan, "create_worktree": run_create_worktree, @@ -957,7 +1166,7 @@ def update_context(context: dict, messages: list) -> dict: return {"memories": memories} -# ── Agent Loop (s19: dynamic tool pool, no prompt cache) ── +# ── Agent Loop (s18: dynamic tool pool, no prompt cache) ── def agent_loop(messages: list, context: dict): tools, handlers = assemble_tool_pool() @@ -996,18 +1205,49 @@ def agent_loop(messages: list, context: dict): if __name__ == "__main__": - print("s19: mcp tools") + print("s18: mcp tools") print("Enter a question, press Enter to send. Type q to quit.\n") history = [] context = {"memories": ""} + + events = queue.Queue() + + def input_reader(): + while True: + try: + line = input("\033[36ms18 >> \033[0m") + except (EOFError, KeyboardInterrupt): + events.put(("quit", None)) + return + events.put(("user", line)) + + def inbox_poller(): + while True: + time.sleep(1) + if BUS.peek("lead"): + events.put(("wake", None)) + + threading.Thread(target=input_reader, daemon=True).start() + threading.Thread(target=inbox_poller, daemon=True).start() + + had_teammates = False while True: - try: - query = input("\033[36ms19 >> \033[0m") - except (EOFError, KeyboardInterrupt): + kind, payload = events.get() + if kind == "quit": break - if query.strip().lower() in ("q", "exit", ""): - break - history.append({"role": "user", "content": query}) + if kind == "user": + if payload.strip().lower() in ("q", "exit", ""): + break + history.append({"role": "user", "content": payload}) + else: + inbox = consume_lead_inbox(route_protocol=True) + if not inbox: + continue + history.append({"role": "user", + "content": format_team_events(inbox)}) + print(f"\n\033[33m[wake: {len(inbox)} team events " + f"-> new turn]\033[0m") + agent_loop(history, context) context = update_context(context, history) for block in history[-1]["content"]: @@ -1016,11 +1256,9 @@ if __name__ == "__main__": elif isinstance(block, dict) and block.get("type") == "text": print(block.get("text", "")) - inbox = consume_lead_inbox(route_protocol=True) - if inbox: - inbox_text = "\n".join( - f"From {m['from']} [{m.get('type', 'message')}]: " - f"{m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) + if active_teammates: + had_teammates = True + elif had_teammates and not BUS.peek("lead"): + print("\033[32m[all teammates shut down]\033[0m") + had_teammates = False print() diff --git a/s19_mcp_plugin/images/mcp-architecture.en.svg b/s18_mcp_plugin/images/mcp-architecture.en.svg similarity index 94% rename from s19_mcp_plugin/images/mcp-architecture.en.svg rename to s18_mcp_plugin/images/mcp-architecture.en.svg index 01d0c068..914da1c1 100644 --- a/s19_mcp_plugin/images/mcp-architecture.en.svg +++ b/s18_mcp_plugin/images/mcp-architecture.en.svg @@ -23,11 +23,11 @@ - s18 Preserved + s17 Preserved - s19 New + s18 New - + turn @@ -58,9 +58,9 @@ - + - MCP Architecture (s19 new: standard protocol + external tools dynamic integration) + MCP Architecture (s18 new: standard protocol + external tools dynamic integration) @@ -102,11 +102,11 @@ - s18: worktree + events + protocols (Lead 17) + s17: worktree + events + protocols (Lead 17) - s19: MCP + dynamic tools (Lead 18) + s18: MCP + dynamic tools (Lead 18) - Next: s20 combines tools, permissions, teams, worktrees, MCP, and more into one while True loop. + Next: s19 combines tools, permissions, teams, worktrees, MCP, and more into one while True loop. diff --git a/s19_mcp_plugin/images/mcp-architecture.ja.svg b/s18_mcp_plugin/images/mcp-architecture.ja.svg similarity index 96% rename from s19_mcp_plugin/images/mcp-architecture.ja.svg rename to s18_mcp_plugin/images/mcp-architecture.ja.svg index d2b5255c..86960beb 100644 --- a/s19_mcp_plugin/images/mcp-architecture.ja.svg +++ b/s18_mcp_plugin/images/mcp-architecture.ja.svg @@ -23,9 +23,9 @@ - s18 保持 + s17 保持 - s19 新規 + s18 新規 @@ -60,7 +60,7 @@ - MCP アーキテクチャ(s19 新規:標準プロトコル + 外部ツール動的統合) + MCP アーキテクチャ(s18 新規:標準プロトコル + 外部ツール動的統合) @@ -102,11 +102,11 @@ - s18: worktree + events + protocols(Lead 17) + s17: worktree + events + protocols(Lead 17) - s19: MCP + dynamic tools(Lead 18) + s18: MCP + dynamic tools(Lead 18) - 次の s20:tools、permissions、teams、worktree、MCP などを 1 つの while True ループに統合。 + 次の s19:tools、permissions、teams、worktree、MCP などを 1 つの while True ループに統合。 diff --git a/web/public/course-assets/s19_mcp_plugin/mcp-architecture.svg b/s18_mcp_plugin/images/mcp-architecture.svg similarity index 94% rename from web/public/course-assets/s19_mcp_plugin/mcp-architecture.svg rename to s18_mcp_plugin/images/mcp-architecture.svg index 6b365d6b..f09e0554 100644 --- a/web/public/course-assets/s19_mcp_plugin/mcp-architecture.svg +++ b/s18_mcp_plugin/images/mcp-architecture.svg @@ -23,11 +23,11 @@ - s18 保留 + s17 保留 - s19 新增 + s18 新增 - + turn @@ -58,9 +58,9 @@ - + - MCP 架构(s19 新增:标准协议 + 外部工具动态接入) + MCP 架构(s18 新增:标准协议 + 外部工具动态接入) @@ -102,11 +102,11 @@ - s18: worktree + events + protocols (Lead 17) + s17: worktree + events + protocols (Lead 17) - s19: MCP + dynamic tools (Lead 18) + s18: MCP + dynamic tools (Lead 18) - 下一章 s20:把工具、权限、团队、worktree、MCP 等机制合回同一个 while True 循环。 + 下一章 s19:把工具、权限、团队、worktree、MCP 等机制合回同一个 while True 循环。 diff --git a/s20_comprehensive/README.ja.md b/s19_comprehensive/README.ja.md similarity index 74% rename from s20_comprehensive/README.ja.md rename to s19_comprehensive/README.ja.md index 5291e5c0..19cc0e18 100644 --- a/s20_comprehensive/README.ja.md +++ b/s19_comprehensive/README.ja.md @@ -1,18 +1,18 @@ -# s20: Comprehensive Agent — すべての仕組みを 1 つのループへ +# s19: Comprehensive Agent — すべての仕組みを 1 つのループへ [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s22 +s01 → ... → s17 → s18 → `s19` → [s20](../s20_workflow_runtime/) → s21 > *"仕組みは多い、ループは 1 つ"* — tools、permissions、memory、tasks、teams、plugins はすべて同じ `while True` に接続される。 > -> **Harness レイヤー**: 総合 — 前 19 章の仕組みを 1 つの実行可能なシステムへ戻す。 +> **Harness レイヤー**: 総合 — s01-s18 の仕組みを 1 つの実行可能なシステムへ戻す。 --- ## 問題 -前 19 章では、各章が 1 つの仕組みだけを追加した。学習にはその形が適している。しかし実際の agent は、1 つの仕組みだけで動くわけではない。 +前 18 章では、各境界を観察できるように仕組みを一つずつ追加した。本章では、それらを一つのランタイムへ接続する。 長時間動く coding agent には、同時に次のものが必要になる: @@ -26,7 +26,7 @@ s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s2 - worktree isolation - MCP external tool integration -難しいのは機能を積み上げることではない。それぞれの仕組みが loop のどこに接続されるかを見抜くことだ。S20 は統合チェックポイントであり、これまでの component を 1 つの harness に戻してから、s21-s22 が編成と目標完了を外側に追加する。 +難しいのは機能を積み上げることではない。それぞれの仕組みが loop のどこに接続されるかを見抜くことだ。S19 は統合チェックポイントであり、これまでの component を 1 つの harness に戻してから、s20-s21 が編成と目標完了を外側に追加する。 --- @@ -34,7 +34,7 @@ s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s2 ![System Architecture](images/system-architecture.ja.svg) -S20 は新しい単独 mechanism を発明しない。前章までの teaching component を 1 つの完全な harness に統合する: +S19 は新しい mechanism を追加せず、前章までの component を 1 つの完全な harness に統合する: ```text user input @@ -52,7 +52,7 @@ user input → next round ``` -loop 自体は同じ構造のままだ。model を呼び、response に `tool_use` block があるかを見て、tool を実行し、結果を `messages` に戻す。CC source でも `stop_reason == "tool_use"` を直接信頼せず、実際に tool_use block が出たかを continuation signal として扱う。変わったのは、loop の周囲の harness が完成形になったことだけ。 +loop 自体は同じ構造のままだ。model を呼び、response に `tool_use` block があるかを見て、tool を実行し、結果を `messages` に戻す。tool 実行を続けるかどうかは、実際の `tool_use` block の有無で決まる。 --- @@ -79,14 +79,14 @@ loop 自体は同じ構造のままだ。model を呼び、response に `tool_us ### Tools と Dispatch -built-in tool pool には 27 個の tool がある: +built-in tool pool には 26 個の tool がある: ```text bash, read_file, write_file, edit_file, glob todo_write, task, load_skill, compact create_task, list_tasks, get_task, claim_task, complete_task schedule_cron, list_crons, cancel_cron -spawn_teammate, send_message, check_inbox +spawn_teammate, send_message request_shutdown, request_plan, review_plan create_worktree, remove_worktree, keep_worktree connect_mcp @@ -116,7 +116,7 @@ if blocked: ### Plan と Task -S20 には 2 層の plan がある: +S19 には 2 層の plan がある: - `todo_write`: current session 用の軽量 plan。メモリに保持。 - task graph: cross-session、dependency-aware、claimable な task file。`.tasks/task_*.json` に保存。 @@ -127,10 +127,10 @@ S20 には 2 層の plan がある: ### Subagent と Team -S20 には 2 種類の delegation がある: +S19 には 2 種類の delegation がある: - `task`: one-shot subagent。独立した `messages[]` を使い、中間 context を捨て、final summary だけ返す。 -- `spawn_teammate`: persistent teammate thread。`MessageBus` で通信し、idle 中に task board を polling して自律的に claim できる。 +- `spawn_teammate`: persistent teammate thread。ランタイムが `MessageBus` event を自動配信し、teammate は idle 中に task board を確認して自律的に claim できる。 one-shot subagent は context isolation を解決する。persistent teammate は長期並列協作を解決する。 @@ -188,19 +188,19 @@ MCP は external capability を担当する: --- -## s19 からの変化 +## s18 からの変化 -| Component | s19 | s20 | +| Component | s18 | s19 | |-----------|-----|-----| -| tool pool | built-in + MCP | built-in + MCP、s01-s18 の tool を補完 | -| permission | teaching body では省略 | `PreToolUse` hook で実行 | -| hooks | 省略 | UserPromptSubmit / PreToolUse / PostToolUse / Stop | -| todo | 省略 | `todo_write` + reminder | -| skill | 省略 | system prompt の catalog + `load_skill` | -| compact | 省略 | LLM 前 compaction + `compact` tool + reactive compact | +| tool pool | built-in + MCP | built-in + MCP、s01-s17 の tool を補完 | +| permission | s18 の対象外 | `PreToolUse` hook で実行 | +| hooks | s18 の対象外 | UserPromptSubmit / PreToolUse / PostToolUse / Stop | +| todo | s18 の対象外 | `todo_write` + reminder | +| skill | s18 の対象外 | system prompt の catalog + `load_skill` | +| compact | s18 の対象外 | LLM 前 compaction + `compact` tool + reactive compact | | error recovery | simple try/except | retry / max_tokens / prompt too long | -| background | 省略 | slow-operation thread + task notification | -| cron | 省略 | daemon scheduler + durable jobs | +| background | s18 の対象外 | slow-operation thread + task notification | +| cron | s18 の対象外 | daemon scheduler + durable jobs | | multi-agent | 維持 | 維持。teammate は isolated directory 上の basic tools を使う | | worktree | 維持 | 維持 | | MCP | 新規 | final tool pool の一部として維持 | @@ -211,16 +211,16 @@ MCP は external capability を担当する: ```sh cd learn-claude-code -python s20_comprehensive/code.py +python s19_comprehensive/code.py ``` 試す prompt: -1. `Create a todo list for inspecting this repo, then list Python files` -2. `Connect to the docs MCP server and search for agent loop` -3. `Create two tasks, create worktrees for them, then spawn alice and bob. Ask them to submit plans before claiming tasks.` -4. `remind me of the meeting in 3 minutes.` -5. `Run npm install in the background and continue reading README.md` +1. `このリポジトリを調べ、重要な Python ファイルを教えてください。` +2. `接続済みのドキュメントから agent loop の説明を探してください。` +3. `認証モジュールとログインページを隔離した worktree で並行してリファクタリングし、編集前にそれぞれのプランを見せてください。` +4. `3 分後に会議を知らせてください。` +5. `依存関係をバックグラウンドでインストールしながら README.md を読んでください。` 見るポイント: @@ -236,7 +236,7 @@ python s20_comprehensive/code.py ## 終わりは始まり -s01 から s20 まで、コードの能力は増えていく。しかし中心は変わらない: +s01 から s19 まで、コードの能力は増えていく。しかし中心は変わらない: ```python while True: @@ -247,8 +247,8 @@ while True: messages.append(tool_results) ``` -Claude Code の複雑さは「別の agent brain」ではない。成熟した harness の複雑さだ。model は判断と action selection を担当する。harness は environment、tools、permissions、memory、teams、external capabilities を整理する。 +成熟した harness の複雑さは model 周辺の協調機構から生まれる。model は判断と action selection を担当し、harness は environment、tools、permissions、memory、teams、external capabilities を整理する。 これは本コースの統合チェックポイントだ:仕組みは多い、ループは 1 つ。 -次へ:[s21 Workflow Runtime](../s21_workflow_runtime/) — 編成の形が固定なら、多数の会話ターンではなく、決定的で再開可能なコードへ移す。 +次へ:[s20 Workflow Runtime](../s20_workflow_runtime/) — 編成の形が固定なら、多数の会話ターンではなく、決定的で再開可能なコードへ移す。 diff --git a/s20_comprehensive/README.md b/s19_comprehensive/README.md similarity index 72% rename from s20_comprehensive/README.md rename to s19_comprehensive/README.md index 09b8546d..935dbb22 100644 --- a/s20_comprehensive/README.md +++ b/s19_comprehensive/README.md @@ -1,18 +1,18 @@ -# s20: Comprehensive Agent — All Mechanisms, One Loop +# s19: Comprehensive Agent — All Mechanisms, One Loop [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s22 +s01 → ... → s17 → s18 → `s19` → [s20](../s20_workflow_runtime/) → s21 > *"Many mechanisms, one loop"* — tools, permissions, memory, tasks, teams, and plugins all hang off the same `while True`. > -> **Harness layer**: Comprehensive — put the previous 19 mechanisms back into one runnable system. +> **Harness layer**: Comprehensive — put the mechanisms from s01-s18 into one runnable system. --- ## Problem -The first 19 chapters add one mechanism at a time. That is the right way to learn, but a real agent does not run with only one mechanism enabled. +The first 18 chapters add one mechanism at a time so each boundary stays visible. This chapter connects them in one runtime. A long-running coding agent needs all of these at once: @@ -26,7 +26,7 @@ A long-running coding agent needs all of these at once: - worktree isolation - MCP external tool integration -The hard part is not piling up features. The hard part is seeing where each mechanism belongs around the loop. S20 is the integration checkpoint: every earlier component is placed back into one harness before s21-s22 add orchestration and goal closure around it. +The hard part is not piling up features. The hard part is seeing where each mechanism belongs around the loop. S19 is the integration checkpoint: every earlier component is placed back into one harness before s20-s21 add orchestration and goal closure around it. --- @@ -34,7 +34,7 @@ The hard part is not piling up features. The hard part is seeing where each mech ![System Architecture](images/system-architecture.en.svg) -S20 does not invent a new mechanism. It merges the teaching components from the earlier chapters into one complete harness: +S19 does not introduce a new mechanism. It connects the components from the earlier chapters in one complete harness: ```text user input @@ -52,7 +52,7 @@ user input → next round ``` -The loop is still the same structure: call the model, check whether the response contains a `tool_use` block, execute tools, append results back to `messages`. CC source does not directly trust `stop_reason == "tool_use"`; the actual presence of a tool_use block is the continuation signal. What changed is that the harness around the loop is now complete. +The loop keeps the same structure: call the model, check whether the response contains a `tool_use` block, execute tools, and append results to `messages`. The presence of a `tool_use` block decides whether tool execution continues. --- @@ -79,14 +79,14 @@ The loop is still the same structure: call the model, check whether the response ### Tools and Dispatch -The built-in tool pool contains 27 tools: +The built-in tool pool contains 26 tools: ```text bash, read_file, write_file, edit_file, glob todo_write, task, load_skill, compact create_task, list_tasks, get_task, claim_task, complete_task schedule_cron, list_crons, cancel_cron -spawn_teammate, send_message, check_inbox +spawn_teammate, send_message request_shutdown, request_plan, review_plan create_worktree, remove_worktree, keep_worktree connect_mcp @@ -116,7 +116,7 @@ That means permission, logging, and audit logic all attach to the same hook poin ### Planning and Tasks -S20 keeps two planning layers: +S19 keeps two planning layers: - `todo_write`: lightweight plan for the current session, kept in memory - task graph: cross-session, dependency-aware, claimable task files under `.tasks/task_*.json` @@ -127,10 +127,10 @@ They share an intent, not an implementation: `todo_write` replaces one session c ### Subagents and Teams -S20 has two kinds of delegation: +S19 has two kinds of delegation: - `task`: one-shot subagent. It uses an isolated `messages[]`, discards intermediate context, and returns only a final summary. -- `spawn_teammate`: persistent teammate thread. It communicates through `MessageBus`, polls the task board while idle, and can claim work autonomously. +- `spawn_teammate`: persistent teammate thread. The runtime delivers `MessageBus` events, and the teammate scans the task board while idle so it can claim work autonomously. One-shot subagents solve context isolation. Persistent teammates solve long-running parallel collaboration. @@ -148,7 +148,7 @@ Skills only put their catalog into the system prompt. Full content is loaded on ### Compaction and Recovery -Before the LLM call, S20 runs the compaction pipeline: +Before the LLM call, S19 runs the compaction pipeline: ```text tool_result_budget → snip_compact → micro_compact → compact_history @@ -188,19 +188,19 @@ MCP owns external capability: --- -## Changes from s19 +## Changes from s18 -| Component | s19 | s20 | +| Component | s18 | s19 | |-----------|-----|-----| -| tool pool | built-in + MCP | built-in + MCP, with s01-s18 tools restored | -| permission | omitted in teaching body | runs inside `PreToolUse` hook | -| hooks | omitted | UserPromptSubmit / PreToolUse / PostToolUse / Stop | -| todo | omitted | `todo_write` + reminder | -| skill | omitted | catalog in system prompt + `load_skill` | -| compact | omitted | pre-LLM compaction + `compact` tool + reactive compact | +| tool pool | built-in + MCP | built-in + MCP, with s01-s17 tools restored | +| permission | outside s18's scope | runs inside `PreToolUse` hook | +| hooks | outside s18's scope | UserPromptSubmit / PreToolUse / PostToolUse / Stop | +| todo | outside s18's scope | `todo_write` + reminder | +| skill | outside s18's scope | catalog in system prompt + `load_skill` | +| compact | outside s18's scope | pre-LLM compaction + `compact` tool + reactive compact | | error recovery | simple try/except | retry / max_tokens / prompt too long | -| background | omitted | slow-operation thread + task notification | -| cron | omitted | daemon scheduler + durable jobs | +| background | outside s18's scope | slow-operation thread + task notification | +| cron | outside s18's scope | daemon scheduler + durable jobs | | multi-agent | kept | kept; teammates use basic tools in isolated directories | | worktree | kept | kept | | MCP | new | kept as part of the final tool pool | @@ -211,16 +211,16 @@ MCP owns external capability: ```sh cd learn-claude-code -python s20_comprehensive/code.py +python s19_comprehensive/code.py ``` Try: -1. `Create a todo list for inspecting this repo, then list Python files` -2. `Connect to the docs MCP server and search for agent loop` -3. `Create two tasks, create worktrees for them, then spawn alice and bob. Ask them to submit plans before claiming tasks.` -4. `remind me of the meeting in 3 minutes.` -5. `Run npm install in the background and continue reading README.md` +1. `Inspect this repository and tell me which Python files matter most.` +2. `Search the connected documentation for agent loop guidance.` +3. `Refactor the authentication module and login page in parallel in isolated worktrees. Show me each plan before editing.` +4. `Remind me about the meeting in 3 minutes.` +5. `Install the dependencies in the background while you read README.md.` Watch for: @@ -236,7 +236,7 @@ Watch for: ## The End Is the Beginning -From s01 to s20, the code gets more capable, but the core remains unchanged: +From s01 to s19, the code gets more capable, but the core remains unchanged: ```python while True: @@ -247,8 +247,8 @@ while True: messages.append(tool_results) ``` -Claude Code's complexity is not "another agent brain." It is the complexity of a mature harness. The model decides and chooses actions; the harness organizes environment, tools, permissions, memory, teams, and external capabilities. +A mature harness gets its complexity from coordination around the model. The model chooses actions; the harness organizes the environment, tools, permissions, memory, teams, and external capabilities. This is the course's integration checkpoint: many mechanisms, one loop. -Next: [s21 Workflow Runtime](../s21_workflow_runtime/) — when the orchestration shape is fixed, move it out of chat turns and into deterministic, resumable code. +Next: [s20 Workflow Runtime](../s20_workflow_runtime/) — when the orchestration shape is fixed, move it out of chat turns and into deterministic, resumable code. diff --git a/s20_comprehensive/README.zh.md b/s19_comprehensive/README.zh.md similarity index 72% rename from s20_comprehensive/README.zh.md rename to s19_comprehensive/README.zh.md index 6084c40a..52562107 100644 --- a/s20_comprehensive/README.zh.md +++ b/s19_comprehensive/README.zh.md @@ -1,18 +1,18 @@ -# s20: Comprehensive Agent — 全部机制,归到一个循环 +# s19: Comprehensive Agent — 全部机制,归到一个循环 [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s22 +s01 → ... → s17 → s18 → `s19` → [s20](../s20_workflow_runtime/) → s21 > *"机制很多,循环一个"* — 工具、权限、记忆、任务、团队、插件都挂在同一个 while True 上。 > -> **Harness 层**: 综合 — 把前 19 章的机制放回同一个可运行系统。 +> **Harness 层**: 综合 — 把 s01-s18 的机制放回同一个可运行系统。 --- ## 问题 -前 19 章每章只加一个机制。这样适合学习,但真实 Agent 不会只带一个机制运行。 +前 18 章每章只加一个机制,让每个边界都能单独观察。本章把它们接入同一个运行时。 一个能长期工作的 coding agent 需要同时拥有: @@ -26,7 +26,7 @@ s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s2 - worktree 隔离 - MCP 外部工具接入 -难点不是把功能堆起来,而是看清楚它们都挂在循环的哪个位置。S20 是集成检查点:先把此前组件归位,再由 s21-s22 在外层加入编排与目标闭环。 +难点不是把功能堆起来,而是看清楚它们都挂在循环的哪个位置。S19 是集成检查点:先把此前组件归位,再由 s20-s21 在外层加入编排与目标闭环。 --- @@ -34,7 +34,7 @@ s01 → ... → s18 → s19 → `s20` → [s21](../s21_workflow_runtime/) → s2 ![System Architecture](images/system-architecture.svg) -S20 不是再发明一个新机制,而是把前面的教学组件合成一个完整 harness: +S19 不再引入新机制,而是把前面各章的组件接入一个完整 harness: ```text 用户输入 @@ -52,7 +52,7 @@ S20 不是再发明一个新机制,而是把前面的教学组件合成一个 → 下一轮 ``` -循环本身仍然是同一个结构:调用模型,检查响应里是否出现 `tool_use` block,执行工具,把结果追加回 `messages`。CC 源码里也不直接信任 `stop_reason == "tool_use"`,而是以实际出现的 tool_use block 作为是否继续工具轮的信号。变化的是循环周围的 harness 变完整了。 +循环仍是同一个结构:调用模型,检查响应里是否出现 `tool_use` block,执行工具,再把结果追加回 `messages`。是否继续工具轮,由响应中有没有实际的 `tool_use` block 决定。 --- @@ -79,14 +79,14 @@ S20 不是再发明一个新机制,而是把前面的教学组件合成一个 ### 工具与分发 -内置工具池包含 27 个工具: +内置工具池包含 26 个工具: ```text bash, read_file, write_file, edit_file, glob todo_write, task, load_skill, compact create_task, list_tasks, get_task, claim_task, complete_task schedule_cron, list_crons, cancel_cron -spawn_teammate, send_message, check_inbox +spawn_teammate, send_message request_shutdown, request_plan, review_plan create_worktree, remove_worktree, keep_worktree connect_mcp @@ -116,7 +116,7 @@ if blocked: ### 计划与任务 -S20 同时保留两层计划: +S19 同时保留两层计划: - `todo_write`:当前会话内的轻量计划,保存在内存中 - task graph:跨会话、可依赖、可认领的任务文件,写入 `.tasks/task_*.json` @@ -127,10 +127,10 @@ S20 同时保留两层计划: ### 子 agent 与团队 -S20 有两种 delegation: +S19 有两种 delegation: - `task`:一次性 subagent。独立 `messages[]`,中间过程丢弃,只返回最终摘要。 -- `spawn_teammate`:持久队友线程。通过 MessageBus 收发消息,能 idle 轮询任务板并自动认领。 +- `spawn_teammate`:持久队友线程。运行时自动投递 MessageBus 事件,队友在 idle 时扫描任务板并自主认领。 一次性 subagent 解决“上下文隔离”;持久队友解决“长期并行协作”。 @@ -188,19 +188,19 @@ MCP 负责外部能力: --- -## 相对 s19 的变化 +## 相对 s18 的变化 -| 组件 | s19 | s20 | +| 组件 | s18 | s19 | |------|-----|-----| -| 工具池 | 内置 + MCP | 内置 + MCP,补齐 s01-s18 的工具 | -| 权限 | 教学主体省略 | `PreToolUse` hook 中执行 | -| hooks | 省略 | UserPromptSubmit / PreToolUse / PostToolUse / Stop | -| todo | 省略 | `todo_write` + reminder | -| skill | 省略 | catalog in system prompt + `load_skill` | -| compact | 省略 | LLM 前压缩 + `compact` 工具 + reactive compact | +| 工具池 | 内置 + MCP | 内置 + MCP,补齐 s01-s17 的工具 | +| 权限 | 不在 s18 范围内 | `PreToolUse` hook 中执行 | +| hooks | 不在 s18 范围内 | UserPromptSubmit / PreToolUse / PostToolUse / Stop | +| todo | 不在 s18 范围内 | `todo_write` + reminder | +| skill | 不在 s18 范围内 | catalog in system prompt + `load_skill` | +| compact | 不在 s18 范围内 | LLM 前压缩 + `compact` 工具 + reactive compact | | error recovery | 简化 try/except | retry / max_tokens / prompt too long | -| background | 省略 | 慢操作后台线程 + task notification | -| cron | 省略 | daemon scheduler + durable jobs | +| background | 不在 s18 范围内 | 慢操作后台线程 + task notification | +| cron | 不在 s18 范围内 | daemon scheduler + durable jobs | | multi-agent | 保留 | 保留;队友使用隔离目录下的基础工具 | | worktree | 保留 | 保留 | | MCP | 新增 | 保留,作为最终工具池的一部分 | @@ -211,16 +211,16 @@ MCP 负责外部能力: ```sh cd learn-claude-code -python s20_comprehensive/code.py +python s19_comprehensive/code.py ``` 可以试: -1. `Create a todo list for inspecting this repo, then list Python files` -2. `Connect to the docs MCP server and search for agent loop` -3. `Create two tasks, create worktrees for them, then spawn alice and bob. Ask them to submit plans before claiming tasks.` -4. `remind me of the meeting in 3 minutes.` -5. `Run npm install in the background and continue reading README.md` +1. `检查这个仓库,告诉我哪些 Python 文件最重要。` +2. `从已连接的文档中查一下 agent loop 的相关说明。` +3. `请在隔离的 worktree 中并行重构认证模块和登录页,修改前先把各自的计划给我看。` +4. `3 分钟后提醒我开会。` +5. `在后台安装依赖,同时继续阅读 README.md。` 观察重点: @@ -236,7 +236,7 @@ python s20_comprehensive/code.py ## 结束亦是开始 -从 s01 到 s20,代码表面越来越复杂,但核心始终没变: +从 s01 到 s19,代码表面越来越复杂,但核心始终没变: ```python while True: @@ -247,8 +247,8 @@ while True: messages.append(tool_results) ``` -Claude Code 的复杂性不是“另一个 agent 大脑”,而是一个成熟 harness 的复杂性。模型负责判断和行动选择;harness 负责把环境、工具、权限、记忆、团队和外部能力组织好。 +成熟 harness 的复杂性来自模型周围的协作机制。模型负责判断和行动选择,harness 负责组织环境、工具、权限、记忆、团队和外部能力。 这是课程的集成检查点:机制很多,循环一个。 -下一章:[s21 Workflow Runtime](../s21_workflow_runtime/) — 当编排形状固定时,把它从多轮对话移入确定性、可恢复的代码。 +下一章:[s20 Workflow Runtime](../s20_workflow_runtime/) — 当编排形状固定时,把它从多轮对话移入确定性、可恢复的代码。 diff --git a/s20_comprehensive/code.py b/s19_comprehensive/code.py similarity index 81% rename from s20_comprehensive/code.py rename to s19_comprehensive/code.py index 417d6065..fe20cdfb 100644 --- a/s20_comprehensive/code.py +++ b/s19_comprehensive/code.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 """ -s20: Comprehensive Agent — all teaching components in one loop. +s19: Comprehensive Agent — all course mechanisms in one loop. -Run: python s20_comprehensive/code.py +Run: python s19_comprehensive/code.py Need: pip install anthropic python-dotenv pyyaml + .env with ANTHROPIC_API_KEY -This final chapter intentionally puts the earlier teaching mechanisms back -together: dispatch, permission, hooks, todo, subagent, skills, compaction, +This final chapter puts the earlier mechanisms back together: dispatch, +permission, hooks, todo, subagent, skills, compaction, memory, prompt assembly, error recovery, task graph, background tasks, cron, teams, protocols, autonomous agents, worktrees, and MCP. """ @@ -51,7 +51,7 @@ CONTEXT_LIMIT = 50000 KEEP_RECENT_TOOL_RESULTS = 3 PERSIST_THRESHOLD = 30000 CONTINUATION_PROMPT = "Continue from the previous response. Do not repeat completed work." -PROMPT = "\033[36ms20 >> \033[0m" +PROMPT = "\033[36ms19 >> \033[0m" CLI_ACTIVE = False @@ -74,6 +74,7 @@ def terminal_print(text: str): # worktrees, and teammates on top of this same file-backed state. TASKS_DIR = WORKDIR / ".tasks" TASKS_DIR.mkdir(exist_ok=True) +task_lock = threading.RLock() CURRENT_TODOS: list[dict] = [] @@ -134,22 +135,27 @@ def can_start(task_id: str) -> bool: def claim_task(task_id: str, owner: str = "agent") -> str: - task = load_task(task_id) - if task.status != "pending": - return f"Task {task_id} is {task.status}, cannot claim" - if task.owner: - return f"Task {task_id} already owned by {task.owner}" - if not can_start(task_id): - deps = [d for d in task.blockedBy - if _task_path(d).exists() and load_task(d).status != "completed"] - missing = [d for d in task.blockedBy if not _task_path(d).exists()] - parts = [] - if deps: parts.append(f"blocked by: {deps}") - if missing: parts.append(f"missing deps: {missing}") - return "Cannot start — " + ", ".join(parts) - task.owner = owner - task.status = "in_progress" - save_task(task) + with task_lock: + task = load_task(task_id) + if task.status != "pending": + return f"Task {task_id} is {task.status}, cannot claim" + if task.owner: + return f"Task {task_id} already owned by {task.owner}" + if not can_start(task_id): + deps = [d for d in task.blockedBy + if (_task_path(d).exists() + and load_task(d).status != "completed")] + missing = [d for d in task.blockedBy + if not _task_path(d).exists()] + parts = [] + if deps: + parts.append(f"blocked by: {deps}") + if missing: + parts.append(f"missing deps: {missing}") + return "Cannot start: " + ", ".join(parts) + task.owner = owner + task.status = "in_progress" + save_task(task) print(f" \033[36m[claim] {task.subject} → in_progress\033[0m") return f"Claimed {task.id} ({task.subject})" @@ -171,8 +177,8 @@ def complete_task(task_id: str) -> str: # ── Worktree System ── -# Worktree names become filesystem paths, so the teaching version keeps the -# validation rules strict and reuses them for create/remove/keep. +# Worktree names become filesystem paths, so validation stays strict and is +# reused for create/remove/keep. WORKTREES_DIR = WORKDIR / ".worktrees" WORKTREES_DIR.mkdir(exist_ok=True) @@ -348,10 +354,15 @@ PROMPT_SECTIONS = { "todo_write, task, load_skill, compact, " "create_task, list_tasks, get_task, claim_task, complete_task, " "schedule_cron, list_crons, cancel_cron, " - "spawn_teammate, send_message, check_inbox, " + "spawn_teammate, send_message, " "request_shutdown, request_plan, review_plan, " "create_worktree, remove_worktree, keep_worktree, " "connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.", + "teams": ( + "When parallel work would help, first propose a small team with clear " + "responsibilities and wait for the user's confirmation. Do not call " + "spawn_teammate before the user confirms." + ), "workspace": f"Working directory: {WORKDIR}", "memory": "Relevant memories are injected below when available.", } @@ -362,6 +373,7 @@ def assemble_system_prompt(context: dict) -> str: # memory, skill catalog, MCP state, and active teammates become visible. sections = [PROMPT_SECTIONS["identity"], PROMPT_SECTIONS["tools"], + PROMPT_SECTIONS["teams"], PROMPT_SECTIONS["workspace"]] sections.append(f"Current time: {datetime.now().isoformat(timespec='seconds')}") sections.append("Skills catalog:\n" + list_skills() + @@ -481,28 +493,33 @@ def run_todo_write(todos: list) -> str: return f"Updated {len(CURRENT_TODOS)} todos" -# ── MessageBus ── +# ── MessageBus (from s15) ── -# Team communication is append-only JSONL mailboxes. This keeps the protocol -# inspectable on disk and lets background teammates send messages. MAILBOX_DIR = WORKDIR / ".mailboxes" MAILBOX_DIR.mkdir(exist_ok=True) +MAILBOX_ROOT = MAILBOX_DIR.resolve() +VALID_AGENT_NAME = re.compile(r"^[A-Za-z0-9_-]{1,64}$") + + +def is_valid_agent_name(name: str) -> bool: + return bool(VALID_AGENT_NAME.fullmatch(name)) class MessageBus: - def send(self, from_agent: str, to_agent: str, content: str, - msg_type: str = "message", metadata: dict = None): - msg = {"from": from_agent, "to": to_agent, - "content": content, "type": msg_type, - "ts": time.time(), "metadata": metadata or {}} - inbox = MAILBOX_DIR / f"{to_agent}.jsonl" - with open(inbox, "a") as f: - f.write(json.dumps(msg) + "\n") - terminal_print(f" \033[33m[bus] {from_agent} → {to_agent}: " - f"({msg_type}) {content[:50]}\033[0m") + def __init__(self): + self._lock = threading.RLock() + self._changed = threading.Condition(self._lock) - def read_inbox(self, agent: str) -> list[dict]: - inbox = MAILBOX_DIR / f"{agent}.jsonl" + def _path(self, agent: str) -> Path: + if not is_valid_agent_name(agent): + raise ValueError(f"Invalid mailbox recipient: {agent!r}") + path = (MAILBOX_DIR / f"{agent}.jsonl").resolve() + if not path.is_relative_to(MAILBOX_ROOT): + raise ValueError(f"Mailbox path escapes directory: {agent!r}") + return path + + def _read_unlocked(self, agent: str) -> list[dict]: + inbox = self._path(agent) if not inbox.exists(): return [] msgs = [json.loads(line) for line in inbox.read_text().splitlines() @@ -510,11 +527,47 @@ class MessageBus: inbox.unlink() return msgs + def send(self, from_agent: str, to_agent: str, content: str, + msg_type: str = "message", metadata: dict | None = None): + msg = {"from": from_agent, "to": to_agent, + "content": content, "type": msg_type, + "ts": time.time(), "metadata": metadata or {}} + with self._changed: + with open(self._path(to_agent), "a") as f: + f.write(json.dumps(msg, ensure_ascii=False) + "\n") + self._changed.notify_all() + print(f" \033[33m[bus] {from_agent} → {to_agent}: " + f"({msg_type}) {content[:50]}\033[0m") + + def read_inbox(self, agent: str) -> list[dict]: + with self._lock: + return self._read_unlocked(agent) + + def peek(self, agent: str) -> bool: + with self._lock: + inbox = self._path(agent) + return inbox.exists() and inbox.stat().st_size > 0 + + def wait_for_messages(self, agent: str, + timeout: float | None = None) -> list[dict]: + deadline = None if timeout is None else time.monotonic() + timeout + with self._changed: + while not self.peek(agent): + remaining = (None if deadline is None + else deadline - time.monotonic()) + if remaining is not None and remaining <= 0: + return [] + self._changed.wait(remaining) + return self._read_unlocked(agent) + BUS = MessageBus() -active_teammates: dict[str, bool] = {} +active_teammates: dict[str, str] = {} +plan_gates: dict[str, str] = {} +plan_request_ids: dict[str, str] = {} +team_lock = threading.RLock() -# ── Protocol State ── +# ── Protocol State (from s15) ── @dataclass class ProtocolState: @@ -531,20 +584,38 @@ pending_requests: dict[str, ProtocolState] = {} def new_request_id() -> str: - return f"req_{random.randint(0, 999999):06d}" + while True: + request_id = f"req_{random.randint(0, 999999):06d}" + if request_id not in pending_requests: + return request_id -def match_response(response_type: str, request_id: str, approve: bool): - # Responses are matched by request_id so one protocol reply cannot approve - # a different pending request. - state = pending_requests.get(request_id) - if not state: - return - if state.type == "shutdown" and response_type != "shutdown_response": - return - if state.type == "plan_approval" and response_type != "plan_approval_response": - return - state.status = "approved" if approve else "rejected" +def match_response(response_type: str, request_id: str, approve: bool, + from_agent: str, to_agent: str) -> bool: + with team_lock: + state = pending_requests.get(request_id) + if not state: + print(f" \033[31m[protocol] unknown request_id: {request_id}\033[0m") + return False + expected = { + "shutdown": "shutdown_response", + "plan_approval": "plan_approval_response", + }[state.type] + if response_type != expected: + print(f" \033[31m[protocol] expected {expected}, " + f"got {response_type}\033[0m") + return False + if from_agent != state.target or to_agent != state.sender: + print(f" \033[31m[protocol] {request_id} responder mismatch\033[0m") + return False + if state.status != "pending": + return False + state.status = "approved" if approve else "rejected" + icon = "✓" if approve else "✗" + color = "32" if approve else "31" + print(f" \033[{color}m[protocol] {state.type} {icon} " + f"({request_id}: {state.status})\033[0m") + return True def consume_lead_inbox(route_protocol=True) -> list[dict]: @@ -555,101 +626,173 @@ def consume_lead_inbox(route_protocol=True) -> list[dict]: req_id = meta.get("request_id", "") msg_type = msg.get("type", "") if req_id and msg_type.endswith("_response"): - match_response(msg_type, req_id, meta.get("approve", False)) + match_response(msg_type, req_id, meta.get("approve", False), + msg.get("from", ""), msg.get("to", "")) return msgs -# ── Autonomous Agent ── - -IDLE_POLL_INTERVAL = 5 -IDLE_TIMEOUT = 60 +def format_team_events(msgs: list[dict]) -> str: + lines = [] + for msg in msgs: + request_id = msg.get("metadata", {}).get("request_id") + suffix = f" request_id={request_id}" if request_id else "" + lines.append( + f"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}" + ) + return "[Team events]\n" + "\n".join(lines) -def scan_unclaimed_tasks() -> list[dict]: - unclaimed = [] - for f in sorted(TASKS_DIR.glob("task_*.json")): - task = json.loads(f.read_text()) - if (task.get("status") == "pending" - and not task.get("owner") - and can_start(task["id"])): - unclaimed.append(task) - return unclaimed +# ── Autonomous Agent (from s16, + worktree cwd) ── + +IDLE_SCAN_INTERVAL = 2.0 -def idle_poll(agent_name: str, messages: list, - name: str, role: str, - worktree_context: dict | None = None) -> str: - # Autonomous teammates wake up for inbox messages first, then look for - # unclaimed tasks. This keeps direct protocol messages higher priority. - for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL): - time.sleep(IDLE_POLL_INTERVAL) - inbox = BUS.read_inbox(agent_name) - if inbox: - for msg in inbox: - if msg.get("type") == "shutdown_request": - req_id = msg.get("metadata", {}).get("request_id", "") - BUS.send(name, "lead", "Shutting down.", - "shutdown_response", - {"request_id": req_id, "approve": True}) - return "shutdown" - messages.append({"role": "user", - "content": "" + json.dumps(inbox) + ""}) - return "work" - unclaimed = scan_unclaimed_tasks() - if unclaimed: - task_data = unclaimed[0] - result = claim_task(task_data["id"], agent_name) - if "Claimed" in result: - wt_info = "" - if task_data.get("worktree"): - wt_path = WORKTREES_DIR / task_data["worktree"] - wt_info = f"\nWork directory: {wt_path}" - if worktree_context is not None: - worktree_context["path"] = str(wt_path) - messages.append({"role": "user", - "content": f"Task {task_data['id']}: " - f"{task_data['subject']}{wt_info}"}) - return "work" - return "timeout" +def scan_unclaimed_tasks() -> list[Task]: + return [ + task for task in list_tasks() + if (task.status == "pending" + and task.owner is None + and can_start(task.id)) + ] + + +def claim_next_task(name: str) -> Task | None: + for task in scan_unclaimed_tasks(): + result = claim_task(task.id, owner=name) + if result.startswith("Claimed "): + return load_task(task.id) + return None + + +def _last_assistant_text(content) -> str: + for block in content: + if getattr(block, "type", None) == "text": + return block.text.strip() + if isinstance(block, dict) and block.get("type") == "text": + return str(block.get("text", "")).strip() + return "" + + +def _run_teammate_tool(name: str, block, handlers: dict) -> str: + gate = plan_gates.get(name, "not_required") + if (block.name in {"bash", "write_file"} + and gate not in {"not_required", "approved"}): + return f"Blocked: plan status is {gate}." + handler = handlers.get(block.name) + return str(handler(**block.input)) if handler else f"Unknown tool: {block.name}" + + +def apply_plan_response(name: str, msg: dict) -> tuple[bool, str]: + """Apply only the Lead response for this teammate's current plan.""" + metadata = msg.get("metadata", {}) + request_id = metadata.get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + expected_id = plan_request_ids.get(name) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and request_id == expected_id + and state is not None + and state.type == "plan_approval" + and state.sender == name + and state.target == "lead" + and state.status in {"approved", "rejected"} + and metadata.get("approve", False) + == (state.status == "approved") + ) + if not valid: + return False, "[Ignored plan response: request mismatch]" + plan_gates[name] = state.status + active_teammates[name] = "working" + plan_request_ids.pop(name, None) + outcome = state.status + return True, f"[Plan {outcome}] {msg['content']}" + + +def apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]: + """Accept only a pending shutdown request sent by Lead to this teammate.""" + request_id = msg.get("metadata", {}).get("request_id", "") + with team_lock: + state = pending_requests.get(request_id) + valid = ( + msg.get("from") == "lead" + and msg.get("to") == name + and state is not None + and state.type == "shutdown" + and state.sender == "lead" + and state.target == name + and state.status == "pending" + and active_teammates.get(name) != "stopping" + ) + if not valid: + return False, "[Ignored shutdown request: request mismatch]" + active_teammates[name] = "stopping" + return True, request_id + + +def _teammate_send_message(from_name: str, to: str, content: str) -> str: + with team_lock: + if to != "lead" and to not in active_teammates: + return f"Agent '{to}' is not active" + BUS.send(from_name, to, content) + return f"Sent to {to}" # ── Teammate Thread ── def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: - if name in active_teammates: - return f"Teammate '{name}' already exists" + if not is_valid_agent_name(name): + return ("Invalid teammate name: use 1-64 letters, digits, " + "underscores, or dashes") + with team_lock: + if name in active_teammates: + return f"Teammate '{name}' already exists" + active_teammates[name] = "working" + plan_gates[name] = "not_required" - # Plan approval is a real gate: after submit_plan, the teammate stops - # taking model/tool steps until lead sends plan_approval_response. - protocol_ctx = {"waiting_plan": None} system = (f"You are '{name}', a {role}. " - f"Use tools to complete tasks. " - f"If a task has a worktree, work in that directory.") + "Use tools to complete tasks. " + "You can list and claim tasks from the board. " + "If a task has a worktree, work in that directory. " + "When asked for a plan, submit it before bash or write_file " + "and wait for approval.") def handle_inbox_message(name: str, msg: dict, messages: list): msg_type = msg.get("type", "message") meta = msg.get("metadata", {}) req_id = meta.get("request_id", "") + if msg_type == "shutdown_request": - BUS.send(name, "lead", "Shutting down.", + accepted, notice = apply_shutdown_request(name, msg) + if not accepted: + messages.append({"role": "user", "content": notice}) + return False + req_id = notice + BUS.send(name, "lead", "Shutting down gracefully.", "shutdown_response", {"request_id": req_id, "approve": True}) + print(f" \033[35m[protocol] {name} approved shutdown " + f"({req_id})\033[0m") return True + if msg_type == "plan_approval_response": - approve = meta.get("approve", False) - if req_id == protocol_ctx["waiting_plan"]: - protocol_ctx["waiting_plan"] = None + _, notice = apply_plan_response(name, msg) messages.append({"role": "user", - "content": "[Plan approved]" if approve - else f"[Plan rejected] {msg['content']}"}) + "content": notice}) + elif msg_type == "plan_request": + messages.append({"role": "user", + "content": f"[Plan required] {msg['content']}"}) + elif msg_type == "message": + messages.append({"role": "user", + "content": f"[Message from {msg['from']}] {msg['content']}"}) return False def run(): + # Track current worktree for this teammate's cwd wt_ctx = {"path": None} - def _wt_cwd(): - # Once a task with a worktree is claimed, all teammate file tools - # transparently run inside that isolated directory. + def _wt_cwd() -> Path | None: p = wt_ctx["path"] return Path(p) if p else None @@ -674,9 +817,12 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: def _run_claim_task(task_id: str): result = claim_task(task_id, owner=name) if "Claimed" in result: + # Set worktree cwd if task has one task = load_task(task_id) - wt_ctx["path"] = (str(WORKTREES_DIR / task.worktree) - if task.worktree else None) + if task.worktree: + wt_ctx["path"] = str(WORKTREES_DIR / task.worktree) + else: + wt_ctx["path"] = None return result def _run_complete_task(task_id: str): @@ -692,9 +838,7 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: "required": ["command"]}}, {"name": "read_file", "description": "Read file.", "input_schema": {"type": "object", - "properties": {"path": {"type": "string"}, - "limit": {"type": "integer"}, - "offset": {"type": "integer"}}, + "properties": {"path": {"type": "string"}}, "required": ["path"]}}, {"name": "write_file", "description": "Write file.", "input_schema": {"type": "object", @@ -713,7 +857,7 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: "properties": {"plan": {"type": "string"}}, "required": ["plan"]}}, {"name": "list_tasks", - "description": "List all tasks.", + "description": "List all tasks on the board.", "input_schema": {"type": "object", "properties": {}, "required": []}}, {"name": "claim_task", @@ -731,18 +875,22 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: sub_handlers = { "bash": _run_bash, "read_file": _run_read, "write_file": _run_write, - "send_message": lambda to, content: (BUS.send(name, to, content), - "Sent")[1], + "send_message": lambda to, content: _teammate_send_message( + name, to, content), + "submit_plan": lambda plan: _teammate_submit_plan(name, plan), "list_tasks": _run_list_tasks, "claim_task": _run_claim_task, "complete_task": _run_complete_task, } + # Outer loop: WORK → IDLE cycle while True: if len(messages) <= 3: messages.insert(0, {"role": "user", "content": f"You are '{name}', role: {role}. " f"Continue your work."}) + + # WORK phase should_shutdown = False for _ in range(10): inbox = BUS.read_inbox(name) @@ -753,17 +901,6 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: break if should_shutdown: break - if protocol_ctx["waiting_plan"]: - # Poll only for protocol replies while the approval gate is - # closed; do not let the model continue with the task. - time.sleep(IDLE_POLL_INTERVAL) - continue - if inbox and not should_shutdown: - non_protocol = [m for m in inbox - if m.get("type") == "message"] - if non_protocol: - messages.append({"role": "user", - "content": "" + json.dumps(non_protocol) + ""}) try: response = client.messages.create( model=MODEL, system=system, messages=messages[-20:], @@ -771,98 +908,141 @@ def spawn_teammate_thread(name: str, role: str, prompt: str) -> str: except Exception: break messages.append({"role": "assistant", "content": response.content}) - if not has_tool_use(response.content): + if response.stop_reason != "tool_use": + summary = _last_assistant_text(response.content) + gate = plan_gates.get(name, "not_required") + if gate != "pending" and summary: + BUS.send(name, "lead", summary, "result") + if gate == "pending": + with team_lock: + active_teammates[name] = "waiting_approval" + else: + with team_lock: + active_teammates[name] = "idle" + BUS.send(name, "lead", "Waiting for more work.", + "idle_notification") break results = [] for block in response.content: if block.type == "tool_use": - if block.name == "submit_plan": - output = _teammate_submit_plan( - name, block.input.get("plan", "")) - match = re.search(r"\((req_\d+)\)", output) - protocol_ctx["waiting_plan"] = ( - match.group(1) if match else output) - else: - handler = sub_handlers.get(block.name) - output = call_tool_handler(handler, block.input, - block.name) + output = _run_teammate_tool(name, block, sub_handlers) results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(output)}) - if protocol_ctx["waiting_plan"]: - # Ignore later tool_use blocks from the same model - # response; they belong after approval, not before. - break messages.append({"role": "user", "content": results}) - if protocol_ctx["waiting_plan"]: - break + if should_shutdown: break - if protocol_ctx["waiting_plan"]: - continue - idle_result = idle_poll(name, messages, name, role, wt_ctx) - if idle_result in ("shutdown", "timeout"): - break - summary = "Done." - for msg in reversed(messages): - if msg["role"] == "assistant" and isinstance(msg["content"], list): - for b in msg["content"]: - if getattr(b, "type", None) == "text": - summary = b.text + # IDLE phase: messages take priority, then scan the task board. + while True: + inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL) + if inbox: + for msg in inbox: + if handle_inbox_message(name, msg, messages): + should_shutdown = True + break + if should_shutdown or messages[-1]["role"] == "user": break - else: continue - break - BUS.send(name, "lead", summary, "result") - active_teammates.pop(name, None) - active_teammates[name] = True + task = claim_next_task(name) + if not task: + continue + wt_ctx["path"] = (str(WORKTREES_DIR / task.worktree) + if task.worktree else None) + workdir = (f"\nWork directory: {wt_ctx['path']}" + if wt_ctx["path"] else "") + messages.append({ + "role": "user", + "content": ( + f"[Auto-claimed task {task.id}] " + f"{task.subject}\n{task.description}{workdir}" + ), + }) + print(f" \033[32m[idle] {name} claimed " + f"{task.id}: {task.subject}\033[0m") + break + if should_shutdown: + break + + with team_lock: + active_teammates.pop(name, None) + plan_gates.pop(name, None) + plan_request_ids.pop(name, None) + print(f" \033[32m[teammate] {name} finished\033[0m") + threading.Thread(target=run, daemon=True).start() - return f"Teammate '{name}' spawned as {role}" + print(f" \033[36m[teammate] {name} spawned as {role}\033[0m") + return f"Teammate '{name}' spawned as {role} (autonomous)" def _teammate_submit_plan(from_name: str, plan: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="plan_approval", - sender=from_name, target="lead", - status="pending", payload=plan) + with team_lock: + if plan_gates.get(from_name) == "pending": + return "A plan is already waiting for review." + req_id = new_request_id() + pending_requests[req_id] = ProtocolState( + request_id=req_id, type="plan_approval", + sender=from_name, target="lead", + status="pending", payload=plan) + plan_gates[from_name] = "pending" + plan_request_ids[from_name] = req_id + active_teammates[from_name] = "waiting_approval" BUS.send(from_name, "lead", plan, "plan_approval_request", {"request_id": req_id}) - return f"Plan submitted ({req_id})" + return f"Plan submitted ({req_id}). Waiting for approval..." -# ── Lead Protocol Tools ── +# ── Lead Protocol Tools (from s15) ── def run_request_shutdown(teammate: str) -> str: - req_id = new_request_id() - pending_requests[req_id] = ProtocolState( - request_id=req_id, type="shutdown", - sender="lead", target=teammate, - status="pending", payload="") - BUS.send("lead", teammate, "Shut down.", "shutdown_request", + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + req_id = new_request_id() + pending_requests[req_id] = ProtocolState( + request_id=req_id, type="shutdown", + sender="lead", target=teammate, + status="pending", payload="") + BUS.send("lead", teammate, "Please shut down gracefully.", + "shutdown_request", {"request_id": req_id}) - return f"Shutdown request sent to {teammate}" + print(f" \033[35m[protocol] shutdown_request → {teammate} " + f"({req_id})\033[0m") + return f"Shutdown request sent to {teammate} (req: {req_id})" def run_request_plan(teammate: str, task: str) -> str: - BUS.send("lead", teammate, f"Submit plan for: {task}", "message") + if teammate not in active_teammates: + return f"Teammate '{teammate}' is not active" + with team_lock: + plan_gates[teammate] = "required" + BUS.send("lead", teammate, task, "plan_request") return f"Asked {teammate} to submit a plan" def run_review_plan(request_id: str, approve: bool, feedback: str = "") -> str: - state = pending_requests.get(request_id) - if not state: - return f"Request {request_id} not found" - state.status = "approved" if approve else "rejected" + with team_lock: + state = pending_requests.get(request_id) + if not state: + return f"Request {request_id} not found" + if state.type != "plan_approval": + return f"Request {request_id} is not a plan" + if state.status != "pending": + return f"Request {request_id} already {state.status}" + if plan_request_ids.get(state.sender) != request_id: + return f"Request {request_id} is not the current plan" + state.status = "approved" if approve else "rejected" BUS.send("lead", state.sender, feedback or ("Approved" if approve else "Rejected"), "plan_approval_response", {"request_id": request_id, "approve": approve}) - return f"Plan {'approved' if approve else 'rejected'}" + icon = "✓" if approve else "✗" + print(f" \033[32m[protocol] plan {icon} ({request_id})\033[0m") + return f"Plan {'approved' if approve else 'rejected'} ({request_id})" # ── Hooks + Permission Pipeline ── @@ -1529,7 +1709,7 @@ threading.Thread(target=cron_scheduler_loop, daemon=True).start() # MCP is modeled as late-bound tools: connect first, then discovered server # tools are merged into the normal tool pool with mcp__server__tool names. class MCPClient: - """Discovers and calls tools on an MCP server (mock for teaching).""" + """Discovers and calls tools on an in-process MCP server.""" def __init__(self, name: str): self.name = name @@ -1585,7 +1765,7 @@ def _mock_server_deploy(): client.register( tool_defs=[ {"name": "trigger", - "description": "Trigger a deployment. (destructive — requires approval in real CC)", + "description": "Trigger a deployment. (destructive; requires approval)", "inputSchema": {"type": "object", "properties": {"service": {"type": "string"}}, "required": ["service"]}}, @@ -1695,28 +1875,18 @@ def run_spawn_teammate(name: str, role: str, prompt: str) -> str: return spawn_teammate_thread(name, role, prompt) def run_send_message(to: str, content: str) -> str: + if to not in active_teammates: + return f"Teammate '{to}' is not active" BUS.send("lead", to, content) return f"Sent to {to}" -def run_check_inbox() -> str: - msgs = consume_lead_inbox(route_protocol=True) - if not msgs: - return "(inbox empty)" - lines = [] - for m in msgs: - meta = m.get("metadata", {}) - req_id = meta.get("request_id", "") - tag = f" [{m['type']} req:{req_id}]" if req_id else f" [{m['type']}]" - lines.append(f" [{m['from']}]{tag} {m['content'][:200]}") - return "\n".join(lines) - def run_connect_mcp(name: str) -> str: return connect_mcp(name) # ── Tool Definitions ── -# The model sees tool schemas; Python executes handlers. S20 keeps both tables +# The model sees tool schemas; Python executes handlers. S19 keeps both tables # explicit so every added capability is visible in one place. BUILTIN_TOOLS = [ {"name": "bash", "description": "Run a shell command.", @@ -1810,7 +1980,10 @@ BUILTIN_TOOLS = [ "required": ["job_id"]}}, {"name": "spawn_teammate", "description": "Spawn an autonomous teammate.", "input_schema": {"type": "object", - "properties": {"name": {"type": "string"}, + "properties": {"name": { + "type": "string", + "pattern": "^[A-Za-z0-9_-]{1,64}$", + }, "role": {"type": "string"}, "prompt": {"type": "string"}}, "required": ["name", "role", "prompt"]}}, @@ -1819,9 +1992,6 @@ BUILTIN_TOOLS = [ "properties": {"to": {"type": "string"}, "content": {"type": "string"}}, "required": ["to", "content"]}}, - {"name": "check_inbox", - "description": "Check inbox for messages and protocol responses.", - "input_schema": {"type": "object", "properties": {}, "required": []}}, {"name": "request_shutdown", "description": "Request a teammate to shut down.", "input_schema": {"type": "object", @@ -1876,7 +2046,7 @@ BUILTIN_HANDLERS = { "list_crons": run_list_crons, "cancel_cron": run_cancel_cron, "spawn_teammate": run_spawn_teammate, - "send_message": run_send_message, "check_inbox": run_check_inbox, + "send_message": run_send_message, "request_shutdown": run_request_shutdown, "request_plan": run_request_plan, "review_plan": run_review_plan, "create_worktree": run_create_worktree, @@ -2063,19 +2233,25 @@ def print_turn_assistants(messages: list, turn_start: int): terminal_print(block["text"] if isinstance(block, dict) else block.text) -def cron_autorun_loop(history: list, context: dict): +def async_event_loop(history: list, context: dict): while True: time.sleep(1) - fired = consume_cron_queue() - if not fired: - continue with agent_lock: + fired = consume_cron_queue() + inbox = consume_lead_inbox(route_protocol=True) + if not fired and not inbox: + continue turn_start = len(history) for job in fired: history.append({"role": "user", "content": f"[Scheduled] {job.prompt}"}) terminal_print( f" \033[35m[cron auto] {job.prompt[:60]}\033[0m") + if inbox: + history.append({"role": "user", + "content": format_team_events(inbox)}) + terminal_print( + f" \033[33m[team auto] {len(inbox)} events\033[0m") agent_loop(history, context) context.update(update_context(context, history)) print_turn_assistants(history, turn_start) @@ -2083,11 +2259,11 @@ def cron_autorun_loop(history: list, context: dict): if __name__ == "__main__": CLI_ACTIVE = True - print("s20: comprehensive agent") + print("s19: comprehensive agent") print("Enter a question, press Enter to send. Type q to quit.\n") history = [] context = update_context({}, []) - threading.Thread(target=cron_autorun_loop, + threading.Thread(target=async_event_loop, args=(history, context), daemon=True).start() while True: try: @@ -2103,17 +2279,4 @@ if __name__ == "__main__": agent_loop(history, context) context = update_context(context, history) print_turn_assistants(history, turn_start) - - inbox = consume_lead_inbox(route_protocol=True) - if inbox: - def inbox_label(msg): - req_id = msg.get("metadata", {}).get("request_id", "") - suffix = f" req:{req_id}" if req_id else "" - return f"{msg.get('type', 'message')}{suffix}" - - inbox_text = "\n".join( - f"From {m['from']} [{inbox_label(m)}]: " - f"{m['content'][:200]}" for m in inbox) - history.append({"role": "user", - "content": f"[Inbox]\n{inbox_text}"}) print() diff --git a/s20_comprehensive/images/system-architecture.en.svg b/s19_comprehensive/images/system-architecture.en.svg similarity index 96% rename from s20_comprehensive/images/system-architecture.en.svg rename to s19_comprehensive/images/system-architecture.en.svg index 01ac3dfb..9958a972 100644 --- a/s20_comprehensive/images/system-architecture.en.svg +++ b/s19_comprehensive/images/system-architecture.en.svg @@ -20,7 +20,7 @@ - s20 Comprehensive Agent — Every Mechanism Around One Loop + s19 Comprehensive Agent — Every Mechanism Around One Loop Core Agent Loop @@ -69,16 +69,16 @@ Teams & Plugins s06 subagent - s15-s17 team protocols - s18 worktree isolation - s19 MCP tools + s15-s16 team protocols + s17 worktree isolation + s18 MCP tools TOOL POOL: 27 builtins + dynamic mcp__server__tool file/shell: bash · read · write · edit · glob single-agent: todo_write · task · load_skill · compact durable work: task tools · cron tools - team: spawn_teammate · send_message · check_inbox + team: spawn_teammate · send_message · typed protocols protocol: request_shutdown · request_plan · review_plan isolation/plugin: worktree tools · connect_mcp diff --git a/web/public/course-assets/s20_comprehensive/system-architecture.ja.svg b/s19_comprehensive/images/system-architecture.ja.svg similarity index 96% rename from web/public/course-assets/s20_comprehensive/system-architecture.ja.svg rename to s19_comprehensive/images/system-architecture.ja.svg index 0461be00..0e5076a4 100644 --- a/web/public/course-assets/s20_comprehensive/system-architecture.ja.svg +++ b/s19_comprehensive/images/system-architecture.ja.svg @@ -20,7 +20,7 @@ - s20 Comprehensive Agent — すべての仕組みを 1 つのループへ + s19 Comprehensive Agent — すべての仕組みを 1 つのループへ Core Agent Loop @@ -69,16 +69,16 @@ Teams / Plugins s06 subagent - s15-s17 team protocols - s18 worktree isolation - s19 MCP tools + s15-s16 team protocols + s17 worktree isolation + s18 MCP tools TOOL POOL: 27 builtins + dynamic mcp__server__tool file/shell: bash · read · write · edit · glob single-agent: todo_write · task · load_skill · compact durable work: task tools · cron tools - team: spawn_teammate · send_message · check_inbox + team: spawn_teammate · send_message · typed protocols protocol: request_shutdown · request_plan · review_plan isolation/plugin: worktree tools · connect_mcp diff --git a/web/public/course-assets/s20_comprehensive/system-architecture.svg b/s19_comprehensive/images/system-architecture.svg similarity index 96% rename from web/public/course-assets/s20_comprehensive/system-architecture.svg rename to s19_comprehensive/images/system-architecture.svg index 72e52f88..e37fb1e8 100644 --- a/web/public/course-assets/s20_comprehensive/system-architecture.svg +++ b/s19_comprehensive/images/system-architecture.svg @@ -21,7 +21,7 @@ - s20 Comprehensive Agent — 全部机制挂在同一个循环上 + s19 Comprehensive Agent — 全部机制挂在同一个循环上 @@ -87,9 +87,9 @@ 团队与插件 s06 subagent - s15-s17 team protocols - s18 worktree isolation - s19 MCP tools + s15-s16 team protocols + s17 worktree isolation + s18 MCP tools @@ -98,7 +98,7 @@ file/shell: bash · read · write · edit · glob single-agent: todo_write · task · load_skill · compact durable work: create/list/get/claim/complete_task · schedule/list/cancel_cron - team: spawn_teammate · send_message · check_inbox + team: spawn_teammate · send_message · typed protocols protocol: request_shutdown · request_plan · review_plan isolation/plugin: create/remove/keep_worktree · connect_mcp diff --git a/s19_mcp_plugin/README.ja.md b/s19_mcp_plugin/README.ja.md deleted file mode 100644 index 5ea052b9..00000000 --- a/s19_mcp_plugin/README.ja.md +++ /dev/null @@ -1,282 +0,0 @@ -# s19: MCP Tools — 外部ツール、標準プロトコル - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s17 → s18 → `s19` → [s20](../s20_comprehensive/) → s21 → s22 - -> *"外部ツール、標準プロトコル"* — 発見、組み立て、呼び出し。Agent はツールを誰が書いたか知る必要がない。 -> -> **Harness 層**: プラグイン — 外部能力を標準プロトコルで接続。 - ---- - -## 課題 - -s01 から s18 まで、Agent の全ツールは手書き — bash、read、write、task、worktree。入力検証、実行ロジック、エラーハンドリング、全て一行ずつ書いた。 - -今、統合したい外部サービスが 3 つある:社内の Jira API(issue 検索、ticket 作成)、独自のデプロイシステム(deploy トリガー、ログ閲覧)、チームの Notion ナレッジベース(ドキュメント検索、ページ作成)。各サービスのためにツールコードを書き直したくない。 - -標準プロトコルが必要 — 外部サービスがこのプロトコルを実装していれば、サービスが何の言語で書かれていても、Agent は直接そのツールを呼び出せる。 - ---- - -## ソリューション - -![MCP Architecture](images/mcp-architecture.ja.svg) - -MCP(Model Context Protocol)は、Agent が外部ツールを発見・呼び出しする方法を定義。核心概念: - -| 概念 | 目的 | -|------|------| -| MCPClient | Agent 側のクライアント — server に接続、ツールを発見、ツールを呼び出し | -| MCP Server | 外部サービス側 — `tools/list` + `tools/call` を実装 | -| assemble_tool_pool | 組み込みツールと MCP ツールを一つのツールプールに組み立てる | -| mcp\_\_server\_\_tool 命名 | 異なる server 間のツール名衝突を防止 | - -s18 の教学版 worktree 隔離、自動認領、空き時ポーリング、プロトコルシステムを踏襲。本章の追加:`connect_mcp` ツール — 外部サービスに接続、ツールを発見、ツールプールに追加。 - -教学版は mock handler で外部 server をシミュレート。実際の版はサブプロセスを起動し、stdin/stdout で JSON-RPC リクエストを送信。mock の利点は外部サービスなしで完全なフローを実行できること;代償は実際のネットワーク通信やプロセス管理が見えないこと。 - ---- - -## 仕組み - -### MCPClient:発見 + 呼び出し - -```python -class MCPClient: - def __init__(self, name: str): - self.name = name - self.tools: list[dict] = [] - self._handlers: dict[str, callable] = {} - - def register(self, tool_defs, handlers): - """Simulates tools/list discovery.""" - self.tools = tool_defs - self._handlers = handlers - - def call_tool(self, tool_name: str, args: dict) -> str: - """Simulates tools/call.""" - handler = self._handlers.get(tool_name) - if not handler: - return f"MCP error: unknown tool '{tool_name}'" - return handler(**args) -``` - -教学版は Python 関数で server のツール実装をシミュレート。実際の版は stdio JSON-RPC でサブプロセスと通信。 - -### connect_mcp:接続 + 発見 - -```python -def connect_mcp(name: str) -> str: - if name in mcp_clients: - return f"MCP server '{name}' already connected" - factory = MOCK_SERVERS.get(name) - if not factory: - return f"Unknown server '{name}'. Available: ..." - mcp_client = factory() - mcp_clients[name] = mcp_client - return f"Connected to '{name}'. Discovered: ..." -``` - -接続後、server が提供するツールが即座に利用可能。 - -### normalize_mcp_name:名前の正規化 - -```python -_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]') - -def normalize_mcp_name(name: str) -> str: - return _DISALLOWED_CHARS.sub('_', name) -``` - -`[a-zA-Z0-9_-]` 以外の全文字を `_` に置換。server 名やツール名の特殊文字による名前衝突やインジェクション問題を防止。 - -### assemble_tool_pool:ツールプールの組み立て - -```python -def assemble_tool_pool() -> tuple[list[dict], dict]: - tools = list(BUILTIN_TOOLS) - handlers = dict(BUILTIN_HANDLERS) - for server_name, mcp_client in mcp_clients.items(): - safe_server = normalize_mcp_name(server_name) - for tool_def in mcp_client.tools: - safe_tool = normalize_mcp_name(tool_def["name"]) - prefixed = f"mcp__{safe_server}__{safe_tool}" - tools.append(...) - handlers[prefixed] = ( - lambda *, c=mcp_client, t=tool_def["name"], **kw: - c.call_tool(t, kw)) - return tools, handlers -``` - -プレフィックス `mcp__{server}__{tool}` で異なる server 間のツール名衝突を防止。名前は `normalize_mcp_name` で正規化。 - -MCP ツールの description に `(readOnly)` または `(destructive)` アノテーションを付与 — 教学版はテキストアノテーション、実際の CC は tool annotations 構造体で権限システムが判断。 - -### キャッシュなし:ツールプールが変われば、プロンプトも変わる - -s10-s18 の agent_loop は prompt cache で再シリアライズを回避。s19 はキャッシュを削除: - -```python -def agent_loop(messages, context): - tools, handlers = assemble_tool_pool() # 毎回再構築 - system = assemble_system_prompt(context) # 毎回再生成 - ... - if any(b.name == "connect_mcp" ...): - tools, handlers = assemble_tool_pool() # 接続後に再構築 - system = assemble_system_prompt(context) -``` - -理由:`connect_mcp` 後にツールプールが変化 — `mcp__docs__search` などの新ツールが追加される。キャッシュ内のツールリストは古く、使い続けるとモデルが新ツールを呼び出せない。教学版はキャッシュを単に削除、代償はシリアライズ時間の若干の増加。 - -### MCP ツールは Lead のみ利用可能 - -教学版では、`connect_mcp` は Lead ツール、`assemble_tool_pool` も Lead の agent_loop のみにサービスを提供。チームメイトは引き続き固定の 8 ツールサブセット(bash、read_file、write_file、send_message、submit_plan、list_tasks、claim_task、complete_task)を使用。 - -これは教学簡略化。実際の CC では、MCP ツールはメイン agent とサブ agent の両方で利用可能 — サブ agent は親の MCP 設定を継承。 - ---- - -## s18 からの変更 - -| コンポーネント | 変更前 (s18) | 変更後 (s19) | -|--------------|------------|------------| -| ツールソース | 全て手書き builtin | 手書き + MCP 外部ツール動的発見 | -| ツールプール | 固定 BUILTIN_TOOLS | assemble_tool_pool が動的に mcp\_\_ プレフィックスツールを組み立てる | -| 名前の安全性 | なし | normalize_mcp_name 正規化 | -| 新規タイプ | — | MCPClient クラス(tools/list + tools/call をシミュレート) | -| 名前空間 | — | mcp\_\_server\_\_tool 衝突防止 | -| ツール説明 | アノテーションなし | (readOnly)/(destructive) アノテーション | -| プロンプトキャッシュ | あり(s10 から) | 削除 — ツールプールが動的、キャッシュが陳腐化 | -| Lead ツール | 17 (s18) | 18 (+connect_mcp) | -| チームメイトツール | 8 (s18) | 8(変更なし、MCP ツールは Lead のみ) | -| 拡張方法 | ツール追加のコードを書く | 標準プロトコル、任意言語で server を実装 | - ---- - -## 試してみる - -```sh -cd learn-claude-code -python s19_mcp_plugin/code.py -``` - -以下のプロンプトを試してください: - -1. `Connect to the docs MCP server and search for something` -2. `Connect to the deploy server and trigger a deployment` -3. `Connect both servers — what tools are now available?` - -観察ポイント:MCP server 接続後、ツール名に `mcp__docs__` や `mcp__deploy__` プレフィックスが付いているか?両方の server のツールが同時に利用可能か?MCP ツールの description に (readOnly)/(destructive) アノテーションが付いているか? - ---- - -## 次の章 - -Agent は標準プロトコルで外部ツールに接続できるようになりました。しかし前 19 章は各章で 1 つの仕組みだけを追加しています。実際の Agent は 19 個の demo に分かれて動くわけではありません。 - -tools、permissions、hooks、todo、task graph、memory、compact、background work、cron、teams、worktree、MCP は、別々の例ではなく同じ loop に接続されるべきです。 - -s20 Comprehensive Agent → 前 19 章の仕組みを 1 つの完全な harness に統合。仕組みは多く、loop は 1 つ。 - -
-CC ソースコード深掘り - -> 以下は CC ソースコード `services/mcp/client.ts`、`auth.ts`、`config.ts`、`channelNotification.ts` の分析に基づく。 - -### 一、6 種の Transport タイプ - -教学版は stdio mock のみ。CC は 6 種のトランスポートをサポート(`types.ts:23-25`): - -| Transport | 通信方式 | -|-----------|---------| -| `stdio` | サブプロセス stdin/stdout(クロスプラットフォームデフォルト) | -| `sse` | HTTP Server-Sent Events | -| `http` | Streamable HTTP(POST/SSE 双方向) | -| `ws` | WebSocket | -| `sse-ide` | IDE 内蔵 SSE トランスポート | -| `sdk` | プロセス内 SDK トランスポート | - -接続時、ローカル(stdio)とリモート(http/sse/ws)サーバーをバッチで並行処理:ローカルは 3 つずつ、リモートは 20 つずつ。 - -### 二、ツールプール組み立てアルゴリズム - -`assembleToolPool()`(`tools.ts:345-364`): - -```typescript -// 重複排除時に組み込みツールを優先(name が同じ場合、組み込みが先) -return uniqBy( - [...builtInTools.sort(byName), ...filteredMcpTools.sort(byName)], - 'name', -) -``` - -組み込みツールと MCP ツールは別々にソート、混ぜてソートしない。理由は CC の `claude_code_system_cache_policy` が最後の組み込みツールの後の特定位置にグローバルキャッシュブレークポイントを置く設計のため — ソートを混ぜるとこの設計が壊れる。 - -### 三、命名規則:`mcp__server__tool` - -`buildMcpToolName()`(`mcpStringUtils.ts:50-52`): - -``` -mcp____ -``` - -`[a-zA-Z0-9_-]` 以外の全文字を `_` に置換(`normalization.ts:17-23`)。教学版の `normalize_mcp_name` も同じルールを使用。 - -### 四、権限チェック - -CC は MCP ツールに対して独立した権限システムを持つ。`checkPermissions()` は MCP ツールに対して組み込みツールとは異なるロジックを適用 — MCP ツールは独自の権限要件(readOnly、destructive 等)を宣言でき、CC は宣言に基づいてユーザー確認が必要かを判断。教学版は description 内のテキストアノテーション `(readOnly)` / `(destructive)` のみで、権限インターセプトは行わない。 - -### 五、設定ソースと優先度 - -MCP サーバー設定は複数のソースから。CC の優先度は低い順に: - -``` -claude.ai コネクタ < プラグイン < ユーザー settings.json < 承認済みプロジェクト .mcp.json < ローカル settings.local.json -``` - -`claude.ai` コネクタは個別に取得、コンテンツ署名で重複排除し、最低優先度で統合(`config.ts:1267-1289`)。企業 `managed-mcp.json` が存在する場合、他の全設定を完全に除外。 - -教学版は server 名を直接 `MOCK_SERVERS` 辞書に渡し、設定マージは行わない。 - -### 六、Channel 通知:サーバーからの逆方向メッセージ - -教学版は Agent → MCP Server の一方向呼び出しのみ。CC は逆方向通知もサポート(`channelNotification.ts`): - -1. Server が `capabilities.experimental['claude/channel']` を宣言 -2. Server が MCP 通知 `notifications/claude/channel` で Agent にメッセージを送信 -3. メッセージは `...` XML タグでラップ -4. Agent は SleepTool で起床(1 秒以内) - -Server は権限リクエストも可能:`notifications/claude/channel/permission_request` → Agent が `notifications/claude/channel/permission` で応答。ユーザーは 5 文字の短い ID で確認/拒否。 - -### 七、OAuth 認証フロー - -CC の MCP 認証(`auth.ts`)は完全な OAuth 2.0 + PKCE フローをサポート: -- 公開クライアント + PKCE で OAuth メタデータを発見(RFC 8414 / RFC 9728) -- ローカルコールバックサーバーが認可コードを受信 -- トークンは `getSecureStorage()` で永続化(macOS Keychain / Linux 暗号化ファイル / Windows 資格情報マネージャー) -- 有効期限 5 分前に自動リフレッシュ -- クロスアプリケーションアクセス(XAA):ブラウザが id_token を取得 → RFC 8693 + RFC 7523 交換 → 繰り返しブラウザポップアップ不要 - -### 八、接続ライフサイクルのエラーハンドリング - -CC は MCP 接続にきめ細かいエラー分類とリトライを行う(`client.ts:1266-1402`): -- 終局エラー(ECONNRESET、ETIMEDOUT、EPIPE 等):連続 3 回 → クローズ + 再接続 -- ツール呼び出し 401:トークン期限切れ → `McpAuthError` スロー → 再認証トリガー -- ツール呼び出しタイムアウト:`Promise.race` タイムアウト(設定可能、デフォルト約 28 時間) -- Stdio 切断:SIGINT → SIGTERM → SIGKILL の順でプロセスを kill - -### 教学版の簡略化 - -- 6 種のトランスポート → 1 種(mock stdio):概念量を管理可能に -- Channel 逆方向通知 → 省略:教学版 Agent は常にイニシエータ -- OAuth フロー → 省略:教学版は server が認証不要と仮定 -- 多層設定優先度 → 省略:教学版は直接 server 名を渡す -- 複雑なエラー分類 → 省略:教学版は try/except でフォールバック -- MCP ツールは Lead のみ → サブ agent 継承を省略:コード構造を簡略化 - -
- - diff --git a/s19_mcp_plugin/README.md b/s19_mcp_plugin/README.md deleted file mode 100644 index 8150e803..00000000 --- a/s19_mcp_plugin/README.md +++ /dev/null @@ -1,282 +0,0 @@ -# s19: MCP Tools — External Tools, Standard Protocol - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s17 → s18 → `s19` → [s20](../s20_comprehensive/) → s21 → s22 - -> *"External tools, standard protocol"* — Discover, assemble, invoke. Agent doesn't need to know who wrote them. -> -> **Harness layer**: Plugins — External capabilities via a standard protocol. - ---- - -## The Problem - -From s01 through s18, every tool the agent uses was hand-written — bash, read, write, task, worktree. Input validation, execution logic, error handling — all written line by line. - -Now you have 3 external services to integrate: the company's Jira API (query issues, create tickets), an in-house deployment system (trigger deploys, view logs), and the team's Notion knowledge base (search docs, create pages). You don't want to rewrite tool code for every service. - -You need a standard protocol — as long as an external service implements it, the agent can call its tools directly, regardless of what language the service is written in. - ---- - -## The Solution - -![MCP Architecture](images/mcp-architecture.en.svg) - -MCP (Model Context Protocol) defines how agents discover and invoke external tools. Core concepts: - -| Concept | Purpose | -|------|------| -| MCPClient | The agent-side client — connects to servers, discovers tools, invokes tools | -| MCP Server | The external service — implements `tools/list` + `tools/call` | -| assemble_tool_pool | Assembles built-in tools and MCP tools into one tool pool | -| mcp\_\_server\_\_tool naming | Prevents tool name collisions across different servers | - -Carries forward s18's teaching-version worktree isolation, autonomous claiming, idle polling, and protocol system. This chapter adds: the `connect_mcp` tool — connect to external services, discover tools, add them to the tool pool. - -The tutorial uses mock handlers to simulate external servers. The real version would spawn subprocesses and communicate via stdin/stdout JSON-RPC. Mocks let you run the full flow without external dependencies; the tradeoff is you don't see real network communication or process management. - ---- - -## How It Works - -### MCPClient: Discovery + Invocation - -```python -class MCPClient: - def __init__(self, name: str): - self.name = name - self.tools: list[dict] = [] - self._handlers: dict[str, callable] = {} - - def register(self, tool_defs, handlers): - """Simulates tools/list discovery.""" - self.tools = tool_defs - self._handlers = handlers - - def call_tool(self, tool_name: str, args: dict) -> str: - """Simulates tools/call.""" - handler = self._handlers.get(tool_name) - if not handler: - return f"MCP error: unknown tool '{tool_name}'" - return handler(**args) -``` - -The tutorial uses Python functions to simulate server tool implementations. The real version communicates with subprocesses via stdio JSON-RPC. - -### connect_mcp: Connect + Discover - -```python -def connect_mcp(name: str) -> str: - if name in mcp_clients: - return f"MCP server '{name}' already connected" - factory = MOCK_SERVERS.get(name) - if not factory: - return f"Unknown server '{name}'. Available: ..." - mcp_client = factory() - mcp_clients[name] = mcp_client - return f"Connected to '{name}'. Discovered: ..." -``` - -After connecting, the server's tools are immediately available. - -### normalize_mcp_name: Name Normalization - -```python -_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]') - -def normalize_mcp_name(name: str) -> str: - return _DISALLOWED_CHARS.sub('_', name) -``` - -All non-`[a-zA-Z0-9_-]` characters are replaced with `_`. Prevents special characters in server or tool names from causing naming conflicts or injection issues. - -### assemble_tool_pool: Assemble Tool Pool - -```python -def assemble_tool_pool() -> tuple[list[dict], dict]: - tools = list(BUILTIN_TOOLS) - handlers = dict(BUILTIN_HANDLERS) - for server_name, mcp_client in mcp_clients.items(): - safe_server = normalize_mcp_name(server_name) - for tool_def in mcp_client.tools: - safe_tool = normalize_mcp_name(tool_def["name"]) - prefixed = f"mcp__{safe_server}__{safe_tool}" - tools.append(...) - handlers[prefixed] = ( - lambda *, c=mcp_client, t=tool_def["name"], **kw: - c.call_tool(t, kw)) - return tools, handlers -``` - -The prefix `mcp__{server}__{tool}` prevents tool name collisions across different servers. Names are normalized through `normalize_mcp_name`. - -MCP tool descriptions include `(readOnly)` or `(destructive)` annotations — the tutorial uses text annotations, while real CC uses structured tool annotations for the permission system. - -### No Cache: Tool Pool Changes, Prompt Changes Too - -s10-s18's agent_loop used prompt caching to avoid re-serialization. s19 removes the cache: - -```python -def agent_loop(messages, context): - tools, handlers = assemble_tool_pool() # Rebuild every time - system = assemble_system_prompt(context) # Regenerate every time - ... - if any(b.name == "connect_mcp" ...): - tools, handlers = assemble_tool_pool() # Rebuild after connection - system = assemble_system_prompt(context) -``` - -Reason: after `connect_mcp`, the tool pool changes — new tools like `mcp__docs__search` are added. The cached tool list is stale; continuing to use it means the model can't call the new tools. The tutorial simply removes caching, at the cost of slightly more serialization time. - -### MCP Tools: Lead Only - -In the tutorial, `connect_mcp` is a Lead tool, and `assemble_tool_pool` only serves the Lead's agent_loop. Teammates still use a fixed 8-tool subset (bash, read_file, write_file, send_message, submit_plan, list_tasks, claim_task, complete_task). - -This is a teaching simplification. In real CC, MCP tools are available to both the main agent and sub-agents — sub-agents inherit the parent's MCP configuration. - ---- - -## Changes from s18 - -| Component | Before (s18) | After (s19) | -|------|-----------|-----------| -| Tool source | All hand-written built-in | Hand-written + MCP external tools with dynamic discovery | -| Tool pool | Fixed BUILTIN_TOOLS | assemble_tool_pool dynamically assembles mcp\_\_ prefixed tools | -| Name safety | None | normalize_mcp_name normalization | -| New type | — | MCPClient class (simulates tools/list + tools/call) | -| Namespace | — | mcp\_\_server\_\_tool prevents collisions | -| Tool descriptions | No annotations | (readOnly)/(destructive) annotations | -| Prompt cache | Yes (since s10) | Removed — tool pool is dynamic, cache goes stale | -| Lead tools | 17 (s18) | 18 (+connect_mcp) | -| Teammate tools | 8 (s18) | 8 (unchanged, MCP tools are Lead-only) | -| Extension method | Write code to add tools | Standard protocol, implement servers in any language | - ---- - -## Try It Out - -```sh -cd learn-claude-code -python s19_mcp_plugin/code.py -``` - -Try these prompts: - -1. `Connect to the docs MCP server and search for something` -2. `Connect to the deploy server and trigger a deployment` -3. `Connect both servers — what tools are now available?` - -What to observe: After connecting to an MCP server, do tool names have `mcp__docs__` or `mcp__deploy__` prefixes? Are both servers' tools available simultaneously? Do MCP tool descriptions include (readOnly)/(destructive) annotations? - ---- - -## What's Next - -The Agent can now connect external tools through a standard protocol. But the first 19 chapters each add one mechanism in isolation; a real Agent does not run as 19 separate demos. - -Tools, permissions, hooks, todo, task graph, memory, compact, background work, cron, teams, worktrees, and MCP should all attach to the same loop, not live in separate examples. - -s20 Comprehensive Agent → Combine the first 19 chapters into one complete harness. Many mechanisms, one loop. - -
-Deep Dive into CC Source - -> The following is based on analysis of CC source: `services/mcp/client.ts`, `auth.ts`, `config.ts`, `channelNotification.ts`. - -### 1. Six Transport Types - -The tutorial only shows a stdio mock. CC supports 6 transport types (`types.ts:23-25`): - -| Transport | Communication method | -|-----------|---------| -| `stdio` | Subprocess stdin/stdout (cross-platform default) | -| `sse` | HTTP Server-Sent Events | -| `http` | Streamable HTTP (POST/SSE bidirectional) | -| `ws` | WebSocket | -| `sse-ide` | IDE-embedded SSE transport | -| `sdk` | In-process SDK transport | - -On connection, local (stdio) and remote (http/sse/ws) servers are batched concurrently: local batch of 3, remote batch of 20. - -### 2. Tool Pool Merging Algorithm - -`assembleToolPool()` (`tools.ts:345-364`): - -```typescript -// Dedup with priority: built-in tools win on name collision (sorted first) -return uniqBy( - [...builtInTools.sort(byName), ...filteredMcpTools.sort(byName)], - 'name', -) -``` - -Built-in and MCP tools are sorted separately, not together. The reason is CC's `claude_code_system_cache_policy` places a global cache breakpoint after the last built-in tool at a specific position — mixing the sort would break this design. - -### 3. Naming Convention: `mcp__server__tool` - -`buildMcpToolName()` (`mcpStringUtils.ts:50-52`): - -``` -mcp____ -``` - -All non-`[a-zA-Z0-9_-]` characters are replaced with `_` (`normalization.ts:17-23`). The tutorial's `normalize_mcp_name` uses the same rule. - -### 4. Permission Checks - -CC has a separate permission system for MCP tools. `checkPermissions()` applies different logic for MCP tools than for built-in tools — MCP tools can declare their own permission requirements (readOnly, destructive, etc.), and CC decides whether user confirmation is needed based on the declaration. The tutorial only uses text annotations `(readOnly)` / `(destructive)` in descriptions, without permission enforcement. - -### 5. Configuration Sources and Priority - -MCP server configuration comes from multiple sources. CC's priority from lowest to highest: - -``` -claude.ai connectors < plugin < user settings.json < approved project .mcp.json < local settings.local.json -``` - -`claude.ai` connectors are fetched separately, deduplicated by content signature, and merged at the lowest precedence (`config.ts:1267-1289`). When enterprise `managed-mcp.json` exists, all other configurations are excluded. - -The tutorial passes server names directly to the `MOCK_SERVERS` dict, without config merging. - -### 6. Channel Notifications: Servers Push Messages Back - -The tutorial only covers agent → MCP Server unidirectional calls. CC also supports reverse notifications (`channelNotification.ts`): - -1. Server declares `capabilities.experimental['claude/channel']` -2. Server sends messages to agent via MCP notification `notifications/claude/channel` -3. Messages are wrapped in `...` XML tags -4. Agent is woken up by SleepTool (within 1 second) - -Servers can also request permissions: `notifications/claude/channel/permission_request` → Agent replies `notifications/claude/channel/permission`. Users confirm/deny via a 5-letter short ID. - -### 7. OAuth Authentication Flow - -CC's MCP authentication (`auth.ts`) supports a full OAuth 2.0 + PKCE flow: -- OAuth metadata discovery via public client + PKCE (RFC 8414 / RFC 9728) -- Local callback server receives authorization code -- Tokens persisted via `getSecureStorage()` (macOS Keychain / Linux encrypted file / Windows Credential Manager) -- Auto-refresh 5 minutes before expiry -- Cross-application access (XAA): browser gets id_token → RFC 8693 + RFC 7523 exchange → no repeated browser popups - -### 8. Connection Lifecycle Error Handling - -CC has fine-grained error classification and retry for MCP connections (`client.ts:1266-1402`): -- Terminal errors (ECONNRESET, ETIMEDOUT, EPIPE, etc.): 3 consecutive failures → close + reconnect -- Tool call 401: Token expired → throw `McpAuthError` → trigger re-authentication -- Tool call timeout: `Promise.race` timeout (configurable, default ~28 hours) -- Stdio disconnect: Kill process in SIGINT → SIGTERM → SIGKILL order - -### The Tutorial's Simplifications - -- 6 transport types → 1 (mock stdio): Manageable concept count -- Channel reverse notifications → omitted: Tutorial agent is always the initiator -- OAuth flow → omitted: Tutorial assumes servers need no auth -- Multi-layer config priority → omitted: Tutorial passes server name directly -- Complex error classification → omitted: Tutorial uses try/except as fallback -- MCP tools Lead-only → omitted sub-agent inheritance: Simplifies code structure - -
- - diff --git a/s19_mcp_plugin/README.zh.md b/s19_mcp_plugin/README.zh.md deleted file mode 100644 index e9f77d39..00000000 --- a/s19_mcp_plugin/README.zh.md +++ /dev/null @@ -1,282 +0,0 @@ -# s19: MCP Tools — 外接工具,标准协议 - -[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) - -s01 → ... → s17 → s18 → `s19` → [s20](../s20_comprehensive/) → s21 → s22 - -> *"外接工具, 标准协议"* — 发现、组装、调用,Agent 不需要知道工具是谁写的。 -> -> **Harness 层**: 插件 — 外部能力通过标准协议接入。 - ---- - -## 问题 - -s01 到 s18,Agent 的所有工具都是手写的——bash、read、write、task、worktree。每个工具的输入验证、执行逻辑、错误处理,都是你一行行写的。 - -现在你有 3 个外部服务想接入:公司的 Jira API(查 issue、建 ticket)、自建的部署系统(触发 deploy、看日志)、团队的 Notion 知识库(搜文档、建页面)。你不想为每个服务重写一套工具代码。 - -你需要一个标准协议——外部服务只要实现它,Agent 就能直接调用,不管服务用什么语言写的。 - ---- - -## 解决方案 - -![MCP Architecture](images/mcp-architecture.svg) - -MCP(Model Context Protocol)定义了 Agent 如何发现和调用外部工具。核心概念: - -| 概念 | 作用 | -|------|------| -| MCPClient | Agent 端的客户端,连接 server、发现工具、调用工具 | -| MCP Server | 外部服务,实现 `tools/list` + `tools/call` | -| assemble_tool_pool | 把内置工具和 MCP 工具组装成一个工具池 | -| mcp\_\_server\_\_tool 命名 | 避免不同 server 的工具名冲突 | - -沿用 s18 的教学版 worktree 隔离、自主认领、空闲轮询、协议系统。本章新增:`connect_mcp` 工具——连接外部服务,发现工具,加入工具池。 - -教学版用 mock handler 模拟外部 server。真实版会启动子进程,通过 stdin/stdout 发送 JSON-RPC 请求。mock 的好处是不依赖外部服务就能跑完整流程;代价是你看不到真正的网络通信和进程管理。 - ---- - -## 工作原理 - -### MCPClient:发现 + 调用 - -```python -class MCPClient: - def __init__(self, name: str): - self.name = name - self.tools: list[dict] = [] - self._handlers: dict[str, callable] = {} - - def register(self, tool_defs, handlers): - """Simulates tools/list discovery.""" - self.tools = tool_defs - self._handlers = handlers - - def call_tool(self, tool_name: str, args: dict) -> str: - """Simulates tools/call.""" - handler = self._handlers.get(tool_name) - if not handler: - return f"MCP error: unknown tool '{tool_name}'" - return handler(**args) -``` - -教学版用 Python 函数模拟 server 的工具实现。真实版通过 stdio JSON-RPC 与子进程通信。 - -### connect_mcp:连接 + 发现 - -```python -def connect_mcp(name: str) -> str: - if name in mcp_clients: - return f"MCP server '{name}' already connected" - factory = MOCK_SERVERS.get(name) - if not factory: - return f"Unknown server '{name}'. Available: ..." - mcp_client = factory() - mcp_clients[name] = mcp_client - return f"Connected to '{name}'. Discovered: ..." -``` - -连接后,server 提供的工具立即可用。 - -### normalize_mcp_name:名称规范化 - -```python -_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]') - -def normalize_mcp_name(name: str) -> str: - return _DISALLOWED_CHARS.sub('_', name) -``` - -所有非 `[a-zA-Z0-9_-]` 的字符替换为 `_`。防止 server 名或工具名中包含特殊字符导致命名冲突或注入问题。 - -### assemble_tool_pool:组装工具池 - -```python -def assemble_tool_pool() -> tuple[list[dict], dict]: - tools = list(BUILTIN_TOOLS) - handlers = dict(BUILTIN_HANDLERS) - for server_name, mcp_client in mcp_clients.items(): - safe_server = normalize_mcp_name(server_name) - for tool_def in mcp_client.tools: - safe_tool = normalize_mcp_name(tool_def["name"]) - prefixed = f"mcp__{safe_server}__{safe_tool}" - tools.append(...) - handlers[prefixed] = ( - lambda *, c=mcp_client, t=tool_def["name"], **kw: - c.call_tool(t, kw)) - return tools, handlers -``` - -前缀 `mcp__{server}__{tool}` 避免不同 server 的工具名冲突。名称经过 `normalize_mcp_name` 规范化。 - -MCP 工具的 description 带 `(readOnly)` 或 `(destructive)` 标注——教学版用文本标注,真实 CC 用 tool annotations 结构体让权限系统判断。 - -### 无缓存:工具池变了,prompt 也变 - -s10-s18 的 agent_loop 用 prompt cache 避免重复序列化。s19 去掉了缓存: - -```python -def agent_loop(messages, context): - tools, handlers = assemble_tool_pool() # 每次重新构建 - system = assemble_system_prompt(context) # 每次重新生成 - ... - if any(b.name == "connect_mcp" ...): - tools, handlers = assemble_tool_pool() # 连接后重建 - system = assemble_system_prompt(context) -``` - -原因:`connect_mcp` 之后工具池变化了——新增了 `mcp__docs__search` 等工具。缓存中的工具列表是旧的,继续用会导致模型调用不到新工具。教学版直接去掉缓存,代价是多花一点序列化时间。 - -### MCP 工具只有 Lead 可用 - -教学版中,`connect_mcp` 是 Lead 工具,`assemble_tool_pool` 也只服务于 Lead 的 agent_loop。Teammate 仍使用固定的 8 个子集工具(bash、read_file、write_file、send_message、submit_plan、list_tasks、claim_task、complete_task)。 - -这是教学简化。真实 CC 中,MCP 工具对主 agent 和子 agent 都可用——子 agent 继承父级的 MCP 配置。 - ---- - -## 相对 s18 的变更 - -| 组件 | 之前 (s18) | 之后 (s19) | -|------|-----------|-----------| -| 工具来源 | 全部手写 builtin | 手写 + MCP 外部工具动态发现 | -| 工具池 | 固定 BUILTIN_TOOLS | assemble_tool_pool 动态组装 mcp\_\_ 前缀工具 | -| 名称安全 | 无 | normalize_mcp_name 规范化 | -| 新类型 | — | MCPClient 类(模拟 tools/list + tools/call) | -| 命名空间 | — | mcp\_\_server\_\_tool 避免冲突 | -| 工具描述 | 无标注 | (readOnly)/(destructive) 标注 | -| prompt 缓存 | 有(s10 起) | 去掉——工具池动态变化后缓存失效 | -| Lead 工具 | 17 (s18) | 18 (+connect_mcp) | -| Teammate 工具 | 8 (s18) | 8(不变,MCP 工具仅 Lead 可用) | -| 扩展方式 | 写代码加工具 | 标准协议,任意语言实现 server | - ---- - -## 试一下 - -```sh -cd learn-claude-code -python s19_mcp_plugin/code.py -``` - -试试这些 prompt: - -1. `Connect to the docs MCP server and search for something` -2. `Connect to the deploy server and trigger a deployment` -3. `Connect both servers — what tools are now available?` - -观察重点:连接 MCP server 后,工具名是否带 `mcp__docs__` 或 `mcp__deploy__` 前缀?两个 server 的工具是否同时可用?MCP 工具的 description 是否带 (readOnly)/(destructive) 标注? - ---- - -## 接下来 - -现在 Agent 可以通过标准协议接入外部工具了。但前面 19 章每章都只加一个机制,真实 Agent 不会这样拆开运行。 - -工具、权限、hooks、todo、任务图、记忆、压缩、后台、cron、团队、worktree、MCP 这些机制应该挂在同一个循环上,而不是散在 19 个 demo 里。 - -s20 Comprehensive Agent → 把前 19 章的机制合回一个完整 harness。机制很多,循环一个。 - -
-深入 CC 源码 - -> 以下基于 CC 源码 `services/mcp/client.ts`、`auth.ts`、`config.ts`、`channelNotification.ts` 的分析。 - -### 一、6 种 Transport 类型 - -教学版只展示了 stdio mock。CC 支持 6 种传输(`types.ts:23-25`): - -| Transport | 通信方式 | -|-----------|---------| -| `stdio` | 子进程 stdin/stdout(跨平台默认) | -| `sse` | HTTP Server-Sent Events | -| `http` | Streamable HTTP(POST/SSE 双向) | -| `ws` | WebSocket | -| `sse-ide` | IDE 内嵌 SSE 传输 | -| `sdk` | 进程内 SDK 传输 | - -连接时本地(stdio)和远程(http/sse/ws)服务器分批并发:本地批量 3 个,远程批量 20 个。 - -### 二、工具池组装算法 - -`assembleToolPool()`(`tools.ts:345-364`): - -```typescript -// 去重时优先保留内置工具(name 相同时内置在前) -return uniqBy( - [...builtInTools.sort(byName), ...filteredMcpTools.sort(byName)], - 'name', -) -``` - -内置工具和 MCP 工具分开排序,不是合起来排。原因是 CC 的 `claude_code_system_cache_policy` 在最后一个内置工具之后的某个位置放全局缓存断点——混排会破坏这个设计。 - -### 三、命名规则:`mcp__server__tool` - -`buildMcpToolName()`(`mcpStringUtils.ts:50-52`): - -``` -mcp____ -``` - -所有非 `[a-zA-Z0-9_-]` 字符替换为 `_`(`normalization.ts:17-23`)。教学版的 `normalize_mcp_name` 用同样的规则。 - -### 四、权限检查 - -CC 对 MCP 工具有独立的权限系统。`checkPermissions()` 对 MCP 工具的检查逻辑不同于内置工具——MCP 工具可以声明自己的权限需求(readOnly、destructive 等),CC 根据声明决定是否需要用户确认。教学版只在 description 中用文本标注 `(readOnly)` / `(destructive)`,不做权限拦截。 - -### 五、配置来源与优先级 - -MCP 服务器配置来自多个来源。CC 的配置优先级从低到高: - -``` -claude.ai 连接器 < plugin < user settings.json < approved project .mcp.json < local settings.local.json -``` - -`claude.ai` 连接器单独拉取、按内容签名去重,以最低优先级合并(`config.ts:1267-1289`)。企业 `managed-mcp.json` 存在时完全排除其他配置。 - -教学版直接传 server name 给 `MOCK_SERVERS` 字典,不做配置合并。 - -### 六、Channel 通知:服务器反向推消息 - -教学版只讲了 Agent → MCP Server 的单向调用。CC 还支持反向通知(`channelNotification.ts`): - -1. Server 声明 `capabilities.experimental['claude/channel']` -2. Server 通过 MCP 通知 `notifications/claude/channel` 给 Agent 发消息 -3. 消息包装在 `...` XML 标签中 -4. Agent 被 SleepTool 唤醒(1 秒内) - -Server 还可以请求权限:`notifications/claude/channel/permission_request` → Agent 回复 `notifications/claude/channel/permission`。用户通过 5 字母短 ID 确认/拒绝。 - -### 七、OAuth 认证流程 - -CC 的 MCP 认证(`auth.ts`)支持完整的 OAuth 2.0 + PKCE 流程: -- 通过公钥客户端 + PKCE 发现 OAuth 元数据(RFC 8414 / RFC 9728) -- 本地回调服务器接收授权码 -- 令牌通过 `getSecureStorage()` 持久化(macOS Keychain / Linux 加密文件 / Windows 凭据管理器) -- 过期前 5 分钟自动刷新 -- 支持跨应用访问(XAA):浏览器获取 id_token → RFC 8693 + RFC 7523 交换 → 无需反复弹浏览器 - -### 八、连接生命周期的错误处理 - -CC 对 MCP 连接有精细的错误分类和重试(`client.ts:1266-1402`): -- 终局性错误(ECONNRESET、ETIMEDOUT、EPIPE 等):连续 3 次 → 关闭 + 重连 -- 工具调用 401:令牌过期 → 抛出 `McpAuthError` → 触发重认证 -- 工具调用超时:`Promise.race` 超时(可配置,默认约 28 小时) -- Stdio 断连:按 SIGINT → SIGTERM → SIGKILL 顺序杀进程 - -### 教学版的简化 - -- 6 种 transport → 1 种(mock stdio):概念量可控 -- Channel 反向通知 → 省略:教学版 Agent 是主动方 -- OAuth 流程 → 省略:教学版假设 server 不需要认证 -- 多层配置优先级 → 省略:教学版直接传 server name -- 复杂的错误分类 → 省略:教学版用 try/except 兜底 -- MCP 工具只给 Lead → 省略子 agent 继承:简化代码结构 - -
- - diff --git a/s21_workflow_runtime/README.ja.md b/s20_workflow_runtime/README.ja.md similarity index 90% rename from s21_workflow_runtime/README.ja.md rename to s20_workflow_runtime/README.ja.md index 24aa53b9..b734a524 100644 --- a/s21_workflow_runtime/README.ja.md +++ b/s20_workflow_runtime/README.ja.md @@ -1,8 +1,8 @@ -# s21: Workflow Runtime — モデルが単一 step を決め、script が orchestration を決める +# s20: Workflow Runtime — モデルが単一 step を決め、script が orchestration を決める [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s19 → s20 → `s21` → [s22](../s22_goal_loop/) +s01 → ... → s18 → s19 → `s20` → [s21](../s21_goal_loop/) > *「1 回の tool_use で、バックグラウンドに一式の orchestration を走らせる」* — `Workflow` ツールが決定的で復元可能な script runtime を起動し、多数の subagent をまとめて送り出します。 > @@ -12,7 +12,7 @@ s01 → ... → s19 → s20 → `s21` → [s22](../s22_goal_loop/) --- -s01 から s20 まで、loop は常にモデル駆動で 1 step ずつ進みました。各ラウンドでモデルが 1 つのツールを選び、結果を `messages[]` へ入れ、次のラウンドへ進みます。open-ended なタスクには最適です。次に何をするかを、モデルが context を見てその場で決められます。 +s01 から s19 まで、loop は常にモデル駆動で 1 step ずつ進みました。各ラウンドでモデルが 1 つのツールを選び、結果を `messages[]` へ入れ、次のラウンドへ進みます。open-ended なタスクには最適です。次に何をするかを、モデルが context を見てその場で決められます。 しかし、複数の Agent を決定的に指揮したい仕事もあります。大きな変更の review を考えてください。10 の観点から並行して問題を探す → 各 finding へ別 Agent を送り adversarial verification を行う → 結果を集約して重複を除く → severity 順に並べる。この流れの形は固定されており、本当に必要なのは 3 つです。 @@ -64,7 +64,7 @@ class WorkflowTool: 不正な入力はすぐ `WorkflowInputError` になり、登録時に止まります。s14 の cron 式検証と同じ考えです。不正な script が実行時まで進んでから壊れないようにします。 -教材 runtime は `meta.name` をローカル artifact のファイル名に使うため、英数字で始まり、英数字、`.`、`_`、`-` のみからなる 1-64 文字の安全な slug も要求する。 +runtime は `meta.name` をローカル artifact のファイル名に使うため、英数字で始まり、英数字、`.`、`_`、`-` のみからなる 1-64 文字の安全な slug も要求する。 ```python def validate_meta(meta): @@ -139,7 +139,7 @@ class LocalWorkflowTask: ## 保存: Snapshot + journal で中断から再開する -この最小 runtime は各 run を `s21_workflow_runtime/.runtime/` に保存します。`.json` snapshot、`.output.json` output、`.journal.jsonl` journal です。production harness では workflow script や subagent transcript も保存できますが、snapshot と journal が安定した `runId` を共有することが重要です。 +runtime は各 run を `s20_workflow_runtime/.runtime/` に保存します。`.json` snapshot、`.output.json` output、`.journal.jsonl` journal です。snapshot と journal は安定した `runId` を共有し、resume 時に同じ run の状態と完了済み step を特定できるようにします。 journal は checkpoint resume の中心で、各 `agent()` の結果を 1 行ずつ記録します。 @@ -171,7 +171,7 @@ if cached is not MISS: ## 決定性: Resume に意味を持たせる再現性 -resume が動くには、workflow が再現可能でなければなりません。この最小 Python runtime は stable hash と決定的な mock runner を使い、同じ workflow + 同じ argument から同じ key を作ります。production harness では workflow code も隔離し、制御されていない clock、randomness、filesystem access などの非決定的な source を除くべきです。 +resume が動くには、workflow が再現可能でなければなりません。stable hash と決定的な runner は、同じ workflow + 同じ argument から同じ key を作ります。そのため workflow code は、制御されていない clock、randomness、filesystem state など、run ごとに key を変える入力を避けます。 ## 実際に動かす @@ -199,22 +199,22 @@ async def sample_workflow(ctx, args): ... ``` -## s20 からの変更点 +## s19 からの変更点 -| | s20 Comprehensive Agent | s21 Workflow Runtime | +| | s19 Comprehensive Agent | s20 Workflow Runtime | |--|-----------|---------------------| | loop | 1 つ、モデル駆動 | main loop は不変。その上に決定的 orchestration を追加 | | 次の step を決めるもの | モデルが毎ラウンド判断 | script が orchestration flow を事前に定義 | | multi-agent | s06 subagent を一度だけ派遣 | script 化された、再現可能で復元可能な一括 orchestration | | 新しい仕組み | — | script DSL、background task、progress event、journal/resume、structured output、deterministic VM | -s21 は main loop を置き換えません。tool layer に `Workflow` を公開し、背後で local workflow runtime を起動します。1 つの workflow が N 個の Agent loop を決定的に駆動します。s06 の subagent はモデルがその場で 1 回派遣し、s21 は orchestration を replay 可能な script にします。 +s20 は main loop を置き換えません。tool layer に `Workflow` を公開し、背後で local workflow runtime を起動します。1 つの workflow が N 個の Agent loop を決定的に駆動します。s06 の subagent はモデルがその場で 1 回派遣し、s20 は orchestration を replay 可能な script にします。 ## 試してみる ```bash -python s21_workflow_runtime/code.py # review-changes を起動し、event stream を確認 -python s21_workflow_runtime/code.py resume # 前回の runId から resume。すべての agent() が journal cache に当たる +python s20_workflow_runtime/code.py # review-changes を起動し、event stream を確認 +python s20_workflow_runtime/code.py resume # 前回の runId から resume。すべての agent() が journal cache に当たる ``` 1 回の起動から `async_launched`、background の phase change と subagent progress、最後の `task_notification` までを観察してください。結果は task object に保存されます。resume 時はすべて cache hit するため `agents=0 tokens=0` と表示され、結果は前回と 1 byte も違いません。 @@ -223,6 +223,6 @@ python s21_workflow_runtime/code.py resume # 前回の runId から resume。 orchestration は Agent 能力の上にもう 1 層を加えます。main loop は個々の操作を管理し、script はチーム全体の flow を管理します。仕事が決定的で復元可能な script になると、モデルは「ラウンドごとの driver」から「script に schedule される実行 unit」へ変わります。同じ `agent()` を main loop でモデルがその場で呼ぶことも、workflow 内で script がまとめて編成することもできます。 -次へ: [s22 Goal Loop](../s22_goal_loop/) — Orchestration は仕事を fan-out し、main loop から離れます。次章は逆に、1 つの goal が control を main loop へ引き戻し、objective が達成されるまで turn の終了を認めません。 +次へ: [s21 Goal Loop](../s21_goal_loop/) — Orchestration は仕事を fan-out し、main loop から離れます。次章は逆に、1 つの goal が control を main loop へ引き戻し、objective が達成されるまで turn の終了を認めません。 diff --git a/s21_workflow_runtime/README.md b/s20_workflow_runtime/README.md similarity index 90% rename from s21_workflow_runtime/README.md rename to s20_workflow_runtime/README.md index 20b9541c..82f55c76 100644 --- a/s21_workflow_runtime/README.md +++ b/s20_workflow_runtime/README.md @@ -1,8 +1,8 @@ -# s21: Workflow Runtime — The Model Decides Each Step; a Script Decides the Orchestration +# s20: Workflow Runtime — The Model Decides Each Step; a Script Decides the Orchestration [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s19 → s20 → `s21` → [s22](../s22_goal_loop/) +s01 → ... → s18 → s19 → `s20` → [s21](../s21_goal_loop/) > *"One tool_use starts an entire orchestration in the background"* — The `Workflow` tool starts a deterministic, recoverable script runtime that dispatches many subagents in bulk. > @@ -12,7 +12,7 @@ s01 → ... → s19 → s20 → `s21` → [s22](../s22_goal_loop/) --- -From s01 through s20, our loop has always been model-driven and step-by-step: the model chooses one tool each round, its result enters `messages[]`, and another round begins. That is ideal for open-ended tasks because the model can inspect the current context and decide the next step on the spot. +From s01 through s19, our loop has always been model-driven and step-by-step: the model chooses one tool each round, its result enters `messages[]`, and another round begins. That is ideal for open-ended tasks because the model can inspect the current context and decide the next step on the spot. Some jobs, however, require deterministic command of a group of agents. Consider reviewing a large change: inspect ten dimensions in parallel → send each finding to a separate agent for adversarial verification → combine and deduplicate the results → sort by severity. The shape is fixed, and you really need three properties: @@ -64,7 +64,7 @@ Each workflow registers a metadata object with `name`, `description`, and option Invalid input raises `WorkflowInputError` immediately and is rejected during registration. This is the same idea as validating cron expressions in s14: do not wait until execution to discover a bad script. -Because the teaching runtime uses `meta.name` in local artifact filenames, it also requires a 1-64 character safe slug containing letters, numbers, `.`, `_`, or `-`. +Because the runtime uses `meta.name` in local artifact filenames, it also requires a 1-64 character safe slug containing letters, numbers, `.`, `_`, or `-`. ```python def validate_meta(meta): @@ -139,7 +139,7 @@ class LocalWorkflowTask: ## Storage: Snapshot + Journal for Resuming after Interruptions -The minimal runtime stores each run under `s21_workflow_runtime/.runtime/`: a `.json` snapshot, `.output.json` output, and `.journal.jsonl` journal. A production harness may also persist the workflow script and subagent transcripts, but the key requirement is that the snapshot and journal share a stable `runId`. +The runtime stores each run under `s20_workflow_runtime/.runtime/`: a `.json` snapshot, `.output.json` output, and `.journal.jsonl` journal. The snapshot and journal share a stable `runId`, so resume can locate one run's state and completed steps. The journal is the core of checkpointed resume. It records every `agent()` result one line at a time: @@ -171,7 +171,7 @@ if cached is not MISS: ## Determinism: Reproducibility Makes Resume Meaningful -Resume works only if the workflow is reproducible. The minimal Python runtime uses stable hashes and a deterministic mock runner, so the same workflow plus the same arguments produces the same keys. A production harness should also isolate workflow code and remove uncontrolled clocks, randomness, filesystem access, and other sources of nondeterminism. +Resume works only if the workflow is reproducible. Stable hashes and a deterministic runner make the same workflow plus the same arguments produce the same keys. Workflow code must therefore avoid uncontrolled clocks, randomness, filesystem state, and other inputs that would change those keys between runs. ## See It Run @@ -199,22 +199,22 @@ async def sample_workflow(ctx, args): ... ``` -## Changes from s20 +## Changes from s19 -| | s20 Comprehensive Agent | s21 Workflow Runtime | +| | s19 Comprehensive Agent | s20 Workflow Runtime | |--|-----------|---------------------| | Loop | One model-driven loop | Main loop unchanged; deterministic orchestration added above it | | Who decides the next step | Model decides each round | Script declares the orchestration in advance | | Multiple agents | One-shot s06 subagents | Scripted, reproducible, recoverable bulk orchestration | | New mechanisms | — | Script DSL, background tasks, progress events, journal/resume, structured output, deterministic VM | -s21 does not replace the main loop. It exposes `Workflow` at the tool layer and starts a local workflow runtime behind it: one workflow deterministically drives N agent loops. An s06 subagent is dispatched once at the model's discretion; s21 turns orchestration into a replayable script. +s20 does not replace the main loop. It exposes `Workflow` at the tool layer and starts a local workflow runtime behind it: one workflow deterministically drives N agent loops. An s06 subagent is dispatched once at the model's discretion; s20 turns orchestration into a replayable script. ## Try It ```bash -python s21_workflow_runtime/code.py # Start review-changes and watch the event stream -python s21_workflow_runtime/code.py resume # Resume by the last runId; every agent() hits the journal cache +python s20_workflow_runtime/code.py # Start review-changes and watch the event stream +python s20_workflow_runtime/code.py resume # Resume by the last runId; every agent() hits the journal cache ``` Watch one launch produce `async_launched`, followed by background phase changes and subagent progress, then `task_notification`; the result is stored on the task object. A resumed run reports `agents=0 tokens=0` because every call hits the cache, and its result is byte-for-byte identical. @@ -223,6 +223,6 @@ Watch one launch produce `async_launched`, followed by background phase changes Orchestration adds a layer above agent capabilities: the main loop handles individual operations, while a script manages the whole team's flow. Once work becomes a deterministic, recoverable script, the model changes from the round-by-round driver into an execution unit scheduled by that script. The same `agent()` can be invoked ad hoc by the model in the main loop or orchestrated in bulk inside a workflow. -Next: [s22 Goal Loop](../s22_goal_loop/) — Orchestration fans work out and leaves the main loop. The next chapter moves in the opposite direction: a goal pulls control back into the main loop and refuses to let the turn end until the objective is achieved. +Next: [s21 Goal Loop](../s21_goal_loop/) — Orchestration fans work out and leaves the main loop. The next chapter moves in the opposite direction: a goal pulls control back into the main loop and refuses to let the turn end until the objective is achieved. diff --git a/s21_workflow_runtime/README.zh.md b/s20_workflow_runtime/README.zh.md similarity index 89% rename from s21_workflow_runtime/README.zh.md rename to s20_workflow_runtime/README.zh.md index 3983a45c..5bcf8d30 100644 --- a/s21_workflow_runtime/README.zh.md +++ b/s20_workflow_runtime/README.zh.md @@ -1,8 +1,8 @@ -# s21: Workflow Runtime — 模型决定单步,脚本决定编排 +# s20: Workflow Runtime — 模型决定单步,脚本决定编排 [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s19 → s20 → `s21` → [s22](../s22_goal_loop/) +s01 → ... → s18 → s19 → `s20` → [s21](../s21_goal_loop/) > *"一次 tool_use,后台跑完一整套编排"* — `Workflow` 工具启动一个确定、可恢复的脚本运行时,批量派出去一堆子 agent。 > @@ -12,7 +12,7 @@ s01 → ... → s19 → s20 → `s21` → [s22](../s22_goal_loop/) --- -从 s01 到 s20,我们的循环一直是模型驱动、一步一步来的:每一轮模型挑一个工具,结果塞回 `messages[]`,再来一轮。开放式任务这么干最合适,下一步做什么,让模型看着上下文临场决定就好。 +从 s01 到 s19,我们的循环一直是模型驱动、一步一步来的:每一轮模型挑一个工具,结果塞回 `messages[]`,再来一轮。开放式任务这么干最合适,下一步做什么,让模型看着上下文临场决定就好。 但有些活,你需要的是确定地指挥一群 agent 干活。比如审一个大改动:十个维度并行找问题 → 每条发现各自派一个 agent 做对抗性验证 → 结果汇总去重 → 按严重度排序。这种流程的形状是固定的,你要的其实是三样东西: @@ -64,7 +64,7 @@ class WorkflowTool: 不对的输入直接抛 `WorkflowInputError`,注册的时候就拦住——这和 s14 校验 cron 表达式是一个思路:坏脚本别让它跑到执行的时候才炸。 -教学运行时会把 `meta.name` 用在本地产物文件名中,因此还要求它是 1-64 个字符的安全 slug,只能包含字母、数字、`.`、`_`、`-`。 +运行时会把 `meta.name` 用在本地产物文件名中,因此还要求它是 1-64 个字符的安全 slug,只能包含字母、数字、`.`、`_`、`-`。 ```python def validate_meta(meta): @@ -139,7 +139,7 @@ class LocalWorkflowTask: ## 存储:快照 + journal,断了能续 -这个最小运行时把每次运行的数据存在 `s21_workflow_runtime/.runtime/`:快照 `.json`、输出 `.output.json` 和 journal `.journal.jsonl`。生产级 harness 还可以保存 workflow 脚本与子 agent 对话记录,但关键约束是快照和 journal 必须共享稳定的 `runId`。 +运行时把每次运行的数据存在 `s20_workflow_runtime/.runtime/`:快照 `.json`、输出 `.output.json` 和 journal `.journal.jsonl`。快照与 journal 共享稳定的 `runId`,续跑时才能找到同一次运行的状态和已完成步骤。 journal 是断点续跑的核心,它一条一条记下来每个 `agent()` 的结果: @@ -171,7 +171,7 @@ if cached is not MISS: ## 确定性:能复现,续跑才有意义 -续跑要能工作,workflow 首先得可复现。这个最小 Python 运行时使用稳定哈希和确定性的 mock runner,让同一份 workflow + 同样的参数产生同样的 key。生产级 harness 还应该隔离 workflow 代码,并移除不受控的时钟、随机数、文件系统访问等不确定来源。 +续跑要能工作,workflow 首先得可复现。稳定哈希和确定性的 runner 让同一份 workflow + 同样的参数产生同样的 key。因此 workflow 代码要避免不受控的时钟、随机数、文件系统状态等会让 key 在两次运行间变化的输入。 ## 跑起来看看 @@ -199,22 +199,22 @@ async def sample_workflow(ctx, args): ... ``` -## 相对 s20 的变更 +## 相对 s19 的变更 -| | s20 综合体 | s21 Workflow Runtime | +| | s19 综合体 | s20 Workflow Runtime | |--|-----------|---------------------| | 循环 | 单个、模型驱动 | 主循环不变;上面加一层确定的编排 | | 谁决定下一步 | 模型逐轮决定 | 脚本预先写好编排流程 | | 多 agent | s06 子 agent,一次性派出去 | 脚本化、可复现、可恢复的批量编排 | | 新增机制 | — | 脚本 DSL、后台任务、进度事件、journal/续跑、结构化输出、确定性 VM | -s21 不替换主循环,它只是在工具层暴露了 `Workflow`,背后启动一个本地 workflow 运行时:一个 workflow 确定地驱动 N 个 agent 循环。s06 的子 agent 是模型临场派一次;s21 是把编排写成可以重放的脚本。 +s20 不替换主循环,它只是在工具层暴露了 `Workflow`,背后启动一个本地 workflow 运行时:一个 workflow 确定地驱动 N 个 agent 循环。s06 的子 agent 是模型临场派一次;s20 是把编排写成可以重放的脚本。 ## 试一下 ```bash -python s21_workflow_runtime/code.py # 启动 review-changes,看事件流 -python s21_workflow_runtime/code.py resume # 用上次的 runId 续跑,每个 agent() 都命中 journal 缓存 +python s20_workflow_runtime/code.py # 启动 review-changes,看事件流 +python s20_workflow_runtime/code.py resume # 用上次的 runId 续跑,每个 agent() 都命中 journal 缓存 ``` 观察:一次启动 → `async_launched` → 后台阶段切换/子agent进度推进 → `task_notification`;结果存在任务对象上。续跑的时候会显示 `agents=0 tokens=0`(全部命中缓存),结果和上次一字不差。 @@ -223,6 +223,6 @@ python s21_workflow_runtime/code.py resume # 用上次的 runId 续跑,每 编排是在 agent 能力之上又加了一层:主循环管单步操作,脚本管整支队伍的流程。把工作写成确定、可恢复的脚本,模型就从"逐轮驱动者"变成了"被脚本调度的执行单元"。同一个 `agent()`,既能在主循环里被模型临场调用,也能在 workflow 里被脚本批量编排。 -下一章:[s22 Goal Loop](../s22_goal_loop/) — 编排是把工作扇出去、脱离主循环;下一章反过来,一个目标把控制权重拉回主循环,没达成就不让这一轮结束。 +下一章:[s21 Goal Loop](../s21_goal_loop/) — 编排是把工作扇出去、脱离主循环;下一章反过来,一个目标把控制权重拉回主循环,没达成就不让这一轮结束。 diff --git a/s21_workflow_runtime/code.py b/s20_workflow_runtime/code.py similarity index 94% rename from s21_workflow_runtime/code.py rename to s20_workflow_runtime/code.py index e1e8a838..a02a4956 100644 --- a/s21_workflow_runtime/code.py +++ b/s20_workflow_runtime/code.py @@ -1,8 +1,8 @@ """ -s21_workflow_runtime — minimal dynamic Workflow runtime for a teaching harness +s20_workflow_runtime — minimal dynamic Workflow runtime Idea: - s01-s20 build a single, model-driven agent loop. s21 adds a deterministic + s01-s19 build a single, model-driven agent loop. s20 adds a deterministic orchestration LAYER on top: the main loop exposes a `Workflow` tool that launches a background runtime; a script written with agent()/parallel()/ pipeline()/phase() drives many subagents deterministically, reports progress, @@ -13,11 +13,10 @@ Run: python code.py resume # resume the last run; unchanged agent() calls hit cache Implementation choices: - - The "subagent" is a deterministic MockAgentRunner, not a real LLM. - - A workflow is a plain async Python function. A production harness may use a - declarative format or run user-authored scripts in an isolated VM. - - The CLI emits `async_launched` and then awaits completion so the demo stays - deterministic. A long-running host can return while execution continues. + - MockAgentRunner is deterministic so resume behavior is reproducible. + - A workflow is a plain async Python function. + - The CLI emits `async_launched` and then awaits completion so event order is + deterministic. - Storage is a local .runtime/ directory beside this file. """ @@ -44,8 +43,7 @@ def _stable_hash(s: str) -> int: def create_run_id(meta) -> str: - # Deterministic in the teaching version so the journal path is predictable - # and `resume` lands on the same file. + # Keep the ID deterministic so `resume` lands on the same journal file. return f"wf_{meta['name']}_{_stable_hash(meta['name']) % 10000:04d}" @@ -90,8 +88,7 @@ def validate_meta(meta): def check_permission(meta, settings=None): - """allow / deny / ask gate before launch (s03 permission system, applied to - Workflow). Teaching version allows by default; a deny rule blocks.""" + """Apply the s03 allow/deny gate before launching a workflow.""" settings = settings or {} if meta["name"] in settings.get("deny", []): raise WorkflowInputError(f"workflow '{meta['name']}' denied by settings") @@ -102,7 +99,7 @@ def check_permission(meta, settings=None): # Minimal JSON-schema for structured output (SimpleJsonSchema) # ============================================================ class SimpleJsonSchema: - """Tiny validator backing agent({schema}). Just enough for teaching: + """Tiny validator backing agent({schema}): object/array/string/boolean/number + required keys.""" def __init__(self, schema): @@ -159,12 +156,10 @@ def _fill_schema(schema, seed): # ============================================================ -# Subagent runner (mock for teaching; real path = an LLM tool loop) +# Deterministic subagent runner # ============================================================ class MockAgentRunner: - """Stands in for a spawned subagent. Deterministic so resume is reproducible. - A real runner would run an isolated agent loop that calls repo tools and is - forced to emit StructuredOutput when a schema is present.""" + """Runs deterministic subagent outputs so resume is reproducible.""" def run(self, prompt, schema=None, label=None): if schema is None: @@ -409,7 +404,7 @@ class ExecutionState: class WorkflowTool: """The Workflow tool. .call() validates meta, runs the permission check, creates runId/taskId, registers a LocalWorkflowTask, and emits lifecycle - events while this teaching CLI awaits the final result. Supports resume.""" + events while the CLI awaits the final result. Supports resume.""" async def call(self, meta, script_fn, args=None, resume_from_run_id=None): validate_meta(meta) @@ -423,7 +418,7 @@ class WorkflowTool: resuming = resume_from_run_id is not None task = LocalWorkflowTask(task_id, run_id, meta) - # The real tool returns this immediately and runs the rest in background. + # Record the launch envelope before workflow execution starts. launched = {"status": "async_launched", "taskId": task_id, "taskType": "local_workflow", "runId": run_id, "workflowName": meta["name"]} diff --git a/s21_workflow_runtime/images/workflow-runtime-overview.svg b/s20_workflow_runtime/images/workflow-runtime-overview.svg similarity index 100% rename from s21_workflow_runtime/images/workflow-runtime-overview.svg rename to s20_workflow_runtime/images/workflow-runtime-overview.svg diff --git a/s22_goal_loop/README.ja.md b/s21_goal_loop/README.ja.md similarity index 91% rename from s22_goal_loop/README.ja.md rename to s21_goal_loop/README.ja.md index 1134ce9f..025a3ce0 100644 --- a/s22_goal_loop/README.ja.md +++ b/s21_goal_loop/README.ja.md @@ -1,8 +1,8 @@ -# s22: Goal Loop — いつ止まるかはモデルではなく goal が決める +# s21: Goal Loop — いつ止まるかはモデルではなく goal が決める [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s20 → s21 → `s22` +s01 → ... → s19 → s20 → `s21` > *「turn が終了できるかは goal condition を満たすかで決まり、モデルが stop と言っただけでは終わらない」* — `/goal` は main loop の各 turn の終端に gate を追加します。独立した evaluator が trusted evidence の充足を確認し、不足ならモデルを次のラウンドへ押し戻します。 > @@ -10,7 +10,7 @@ s01 → ... → s20 → s21 → `s22` --- -s01 から s21 まで、会話の 1 turn はどう終わったでしょうか。モデルが `tool_use` を出さなくなると、loop はそのまま `return` しました。one-shot task なら問題ありません。終わったら止まります。 +s01 から s20 まで、会話の 1 turn はどう終わったでしょうか。モデルが `tool_use` を出さなくなると、loop はそのまま `return` しました。one-shot task なら問題ありません。終わったら止まります。 しかし「テストを通す」「deploy が成功するまで続ける」のように、最後まで見届けるべき goal もあります。そこでは 2 つの問題がよく起きます。モデルが途中まで進めて十分だと思い、自分で止まる。さらに悪ければ、口頭で `tests passed` と言うだけで終了しようとします。必要なことは単純です。turn が終了できるかをモデル自身に決めさせず、明示的な condition を実際の evidence に照らして判断します。 @@ -28,7 +28,7 @@ s01 の loop と比べて、追加されるのは 1 つの判断だけです。 # s01: モデルが stop と言えば停止 if not has_tool_use(response): return -# s22: 止まりたい?先に goal gate を通る +# s21: 止まりたい?先に goal gate を通る if not has_tool_use(response): verdict = goal.evaluate_after_turn() if verdict == "continuing": @@ -71,9 +71,9 @@ def evidence_text(self): return "\n".join(out) ``` -効果は明確です。同じ `tests passed` でも、あなたが入力したものは数えず、background task notification が持ち帰ったものだけを数えます。モデルは「完了した」と自分で言うだけでは goal を complete にできません。これはコース全体に繰り返し現れた trust boundary の最後の登場です。s16 は protocol が理解ではなく field に依存すると言い、s19 は annotation が申告であり、申告は嘘をつけると言い、s22 は completion evidence を content ではなく origin で信頼します。 +効果は明確です。同じ `tests passed` でも、あなたが入力したものは数えず、background task notification が持ち帰ったものだけを数えます。モデルは「完了した」と自分で言うだけでは goal を complete にできません。これはコース全体に繰り返し現れた trust boundary の最後の登場です。s15 は protocol が理解ではなく field に依存すると言い、s18 は annotation が申告であり、申告は嘘をつけると言い、s21 は completion evidence を content ではなく origin で信頼します。 -最小版の `goal_satisfied()` は決定的な keyword matching を使い、demo を offline かつ再現可能に保ちます。production harness では、この policy を独立した lightweight evaluator model に置き換えられますが、trusted evidence boundary はそのまま維持します。 +`goal_satisfied()` は決定的な keyword matching を使い、例を offline かつ再現可能に保ちます。評価と実行を分けることで、trusted evidence boundary を維持します。 ## Gate の 3 状態: Completed / continuing / budget 超過 @@ -126,27 +126,27 @@ s.deliver_host_event("tests passed; deploy green", `submit()` は通常のユーザーテキストだけを受け取る。trusted label は独立した host event channel から入り、source は harness の allowlist で検証される。ユーザーやモデルのテキストが自分に `task-notification` label を付けることはできない。 -## s21 からの変更点 +## s20 からの変更点 -| | s21 Workflow Runtime | s22 Goal Loop | +| | s20 Workflow Runtime | s21 Goal Loop | |--|---------------------|---------------| | trigger | script-controlled orchestration(main loop の外) | condition-controlled continuation(main loop へ引き戻す) | | 接続位置 | tool layer: 1 つの `Workflow` ツール | turn 終端: completion gate | | stop を決めるもの | script が完了 | goal condition を trusted evidence と照合 | | 新しい仕組み | script DSL、background task、journal/resume、structured output | goal gate、evidence trust boundary、continuation 分流、budget | -s21 は script-defined orchestration を main loop の外へ送り出します。s22 は反対の力で control を引き戻します。goal が未達成なら turn は終わっていません。どちらも s01 の `while` loop を変えず、両側から制約を加えます。 +s20 は script-defined orchestration を main loop の外へ送り出します。s21 は反対の力で control を引き戻します。goal が未達成なら turn は終わっていません。どちらも s01 の `while` loop を変えず、両側から制約を加えます。 ## 試してみる ```bash -python s22_goal_loop/code.py # /goal until tests pass + deploy green。gate の判定を見る +python s21_goal_loop/code.py # /goal until tests pass + deploy green。gate の判定を見る ``` goal 設定後、各 turn が `goal_evaluated` を出す様子を確認してください。ordinary text は `satisfied=False`、同じ内容でも `task-notification` origin は `satisfied=True`、budget を使い切ると `goal_blocked` です。同じ `tests passed` でも origin によって結果が正反対になります。空疎な主張で `/goal` を欺けない理由です。 ## 次へ -`/goal` は control を main loop へ引き戻す trigger の 1 つ、condition control です。s21 の main loop 外 orchestration と対になり、一方は仕事を外へ送り、もう一方は control を内へ戻します。その外側には `/loop` と cron による time-controlled re-entry、`Monitor` による event-controlled re-entry もあり、同じ task/notification 基盤を共有します。しかし gate の core はすでにここにあります。**stop するかはモデルの一言では決まらず、goal が trusted evidence に照らして判断します。** +`/goal` は control を main loop へ引き戻す trigger の 1 つ、condition control です。s20 の main loop 外 orchestration と対になり、一方は仕事を外へ送り、もう一方は control を内へ戻します。その外側には `/loop` と cron による time-controlled re-entry、`Monitor` による event-controlled re-entry もあり、同じ task/notification 基盤を共有します。しかし gate の core はすでにここにあります。**stop するかはモデルの一言では決まらず、goal が trusted evidence に照らして判断します。** diff --git a/s22_goal_loop/README.md b/s21_goal_loop/README.md similarity index 90% rename from s22_goal_loop/README.md rename to s21_goal_loop/README.md index 85cbd5f0..9d35df84 100644 --- a/s22_goal_loop/README.md +++ b/s21_goal_loop/README.md @@ -1,8 +1,8 @@ -# s22: Goal Loop — The Goal Decides When to Stop, Not the Model +# s21: Goal Loop — The Goal Decides When to Stop, Not the Model [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s20 → s21 → `s22` +s01 → ... → s19 → s20 → `s21` > *"A turn ends only when the goal condition is satisfied, not merely when the model says stop"* — `/goal` adds a gate at the end of every main-loop turn. An independent evaluator checks whether trusted evidence is sufficient; if not, it pushes the model into another round. > @@ -10,7 +10,7 @@ s01 → ... → s20 → s21 → `s22` --- -From s01 through s21, how does a conversation turn end? When the model stops emitting `tool_use`, the loop simply executes `return`. That is fine for one-shot work: finish and stop. +From s01 through s20, how does a conversation turn end? When the model stops emitting `tool_use`, the loop simply executes `return`. That is fine for one-shot work: finish and stop. Some objectives, however, must be carried through to completion: "get the tests passing" or "do not stop until the deployment succeeds." Two problems appear often. The model does half the work, decides it is close enough, and stops. Worse, it says `tests passed` and tries to declare victory. The requirement is simple: the model cannot decide by itself whether the turn may end. An explicit condition must be evaluated against concrete evidence. @@ -28,7 +28,7 @@ Compared with the s01 loop, there is only one additional decision: when the mode # s01: stop when the model says stop if not has_tool_use(response): return -# s22: want to stop? Pass the goal gate first +# s21: want to stop? Pass the goal gate first if not has_tool_use(response): verdict = goal.evaluate_after_turn() if verdict == "continuing": @@ -71,9 +71,9 @@ def evidence_text(self): return "\n".join(out) ``` -The effect is clear. The same sentence, `tests passed`, does not count when typed by you, but does count when delivered by a background task notification. The model cannot bluff its way out by saying "I finished." This is the final appearance of the trust boundary repeated throughout the course. s16 said protocols rely on fields, not interpretation. s19 said annotations are claims and claims may be false. s22 says completion evidence is trusted by origin, not by content alone. +The effect is clear. The same sentence, `tests passed`, does not count when typed by you, but does count when delivered by a background task notification. The model cannot bluff its way out by saying "I finished." This is the final appearance of the trust boundary repeated throughout the course. s15 said protocols rely on fields, not interpretation. s18 said annotations are claims and claims may be false. s21 says completion evidence is trusted by origin, not by content alone. -The minimal `goal_satisfied()` uses deterministic keyword matching so the demo stays offline and reproducible. A production harness can replace this policy with a separate lightweight evaluator model, while keeping the same trusted evidence boundary. +`goal_satisfied()` uses deterministic keyword matching so the example stays offline and reproducible. Keeping evaluation separate from execution preserves the trusted evidence boundary. ## Three Gate States: Completed, Continuing, or Over Budget @@ -126,27 +126,27 @@ s.deliver_host_event("tests passed; deploy green", `submit()` accepts only ordinary user text. Trusted labels enter through the separate host-event channel, whose source is allowlisted by the harness; user or model text cannot attach its own `task-notification` label. -## Changes from s21 +## Changes from s20 -| | s21 Workflow Runtime | s22 Goal Loop | +| | s20 Workflow Runtime | s21 Goal Loop | |--|---------------------|---------------| | Trigger | Script-controlled orchestration outside the main loop | Condition-controlled continuation pulled back into the main loop | | Attachment point | Tool layer: one `Workflow` tool | End of turn: a completion gate | | Who decides when to stop | The script finishes | Goal condition evaluated against trusted evidence | | New mechanisms | Script DSL, background tasks, journal/resume, structured output | Goal gate, evidence trust boundary, separate continuation path, budget | -s21 sends script-defined orchestration away from the main loop. s22 applies an opposite force that pulls control back: if the goal is not achieved, the turn is not finished. Neither changes the `while` loop from s01; each constrains it from a different side. +s20 sends script-defined orchestration away from the main loop. s21 applies an opposite force that pulls control back: if the goal is not achieved, the turn is not finished. Neither changes the `while` loop from s01; each constrains it from a different side. ## Try It ```bash -python s22_goal_loop/code.py # /goal until tests pass + deploy green; watch the gate decide +python s21_goal_loop/code.py # /goal until tests pass + deploy green; watch the gate decide ``` After setting a goal, watch every turn produce `goal_evaluated`. Ordinary text yields `satisfied=False`; the same content from a `task-notification` origin yields `satisfied=True`; exhausted budget produces `goal_blocked`. The same `tests passed` sentence has opposite results depending on its origin. That is why an empty claim cannot fool `/goal`. ## Next -`/goal` is one kind of trigger that pulls control back into the main loop: condition control. It pairs naturally with s21's orchestration outside the main loop, one dispatching work outward and the other pulling control inward. Beyond them are time-controlled re-entry through `/loop` and cron, and event-controlled re-entry through `Monitor`; all share the same task and notification foundation. But the essential gate is already here: **the model's words do not decide whether to stop. The goal must judge trusted evidence.** +`/goal` is one kind of trigger that pulls control back into the main loop: condition control. It pairs naturally with s20's orchestration outside the main loop, one dispatching work outward and the other pulling control inward. Beyond them are time-controlled re-entry through `/loop` and cron, and event-controlled re-entry through `Monitor`; all share the same task and notification foundation. But the essential gate is already here: **the model's words do not decide whether to stop. The goal must judge trusted evidence.** diff --git a/s22_goal_loop/README.zh.md b/s21_goal_loop/README.zh.md similarity index 91% rename from s22_goal_loop/README.zh.md rename to s21_goal_loop/README.zh.md index 95dd2344..4324b67c 100644 --- a/s22_goal_loop/README.zh.md +++ b/s21_goal_loop/README.zh.md @@ -1,8 +1,8 @@ -# s22: Goal Loop — 什么时候停,目标说了算,不是模型说了算 +# s21: Goal Loop — 什么时候停,目标说了算,不是模型说了算 [English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md) -s01 → ... → s20 → s21 → `s22` +s01 → ... → s19 → s20 → `s21` > *"一轮能不能结束,看目标条件满不满足,不是模型说停就停"* — `/goal` 在主循环每轮收尾的地方加一道闸门:每轮结束后,一个独立的判断器看可信证据够不够,不够就把模型推回去再来一轮。 > @@ -10,7 +10,7 @@ s01 → ... → s20 → s21 → `s22` --- -从 s01 到 s21,一轮对话怎么结束?模型不再发 `tool_use`,循环就直接 `return` 了。一次性任务这么干没问题,做完就停。 +从 s01 到 s20,一轮对话怎么结束?模型不再发 `tool_use`,循环就直接 `return` 了。一次性任务这么干没问题,做完就停。 但有些目标你得盯着它做到底:"把测试跑过"、"部署成功了再说"。这时候经常出两种问题:模型做了一半觉得差不多了,自己就停了;更过分的是,它嘴上说一句 `tests passed` 就想收工。你要的其实很简单:这一轮能不能结束,不能模型自己说了算,得有个明确的条件,对着实打实的证据来判断。 @@ -28,7 +28,7 @@ s01 → ... → s20 → s21 → `s22` # s01:模型说停就停 if not has_tool_use(response): return -# s22:想停?先过目标闸门 +# s21:想停?先过目标闸门 if not has_tool_use(response): verdict = goal.evaluate_after_turn() if verdict == "continuing": @@ -71,9 +71,9 @@ def evidence_text(self): return "\n".join(out) ``` -效果很明显:同样一句 `tests passed`,你打字说的不算,后台任务通知带回来的才算。模型糊弄不过去,它没法靠自己说一句"我做完了"就把目标判成完成。这是全课程反复出现的那条信任边界的最后一次登场:s16 说协议靠字段不靠理解,s19 说注解是申报、申报可以撒谎,s22 说完成证据只看来源不看内容。 +效果很明显:同样一句 `tests passed`,你打字说的不算,后台任务通知带回来的才算。模型糊弄不过去,它没法靠自己说一句"我做完了"就把目标判成完成。这是全课程反复出现的那条信任边界的最后一次登场:s15 说协议靠字段不靠理解,s18 说注解是申报、申报可以撒谎,s21 说完成证据只看来源不看内容。 -最小版的 `goal_satisfied()` 使用确定的关键词匹配,让演示保持离线和可复现。生产级 harness 可以把这条策略替换成独立的轻量判断模型,但仍然保留相同的可信证据边界。 +`goal_satisfied()` 使用确定的关键词匹配,让示例保持离线和可复现。把判断与执行分开,才能守住可信证据边界。 ## 闸门三态:完成/继续/超预算 @@ -126,27 +126,27 @@ s.deliver_host_event("tests passed; deploy green", `submit()` 只接受普通用户文本。可信标签必须走独立的宿主事件通道,来源由 harness 白名单校验;用户或模型文本不能给自己贴上 `task-notification` 标签。 -## 相对 s21 的变更 +## 相对 s20 的变更 -| | s21 Workflow Runtime | s22 Goal Loop | +| | s20 Workflow Runtime | s21 Goal Loop | |--|---------------------|---------------| | 触发方式 | 脚本控制的编排(脱离主循环) | 条件控制的继续(拉回主循环) | | 加在哪 | 工具层:一个 `Workflow` 工具 | 轮次收尾:一道完成闸门 | | 谁决定停 | 脚本跑完就停 | 目标条件对着可信证据判 | | 新增机制 | 脚本 DSL、后台任务、journal/续跑、结构化输出 | 目标闸门、证据信任边界、继续提示分流、预算 | -s21 是把编排写成脚本、派出去脱离主循环;s22 反过来,是一股力量把控制权重拉回主循环:目标没达成,这一轮就不算结束。两个都不改 s01 那个 `while` 循环,只是从两头给它加约束。 +s20 是把编排写成脚本、派出去脱离主循环;s21 反过来,是一股力量把控制权重拉回主循环:目标没达成,这一轮就不算结束。两个都不改 s01 那个 `while` 循环,只是从两头给它加约束。 ## 试一下 ```bash -python s22_goal_loop/code.py # /goal until tests pass + deploy green,看闸门怎么判 +python s21_goal_loop/code.py # /goal until tests pass + deploy green,看闸门怎么判 ``` 观察:设了目标之后,每轮结束都有一条 `goal_evaluated`;普通文本判 `satisfied=False`,`task-notification` 来源判 `satisfied=True`;预算花完的时候出 `goal_blocked`。同样一句 `tests passed`,来源不同,结果完全相反。这就是 `/goal` 不会被一句空话糊弄的地方。 ## 接下来 -`/goal` 是"拉回主循环"的一种触发:条件控制。它和 s21 的"脱离主循环"正好成对,一个把工作派出去,一个把控制权拉回来。再往外,还有时间控制(`/loop`、cron)和事件控制(`Monitor`)的重入,它们共享同一套任务/通知基底;但闸门的核心已经在这里:**停不停,不是模型一句话说了算,得目标对着可信证据来判。** +`/goal` 是"拉回主循环"的一种触发:条件控制。它和 s20 的"脱离主循环"正好成对,一个把工作派出去,一个把控制权拉回来。再往外,还有时间控制(`/loop`、cron)和事件控制(`Monitor`)的重入,它们共享同一套任务/通知基底;但闸门的核心已经在这里:**停不停,不是模型一句话说了算,得目标对着可信证据来判。** diff --git a/s22_goal_loop/code.py b/s21_goal_loop/code.py similarity index 96% rename from s22_goal_loop/code.py rename to s21_goal_loop/code.py index 9ae05f9a..dded3b2a 100644 --- a/s22_goal_loop/code.py +++ b/s21_goal_loop/code.py @@ -1,8 +1,8 @@ """ -s22_goal_loop — minimal /goal session loop for a teaching harness +s21_goal_loop — minimal /goal session loop Idea: - s01-s21 end a turn when the model emits no tool_use. `/goal` adds a + s01-s20 end a turn when the model emits no tool_use. `/goal` adds a host-owned turn-completion GATE: the user sets a stopping CONDITION, and after every turn a separate evaluator judges whether trusted transcript evidence satisfies it. Not satisfied -> the gate blocks the stop and feeds a @@ -13,7 +13,7 @@ Idea: # s01: the model says stop -> stop if not has_tool_use(response): return - # s22: when it wants to stop, pass the goal gate first + # s21: when it wants to stop, pass the goal gate first if not has_tool_use(response): verdict = goal.evaluate_after_turn() if verdict == "continuing": @@ -51,7 +51,7 @@ def event(lane, etype, detail=""): # A message's origin.kind is the TRUST LABEL that decides whether it can count -# as goal evidence. Trusted async origins land real tool/task evidence; user / +# as goal evidence. Trusted async origins carry host-validated evidence; user / # slash-command / active-goal (the continuation reminder) / assistant do not. TRUSTED_EVIDENCE_ORIGINS = {"task-notification", "monitor-line"} @@ -144,8 +144,7 @@ class GoalRuntime: return "\n".join(out) def goal_satisfied(self): - # A production harness can route this evidence window to a separate - # evaluator model. The demo uses a deterministic keyword policy. + # Evaluate only the trusted evidence window with a deterministic policy. objective = self.active["objective"].lower() evidence = self.evidence_text().lower() wants_tests = "test" in objective diff --git a/s22_goal_loop/images/goal-loop-overview.svg b/s21_goal_loop/images/goal-loop-overview.svg similarity index 100% rename from s22_goal_loop/images/goal-loop-overview.svg rename to s21_goal_loop/images/goal-loop-overview.svg diff --git a/tests/test_agent_teams_runtime.py b/tests/test_agent_teams_runtime.py new file mode 100644 index 00000000..e4172d13 --- /dev/null +++ b/tests/test_agent_teams_runtime.py @@ -0,0 +1,308 @@ +import importlib.util +import os +import sys +import tempfile +import threading +import time +import types +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +LESSON = ROOT / "s15_agent_teams" / "code.py" +AUTONOMOUS_LESSON = ROOT / "s16_autonomous_agents" / "code.py" + + +def load_lesson(temp_cwd: Path, lesson_path: Path = LESSON): + fake_anthropic = types.ModuleType("anthropic") + + class FakeAnthropic: + def __init__(self, *args, **kwargs): + self.messages = types.SimpleNamespace(create=None) + + fake_dotenv = types.ModuleType("dotenv") + setattr(fake_anthropic, "Anthropic", FakeAnthropic) + setattr(fake_dotenv, "load_dotenv", lambda override=True: None) + + previous_modules = { + "anthropic": sys.modules.get("anthropic"), + "dotenv": sys.modules.get("dotenv"), + } + previous_cwd = Path.cwd() + previous_model = os.environ.get("MODEL_ID") + + name = f"agent_teams_test_{lesson_path.parent.name}_{time.time_ns()}" + spec = importlib.util.spec_from_file_location(name, lesson_path) + if spec is None or spec.loader is None: + raise RuntimeError(f"Unable to load {lesson_path}") + module = importlib.util.module_from_spec(spec) + + sys.modules["anthropic"] = fake_anthropic + sys.modules["dotenv"] = fake_dotenv + sys.modules[name] = module + try: + os.chdir(temp_cwd) + os.environ["MODEL_ID"] = "test-model" + spec.loader.exec_module(module) + return module + finally: + os.chdir(previous_cwd) + if previous_model is None: + os.environ.pop("MODEL_ID", None) + else: + os.environ["MODEL_ID"] = previous_model + for module_name, previous in previous_modules.items(): + if previous is None: + sys.modules.pop(module_name, None) + else: + sys.modules[module_name] = previous + + +def wait_until(predicate, timeout=2.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.01) + return False + + +class AgentTeamsRuntimeTests(unittest.TestCase): + def test_inbox_delivery_is_runtime_owned(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + + tool_names = {tool["name"] for tool in lesson.TOOLS} + self.assertNotIn("check_inbox", tool_names) + self.assertIn("wait for the user's confirmation", + lesson.PROMPT_SECTIONS["teams"]) + + lesson.BUS.send("alice", "lead", "done", "result") + events = lesson.consume_lead_inbox() + + self.assertEqual([event["type"] for event in events], ["result"]) + self.assertIn("[result] alice: done", + lesson.format_team_events(events)) + + def test_message_bus_rejects_unregistered_or_unsafe_recipients(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + lesson = load_lesson(root) + lesson.active_teammates["alice"] = "idle" + + with self.assertRaises(ValueError): + lesson.BUS.send("alice", "../escape", "bad") + self.assertFalse((root / "escape.jsonl").exists()) + + result = lesson._teammate_send_message( + "alice", "ghost", "Are you there?" + ) + self.assertIn("not active", result) + self.assertFalse((lesson.MAILBOX_DIR / "ghost.jsonl").exists()) + + def test_plan_gate_blocks_mutating_tools_until_approval(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + calls = [] + block = types.SimpleNamespace( + name="write_file", + input={"path": "config.py", "content": "VALUE = 1"}, + ) + handlers = { + "write_file": lambda **kwargs: calls.append(kwargs) or "wrote" + } + + lesson.plan_gates["alice"] = "pending" + blocked = lesson._run_teammate_tool("alice", block, handlers) + self.assertIn("Blocked", blocked) + self.assertEqual(calls, []) + + lesson.plan_gates["alice"] = "approved" + allowed = lesson._run_teammate_tool("alice", block, handlers) + self.assertEqual(allowed, "wrote") + self.assertEqual(len(calls), 1) + + def test_plan_rejection_requires_a_new_submission(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + lesson.active_teammates["alice"] = "idle" + + self.assertIn("Plan requested", + lesson.run_request_plan("alice", "Refactor auth")) + request = lesson.BUS.read_inbox("alice") + self.assertEqual(request[0]["type"], "plan_request") + self.assertEqual(lesson.plan_gates["alice"], "required") + + submission = lesson._teammate_submit_plan("alice", "1. Read\n2. Test") + request_id = submission.split("(")[1].split(")")[0] + self.assertEqual(lesson.pending_requests[request_id].status, "pending") + + result = lesson.run_review_plan( + request_id, False, "Add a rollback step." + ) + self.assertIn("rejected", result) + self.assertEqual(lesson.plan_gates["alice"], "pending") + + responses = lesson.BUS.read_inbox("alice") + accepted, _ = lesson.apply_plan_response("alice", responses[-1]) + self.assertTrue(accepted) + self.assertEqual(lesson.plan_gates["alice"], "rejected") + + second = lesson._teammate_submit_plan( + "alice", "1. Read\n2. Change\n3. Test\n4. Roll back on failure" + ) + second_id = second.split("(")[1].split(")")[0] + self.assertNotEqual(second_id, request_id) + self.assertEqual(lesson.pending_requests[second_id].status, "pending") + + def test_mismatched_plan_response_cannot_release_gate(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + lesson.active_teammates["alice"] = "waiting_approval" + submission = lesson._teammate_submit_plan("alice", "1. Read\n2. Test") + request_id = submission.split("(")[1].split(")")[0] + + forged = { + "from": "lead", + "to": "alice", + "type": "plan_approval_response", + "content": "Approved", + "metadata": {"request_id": "req_stale", "approve": True}, + } + accepted, notice = lesson.apply_plan_response("alice", forged) + + self.assertFalse(accepted) + self.assertIn("Ignored", notice) + self.assertEqual(lesson.plan_gates["alice"], "pending") + self.assertEqual(lesson.plan_request_ids["alice"], request_id) + + current_but_unreviewed = { + **forged, + "metadata": {"request_id": request_id, "approve": True}, + } + accepted, _ = lesson.apply_plan_response( + "alice", current_but_unreviewed + ) + self.assertFalse(accepted) + self.assertEqual(lesson.plan_gates["alice"], "pending") + + def test_shutdown_response_must_come_from_requested_teammate(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + lesson.active_teammates.update({"alice": "idle", "bob": "idle"}) + result = lesson.run_request_shutdown("alice") + request_id = result.split("(")[1].split(")")[0] + + lesson.BUS.send( + "bob", "lead", "Shutdown acknowledged.", + "shutdown_response", + {"request_id": request_id, "approve": True}, + ) + lesson.consume_lead_inbox() + + self.assertEqual( + lesson.pending_requests[request_id].status, "pending" + ) + + def test_shutdown_request_must_match_active_protocol(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + lesson.active_teammates["alice"] = "idle" + forged = { + "from": "lead", + "to": "alice", + "type": "shutdown_request", + "content": "Shut down.", + "metadata": {"request_id": "req_unknown"}, + } + + accepted, notice = lesson.apply_shutdown_request("alice", forged) + self.assertFalse(accepted) + self.assertIn("Ignored", notice) + self.assertEqual(lesson.active_teammates["alice"], "idle") + + result = lesson.run_request_shutdown("alice") + request_id = result.split("(")[1].split(")")[0] + request = lesson.BUS.read_inbox("alice")[-1] + accepted, matched_id = lesson.apply_shutdown_request( + "alice", request + ) + + self.assertTrue(accepted) + self.assertEqual(matched_id, request_id) + self.assertEqual(lesson.active_teammates["alice"], "stopping") + replayed, _ = lesson.apply_shutdown_request("alice", request) + self.assertFalse(replayed) + + def test_teammate_emits_result_then_idle_and_shuts_down(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp)) + lesson.client.messages.create = lambda **kwargs: types.SimpleNamespace( + stop_reason="end_turn", + content=[types.SimpleNamespace(type="text", text="Task complete.")], + ) + + lesson.spawn_teammate_thread("alice", "backend", "Inspect auth.") + lead_inbox = lesson.MAILBOX_DIR / "lead.jsonl" + self.assertTrue(wait_until( + lambda: ( + lead_inbox.exists() + and len(lead_inbox.read_text().splitlines()) >= 2 + ) + )) + events = lesson.consume_lead_inbox() + + self.assertEqual( + [event["type"] for event in events], + ["result", "idle_notification"], + ) + self.assertEqual(lesson.active_teammates["alice"], "idle") + + lesson.run_request_shutdown("alice") + self.assertTrue( + wait_until(lambda: "alice" not in lesson.active_teammates) + ) + shutdown_events = lesson.consume_lead_inbox() + self.assertEqual(shutdown_events[-1]["type"], "shutdown_response") + request_id = shutdown_events[-1]["metadata"]["request_id"] + self.assertEqual( + lesson.pending_requests[request_id].status, "approved" + ) + + def test_autonomous_claim_is_atomic_across_teammates(self): + with tempfile.TemporaryDirectory() as tmp: + lesson = load_lesson(Path(tmp), AUTONOMOUS_LESSON) + lesson.create_task("Refactor auth") + lesson.create_task("Refactor login") + + barrier = threading.Barrier(3) + claimed = {} + + def claim(name): + barrier.wait() + claimed[name] = lesson.claim_next_task(name) + + threads = [ + threading.Thread(target=claim, args=(name,)) + for name in ("alice", "bob") + ] + for thread in threads: + thread.start() + barrier.wait() + for thread in threads: + thread.join(timeout=2) + + self.assertTrue(all(not thread.is_alive() for thread in threads)) + self.assertEqual( + {task.owner for task in claimed.values() if task is not None}, + {"alice", "bob"}, + ) + self.assertEqual( + len({task.id for task in claimed.values() if task is not None}), + 2, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_chapter_readmes.py b/tests/test_chapter_readmes.py index b4727df5..6e142ac3 100644 --- a/tests/test_chapter_readmes.py +++ b/tests/test_chapter_readmes.py @@ -7,7 +7,7 @@ CHAPTERS = sorted(ROOT.glob("s[0-9][0-9]_*")) def test_every_chapter_uses_english_as_the_default_readme() -> None: - assert len(CHAPTERS) == 22 + assert len(CHAPTERS) == 21 for chapter in CHAPTERS: assert (chapter / "README.md").is_file() diff --git a/tests/test_compaction_tool_pairs.py b/tests/test_compaction_tool_pairs.py index 3289a977..cd01b50e 100644 --- a/tests/test_compaction_tool_pairs.py +++ b/tests/test_compaction_tool_pairs.py @@ -11,7 +11,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] MODULES = { "s08": REPO_ROOT / "s08_context_compact" / "code.py", "s09": REPO_ROOT / "s09_memory" / "code.py", - "s20": REPO_ROOT / "s20_comprehensive" / "code.py", + "s19": REPO_ROOT / "s19_comprehensive" / "code.py", } @@ -244,9 +244,9 @@ class CompactionToolPairTests(unittest.TestCase): self.assertEqual(compacted[1:], messages[3:]) assert_no_orphan_tool_results(self, compacted) - def test_s20_has_tool_use_still_accepts_content_blocks(self): + def test_s19_has_tool_use_still_accepts_content_blocks(self): with tempfile.TemporaryDirectory() as tmp: - module = load_module("s20_has_tool_use_under_test", MODULES["s20"], Path(tmp)) + module = load_module("s19_has_tool_use_under_test", MODULES["s19"], Path(tmp)) self.assertTrue(module.has_tool_use([types.SimpleNamespace(type="tool_use")])) self.assertFalse(module.has_tool_use([types.SimpleNamespace(type="text")])) diff --git a/tests/test_todo_write_string_input.py b/tests/test_todo_write_string_input.py index 8decd482..a1200b8f 100644 --- a/tests/test_todo_write_string_input.py +++ b/tests/test_todo_write_string_input.py @@ -13,7 +13,7 @@ COURSE_MODULES = [ ("s06", REPO_ROOT / "s06_subagent" / "code.py"), ("s07", REPO_ROOT / "s07_skill_loading" / "code.py"), ("s08", REPO_ROOT / "s08_context_compact" / "code.py"), - ("s20", REPO_ROOT / "s20_comprehensive" / "code.py"), + ("s19", REPO_ROOT / "s19_comprehensive" / "code.py"), ] diff --git a/tests/test_workflow_goal_lessons.py b/tests/test_workflow_goal_lessons.py index 18bb3297..74be5c39 100644 --- a/tests/test_workflow_goal_lessons.py +++ b/tests/test_workflow_goal_lessons.py @@ -36,7 +36,7 @@ def run_lesson(script: Path, *args: str) -> str: def test_workflow_runtime_resumes_from_journal(tmp_path: Path) -> None: script = tmp_path / "code.py" - shutil.copy2(ROOT / "s21_workflow_runtime" / "code.py", script) + shutil.copy2(ROOT / "s20_workflow_runtime" / "code.py", script) first = run_lesson(script) resumed = run_lesson(script, "resume") @@ -49,7 +49,7 @@ def test_workflow_runtime_resumes_from_journal(tmp_path: Path) -> None: def test_workflow_runtime_rejects_unsafe_artifact_names() -> None: workflow = load_lesson( - "workflow_name_test", ROOT / "s21_workflow_runtime" / "code.py" + "workflow_name_test", ROOT / "s20_workflow_runtime" / "code.py" ) for name in ("../escape", "../../escape", "nested/name"): @@ -61,7 +61,7 @@ def test_workflow_runtime_enforces_budget_and_shared_agent_cap( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: workflow = load_lesson( - "workflow_limit_test", ROOT / "s21_workflow_runtime" / "code.py" + "workflow_limit_test", ROOT / "s20_workflow_runtime" / "code.py" ) budget = workflow.Budget(total=1) with pytest.raises(workflow.WorkflowInputError): @@ -105,7 +105,7 @@ def test_workflow_runtime_enforces_budget_and_shared_agent_cap( def test_workflow_runtime_rejects_corrupt_resume_journal(tmp_path: Path) -> None: workflow = load_lesson( - "workflow_journal_test", ROOT / "s21_workflow_runtime" / "code.py" + "workflow_journal_test", ROOT / "s20_workflow_runtime" / "code.py" ) run_id = "wf_corrupt_0001" (tmp_path / f"{run_id}.journal.jsonl").write_text("{not-json}\n") @@ -118,7 +118,7 @@ def test_goal_loop_requires_trusted_evidence_and_has_a_budget( tmp_path: Path, ) -> None: script = tmp_path / "code.py" - shutil.copy2(ROOT / "s22_goal_loop" / "code.py", script) + shutil.copy2(ROOT / "s21_goal_loop" / "code.py", script) output = run_lesson(script) @@ -128,7 +128,7 @@ def test_goal_loop_requires_trusted_evidence_and_has_a_budget( def test_goal_loop_separates_user_input_from_host_evidence() -> None: - goal_loop = load_lesson("goal_trust_test", ROOT / "s22_goal_loop" / "code.py") + goal_loop = load_lesson("goal_trust_test", ROOT / "s21_goal_loop" / "code.py") session = goal_loop.Session() assert session.submit("/goal until tests passed") == "continuing" diff --git a/web/public/course-assets/s02_tool_use/concurrency-comparison.en.svg b/web/public/course-assets/s02_tool_use/concurrency-comparison.en.svg deleted file mode 100644 index 04dab323..00000000 --- a/web/public/course-assets/s02_tool_use/concurrency-comparison.en.svg +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - Tool Concurrency — Teaching Version vs Claude Code - - - - Model returns 5 tool calls at once - - - read A.py - - - glob *.py - - - bash "ls -la" - - - write B.py - - - read C.py - - - - Teaching: Original Order, One by One - - - for block in response.content: - TOOL_HANDLERS[name](**input) - - Result: 5 serial calls, no batches - - - 1. read A.py - - - 2. glob *.py - - - 3. bash "ls -la" - - - 4. write B.py - - - 5. read C.py - - Teaching focus: tool dispatch first; concurrency omitted - - - - Claude Code: isConcurrencySafe(input) - - - Each tool call judged individually: - tool.isConcurrencySafe(parsedInput) → bool - - Result: 3 batches (by consecutive blocks) - - - Batch 1 - Concurrent - read A · glob · bash "ls" - - - - - Batch 2 - Serial - write B - - - - - Batch 3 - Concurrent - read C - - bash "ls" is safe and consecutive, so it stays in Batch 1 - - ✓ Input-dependent safety, not tool-name hardcoding - ✓ Original order preserved; only safe consecutive calls run together - - - - Key Difference - • Teaching: executes response.content in original order, one tool call at a time; no concurrency or batching - • CC: checks isConcurrencySafe(input), then groups consecutive safe calls into one batch - • Key difference: teaching focuses on dispatch; CC optimizes safe concurrency while preserving order semantics - diff --git a/web/public/course-assets/s02_tool_use/concurrency-comparison.ja.svg b/web/public/course-assets/s02_tool_use/concurrency-comparison.ja.svg deleted file mode 100644 index f130d5b3..00000000 --- a/web/public/course-assets/s02_tool_use/concurrency-comparison.ja.svg +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - ツール並列実行 — 教育版 vs Claude Code - - - - モデルが一度に 5 つのツール呼び出しを返す - - - read A.py - - - glob *.py - - - bash "ls -la" - - - write B.py - - - read C.py - - - - 教育版:元の順序で一つずつ実行 - - - for block in response.content: - TOOL_HANDLERS[name](**input) - - 結果:5 回の直列呼び出し、batch なし - - - 1. read A.py - - - 2. glob *.py - - - 3. bash "ls -la" - - - 4. write B.py - - - 5. read C.py - - 教育の焦点:まず tool_use 分配を理解し、並列は省略 - - - - Claude Code:isConcurrencySafe(input) - - - 各ツール呼び出しを個別に判定: - tool.isConcurrencySafe(parsedInput) → bool - - 結果:3 バッチ(連続ブロックごと) - - - Batch 1 - 並列 - read A · glob · bash "ls" - - - - - Batch 2 - 直列 - write B - - - - - Batch 3 - 並列 - read C - - bash "ls" は安全かつ連続しているため Batch 1 に入る - - ✓ 入力に基づく安全判定、ツール名ハードコードではない - ✓ 元の順序を保ち、連続する安全呼び出しだけ並列化 - - - - 核心的な違い - • 教育版:response.content の元の順序で一つずつ実行し、並列処理も batch 化もしない - • CC:isConcurrencySafe(input) で判定し、連続する安全呼び出しを同じ batch にまとめる - • 差分の要点:教育版は分配に集中し、CC は順序意味を保ったまま安全な並列を最適化する - diff --git a/web/public/course-assets/s02_tool_use/concurrency-comparison.svg b/web/public/course-assets/s02_tool_use/concurrency-comparison.svg deleted file mode 100644 index e6941e61..00000000 --- a/web/public/course-assets/s02_tool_use/concurrency-comparison.svg +++ /dev/null @@ -1,108 +0,0 @@ - - - - - - - - - - - - - - - - - - - - Tool Concurrency — 教学版 vs Claude Code - - - - 模型一次返回 5 个工具调用 - - - read A.py - - - glob *.py - - - bash "ls -la" - - - write B.py - - - read C.py - - - - 教学版:按原始顺序逐个执行 - - - for block in response.content: - TOOL_HANDLERS[name](**input) - - 结果:5 次串行调用,不做 batch - - - 1. read A.py - - - 2. glob *.py - - - 3. bash "ls -la" - - - 4. write B.py - - - 5. read C.py - - 教学重点:先理解 tool_use 分发,暂不引入并发执行 - - - - Claude Code:isConcurrencySafe(input) - - - 每个工具调用单独判断: - tool.isConcurrencySafe(parsedInput) → bool - - 结果:3 个 batch(按连续块分批) - - - Batch 1 - 并发 - read A · glob · bash "ls" - - - - - Batch 2 - 串行 - write B - - - - - Batch 3 - 并发 - read C - - bash "ls" 是并发安全调用,且和 read/glob 连续,所以留在 Batch 1 - - ✓ 按输入判断并发安全,不按工具名硬编码 - ✓ 保留原始顺序,只在连续安全块内部并发 - - - - 核心差异 - • 教学版:按 response.content 原始顺序逐个执行,不做并发,也不分 batch - • CC:按 isConcurrencySafe(input) 判断,并把连续的并发安全调用合成同一个 batch - • 差异重点:教学版聚焦工具分发;CC 在保持顺序语义的同时优化安全并发 - diff --git a/web/public/course-assets/s04_hooks/hooks-overview.en.svg b/web/public/course-assets/s04_hooks/hooks-overview.en.svg index 87afdc0c..14f725e8 100644 --- a/web/public/course-assets/s04_hooks/hooks-overview.en.svg +++ b/web/public/course-assets/s04_hooks/hooks-overview.en.svg @@ -57,7 +57,7 @@ PreToolUse permission_hook · log_hook - Teaching: non-None → block + non-None → block diff --git a/web/public/course-assets/s04_hooks/hooks-overview.ja.svg b/web/public/course-assets/s04_hooks/hooks-overview.ja.svg index d1addf60..5f00d1c5 100644 --- a/web/public/course-assets/s04_hooks/hooks-overview.ja.svg +++ b/web/public/course-assets/s04_hooks/hooks-overview.ja.svg @@ -57,7 +57,7 @@ PreToolUse permission_hook · log_hook - 教育版: 非 None → ブロック + 非 None → ブロック diff --git a/web/public/course-assets/s04_hooks/hooks-overview.svg b/web/public/course-assets/s04_hooks/hooks-overview.svg index 410593af..934df956 100644 --- a/web/public/course-assets/s04_hooks/hooks-overview.svg +++ b/web/public/course-assets/s04_hooks/hooks-overview.svg @@ -57,7 +57,7 @@ PreToolUse permission_hook · log_hook - 教学版:非 None → 阻止 + 非 None → 阻止 diff --git a/web/public/course-assets/s08_context_compact/compaction-layers.en.svg b/web/public/course-assets/s08_context_compact/compaction-layers.en.svg index 5a27e96d..f8eae9a0 100644 --- a/web/public/course-assets/s08_context_compact/compaction-layers.en.svg +++ b/web/public/course-assets/s08_context_compact/compaction-layers.en.svg @@ -69,7 +69,7 @@ microCompact old tool_result → placeholder (keep latest 3) compact old - Trigger: every turn automatically; tutorial uses text placeholder + Trigger: every turn; replace older results with text placeholders diff --git a/web/public/course-assets/s08_context_compact/compaction-layers.ja.svg b/web/public/course-assets/s08_context_compact/compaction-layers.ja.svg index 85190548..5a8ca2de 100644 --- a/web/public/course-assets/s08_context_compact/compaction-layers.ja.svg +++ b/web/public/course-assets/s08_context_compact/compaction-layers.ja.svg @@ -69,7 +69,7 @@ microCompact 古い tool_result → プレースホルダー(最新 3 件保持) 旧結果を圧縮 - トリガー:毎ターン自動実行、チュートリアル版はテキストプレースホルダーで模擬 + トリガー:毎ターン、古い結果をテキストプレースホルダーに置換 diff --git a/web/public/course-assets/s08_context_compact/compaction-layers.svg b/web/public/course-assets/s08_context_compact/compaction-layers.svg index 818b44e5..f82bdd44 100644 --- a/web/public/course-assets/s08_context_compact/compaction-layers.svg +++ b/web/public/course-assets/s08_context_compact/compaction-layers.svg @@ -69,7 +69,7 @@ microCompact 旧 tool_result → 占位符(保留最近 3 条) 压旧结果 - 触发:每轮自动,教学版用文本占位符模拟 + 触发:每轮自动,把较旧结果替换为文本占位符 diff --git a/web/public/course-assets/s08_context_compact/micro-compact.en.svg b/web/public/course-assets/s08_context_compact/micro-compact.en.svg index 8f5c5dc8..4c8d049b 100644 --- a/web/public/course-assets/s08_context_compact/micro-compact.en.svg +++ b/web/public/course-assets/s08_context_compact/micro-compact.en.svg @@ -50,9 +50,9 @@ - How (teaching version) - Iterate through tool_result, keep only latest 3 complete, replace older ones with placeholders. - Real CC - Clears old results via API cache_edits (without breaking prompt cache prefix), only for COMPACTABLE_TOOLS: - Read, Bash, Grep, Glob, WebSearch, WebFetch, Edit, Write. Teaching version uses text placeholders to simulate the same effect. + Rule + Keep the latest 3 tool results complete and replace older results with placeholders. + Placeholder + Explain that the result was compacted and that the tool can be run again if needed. + The message structure remains valid for the next loop iteration. diff --git a/web/public/course-assets/s08_context_compact/micro-compact.ja.svg b/web/public/course-assets/s08_context_compact/micro-compact.ja.svg index a418c544..f54339fa 100644 --- a/web/public/course-assets/s08_context_compact/micro-compact.ja.svg +++ b/web/public/course-assets/s08_context_compact/micro-compact.ja.svg @@ -50,9 +50,9 @@ - 方法(教学版) - tool_result を走査し、最新 3 件のみ完全保持、古いものはプレースホルダーに置換。 - 実際の CC - API cache_edits で旧結果をクリア(prompt cache プレフィックスを破壊しない)、COMPACTABLE_TOOLS のみ対象: - Read, Bash, Grep, Glob, WebSearch, WebFetch, Edit, Write。教学版はテキストプレースホルダーで同様の効果を模擬。 + 処理規則 + 最新 3 件の tool_result を完全保持し、古い結果をプレースホルダーに置換する。 + プレースホルダー + 結果が圧縮済みで、必要ならツールを再実行できることを示す。 + メッセージ構造を保ったまま次のループへ進める。 diff --git a/web/public/course-assets/s08_context_compact/micro-compact.svg b/web/public/course-assets/s08_context_compact/micro-compact.svg index e1728f7d..fd979840 100644 --- a/web/public/course-assets/s08_context_compact/micro-compact.svg +++ b/web/public/course-assets/s08_context_compact/micro-compact.svg @@ -49,9 +49,9 @@ - 怎么做(教学版) - 遍历 tool_result,只保留最近 3 条完整,更旧的替换为占位符。 - 真实 CC - 通过 API cache_edits 清除旧结果(不破坏 prompt cache 前缀),仅对 COMPACTABLE_TOOLS 生效: - Read, Bash, Grep, Glob, WebSearch, WebFetch, Edit, Write。教学版用文本占位模拟同样效果。 + 处理规则 + 遍历 tool_result,只保留最近 3 条完整,更旧的替换为占位符。 + 占位内容 + 说明原结果已压缩,并提示需要时重新运行对应工具。 + 消息结构保持不变,后续循环仍可继续处理。 diff --git a/web/public/course-assets/s12_task_system/task-system-overview.en.svg b/web/public/course-assets/s12_task_system/task-system-overview.en.svg index b4a74b6c..4337f6eb 100644 --- a/web/public/course-assets/s12_task_system/task-system-overview.en.svg +++ b/web/public/course-assets/s12_task_system/task-system-overview.en.svg @@ -57,7 +57,7 @@ .tasks/ — Cross-session Persistence task_xxx.json · task_yyy.json · task_zzz.json {id, subject, description, status, owner, blockedBy} - Tutorial ID: timestamp + random | CC: sequential ID + highwatermark + ID: timestamp + random diff --git a/web/public/course-assets/s12_task_system/task-system-overview.ja.svg b/web/public/course-assets/s12_task_system/task-system-overview.ja.svg index 906a0dbf..68b56a5c 100644 --- a/web/public/course-assets/s12_task_system/task-system-overview.ja.svg +++ b/web/public/course-assets/s12_task_system/task-system-overview.ja.svg @@ -57,7 +57,7 @@ .tasks/ — セッション横断永続化 task_xxx.json · task_yyy.json · task_zzz.json {id, subject, description, status, owner, blockedBy} - チュートリアル ID: timestamp + random | CC: 順次 ID + highwatermark + ID: timestamp + random diff --git a/web/public/course-assets/s12_task_system/task-system-overview.svg b/web/public/course-assets/s12_task_system/task-system-overview.svg index 097b61f3..5dbfb11f 100644 --- a/web/public/course-assets/s12_task_system/task-system-overview.svg +++ b/web/public/course-assets/s12_task_system/task-system-overview.svg @@ -57,7 +57,7 @@ .tasks/ — 跨会话持久化 task_xxx.json · task_yyy.json · task_zzz.json {id, subject, description, status, owner, blockedBy} - 教学版 ID: timestamp + random | CC: 顺序 ID + highwatermark + ID: timestamp + random diff --git a/web/public/course-assets/s15_agent_teams/agent-teams-overview.en.svg b/web/public/course-assets/s15_agent_teams/agent-teams-overview.en.svg index f87995ad..2eca1728 100644 --- a/web/public/course-assets/s15_agent_teams/agent-teams-overview.en.svg +++ b/web/public/course-assets/s15_agent_teams/agent-teams-overview.en.svg @@ -32,7 +32,7 @@ Teammate - Real CC detail + Protocol gate @@ -58,7 +58,7 @@ TOOL DISPATCH bash · read · write · task(4) · cron(3) - ★ spawn_teammate · send_message · check_inbox + ★ spawn · send · shutdown · plan review @@ -90,7 +90,7 @@ Teammate: alice (Backend) inbox → LLM → bash/read/write/send - Max 10 rounds → summary → BUS.send + WORK → result → IDLE → next message Teammate: bob (Frontend) @@ -100,21 +100,21 @@ Teammate: charlie (QA) Cannot spawn other teammates - spawn → work → summary + spawn → work → result → idle - + - permission_request + plan_request - Permission Bubbling (real CC; omitted in teaching code) - ① Teammate needs approval → MessageBus sends permission_request ② Lead receives → user approval → approve/deny + Plan Approval Gate + ① Teammate submits plan ② Lead approves or rejects ③ bash / write_file stay blocked until approved s10-s14: prompt assembly, error recovery, task graph, background threads, cron scheduling - s15: MessageBus + spawn_teammate_thread + send_message + check_inbox (permission bubbling is a real CC detail) + s15: MessageBus + persistent teammates + event delivery + typed protocols + plan gate diff --git a/web/public/course-assets/s15_agent_teams/agent-teams-overview.ja.svg b/web/public/course-assets/s15_agent_teams/agent-teams-overview.ja.svg index 47c96654..5fdc98a1 100644 --- a/web/public/course-assets/s15_agent_teams/agent-teams-overview.ja.svg +++ b/web/public/course-assets/s15_agent_teams/agent-teams-overview.ja.svg @@ -32,7 +32,7 @@ チームメイト - 真实 CC 補足 + プロトコルゲート @@ -58,7 +58,7 @@ TOOL DISPATCH bash · read · write · task(4) · cron(3) - ★ spawn_teammate · send_message · check_inbox + ★ spawn · send · shutdown · plan review @@ -90,7 +90,7 @@ チームメイト: alice (Backend) inbox → LLM → bash/read/write/send - 最大 10 ラウンド → summary → BUS.send + WORK → result → IDLE → next message チームメイト: bob (Frontend) @@ -100,21 +100,21 @@ チームメイト: charlie (QA) 他のチームメイトを spawn 不可 - spawn → work → summary + spawn → work → result → idle - + - permission_request + plan_request - 権限バブリング(真实 CC、教学版は省略) - ① 承認が必要 → MessageBus が permission_request 送信 ② Lead が受信 → ユーザー承認 → approve/deny + プラン承認ゲート + ① プラン提出 ② Lead が承認または却下 ③ approved まで bash / write_file を遮断 s10-s14:プロンプト組み立て、エラーリカバリ、タスクグラフ、バックグラウンドスレッド、cron - s15:MessageBus + spawn_teammate_thread + send_message + check_inbox(権限バブリングは真实 CC 補足) + s15:MessageBus + 永続チームメイト + イベント配信 + 型付きプロトコル + プランゲート diff --git a/web/public/course-assets/s15_agent_teams/agent-teams-overview.svg b/web/public/course-assets/s15_agent_teams/agent-teams-overview.svg index e708a334..689bfa9a 100644 --- a/web/public/course-assets/s15_agent_teams/agent-teams-overview.svg +++ b/web/public/course-assets/s15_agent_teams/agent-teams-overview.svg @@ -32,7 +32,7 @@ Teammate - 真实 CC 补充 + 协议闸门 @@ -60,7 +60,7 @@ TOOL DISPATCH bash · read · write · task(4) · cron(3) - ★ spawn_teammate · send_message · check_inbox + ★ spawn · send · shutdown · plan review @@ -99,7 +99,7 @@ Teammate: alice (Backend) inbox → LLM → bash/read/write/send - 最多 10 轮 → summary → BUS.send + WORK → result → IDLE → next message @@ -111,22 +111,21 @@ Teammate: charlie (QA) 不能 spawn 其他 teammate - spawn → work → summary + spawn → work → result → idle - - + - permission_request + plan_request - 权限冒泡(真实 CC,教学版省略) - ① 队友需审批 → MessageBus 发送 permission_request ② Lead 收到 → 用户审批 → 回复 approve/deny + 计划审批闸门 + ① 队友提交计划 ② Lead 批准或拒绝 ③ approved 前 bash / write_file 被拦截 s10-s14: prompt 组装、错误恢复、任务图、后台线程、cron 调度 - s15: MessageBus + spawn_teammate_thread + send_message + check_inbox(权限冒泡见真实 CC 补充) + s15: MessageBus + 持久队友 + 自动事件投递 + 类型化协议 + 计划闸门 diff --git a/s16_team_protocols/images/team-protocols-overview.en.svg b/web/public/course-assets/s15_agent_teams/team-protocols-overview.en.svg similarity index 97% rename from s16_team_protocols/images/team-protocols-overview.en.svg rename to web/public/course-assets/s15_agent_teams/team-protocols-overview.en.svg index 36e335ba..ca48820d 100644 --- a/s16_team_protocols/images/team-protocols-overview.en.svg +++ b/web/public/course-assets/s15_agent_teams/team-protocols-overview.en.svg @@ -24,9 +24,9 @@ Team Protocols — Request-Response + request_id Correlation + State Machine - s15 Preserved + Team runtime - s16 New + Protocols @@ -135,7 +135,7 @@ - s15: MessageBus + spawn_teammate + inbox + Runtime: MessageBus + persistent teammates + automatic delivery - s16: request_id protocol + dispatch + pending_requests + state machine + Protocol: request_id + dispatch + pending_requests + plan gate diff --git a/s16_team_protocols/images/team-protocols-overview.ja.svg b/web/public/course-assets/s15_agent_teams/team-protocols-overview.ja.svg similarity index 97% rename from s16_team_protocols/images/team-protocols-overview.ja.svg rename to web/public/course-assets/s15_agent_teams/team-protocols-overview.ja.svg index f4a34f4e..e932d05a 100644 --- a/s16_team_protocols/images/team-protocols-overview.ja.svg +++ b/web/public/course-assets/s15_agent_teams/team-protocols-overview.ja.svg @@ -24,9 +24,9 @@ Team Protocols — リクエスト・レスポンス + request_id 紐付け + 状態機械 - s15 維持 + チームランタイム - s16 新規 + 協調プロトコル @@ -135,7 +135,7 @@ - s15: MessageBus + spawn_teammate + inbox + Runtime: MessageBus + 永続チームメイト + 自動イベント配信 - s16: request_id プロトコル + dispatch + pending_requests + 状態機械 + Protocol: request_id + dispatch + pending_requests + プランゲート diff --git a/web/public/course-assets/s16_team_protocols/team-protocols-overview.svg b/web/public/course-assets/s15_agent_teams/team-protocols-overview.svg similarity index 97% rename from web/public/course-assets/s16_team_protocols/team-protocols-overview.svg rename to web/public/course-assets/s15_agent_teams/team-protocols-overview.svg index dcc53a0d..3cda2396 100644 --- a/web/public/course-assets/s16_team_protocols/team-protocols-overview.svg +++ b/web/public/course-assets/s15_agent_teams/team-protocols-overview.svg @@ -24,9 +24,9 @@ Team Protocols — 请求-响应协议 + request_id 关联 + 状态机 - s15 保留 + 团队运行时 - s16 新增 + 协作协议 @@ -135,7 +135,7 @@ - s15: MessageBus + spawn_teammate + inbox + 运行时: MessageBus + 持久队友 + 自动事件投递 - s16: request_id 协议 + dispatch + pending_requests + 状态机 + 协议: request_id + dispatch + pending_requests + 计划闸门 diff --git a/web/public/course-assets/s15_agent_teams/team-topology.en.svg b/web/public/course-assets/s15_agent_teams/team-topology.en.svg index 7540db7c..62377e4b 100644 --- a/web/public/course-assets/s15_agent_teams/team-topology.en.svg +++ b/web/public/course-assets/s15_agent_teams/team-topology.en.svg @@ -23,7 +23,7 @@ Lead Agent Main loop + spawn + inbox handling - check_inbox receives teammate messages + runtime delivers team events automatically diff --git a/web/public/course-assets/s15_agent_teams/team-topology.ja.svg b/web/public/course-assets/s15_agent_teams/team-topology.ja.svg index 77c8709e..1f132290 100644 --- a/web/public/course-assets/s15_agent_teams/team-topology.ja.svg +++ b/web/public/course-assets/s15_agent_teams/team-topology.ja.svg @@ -23,7 +23,7 @@ Lead Agent メインループ + spawn + inbox 処理 - check_inbox でチームメイトのメッセージ受信 + ランタイムがチームイベントを自動配信 diff --git a/web/public/course-assets/s15_agent_teams/team-topology.svg b/web/public/course-assets/s15_agent_teams/team-topology.svg index 9272e1b6..79937068 100644 --- a/web/public/course-assets/s15_agent_teams/team-topology.svg +++ b/web/public/course-assets/s15_agent_teams/team-topology.svg @@ -26,7 +26,7 @@ Lead Agent 主循环 + spawn + inbox 处理 - check_inbox 接收队友消息 + 运行时自动投递团队事件 diff --git a/web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.en.svg b/web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.en.svg similarity index 79% rename from web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.en.svg rename to web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.en.svg index 709676b6..2ba87548 100644 --- a/web/public/course-assets/s17_autonomous_agents/autonomous-agents-overview.en.svg +++ b/web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.en.svg @@ -19,15 +19,15 @@ - Autonomous Agents — Idle Loop + Auto-Claim + WORK/IDLE Lifecycle + Autonomous Agents — Idle Task Discovery + Atomic Claim - s16 Preserved + s15 Preserved - s17 New + s16 New - + turn @@ -49,28 +49,28 @@ - TOOL DISPATCH (all s16 preserved) - bash · read · write · task(4) · send · inbox + TOOL DISPATCH (all s15 preserved) + bash · read · write · task tools · send · protocols ★ request_shutdown · request_plan · review_plan - + - same inner LLM/tool loop inside WORK + idle teammates look for ready work - + - Teammate Lifecycle (s17 new: WORK → IDLE → SHUTDOWN) + s15 Lifecycle + s16 Task-Board Entry WORK Phase - inner loop: inbox → LLM → bash / read / write + runtime-delivered messages → LLM → tool calls stop_reason == tool_use → loop stop_reason != tool_use → IDLE - Max 10 rounds / interruptible by shutdown_request + send result, then enter IDLE @@ -82,11 +82,11 @@ - IDLE Phase (poll every 5s) - ├ Check inbox → has message → back to WORK + IDLE Phase + ├ Wait for runtime delivery → back to WORK ├ scan_unclaimed_tasks → claim → back to WORK - └ 60s timeout → SHUTDOWN ↓ - idle_poll() + claim_task() + └ No ready task → remain IDLE + wait_for_messages() + claim_next_task() @@ -94,16 +94,16 @@ - 60s timeout + shutdown_request - s16: MessageBus + protocols + request_shutdown + plan approval + s15: MessageBus + protocols + request_shutdown + plan approval - s17: idle_poll + scan_unclaimed_tasks + auto_claim + identity re-injection + s16: scan_unclaimed_tasks + claim_next_task + task_lock - Lead tools unchanged (14) · Teammate tools 5 → 8 (+3 task tools) · Teammates self-claim, Lead only creates tasks + Lead creates the task graph · teammates gain 3 task tools and atomically claim ready work diff --git a/s17_autonomous_agents/images/autonomous-agents-overview.ja.svg b/web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.ja.svg similarity index 77% rename from s17_autonomous_agents/images/autonomous-agents-overview.ja.svg rename to web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.ja.svg index 65d9a764..34123b86 100644 --- a/s17_autonomous_agents/images/autonomous-agents-overview.ja.svg +++ b/web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.ja.svg @@ -19,13 +19,13 @@ - Autonomous Agents — アイドルポーリング + 自動認領 + WORK/IDLE ライフサイクル + Autonomous Agents — アイドル時のタスク発見 + 原子的な認領 - s16 保持 + s15 保持 - s17 新規 + s16 新規 @@ -49,28 +49,28 @@ - TOOL DISPATCH(s16 全保持) - bash · read · write · task(4) · send · inbox + TOOL DISPATCH(s15 全保持) + bash · read · write · task tools · send · protocols ★ request_shutdown · request_plan · review_plan - + - 同じ内側 LLM/tool loop を WORK に入れる + 待機中に実行可能な仕事を探す - + - チームメイトライフサイクル(s17 新規:WORK → IDLE → SHUTDOWN) + s15 ライフサイクル + s16 タスクボード入口 WORK フェーズ - 内側ループ:inbox → LLM → bash / read / write + ランタイム配信メッセージ → LLM → ツール呼び出し stop_reason == tool_use → ループ stop_reason != tool_use → IDLE - 最大 10 ラウンド / shutdown_request で中断可能 + result を送り、IDLE に入る @@ -82,11 +82,11 @@ - IDLE フェーズ(5 秒ごとにポーリング) - ├ inbox チェック → メッセージあり → WORK に戻る + IDLE フェーズ + ├ ランタイム配信を待つ → WORK に戻る ├ scan_unclaimed_tasks → 認領 → WORK に戻る - └ 60 秒タイムアウト → SHUTDOWN ↓ - idle_poll() + claim_task() + └ 実行可能なタスクなし → IDLE を維持 + wait_for_messages() + claim_next_task() @@ -94,16 +94,16 @@ - 60 秒タイムアウト + shutdown_request - s16: MessageBus + protocols + request_shutdown + plan approval + s15: MessageBus + protocols + request_shutdown + plan approval - s17: idle_poll + scan_unclaimed_tasks + auto_claim + identity re-injection + s16: scan_unclaimed_tasks + claim_next_task + task_lock - Lead ツール不変(14) · チームメイトツール 5 → 8(+3 task tools) · チームメイトが自己認領、Lead はタスク作成のみ + Lead が依存グラフを作成 · チームメイトは 3 つのタスクツールで仕事を原子的に認領 diff --git a/s17_autonomous_agents/images/autonomous-agents-overview.svg b/web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.svg similarity index 79% rename from s17_autonomous_agents/images/autonomous-agents-overview.svg rename to web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.svg index df99675a..48d34b80 100644 --- a/s17_autonomous_agents/images/autonomous-agents-overview.svg +++ b/web/public/course-assets/s16_autonomous_agents/autonomous-agents-overview.svg @@ -19,15 +19,15 @@ - Autonomous Agents — 空闲循环 + 自动认领 + WORK/IDLE 生命周期 + Autonomous Agents — 空闲任务发现 + 原子认领 - s16 保留 + s15 保留 - s17 新增 + s16 新增 - + turn @@ -49,28 +49,28 @@ - TOOL DISPATCH (s16 全保留) - bash · read · write · task(4) · send · inbox + TOOL DISPATCH (s15 全保留) + bash · read · write · task tools · send · protocols ★ request_shutdown · request_plan · review_plan - + - 同一个内层 LLM/tool loop 放进 WORK + 空闲时从任务板寻找可执行工作 - + - 队友生命周期(s17 新增:WORK → IDLE → SHUTDOWN) + s15 生命周期 + s16 任务板入口 WORK 阶段 - 内层循环:inbox → LLM → bash / read / write + 消息自动进入上下文 → LLM → 工具调用 stop_reason == tool_use → loop stop_reason != tool_use → IDLE - 最多 10 轮 / 可被 shutdown_request 中断 + 完成后发送 result,再进入 IDLE @@ -82,11 +82,11 @@ - IDLE 阶段(每 5s 轮询) - ├ 检查 inbox → 有消息 → 回 WORK + IDLE 阶段 + ├ 等待运行时投递消息 → 回 WORK ├ scan_unclaimed_tasks → 认领 → 回 WORK - └ 60s 超时 → SHUTDOWN ↓ - idle_poll() + claim_task() + └ 没有就绪任务 → 保持 IDLE + wait_for_messages() + claim_next_task() @@ -94,16 +94,16 @@ - 60s 超时 + shutdown_request - s16: MessageBus + protocols + request_shutdown + plan approval + s15: MessageBus + protocols + request_shutdown + plan approval - s17: idle_poll + scan_unclaimed_tasks + auto_claim + identity re-injection + s16: scan_unclaimed_tasks + claim_next_task + task_lock - Lead 工具不变(14) · 队友工具 5 → 8(+3 task tools) · 队友自主认领,Lead 只创建任务 + Lead 创建任务依赖图 · 队友获得 3 个任务工具并原子认领就绪工作 diff --git a/s18_worktree_isolation/images/worktree-overview.en.svg b/web/public/course-assets/s17_worktree_isolation/worktree-overview.en.svg similarity index 91% rename from s18_worktree_isolation/images/worktree-overview.en.svg rename to web/public/course-assets/s17_worktree_isolation/worktree-overview.en.svg index 57c915f7..87ab6bee 100644 --- a/s18_worktree_isolation/images/worktree-overview.en.svg +++ b/web/public/course-assets/s17_worktree_isolation/worktree-overview.en.svg @@ -23,11 +23,11 @@ - s17 Preserved + s16 Preserved - s18 New + s17 New - + turn @@ -49,7 +49,7 @@ - TOOL DISPATCH (s17 + s18) + TOOL DISPATCH (s16 + s17) bash · read · write · task(4) · send · inbox request_shutdown · request_plan · review_plan ★ create_worktree · remove_worktree · keep_worktree @@ -57,9 +57,9 @@ - + - Worktree Isolation (s18 new: each task gets its own directory + branch) + Worktree Isolation (s17 new: each task gets its own directory + branch) @@ -92,12 +92,12 @@ Event log: .worktrees/events.jsonl → create / remove / keep - Cleanup: keep (preserve branch for review) / remove (delete + mark done) + Cleanup: keep (preserve for review) / remove (delete worktree) - s17: idle_poll + auto_claim + protocols + WORK/IDLE lifecycle + s16: scan_unclaimed_tasks + claim_next_task + task_lock - s18: create_worktree + bind_task + remove/keep + events.jsonl (Lead 14→17) + s17: create_worktree + bind_task + remove/keep + events.jsonl diff --git a/s18_worktree_isolation/images/worktree-overview.ja.svg b/web/public/course-assets/s17_worktree_isolation/worktree-overview.ja.svg similarity index 92% rename from s18_worktree_isolation/images/worktree-overview.ja.svg rename to web/public/course-assets/s17_worktree_isolation/worktree-overview.ja.svg index 2a26071d..e8b8d75c 100644 --- a/s18_worktree_isolation/images/worktree-overview.ja.svg +++ b/web/public/course-assets/s17_worktree_isolation/worktree-overview.ja.svg @@ -23,9 +23,9 @@ - s17 保持 + s16 保持 - s18 新規 + s17 新規 @@ -49,7 +49,7 @@ - TOOL DISPATCH(s17 + s18) + TOOL DISPATCH(s16 + s17) bash · read · write · task(4) · send · inbox request_shutdown · request_plan · review_plan ★ create_worktree · remove_worktree · keep_worktree @@ -59,7 +59,7 @@ - Worktree 隔離(s18 新規:各タスクに独立ディレクトリ + 独立ブランチ) + Worktree 隔離(s17 新規:各タスクに独立ディレクトリ + 独立ブランチ) @@ -92,12 +92,12 @@ イベントログ: .worktrees/events.jsonl → create / remove / keep - 片付け: keep(ブランチ保持 review)/ remove(削除+完了マーク) + 片付け: keep(review 用に保持)/ remove(worktree を削除) - s17: idle_poll + auto_claim + protocols + WORK/IDLE ライフサイクル + s16: scan_unclaimed_tasks + claim_next_task + task_lock - s18: create_worktree + bind_task + remove/keep + events.jsonl(Lead 14→17) + s17: create_worktree + bind_task + remove/keep + events.jsonl diff --git a/web/public/course-assets/s18_worktree_isolation/worktree-overview.svg b/web/public/course-assets/s17_worktree_isolation/worktree-overview.svg similarity index 91% rename from web/public/course-assets/s18_worktree_isolation/worktree-overview.svg rename to web/public/course-assets/s17_worktree_isolation/worktree-overview.svg index 2b88a75c..402eef74 100644 --- a/web/public/course-assets/s18_worktree_isolation/worktree-overview.svg +++ b/web/public/course-assets/s17_worktree_isolation/worktree-overview.svg @@ -23,11 +23,11 @@ - s17 保留 + s16 保留 - s18 新增 + s17 新增 - + turn @@ -49,7 +49,7 @@ - TOOL DISPATCH (s17 + s18) + TOOL DISPATCH (s16 + s17) bash · read · write · task(4) · send · inbox request_shutdown · request_plan · review_plan ★ create_worktree · remove_worktree · keep_worktree @@ -57,9 +57,9 @@ - + - Worktree 隔离(s18 新增:每个任务独立目录 + 独立分支) + Worktree 隔离(s17 新增:每个任务独立目录 + 独立分支) @@ -92,12 +92,12 @@ 事件日志: .worktrees/events.jsonl → create / remove / keep - 收尾: keep (保留分支 review) / remove (删除+标记完成) + 收尾: keep (保留分支 review) / remove (删除 worktree) - s17: idle_poll + auto_claim + protocols + WORK/IDLE lifecycle + s16: scan_unclaimed_tasks + claim_next_task + task_lock - s18: create_worktree + bind_task + remove/keep + events.jsonl (Lead 14→17) + s17: create_worktree + bind_task + remove/keep + events.jsonl diff --git a/web/public/course-assets/s19_mcp_plugin/mcp-architecture.en.svg b/web/public/course-assets/s18_mcp_plugin/mcp-architecture.en.svg similarity index 94% rename from web/public/course-assets/s19_mcp_plugin/mcp-architecture.en.svg rename to web/public/course-assets/s18_mcp_plugin/mcp-architecture.en.svg index 01d0c068..914da1c1 100644 --- a/web/public/course-assets/s19_mcp_plugin/mcp-architecture.en.svg +++ b/web/public/course-assets/s18_mcp_plugin/mcp-architecture.en.svg @@ -23,11 +23,11 @@ - s18 Preserved + s17 Preserved - s19 New + s18 New - + turn @@ -58,9 +58,9 @@ - + - MCP Architecture (s19 new: standard protocol + external tools dynamic integration) + MCP Architecture (s18 new: standard protocol + external tools dynamic integration) @@ -102,11 +102,11 @@ - s18: worktree + events + protocols (Lead 17) + s17: worktree + events + protocols (Lead 17) - s19: MCP + dynamic tools (Lead 18) + s18: MCP + dynamic tools (Lead 18) - Next: s20 combines tools, permissions, teams, worktrees, MCP, and more into one while True loop. + Next: s19 combines tools, permissions, teams, worktrees, MCP, and more into one while True loop. diff --git a/web/public/course-assets/s19_mcp_plugin/mcp-architecture.ja.svg b/web/public/course-assets/s18_mcp_plugin/mcp-architecture.ja.svg similarity index 96% rename from web/public/course-assets/s19_mcp_plugin/mcp-architecture.ja.svg rename to web/public/course-assets/s18_mcp_plugin/mcp-architecture.ja.svg index d2b5255c..86960beb 100644 --- a/web/public/course-assets/s19_mcp_plugin/mcp-architecture.ja.svg +++ b/web/public/course-assets/s18_mcp_plugin/mcp-architecture.ja.svg @@ -23,9 +23,9 @@ - s18 保持 + s17 保持 - s19 新規 + s18 新規 @@ -60,7 +60,7 @@ - MCP アーキテクチャ(s19 新規:標準プロトコル + 外部ツール動的統合) + MCP アーキテクチャ(s18 新規:標準プロトコル + 外部ツール動的統合) @@ -102,11 +102,11 @@ - s18: worktree + events + protocols(Lead 17) + s17: worktree + events + protocols(Lead 17) - s19: MCP + dynamic tools(Lead 18) + s18: MCP + dynamic tools(Lead 18) - 次の s20:tools、permissions、teams、worktree、MCP などを 1 つの while True ループに統合。 + 次の s19:tools、permissions、teams、worktree、MCP などを 1 つの while True ループに統合。 diff --git a/s19_mcp_plugin/images/mcp-architecture.svg b/web/public/course-assets/s18_mcp_plugin/mcp-architecture.svg similarity index 94% rename from s19_mcp_plugin/images/mcp-architecture.svg rename to web/public/course-assets/s18_mcp_plugin/mcp-architecture.svg index 6b365d6b..f09e0554 100644 --- a/s19_mcp_plugin/images/mcp-architecture.svg +++ b/web/public/course-assets/s18_mcp_plugin/mcp-architecture.svg @@ -23,11 +23,11 @@ - s18 保留 + s17 保留 - s19 新增 + s18 新增 - + turn @@ -58,9 +58,9 @@ - + - MCP 架构(s19 新增:标准协议 + 外部工具动态接入) + MCP 架构(s18 新增:标准协议 + 外部工具动态接入) @@ -102,11 +102,11 @@ - s18: worktree + events + protocols (Lead 17) + s17: worktree + events + protocols (Lead 17) - s19: MCP + dynamic tools (Lead 18) + s18: MCP + dynamic tools (Lead 18) - 下一章 s20:把工具、权限、团队、worktree、MCP 等机制合回同一个 while True 循环。 + 下一章 s19:把工具、权限、团队、worktree、MCP 等机制合回同一个 while True 循环。 diff --git a/web/public/course-assets/s20_comprehensive/system-architecture.en.svg b/web/public/course-assets/s19_comprehensive/system-architecture.en.svg similarity index 96% rename from web/public/course-assets/s20_comprehensive/system-architecture.en.svg rename to web/public/course-assets/s19_comprehensive/system-architecture.en.svg index 01ac3dfb..9958a972 100644 --- a/web/public/course-assets/s20_comprehensive/system-architecture.en.svg +++ b/web/public/course-assets/s19_comprehensive/system-architecture.en.svg @@ -20,7 +20,7 @@ - s20 Comprehensive Agent — Every Mechanism Around One Loop + s19 Comprehensive Agent — Every Mechanism Around One Loop Core Agent Loop @@ -69,16 +69,16 @@ Teams & Plugins s06 subagent - s15-s17 team protocols - s18 worktree isolation - s19 MCP tools + s15-s16 team protocols + s17 worktree isolation + s18 MCP tools TOOL POOL: 27 builtins + dynamic mcp__server__tool file/shell: bash · read · write · edit · glob single-agent: todo_write · task · load_skill · compact durable work: task tools · cron tools - team: spawn_teammate · send_message · check_inbox + team: spawn_teammate · send_message · typed protocols protocol: request_shutdown · request_plan · review_plan isolation/plugin: worktree tools · connect_mcp diff --git a/s20_comprehensive/images/system-architecture.ja.svg b/web/public/course-assets/s19_comprehensive/system-architecture.ja.svg similarity index 96% rename from s20_comprehensive/images/system-architecture.ja.svg rename to web/public/course-assets/s19_comprehensive/system-architecture.ja.svg index 0461be00..0e5076a4 100644 --- a/s20_comprehensive/images/system-architecture.ja.svg +++ b/web/public/course-assets/s19_comprehensive/system-architecture.ja.svg @@ -20,7 +20,7 @@ - s20 Comprehensive Agent — すべての仕組みを 1 つのループへ + s19 Comprehensive Agent — すべての仕組みを 1 つのループへ Core Agent Loop @@ -69,16 +69,16 @@ Teams / Plugins s06 subagent - s15-s17 team protocols - s18 worktree isolation - s19 MCP tools + s15-s16 team protocols + s17 worktree isolation + s18 MCP tools TOOL POOL: 27 builtins + dynamic mcp__server__tool file/shell: bash · read · write · edit · glob single-agent: todo_write · task · load_skill · compact durable work: task tools · cron tools - team: spawn_teammate · send_message · check_inbox + team: spawn_teammate · send_message · typed protocols protocol: request_shutdown · request_plan · review_plan isolation/plugin: worktree tools · connect_mcp diff --git a/s20_comprehensive/images/system-architecture.svg b/web/public/course-assets/s19_comprehensive/system-architecture.svg similarity index 96% rename from s20_comprehensive/images/system-architecture.svg rename to web/public/course-assets/s19_comprehensive/system-architecture.svg index 72e52f88..e37fb1e8 100644 --- a/s20_comprehensive/images/system-architecture.svg +++ b/web/public/course-assets/s19_comprehensive/system-architecture.svg @@ -21,7 +21,7 @@ - s20 Comprehensive Agent — 全部机制挂在同一个循环上 + s19 Comprehensive Agent — 全部机制挂在同一个循环上 @@ -87,9 +87,9 @@ 团队与插件 s06 subagent - s15-s17 team protocols - s18 worktree isolation - s19 MCP tools + s15-s16 team protocols + s17 worktree isolation + s18 MCP tools @@ -98,7 +98,7 @@ file/shell: bash · read · write · edit · glob single-agent: todo_write · task · load_skill · compact durable work: create/list/get/claim/complete_task · schedule/list/cancel_cron - team: spawn_teammate · send_message · check_inbox + team: spawn_teammate · send_message · typed protocols protocol: request_shutdown · request_plan · review_plan isolation/plugin: create/remove/keep_worktree · connect_mcp diff --git a/web/public/course-assets/s21_workflow_runtime/workflow-runtime-overview.svg b/web/public/course-assets/s20_workflow_runtime/workflow-runtime-overview.svg similarity index 100% rename from web/public/course-assets/s21_workflow_runtime/workflow-runtime-overview.svg rename to web/public/course-assets/s20_workflow_runtime/workflow-runtime-overview.svg diff --git a/web/public/course-assets/s22_goal_loop/goal-loop-overview.svg b/web/public/course-assets/s21_goal_loop/goal-loop-overview.svg similarity index 100% rename from web/public/course-assets/s22_goal_loop/goal-loop-overview.svg rename to web/public/course-assets/s21_goal_loop/goal-loop-overview.svg diff --git a/web/src/components/architecture/design-decisions.tsx b/web/src/components/architecture/design-decisions.tsx index 0a6523ac..74694b22 100644 --- a/web/src/components/architecture/design-decisions.tsx +++ b/web/src/components/architecture/design-decisions.tsx @@ -27,7 +27,6 @@ import s18Annotations from "@/data/annotations/s18.json"; import s19Annotations from "@/data/annotations/s19.json"; import s20Annotations from "@/data/annotations/s20.json"; import s21Annotations from "@/data/annotations/s21.json"; -import s22Annotations from "@/data/annotations/s22.json"; interface Decision { id: string; @@ -65,7 +64,6 @@ const ANNOTATIONS: Record = { s19: s19Annotations as AnnotationFile, s20: s20Annotations as AnnotationFile, s21: s21Annotations as AnnotationFile, - s22: s22Annotations as AnnotationFile, }; interface DesignDecisionsProps { diff --git a/web/src/components/simulator/agent-loop-simulator.tsx b/web/src/components/simulator/agent-loop-simulator.tsx index 6a9a3a91..5ea8a9b7 100644 --- a/web/src/components/simulator/agent-loop-simulator.tsx +++ b/web/src/components/simulator/agent-loop-simulator.tsx @@ -30,7 +30,6 @@ const scenarioModules: Record Promise<{ default: Scenario }>> = { s19: () => import("@/data/scenarios/s19.json") as Promise<{ default: Scenario }>, s20: () => import("@/data/scenarios/s20.json") as Promise<{ default: Scenario }>, s21: () => import("@/data/scenarios/s21.json") as Promise<{ default: Scenario }>, - s22: () => import("@/data/scenarios/s22.json") as Promise<{ default: Scenario }>, }; interface AgentLoopSimulatorProps { diff --git a/web/src/components/visualizations/index.tsx b/web/src/components/visualizations/index.tsx index 51b73805..6a2740f2 100644 --- a/web/src/components/visualizations/index.tsx +++ b/web/src/components/visualizations/index.tsx @@ -21,12 +21,11 @@ const visualizations: Record< s12: lazy(() => import("./s07-task-system")), s13: lazy(() => import("./s08-background-tasks")), s14: lazy(() => import("./s14-cron-scheduler")), - s15: lazy(() => import("./s09-agent-teams")), - s16: lazy(() => import("./s10-team-protocols")), - s17: lazy(() => import("./s11-autonomous-agents")), - s18: lazy(() => import("./s12-worktree-task-isolation")), - s19: lazy(() => import("./s19-mcp-tools")), - s20: lazy(() => import("./s20-comprehensive")), + s15: lazy(() => import("./s10-team-protocols")), + s16: lazy(() => import("./s11-autonomous-agents")), + s17: lazy(() => import("./s12-worktree-task-isolation")), + s18: lazy(() => import("./s19-mcp-tools")), + s19: lazy(() => import("./s20-comprehensive")), }; export function SessionVisualization({ version }: { version: string }) { diff --git a/web/src/data/annotations/s06.json b/web/src/data/annotations/s06.json index bbeb5553..486080db 100644 --- a/web/src/data/annotations/s06.json +++ b/web/src/data/annotations/s06.json @@ -33,7 +33,7 @@ "id": "no-recursive-task-tool", "title": "Subagents Cannot Spawn Subagents", "description": "The child tool set omits task, preventing recursive delegation from exploding. The lesson keeps isolation visible before adding richer team behavior later.", - "alternatives": "Allowing recursion is powerful, but much harder to bound and explain in a teaching runtime.", + "alternatives": "Allowing recursion is powerful, but much harder to bound and explain.", "zh": { "title": "子代理不能再创建子代理", "description": "子代理工具集中不包含 task,避免递归委派失控。课程先把隔离讲清楚,再在后续章节加入更复杂团队行为。" diff --git a/web/src/data/annotations/s13.json b/web/src/data/annotations/s13.json index 65adc0cb..99597f55 100644 --- a/web/src/data/annotations/s13.json +++ b/web/src/data/annotations/s13.json @@ -33,7 +33,7 @@ "id": "shared-result-store", "title": "A Small Shared Store Keeps Threads Observable", "description": "The implementation tracks background task state and results in explicit dictionaries. That keeps the code teachable while still exposing the hard parts of concurrency: ids, lifecycle state, and safe collection.", - "alternatives": "A full queue or job database would be more production-ready, but it would obscure the minimal moving parts needed to understand threaded agent work.", + "alternatives": "A full queue or job database adds durability, but it would obscure the minimal moving parts needed to understand threaded agent work.", "zh": { "title": "小型共享存储让线程可观察", "description": "实现用显式字典记录后台任务状态和结果。这样代码仍然易学,同时暴露并发中的关键问题:任务 id、生命周期状态和结果收集。" diff --git a/web/src/data/annotations/s15.json b/web/src/data/annotations/s15.json index bbca4e57..c3c23cbd 100644 --- a/web/src/data/annotations/s15.json +++ b/web/src/data/annotations/s15.json @@ -2,45 +2,59 @@ "version": "s15", "decisions": [ { - "id": "lead-agent-owns-coordination", - "title": "The Lead Owns Coordination", - "description": "The lead agent decides when to spawn teammates, what to send them, and how to interpret replies. Teammates can work independently, but the user-facing conversation stays anchored in one lead loop.", - "alternatives": "A peer-to-peer team would be more flexible, but much harder to explain because no single loop owns the answer.", + "id": "confirm-team-before-spawn", + "title": "The User Confirms the Team Before It Starts", + "description": "The Lead may notice that a request can be split, but it first proposes a small team with clear responsibilities. Teammates start only after the user confirms the extra agents.", + "alternatives": "Spawning immediately saves one turn, but hides the cost and coordination choice from the user.", "zh": { - "title": "由 Lead Agent 负责协调", - "description": "Lead agent 决定何时创建队友、发送什么任务、如何解释回复。队友可以独立工作,但面向用户的对话始终锚定在一个 lead 循环中。" + "title": "启动团队前先征得用户确认", + "description": "Lead 可以判断一个需求适合拆分,但要先提出职责清晰的小团队。只有用户确认后,运行时才启动额外的 Agent。" }, "ja": { - "title": "調整はリードエージェントが担う", - "description": "リードエージェントがチームメイトの生成、送信内容、返信の解釈を決めます。チームメイトは独立して作業できますが、ユーザー向けの会話は一つのリードループに固定されます。" + "title": "チームを起動する前にユーザーが確認する", + "description": "Lead は依頼を分割できると判断しても、まず役割が明確な小さなチームを提案する。追加 Agent はユーザーの確認後に起動する。" } }, { - "id": "file-backed-mailboxes", - "title": "Mailboxes Make Team Communication Inspectable", - "description": "MessageBus writes JSONL mailboxes so every handoff is visible on disk. This avoids magical shared memory and gives learners a concrete artifact for debugging team behavior.", - "alternatives": "In-memory channels are faster, but they hide the communication history and disappear when the process stops.", + "id": "runtime-owned-delivery", + "title": "Message Delivery Belongs to the Runtime", + "description": "MessageBus stores each handoff in JSONL, while the runtime watches the Lead mailbox and injects new team events into the next turn. The model does not need an inbox polling tool.", + "alternatives": "A model-visible check_inbox tool is easy to add, but wastes turns and can leave completed work unnoticed.", "zh": { - "title": "邮箱文件让团队通信可检查", - "description": "MessageBus 使用 JSONL 邮箱记录每次交接。这样避免了神秘的共享内存,也给学习者一个能直接调试团队行为的具体文件。" + "title": "消息投递由运行时负责", + "description": "MessageBus 把每次交接写入 JSONL,运行时监听 Lead 邮箱,并把新的团队事件送入下一轮上下文。模型不需要调用邮箱轮询工具。" }, "ja": { - "title": "メールボックスでチーム通信を検査可能にする", - "description": "MessageBus は JSONL メールボックスへ各ハンドオフを書き込みます。見えない共有メモリを避け、チーム動作をデバッグできる具体的な成果物を提供します。" + "title": "メッセージ配信はランタイムが担う", + "description": "MessageBus は各ハンドオフを JSONL に保存し、ランタイムが Lead のメールボックスを監視して新しい team event を次の turn に注入する。モデルに受信箱確認ツールは要らない。" } }, { - "id": "scoped-teammate-tools", - "title": "Teammates Use Scoped Tool Sets", - "description": "A teammate loop receives a narrower prompt and tool set than the lead. That keeps delegation focused and prevents a helper agent from accidentally taking over orchestration.", - "alternatives": "Giving every teammate the full tool pool is simpler, but it blurs roles and makes failures harder to attribute.", + "id": "typed-request-correlation", + "title": "Typed Requests Carry Correlation IDs", + "description": "Plan and shutdown requests use explicit message types and request ids. Replies can arrive in any order and still update the correct pending request.", + "alternatives": "Matching the latest free-form message works only until requests overlap.", "zh": { - "title": "队友使用受限工具集", - "description": "队友循环拿到比 lead 更窄的提示词和工具集。这样委派更聚焦,也避免 helper agent 意外接管整体协调。" + "title": "类型化请求携带关联 ID", + "description": "计划和关机请求使用明确的消息类型与 request id。即使回复顺序不同,运行时也能更新正确的 pending request。" }, "ja": { - "title": "チームメイトには範囲を絞ったツールセットを与える", - "description": "チームメイトループにはリードより狭いプロンプトとツールセットを渡します。委任を集中させ、補助エージェントが誤って全体調整を奪うことを防ぎます。" + "title": "型付きリクエストに対応 ID を持たせる", + "description": "プランと終了の要求は明示的な message type と request id を使う。返信順が変わっても、正しい pending request を更新できる。" + } + }, + { + "id": "plan-approval-is-a-gate", + "title": "Plan Approval Is an Execution Gate", + "description": "When the Lead requests a plan, mutating tools remain blocked until the matching plan is approved. Rejection requires a new submission, and an idle teammate remains available for later assignments until a typed shutdown completes.", + "alternatives": "Treating approval as a conversational suggestion cannot prevent an early write or shell command.", + "zh": { + "title": "计划审批是执行闸门", + "description": "Lead 请求计划后,修改类工具会保持阻塞,直到对应计划通过。被拒绝的计划必须重新提交;空闲队友会继续保留,直到类型化关机协议完成。" + }, + "ja": { + "title": "プラン承認を実行ゲートにする", + "description": "Lead がプランを要求すると、対応するプランが承認されるまで変更系ツールをブロックする。却下後は再提出が必要で、待機中のチームメイトは型付き終了プロトコルが完了するまで残る。" } } ] diff --git a/web/src/data/annotations/s16.json b/web/src/data/annotations/s16.json index cdc8acb3..054b78d0 100644 --- a/web/src/data/annotations/s16.json +++ b/web/src/data/annotations/s16.json @@ -2,45 +2,45 @@ "version": "s16", "decisions": [ { - "id": "typed-protocol-messages", - "title": "Typed Messages Replace Informal Chat", - "description": "Plan requests and shutdown requests are encoded as protocol messages with explicit kinds. The teammate can branch on message type instead of guessing intent from free-form text.", - "alternatives": "Plain natural-language messages are easier to write, but brittle once the team has multiple request types.", + "id": "idle-state-discovers-work", + "title": "Idle Teammates Look for Ready Work", + "description": "s15 already keeps teammates alive in IDLE. s16 gives that state one more input: after waiting for messages, a teammate scans the shared task board for pending, unowned, unblocked work.", + "alternatives": "The Lead could dispatch every assignment, but then an idle teammate cannot help with work that becomes ready later.", "zh": { - "title": "用类型化协议消息替代随意聊天", - "description": "计划请求和关闭请求会编码成带有明确 kind 的协议消息。队友可以根据消息类型分支处理,而不是从自由文本中猜意图。" + "title": "空闲队友主动寻找就绪任务", + "description": "s15 已经让队友在 IDLE 中保持存活。s16 为这个状态增加任务板入口:等待消息后,队友会扫描 pending、未分配且依赖已完成的任务。" }, "ja": { - "title": "非公式チャットを型付きプロトコルメッセージに置き換える", - "description": "計画要求とシャットダウン要求は明示的な kind を持つプロトコルメッセージとして表現されます。チームメイトは自由文から意図を推測せず、型で分岐できます。" + "title": "待機中のチームメイトが実行可能な仕事を探す", + "description": "s15 ですでにチームメイトは IDLE のまま残る。s16 はその状態にタスクボード入口を追加し、メッセージ待機後に pending、未所有、依存解決済みのタスクを探す。" } }, { - "id": "request-id-correlation", - "title": "Request IDs Close the Loop", - "description": "Each protocol request creates a pending record with a request_id. Responses must carry the same id, which lets the lead match replies even when multiple teammates are active.", - "alternatives": "Matching by latest message works in demos, but fails as soon as two requests overlap.", + "id": "atomic-claim", + "title": "Claiming Is Atomic", + "description": "The ownership check and task update run under one lock. When two teammates see the same ready task, only one can move it from pending to in_progress.", + "alternatives": "Scanning and writing without a shared lock can assign the same task twice.", "zh": { - "title": "Request ID 闭合协议循环", - "description": "每个协议请求都会创建带 request_id 的 pending 记录。响应必须携带同一个 id,因此即使多个队友同时工作,lead 也能匹配对应回复。" + "title": "任务认领必须原子化", + "description": "所有权检查与任务更新在同一把锁内完成。两个队友同时看到一个就绪任务时,只有一个能把它从 pending 推进到 in_progress。" }, "ja": { - "title": "request_id がループを閉じる", - "description": "各プロトコル要求は request_id 付きの pending レコードを作ります。応答も同じ id を持つため、複数のチームメイトが動いていてもリードは対応する返信を照合できます。" + "title": "タスク認領を原子的に行う", + "description": "所有権確認とタスク更新を同じ lock の中で行う。二つのチームメイトが同じ実行可能タスクを見ても、pending から in_progress へ進められるのは一方だけである。" } }, { - "id": "idle-protocol-handling", - "title": "Protocol Handling Runs During Idle Time", - "description": "Teammates can consume protocol messages while idle, so the lead can request plans or shutdowns without waiting for a separate user turn. This makes team control part of the runtime lifecycle.", - "alternatives": "Only checking protocols during active work would delay control messages and make shutdown unreliable.", + "id": "dependencies-filter-readiness", + "title": "Dependencies Define Readiness", + "description": "The scan returns a task only when every blockedBy dependency is completed. A teammate with nothing ready remains idle instead of starting work out of order.", + "alternatives": "Ignoring dependencies increases utilization, but produces work against unfinished inputs.", "zh": { - "title": "空闲期也处理协议", - "description": "队友在空闲状态也会消费协议消息,因此 lead 可以请求计划或关闭,而不必等待另一个用户回合。这让团队控制成为运行时生命周期的一部分。" + "title": "依赖关系决定任务是否就绪", + "description": "只有 blockedBy 中的依赖全部完成,扫描才会返回该任务。没有就绪任务的队友继续保持 IDLE,不会越过依赖提前开工。" }, "ja": { - "title": "アイドル中にもプロトコルを処理する", - "description": "チームメイトはアイドル時にもプロトコルメッセージを消費します。リードは別のユーザーターンを待たずに計画や終了を要求でき、チーム制御がランタイムのライフサイクルに組み込まれます。" + "title": "依存関係が実行可能性を決める", + "description": "blockedBy の依存がすべて完了したタスクだけを走査結果に含める。実行可能な仕事がなければ IDLE を維持し、順序を飛ばして開始しない。" } } ] diff --git a/web/src/data/annotations/s17.json b/web/src/data/annotations/s17.json index f1d2900c..31f1282f 100644 --- a/web/src/data/annotations/s17.json +++ b/web/src/data/annotations/s17.json @@ -2,45 +2,45 @@ "version": "s17", "decisions": [ { - "id": "idle-poll-loop", - "title": "Autonomy Starts from Idle Polling", - "description": "The agent becomes autonomous by doing useful checks while idle: scanning tasks, reading inbox messages, and deciding whether to claim work. No new magic planner is introduced.", - "alternatives": "A central scheduler could assign every task, but this lesson focuses on local autonomy inside each teammate loop.", + "id": "worktree-name-validation", + "title": "Worktree Names Are Validated Before Git Runs", + "description": "The tool validates names before creating branches or directories, so unsafe user input never reaches git or filesystem operations.", + "alternatives": "Passing names directly to git is shorter, but it turns a collaboration feature into an injection hazard.", "zh": { - "title": "自治从空闲轮询开始", - "description": "Agent 通过在空闲时做有用检查获得自治能力:扫描任务、读取 inbox、判断是否 claim 工作。这里没有引入新的神秘规划器。" + "title": "运行 Git 前先校验 Worktree 名称", + "description": "工具在创建分支或目录前先校验名称,不让不安全的用户输入进入 git 或文件系统操作。" }, "ja": { - "title": "自律性はアイドルポーリングから始まる", - "description": "エージェントはアイドル時にタスク走査、受信箱確認、作業の claim 判断を行うことで自律的になります。新しい魔法のプランナーは導入しません。" + "title": "git 実行前に worktree 名を検証する", + "description": "ブランチやディレクトリ作成前に名前を検証し、危険なユーザー入力が git やファイルシステム操作へ流れないようにします。" } }, { - "id": "claim-before-work", - "title": "Claim Before Work Prevents Collisions", - "description": "A teammate must claim a task before entering WORK state. Ownership checks make autonomous pickup safe when multiple agents poll the same task board.", - "alternatives": "Agents could simply pick any open task, but two agents might duplicate work or overwrite each other's result.", + "id": "task-bound-worktree", + "title": "The Task Record Owns the Worktree Binding", + "description": "A task stores its assigned worktree so future commands know where to run. The binding is explicit data, not a hidden convention based on naming or current working directory.", + "alternatives": "Deriving the worktree path from branch names is convenient, but brittle when tasks are renamed or moved.", "zh": { - "title": "先 Claim 再工作,避免冲突", - "description": "队友必须先 claim 任务,再进入 WORK 状态。多个 agent 轮询同一个任务板时,所有权检查让自治领取任务更安全。" + "title": "任务记录持有 Worktree 绑定关系", + "description": "任务会记录自己分配到的 worktree,因此后续命令知道应该在哪里运行。这个绑定是显式数据,而不是依赖命名或当前目录的隐藏约定。" }, "ja": { - "title": "作業前に claim して衝突を防ぐ", - "description": "チームメイトは WORK 状態へ入る前にタスクを claim します。複数のエージェントが同じタスクボードをポーリングしても、所有権チェックにより安全に取得できます。" + "title": "タスクレコードが worktree の紐付けを持つ", + "description": "タスクは割り当てられた worktree を保持し、後続コマンドは実行場所を把握できます。この紐付けは命名や現在ディレクトリに依存する暗黙の規約ではなく、明示的なデータです。" } }, { - "id": "identity-reinjection", - "title": "Advanced Teaching Workaround: Identity Re-injection", - "description": "The simplified lesson re-injects identity after its compaction heuristic. This is optional teaching scaffolding; production compaction should preserve stable system instructions instead.", - "alternatives": "Keep identity in stable system instructions and preserve that boundary through compaction.", + "id": "lifecycle-event-stream", + "title": "Lifecycle Events Stay Separate from Tool Results", + "description": "Creation, status, keep, and removal events are emitted to a side-channel log. That makes worktree state observable without overloading the conversational transcript.", + "alternatives": "Only returning tool results is simpler, but later debugging needs a durable audit trail of worktree lifecycle changes.", "zh": { - "title": "进阶教学补丁:身份重注入", - "description": "简化课程在压缩启发式触发后重新注入身份。这是选学脚手架;生产实现应在压缩时保留稳定的 system 指令。" + "title": "生命周期事件与工具结果分离", + "description": "创建、状态、保留和移除事件会写入旁路日志。这样 worktree 状态可观察,同时不会把对话 transcript 塞满运行时事件。" }, "ja": { - "title": "発展用の教育補助:アイデンティティ再注入", - "description": "簡略化した教材は圧縮ヒューリスティック後にアイデンティティを再注入します。これは任意の足場であり、本番実装では圧縮を越えて安定した system 指示を保持すべきです。" + "title": "ライフサイクルイベントをツール結果から分離する", + "description": "作成、状態、保持、削除のイベントはサイドチャネルログへ出力します。会話 transcript をランタイムイベントで埋めずに worktree 状態を観測できます。" } } ] diff --git a/web/src/data/annotations/s18.json b/web/src/data/annotations/s18.json index d3c83129..7023a2da 100644 --- a/web/src/data/annotations/s18.json +++ b/web/src/data/annotations/s18.json @@ -2,45 +2,45 @@ "version": "s18", "decisions": [ { - "id": "worktree-name-validation", - "title": "Worktree Names Are Validated Before Git Runs", - "description": "The tool validates names before creating branches or directories. That keeps a teaching implementation from normalizing unsafe user input into shell or filesystem operations.", - "alternatives": "Passing names directly to git is shorter, but it turns a collaboration feature into an injection hazard.", + "id": "normalized-mcp-namespace", + "title": "MCP Tools Use a Normalized Namespace", + "description": "Discovered tools are exposed as mcp__server__tool. The prefix makes the source explicit and avoids collisions with built-in tools or tools from another server.", + "alternatives": "Using the raw tool name is shorter, but search from two servers could overwrite each other.", "zh": { - "title": "运行 Git 前先校验 Worktree 名称", - "description": "工具在创建分支或目录前先校验名称。这样教学实现不会把不安全的用户输入直接传入 shell 或文件系统操作。" + "title": "MCP 工具使用规范化命名空间", + "description": "发现到的工具会暴露为 mcp__server__tool。前缀让工具来源明确,也避免和内置工具或其他服务器工具冲突。" }, "ja": { - "title": "git 実行前に worktree 名を検証する", - "description": "ブランチやディレクトリ作成前に名前を検証します。学習用実装が危険なユーザー入力を shell やファイルシステム操作へ流し込むことを防ぎます。" + "title": "MCP ツールは正規化された名前空間を使う", + "description": "発見されたツールは mcp__server__tool として公開されます。接頭辞により出所が明確になり、組み込みツールや別サーバーのツールとの衝突を避けます。" } }, { - "id": "task-bound-worktree", - "title": "The Task Record Owns the Worktree Binding", - "description": "A task stores its assigned worktree so future commands know where to run. The binding is explicit data, not a hidden convention based on naming or current working directory.", - "alternatives": "Deriving the worktree path from branch names is convenient, but brittle when tasks are renamed or moved.", + "id": "dynamic-tool-pool", + "title": "Tool Discovery Updates the Active Tool Pool", + "description": "After connecting to a server, the runtime assembles a new tool pool for the next LLM call. The model can only use MCP tools after discovery has made them visible.", + "alternatives": "Preloading every possible MCP tool would create a huge prompt and expose capabilities the user did not request.", "zh": { - "title": "任务记录持有 Worktree 绑定关系", - "description": "任务会记录自己分配到的 worktree,因此后续命令知道应该在哪里运行。这个绑定是显式数据,而不是依赖命名或当前目录的隐藏约定。" + "title": "工具发现会更新活动工具池", + "description": "连接服务器后,运行时会为下一次 LLM 调用组装新的工具池。模型只有在发现阶段让 MCP 工具可见之后,才能调用它们。" }, "ja": { - "title": "タスクレコードが worktree の紐付けを持つ", - "description": "タスクは割り当てられた worktree を保持し、後続コマンドは実行場所を把握できます。この紐付けは命名や現在ディレクトリに依存する暗黙の規約ではなく、明示的なデータです。" + "title": "ツール発見がアクティブなツールプールを更新する", + "description": "サーバー接続後、ランタイムは次の LLM 呼び出し用に新しいツールプールを組み立てます。MCP ツールは発見で可視化された後にのみモデルが利用できます。" } }, { - "id": "lifecycle-event-stream", - "title": "Lifecycle Events Stay Separate from Tool Results", - "description": "Creation, status, keep, and removal events are emitted to a side-channel log. That makes worktree state observable without overloading the conversational transcript.", - "alternatives": "Only returning tool results is simpler, but later debugging needs a durable audit trail of worktree lifecycle changes.", + "id": "external-results-append-like-tools", + "title": "External Results Reuse the Tool Result Path", + "description": "MCP responses are appended to the conversation like ordinary tool results. This keeps the agent loop unchanged while still letting external systems participate.", + "alternatives": "A separate external-response channel would make MCP feel special and require extra loop logic.", "zh": { - "title": "生命周期事件与工具结果分离", - "description": "创建、状态、保留和移除事件会写入旁路日志。这样 worktree 状态可观察,同时不会把对话 transcript 塞满运行时事件。" + "title": "外部结果复用 Tool Result 路径", + "description": "MCP 响应会像普通 tool result 一样追加到对话中。这样 agent 循环无需改变,同时外部系统仍然可以参与。" }, "ja": { - "title": "ライフサイクルイベントをツール結果から分離する", - "description": "作成、状態、保持、削除のイベントはサイドチャネルログへ出力します。会話 transcript をランタイムイベントで埋めずに worktree 状態を観測できます。" + "title": "外部結果は tool result 経路を再利用する", + "description": "MCP の応答は通常の tool result と同じように会話へ追加されます。エージェントループを変えずに外部システムを参加させられます。" } } ] diff --git a/web/src/data/annotations/s19.json b/web/src/data/annotations/s19.json index eba7975a..5f2c49bf 100644 --- a/web/src/data/annotations/s19.json +++ b/web/src/data/annotations/s19.json @@ -2,45 +2,45 @@ "version": "s19", "decisions": [ { - "id": "normalized-mcp-namespace", - "title": "MCP Tools Use a Normalized Namespace", - "description": "Discovered tools are exposed as mcp__server__tool. The prefix makes the source explicit and avoids collisions with built-in tools or tools from another server.", - "alternatives": "Using the raw tool name is shorter, but search from two servers could overwrite each other.", + "id": "composition-over-new-loop", + "title": "The Final Agent Composes Previous Layers", + "description": "The comprehensive agent does not replace the loop with a new architecture. It composes memory, tasks, skills, background work, teams, worktrees, and MCP around the same core model-tool-result cycle.", + "alternatives": "A new orchestration framework would look more impressive, but it would hide the continuity across the course.", "zh": { - "title": "MCP 工具使用规范化命名空间", - "description": "发现到的工具会暴露为 mcp__server__tool。前缀让工具来源明确,也避免和内置工具或其他服务器工具冲突。" + "title": "最终 Agent 是组合既有层,而不是换掉循环", + "description": "综合 Agent 没有用新架构替换循环,而是把 memory、task、skill、后台任务、团队、worktree、MCP 组合到同一个模型-工具-结果循环周围。" }, "ja": { - "title": "MCP ツールは正規化された名前空間を使う", - "description": "発見されたツールは mcp__server__tool として公開されます。接頭辞により出所が明確になり、組み込みツールや別サーバーのツールとの衝突を避けます。" + "title": "最終エージェントは既存レイヤーの合成", + "description": "総合エージェントはループを新しい構造で置き換えません。memory、task、skill、バックグラウンド処理、チーム、worktree、MCP を同じ model-tool-result サイクルの周囲に合成します。" } }, { - "id": "dynamic-tool-pool", - "title": "Tool Discovery Updates the Active Tool Pool", - "description": "After connecting to a server, the runtime assembles a new tool pool for the next LLM call. The model can only use MCP tools after discovery has made them visible.", - "alternatives": "Preloading every possible MCP tool would create a huge prompt and expose capabilities the user did not request.", + "id": "single-source-of-runtime-truth", + "title": "Runtime State Has Named Sources", + "description": "Context assembly pulls from named sources such as memory, task graph, skills, tool registry, and policy. This keeps a large agent debuggable because each piece of prompt context has an owner.", + "alternatives": "Dumping everything into one prompt string is shorter, but it becomes impossible to tell which subsystem caused a bad decision.", "zh": { - "title": "工具发现会更新活动工具池", - "description": "连接服务器后,运行时会为下一次 LLM 调用组装新的工具池。模型只有在发现阶段让 MCP 工具可见之后,才能调用它们。" + "title": "运行时状态来自具名来源", + "description": "上下文组装从 memory、task graph、skills、tool registry、policy 等具名来源读取。大型 agent 因此仍可调试,因为每块 prompt context 都有清晰归属。" }, "ja": { - "title": "ツール発見がアクティブなツールプールを更新する", - "description": "サーバー接続後、ランタイムは次の LLM 呼び出し用に新しいツールプールを組み立てます。MCP ツールは発見で可視化された後にのみモデルが利用できます。" + "title": "ランタイム状態には名前付きの出所がある", + "description": "コンテキスト組み立ては memory、task graph、skills、tool registry、policy などの名前付きソースから取得します。各 prompt context に所有者があるため、大きなエージェントでもデバッグ可能です。" } }, { - "id": "external-results-append-like-tools", - "title": "External Results Reuse the Tool Result Path", - "description": "MCP responses are appended to the conversation like ordinary tool results. This keeps the agent loop unchanged while still letting external systems participate.", - "alternatives": "A separate external-response channel would make MCP feel special and require extra loop logic.", + "id": "recovery-is-first-class", + "title": "Recovery Is Part of the Main Flow", + "description": "Compaction, error recovery, and asynchronous result collection are normal loop behavior. The harness handles recovery and resumption through named paths instead of scattered exception branches.", + "alternatives": "Leaving recovery at the edges makes it harder to see which state is safe to resume.", "zh": { - "title": "外部结果复用 Tool Result 路径", - "description": "MCP 响应会像普通 tool result 一样追加到对话中。这样 agent 循环无需改变,同时外部系统仍然可以参与。" + "title": "恢复能力是一等流程", + "description": "压缩、错误恢复和异步结果收集都属于正常循环。Harness 通过明确的路径处理恢复与续跑,而不是把逻辑散落在异常分支中。" }, "ja": { - "title": "外部結果は tool result 経路を再利用する", - "description": "MCP の応答は通常の tool result と同じように会話へ追加されます。エージェントループを変えずに外部システムを参加させられます。" + "title": "リカバリは主要フローの一部", + "description": "圧縮、エラー回復、非同期結果収集を通常のループ動作として扱います。Harness は回復と再開を名前付きの経路にまとめ、例外分岐へ散らしません。" } } ] diff --git a/web/src/data/annotations/s20.json b/web/src/data/annotations/s20.json index 9bd319f2..5df979a1 100644 --- a/web/src/data/annotations/s20.json +++ b/web/src/data/annotations/s20.json @@ -2,45 +2,45 @@ "version": "s20", "decisions": [ { - "id": "composition-over-new-loop", - "title": "The Final Agent Composes Previous Layers", - "description": "The comprehensive agent does not replace the loop with a new architecture. It composes memory, tasks, skills, background work, teams, worktrees, and MCP around the same core model-tool-result cycle.", - "alternatives": "A new orchestration framework would look more impressive, but it would hide the continuity across the course.", + "id": "script-owns-fixed-orchestration", + "title": "Code Owns Fixed Orchestration", + "description": "When the stages and aggregation rules are known in advance, a workflow script makes the process parallel, reproducible, and inspectable without changing the main agent loop.", + "alternatives": "Letting the model choose every next step is more flexible, but slower and harder to resume for a fixed procedure.", "zh": { - "title": "最终 Agent 是组合既有层,而不是换掉循环", - "description": "综合 Agent 没有用新架构替换循环,而是把 memory、task、skill、后台任务、团队、worktree、MCP 组合到同一个模型-工具-结果循环周围。" + "title": "固定编排由代码负责", + "description": "当阶段与汇总规则事先确定时,workflow 脚本能让流程并行、可复现、可检查,同时不修改主 Agent 循环。" }, "ja": { - "title": "最終エージェントは既存レイヤーの合成", - "description": "総合エージェントはループを新しい構造で置き換えません。memory、task、skill、バックグラウンド処理、チーム、worktree、MCP を同じ model-tool-result サイクルの周囲に合成します。" + "title": "固定された編成はコードが担う", + "description": "段階と集約ルールが事前に決まっているなら、workflow script は main Agent loop を変えずに処理を並列化し、再現可能で検査可能にする。" } }, { - "id": "single-source-of-runtime-truth", - "title": "Runtime State Has Named Sources", - "description": "Context assembly pulls from named sources such as memory, task graph, skills, tool registry, and policy. This keeps a large agent debuggable because each piece of prompt context has an owner.", - "alternatives": "Dumping everything into one prompt string is shorter, but it becomes impossible to tell which subsystem caused a bad decision.", + "id": "semantic-journal-keys", + "title": "Semantic Keys Make Resume Independent of Completion Order", + "description": "Journal entries use stable call content rather than a shared completion counter. Concurrent calls can finish in any order and still map to the correct cached result.", + "alternatives": "Indexing by completion order is simpler, but replays the wrong result as soon as concurrent timing changes.", "zh": { - "title": "运行时状态来自具名来源", - "description": "上下文组装从 memory、task graph、skills、tool registry、policy 等具名来源读取。大型 agent 因此仍可调试,因为每块 prompt context 都有清晰归属。" + "title": "语义键让恢复不依赖完成顺序", + "description": "Journal 用稳定的调用内容作为 key,而不是共享完成计数器。并发调用无论以什么顺序结束,都能命中正确缓存。" }, "ja": { - "title": "ランタイム状態には名前付きの出所がある", - "description": "コンテキスト組み立ては memory、task graph、skills、tool registry、policy などの名前付きソースから取得します。各 prompt context に所有者があるため、大きなエージェントでもデバッグ可能です。" + "title": "意味キーで完了順序に依存せず再開する", + "description": "Journal は共有完了カウンタではなく安定した call 内容を key にする。並行 call の終了順が変わっても正しい cache result に対応できる。" } }, { - "id": "recovery-is-first-class", - "title": "Recovery Is Part of the Main Flow", - "description": "Compaction, error recovery, and asynchronous result collection are treated as normal loop behavior. The final lesson shows that production agents spend as much effort recovering and resuming as they do calling tools.", - "alternatives": "Recovery could be left as error handling around the edges, but then the architecture would understate what real long-running agents need.", + "id": "fail-the-workflow", + "title": "Orchestration Failures Propagate", + "description": "A failed stage, invalid structured result, corrupt journal, or exceeded run-wide limit fails the workflow instead of silently dropping an item and reporting success.", + "alternatives": "Best-effort collection can be useful for optional work, but it must be explicit rather than the default.", "zh": { - "title": "恢复能力是一等流程", - "description": "压缩、错误恢复、异步结果收集都被视为正常循环行为。最终课展示了生产级 agent 在恢复和续跑上投入的工程量,并不低于调用工具本身。" + "title": "编排故障必须向上传播", + "description": "阶段失败、结构化结果不合法、journal 损坏或超过全局限制时,workflow 直接失败,而不是静默丢项后仍报告成功。" }, "ja": { - "title": "リカバリは主要フローの一部", - "description": "圧縮、エラー回復、非同期結果収集を通常のループ動作として扱います。実運用の長時間エージェントでは、ツール呼び出しと同じくらい回復と再開が重要であることを示します。" + "title": "編成の失敗は上位へ伝播させる", + "description": "stage failure、無効な structured result、破損 journal、run-wide limit 超過は workflow を失敗させ、項目を黙って落として成功扱いしない。" } } ] diff --git a/web/src/data/annotations/s21.json b/web/src/data/annotations/s21.json index 334cc93b..e9747f56 100644 --- a/web/src/data/annotations/s21.json +++ b/web/src/data/annotations/s21.json @@ -2,45 +2,45 @@ "version": "s21", "decisions": [ { - "id": "script-owns-fixed-orchestration", - "title": "Code Owns Fixed Orchestration", - "description": "When the stages and aggregation rules are known in advance, a workflow script makes the process parallel, reproducible, and inspectable without changing the main agent loop.", - "alternatives": "Letting the model choose every next step is more flexible, but slower and harder to resume for a fixed procedure.", + "id": "host-owns-completion-gate", + "title": "The Host Owns the Completion Gate", + "description": "The working model may request to stop, but the harness evaluates the active goal before returning. Completion is a program decision at the turn boundary.", + "alternatives": "Asking the working model whether it is finished is simpler, but lets the same actor make and verify its own claim.", "zh": { - "title": "固定编排由代码负责", - "description": "当阶段与汇总规则事先确定时,workflow 脚本能让流程并行、可复现、可检查,同时不修改主 Agent 循环。" + "title": "完成闸门由宿主持有", + "description": "工作模型可以请求停止,但 harness 会在 return 前评估 active goal。是否完成是轮次边界上的程序决策。" }, "ja": { - "title": "固定された編成はコードが担う", - "description": "段階と集約ルールが事前に決まっているなら、workflow script は main Agent loop を変えずに処理を並列化し、再現可能で検査可能にする。" + "title": "完了ゲートはホストが所有する", + "description": "作業モデルは停止を要求できるが、harness は return 前に active goal を評価する。完了は turn 境界でのプログラム判断である。" } }, { - "id": "semantic-journal-keys", - "title": "Semantic Keys Make Resume Independent of Completion Order", - "description": "Journal entries use stable call content rather than a shared completion counter. Concurrent calls can finish in any order and still map to the correct cached result.", - "alternatives": "Indexing by completion order is simpler, but replays the wrong result as soon as concurrent timing changes.", + "id": "host-assigned-evidence-origins", + "title": "Evidence Trust Comes from the Ingress Path", + "description": "Ordinary submit calls cannot attach trusted labels. Only an allowlisted host-event channel can deliver task or monitor evidence, so user and model prose cannot certify itself.", + "alternatives": "Trusting text content or caller-supplied labels makes the evidence boundary forgeable.", "zh": { - "title": "语义键让恢复不依赖完成顺序", - "description": "Journal 用稳定的调用内容作为 key,而不是共享完成计数器。并发调用无论以什么顺序结束,都能命中正确缓存。" + "title": "证据信任来自入口路径", + "description": "普通 submit 不能附加可信标签;只有白名单宿主事件通道能送入 task 或 monitor 证据,因此用户与模型文本不能自证完成。" }, "ja": { - "title": "意味キーで完了順序に依存せず再開する", - "description": "Journal は共有完了カウンタではなく安定した call 内容を key にする。並行 call の終了順が変わっても正しい cache result に対応できる。" + "title": "証拠の信頼は入力経路から得る", + "description": "通常の submit は trusted label を付けられず、allowlist 済み host event channel だけが task や monitor evidence を届ける。ユーザーやモデルの文章は自己証明できない。" } }, { - "id": "fail-the-workflow", - "title": "Orchestration Failures Propagate", - "description": "A failed stage, invalid structured result, corrupt journal, or exceeded run-wide limit fails the workflow instead of silently dropping an item and reporting success.", - "alternatives": "Best-effort collection can be useful for optional work, but it must be explicit rather than the default.", + "id": "bounded-continuation", + "title": "Every Automatic Continuation Needs a Budget", + "description": "An unmet goal queues another turn only while budget remains. Exhaustion marks the goal blocked and releases the gate instead of creating an infinite loop.", + "alternatives": "An unbounded goal is persistent, but an impossible condition can consume resources forever.", "zh": { - "title": "编排故障必须向上传播", - "description": "阶段失败、结构化结果不合法、journal 损坏或超过全局限制时,workflow 直接失败,而不是静默丢项后仍报告成功。" + "title": "每次自动续轮都必须有预算", + "description": "目标未满足时只在预算剩余时继续;耗尽后将目标标记为 blocked 并释放闸门,避免无限循环。" }, "ja": { - "title": "編成の失敗は上位へ伝播させる", - "description": "stage failure、無効な structured result、破損 journal、run-wide limit 超過は workflow を失敗させ、項目を黙って落として成功扱いしない。" + "title": "自動継続には必ず予算を置く", + "description": "goal 未達時は予算が残る間だけ次の turn を追加する。使い切れば blocked にして gate を解放し、無限 loop を防ぐ。" } } ] diff --git a/web/src/data/annotations/s22.json b/web/src/data/annotations/s22.json deleted file mode 100644 index 12db5473..00000000 --- a/web/src/data/annotations/s22.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "version": "s22", - "decisions": [ - { - "id": "host-owns-completion-gate", - "title": "The Host Owns the Completion Gate", - "description": "The working model may request to stop, but the harness evaluates the active goal before returning. Completion is a program decision at the turn boundary.", - "alternatives": "Asking the working model whether it is finished is simpler, but lets the same actor make and verify its own claim.", - "zh": { - "title": "完成闸门由宿主持有", - "description": "工作模型可以请求停止,但 harness 会在 return 前评估 active goal。是否完成是轮次边界上的程序决策。" - }, - "ja": { - "title": "完了ゲートはホストが所有する", - "description": "作業モデルは停止を要求できるが、harness は return 前に active goal を評価する。完了は turn 境界でのプログラム判断である。" - } - }, - { - "id": "host-assigned-evidence-origins", - "title": "Evidence Trust Comes from the Ingress Path", - "description": "Ordinary submit calls cannot attach trusted labels. Only an allowlisted host-event channel can deliver task or monitor evidence, so user and model prose cannot certify itself.", - "alternatives": "Trusting text content or caller-supplied labels makes the evidence boundary forgeable.", - "zh": { - "title": "证据信任来自入口路径", - "description": "普通 submit 不能附加可信标签;只有白名单宿主事件通道能送入 task 或 monitor 证据,因此用户与模型文本不能自证完成。" - }, - "ja": { - "title": "証拠の信頼は入力経路から得る", - "description": "通常の submit は trusted label を付けられず、allowlist 済み host event channel だけが task や monitor evidence を届ける。ユーザーやモデルの文章は自己証明できない。" - } - }, - { - "id": "bounded-continuation", - "title": "Every Automatic Continuation Needs a Budget", - "description": "An unmet goal queues another turn only while budget remains. Exhaustion marks the goal blocked and releases the gate instead of creating an infinite loop.", - "alternatives": "An unbounded goal is persistent, but an impossible condition can consume resources forever.", - "zh": { - "title": "每次自动续轮都必须有预算", - "description": "目标未满足时只在预算剩余时继续;耗尽后将目标标记为 blocked 并释放闸门,避免无限循环。" - }, - "ja": { - "title": "自動継続には必ず予算を置く", - "description": "goal 未達時は予算が残る間だけ次の turn を追加する。使い切れば blocked にして gate を解放し、無限 loop を防ぐ。" - } - } - ] -} diff --git a/web/src/data/execution-flows.ts b/web/src/data/execution-flows.ts index f879651a..a7ae158f 100644 --- a/web/src/data/execution-flows.ts +++ b/web/src/data/execution-flows.ts @@ -368,74 +368,45 @@ export const EXECUTION_FLOWS: Record = { }, s15: { nodes: [ - { id: "start", label: "User Input", type: "start", x: COL_CENTER, y: 30 }, - { id: "lead", label: "Lead LLM", type: "process", x: COL_CENTER, y: 110 }, - { id: "team_tool", label: "team tool?", type: "decision", x: COL_CENTER, y: 200 }, - { id: "spawn", label: "Spawn Teammate", type: "subprocess", x: COL_LEFT, y: 300 }, - { id: "send", label: "Send Message", type: "subprocess", x: COL_CENTER, y: 300 }, - { id: "bus", label: "MessageBus\n.mailboxes", type: "process", x: COL_CENTER, y: 400 }, - { id: "teammate", label: "Teammate Loop", type: "process", x: COL_RIGHT, y: 500 }, - { id: "tools", label: "Scoped Tools", type: "subprocess", x: COL_RIGHT, y: 590 }, - { id: "inbox", label: "Lead Inbox", type: "process", x: COL_CENTER, y: 700 }, - { id: "append", label: "Append Result", type: "process", x: COL_LEFT, y: 700 }, - { id: "end", label: "Output", type: "end", x: COL_RIGHT, y: 300 }, + { id: "start", label: "User Requirement", type: "start", x: COL_CENTER, y: 30 }, + { id: "lead", label: "Lead Proposes\nSmall Team", type: "process", x: COL_CENTER, y: 110 }, + { id: "team_tool", label: "User Confirms?", type: "decision", x: COL_CENTER, y: 200 }, + { id: "spawn", label: "Spawn Persistent\nTeammates", type: "subprocess", x: COL_LEFT, y: 300 }, + { id: "send", label: "Assignment /\nTyped Request", type: "subprocess", x: COL_LEFT, y: 400 }, + { id: "bus", label: "MessageBus\nJSONL Mailboxes", type: "process", x: COL_CENTER, y: 500 }, + { id: "teammate", label: "Teammate\nWORK / IDLE", type: "process", x: COL_RIGHT, y: 400 }, + { id: "tools", label: "Scoped Tools /\nPlan Gate", type: "subprocess", x: COL_RIGHT, y: 500 }, + { id: "inbox", label: "Runtime Delivery", type: "process", x: COL_CENTER, y: 600 }, + { id: "append", label: "Append Team Events", type: "process", x: COL_LEFT, y: 690 }, + { id: "end", label: "Continue Alone", type: "end", x: COL_RIGHT, y: 300 }, ], edges: [ { from: "start", to: "lead" }, { from: "lead", to: "team_tool" }, - { from: "team_tool", to: "spawn", label: "spawn" }, - { from: "team_tool", to: "send", label: "send" }, + { from: "team_tool", to: "spawn", label: "yes" }, { from: "team_tool", to: "end", label: "no" }, - { from: "spawn", to: "bus", label: "register" }, + { from: "spawn", to: "send" }, { from: "send", to: "bus" }, { from: "bus", to: "teammate" }, { from: "teammate", to: "tools" }, - { from: "tools", to: "bus", label: "reply" }, - { from: "bus", to: "inbox" }, + { from: "tools", to: "bus", label: "result / protocol reply" }, + { from: "bus", to: "inbox", label: "wake Lead" }, { from: "inbox", to: "append" }, { from: "append", to: "lead" }, ], }, s16: { nodes: [ - { id: "start", label: "User Input", type: "start", x: COL_CENTER, y: 30 }, - { id: "lead", label: "Lead LLM", type: "process", x: COL_CENTER, y: 110 }, - { id: "protocol", label: "protocol?", type: "decision", x: COL_CENTER, y: 200 }, - { id: "request", label: "request_plan /\nrequest_shutdown", type: "subprocess", x: COL_LEFT, y: 300 }, - { id: "pending", label: "Pending Requests\nrequest_id", type: "process", x: COL_LEFT, y: 390 }, - { id: "dispatch", label: "Dispatch Message", type: "process", x: COL_CENTER, y: 470 }, - { id: "teammate", label: "Teammate Handler", type: "process", x: COL_RIGHT, y: 470 }, - { id: "response", label: "submit_plan /\nack shutdown", type: "subprocess", x: COL_RIGHT, y: 560 }, - { id: "match", label: "match_response?", type: "decision", x: COL_CENTER, y: 640 }, - { id: "append", label: "Append Protocol\nResult", type: "process", x: COL_CENTER, y: 730 }, - { id: "end", label: "Output", type: "end", x: COL_RIGHT, y: 300 }, - ], - edges: [ - { from: "start", to: "lead" }, - { from: "lead", to: "protocol" }, - { from: "protocol", to: "request", label: "yes" }, - { from: "protocol", to: "end", label: "no" }, - { from: "request", to: "pending" }, - { from: "pending", to: "dispatch" }, - { from: "dispatch", to: "teammate" }, - { from: "teammate", to: "response" }, - { from: "response", to: "match" }, - { from: "match", to: "append", label: "matched" }, - { from: "append", to: "lead" }, - ], - }, - s17: { - nodes: [ - { id: "start", label: "System Tick", type: "start", x: COL_CENTER, y: 30 }, - { id: "idle", label: "Idle Poll", type: "process", x: COL_CENTER, y: 110 }, - { id: "scan", label: "Scan Tasks", type: "subprocess", x: COL_CENTER, y: 190 }, - { id: "claimable", label: "claimable?", type: "decision", x: COL_CENTER, y: 280 }, - { id: "claim", label: "claim_task\n(owner check)", type: "subprocess", x: COL_LEFT, y: 380 }, + { id: "start", label: "Teammate IDLE", type: "start", x: COL_CENTER, y: 30 }, + { id: "idle", label: "Wait for Messages", type: "process", x: COL_CENTER, y: 110 }, + { id: "scan", label: "Scan Ready Tasks", type: "subprocess", x: COL_CENTER, y: 190 }, + { id: "claimable", label: "Ready Task?", type: "decision", x: COL_CENTER, y: 280 }, + { id: "claim", label: "Atomic Claim\ntask_lock", type: "subprocess", x: COL_LEFT, y: 380 }, { id: "work", label: "WORK State", type: "process", x: COL_LEFT, y: 470 }, { id: "complete", label: "complete_task", type: "subprocess", x: COL_LEFT, y: 560 }, - { id: "inbox", label: "Check Inbox", type: "process", x: COL_RIGHT, y: 380 }, - { id: "shutdown", label: "Shutdown?", type: "decision", x: COL_RIGHT, y: 470 }, - { id: "done", label: "IDLE / SHUTDOWN", type: "end", x: COL_RIGHT, y: 560 }, + { id: "inbox", label: "No Ready Task", type: "process", x: COL_RIGHT, y: 380 }, + { id: "shutdown", label: "Remain IDLE", type: "process", x: COL_RIGHT, y: 470 }, + { id: "done", label: "Result + IDLE Event", type: "process", x: COL_CENTER, y: 650 }, ], edges: [ { from: "start", to: "idle" }, @@ -445,13 +416,13 @@ export const EXECUTION_FLOWS: Record = { { from: "claimable", to: "inbox", label: "no" }, { from: "claim", to: "work" }, { from: "work", to: "complete" }, - { from: "complete", to: "idle" }, + { from: "complete", to: "done" }, + { from: "done", to: "idle" }, { from: "inbox", to: "shutdown" }, - { from: "shutdown", to: "done", label: "yes" }, - { from: "shutdown", to: "idle", label: "no" }, + { from: "shutdown", to: "idle" }, ], }, - s18: { + s17: { nodes: [ { id: "start", label: "Task Selected", type: "start", x: COL_CENTER, y: 30 }, { id: "create", label: "create_worktree", type: "subprocess", x: COL_CENTER, y: 110 }, @@ -480,7 +451,7 @@ export const EXECUTION_FLOWS: Record = { { from: "keep", to: "end" }, ], }, - s19: { + s18: { nodes: [ { id: "start", label: "User Input", type: "start", x: COL_CENTER, y: 30 }, { id: "llm", label: "LLM Call", type: "process", x: COL_CENTER, y: 110 }, @@ -507,7 +478,7 @@ export const EXECUTION_FLOWS: Record = { { from: "append", to: "llm" }, ], }, - s20: { + s19: { nodes: [ { id: "start", label: "User Input", type: "start", x: COL_CENTER, y: 30 }, { id: "context", label: "Assemble Context\nmemory + tasks", type: "process", x: COL_CENTER, y: 115 }, @@ -541,7 +512,7 @@ export const EXECUTION_FLOWS: Record = { { from: "recover", to: "context" }, ], }, - s21: { + s20: { nodes: [ { id: "start", label: "Workflow Tool Call", type: "start", x: COL_CENTER, y: 30 }, { id: "validate", label: "Validate Meta +\nPermission", type: "process", x: COL_CENTER, y: 120 }, @@ -565,7 +536,7 @@ export const EXECUTION_FLOWS: Record = { { from: "output", to: "notify" }, ], }, - s22: { + s21: { nodes: [ { id: "start", label: "Model Wants to Stop", type: "start", x: COL_CENTER, y: 30 }, { id: "active", label: "Active Goal?", type: "decision", x: COL_CENTER, y: 120 }, diff --git a/web/src/data/generated/docs.json b/web/src/data/generated/docs.json index 157787f3..63bd9083 100644 --- a/web/src/data/generated/docs.json +++ b/web/src/data/generated/docs.json @@ -3,396 +3,378 @@ "version": "s01", "locale": "en", "title": "s01: The Agent Loop — One Loop Is All You Need", - "content": "# s01: The Agent Loop — One Loop Is All You Need\n\n`s01` → [s02](/en/s02) → s03 → s04 → ... → s20 → s21 → s22\n> *\"One loop & Bash is all you need\"* — One tool + one loop = one Agent.\n>\n> **Harness Layer**: The Loop — the first bridge between the model and the real world.\n\n---\n\n## The Problem\n\nYou ask the model: \"List the files in my directory and run XXX.py.\"\n\nThe model can output a bash command, but once it's done outputting, it stops — it won't execute the command on its own, and it won't keep reasoning based on the result.\n\nYou could run it manually, paste the output back into the chat, and let it continue. Next command comes out, you run it again, paste it back.\n\nEvery round-trip, you're the middle layer. Automating that is what this chapter is about.\n\n---\n\n## The Solution\n\n![Agent Loop](/course-assets/s01_agent_loop/agent-loop.en.svg)\n\nA `while True` loop: keep going when the model calls a tool, stop when it doesn't. The entire process hinges on two signals:\n\n| Signal | Meaning | Loop Action |\n|--------|---------|-------------|\n| `stop_reason == \"tool_use\"` | Model raises hand: \"I need a tool\" | Execute → feed result back → continue |\n| `stop_reason != \"tool_use\"` | Model says: \"I'm done\" | Exit loop |\n\n---\n\n## How It Works\n\nLet's translate this process into code. Step by step:\n\n**Step 1**: Start with the user's question as the first message.\n\n```python\nmessages = [{\"role\": \"user\", \"content\": query}]\n```\n\n**Step 2**: Send the messages and tool definitions to the LLM.\n\n```python\nresponse = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n)\n```\n\n**Step 3**: Append the model's response and check whether it called a tool. No tool call → done.\n\n```python\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\nif response.stop_reason != \"tool_use\":\n return\n```\n\n**Step 4**: Execute the tool the model requested and collect the results.\n\n```python\nresults = []\nfor block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n```\n\n**Step 5**: Append the tool results as a new message and go back to Step 2.\n\n```python\nmessages.append({\"role\": \"user\", \"content\": results})\n```\n\nAssembled into a complete function:\n\n```python\ndef agent_loop(messages):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n messages.append({\"role\": \"user\", \"content\": results})\n```\n\nUnder 30 lines — that's the minimal runnable agent harness kernel. It's not intelligence itself, but the smallest runtime framework that lets the model keep acting. The model decides (whether to call a tool, which one), the harness executes (if called, run it, feed the result back). The next 18 chapters all add mechanisms on top of this loop. The loop itself never changes.\n\n---\n\n## Try It\n\n> **Teaching demo notice**: The code executes shell commands generated by the model. Run it in a temporary test directory to avoid affecting your project files. s03 covers the real permission system.\n\n**Setup** (first run):\n\n```sh\npip install -r requirements.txt\ncp .env.example .env\n# Edit .env, fill in ANTHROPIC_API_KEY and MODEL_ID\n```\n\n**Run**:\n\n```sh\npython s01_agent_loop/code.py\n```\n\nTry these prompts:\n\n1. `Create a file called hello.py that prints \"Hello, World!\"`\n2. `List all Python files in this directory`\n3. `What is the current git branch?`\n\nWhat to watch for: When does the model call a tool (loop continues), and when does it not (loop ends)?\n\n---\n\n## What's Next\n\nRight now the model only has bash — reading files requires `cat`, writing files requires `echo ... >`, finding files requires `find`. Ugly and error-prone.\n\n→ s02 Tool Use: What happens when we give it 5 proper tools? Will the model call multiple tools at once? Will parallel tool executions step on each other?\n\n
\nDive into CC Source Code\n\n> The following is based on a review of CC source code `src/query.ts` (1729 lines). The core differences are twofold: CC doesn't rely on the `stop_reason` field to decide whether to continue the loop — instead it checks whether the content contains `tool_use` blocks (because `stop_reason` is unreliable in streaming responses); CC has more exit paths and recovery strategies for production-grade protection.\n\n**The 30-line `while True` from the teaching version IS the core of CC's 1729 lines.** Everything below is a protection mechanism layered on top of that core.\n\n
\n1. Loop Structure Differences\n\nThe teaching version checks `response.stop_reason`. CC doesn't use it as the sole signal for loop continuation — in streaming responses, `stop_reason` may not have updated yet even though `tool_use` blocks are already present. CC uses a `needsFollowUp` flag: during streaming message reception (`query.ts:830-834`), it's set to `true` whenever a `tool_use` block is detected. `QueryEngine.ts` captures the real `stop_reason` from `message_delta` for other logic, but the query loop itself relies on `needsFollowUp`.\n\n```typescript\n// query.ts:554-558\n// stop_reason === 'tool_use' is unreliable.\n// Set during streaming whenever a tool_use block arrives.\nlet needsFollowUp = false\n```\n\n
\n\n
\n2. State Object — 10 Fields (Teaching Version Only Uses messages)\n\n| # | Field | Purpose | Chapter |\n|---|-------|---------|---------|\n| 1 | `messages` | Message array for the current iteration | s01 |\n| 2 | `toolUseContext` | Tool, signal, and permission context | s02 |\n| 3 | `autoCompactTracking` | Compaction state tracking | s08 |\n| 4 | `maxOutputTokensRecoveryCount` | Token recovery attempt count (max 3) | s11 |\n| 5 | `hasAttemptedReactiveCompact` | Whether reactive compaction was attempted this round | s08 |\n| 6 | `maxOutputTokensOverride` | 8K→64K upgrade override | s11 |\n| 7 | `pendingToolUseSummary` | Background Haiku-generated tool use summary | s08 |\n| 8 | `stopHookActive` | Whether the stop hook produced a blocking error | s04 |\n| 9 | `turnCount` | Turn count (for maxTurns check) | s01 |\n| 10 | `transition` | Last continue reason | s11 |\n\n> Note: `taskBudgetRemaining` (`query.ts:291`) is a loop-local variable, not on State. The source comment explicitly says \"Loop-local (not on State)\".\n\n
\n\n
\n3. Multiple Exit and Continue Paths\n\nThe teaching version has only 1 exit path (model doesn't call a tool → done). The production version has multiple exit and continue paths, covering blocking limit, prompt too long, model error, abort, hook stop, max turns, token budget continuation, reactive compact retry, and more. Each scenario has a corresponding recovery or exit strategy.\n\n
\n\n
\n4. Streaming Tool Execution and QueryEngine\n\nCC's `StreamingToolExecutor` (`query.ts:561`) allows tools to begin parallel execution while the model is still generating (concurrency-safe tools run in parallel, others run exclusively). `QueryEngine.ts` adds additional protections for cost overruns, structured output validation failures, and more. The teaching version doesn't implement these — the goal is conceptual clarity, not peak performance.\n\n
\n\n**In one sentence**: The core of query.ts's 1729 lines is a 30-line `while True`. All the complex fields and exit paths are protection mechanisms. Understand the core loop first, and everything that follows unfolds naturally.\n\n
\n\n\n" + "content": "# s01: The Agent Loop — One Loop Is All You Need\n\n`s01` → [s02](/en/s02) → s03 → s04 → ... → s20 → s21\n> *\"One loop & Bash is all you need\"* — One tool + one loop = one Agent.\n>\n> **Harness Layer**: The Loop — the first bridge between the model and the real world.\n\n---\n\n## The Problem\n\nYou ask the model: \"List the files in my directory and run XXX.py.\"\n\nThe model can output a bash command, but once it's done outputting, it stops — it won't execute the command on its own, and it won't keep reasoning based on the result.\n\nYou could run it manually, paste the output back into the chat, and let it continue. Next command comes out, you run it again, paste it back.\n\nEvery round-trip, you're the middle layer. Automating that is what this chapter is about.\n\n---\n\n## The Solution\n\n![Agent Loop](/course-assets/s01_agent_loop/agent-loop.en.svg)\n\nA `while True` loop: keep going when the model calls a tool, stop when it doesn't. The entire process hinges on two signals:\n\n| Signal | Meaning | Loop Action |\n|--------|---------|-------------|\n| `stop_reason == \"tool_use\"` | Model raises hand: \"I need a tool\" | Execute → feed result back → continue |\n| `stop_reason != \"tool_use\"` | Model says: \"I'm done\" | Exit loop |\n\n---\n\n## How It Works\n\nLet's translate this process into code. Step by step:\n\n**Step 1**: Start with the user's question as the first message.\n\n```python\nmessages = [{\"role\": \"user\", \"content\": query}]\n```\n\n**Step 2**: Send the messages and tool definitions to the LLM.\n\n```python\nresponse = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n)\n```\n\n**Step 3**: Append the model's response and check whether it called a tool. No tool call → done.\n\n```python\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\nif response.stop_reason != \"tool_use\":\n return\n```\n\n**Step 4**: Execute the tool the model requested and collect the results.\n\n```python\nresults = []\nfor block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n```\n\n**Step 5**: Append the tool results as a new message and go back to Step 2.\n\n```python\nmessages.append({\"role\": \"user\", \"content\": results})\n```\n\nAssembled into a complete function:\n\n```python\ndef agent_loop(messages):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n messages.append({\"role\": \"user\", \"content\": results})\n```\n\nUnder 30 lines — that's the minimal runnable agent harness kernel. It's not intelligence itself, but the smallest runtime framework that lets the model keep acting. The model decides (whether to call a tool, which one), the harness executes (if called, run it, feed the result back). The next 18 chapters all add mechanisms on top of this loop. The loop itself never changes.\n\n---\n\n## Try It\n\n> **Safety notice**: The code executes shell commands generated by the model. Run it in a temporary test directory to avoid affecting your project files. s03 adds permission controls.\n\n**Setup** (first run):\n\n```sh\npip install -r requirements.txt\ncp .env.example .env\n# Edit .env, fill in ANTHROPIC_API_KEY and MODEL_ID\n```\n\n**Run**:\n\n```sh\npython s01_agent_loop/code.py\n```\n\nTry these prompts:\n\n1. `Create a file called hello.py that prints \"Hello, World!\"`\n2. `List all Python files in this directory`\n3. `What is the current git branch?`\n\nWhat to watch for: When does the model call a tool (loop continues), and when does it not (loop ends)?\n\n---\n\n## What's Next\n\nRight now the model only has bash — reading files requires `cat`, writing files requires `echo ... >`, finding files requires `find`. Ugly and error-prone.\n\n→ s02 Tool Use: What happens when we give it 5 proper tools? Will the model call multiple tools at once? Will parallel tool executions step on each other?\n\n\n\n" }, { "version": "s01", "locale": "zh", "title": "s01: Agent Loop — 一个循环就够了", - "content": "# s01: Agent Loop — 一个循环就够了\n\n`s01` → [s02](/zh/s02) → s03 → s04 → ... → s20 → s21 → s22\n> *\"One loop & Bash is all you need\"* — 一个工具 + 一个循环 = 一个 Agent。\n>\n> **Harness 层**: 循环 — 模型与真实世界的第一道连接。\n\n---\n\n## 问题\n\n你提出了一个问题给大模型:“帮我读取下我的目录下有哪些文件,并且执行XXX.py”。\n\n模型能输出一条 bash 命令,但输出完了就停了,它不会自己跑,也不会看到结果后继续推理。\n\n你可以手动跑一遍,把输出粘贴回对话框,让它接着干。下一个命令出来,你再跑一遍、再贴回去。\n\n每一个来回,你都在做中间层。而把它自动化,就是这一章要做的事。\n\n---\n\n## 解决方案\n\n![Agent Loop](/course-assets/s01_agent_loop/agent-loop.svg)\n\n一个 `while True` 循环,模型调用工具就继续,不调用就停。整个过程只有两个信号:\n\n| 信号 | 含义 | 循环动作 |\n|------|------|---------|\n| `stop_reason == \"tool_use\"` | 模型举手说\"我要用工具\" | 执行 → 结果喂回去 → 继续 |\n| `stop_reason != \"tool_use\"` | 模型说\"我做完了\" | 退出循环 |\n\n---\n\n## 工作原理\n\n将这个过程翻译成代码。分步来看:\n\n**第 1 步**:把用户的问题作为第一条消息。\n\n```python\nmessages = [{\"role\": \"user\", \"content\": query}]\n```\n\n**第 2 步**:将消息和工具定义一起发给 LLM。\n\n```python\nresponse = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n)\n```\n\n**第 3 步**:追加模型回答,检查它是否调了工具。没调 → 结束。\n\n```python\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\nif response.stop_reason != \"tool_use\":\n return\n```\n\n**第 4 步**:执行模型要求的工具,收集结果。\n\n```python\nresults = []\nfor block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n```\n\n**第 5 步**:把工具结果作为新消息追加,回到第 2 步。\n\n```python\nmessages.append({\"role\": \"user\", \"content\": results})\n```\n\n组装为一个完整函数:\n\n```python\ndef agent_loop(messages):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n messages.append({\"role\": \"user\", \"content\": results})\n```\n\n不到 30 行,这就是最小可运行的 agent harness 内核。它不是智能本身,而是让模型能持续行动的最小运行框架,模型负责决策(要不要调工具、调哪个),harness 负责执行(调了就跑、结果喂回去)。后面 18 个章节都在这个循环上叠加机制,循环本身始终不变。\n\n---\n\n## 试一下\n\n> **教学 demo 提示**:代码会执行模型生成的 shell 命令。建议在一个临时测试目录中运行,避免影响你的项目文件。s03 会讲真正的权限系统。\n\n**准备**(首次运行):\n\n```sh\npip install -r requirements.txt\ncp .env.example .env\n# 编辑 .env,填入 ANTHROPIC_API_KEY 和 MODEL_ID\n```\n\n**运行**:\n\n```sh\npython s01_agent_loop/code.py\n```\n\n试试这些 prompt:\n\n1. `Create a file called hello.py that prints \"Hello, World!\"`\n2. `List all Python files in this directory`\n3. `What is the current git branch?`\n\n观察重点:模型什么时候调用工具(循环继续),什么时候不调用(循环结束)?\n\n---\n\n## 接下来\n\n现在模型手里只有 bash 一个工具,读文件要 `cat`,写文件要 `echo ... >`,找个文件要 `find`,又丑又容易出错。\n\ns02 Tool Use → 给它 5 个真正的工具,会发生什么?模型会不会一次调用多个工具?几个工具同时跑会不会互相踩?\n\n
\n深入 CC 源码\n\n> 以下内容基于 CC 源码 `src/query.ts`(1729 行)的核查。核心差异就两个:CC 不看 `stop_reason` 字段而是检查内容里有没有 tool_use 块(因为流式响应中 stop_reason 不可靠);CC 有更多的退出路径和恢复策略做生产级保护。\n\n**教学版的 30 行 `while True` 就是 CC 1729 行的核心。** 下面每一项都是在这个核心上叠加的保护机制。\n\n
\n一、循环结构差异\n\n教学版检查 `response.stop_reason`。CC 不把它作为循环继续的唯一依据——流式响应中 `stop_reason` 可能还没更新但内容里已经有 `tool_use` 块了。CC 用 `needsFollowUp` 标志:接收到流式消息时(`query.ts:830-834`),只要检测到 `tool_use` 块就设为 `true`;`QueryEngine.ts` 会从 `message_delta` 捕获真实 `stop_reason` 用于其他逻辑,但 query loop 本身靠 `needsFollowUp` 决定是否继续。\n\n```typescript\n// query.ts:554-558\n// stop_reason === 'tool_use' is unreliable.\n// Set during streaming whenever a tool_use block arrives.\nlet needsFollowUp = false\n```\n\n
\n\n
\n二、State 对象 10 字段(教学版只用 messages)\n\n| # | 字段 | 用途 | 对应章节 |\n|---|------|------|---------|\n| 1 | `messages` | 当前迭代的消息数组 | s01 |\n| 2 | `toolUseContext` | 工具、信号、权限上下文 | s02 |\n| 3 | `autoCompactTracking` | 压缩状态追踪 | s08 |\n| 4 | `maxOutputTokensRecoveryCount` | token 恢复尝试次数(上限 3) | s11 |\n| 5 | `hasAttemptedReactiveCompact` | 本轮是否已尝试响应式压缩 | s08 |\n| 6 | `maxOutputTokensOverride` | 8K→64K 的升级覆盖 | s11 |\n| 7 | `pendingToolUseSummary` | 后台 Haiku 生成的 tool use 摘要 | s08 |\n| 8 | `stopHookActive` | 停止钩子是否产生阻塞错误 | s04 |\n| 9 | `turnCount` | 轮次计数(maxTurns 检查) | s01 |\n| 10 | `transition` | 上一次继续原因 | s11 |\n\n> 注:`taskBudgetRemaining`(`query.ts:291`)是 loop-local 局部变量,不在 State 上。源码注释明确写了 \"Loop-local (not on State)\"。\n\n
\n\n
\n三、多条退出和继续路径\n\n教学版只有 1 条退出路径(模型不调工具就结束)。生产版有多条退出和继续路径,覆盖 blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry 等场景。每种场景都有对应的恢复或退出策略。\n\n
\n\n
\n四、流式工具执行和 QueryEngine\n\nCC 的 `StreamingToolExecutor`(`query.ts:561`)让工具在模型还在生成时就开始并行执行(根据工具是否 concurrency-safe 决定并发或独占)。`QueryEngine.ts` 额外加了费用超限、结构化输出验证失败等保护。教学版不实现这些——目标是概念清晰,不是性能极致。\n\n
\n\n**一句话**:1729 行的 query.ts 核心就是 30 行 `while True`。所有复杂字段和退出路径都是保护机制。先理解核心循环,后面的一切自然展开。\n\n
\n\n\n" + "content": "# s01: Agent Loop — 一个循环就够了\n\n`s01` → [s02](/zh/s02) → s03 → s04 → ... → s20 → s21\n> *\"One loop & Bash is all you need\"* — 一个工具 + 一个循环 = 一个 Agent。\n>\n> **Harness 层**: 循环 — 模型与真实世界的第一道连接。\n\n---\n\n## 问题\n\n你提出了一个问题给大模型:“帮我读取下我的目录下有哪些文件,并且执行XXX.py”。\n\n模型能输出一条 bash 命令,但输出完了就停了,它不会自己跑,也不会看到结果后继续推理。\n\n你可以手动跑一遍,把输出粘贴回对话框,让它接着干。下一个命令出来,你再跑一遍、再贴回去。\n\n每一个来回,你都在做中间层。而把它自动化,就是这一章要做的事。\n\n---\n\n## 解决方案\n\n![Agent Loop](/course-assets/s01_agent_loop/agent-loop.svg)\n\n一个 `while True` 循环,模型调用工具就继续,不调用就停。整个过程只有两个信号:\n\n| 信号 | 含义 | 循环动作 |\n|------|------|---------|\n| `stop_reason == \"tool_use\"` | 模型举手说\"我要用工具\" | 执行 → 结果喂回去 → 继续 |\n| `stop_reason != \"tool_use\"` | 模型说\"我做完了\" | 退出循环 |\n\n---\n\n## 工作原理\n\n将这个过程翻译成代码。分步来看:\n\n**第 1 步**:把用户的问题作为第一条消息。\n\n```python\nmessages = [{\"role\": \"user\", \"content\": query}]\n```\n\n**第 2 步**:将消息和工具定义一起发给 LLM。\n\n```python\nresponse = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n)\n```\n\n**第 3 步**:追加模型回答,检查它是否调了工具。没调 → 结束。\n\n```python\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\nif response.stop_reason != \"tool_use\":\n return\n```\n\n**第 4 步**:执行模型要求的工具,收集结果。\n\n```python\nresults = []\nfor block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n```\n\n**第 5 步**:把工具结果作为新消息追加,回到第 2 步。\n\n```python\nmessages.append({\"role\": \"user\", \"content\": results})\n```\n\n组装为一个完整函数:\n\n```python\ndef agent_loop(messages):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n messages.append({\"role\": \"user\", \"content\": results})\n```\n\n不到 30 行,这就是最小可运行的 agent harness 内核。它不是智能本身,而是让模型能持续行动的最小运行框架,模型负责决策(要不要调工具、调哪个),harness 负责执行(调了就跑、结果喂回去)。后面 18 个章节都在这个循环上叠加机制,循环本身始终不变。\n\n---\n\n## 试一下\n\n> **安全提示**:代码会执行模型生成的 shell 命令。建议在一个临时测试目录中运行,避免影响你的项目文件。s03 会加入权限控制。\n\n**准备**(首次运行):\n\n```sh\npip install -r requirements.txt\ncp .env.example .env\n# 编辑 .env,填入 ANTHROPIC_API_KEY 和 MODEL_ID\n```\n\n**运行**:\n\n```sh\npython s01_agent_loop/code.py\n```\n\n试试这些 prompt:\n\n1. `Create a file called hello.py that prints \"Hello, World!\"`\n2. `List all Python files in this directory`\n3. `What is the current git branch?`\n\n观察重点:模型什么时候调用工具(循环继续),什么时候不调用(循环结束)?\n\n---\n\n## 接下来\n\n现在模型手里只有 bash 一个工具,读文件要 `cat`,写文件要 `echo ... >`,找个文件要 `find`,又丑又容易出错。\n\ns02 Tool Use → 给它 5 个真正的工具,会发生什么?模型会不会一次调用多个工具?几个工具同时跑会不会互相踩?\n\n\n\n" }, { "version": "s01", "locale": "ja", "title": "s01: Agent Loop — ループ一つで十分", - "content": "# s01: Agent Loop — ループ一つで十分\n\n`s01` → [s02](/ja/s02) → s03 → s04 → ... → s20 → s21 → s22\n> *\"One loop & Bash is all you need\"* — ツール一つ + ループ一つ = 一つの Agent。\n>\n> **Harness レイヤー**: ループ — モデルと現実世界をつなぐ最初の架け橋。\n\n---\n\n## 課題\n\nモデルにこう頼んだとする:「ディレクトリ内のファイル一覧を取得して、XXX.py を実行して」。\n\nモデルは bash コマンドを出力できるが、出力が終わると止まってしまう — 自分で実行することも、結果を見て推論を続けることもない。\n\n手動で実行し、出力をチャットに貼り付ければ、モデルは続きを生成できる。次のコマンドが出たら、また実行して貼り付ける。\n\n毎回の往復で、あなたが中間層になっている。これを自動化するのが、この章の目的だ。\n\n---\n\n## ソリューション\n\n![Agent Loop](/course-assets/s01_agent_loop/agent-loop.ja.svg)\n\n一つの `while True` ループ — モデルがツールを呼べば続き、呼ばなければ停止。全体でたった 2 つのシグナル:\n\n| シグナル | 意味 | ループの動作 |\n|----------|------|-------------|\n| `stop_reason == \"tool_use\"` | モデルが「ツールが必要」と挙手 | 実行 → 結果を戻す → 続行 |\n| `stop_reason != \"tool_use\"` | モデルが「完了」と宣言 | ループ終了 |\n\n---\n\n## 仕組み\n\nこのプロセスをコードに変換してみよう。ステップごとに:\n\n**ステップ 1**:ユーザーの質問を最初のメッセージとして設定する。\n\n```python\nmessages = [{\"role\": \"user\", \"content\": query}]\n```\n\n**ステップ 2**:メッセージとツール定義を一緒に LLM に送信する。\n\n```python\nresponse = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n)\n```\n\n**ステップ 3**:モデルの応答を追加し、ツールを呼び出したか確認する。呼び出しなし → 終了。\n\n```python\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\nif response.stop_reason != \"tool_use\":\n return\n```\n\n**ステップ 4**:モデルが要求したツールを実行し、結果を収集する。\n\n```python\nresults = []\nfor block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n```\n\n**ステップ 5**:ツールの結果を新しいメッセージとして追加し、ステップ 2 に戻る。\n\n```python\nmessages.append({\"role\": \"user\", \"content\": results})\n```\n\n完全な関数に組み立てる:\n\n```python\ndef agent_loop(messages):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n messages.append({\"role\": \"user\", \"content\": results})\n```\n\n30 行未満 — これが最小実行可能な agent harness のカーネルだ。これは知能そのものではなく、モデルが継続的に行動できるための最小ランタイムフレームワーク。モデルが決定し(ツールを呼ぶか、どれを呼ぶか)、harness が実行する(呼ばれたら実行し、結果を戻す)。次の 18 章はすべてこのループの上に仕組みを積み重ねていく。ループ自体は永遠に変わらない。\n\n---\n\n## 試してみよう\n\n> **教育デモの注意**: このコードはモデルが生成したシェルコマンドを実行します。プロジェクトファイルへの影響を避けるため、一時テストディレクトリで実行してください。s03 で本格的な権限システムを説明します。\n\n**準備**(初回のみ):\n\n```sh\npip install -r requirements.txt\ncp .env.example .env\n# .env を編集し、ANTHROPIC_API_KEY と MODEL_ID を入力\n```\n\n**実行**:\n\n```sh\npython s01_agent_loop/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Create a file called hello.py that prints \"Hello, World!\"`\n2. `List all Python files in this directory`\n3. `What is the current git branch?`\n\n観察のポイント:モデルがツールを呼び出すとき(ループ継続)、呼び出さないとき(ループ終了)の違い。\n\n---\n\n## 次へ\n\n現在、モデルが持っているのは bash だけだ — ファイルを読むには `cat`、書くには `echo ... >`、探すには `find`。不便でエラーも起きやすい。\n\n→ s02 Tool Use:5 つの本格的なツールを与えたらどうなる? モデルは複数のツールを同時に呼び出すか? 並列実行で競合は起きないか?\n\n
\nCC ソースコードを深掘り\n\n> 以下は CC ソースコード `src/query.ts`(1729 行)の検証に基づく。核心的な違いは二つ:CC はループ継続の判断に `stop_reason` フィールドを頼らず、コンテンツに `tool_use` ブロックが含まれるかをチェックする(ストリーミングレスポンスでは `stop_reason` が信頼できないため)。CC には本番環境向けのより多くの終了パスとリカバリ戦略がある。\n\n**教育版の 30 行 `while True` が CC の 1729 行の核心。** 以下の各項目は、すべてその核心の上に積み重ねられた保護機構である。\n\n
\n一、ループ構造の違い\n\n教育版は `response.stop_reason` をチェックする。CC はこれをループ継続の唯一の根拠として使わない — ストリーミングレスポンスでは、`stop_reason` がまだ更新されていなくても、コンテンツに既に `tool_use` ブロックが含まれている可能性がある。CC は `needsFollowUp` フラグを使用する:ストリーミングメッセージの受信時(`query.ts:830-834`)に、`tool_use` ブロックが検出されると `true` に設定される。`QueryEngine.ts` は `message_delta` から実際の `stop_reason` を取得して他の処理に利用するが、query loop 自体は `needsFollowUp` に依存する。\n\n```typescript\n// query.ts:554-558\n// stop_reason === 'tool_use' is unreliable.\n// Set during streaming whenever a tool_use block arrives.\nlet needsFollowUp = false\n```\n\n
\n\n
\n二、State オブジェクト 10 フィールド(教育版は messages のみ使用)\n\n| # | フィールド | 用途 | 対応章 |\n|---|-----------|------|--------|\n| 1 | `messages` | 現在のイテレーションのメッセージ配列 | s01 |\n| 2 | `toolUseContext` | ツール、シグナル、権限コンテキスト | s02 |\n| 3 | `autoCompactTracking` | 圧縮状態の追跡 | s08 |\n| 4 | `maxOutputTokensRecoveryCount` | トークンリカバリ試行回数(上限 3) | s11 |\n| 5 | `hasAttemptedReactiveCompact` | 今回のラウンドでリアクティブ圧縮を試みたか | s08 |\n| 6 | `maxOutputTokensOverride` | 8K→64K へのアップグレード上書き | s11 |\n| 7 | `pendingToolUseSummary` | バックグラウンド Haiku 生成のツール使用要約 | s08 |\n| 8 | `stopHookActive` | 停止フックがブロッキングエラーを発生させたか | s04 |\n| 9 | `turnCount` | ターン数(maxTurns チェック用) | s01 |\n| 10 | `transition` | 前回の継続理由 | s11 |\n\n> 注:`taskBudgetRemaining`(`query.ts:291`)は loop-local のローカル変数であり、State には含まれない。ソースコメントには明確に \"Loop-local (not on State)\" と書かれている。\n\n
\n\n
\n三、複数の終了パスと継続パス\n\n教育版には 1 つの終了パスしかない(モデルがツールを呼ばなければ終了)。本番版には複数の終了・継続パスがあり、blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry など多くのシナリオをカバーしている。各シナリオには対応するリカバリまたは終了戦略がある。\n\n
\n\n
\n四、ストリーミングツール実行と QueryEngine\n\nCC の `StreamingToolExecutor`(`query.ts:561`)は、モデルがまだ生成中にツールの実行を開始できる(concurrency-safe なツールは並列、それ以外は排他実行)。`QueryEngine.ts` はさらに、コスト超過や構造化出力の検証失敗などの保護を追加する。教育版はこれらを実装しない — 目標は概念の明確さであり、極限のパフォーマンスではない。\n\n
\n\n**一言で**: query.ts の 1729 行の核心は 30 行の `while True`。複雑なフィールドや終了パスはすべて保護機構だ。まず核心のループを理解すれば、その後のすべては自然に理解できる。\n\n
\n\n\n" + "content": "# s01: Agent Loop — ループ一つで十分\n\n`s01` → [s02](/ja/s02) → s03 → s04 → ... → s20 → s21\n> *\"One loop & Bash is all you need\"* — ツール一つ + ループ一つ = 一つの Agent。\n>\n> **Harness レイヤー**: ループ — モデルと現実世界をつなぐ最初の架け橋。\n\n---\n\n## 課題\n\nモデルにこう頼んだとする:「ディレクトリ内のファイル一覧を取得して、XXX.py を実行して」。\n\nモデルは bash コマンドを出力できるが、出力が終わると止まってしまう — 自分で実行することも、結果を見て推論を続けることもない。\n\n手動で実行し、出力をチャットに貼り付ければ、モデルは続きを生成できる。次のコマンドが出たら、また実行して貼り付ける。\n\n毎回の往復で、あなたが中間層になっている。これを自動化するのが、この章の目的だ。\n\n---\n\n## ソリューション\n\n![Agent Loop](/course-assets/s01_agent_loop/agent-loop.ja.svg)\n\n一つの `while True` ループ — モデルがツールを呼べば続き、呼ばなければ停止。全体でたった 2 つのシグナル:\n\n| シグナル | 意味 | ループの動作 |\n|----------|------|-------------|\n| `stop_reason == \"tool_use\"` | モデルが「ツールが必要」と挙手 | 実行 → 結果を戻す → 続行 |\n| `stop_reason != \"tool_use\"` | モデルが「完了」と宣言 | ループ終了 |\n\n---\n\n## 仕組み\n\nこのプロセスをコードに変換してみよう。ステップごとに:\n\n**ステップ 1**:ユーザーの質問を最初のメッセージとして設定する。\n\n```python\nmessages = [{\"role\": \"user\", \"content\": query}]\n```\n\n**ステップ 2**:メッセージとツール定義を一緒に LLM に送信する。\n\n```python\nresponse = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n)\n```\n\n**ステップ 3**:モデルの応答を追加し、ツールを呼び出したか確認する。呼び出しなし → 終了。\n\n```python\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\nif response.stop_reason != \"tool_use\":\n return\n```\n\n**ステップ 4**:モデルが要求したツールを実行し、結果を収集する。\n\n```python\nresults = []\nfor block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n```\n\n**ステップ 5**:ツールの結果を新しいメッセージとして追加し、ステップ 2 に戻る。\n\n```python\nmessages.append({\"role\": \"user\", \"content\": results})\n```\n\n完全な関数に組み立てる:\n\n```python\ndef agent_loop(messages):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = run_bash(block.input[\"command\"])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n messages.append({\"role\": \"user\", \"content\": results})\n```\n\n30 行未満 — これが最小実行可能な agent harness のカーネルだ。これは知能そのものではなく、モデルが継続的に行動できるための最小ランタイムフレームワーク。モデルが決定し(ツールを呼ぶか、どれを呼ぶか)、harness が実行する(呼ばれたら実行し、結果を戻す)。次の 18 章はすべてこのループの上に仕組みを積み重ねていく。ループ自体は永遠に変わらない。\n\n---\n\n## 試してみよう\n\n> **安全上の注意**: このコードはモデルが生成したシェルコマンドを実行します。プロジェクトファイルへの影響を避けるため、一時テストディレクトリで実行してください。s03 で権限制御を追加します。\n\n**準備**(初回のみ):\n\n```sh\npip install -r requirements.txt\ncp .env.example .env\n# .env を編集し、ANTHROPIC_API_KEY と MODEL_ID を入力\n```\n\n**実行**:\n\n```sh\npython s01_agent_loop/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Create a file called hello.py that prints \"Hello, World!\"`\n2. `List all Python files in this directory`\n3. `What is the current git branch?`\n\n観察のポイント:モデルがツールを呼び出すとき(ループ継続)、呼び出さないとき(ループ終了)の違い。\n\n---\n\n## 次へ\n\n現在、モデルが持っているのは bash だけだ — ファイルを読むには `cat`、書くには `echo ... >`、探すには `find`。不便でエラーも起きやすい。\n\n→ s02 Tool Use:5 つの本格的なツールを与えたらどうなる? モデルは複数のツールを同時に呼び出すか? 並列実行で競合は起きないか?\n\n\n\n" }, { "version": "s02", "locale": "en", "title": "s02: Tool Use — Add a Tool, Add Just One Line", - "content": "# s02: Tool Use — Add a Tool, Add Just One Line\n\ns01 → `s02` → [s03](/en/s03) → s04 → ... → s20 → s21 → s22\n> *\"Add a tool, add just one handler\"* — The loop stays the same. Register the new tool in the dispatch map and you're done.\n>\n> **Harness Layer**: Tool Dispatch — Expanding the model's reach.\n\n---\n\n## Only One Tool: Bash\n\nThe s01 Agent has only one tool: bash. To read a file, `cat`; to write, `echo \"...\" > file.py`; to edit, `sed`.\n\nThe model thinks \"read this file\" but has to spell out `cat path/to/file`. An extra layer of translation that wastes tokens and invites errors.\n\n---\n\n## Overview: Tool Dispatch\n\n![Tool Dispatch](/course-assets/s02_tool_use/tool-dispatch.en.svg)\n\nThe s01 loop is fully preserved (LLM call, stop_reason check, message append — not a single word changed). The only change is in that one line of tool execution: `run_bash()` is replaced with `TOOL_HANDLERS[block.name]()` dispatch lookup.\n\nAdding a tool to the Agent requires just two things:\n\n1. **Define the tool**: Add one entry to the `TOOLS` array\n2. **Register the handler**: Add one mapping in the `TOOL_HANDLERS` dict\n\n---\n\n## From 1 Tool to 5 Tools\n\ns01 had only bash:\n\n```python\nTOOLS = [{\"name\": \"bash\", ...}]\n\ndef run_bash(command): ...\n```\n\ns02 expands to 5 tools, each independently defined:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\", ...},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\", ...},\n {\"name\": \"write_file\", \"description\": \"Write content to file.\", ...},\n {\"name\": \"edit_file\", \"description\": \"Replace text in file once.\", ...},\n {\"name\": \"glob\", \"description\": \"Find files by pattern.\", ...},\n]\n```\n\nEach tool has its own implementation function:\n\n```python\ndef run_read(path, limit=None):\n lines = safe_path(path).read_text().splitlines()\n if limit:\n lines = lines[:limit]\n return \"\\n\".join(lines)\n\ndef run_write(path, content):\n safe_path(path).write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n\ndef run_edit(path, old_text, new_text):\n text = safe_path(path).read_text()\n if old_text not in text:\n return \"Error: text not found\"\n safe_path(path).write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n\ndef run_glob(pattern):\n import glob as g\n return \"\\n\".join(g.glob(pattern, root_dir=WORKDIR))\n```\n\n---\n\n## Tool Dispatch\n\n```python\nTOOL_HANDLERS = {\n \"bash\": run_bash,\n \"read_file\": run_read,\n \"write_file\": run_write,\n \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n# Only one line changed in the loop — from hardcoded run_bash to dispatch lookup:\nfor block in response.content:\n if block.type == \"tool_use\":\n handler = TOOL_HANDLERS[block.name] # lookup\n output = handler(**block.input) # call\n results.append(...)\n```\n\nAdding a tool = one entry in `TOOLS` array + one line in `TOOL_HANDLERS` dict. The loop stays the same.\n\n---\n\n## Multiple Tool Calls\n\nThe model often returns multiple tool_use calls at once — \"read a.py and b.py, then list all .py files\".\n\nThe teaching version executes them one by one in the original `response.content` order. CC's approach is more complex: it slices the original order into consecutive batches, where concurrency-safe tools within a batch run in parallel, and batches are strictly sequential (see appendix).\n\n---\n\n## Quick Reference\n\n| Concept | One-Liner |\n|---------|-----------|\n| TOOL_HANDLERS | Tool name → handler function dict. Add a tool = add one mapping line |\n| Tool Definition | JSON schema telling the model \"what I can do\" |\n| Multiple tool calls | Model may return multiple tool_use at once; teaching version executes them in original order |\n| Loop Unchanged | s01's `while True` loop — not a single line changed |\n\n---\n\n## Changes from s01\n\n| Component | Before (s01) | After (s02) |\n|-----------|-------------|-------------|\n| Tool count | 1 (bash) | 5 (+read, write, edit, glob) |\n| Tool execution | Hardcoded `run_bash()` | TOOL_HANDLERS dispatch lookup |\n| Path safety | None | safe_path validation (file tools only) |\n| Loop | `while True` + `stop_reason` | Identical to s01 |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s02_tool_use/code.py\n```\n\nTry these prompts:\n\n1. `Read the file README.md and tell me what this project is about`\n2. `Create a file called test.py that prints \"hello\", then read it back`\n3. `Find all Python files in this directory`\n4. `Read both README.md and requirements.txt, then create a summary file`\n\nWhat to watch for: When does the model call just one tool, and when does it call multiple at once? Are multiple tool calls executed in the correct order?\n\n---\n\n## What's Next\n\nThe Agent now has 5 specialized tools. File tools are protected by `safe_path`, but bash is unrestricted — `rm -rf /` still runs.\n\n→ s03 Permission: Add a gate before tool execution — is this operation safe? Does it need user approval?\n\n
\nDive into CC Source Code\n\n> The following is based on a review of CC source code `Tool.ts`, `tools.ts`, `toolOrchestration.ts`, `toolExecution.ts`, and `StreamingToolExecutor.ts`.\n\n### 1. Tool Definition Approach\n\n**Teaching version**: `TOOLS` array + `TOOL_HANDLERS` dict. Definition and implementation are separate.\n**CC**: Each tool is an independent object created by `buildTool()`, containing schema, validation, permissions, and execution. `getAllBaseTools()` aggregates all tools.\n\nThe teaching version's separation is clearer for teaching — readers immediately see \"add a tool = two definitions\".\n\n### 2. Concurrency Safety: isConcurrencySafe()\n\n![Tool Concurrency](/course-assets/s02_tool_use/concurrency-comparison.en.svg)\n\nThe teaching version executes tools one by one in original order, without concurrency. CC uses `isConcurrencySafe(input)` to determine concurrency — note this isn't simply \"read-only vs write\", but judges by specific input:\n\n| | isReadOnly | isConcurrencySafe |\n|---|---|---|\n| FileRead | true | true |\n| Glob | true | true |\n| Bash `ls` | true | **true** ← key difference |\n| Bash `rm` | false | false |\n| TaskCreate | false | **true** ← modifies state but can be concurrent (introduced in s12) |\n\nCC's Bash tool's `isConcurrencySafe` equals `isReadOnly` — read-only commands can be concurrent, write commands cannot. TaskCreate modifies task files, but each writes a different file, so it can be concurrent.\n\n### 3. Partition Algorithm\n\nCC's `partitionToolCalls()` (`toolOrchestration.ts:91-115`) doesn't split into two groups — it batches tool calls **by consecutive blocks**:\n\n```\n[read A, read B, glob *.py, bash \"rm x\", read C]\n → batch1(concurrent): [read A, read B, glob *.py]\n → batch2(serial): [bash \"rm x\"]\n → batch3(concurrent): [read C]\n```\n\nConsecutive concurrency-safe calls are grouped into the same batch for truly concurrent execution (`toolOrchestration.ts:152-176`, with a concurrency limit). When a non-concurrency-safe call is encountered, a new batch starts for serial execution. Batches are strictly sequential.\n\n### 4. Validation Pipeline\n\nEach tool call in CC goes through a strict 5-step validation (`toolExecution.ts`):\n\n1. **Zod schema validation** (`614-680`, teaching version uses JSON Schema): parameter type/structure check\n2. **Tool-level validateInput()** (`682-733`): parameter value validation (e.g., is the path within the working directory)\n3. **PreToolUse hooks** (`800-862`, covered in s04): hooks can return messages, modify input, or block execution\n4. **Permission check** (`921-931`, core topic of s03): canUseTool + checkPermissions → allow/deny/ask\n5. **Execute tool.call()** (`1207-1222`)\n\nThe teaching version omits Zod (uses JSON Schema), omits validateInput (uses safety functions), but preserves the permission check and hook concepts.\n\n### 5. Streaming Tool Execution\n\nCC's `StreamingToolExecutor` (`StreamingToolExecutor.ts`) starts tools while the model is still generating — no waiting for the model to finish. `read_file` might complete while the model is still outputting \"Let me analyze\". The teaching version doesn't implement this, consistent with s01's goal — conceptual clarity, not peak performance.\n\n### 6. Tool Result Persistence\n\nEach tool has a `maxResultSizeChars` field. Results exceeding this threshold are persisted to disk, and the model sees a preview + file path. FileRead is special — set to `Infinity`, preventing file read output from being persisted again. Specifically, if FileRead's result exceeds the threshold and gets persisted, the model's next read of that persisted file would trigger another persistence → infinite loop (read file → persist → re-read → re-persist → ...).\n\n
\n\n\n" + "content": "# s02: Tool Use — Add a Tool, Add Just One Line\n\ns01 → `s02` → [s03](/en/s03) → s04 → ... → s20 → s21\n> *\"Add a tool, add just one handler\"* — The loop stays the same. Register the new tool in the dispatch map and you're done.\n>\n> **Harness Layer**: Tool Dispatch — Expanding the model's reach.\n\n---\n\n## Only One Tool: Bash\n\nThe s01 Agent has only one tool: bash. To read a file, `cat`; to write, `echo \"...\" > file.py`; to edit, `sed`.\n\nThe model thinks \"read this file\" but has to spell out `cat path/to/file`. An extra layer of translation that wastes tokens and invites errors.\n\n---\n\n## Overview: Tool Dispatch\n\n![Tool Dispatch](/course-assets/s02_tool_use/tool-dispatch.en.svg)\n\nThe s01 loop is fully preserved (LLM call, stop_reason check, message append — not a single word changed). The only change is in that one line of tool execution: `run_bash()` is replaced with `TOOL_HANDLERS[block.name]()` dispatch lookup.\n\nAdding a tool to the Agent requires just two things:\n\n1. **Define the tool**: Add one entry to the `TOOLS` array\n2. **Register the handler**: Add one mapping in the `TOOL_HANDLERS` dict\n\n---\n\n## From 1 Tool to 5 Tools\n\ns01 had only bash:\n\n```python\nTOOLS = [{\"name\": \"bash\", ...}]\n\ndef run_bash(command): ...\n```\n\ns02 expands to 5 tools, each independently defined:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\", ...},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\", ...},\n {\"name\": \"write_file\", \"description\": \"Write content to file.\", ...},\n {\"name\": \"edit_file\", \"description\": \"Replace text in file once.\", ...},\n {\"name\": \"glob\", \"description\": \"Find files by pattern.\", ...},\n]\n```\n\nEach tool has its own implementation function:\n\n```python\ndef run_read(path, limit=None):\n lines = safe_path(path).read_text().splitlines()\n if limit:\n lines = lines[:limit]\n return \"\\n\".join(lines)\n\ndef run_write(path, content):\n safe_path(path).write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n\ndef run_edit(path, old_text, new_text):\n text = safe_path(path).read_text()\n if old_text not in text:\n return \"Error: text not found\"\n safe_path(path).write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n\ndef run_glob(pattern):\n import glob as g\n return \"\\n\".join(g.glob(pattern, root_dir=WORKDIR))\n```\n\n---\n\n## Tool Dispatch\n\n```python\nTOOL_HANDLERS = {\n \"bash\": run_bash,\n \"read_file\": run_read,\n \"write_file\": run_write,\n \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n# Only one line changed in the loop — from hardcoded run_bash to dispatch lookup:\nfor block in response.content:\n if block.type == \"tool_use\":\n handler = TOOL_HANDLERS[block.name] # lookup\n output = handler(**block.input) # call\n results.append(...)\n```\n\nAdding a tool = one entry in `TOOLS` array + one line in `TOOL_HANDLERS` dict. The loop stays the same.\n\n---\n\n## Multiple Tool Calls\n\nThe model often returns multiple tool_use calls at once — \"read a.py and b.py, then list all .py files\".\n\nCalls are executed one by one in their original `response.content` order.\n\n---\n\n## Quick Reference\n\n| Concept | One-Liner |\n|---------|-----------|\n| TOOL_HANDLERS | Tool name → handler function dict. Add a tool = add one mapping line |\n| Tool Definition | JSON schema telling the model \"what I can do\" |\n| Multiple tool calls | Model may return multiple tool_use at once; calls execute in their original order |\n| Loop Unchanged | s01's `while True` loop — not a single line changed |\n\n---\n\n## Changes from s01\n\n| Component | Before (s01) | After (s02) |\n|-----------|-------------|-------------|\n| Tool count | 1 (bash) | 5 (+read, write, edit, glob) |\n| Tool execution | Hardcoded `run_bash()` | TOOL_HANDLERS dispatch lookup |\n| Path safety | None | safe_path validation (file tools only) |\n| Loop | `while True` + `stop_reason` | Identical to s01 |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s02_tool_use/code.py\n```\n\nTry these prompts:\n\n1. `Read the file README.md and tell me what this project is about`\n2. `Create a file called test.py that prints \"hello\", then read it back`\n3. `Find all Python files in this directory`\n4. `Read both README.md and requirements.txt, then create a summary file`\n\nWhat to watch for: When does the model call just one tool, and when does it call multiple at once? Are multiple tool calls executed in the correct order?\n\n---\n\n## What's Next\n\nThe Agent now has 5 specialized tools. File tools are protected by `safe_path`, but bash is unrestricted — `rm -rf /` still runs.\n\n→ s03 Permission: Add a gate before tool execution — is this operation safe? Does it need user approval?\n\n\n\n" }, { "version": "s02", "locale": "zh", "title": "s02: Tool Use — 多加一个工具,只加一行", - "content": "# s02: Tool Use — 多加一个工具,只加一行\n\ns01 → `s02` → [s03](/zh/s03) → s04 → ... → s20 → s21 → s22\n> *\"加一个工具, 只加一个 handler\"* — 循环不用动, 新工具注册进 dispatch map 就行。\n>\n> **Harness 层**: 工具分发 — 扩展模型能触达的边界。\n\n---\n\n## 只有 bash 一个工具\n\ns01 的 Agent 只有一个 bash 工具。读文件要 `cat`,写文件要 `echo \"...\" > file.py`,改文件要 `sed`。\n\n模型想的是\"读这个文件\",却要拼出 `cat path/to/file`。多了一层翻译,浪费 token,还容易拼错。\n\n---\n\n## 全局视角:工具分发\n\n![Tool Dispatch](/course-assets/s02_tool_use/tool-dispatch.svg)\n\ns01 的循环完全保留(LLM 调用、stop_reason 判断、消息追加)。唯一的变动在工具执行那 1 行:`run_bash()` 替换为 `TOOL_HANDLERS[block.name]()` 查表分发。\n\n给 Agent 加一个工具只需要做两件事:\n\n1. **定义工具**:在 `TOOLS` 数组里加一条描述\n2. **注册处理函数**:在 `TOOL_HANDLERS` 字典里加一个映射\n\n---\n\n## 从 1 个工具到 5 个工具\n\ns01 只有一个 bash:\n\n```python\nTOOLS = [{\"name\": \"bash\", ...}]\n\ndef run_bash(command): ...\n```\n\ns02 加到 5 个,每个工具都是独立定义:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\", ...},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\", ...},\n {\"name\": \"write_file\", \"description\": \"Write content to file.\", ...},\n {\"name\": \"edit_file\", \"description\": \"Replace text in file once.\", ...},\n {\"name\": \"glob\", \"description\": \"Find files by pattern.\", ...},\n]\n```\n\n每个工具有自己的实现函数:\n\n```python\ndef run_read(path, limit=None):\n lines = safe_path(path).read_text().splitlines()\n if limit:\n lines = lines[:limit]\n return \"\\n\".join(lines)\n\ndef run_write(path, content):\n safe_path(path).write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n\ndef run_edit(path, old_text, new_text):\n text = safe_path(path).read_text()\n if old_text not in text:\n return \"Error: text not found\"\n safe_path(path).write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n\ndef run_glob(pattern):\n import glob as g\n return \"\\n\".join(g.glob(pattern, root_dir=WORKDIR))\n```\n\n---\n\n## 工具分发\n\n```python\nTOOL_HANDLERS = {\n \"bash\": run_bash,\n \"read_file\": run_read,\n \"write_file\": run_write,\n \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n# 循环里只改了一行——从硬编码 run_bash 变成查表:\nfor block in response.content:\n if block.type == \"tool_use\":\n handler = TOOL_HANDLERS[block.name] # 查表\n output = handler(**block.input) # 调用\n results.append(...)\n```\n\n加一个工具 = 在 `TOOLS` 数组加一条 + 在 `TOOL_HANDLERS` 字典加一行。循环不变。\n\n---\n\n## 多个工具调用\n\n模型经常一次返回多个 tool_use:\"读一下 a.py 和 b.py,然后列出所有 .py 文件\"。\n\n教学版按 `response.content` 原始顺序逐个执行。CC 的做法更复杂:按原始顺序切成连续 batch,batch 内并发安全的工具并行执行,batch 间严格顺序(见附录)。\n\n---\n\n## 速查\n\n| 概念 | 一句话 |\n|------|--------|\n| TOOL_HANDLERS | 工具名 → 处理函数的字典。加工具 = 加一行映射 |\n| 工具定义 | 告诉模型\"我能做什么\"的 JSON schema |\n| 多工具调用 | 模型可一次返回多个 tool_use,教学版按原始顺序逐个执行 |\n| 循环不变 | s01 的 `while True` 循环一行都没改 |\n\n---\n\n## 相对 s01 的变更\n\n| 组件 | 之前 (s01) | 之后 (s02) |\n|------|-----------|-----------|\n| 工具数量 | 1 (bash) | 5 (+read, write, edit, glob) |\n| 工具执行 | 硬编码 `run_bash()` | TOOL_HANDLERS 查表分发 |\n| 路径安全 | 无 | safe_path 校验(仅 file tools) |\n| 循环 | `while True` + `stop_reason` | 与 s01 完全一致 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s02_tool_use/code.py\n```\n\n试试这些 prompt:\n\n1. `Read the file README.md and tell me what this project is about`\n2. `Create a file called test.py that prints \"hello\", then read it back`\n3. `Find all Python files in this directory`\n4. `Read both README.md and requirements.txt, then create a summary file`\n\n观察重点:模型什么时候只调一个工具,什么时候一次调多个?多个工具调用的顺序和结果是否正确?\n\n---\n\n## 接下来\n\n现在 Agent 有 5 个专用工具。file tools 受 `safe_path` 保护,但 bash 不受限制,`rm -rf /` 还是能跑。\n\ns03 Permission → 在工具执行之前加一道门:这个操作安全吗?需要用户批准吗?\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `Tool.ts`、`tools.ts`、`toolOrchestration.ts`、`toolExecution.ts`、`StreamingToolExecutor.ts` 的核查。\n\n### 一、工具定义方式\n\n**教学版**:`TOOLS` 数组 + `TOOL_HANDLERS` 字典。定义和实现分开。\n**CC**:每个工具是 `buildTool()` 创建的独立对象,包含 schema、验证、权限、执行。`getAllBaseTools()` 汇总所有工具。\n\n教学版的分离方式对教学更清晰——读者一眼看到\"加一个工具 = 两条定义\"。\n\n### 二、并发安全判断:isConcurrencySafe()\n\n![Tool Concurrency](/course-assets/s02_tool_use/concurrency-comparison.svg)\n\n教学版按原始顺序逐个执行,不做并发。CC 用 `isConcurrencySafe(input)` 判断能否并发——注意这不是简单的\"只读 vs 写\",而是按具体输入判断:\n\n| | isReadOnly | isConcurrencySafe |\n|---|---|---|\n| FileRead | true | true |\n| Glob | true | true |\n| Bash `ls` | true | **true** ← 关键差异 |\n| Bash `rm` | false | false |\n| TaskCreate | false | **true** ← 改状态但可并发(TaskCreate 在 s12 介绍) |\n\nCC 的 Bash tool 的 `isConcurrencySafe` 等于 `isReadOnly`——只读命令可并发,写命令不可。TaskCreate 虽然改了任务文件,但每次都写不同的文件,所以可以并发。\n\n### 三、分区算法\n\nCC 的 `partitionToolCalls()`(`toolOrchestration.ts:91-115`)不是分两组,而是把工具调用**按连续块分批**:\n\n```\n[read A, read B, glob *.py, bash \"rm x\", read C]\n → batch1(并发): [read A, read B, glob *.py]\n → batch2(串行): [bash \"rm x\"]\n → batch3(并发): [read C]\n```\n\n并发安全的连续块编入同一个 batch,batch 内真正并发执行(`toolOrchestration.ts:152-176`,有并发上限)。遇到非并发安全的就开新 batch 串行执行。batch 之间严格顺序。\n\n### 四、验证管线\n\nCC 的每个工具调用经过严格的 5 步验证(`toolExecution.ts`):\n\n1. **Zod schema 验证**(`614-680`,教学版用 JSON Schema 替代):参数类型/结构检查\n2. **工具级 validateInput()**(`682-733`):参数值验证(如路径是否在工作区内)\n3. **PreToolUse hooks**(`800-862`,s04 详细介绍):钩子可以返回消息、修改输入、阻止执行\n4. **权限检查**(`921-931`,s03 的核心内容):canUseTool + checkPermissions → allow/deny/ask\n5. **执行 tool.call()**(`1207-1222`)\n\n教学版省略了 Zod(用 JSON Schema)、省略了 validateInput(用安全函数)、保留了权限检查和钩子概念。\n\n### 五、流式工具执行\n\nCC 的 `StreamingToolExecutor`(`StreamingToolExecutor.ts`)让工具在模型还在生成时就启动——不等模型说完。`read_file` 可能在模型还在输出\"我来分析\"的时候就跑完了。教学版不实现这个,目标和 s01 一致——概念清晰,不追求性能极致。\n\n### 六、工具结果持久化\n\n每个工具有一个 `maxResultSizeChars` 字段。结果超过这个值就落盘,模型看到的是预览 + 文件路径。FileRead 特殊——设为 `Infinity`,防止读文件的输出又被当成文件落盘。具体来说,如果 FileRead 的结果超过阈值被落盘,模型下次读那个落盘文件时又会触发落盘 → 无限循环(读文件 → 落盘 → 再读 → 再落盘 → ...)。\n\n
\n\n\n" + "content": "# s02: Tool Use — 多加一个工具,只加一行\n\ns01 → `s02` → [s03](/zh/s03) → s04 → ... → s20 → s21\n> *\"加一个工具, 只加一个 handler\"* — 循环不用动, 新工具注册进 dispatch map 就行。\n>\n> **Harness 层**: 工具分发 — 扩展模型能触达的边界。\n\n---\n\n## 只有 bash 一个工具\n\ns01 的 Agent 只有一个 bash 工具。读文件要 `cat`,写文件要 `echo \"...\" > file.py`,改文件要 `sed`。\n\n模型想的是\"读这个文件\",却要拼出 `cat path/to/file`。多了一层翻译,浪费 token,还容易拼错。\n\n---\n\n## 全局视角:工具分发\n\n![Tool Dispatch](/course-assets/s02_tool_use/tool-dispatch.svg)\n\ns01 的循环完全保留(LLM 调用、stop_reason 判断、消息追加)。唯一的变动在工具执行那 1 行:`run_bash()` 替换为 `TOOL_HANDLERS[block.name]()` 查表分发。\n\n给 Agent 加一个工具只需要做两件事:\n\n1. **定义工具**:在 `TOOLS` 数组里加一条描述\n2. **注册处理函数**:在 `TOOL_HANDLERS` 字典里加一个映射\n\n---\n\n## 从 1 个工具到 5 个工具\n\ns01 只有一个 bash:\n\n```python\nTOOLS = [{\"name\": \"bash\", ...}]\n\ndef run_bash(command): ...\n```\n\ns02 加到 5 个,每个工具都是独立定义:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\", ...},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\", ...},\n {\"name\": \"write_file\", \"description\": \"Write content to file.\", ...},\n {\"name\": \"edit_file\", \"description\": \"Replace text in file once.\", ...},\n {\"name\": \"glob\", \"description\": \"Find files by pattern.\", ...},\n]\n```\n\n每个工具有自己的实现函数:\n\n```python\ndef run_read(path, limit=None):\n lines = safe_path(path).read_text().splitlines()\n if limit:\n lines = lines[:limit]\n return \"\\n\".join(lines)\n\ndef run_write(path, content):\n safe_path(path).write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n\ndef run_edit(path, old_text, new_text):\n text = safe_path(path).read_text()\n if old_text not in text:\n return \"Error: text not found\"\n safe_path(path).write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n\ndef run_glob(pattern):\n import glob as g\n return \"\\n\".join(g.glob(pattern, root_dir=WORKDIR))\n```\n\n---\n\n## 工具分发\n\n```python\nTOOL_HANDLERS = {\n \"bash\": run_bash,\n \"read_file\": run_read,\n \"write_file\": run_write,\n \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n# 循环里只改了一行——从硬编码 run_bash 变成查表:\nfor block in response.content:\n if block.type == \"tool_use\":\n handler = TOOL_HANDLERS[block.name] # 查表\n output = handler(**block.input) # 调用\n results.append(...)\n```\n\n加一个工具 = 在 `TOOLS` 数组加一条 + 在 `TOOL_HANDLERS` 字典加一行。循环不变。\n\n---\n\n## 多个工具调用\n\n模型经常一次返回多个 tool_use:\"读一下 a.py 和 b.py,然后列出所有 .py 文件\"。\n\n这些调用按照 `response.content` 中的原始顺序逐个执行。\n\n---\n\n## 速查\n\n| 概念 | 一句话 |\n|------|--------|\n| TOOL_HANDLERS | 工具名 → 处理函数的字典。加工具 = 加一行映射 |\n| 工具定义 | 告诉模型\"我能做什么\"的 JSON schema |\n| 多工具调用 | 模型可一次返回多个 tool_use,并按原始顺序逐个执行 |\n| 循环不变 | s01 的 `while True` 循环一行都没改 |\n\n---\n\n## 相对 s01 的变更\n\n| 组件 | 之前 (s01) | 之后 (s02) |\n|------|-----------|-----------|\n| 工具数量 | 1 (bash) | 5 (+read, write, edit, glob) |\n| 工具执行 | 硬编码 `run_bash()` | TOOL_HANDLERS 查表分发 |\n| 路径安全 | 无 | safe_path 校验(仅 file tools) |\n| 循环 | `while True` + `stop_reason` | 与 s01 完全一致 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s02_tool_use/code.py\n```\n\n试试这些 prompt:\n\n1. `Read the file README.md and tell me what this project is about`\n2. `Create a file called test.py that prints \"hello\", then read it back`\n3. `Find all Python files in this directory`\n4. `Read both README.md and requirements.txt, then create a summary file`\n\n观察重点:模型什么时候只调一个工具,什么时候一次调多个?多个工具调用的顺序和结果是否正确?\n\n---\n\n## 接下来\n\n现在 Agent 有 5 个专用工具。file tools 受 `safe_path` 保护,但 bash 不受限制,`rm -rf /` 还是能跑。\n\ns03 Permission → 在工具执行之前加一道门:这个操作安全吗?需要用户批准吗?\n\n\n\n" }, { "version": "s02", "locale": "ja", "title": "s02: Tool Use — ツール一つ追加、一行追加だけ", - "content": "# s02: Tool Use — ツール一つ追加、一行追加だけ\n\ns01 → `s02` → [s03](/ja/s03) → s04 → ... → s20 → s21 → s22\n> *\"ツールを一つ追加、ハンドラを一つ追加\"* — ループはそのまま。新しいツールをディスパッチマップに登録するだけ。\n>\n> **Harness レイヤー**: ツールディスパッチ — モデルが触れる範囲を拡張。\n\n---\n\n## ツールは bash 一つだけ\n\ns01 の Agent には bash 一つのツールしかない。ファイルを読むには `cat`、書くには `echo \"...\" > file.py`、編集するには `sed`。\n\nモデルは「このファイルを読みたい」と考えながら、`cat path/to/file` と組み立てなければならない。翻訳の層が一つ増え、トークンを無駄にし、エラーも起きやすい。\n\n---\n\n## 概要:ツールディスパッチ\n\n![Tool Dispatch](/course-assets/s02_tool_use/tool-dispatch.ja.svg)\n\ns01 のループは完全に保持される(LLM 呼び出し、stop_reason 判定、メッセージ追加 — 一文字も変更なし)。唯一の変更点はツール実行の 1 行:`run_bash()` が `TOOL_HANDLERS[block.name]()` の検索ディスパッチに置き換わる。\n\nAgent にツールを追加するには、たった二つ:\n\n1. **ツールを定義**:`TOOLS` 配列に一条を追加\n2. **ハンドラを登録**:`TOOL_HANDLERS` 辞書に一つのマッピングを追加\n\n---\n\n## 1 つのツールから 5 つのツールへ\n\ns01 には bash だけだった:\n\n```python\nTOOLS = [{\"name\": \"bash\", ...}]\n\ndef run_bash(command): ...\n```\n\ns02 では 5 つに増え、各ツールは独立して定義される:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\", ...},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\", ...},\n {\"name\": \"write_file\", \"description\": \"Write content to file.\", ...},\n {\"name\": \"edit_file\", \"description\": \"Replace text in file once.\", ...},\n {\"name\": \"glob\", \"description\": \"Find files by pattern.\", ...},\n]\n```\n\n各ツールには専用の実装関数がある:\n\n```python\ndef run_read(path, limit=None):\n lines = safe_path(path).read_text().splitlines()\n if limit:\n lines = lines[:limit]\n return \"\\n\".join(lines)\n\ndef run_write(path, content):\n safe_path(path).write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n\ndef run_edit(path, old_text, new_text):\n text = safe_path(path).read_text()\n if old_text not in text:\n return \"Error: text not found\"\n safe_path(path).write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n\ndef run_glob(pattern):\n import glob as g\n return \"\\n\".join(g.glob(pattern, root_dir=WORKDIR))\n```\n\n---\n\n## ツールディスパッチ\n\n```python\nTOOL_HANDLERS = {\n \"bash\": run_bash,\n \"read_file\": run_read,\n \"write_file\": run_write,\n \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n# ループ内で変更されたのは一行だけ — ハードコードの run_bash から検索ディスパッチへ:\nfor block in response.content:\n if block.type == \"tool_use\":\n handler = TOOL_HANDLERS[block.name] # 検索\n output = handler(**block.input) # 呼び出し\n results.append(...)\n```\n\nツールの追加 = `TOOLS` 配列に一条 + `TOOL_HANDLERS` 辞書に一行。ループは変わらない。\n\n---\n\n## 複数のツール呼び出し\n\nモデルはよく一度に複数の tool_use を返す — 「a.py と b.py を読んで、全 .py ファイルを列挙して」。\n\n教育版は `response.content` の元の順序で一つずつ実行する。CC のやり方はより複雑:元の順序を保ったまま連続バッチに分割し、バッチ内の並列安全なツールを並行実行し、バッチ間は厳密に順次(付録を参照)。\n\n---\n\n## 速查\n\n| 概念 | 一言で |\n|------|--------|\n| TOOL_HANDLERS | ツール名 → ハンドラ関数の辞書。ツール追加 = マッピング一行追加 |\n| ツール定義 | モデルに「何ができるか」を伝える JSON schema |\n| 複数ツール呼び出し | モデルは一度に複数の tool_use を返す可能性がある。教育版は元の順序で一つずつ実行 |\n| ループ不変 | s01 の `while True` ループ — 一行も変更なし |\n\n---\n\n## s01 からの変更\n\n| コンポーネント | 変更前 (s01) | 変更後 (s02) |\n|--------------|-------------|-------------|\n| ツール数 | 1 (bash) | 5 (+read, write, edit, glob) |\n| ツール実行 | ハードコード `run_bash()` | TOOL_HANDLERS 検索ディスパッチ |\n| パス安全性 | なし | safe_path 検証(file tools のみ) |\n| ループ | `while True` + `stop_reason` | s01 と完全に同一 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s02_tool_use/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Read the file README.md and tell me what this project is about`\n2. `Create a file called test.py that prints \"hello\", then read it back`\n3. `Find all Python files in this directory`\n4. `Read both README.md and requirements.txt, then create a summary file`\n\n観察のポイント:モデルがツールを一つだけ呼び出すときと、複数同時に呼び出すときの違い。複数のツール呼び出しは正しい順序で実行されているか?\n\n---\n\n## 次へ\n\nAgent は 5 つの専用ツールを持つようになった。file tools は `safe_path` で保護されるが、bash は制限なし — `rm -rf /` はまだ実行できる。\n\n→ s03 Permission:ツール実行前にゲートを追加 — この操作は安全か? ユーザーの承認が必要か?\n\n
\nCC ソースコードを深掘り\n\n> 以下は CC ソースコード `Tool.ts`、`tools.ts`、`toolOrchestration.ts`、`toolExecution.ts`、`StreamingToolExecutor.ts` の検証に基づく。\n\n### 一、ツール定義方式\n\n**教育版**:`TOOLS` 配列 + `TOOL_HANDLERS` 辞書。定義と実装が分離。\n**CC**:各ツールは `buildTool()` で作成された独立オブジェクトで、schema、バリデーション、権限、実行を含む。`getAllBaseTools()` が全ツールを集約。\n\n教育版の分離方式は教学に適している — 読者は「ツール追加 = 二つの定義」と一目で分かる。\n\n### 二、並列安全性:isConcurrencySafe()\n\n![Tool Concurrency](/course-assets/s02_tool_use/concurrency-comparison.ja.svg)\n\n教育版は元の順序で一つずつ実行し、並列処理は行わない。CC は `isConcurrencySafe(input)` で並列可否を判断する — これは単なる「読み取り専用 vs 書き込み」ではなく、具体的な入力で判断する:\n\n| | isReadOnly | isConcurrencySafe |\n|---|---|---|\n| FileRead | true | true |\n| Glob | true | true |\n| Bash `ls` | true | **true** ← 重要な違い |\n| Bash `rm` | false | false |\n| TaskCreate | false | **true** ← 状態変更するが並列可能(s12 で紹介) |\n\nCC の Bash ツールの `isConcurrencySafe` は `isReadOnly` と同じ — 読み取り専用コマンドは並列可能、書き込みコマンドは不可。TaskCreate はタスクファイルを変更するが、毎回異なるファイルに書き込むため並列可能。\n\n### 三、パーティションアルゴリズム\n\nCC の `partitionToolCalls()`(`toolOrchestration.ts:91-115`)は二つのグループに分けるのではなく、ツール呼び出しを**連続ブロックごとにバッチ化**する:\n\n```\n[read A, read B, glob *.py, bash \"rm x\", read C]\n → batch1(並列): [read A, read B, glob *.py]\n → batch2(直列): [bash \"rm x\"]\n → batch3(並列): [read C]\n```\n\n連続する並列安全な呼び出しを同じバッチにまとめ、真の並列実行を行う(`toolOrchestration.ts:152-176`、並列数上限あり)。非並列安全な呼び出しに遭遇すると新しいバッチを開始して直列実行。バッチ間は厳密に順次。\n\n### 四、バリデーションパイプライン\n\nCC の各ツール呼び出しは厳格な 5 段階のバリデーションを経る(`toolExecution.ts`):\n\n1. **Zod schema バリデーション**(`614-680`、教育版は JSON Schema で代替):パラメータの型/構造チェック\n2. **ツールレベル validateInput()**(`682-733`):パラメータ値の検証(例:パスが作業ディレクトリ内か)\n3. **PreToolUse フック**(`800-862`、s04 で詳解):フックはメッセージの返却、入力の変更、実行のブロックが可能\n4. **権限チェック**(`921-931`、s03 の核心):canUseTool + checkPermissions → allow/deny/ask\n5. **tool.call() の実行**(`1207-1222`)\n\n教育版は Zod を省略(JSON Schema を使用)、validateInput を省略(安全関数を使用)、権限チェックとフック概念は保持。\n\n### 五、ストリーミングツール実行\n\nCC の `StreamingToolExecutor`(`StreamingToolExecutor.ts`)はモデルがまだ生成中にツールを起動する — モデルの完了を待たない。`read_file` はモデルが「分析します」と出力中に完了するかもしれない。教育版はこれを実装しない。s01 と同じ目標 — 概念の明確さ、極限のパフォーマンスではない。\n\n### 六、ツール結果の永続化\n\n各ツールには `maxResultSizeChars` フィールドがある。この閾値を超える結果はディスクに保存され、モデルにはプレビュー + ファイルパスが表示される。FileRead は特殊 — `Infinity` に設定され、ファイル読み出し結果の再永続化を防ぐ。具体的には、FileRead の結果が閾値を超えて永続化されると、モデルがその永続化ファイルを次に読むときにまた永続化がトリガーされ → 無限ループ(ファイル読む → 永続化 → 再読み → 再永続化 → ...)になる。\n\n
\n\n\n" + "content": "# s02: Tool Use — ツール一つ追加、一行追加だけ\n\ns01 → `s02` → [s03](/ja/s03) → s04 → ... → s20 → s21\n> *\"ツールを一つ追加、ハンドラを一つ追加\"* — ループはそのまま。新しいツールをディスパッチマップに登録するだけ。\n>\n> **Harness レイヤー**: ツールディスパッチ — モデルが触れる範囲を拡張。\n\n---\n\n## ツールは bash 一つだけ\n\ns01 の Agent には bash 一つのツールしかない。ファイルを読むには `cat`、書くには `echo \"...\" > file.py`、編集するには `sed`。\n\nモデルは「このファイルを読みたい」と考えながら、`cat path/to/file` と組み立てなければならない。翻訳の層が一つ増え、トークンを無駄にし、エラーも起きやすい。\n\n---\n\n## 概要:ツールディスパッチ\n\n![Tool Dispatch](/course-assets/s02_tool_use/tool-dispatch.ja.svg)\n\ns01 のループは完全に保持される(LLM 呼び出し、stop_reason 判定、メッセージ追加 — 一文字も変更なし)。唯一の変更点はツール実行の 1 行:`run_bash()` が `TOOL_HANDLERS[block.name]()` の検索ディスパッチに置き換わる。\n\nAgent にツールを追加するには、たった二つ:\n\n1. **ツールを定義**:`TOOLS` 配列に一条を追加\n2. **ハンドラを登録**:`TOOL_HANDLERS` 辞書に一つのマッピングを追加\n\n---\n\n## 1 つのツールから 5 つのツールへ\n\ns01 には bash だけだった:\n\n```python\nTOOLS = [{\"name\": \"bash\", ...}]\n\ndef run_bash(command): ...\n```\n\ns02 では 5 つに増え、各ツールは独立して定義される:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\", ...},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\", ...},\n {\"name\": \"write_file\", \"description\": \"Write content to file.\", ...},\n {\"name\": \"edit_file\", \"description\": \"Replace text in file once.\", ...},\n {\"name\": \"glob\", \"description\": \"Find files by pattern.\", ...},\n]\n```\n\n各ツールには専用の実装関数がある:\n\n```python\ndef run_read(path, limit=None):\n lines = safe_path(path).read_text().splitlines()\n if limit:\n lines = lines[:limit]\n return \"\\n\".join(lines)\n\ndef run_write(path, content):\n safe_path(path).write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n\ndef run_edit(path, old_text, new_text):\n text = safe_path(path).read_text()\n if old_text not in text:\n return \"Error: text not found\"\n safe_path(path).write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n\ndef run_glob(pattern):\n import glob as g\n return \"\\n\".join(g.glob(pattern, root_dir=WORKDIR))\n```\n\n---\n\n## ツールディスパッチ\n\n```python\nTOOL_HANDLERS = {\n \"bash\": run_bash,\n \"read_file\": run_read,\n \"write_file\": run_write,\n \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n# ループ内で変更されたのは一行だけ — ハードコードの run_bash から検索ディスパッチへ:\nfor block in response.content:\n if block.type == \"tool_use\":\n handler = TOOL_HANDLERS[block.name] # 検索\n output = handler(**block.input) # 呼び出し\n results.append(...)\n```\n\nツールの追加 = `TOOLS` 配列に一条 + `TOOL_HANDLERS` 辞書に一行。ループは変わらない。\n\n---\n\n## 複数のツール呼び出し\n\nモデルはよく一度に複数の tool_use を返す — 「a.py と b.py を読んで、全 .py ファイルを列挙して」。\n\nこれらの呼び出しは、`response.content` に現れる元の順序で一つずつ実行する。\n\n---\n\n## 速查\n\n| 概念 | 一言で |\n|------|--------|\n| TOOL_HANDLERS | ツール名 → ハンドラ関数の辞書。ツール追加 = マッピング一行追加 |\n| ツール定義 | モデルに「何ができるか」を伝える JSON schema |\n| 複数ツール呼び出し | モデルは一度に複数の tool_use を返す可能性があり、元の順序で一つずつ実行する |\n| ループ不変 | s01 の `while True` ループ — 一行も変更なし |\n\n---\n\n## s01 からの変更\n\n| コンポーネント | 変更前 (s01) | 変更後 (s02) |\n|--------------|-------------|-------------|\n| ツール数 | 1 (bash) | 5 (+read, write, edit, glob) |\n| ツール実行 | ハードコード `run_bash()` | TOOL_HANDLERS 検索ディスパッチ |\n| パス安全性 | なし | safe_path 検証(file tools のみ) |\n| ループ | `while True` + `stop_reason` | s01 と完全に同一 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s02_tool_use/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Read the file README.md and tell me what this project is about`\n2. `Create a file called test.py that prints \"hello\", then read it back`\n3. `Find all Python files in this directory`\n4. `Read both README.md and requirements.txt, then create a summary file`\n\n観察のポイント:モデルがツールを一つだけ呼び出すときと、複数同時に呼び出すときの違い。複数のツール呼び出しは正しい順序で実行されているか?\n\n---\n\n## 次へ\n\nAgent は 5 つの専用ツールを持つようになった。file tools は `safe_path` で保護されるが、bash は制限なし — `rm -rf /` はまだ実行できる。\n\n→ s03 Permission:ツール実行前にゲートを追加 — この操作は安全か? ユーザーの承認が必要か?\n\n\n\n" }, { "version": "s03", "locale": "en", "title": "s03: Permission — Check Permissions Before Execution", - "content": "# s03: Permission — Check Permissions Before Execution\n\ns01 → s02 → `s03` → [s04](/en/s04) → s05 → ... → s20 → s21 → s22\n> *\"Check permissions before executing\"* — The permission pipeline decides which operations need approval.\n>\n> **Harness Layer**: Permission — a gate before tool execution.\n\n---\n\n## The Problem\n\ns02's Agent has 5 tools. File tools are protected by `safe_path`, but bash is unrestricted. Ask it to \"clean up the project,\" and it might run `rm -rf /`.\n\nSafety can't rely on trusting the model — it needs code: a check before every tool execution.\n\n---\n\n## The Solution\n\n![Permission Overview](/course-assets/s03_permission/permission-overview.en.svg)\n\ns02's loop is fully preserved. The only change is inserting `check_permission()` before tool execution — each tool call passes through three gates in a fixed order: hard deny first, then soft ask, and if neither matches, allow.\n\nThe three gates correspond to three decisions:\n\n| Gate | Purpose | On Match |\n|------|---------|----------|\n| 1. Deny List | Permanently forbidden operations (`rm -rf /`, `sudo`) | Denied immediately, not executed |\n| 2. Rule Matching | Context-dependent operations (reading/writing outside workspace, `rm` files) | Passed to Gate 3 |\n| 3. User Approval | After Gate 2 matches, pauses for user confirmation | User decides allow or deny |\n\nNone of the three gates match → execute directly. Most routine operations take this path.\n\n---\n\n## How It Works\n\n![Permission Pipeline](/course-assets/s03_permission/permission-pipeline.en.svg)\n\n**Gate 1**: A hard deny list. Check first; if matched, return a block message. (Teaching demo: simple string matching is not a reliable security mechanism — command variants and shell expansion can bypass it. CC's approach is in the appendix.)\n\n```python\nDENY_LIST = [\n \"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\",\n \"mkfs\", \"dd if=\", \"> /dev/sda\",\n]\n\ndef check_deny_list(command: str) -> str | None:\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Blocked: '{pattern}' is on the deny list\"\n return None\n```\n\n**Gate 2**: Rule matching — describes \"when to ask the user.\" Each rule specifies a tool and a check condition.\n\n```python\nPERMISSION_RULES = [\n {\n \"tools\": [\"read_file\", \"write_file\", \"edit_file\"],\n \"check\": lambda args: not (WORKDIR / args.get(\"path\", \"\")).resolve().is_relative_to(WORKDIR),\n \"message\": \"Access outside workspace\",\n },\n {\n \"tools\": [\"bash\"],\n \"check\": lambda args: any(kw in args.get(\"command\", \"\") for kw in [\"rm \", \"> /etc/\", \"chmod 777\"]),\n \"message\": \"Potentially destructive command\",\n },\n]\n\ndef check_rules(tool_name: str, args: dict) -> str | None:\n for rule in PERMISSION_RULES:\n if tool_name in rule[\"tools\"] and rule[\"check\"](args):\n return rule[\"message\"]\n return None\n```\n\n**Gate 3**: After a rule matches, pause for user input.\n\n```python\ndef ask_user(tool_name: str, args: dict, reason: str) -> str:\n print(f\"\\n⚠ {reason}\")\n print(f\" Tool: {tool_name}({args})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n return \"allow\" if choice in (\"y\", \"yes\") else \"deny\"\n```\n\n**All three gates chained together**, inserted before tool execution:\n\n```python\ndef check_permission(block) -> bool:\n # Gate 1: Hard deny\n if block.name == \"bash\":\n reason = check_deny_list(block.input.get(\"command\", \"\"))\n if reason:\n print(f\"\\n⛔ {reason}\")\n return False\n\n # Gate 2 + 3: Rule matching → User approval\n reason = check_rules(block.name, block.input)\n if reason:\n decision = ask_user(block.name, block.input, reason)\n if decision == \"deny\":\n return False\n\n return True\n\n# In agent_loop — s02's loop with just one line added:\nfor block in response.content:\n if block.type == \"tool_use\":\n if not check_permission(block): # ← NEW\n results.append({... \"content\": \"Permission denied.\"})\n continue\n output = TOOL_HANDLERS[block.name](**block.input) # s02 original\n results.append(...)\n```\n\n---\n\n## Changes from s02\n\n| Component | Before (s02) | After (s03) |\n|-----------|-------------|-------------|\n| Security model | None (trust the model) | Three-gate permission pipeline |\n| New functions | — | check_deny_list, check_rules, ask_user, check_permission |\n| Loop | Executes all tools directly | Inserts check_permission() before execution |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s03_permission/code.py\n```\n\nTry these prompts:\n\n1. `Create a file called test.txt in the current directory` (should pass through)\n2. `Delete the file test.txt` (bash + rm triggers Gate 2)\n3. `What files are in the current directory?` (read-only, all pass)\n4. `Try to write a file to /etc/something` (writing outside workspace triggers Gate 2)\n\nWhat to watch for: Which operations pass through? Which need your confirmation? Which are denied outright?\n\n---\n\n## What's Next\n\nPermission checks are in place — but every check is hardcoded as `check_permission()` inside the loop. What if you want to add logging before and after each tool execution? What if you want to auto-trigger a git commit after certain operations? Scattering this extension logic throughout the loop makes it bloat.\n\n→ s04 Hooks: Add hooks to the loop. Extension logic hangs on hooks; the loop stays clean.\n\n
\nDive into CC Source Code\n\n> The following is based on a review of CC source code `types/permissions.ts`, `utils/permissions/permissions.ts`, `toolExecution.ts`, `utils/permissions/yoloClassifier.ts`, `tools/AgentTool/forkSubagent.ts`.\n\n### 1. PermissionResult: Not 3, but 4\n\nThe teaching version's three gates (deny → ask → allow) don't fully correspond to CC. CC's `PermissionResult` has 4 behaviors (`types/permissions.ts:241-266`):\n\n| behavior | Meaning | Teaching Version Equivalent |\n|----------|---------|---------------------------|\n| `allow` | Allow directly | Gate 3 passes |\n| `deny` | Deny directly | Gate 1 matches |\n| `ask` | Show dialog to user | Gate 2 matches |\n| `passthrough` | Tool doesn't express opinion, passes to generic pipeline | Not in teaching version |\n\n### 2. Production Verification Stages\n\nCC's tool calls don't go through three gates — they go through multiple stages distributed across `checkPermissionsAndCallTool()` (`toolExecution.ts:599-1745`), hooks, `hasPermissionsToUseToolInner()` (`utils/permissions/permissions.ts:1158-1310`), and classifier logic:\n\n1. **Zod schema validation** (`toolExecution.ts:614-680`) — parameter type checking\n2. **validateInput()** (`toolExecution.ts:682-733`) — tool-level semantic validation\n3. **backfillObservableInput()** (`toolExecution.ts:784`) — backfill legacy fields\n4. **PreToolUse hooks** (`toolExecution.ts:800-862`) — hooks can return allow/deny/ask\n5. **resolveHookPermissionDecision()** (`toolExecution.ts:921-931`) — coordinate hook + pipeline decisions\n6. **hasPermissionsToUseToolInner()** (`permissions.ts:1158-1310`) — multi-layer rule check:\n - Entire tool disabled by deny rule → `deny`\n - Entire tool flagged by ask rule → `ask`\n - `tool.checkPermissions()` tool's own judgment\n - Tool itself returns deny → `deny`\n - `requiresUserInteraction()` → `ask`\n - Content-related ask rules → `ask` (not bypassable)\n - Security check violation → `ask` (not bypassable)\n - bypassPermissions mode → `allow`\n - Entire tool allowed by allow rule → `allow`\n - passthrough → converted to `ask`\n\n### 3. Deny List: Not One File, but 8 Sources\n\nCC doesn't have a single deny list. Permission rules come from 8 sources (`types/permissions.ts:54-62`):\n\n| Source | Configuration Location |\n|--------|----------------------|\n| `userSettings` | `~/.claude/settings.json` |\n| `projectSettings` | `.claude/settings.json` |\n| `localSettings` | `settings.local.json` |\n| `flagSettings` | Feature flags |\n| `policySettings` | Enterprise management policy |\n| `cliArg` | `--allowedTools` / `--deniedTools` |\n| `command` | Inline command |\n| `session` | In-session temporary authorization |\n\nEach rule format: `{ toolName: \"Bash\", ruleBehavior: \"deny\", ruleContent: \"npm publish:*\" }`. Rules from multiple sources are merged, with higher-priority sources overriding lower ones (low to high: user < project < local < flag < policy, plus cliArg, command, session).\n\n### 4. What is isDestructive()\n\nIn CC, `isDestructive` (`Tool.ts:405-406`) is **purely for UI display** — showing a `[destructive]` label in the tool list. It doesn't participate in permission decisions. All tools return `false` by default. Only ExitWorktree (on remove) and MCP tools (depending on `annotations.destructiveHint`) override it.\n\n### 5. YoloClassifier (Auto-Approval)\n\nIn CC's auto mode, it doesn't pop a dialog every time. `classifyYoloAction` (`utils/permissions/yoloClassifier.ts:1012`) sends the tool call + conversation context to a classifier LLM to judge safety. It first tries acceptEdits mode simulation (`permissions.ts:620-656`, if acceptEdits allows → auto-approve), then checks the safe tool whitelist (`permissions.ts:658-686`), and finally calls the classifier. If the classifier rejects too many times in a row → falls back to manual approval.\n\n### 6. Permission Bubbling\n\nA sub-Agent's (forked via AgentTool) `permissionMode` is set to `'bubble'` (`forkSubagent.ts:50`). This means permission dialogs **bubble up to the parent Agent's terminal**, rather than being silently denied in the sub-Agent. The Bash classifier continues running during this process — displaying the permission dialog while judging in the background whether auto-approval is possible.\n\n### The Teaching Version's Simplification Is Intentional\n\n- Multi-stage pipeline → 3 gates: dramatically lower barrier to understanding\n- 8 rule sources → 1 local DENY_LIST: manageable concept count\n- isDestructive → omitted (teaching version has no UI layer, and it doesn't participate in permission decisions in CC either)\n- YoloClassifier → omitted (depends on additional LLM calls and telemetry)\n- Permission bubbling → omitted (s15 covers multi-Agent)\n\n
\n\n\n" + "content": "# s03: Permission — Check Permissions Before Execution\n\ns01 → s02 → `s03` → [s04](/en/s04) → s05 → ... → s20 → s21\n> *\"Check permissions before executing\"* — The permission pipeline decides which operations need approval.\n>\n> **Harness Layer**: Permission — a gate before tool execution.\n\n---\n\n## The Problem\n\ns02's Agent has 5 tools. File tools are protected by `safe_path`, but bash is unrestricted. Ask it to \"clean up the project,\" and it might run `rm -rf /`.\n\nSafety can't rely on trusting the model — it needs code: a check before every tool execution.\n\n---\n\n## The Solution\n\n![Permission Overview](/course-assets/s03_permission/permission-overview.en.svg)\n\ns02's loop is fully preserved. The only change is inserting `check_permission()` before tool execution — each tool call passes through three gates in a fixed order: hard deny first, then soft ask, and if neither matches, allow.\n\nThe three gates correspond to three decisions:\n\n| Gate | Purpose | On Match |\n|------|---------|----------|\n| 1. Deny List | Permanently forbidden operations (`rm -rf /`, `sudo`) | Denied immediately, not executed |\n| 2. Rule Matching | Context-dependent operations (reading/writing outside workspace, `rm` files) | Passed to Gate 3 |\n| 3. User Approval | After Gate 2 matches, pauses for user confirmation | User decides allow or deny |\n\nNone of the three gates match → execute directly. Most routine operations take this path.\n\n---\n\n## How It Works\n\n![Permission Pipeline](/course-assets/s03_permission/permission-pipeline.en.svg)\n\n**Gate 1**: A hard deny list. Check first; if matched, return a block message. This list uses simple string matching to show where the permission gate sits; it is not a complete security boundary.\n\n```python\nDENY_LIST = [\n \"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\",\n \"mkfs\", \"dd if=\", \"> /dev/sda\",\n]\n\ndef check_deny_list(command: str) -> str | None:\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Blocked: '{pattern}' is on the deny list\"\n return None\n```\n\n**Gate 2**: Rule matching — describes \"when to ask the user.\" Each rule specifies a tool and a check condition.\n\n```python\nPERMISSION_RULES = [\n {\n \"tools\": [\"read_file\", \"write_file\", \"edit_file\"],\n \"check\": lambda args: not (WORKDIR / args.get(\"path\", \"\")).resolve().is_relative_to(WORKDIR),\n \"message\": \"Access outside workspace\",\n },\n {\n \"tools\": [\"bash\"],\n \"check\": lambda args: any(kw in args.get(\"command\", \"\") for kw in [\"rm \", \"> /etc/\", \"chmod 777\"]),\n \"message\": \"Potentially destructive command\",\n },\n]\n\ndef check_rules(tool_name: str, args: dict) -> str | None:\n for rule in PERMISSION_RULES:\n if tool_name in rule[\"tools\"] and rule[\"check\"](args):\n return rule[\"message\"]\n return None\n```\n\n**Gate 3**: After a rule matches, pause for user input.\n\n```python\ndef ask_user(tool_name: str, args: dict, reason: str) -> str:\n print(f\"\\n⚠ {reason}\")\n print(f\" Tool: {tool_name}({args})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n return \"allow\" if choice in (\"y\", \"yes\") else \"deny\"\n```\n\n**All three gates chained together**, inserted before tool execution:\n\n```python\ndef check_permission(block) -> bool:\n # Gate 1: Hard deny\n if block.name == \"bash\":\n reason = check_deny_list(block.input.get(\"command\", \"\"))\n if reason:\n print(f\"\\n⛔ {reason}\")\n return False\n\n # Gate 2 + 3: Rule matching → User approval\n reason = check_rules(block.name, block.input)\n if reason:\n decision = ask_user(block.name, block.input, reason)\n if decision == \"deny\":\n return False\n\n return True\n\n# In agent_loop — s02's loop with just one line added:\nfor block in response.content:\n if block.type == \"tool_use\":\n if not check_permission(block): # ← NEW\n results.append({... \"content\": \"Permission denied.\"})\n continue\n output = TOOL_HANDLERS[block.name](**block.input) # s02 original\n results.append(...)\n```\n\n---\n\n## Changes from s02\n\n| Component | Before (s02) | After (s03) |\n|-----------|-------------|-------------|\n| Security model | None (trust the model) | Three-gate permission pipeline |\n| New functions | — | check_deny_list, check_rules, ask_user, check_permission |\n| Loop | Executes all tools directly | Inserts check_permission() before execution |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s03_permission/code.py\n```\n\nTry these prompts:\n\n1. `Create a file called test.txt in the current directory` (should pass through)\n2. `Delete the file test.txt` (bash + rm triggers Gate 2)\n3. `What files are in the current directory?` (read-only, all pass)\n4. `Try to write a file to /etc/something` (writing outside workspace triggers Gate 2)\n\nWhat to watch for: Which operations pass through? Which need your confirmation? Which are denied outright?\n\n---\n\n## What's Next\n\nPermission checks are in place — but every check is hardcoded as `check_permission()` inside the loop. What if you want to add logging before and after each tool execution? What if you want to auto-trigger a git commit after certain operations? Scattering this extension logic throughout the loop makes it bloat.\n\n→ s04 Hooks: Add hooks to the loop. Extension logic hangs on hooks; the loop stays clean.\n\n\n\n" }, { "version": "s03", "locale": "zh", "title": "s03: Permission — 执行前做权限判断", - "content": "# s03: Permission — 执行前做权限判断\n\ns01 → s02 → `s03` → [s04](/zh/s04) → s05 → ... → s20 → s21 → s22\n> *\"工具执行前先做权限判断\"* — 权限管线决定哪些操作需要审批。\n>\n> **Harness 层**: 权限 — 在工具执行前加一道门。\n\n---\n\n## 问题\n\ns02 的 Agent 有 5 个工具。file tools 受 `safe_path` 保护,但 bash 不受限制。让它\"清理一下项目\",可能执行 `rm -rf /`。\n\n安全不能靠信任模型,要靠代码——在工具执行之前做判断。\n\n---\n\n## 解决方案\n\n![Permission Overview](/course-assets/s03_permission/permission-overview.svg)\n\ns02 的循环完全保留。唯一的变动在工具执行前插入 `check_permission()`——每个工具调用经过三道闸门,顺序固定:硬拒绝优先,软询问次之,都没命中就放行。\n\n三道闸门对应三种决策:\n\n| 闸门 | 作用 | 命中后 |\n|------|------|--------|\n| 1. 拒绝列表 | 永远禁止的操作(`rm -rf /`、`sudo`) | 直接拒绝,不执行 |\n| 2. 规则匹配 | 取决于上下文的操作(读/写工作区外、`rm` 文件) | 交给闸门 3 |\n| 3. 用户审批 | 闸门 2 命中后,暂停等用户确认 | 用户决定允许或拒绝 |\n\n三道都没命中 → 直接执行。大部分日常操作走这条路。\n\n---\n\n## 工作原理\n\n![Permission Pipeline](/course-assets/s03_permission/permission-pipeline.svg)\n\n**闸门 1**:一张硬拒绝表,先查,命中就返回阻止信息。(教学示意:简单字符串匹配不是可靠安全机制,命令变体和 shell 展开可能绕过。CC 的做法见附录。)\n\n```python\nDENY_LIST = [\n \"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\",\n \"mkfs\", \"dd if=\", \"> /dev/sda\",\n]\n\ndef check_deny_list(command: str) -> str | None:\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Blocked: '{pattern}' is on the deny list\"\n return None\n```\n\n**闸门 2**:规则匹配——描述\"什么时候需要问用户\"。每条规则指定工具和检查条件。\n\n```python\nPERMISSION_RULES = [\n {\n \"tools\": [\"read_file\", \"write_file\", \"edit_file\"],\n \"check\": lambda args: not (WORKDIR / args.get(\"path\", \"\")).resolve().is_relative_to(WORKDIR),\n \"message\": \"Access outside workspace\",\n },\n {\n \"tools\": [\"bash\"],\n \"check\": lambda args: any(kw in args.get(\"command\", \"\") for kw in [\"rm \", \"> /etc/\", \"chmod 777\"]),\n \"message\": \"Potentially destructive command\",\n },\n]\n\ndef check_rules(tool_name: str, args: dict) -> str | None:\n for rule in PERMISSION_RULES:\n if tool_name in rule[\"tools\"] and rule[\"check\"](args):\n return rule[\"message\"]\n return None\n```\n\n**闸门 3**:规则命中后,暂停等用户输入。\n\n```python\ndef ask_user(tool_name: str, args: dict, reason: str) -> str:\n print(f\"\\n⚠ {reason}\")\n print(f\" Tool: {tool_name}({args})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n return \"allow\" if choice in (\"y\", \"yes\") else \"deny\"\n```\n\n**三道闸门串在一起**,插在工具执行之前:\n\n```python\ndef check_permission(block) -> bool:\n # 闸门 1: 硬拒绝\n if block.name == \"bash\":\n reason = check_deny_list(block.input.get(\"command\", \"\"))\n if reason:\n print(f\"\\n⛔ {reason}\")\n return False\n\n # 闸门 2 + 3: 规则匹配 → 用户审批\n reason = check_rules(block.name, block.input)\n if reason:\n decision = ask_user(block.name, block.input, reason)\n if decision == \"deny\":\n return False\n\n return True\n\n# 在 agent_loop 中——s02 的循环只加了一行:\nfor block in response.content:\n if block.type == \"tool_use\":\n if not check_permission(block): # ← 新增\n results.append({... \"content\": \"Permission denied.\"})\n continue\n output = TOOL_HANDLERS[block.name](**block.input) # s02 原有\n results.append(...)\n```\n\n---\n\n## 相对 s02 的变更\n\n| 组件 | 之前 (s02) | 之后 (s03) |\n|------|-----------|-----------|\n| 安全模型 | 无(信任模型) | 三道闸门权限管线 |\n| 新函数 | — | check_deny_list, check_rules, ask_user, check_permission |\n| 循环 | 直接执行所有工具 | 执行前插入 check_permission() |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s03_permission/code.py\n```\n\n试试这些 prompt:\n\n1. `Create a file called test.txt in the current directory`(应该直接通过)\n2. `Delete the file test.txt`(bash + rm 会触发闸门 2)\n3. `What files are in the current directory?`(只读,全部通过)\n4. `Try to write a file to /etc/something`(写工作区外,触发闸门 2)\n\n观察重点:哪些操作直接通过?哪些需要你确认?哪些被直接拒绝?\n\n---\n\n## 接下来\n\n权限检查做了——但每次都在循环里硬编码 `check_permission()`。如果我想在每次工具执行前后加日志?如果想在某些操作后自动触发 git commit?这些扩展逻辑散落在 loop 里,循环很快就会膨胀。\n\ns04 Hooks → 给循环加钩子,扩展逻辑挂在钩子上,循环保持干净。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `types/permissions.ts`、`utils/permissions/permissions.ts`、`toolExecution.ts`、`utils/permissions/yoloClassifier.ts`、`tools/AgentTool/forkSubagent.ts` 的核查。\n\n### 一、PermissionResult:不是 3 种,是 4 种\n\n教学版的三道闸门(deny → ask → allow)和 CC 不完全对应。CC 的 `PermissionResult` 有 4 个 behavior(`types/permissions.ts:241-266`):\n\n| behavior | 含义 | 教学版对应 |\n|----------|------|-----------|\n| `allow` | 直接允许 | 闸门 3 通过 |\n| `deny` | 直接拒绝 | 闸门 1 命中 |\n| `ask` | 弹出对话框问用户 | 闸门 2 命中 |\n| `passthrough` | 工具不表态,交给通用管线决定 | 教学版无 |\n\n### 二、生产版的验证阶段\n\nCC 的工具调用不是经过三道闸门,而是经过多个阶段,分布在 `checkPermissionsAndCallTool()`(`toolExecution.ts:599-1745`)、hooks、`hasPermissionsToUseToolInner()`(`utils/permissions/permissions.ts:1158-1310`)和 classifier 逻辑里:\n\n1. **Zod schema 验证**(`toolExecution.ts:614-680`)— 参数类型检查\n2. **validateInput()**(`toolExecution.ts:682-733`)— 工具级语义验证\n3. **backfillObservableInput()**(`toolExecution.ts:784`)— 补全遗留字段\n4. **PreToolUse hooks**(`toolExecution.ts:800-862`)— 钩子可以返回 allow/deny/ask\n5. **resolveHookPermissionDecision()**(`toolExecution.ts:921-931`)— 协调钩子+管线决策\n6. **hasPermissionsToUseToolInner()**(`permissions.ts:1158-1310`)— 多层规则检查:\n - 整个工具被 deny rule 禁用 → `deny`\n - 整个工具被 ask rule 标记 → `ask`\n - `tool.checkPermissions()` 工具自己的判断\n - 工具自己返回 deny → `deny`\n - `requiresUserInteraction()` → `ask`\n - 内容相关的 ask 规则 → `ask`(不可绕过)\n - 安全检查违规 → `ask`(不可绕过)\n - bypassPermissions 模式 → `allow`\n - 整个工具被 allow rule 放行 → `allow`\n - passthrough → 转为 `ask`\n\n### 三、拒绝列表:不是一个文件,是 8 个来源\n\nCC 没有单一的 deny list。权限规则来自 8 个来源(`types/permissions.ts:54-62`):\n\n| 来源 | 配置位置 |\n|------|---------|\n| `userSettings` | `~/.claude/settings.json` |\n| `projectSettings` | `.claude/settings.json` |\n| `localSettings` | `settings.local.json` |\n| `flagSettings` | Feature flags |\n| `policySettings` | 企业管理策略 |\n| `cliArg` | `--allowedTools` / `--deniedTools` |\n| `command` | 内联命令 |\n| `session` | 会话内临时授权 |\n\n每条规则格式:`{ toolName: \"Bash\", ruleBehavior: \"deny\", ruleContent: \"npm publish:*\" }`。多个来源的规则合并,高优先级来源覆盖低优先级(从低到高:user < project < local < flag < policy,加上 cliArg、command、session)。\n\n### 四、isDestructive() 是什么\n\nCC 中 `isDestructive`(`Tool.ts:405-406`)**纯粹是 UI 展示用的**——在工具列表里显示 `[destructive]` 标签。它不参与权限决策。默认所有工具都返回 `false`。只有 ExitWorktree(remove 时)和 MCP 工具(依赖 `annotations.destructiveHint`)覆写了它。\n\n### 五、YoloClassifier(自动审批)\n\nCC 的 auto 模式下,不会每次都弹对话框。`classifyYoloAction`(`utils/permissions/yoloClassifier.ts:1012`)把工具调用 + 对话上下文发给一个分类器 LLM 判断是否安全。先尝试 acceptEdits 模式模拟(`permissions.ts:620-656`,如果 acceptEdits 允许 → 直接批准),再查安全工具白名单(`permissions.ts:658-686`),最后才调分类器。分类器连续拒绝太多次 → 回退到人工审批。\n\n### 六、权限冒泡\n\n子 Agent(通过 AgentTool fork 出来的)的 `permissionMode` 设为 `'bubble'`(`forkSubagent.ts:50`)。意思是权限弹窗**冒泡到父 Agent 的终端**,而不是在子 Agent 里静默拒绝。Bash 分类器在这个过程中继续跑——给权限对话框显示的同时在后台判断是否可以自动批准。\n\n### 教学版的简化是刻意的\n\n- 多阶段管线 → 3 道闸门:理解门槛大幅降低\n- 8 个规则来源 → 1 个本地 DENY_LIST:概念量可控\n- isDestructive → 忽略(教学版没有 UI 层,CC 里它也不参与权限决策)\n- YoloClassifier → 省略(依赖于额外的 LLM 调用和遥测系统)\n- 权限冒泡 → 省略(s15 才涉及多 Agent)\n\n
\n\n\n" + "content": "# s03: Permission — 执行前做权限判断\n\ns01 → s02 → `s03` → [s04](/zh/s04) → s05 → ... → s20 → s21\n> *\"工具执行前先做权限判断\"* — 权限管线决定哪些操作需要审批。\n>\n> **Harness 层**: 权限 — 在工具执行前加一道门。\n\n---\n\n## 问题\n\ns02 的 Agent 有 5 个工具。file tools 受 `safe_path` 保护,但 bash 不受限制。让它\"清理一下项目\",可能执行 `rm -rf /`。\n\n安全不能靠信任模型,要靠代码——在工具执行之前做判断。\n\n---\n\n## 解决方案\n\n![Permission Overview](/course-assets/s03_permission/permission-overview.svg)\n\ns02 的循环完全保留。唯一的变动在工具执行前插入 `check_permission()`——每个工具调用经过三道闸门,顺序固定:硬拒绝优先,软询问次之,都没命中就放行。\n\n三道闸门对应三种决策:\n\n| 闸门 | 作用 | 命中后 |\n|------|------|--------|\n| 1. 拒绝列表 | 永远禁止的操作(`rm -rf /`、`sudo`) | 直接拒绝,不执行 |\n| 2. 规则匹配 | 取决于上下文的操作(读/写工作区外、`rm` 文件) | 交给闸门 3 |\n| 3. 用户审批 | 闸门 2 命中后,暂停等用户确认 | 用户决定允许或拒绝 |\n\n三道都没命中 → 直接执行。大部分日常操作走这条路。\n\n---\n\n## 工作原理\n\n![Permission Pipeline](/course-assets/s03_permission/permission-pipeline.svg)\n\n**闸门 1**:一张硬拒绝表,先查,命中就返回阻止信息。这张表使用简单字符串匹配来说明权限闸门的位置,不能视为完整的安全边界。\n\n```python\nDENY_LIST = [\n \"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\",\n \"mkfs\", \"dd if=\", \"> /dev/sda\",\n]\n\ndef check_deny_list(command: str) -> str | None:\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Blocked: '{pattern}' is on the deny list\"\n return None\n```\n\n**闸门 2**:规则匹配——描述\"什么时候需要问用户\"。每条规则指定工具和检查条件。\n\n```python\nPERMISSION_RULES = [\n {\n \"tools\": [\"read_file\", \"write_file\", \"edit_file\"],\n \"check\": lambda args: not (WORKDIR / args.get(\"path\", \"\")).resolve().is_relative_to(WORKDIR),\n \"message\": \"Access outside workspace\",\n },\n {\n \"tools\": [\"bash\"],\n \"check\": lambda args: any(kw in args.get(\"command\", \"\") for kw in [\"rm \", \"> /etc/\", \"chmod 777\"]),\n \"message\": \"Potentially destructive command\",\n },\n]\n\ndef check_rules(tool_name: str, args: dict) -> str | None:\n for rule in PERMISSION_RULES:\n if tool_name in rule[\"tools\"] and rule[\"check\"](args):\n return rule[\"message\"]\n return None\n```\n\n**闸门 3**:规则命中后,暂停等用户输入。\n\n```python\ndef ask_user(tool_name: str, args: dict, reason: str) -> str:\n print(f\"\\n⚠ {reason}\")\n print(f\" Tool: {tool_name}({args})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n return \"allow\" if choice in (\"y\", \"yes\") else \"deny\"\n```\n\n**三道闸门串在一起**,插在工具执行之前:\n\n```python\ndef check_permission(block) -> bool:\n # 闸门 1: 硬拒绝\n if block.name == \"bash\":\n reason = check_deny_list(block.input.get(\"command\", \"\"))\n if reason:\n print(f\"\\n⛔ {reason}\")\n return False\n\n # 闸门 2 + 3: 规则匹配 → 用户审批\n reason = check_rules(block.name, block.input)\n if reason:\n decision = ask_user(block.name, block.input, reason)\n if decision == \"deny\":\n return False\n\n return True\n\n# 在 agent_loop 中——s02 的循环只加了一行:\nfor block in response.content:\n if block.type == \"tool_use\":\n if not check_permission(block): # ← 新增\n results.append({... \"content\": \"Permission denied.\"})\n continue\n output = TOOL_HANDLERS[block.name](**block.input) # s02 原有\n results.append(...)\n```\n\n---\n\n## 相对 s02 的变更\n\n| 组件 | 之前 (s02) | 之后 (s03) |\n|------|-----------|-----------|\n| 安全模型 | 无(信任模型) | 三道闸门权限管线 |\n| 新函数 | — | check_deny_list, check_rules, ask_user, check_permission |\n| 循环 | 直接执行所有工具 | 执行前插入 check_permission() |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s03_permission/code.py\n```\n\n试试这些 prompt:\n\n1. `Create a file called test.txt in the current directory`(应该直接通过)\n2. `Delete the file test.txt`(bash + rm 会触发闸门 2)\n3. `What files are in the current directory?`(只读,全部通过)\n4. `Try to write a file to /etc/something`(写工作区外,触发闸门 2)\n\n观察重点:哪些操作直接通过?哪些需要你确认?哪些被直接拒绝?\n\n---\n\n## 接下来\n\n权限检查做了——但每次都在循环里硬编码 `check_permission()`。如果我想在每次工具执行前后加日志?如果想在某些操作后自动触发 git commit?这些扩展逻辑散落在 loop 里,循环很快就会膨胀。\n\ns04 Hooks → 给循环加钩子,扩展逻辑挂在钩子上,循环保持干净。\n\n\n\n" }, { "version": "s03", "locale": "ja", "title": "s03: Permission — 実行前に権限を判断する", - "content": "# s03: Permission — 実行前に権限を判断する\n\ns01 → s02 → `s03` → [s04](/ja/s04) → s05 → ... → s20 → s21 → s22\n> *\"ツール実行前に権限を判断\"* — 権限パイプラインは、どの操作に承認が必要かを決める。\n>\n> **Harness レイヤー**: 権限 — ツール実行前に一つのゲートを追加。\n\n---\n\n## 課題\n\ns02 の Agent は 5 つのツールを持つ。file tools は `safe_path` で保護されるが、bash は制限なし。「プロジェクトを掃除して」と頼むと、`rm -rf /` を実行しかねない。\n\n安全性はモデルを信頼することではなく、コードに頼る — ツール実行前に判断を挟む。\n\n---\n\n## ソリューション\n\n![Permission Overview](/course-assets/s03_permission/permission-overview.ja.svg)\n\ns02 のループは完全に維持される。唯一の変更は、ツール実行前に `check_permission()` を挿入すること — 各ツール呼び出しは 3 つのゲートを固定順序で通過する:ハード拒否が最優先、次にソフト確認、どちらも一致しなければ許可。\n\n3 つのゲートは 3 つの決定に対応する:\n\n| ゲート | 役割 | 一致時 |\n|--------|------|--------|\n| 1. 拒否リスト | 常に禁止される操作(`rm -rf /`、`sudo`) | 即座に拒否、実行しない |\n| 2. ルールマッチング | コンテキスト依存の操作(作業ディレクトリ外への読み書き、`rm` ファイル) | ゲート 3 へ |\n| 3. ユーザー承認 | ゲート 2 が一致した場合、ユーザー確認を待機 | ユーザーが許可または拒否を決定 |\n\n3 つのゲートのどれにも一致しない → 直接実行。日常の操作の大部分はこの経路を通る。\n\n---\n\n## 仕組み\n\n![Permission Pipeline](/course-assets/s03_permission/permission-pipeline.ja.svg)\n\n**ゲート 1**:ハード拒否リスト。最初に確認し、一致すればブロックメッセージを返す。(教育デモ:単純な文字列マッチングは信頼できるセキュリティ機構ではない — コマンドの変種やシェル展開で回避される可能性がある。CC のアプローチは付録を参照。)\n\n```python\nDENY_LIST = [\n \"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\",\n \"mkfs\", \"dd if=\", \"> /dev/sda\",\n]\n\ndef check_deny_list(command: str) -> str | None:\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Blocked: '{pattern}' is on the deny list\"\n return None\n```\n\n**ゲート 2**:ルールマッチング — 「いつユーザーに聞くべきか」を記述する。各ルールはツールとチェック条件を指定する。\n\n```python\nPERMISSION_RULES = [\n {\n \"tools\": [\"read_file\", \"write_file\", \"edit_file\"],\n \"check\": lambda args: not (WORKDIR / args.get(\"path\", \"\")).resolve().is_relative_to(WORKDIR),\n \"message\": \"Access outside workspace\",\n },\n {\n \"tools\": [\"bash\"],\n \"check\": lambda args: any(kw in args.get(\"command\", \"\") for kw in [\"rm \", \"> /etc/\", \"chmod 777\"]),\n \"message\": \"Potentially destructive command\",\n },\n]\n\ndef check_rules(tool_name: str, args: dict) -> str | None:\n for rule in PERMISSION_RULES:\n if tool_name in rule[\"tools\"] and rule[\"check\"](args):\n return rule[\"message\"]\n return None\n```\n\n**ゲート 3**:ルールが一致した後、ユーザー入力を待機。\n\n```python\ndef ask_user(tool_name: str, args: dict, reason: str) -> str:\n print(f\"\\n⚠ {reason}\")\n print(f\" Tool: {tool_name}({args})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n return \"allow\" if choice in (\"y\", \"yes\") else \"deny\"\n```\n\n**3 つのゲートを直列に接続**、ツール実行前に挿入する:\n\n```python\ndef check_permission(block) -> bool:\n # ゲート 1: ハード拒否\n if block.name == \"bash\":\n reason = check_deny_list(block.input.get(\"command\", \"\"))\n if reason:\n print(f\"\\n⛔ {reason}\")\n return False\n\n # ゲート 2 + 3: ルールマッチング → ユーザー承認\n reason = check_rules(block.name, block.input)\n if reason:\n decision = ask_user(block.name, block.input, reason)\n if decision == \"deny\":\n return False\n\n return True\n\n# agent_loop で — s02 のループに 1 行追加するだけ:\nfor block in response.content:\n if block.type == \"tool_use\":\n if not check_permission(block): # ← 新規\n results.append({... \"content\": \"Permission denied.\"})\n continue\n output = TOOL_HANDLERS[block.name](**block.input) # s02 既存\n results.append(...)\n```\n\n---\n\n## s02 からの変更点\n\n| コンポーネント | 変更前 (s02) | 変更後 (s03) |\n|---------------|-------------|-------------|\n| セキュリティモデル | なし(モデルを信頼) | 3 ゲート権限パイプライン |\n| 新規関数 | — | check_deny_list, check_rules, ask_user, check_permission |\n| ループ | すべてのツールを直接実行 | 実行前に check_permission() を挿入 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s03_permission/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Create a file called test.txt in the current directory`(そのまま通過するはず)\n2. `Delete the file test.txt`(bash + rm でゲート 2 が発動)\n3. `What files are in the current directory?`(読み取り専用、すべて通過)\n4. `Try to write a file to /etc/something`(作業ディレクトリ外への書き込みでゲート 2 が発動)\n\n観察のポイント:どの操作がそのまま通過するか? どれに確認が必要か? どれが即座に拒否されるか?\n\n---\n\n## 次へ\n\n権限チェックは実装された — しかし、毎回ループ内に `check_permission()` をハードコードしている。ツール実行の前後にログを追加したい場合は? 特定の操作後に自動的に git commit をトリガーしたい場合は? このような拡張ロジックがループ内に散らばると、ループはすぐに膨張する。\n\n→ s04 Hooks:ループにフックを追加する。拡張ロジックはフックにぶら下げ、ループはクリーンに保つ。\n\n
\nCC ソースコードを深掘り\n\n> 以下は CC ソースコード `types/permissions.ts`、`utils/permissions/permissions.ts`、`toolExecution.ts`、`utils/permissions/yoloClassifier.ts`、`tools/AgentTool/forkSubagent.ts` の検証に基づく。\n\n### 一、PermissionResult:3 種ではなく、4 種\n\n教育版の 3 つのゲート(deny → ask → allow)は CC と完全には対応しない。CC の `PermissionResult` には 4 つの behavior がある(`types/permissions.ts:241-266`):\n\n| behavior | 意味 | 教育版の対応 |\n|----------|------|-------------|\n| `allow` | 直接許可 | ゲート 3 通過 |\n| `deny` | 直接拒否 | ゲート 1 一致 |\n| `ask` | ユーザーにダイアログを表示 | ゲート 2 一致 |\n| `passthrough` | ツールが意見を表明せず、汎用パイプラインに委ねる | 教育版にはなし |\n\n### 二、本番環境の検証段階\n\nCC のツール呼び出しは 3 つのゲートを通るのではなく、`checkPermissionsAndCallTool()`(`toolExecution.ts:599-1745`)、hooks、`hasPermissionsToUseToolInner()`(`utils/permissions/permissions.ts:1158-1310`)、classifier ロジックに分散する複数の段階を経る:\n\n1. **Zod schema 検証**(`toolExecution.ts:614-680`)— パラメータの型チェック\n2. **validateInput()**(`toolExecution.ts:682-733`)— ツールレベルの意味的検証\n3. **backfillObservableInput()**(`toolExecution.ts:784`)— レガシーフィールドの補完\n4. **PreToolUse hooks**(`toolExecution.ts:800-862`)— フックが allow/deny/ask を返す\n5. **resolveHookPermissionDecision()**(`toolExecution.ts:921-931`)— フック + パイプラインの決定を調整\n6. **hasPermissionsToUseToolInner()**(`permissions.ts:1158-1310`)— 多層ルールチェック:\n - ツール全体が deny rule で無効 → `deny`\n - ツール全体が ask rule でマーク → `ask`\n - `tool.checkPermissions()` ツール自身の判断\n - ツール自身が deny を返す → `deny`\n - `requiresUserInteraction()` → `ask`\n - コンテンツ関連の ask ルール → `ask`(バイパス不可)\n - セキュリティチェック違反 → `ask`(バイパス不可)\n - bypassPermissions モード → `allow`\n - ツール全体が allow rule で許可 → `allow`\n - passthrough → `ask` に変換\n\n### 三、拒否リスト:1 つのファイルではなく、8 つのソース\n\nCC には単一の deny list はない。権限ルールは 8 つのソースから来る(`types/permissions.ts:54-62`):\n\n| ソース | 設定場所 |\n|--------|---------|\n| `userSettings` | `~/.claude/settings.json` |\n| `projectSettings` | `.claude/settings.json` |\n| `localSettings` | `settings.local.json` |\n| `flagSettings` | フィーチャーフラグ |\n| `policySettings` | 企業管理ポリシー |\n| `cliArg` | `--allowedTools` / `--deniedTools` |\n| `command` | インラインコマンド |\n| `session` | セッション内一時承認 |\n\n各ルールの形式:`{ toolName: \"Bash\", ruleBehavior: \"deny\", ruleContent: \"npm publish:*\" }`。複数ソースのルールは統合され、高優先度ソースが低優先度を上書きする(低→高:user < project < local < flag < policy、さらに cliArg、command、session)。\n\n### 四、isDestructive() とは\n\nCC では `isDestructive`(`Tool.ts:405-406`)は**純粋に UI 表示用** — ツール一覧に `[destructive]` ラベルを表示するだけ。権限決定には参加しない。デフォルトではすべてのツールが `false` を返す。ExitWorktree(remove 時)と MCP ツール(`annotations.destructiveHint` に依存)のみがオーバーライドする。\n\n### 五、YoloClassifier(自動承認)\n\nCC の auto モードでは、毎回ダイアログを表示するわけではない。`classifyYoloAction`(`utils/permissions/yoloClassifier.ts:1012`)はツール呼び出し + 会話コンテキストを分類器 LLM に送って安全性を判断する。まず acceptEdits モードのシミュレーションを試み(`permissions.ts:620-656`、acceptEdits が許可すれば → 自動承認)、次にセーフツールホワイトリストを確認し(`permissions.ts:658-686`)、最後に分類器を呼び出す。分類器が連続して拒否しすぎた場合 → 手動承認にフォールバック。\n\n### 六、権限バブリング\n\nサブ Agent(AgentTool 経由でフォークされたもの)の `permissionMode` は `'bubble'` に設定される(`forkSubagent.ts:50`)。これは権限ダイアログが**親 Agent のターミナルにバブルアップ**することを意味する。サブ Agent で黙って拒否されるのではない。Bash 分類器はこの過程で引き続き実行され — 権限ダイアログを表示しつつ、バックグラウンドで自動承認可能か判断する。\n\n### 教育版の単純化は意図的\n\n- 多段階パイプライン → 3 ゲート:理解のハードルが大幅に下がる\n- 8 ルールソース → 1 つのローカル DENY_LIST:概念量を制御可能\n- isDestructive → 省略(教育版には UI レイヤーがなく、CC でも権限決定には参加しない)\n- YoloClassifier → 省略(追加の LLM 呼び出しとテレメトリに依存)\n- 権限バブリング → 省略(s15 でマルチ Agent を扱う)\n\n
\n\n\n" + "content": "# s03: Permission — 実行前に権限を判断する\n\ns01 → s02 → `s03` → [s04](/ja/s04) → s05 → ... → s20 → s21\n> *\"ツール実行前に権限を判断\"* — 権限パイプラインは、どの操作に承認が必要かを決める。\n>\n> **Harness レイヤー**: 権限 — ツール実行前に一つのゲートを追加。\n\n---\n\n## 課題\n\ns02 の Agent は 5 つのツールを持つ。file tools は `safe_path` で保護されるが、bash は制限なし。「プロジェクトを掃除して」と頼むと、`rm -rf /` を実行しかねない。\n\n安全性はモデルを信頼することではなく、コードに頼る — ツール実行前に判断を挟む。\n\n---\n\n## ソリューション\n\n![Permission Overview](/course-assets/s03_permission/permission-overview.ja.svg)\n\ns02 のループは完全に維持される。唯一の変更は、ツール実行前に `check_permission()` を挿入すること — 各ツール呼び出しは 3 つのゲートを固定順序で通過する:ハード拒否が最優先、次にソフト確認、どちらも一致しなければ許可。\n\n3 つのゲートは 3 つの決定に対応する:\n\n| ゲート | 役割 | 一致時 |\n|--------|------|--------|\n| 1. 拒否リスト | 常に禁止される操作(`rm -rf /`、`sudo`) | 即座に拒否、実行しない |\n| 2. ルールマッチング | コンテキスト依存の操作(作業ディレクトリ外への読み書き、`rm` ファイル) | ゲート 3 へ |\n| 3. ユーザー承認 | ゲート 2 が一致した場合、ユーザー確認を待機 | ユーザーが許可または拒否を決定 |\n\n3 つのゲートのどれにも一致しない → 直接実行。日常の操作の大部分はこの経路を通る。\n\n---\n\n## 仕組み\n\n![Permission Pipeline](/course-assets/s03_permission/permission-pipeline.ja.svg)\n\n**ゲート 1**:ハード拒否リスト。最初に確認し、一致すればブロックメッセージを返す。このリストは権限ゲートの位置を示すための単純な文字列照合であり、完全なセキュリティ境界ではない。\n\n```python\nDENY_LIST = [\n \"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\",\n \"mkfs\", \"dd if=\", \"> /dev/sda\",\n]\n\ndef check_deny_list(command: str) -> str | None:\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Blocked: '{pattern}' is on the deny list\"\n return None\n```\n\n**ゲート 2**:ルールマッチング — 「いつユーザーに聞くべきか」を記述する。各ルールはツールとチェック条件を指定する。\n\n```python\nPERMISSION_RULES = [\n {\n \"tools\": [\"read_file\", \"write_file\", \"edit_file\"],\n \"check\": lambda args: not (WORKDIR / args.get(\"path\", \"\")).resolve().is_relative_to(WORKDIR),\n \"message\": \"Access outside workspace\",\n },\n {\n \"tools\": [\"bash\"],\n \"check\": lambda args: any(kw in args.get(\"command\", \"\") for kw in [\"rm \", \"> /etc/\", \"chmod 777\"]),\n \"message\": \"Potentially destructive command\",\n },\n]\n\ndef check_rules(tool_name: str, args: dict) -> str | None:\n for rule in PERMISSION_RULES:\n if tool_name in rule[\"tools\"] and rule[\"check\"](args):\n return rule[\"message\"]\n return None\n```\n\n**ゲート 3**:ルールが一致した後、ユーザー入力を待機。\n\n```python\ndef ask_user(tool_name: str, args: dict, reason: str) -> str:\n print(f\"\\n⚠ {reason}\")\n print(f\" Tool: {tool_name}({args})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n return \"allow\" if choice in (\"y\", \"yes\") else \"deny\"\n```\n\n**3 つのゲートを直列に接続**、ツール実行前に挿入する:\n\n```python\ndef check_permission(block) -> bool:\n # ゲート 1: ハード拒否\n if block.name == \"bash\":\n reason = check_deny_list(block.input.get(\"command\", \"\"))\n if reason:\n print(f\"\\n⛔ {reason}\")\n return False\n\n # ゲート 2 + 3: ルールマッチング → ユーザー承認\n reason = check_rules(block.name, block.input)\n if reason:\n decision = ask_user(block.name, block.input, reason)\n if decision == \"deny\":\n return False\n\n return True\n\n# agent_loop で — s02 のループに 1 行追加するだけ:\nfor block in response.content:\n if block.type == \"tool_use\":\n if not check_permission(block): # ← 新規\n results.append({... \"content\": \"Permission denied.\"})\n continue\n output = TOOL_HANDLERS[block.name](**block.input) # s02 既存\n results.append(...)\n```\n\n---\n\n## s02 からの変更点\n\n| コンポーネント | 変更前 (s02) | 変更後 (s03) |\n|---------------|-------------|-------------|\n| セキュリティモデル | なし(モデルを信頼) | 3 ゲート権限パイプライン |\n| 新規関数 | — | check_deny_list, check_rules, ask_user, check_permission |\n| ループ | すべてのツールを直接実行 | 実行前に check_permission() を挿入 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s03_permission/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Create a file called test.txt in the current directory`(そのまま通過するはず)\n2. `Delete the file test.txt`(bash + rm でゲート 2 が発動)\n3. `What files are in the current directory?`(読み取り専用、すべて通過)\n4. `Try to write a file to /etc/something`(作業ディレクトリ外への書き込みでゲート 2 が発動)\n\n観察のポイント:どの操作がそのまま通過するか? どれに確認が必要か? どれが即座に拒否されるか?\n\n---\n\n## 次へ\n\n権限チェックは実装された — しかし、毎回ループ内に `check_permission()` をハードコードしている。ツール実行の前後にログを追加したい場合は? 特定の操作後に自動的に git commit をトリガーしたい場合は? このような拡張ロジックがループ内に散らばると、ループはすぐに膨張する。\n\n→ s04 Hooks:ループにフックを追加する。拡張ロジックはフックにぶら下げ、ループはクリーンに保つ。\n\n\n\n" }, { "version": "s04", "locale": "en", "title": "s04: Hooks — Hang on the Loop, Don't Write into It", - "content": "# s04: Hooks — Hang on the Loop, Don't Write into It\n\ns01 → s02 → s03 → `s04` → [s05](/en/s05) → s06 → ... → s20 → s21 → s22\n\n> *\"Hang on the loop, don't write into it\"* — Hooks inject extension logic before and after tool execution.\n>\n> **Harness Layer**: Hooks — Extension points that don't invade the loop.\n\n---\n\n## The Problem\n\nThe s03 Agent has permission checks. But every new check, \"log every bash call\", \"auto git add after writes\", requires modifying the `agent_loop` function.\n\nThe loop quickly becomes this:\n\n```python\ndef agent_loop(messages):\n while True:\n # ... LLM call ...\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n log_to_file(block) # added a line\n check_permission(block) # added a line\n notify_slack(block) # added another line\n output = execute(block)\n auto_git_add(block) # yet another line\n # ... the loop is unrecognizable\n```\n\nWhat you want to extend is the Agent's behavior, but what you're modifying is the loop itself. The loop should be a stable core; extensions should hang on the outside.\n\n---\n\n## The Solution\n\n![Hooks Overview](/course-assets/s04_hooks/hooks-overview.en.svg)\n\nThe s03 loop and permission logic are fully preserved. The only change is moving `check_permission()` from inside the loop body onto a hook. The loop no longer directly calls any check function. Instead it calls `trigger_hooks(\"PreToolUse\", block)`, and the registry decides what to run.\n\nFour events, covering a complete agent cycle:\n\n| Event | Trigger Timing | Typical Use |\n|-------|---------------|-------------|\n| UserPromptSubmit | After user input, before entering LLM | Input validation, context injection |\n| PreToolUse | Before tool execution | Permission checks, logging |\n| PostToolUse | After tool execution | Side effects (auto git add etc.), output checking |\n| Stop | When the loop is about to exit | Cleanup (CC also supports force continuation) |\n\nExtensions are added via `register_hook()`. The loop only calls `trigger_hooks()`.\n\n---\n\n## How It Works\n\n**Hook registry**: a dict mapping event names to callback lists.\n\n```python\nHOOKS = {\n \"UserPromptSubmit\": [],\n \"PreToolUse\": [],\n \"PostToolUse\": [],\n \"Stop\": [],\n}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # return value ≠ None → hook says \"stop\"\n return result\n return None\n```\n\nIn the teaching version, PreToolUse returning non-None means block execution; Stop returning non-None means force continuation. UserPromptSubmit and PostToolUse return values are unused.\n\n**UserPromptSubmit**, triggers after user input, before entering the LLM. CC can intercept or modify input; the teaching version only logs:\n\n```python\ndef context_inject_hook(query: str) -> str | None:\n \"\"\"Inject current working directory info into every prompt.\"\"\"\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None # return None = no modification, let prompt through\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\n```\n\nIn the main loop, triggered right after user input:\n\n```python\nquery = input(\"s04 >> \")\ntrigger_hooks(\"UserPromptSubmit\", query) # ← before entering LLM\nhistory.append({\"role\": \"user\", \"content\": query})\nagent_loop(history)\n```\n\n**PreToolUse / PostToolUse**, hooks before and after tool execution. s03's permission check logic is now wrapped as a PreToolUse hook, plus a logging hook and a large-output reminder:\n\n```python\n# PreToolUse: permission check (s03 logic, moved from loop to hook)\ndef permission_hook(block):\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n return \"Permission denied by deny list\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n# PreToolUse: logging\ndef log_hook(block):\n print(f\"[HOOK] {block.name}(...)\")\n\n# PostToolUse: large output reminder\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"[HOOK] ⚠ Large output from {block.name}\")\n\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\n```\n\n**Stop**, triggers when the loop is about to exit (`stop_reason != \"tool_use\"`). The teaching version prints a cleanup summary:\n\n```python\ndef summary_hook(messages: list) -> str | None:\n \"\"\"Print a summary when the loop is about to stop.\"\"\"\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None # return None = allow stop, return string = force continuation\n\nregister_hook(\"Stop\", summary_hook)\n```\n\nIn agent_loop, triggered before exit:\n\n```python\nif response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages) # ← before exiting\n if force:\n # hook returned a message → inject it and continue\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n```\n\n**Only one change in the loop**: s03 directly called `check_permission(block)`, s04 replaces it with `trigger_hooks(\"PreToolUse\", block)`:\n\n```python\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s03: if not check_permission(block): ...\n # s04: hooks replace hardcoding\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output)\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": output})\n```\n\nFour hooks cover the critical nodes of the agent cycle: input → before execution → after execution → exit. The loop only calls trigger_hooks(); all logic lives in hook callbacks.\n\n---\n\n## Changes from s03\n\n| Component | Before (s03) | After (s04) |\n|-----------|-------------|-------------|\n| Extension method | check_permission() hardcoded in the loop | HOOKS registry + trigger_hooks() |\n| New functions | — | register_hook, trigger_hooks |\n| Hook callbacks | — | context_inject_hook, permission_hook, log_hook, large_output_hook, summary_hook |\n| Loop | Directly calls check_permission() | Calls trigger_hooks(\"PreToolUse\", ...) |\n| Exit control | None | trigger_hooks(\"Stop\", ...) can prevent exit |\n| Input interception | None | trigger_hooks(\"UserPromptSubmit\", ...) can inject context |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s04_hooks/code.py\n```\n\nTry these prompts:\n\n1. `Read the file README.md` (should pass directly, observe hook logs)\n2. `Create a file called test.txt` (after creation, observe if PostToolUse fires)\n3. `Delete all temporary files in /tmp` (bash + rm triggers permission hook)\n\nWhat to watch for: Before each tool execution, does the `[HOOK]` log appear? When permission is denied, was it intercepted by a hook or hardcoded in the loop?\n\n---\n\n## What's Next\n\nThe Agent can now safely execute operations. But does it ever stop to think \"what should I do first, and what next?\" Given a complex task, does it jump straight in, or plan first?\n\n→ s05 TodoWrite: Give the Agent a planning tool. Make a list first, then execute.\n\n
\nDive into CC Source Code\n\n> The following is based on a complete analysis of CC source code `toolHooks.ts` (650 lines), `hooks.ts`, `stopHooks.ts`, and `coreTypes.ts`.\n\n### 1. Hook Events: Not Just 4, but 27\n\nThe teaching version covers only PreToolUse and PostToolUse. CC actually has 27 hook events (`coreTypes.ts:25-53`):\n\n| Category | Events |\n|----------|--------|\n| Tool-related | `PreToolUse`, `PostToolUse`, `PostToolUseFailure` |\n| Session-related | `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `Setup` |\n| User interaction | `UserPromptSubmit`, `Notification`, `PermissionRequest`, `PermissionDenied` |\n| Sub-agents | `SubagentStart`, `SubagentStop` |\n| Compaction-related | `PreCompact`, `PostCompact` |\n| Team-related | `TeammateIdle`, `TaskCreated`, `TaskCompleted` |\n| Other | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded`, `CwdChanged`, `FileChanged` |\n\nThe teaching version covers only 4 core events (UserPromptSubmit, PreToolUse, PostToolUse, Stop) because they cover every critical node of a complete agent cycle. The other 23 follow the same pattern.\n\n### 2. HookResult Common Fields\n\nCC's `HookResult` (`types/hooks.ts:260-275`) has 14 fields. Common ones:\n\n| Field | Type | Purpose |\n|-------|------|---------|\n| `message` | Message | Optional UI message |\n| `blockingError` | HookBlockingError | Blocking error → injected into conversation for model self-correction |\n| `outcome` | success/blocking/non_blocking_error/cancelled | Execution result |\n| `preventContinuation` | boolean | Prevent subsequent execution |\n| `stopReason` | string | Stop reason description |\n| `permissionBehavior` | allow/deny/ask/passthrough | Hook returns permission decision |\n| `updatedInput` | Record | Modify tool input |\n| `additionalContext` | string | Additional context |\n| `updatedMCPToolOutput` | unknown | MCP tool output modification |\n\n### 3. Key Invariant: Hook 'allow' Cannot Bypass deny/ask Rules\n\nThis is the most important security design in CC's permission system (`toolHooks.ts:325-331`): **when a hook returns allow, it still checks settings.json deny/ask rules.** Even if the user's hook script says \"allow\", if the tool is disabled in settings.json, the operation is still blocked.\n\nThe teaching version doesn't have this layer; hooks returning non-None directly interrupt. This is sufficient for teaching, but would create a security vulnerability in production.\n\n### 4. stopHookActive Mechanism\n\nCC's Stop hooks have an infinite-loop prevention mechanism (`query.ts:212,1300`): the `stopHookActive` state field. When stop hooks produce a blockingError, the loop re-enters with `stopHookActive: true`. Subsequent iterations see this flag and don't trigger stop hooks again. This prevents a never-stopping bug: model self-corrects → stop hook errors again → model self-corrects again → stop hook errors again...\n\n### 5. hook_stopped_continuation\n\nWhen PostToolUse hooks return `preventContinuation: true`, a `hook_stopped_continuation` attachment is produced (`toolHooks.ts:117-130`). query.ts (L1388-1393) detects it and sets `shouldPreventContinuation = true`, causing the loop to exit. This is the mechanism for \"hooks gracefully shut down the Agent\" — not a crash, but a completion.\n\n### Teaching Version Simplifications Are Intentional\n\n- 27 events → 4 (UserPromptSubmit/PreToolUse/PostToolUse/Stop): covers agent cycle critical nodes\n- 14 fields → simple return values (None = continue, non-None = interrupt/continue): minimal cognitive load\n- Hook allow vs deny/ask invariant → omitted: teaching version has no settings.json layer\n- stopHookActive → omitted: teaching version Stop hook only does simple continuation, no infinite-loop prevention needed\n\n
\n\n\n" + "content": "# s04: Hooks — Hang on the Loop, Don't Write into It\n\ns01 → s02 → s03 → `s04` → [s05](/en/s05) → s06 → ... → s20 → s21\n\n> *\"Hang on the loop, don't write into it\"* — Hooks inject extension logic before and after tool execution.\n>\n> **Harness Layer**: Hooks — Extension points that don't invade the loop.\n\n---\n\n## The Problem\n\nThe s03 Agent has permission checks. But every new check, \"log every bash call\", \"auto git add after writes\", requires modifying the `agent_loop` function.\n\nThe loop quickly becomes this:\n\n```python\ndef agent_loop(messages):\n while True:\n # ... LLM call ...\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n log_to_file(block) # added a line\n check_permission(block) # added a line\n notify_slack(block) # added another line\n output = execute(block)\n auto_git_add(block) # yet another line\n # ... the loop is unrecognizable\n```\n\nWhat you want to extend is the Agent's behavior, but what you're modifying is the loop itself. The loop should be a stable core; extensions should hang on the outside.\n\n---\n\n## The Solution\n\n![Hooks Overview](/course-assets/s04_hooks/hooks-overview.en.svg)\n\nThe s03 loop and permission logic are fully preserved. The only change is moving `check_permission()` from inside the loop body onto a hook. The loop no longer directly calls any check function. Instead it calls `trigger_hooks(\"PreToolUse\", block)`, and the registry decides what to run.\n\nFour events, covering a complete agent cycle:\n\n| Event | Trigger Timing | Typical Use |\n|-------|---------------|-------------|\n| UserPromptSubmit | After user input, before entering LLM | Input validation, context injection |\n| PreToolUse | Before tool execution | Permission checks, logging |\n| PostToolUse | After tool execution | Side effects (auto git add etc.), output checking |\n| Stop | When the loop is about to exit | Cleanup, decide whether the loop continues |\n\nExtensions are added via `register_hook()`. The loop only calls `trigger_hooks()`.\n\n---\n\n## How It Works\n\n**Hook registry**: a dict mapping event names to callback lists.\n\n```python\nHOOKS = {\n \"UserPromptSubmit\": [],\n \"PreToolUse\": [],\n \"PostToolUse\": [],\n \"Stop\": [],\n}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # return value ≠ None → hook says \"stop\"\n return result\n return None\n```\n\nWhen `PreToolUse` returns non-None, the current tool execution is blocked. When `Stop` returns non-None, the loop continues. Return values from `UserPromptSubmit` and `PostToolUse` do not affect control flow.\n\n**UserPromptSubmit** triggers after user input and before entering the LLM. The following hook records the current working directory:\n\n```python\ndef context_inject_hook(query: str) -> str | None:\n \"\"\"Inject current working directory info into every prompt.\"\"\"\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None # return None = no modification, let prompt through\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\n```\n\nIn the main loop, triggered right after user input:\n\n```python\nquery = input(\"s04 >> \")\ntrigger_hooks(\"UserPromptSubmit\", query) # ← before entering LLM\nhistory.append({\"role\": \"user\", \"content\": query})\nagent_loop(history)\n```\n\n**PreToolUse / PostToolUse**, hooks before and after tool execution. s03's permission check logic is now wrapped as a PreToolUse hook, plus a logging hook and a large-output reminder:\n\n```python\n# PreToolUse: permission check (s03 logic, moved from loop to hook)\ndef permission_hook(block):\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n return \"Permission denied by deny list\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n# PreToolUse: logging\ndef log_hook(block):\n print(f\"[HOOK] {block.name}(...)\")\n\n# PostToolUse: large output reminder\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"[HOOK] ⚠ Large output from {block.name}\")\n\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\n```\n\n**Stop** triggers when the loop is about to exit (`stop_reason != \"tool_use\"`). The following hook prints a cleanup summary:\n\n```python\ndef summary_hook(messages: list) -> str | None:\n \"\"\"Print a summary when the loop is about to stop.\"\"\"\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None # return None = allow stop, return string = force continuation\n\nregister_hook(\"Stop\", summary_hook)\n```\n\nIn agent_loop, triggered before exit:\n\n```python\nif response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages) # ← before exiting\n if force:\n # hook returned a message → inject it and continue\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n```\n\n**Only one change in the loop**: s03 directly called `check_permission(block)`, s04 replaces it with `trigger_hooks(\"PreToolUse\", block)`:\n\n```python\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s03: if not check_permission(block): ...\n # s04: hooks replace hardcoding\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output)\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": output})\n```\n\nFour hooks cover the critical nodes of the agent cycle: input → before execution → after execution → exit. The loop only calls trigger_hooks(); all logic lives in hook callbacks.\n\n---\n\n## Changes from s03\n\n| Component | Before (s03) | After (s04) |\n|-----------|-------------|-------------|\n| Extension method | check_permission() hardcoded in the loop | HOOKS registry + trigger_hooks() |\n| New functions | — | register_hook, trigger_hooks |\n| Hook callbacks | — | context_inject_hook, permission_hook, log_hook, large_output_hook, summary_hook |\n| Loop | Directly calls check_permission() | Calls trigger_hooks(\"PreToolUse\", ...) |\n| Exit control | None | trigger_hooks(\"Stop\", ...) can prevent exit |\n| Input interception | None | trigger_hooks(\"UserPromptSubmit\", ...) can inject context |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s04_hooks/code.py\n```\n\nTry these prompts:\n\n1. `Read the file README.md` (should pass directly, observe hook logs)\n2. `Create a file called test.txt` (after creation, observe if PostToolUse fires)\n3. `Delete all temporary files in /tmp` (bash + rm triggers permission hook)\n\nWhat to watch for: Before each tool execution, does the `[HOOK]` log appear? When permission is denied, was it intercepted by a hook or hardcoded in the loop?\n\n---\n\n## What's Next\n\nThe Agent can now safely execute operations. But does it ever stop to think \"what should I do first, and what next?\" Given a complex task, does it jump straight in, or plan first?\n\n→ s05 TodoWrite: Give the Agent a planning tool. Make a list first, then execute.\n\n\n\n" }, { "version": "s04", "locale": "zh", "title": "s04: Hooks — 挂在循环上,不写进循环里", - "content": "# s04: Hooks — 挂在循环上,不写进循环里\n\ns01 → s02 → s03 → `s04` → [s05](/zh/s05) → s06 → ... → s20 → s21 → s22\n\n> *\"挂在循环上, 不写进循环里\"* — hook 在工具执行前后注入扩展逻辑。\n>\n> **Harness 层**: hook — 扩展点不侵入循环。\n\n---\n\n## 问题\n\ns03 的 Agent 有权限检查了。但每次加一个新检查,比如\"记录每次 bash 调用\"、\"操作后自动 git add\",都要修改 `agent_loop` 函数。\n\n循环很快就变成了这样:\n\n```python\ndef agent_loop(messages):\n while True:\n # ... LLM call ...\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n log_to_file(block) # 加一行\n check_permission(block) # 加一行\n notify_slack(block) # 又加一行\n output = execute(block)\n auto_git_add(block) # 再加一行\n # ... 很快循环就认不出来了\n```\n\n你想扩展的是 Agent 的行为,但你改的却是循环本身。循环应该是一个稳定的核心,扩展应该挂在外面。\n\n---\n\n## 解决方案\n\n![Hooks Overview](/course-assets/s04_hooks/hooks-overview.svg)\n\ns03 的循环和权限逻辑完全保留。唯一的变动是把 `check_permission()` 从循环体内移到了 hook 上,循环不再直接调用任何检查函数,改为 `trigger_hooks(\"PreToolUse\", block)`,由注册表决定跑什么。\n\n四个事件,覆盖一个完整的 agent cycle:\n\n| 事件 | 触发时机 | 典型用途 |\n|------|---------|---------|\n| UserPromptSubmit | 用户输入提交后、进入 LLM 前 | 输入验证、注入上下文 |\n| PreToolUse | 工具执行前 | 权限检查、日志记录 |\n| PostToolUse | 工具执行后 | 副作用(自动 git add 等)、输出检查 |\n| Stop | 循环即将退出时 | 收尾清理(CC 还支持强制续跑) |\n\n扩展通过 `register_hook()` 添加,循环只调用 `trigger_hooks()`。\n\n---\n\n## 工作原理\n\n**hook 注册表**:一个字典,事件名映射到回调列表。\n\n```python\nHOOKS = {\n \"UserPromptSubmit\": [],\n \"PreToolUse\": [],\n \"PostToolUse\": [],\n \"Stop\": [],\n}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # 返回值 ≠ None → hook 说\"停\"\n return result\n return None\n```\n\n教学版中,PreToolUse 的非 None 返回值会阻止本次工具执行,Stop 的非 None 返回值会强制续跑。UserPromptSubmit 和 PostToolUse 的返回值未被使用。\n\n**UserPromptSubmit**,用户输入提交后、进入 LLM 前触发。CC 中可以拦截或修改输入,教学版只做日志演示:\n\n```python\ndef context_inject_hook(query: str) -> str | None:\n \"\"\"Inject current working directory info into every prompt.\"\"\"\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None # return None = no modification, let prompt through\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\n```\n\n在主循环中,用户输入后立即触发:\n\n```python\nquery = input(\"s04 >> \")\ntrigger_hooks(\"UserPromptSubmit\", query) # ← 进入 LLM 之前\nhistory.append({\"role\": \"user\", \"content\": query})\nagent_loop(history)\n```\n\n**PreToolUse / PostToolUse**,工具执行前后的 hook。s03 的权限检查逻辑现在包装成 PreToolUse hook,再加一个日志 hook 和一个大输出提醒:\n\n```python\n# PreToolUse: 权限检查(s03 的逻辑,从循环移到 hook)\ndef permission_hook(block):\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n return \"Permission denied by deny list\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n# PreToolUse: 日志\ndef log_hook(block):\n print(f\"[HOOK] {block.name}(...)\")\n\n# PostToolUse: 大文件提醒\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"[HOOK] ⚠ Large output from {block.name}\")\n\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\n```\n\n**Stop**,循环即将退出时触发(`stop_reason != \"tool_use\"`)。教学版用于打印收尾统计:\n\n```python\ndef summary_hook(messages: list) -> str | None:\n \"\"\"Print a summary when the loop is about to stop.\"\"\"\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None # return None = allow stop, return string = force continuation\n\nregister_hook(\"Stop\", summary_hook)\n```\n\n在 agent_loop 中,退出前触发:\n\n```python\nif response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages) # ← 退出之前\n if force:\n # hook returned a message → inject it and continue\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n```\n\n**循环里只改了一处**:s03 直接调用 `check_permission(block)`,s04 改为 `trigger_hooks(\"PreToolUse\", block)`:\n\n```python\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s03: if not check_permission(block): ...\n # s04: hook 替代硬编码\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output)\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": output})\n```\n\n四个 hook 覆盖了 agent cycle 的关键节点:输入→执行前→执行后→退出。循环只负责调用 trigger_hooks(),具体逻辑全在 hook 回调里。\n\n---\n\n## 相对 s03 的变更\n\n| 组件 | 之前 (s03) | 之后 (s04) |\n|------|-----------|-----------|\n| 扩展方式 | check_permission() 硬编码在循环里 | HOOKS 注册表 + trigger_hooks() |\n| 新函数 | — | register_hook, trigger_hooks |\n| hook 回调 | — | context_inject_hook, permission_hook, log_hook, large_output_hook, summary_hook |\n| 循环 | 直接调用 check_permission() | 调用 trigger_hooks(\"PreToolUse\", ...) |\n| 退出控制 | 无 | trigger_hooks(\"Stop\", ...) 可阻止退出 |\n| 输入拦截 | 无 | trigger_hooks(\"UserPromptSubmit\", ...) 可注入上下文 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s04_hooks/code.py\n```\n\n试试这些 prompt:\n\n1. `Read the file README.md`(应该直接通过,观察 hook 日志)\n2. `Create a file called test.txt`(通过后观察 PostToolUse 是否触发)\n3. `Delete all temporary files in /tmp`(bash + rm 触发权限 hook)\n\n观察重点:每次工具执行前,是否出现了 `[HOOK]` 日志?权限被拒时,是 hook 拦截的还是循环里硬编码的?\n\n---\n\n## 接下来\n\nAgent 现在能安全执行操作了。但它有没有停下来想过\"我应该先做什么,再做什么\"?给它一个复杂任务,它是一上来就动手,还是先列个计划?\n\ns05 TodoWrite → 给 Agent 一个计划工具。先列清单,再做。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `toolHooks.ts`(650 行)、`hooks.ts`、`stopHooks.ts`、`coreTypes.ts` 的完整分析。\n\n### 一、Hook 事件:不止这 4 个,而是 27 个\n\n教学版只讲了 PreToolUse 和 PostToolUse。CC 实际有 27 个 hook 事件(`coreTypes.ts:25-53`):\n\n| 类别 | 事件 |\n|------|------|\n| 工具相关 | `PreToolUse`, `PostToolUse`, `PostToolUseFailure` |\n| 会话相关 | `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `Setup` |\n| 用户交互 | `UserPromptSubmit`, `Notification`, `PermissionRequest`, `PermissionDenied` |\n| 子 Agent | `SubagentStart`, `SubagentStop` |\n| 压缩相关 | `PreCompact`, `PostCompact` |\n| 团队相关 | `TeammateIdle`, `TaskCreated`, `TaskCompleted` |\n| 其他 | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded`, `CwdChanged`, `FileChanged` |\n\n教学版只讲 4 个核心事件(UserPromptSubmit、PreToolUse、PostToolUse、Stop),因为它们覆盖了一个完整 agent cycle 的关键节点。其他 23 个都是同样的模式。\n\n### 二、HookResult 常用字段摘录\n\nCC 的 `HookResult`(`types/hooks.ts:260-275`)有 14 个字段,以下是常用字段:\n\n| 字段 | 类型 | 用途 |\n|------|------|------|\n| `message` | Message | 可选 UI 消息 |\n| `blockingError` | HookBlockingError | 阻塞错误 → 注入对话让模型自纠 |\n| `outcome` | success/blocking/non_blocking_error/cancelled | 执行结果 |\n| `preventContinuation` | boolean | 阻止后续执行 |\n| `stopReason` | string | 停止原因描述 |\n| `permissionBehavior` | allow/deny/ask/passthrough | hook 返回权限决策 |\n| `updatedInput` | Record | 修改工具输入 |\n| `additionalContext` | string | 附加上下文 |\n| `updatedMCPToolOutput` | unknown | MCP 工具输出修改 |\n\n### 三、关键不变式:Hook 'allow' 不能绕过 deny/ask 规则\n\n这是 CC 权限系统最重要的安全设计(`toolHooks.ts:325-331`):**hook 返回 allow 时,仍然要检查 settings.json 的 deny/ask 规则**。即使用户的 hook 脚本说\"允许\",如果在 settings.json 中禁用了这个工具,操作仍然会被阻止。\n\n教学版没有这个层次,只把 PreToolUse 的非 None 返回值解释为阻止本次工具执行。这在教学场景中够了,但在生产环境中会形成安全漏洞。\n\n### 四、stopHookActive 机制\n\nCC 的 Stop hooks 有一个防无限循环机制(`query.ts:212,1300`):`stopHookActive` 状态字段。当 stop hooks 产生 blockingError 时,循环带 `stopHookActive: true` 重入下一轮。后续迭代中 stop hooks 看到这个标志就不会再次触发。这防止了一个永不停机的 bug:模型自纠后 stop hook 再次报错 → 模型再自纠 → stop hook 再报错...\n\n### 五、hook_stopped_continuation\n\nPostToolUse hooks 返回 `preventContinuation: true` 时,会产生一个 `hook_stopped_continuation` 附件(`toolHooks.ts:117-130`)。query.ts(L1388-1393)检测到后设置 `shouldPreventContinuation = true`,循环退出。这是 \"hook 优雅地让 Agent 停机\" 的机制,不是崩溃,是完成。\n\n### 教学版的简化是刻意的\n\n- 27 个事件 → 4 个(UserPromptSubmit/PreToolUse/PostToolUse/Stop):覆盖 agent cycle 关键节点\n- 14 个字段 → 简单的返回值(None = 继续,非 None = 阻止/续跑):心智负担降到最低\n- Hook allow vs deny/ask 不变式 → 省略:教学版没有 settings.json 层\n- stopHookActive → 省略:教学版 Stop hook 只做简单续跑,不涉及防无限循环机制\n\n
\n\n\n" + "content": "# s04: Hooks — 挂在循环上,不写进循环里\n\ns01 → s02 → s03 → `s04` → [s05](/zh/s05) → s06 → ... → s20 → s21\n\n> *\"挂在循环上, 不写进循环里\"* — hook 在工具执行前后注入扩展逻辑。\n>\n> **Harness 层**: hook — 扩展点不侵入循环。\n\n---\n\n## 问题\n\ns03 的 Agent 有权限检查了。但每次加一个新检查,比如\"记录每次 bash 调用\"、\"操作后自动 git add\",都要修改 `agent_loop` 函数。\n\n循环很快就变成了这样:\n\n```python\ndef agent_loop(messages):\n while True:\n # ... LLM call ...\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n log_to_file(block) # 加一行\n check_permission(block) # 加一行\n notify_slack(block) # 又加一行\n output = execute(block)\n auto_git_add(block) # 再加一行\n # ... 很快循环就认不出来了\n```\n\n你想扩展的是 Agent 的行为,但你改的却是循环本身。循环应该是一个稳定的核心,扩展应该挂在外面。\n\n---\n\n## 解决方案\n\n![Hooks Overview](/course-assets/s04_hooks/hooks-overview.svg)\n\ns03 的循环和权限逻辑完全保留。唯一的变动是把 `check_permission()` 从循环体内移到了 hook 上,循环不再直接调用任何检查函数,改为 `trigger_hooks(\"PreToolUse\", block)`,由注册表决定跑什么。\n\n四个事件,覆盖一个完整的 agent cycle:\n\n| 事件 | 触发时机 | 典型用途 |\n|------|---------|---------|\n| UserPromptSubmit | 用户输入提交后、进入 LLM 前 | 输入验证、注入上下文 |\n| PreToolUse | 工具执行前 | 权限检查、日志记录 |\n| PostToolUse | 工具执行后 | 副作用(自动 git add 等)、输出检查 |\n| Stop | 循环即将退出时 | 收尾清理、决定是否继续循环 |\n\n扩展通过 `register_hook()` 添加,循环只调用 `trigger_hooks()`。\n\n---\n\n## 工作原理\n\n**hook 注册表**:一个字典,事件名映射到回调列表。\n\n```python\nHOOKS = {\n \"UserPromptSubmit\": [],\n \"PreToolUse\": [],\n \"PostToolUse\": [],\n \"Stop\": [],\n}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # 返回值 ≠ None → hook 说\"停\"\n return result\n return None\n```\n\n`PreToolUse` 返回非 `None` 时,本次工具执行被阻止;`Stop` 返回非 `None` 时,循环继续。`UserPromptSubmit` 和 `PostToolUse` 的返回值不参与控制流。\n\n**UserPromptSubmit** 在用户输入提交后、进入 LLM 前触发。以下 hook 记录当前工作目录:\n\n```python\ndef context_inject_hook(query: str) -> str | None:\n \"\"\"Inject current working directory info into every prompt.\"\"\"\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None # return None = no modification, let prompt through\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\n```\n\n在主循环中,用户输入后立即触发:\n\n```python\nquery = input(\"s04 >> \")\ntrigger_hooks(\"UserPromptSubmit\", query) # ← 进入 LLM 之前\nhistory.append({\"role\": \"user\", \"content\": query})\nagent_loop(history)\n```\n\n**PreToolUse / PostToolUse**,工具执行前后的 hook。s03 的权限检查逻辑现在包装成 PreToolUse hook,再加一个日志 hook 和一个大输出提醒:\n\n```python\n# PreToolUse: 权限检查(s03 的逻辑,从循环移到 hook)\ndef permission_hook(block):\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n return \"Permission denied by deny list\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n# PreToolUse: 日志\ndef log_hook(block):\n print(f\"[HOOK] {block.name}(...)\")\n\n# PostToolUse: 大文件提醒\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"[HOOK] ⚠ Large output from {block.name}\")\n\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\n```\n\n**Stop** 在循环即将退出时触发(`stop_reason != \"tool_use\"`)。以下 hook 打印收尾统计:\n\n```python\ndef summary_hook(messages: list) -> str | None:\n \"\"\"Print a summary when the loop is about to stop.\"\"\"\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None # return None = allow stop, return string = force continuation\n\nregister_hook(\"Stop\", summary_hook)\n```\n\n在 agent_loop 中,退出前触发:\n\n```python\nif response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages) # ← 退出之前\n if force:\n # hook returned a message → inject it and continue\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n```\n\n**循环里只改了一处**:s03 直接调用 `check_permission(block)`,s04 改为 `trigger_hooks(\"PreToolUse\", block)`:\n\n```python\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s03: if not check_permission(block): ...\n # s04: hook 替代硬编码\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output)\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": output})\n```\n\n四个 hook 覆盖了 agent cycle 的关键节点:输入→执行前→执行后→退出。循环只负责调用 trigger_hooks(),具体逻辑全在 hook 回调里。\n\n---\n\n## 相对 s03 的变更\n\n| 组件 | 之前 (s03) | 之后 (s04) |\n|------|-----------|-----------|\n| 扩展方式 | check_permission() 硬编码在循环里 | HOOKS 注册表 + trigger_hooks() |\n| 新函数 | — | register_hook, trigger_hooks |\n| hook 回调 | — | context_inject_hook, permission_hook, log_hook, large_output_hook, summary_hook |\n| 循环 | 直接调用 check_permission() | 调用 trigger_hooks(\"PreToolUse\", ...) |\n| 退出控制 | 无 | trigger_hooks(\"Stop\", ...) 可阻止退出 |\n| 输入拦截 | 无 | trigger_hooks(\"UserPromptSubmit\", ...) 可注入上下文 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s04_hooks/code.py\n```\n\n试试这些 prompt:\n\n1. `Read the file README.md`(应该直接通过,观察 hook 日志)\n2. `Create a file called test.txt`(通过后观察 PostToolUse 是否触发)\n3. `Delete all temporary files in /tmp`(bash + rm 触发权限 hook)\n\n观察重点:每次工具执行前,是否出现了 `[HOOK]` 日志?权限被拒时,是 hook 拦截的还是循环里硬编码的?\n\n---\n\n## 接下来\n\nAgent 现在能安全执行操作了。但它有没有停下来想过\"我应该先做什么,再做什么\"?给它一个复杂任务,它是一上来就动手,还是先列个计划?\n\ns05 TodoWrite → 给 Agent 一个计划工具。先列清单,再做。\n\n\n\n" }, { "version": "s04", "locale": "ja", "title": "s04: Hooks — ループに掛ける、ループには書き込まない", - "content": "# s04: Hooks — ループに掛ける、ループには書き込まない\n\ns01 → s02 → s03 → `s04` → [s05](/ja/s05) → s06 → ... → s20 → s21 → s22\n\n> *\"ループに掛ける、ループには書き込まない\"* — フックがツール実行の前後に拡張ロジックを注入する。\n>\n> **Harness レイヤー**: フック — ループを侵襲しない拡張ポイント。\n\n---\n\n## 課題\n\ns03 の Agent には権限チェックがある。しかし新しいチェックを追加するたび、「bash 呼び出しを毎回ログに記録」「操作後に自動 git add」、`agent_loop` 関数を修正する必要がある。\n\nループはすぐにこうなる:\n\n```python\ndef agent_loop(messages):\n while True:\n # ... LLM call ...\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n log_to_file(block) # 一行追加\n check_permission(block) # 一行追加\n notify_slack(block) # さらに一行追加\n output = execute(block)\n auto_git_add(block) # さらに一行追加\n # ... もうループが見えない\n```\n\n拡張したいのは Agent の振る舞いなのに、変更しているのはループそのもの。ループは安定した核心であるべき。拡張は外側に掛ける。\n\n---\n\n## ソリューション\n\n![Hooks Overview](/course-assets/s04_hooks/hooks-overview.ja.svg)\n\ns03 のループと権限ロジックは完全に保持される。唯一の変更点は `check_permission()` をループ本体内からフックに移動したこと。ループはもうチェック関数を直接呼び出さず、代わりに `trigger_hooks(\"PreToolUse\", block)` を呼び、登録済みのフックが何を実行するかを決める。\n\n4 つのイベントで、完全な agent cycle をカバー:\n\n| イベント | 発火タイミング | 典型的な用途 |\n|----------|--------------|-------------|\n| UserPromptSubmit | ユーザー入力後、LLM に入る前 | 入力バリデーション、コンテキスト注入 |\n| PreToolUse | ツール実行前 | 権限チェック、ログ記録 |\n| PostToolUse | ツール実行後 | 副作用(自動 git add など)、出力チェック |\n| Stop | ループが終了する直前 | クリーンアップ(CC は強制続行もサポート) |\n\n拡張は `register_hook()` で追加する。ループは `trigger_hooks()` を呼ぶだけ。\n\n---\n\n## 仕組み\n\n**フック登録簿**:イベント名をコールバックリストにマッピングする辞書。\n\n```python\nHOOKS = {\n \"UserPromptSubmit\": [],\n \"PreToolUse\": [],\n \"PostToolUse\": [],\n \"Stop\": [],\n}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # 戻り値 ≠ None → フックが「止め」と指示\n return result\n return None\n```\n\n教学版では、PreToolUse の非 None 戻り値は実行阻止を意味し、Stop の非 None 戻り値は強制続行を意味する。UserPromptSubmit と PostToolUse の戻り値は未使用。\n\n**UserPromptSubmit**、ユーザー入力後、LLM に入る前に発火。CC では入力の横取りや変更が可能、教学版はログ出力のみ:\n\n```python\ndef context_inject_hook(query: str) -> str | None:\n \"\"\"Inject current working directory info into every prompt.\"\"\"\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None # return None = 変更なし、プロンプトを通す\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\n```\n\nメインループでは、ユーザー入力直後に発火:\n\n```python\nquery = input(\"s04 >> \")\ntrigger_hooks(\"UserPromptSubmit\", query) # ← LLM に入る前\nhistory.append({\"role\": \"user\", \"content\": query})\nagent_loop(history)\n```\n\n**PreToolUse / PostToolUse**、ツール実行の前後のフック。s03 の権限チェックロジックは PreToolUse フックに包まれ、さらにログフックと大出力リマインダーが追加される:\n\n```python\n# PreToolUse: 権限チェック(s03 のロジック、ループからフックに移動)\ndef permission_hook(block):\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n return \"Permission denied by deny list\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n# PreToolUse: ログ\ndef log_hook(block):\n print(f\"[HOOK] {block.name}(...)\")\n\n# PostToolUse: 大ファイルリマインダー\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"[HOOK] ⚠ Large output from {block.name}\")\n\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\n```\n\n**Stop**、ループが終了する直前に発火(`stop_reason != \"tool_use\"`)。教学版ではクリーンアップ統計を印刷:\n\n```python\ndef summary_hook(messages: list) -> str | None:\n \"\"\"Print a summary when the loop is about to stop.\"\"\"\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None # return None = 終了を許可、return 文字列 = 強制続行\n\nregister_hook(\"Stop\", summary_hook)\n```\n\nagent_loop 内では、終了前に発火:\n\n```python\nif response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages) # ← 終了する前に\n if force:\n # フックがメッセージを返した → 注入して続行\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n```\n\n**ループ内で変更されたのは一箇所だけ**:s03 は直接 `check_permission(block)` を呼び出していたが、s04 は `trigger_hooks(\"PreToolUse\", block)` に置き換えた:\n\n```python\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s03: if not check_permission(block): ...\n # s04: フックがハードコードを代替\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output)\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": output})\n```\n\n4 つのフックが agent cycle の重要ノードをカバー:入力→実行前→実行後→終了。ループは trigger_hooks() を呼ぶだけで、具体的なロジックは全てフックコールバックにある。\n\n---\n\n## s03 からの変更\n\n| コンポーネント | 変更前 (s03) | 変更後 (s04) |\n|--------------|-------------|-------------|\n| 拡張方式 | check_permission() をループ内にハードコード | HOOKS 登録簿 + trigger_hooks() |\n| 新規関数 | — | register_hook, trigger_hooks |\n| フックコールバック | — | context_inject_hook, permission_hook, log_hook, large_output_hook, summary_hook |\n| ループ | check_permission() を直接呼び出し | trigger_hooks(\"PreToolUse\", ...) を呼び出し |\n| 終了制御 | なし | trigger_hooks(\"Stop\", ...) が終了を阻止可能 |\n| 入力横取り | なし | trigger_hooks(\"UserPromptSubmit\", ...) がコンテキスト注入可能 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s04_hooks/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Read the file README.md`(そのまま通過するはず、フックログを観察)\n2. `Create a file called test.txt`(作成後、PostToolUse が発火するか観察)\n3. `Delete all temporary files in /tmp`(bash + rm で権限フックが発動)\n\n観察のポイント:各ツール実行前に `[HOOK]` ログが表示されるか? 権限が拒否されたとき、フックが拦截したのか、ループ内のハードコードが拦截したのか?\n\n---\n\n## 次へ\n\nAgent は安全に操作を実行できるようになった。しかし「まず何をして、次に何をすべきか」を立ち止まって考えたことはあるか? 複雑なタスクを与えたとき、すぐに取り掛かるのか、まず計画を立てるのか?\n\n→ s05 TodoWrite:Agent に計画ツールを与える。まずリストを作り、それから実行。\n\n
\nCC ソースコードを深掘り\n\n> 以下は CC ソースコード `toolHooks.ts`(650 行)、`hooks.ts`、`stopHooks.ts`、`coreTypes.ts` の完全分析に基づく。\n\n### 一、Hook イベント:4 つではなく 27 個\n\n教育版は PreToolUse と PostToolUse のみを取り上げる。CC には実際に 27 のフックイベントがある(`coreTypes.ts:25-53`):\n\n| カテゴリ | イベント |\n|----------|---------|\n| ツール関連 | `PreToolUse`, `PostToolUse`, `PostToolUseFailure` |\n| セッション関連 | `SessionStart`, `SessionEnd`, `Stop`, `StopFailure`, `Setup` |\n| ユーザー対話 | `UserPromptSubmit`, `Notification`, `PermissionRequest`, `PermissionDenied` |\n| サブエージェント | `SubagentStart`, `SubagentStop` |\n| 圧縮関連 | `PreCompact`, `PostCompact` |\n| チーム関連 | `TeammateIdle`, `TaskCreated`, `TaskCompleted` |\n| その他 | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `InstructionsLoaded`, `CwdChanged`, `FileChanged` |\n\n教育版は 4 つのコアイベント(UserPromptSubmit、PreToolUse、PostToolUse、Stop)のみを取り上げる。これらで agent cycle の重要ノードを全てカバーできる。残り 23 個は同じパターン。\n\n### 二、HookResult よく使うフィールド抜粋\n\nCC の `HookResult`(`types/hooks.ts:260-275`)には 14 のフィールドがある。よく使うもの:\n\n| フィールド | 型 | 用途 |\n|-----------|-----|------|\n| `message` | Message | オプションの UI メッセージ |\n| `blockingError` | HookBlockingError | ブロッキングエラー → 会話に注入してモデルが自己修正 |\n| `outcome` | success/blocking/non_blocking_error/cancelled | 実行結果 |\n| `preventContinuation` | boolean | 後続実行を阻止 |\n| `stopReason` | string | 停止理由の説明 |\n| `permissionBehavior` | allow/deny/ask/passthrough | フックが権限決定を返す |\n| `updatedInput` | Record | ツール入力の変更 |\n| `additionalContext` | string | 追加コンテキスト |\n| `updatedMCPToolOutput` | unknown | MCP ツール出力の変更 |\n\n### 三、重要な不変条件:Hook 'allow' は deny/ask ルールをバイパスできない\n\nこれは CC 権限システムで最も重要なセキュリティ設計(`toolHooks.ts:325-331`):**フックが allow を返しても、settings.json の deny/ask ルールをチェックする。** ユーザーのフックスクリプトが「許可」と言っても、settings.json でそのツールが無効になっていれば、操作は阻止される。\n\n教育版にはこの階層がない。フックが非 None を返せば直接中断。教育目的では十分だが、本番環境ではセキュリティホールになる。\n\n### 四、stopHookActive 機構\n\nCC の Stop フックには無限ループ防止機構がある(`query.ts:212,1300`):`stopHookActive` 状態フィールド。Stop フックが blockingError を発生させると、ループは `stopHookActive: true` で次のラウンドに再入する。後続のイテレーションではこのフラグを見て Stop フックを再トリガーしない。これで「永久に止まらない」バグを防ぐ:モデルが自己修正 → Stop フックが再度エラー → モデルが再修正 → Stop フックが再度エラー... を防止。\n\n### 五、hook_stopped_continuation\n\nPostToolUse フックが `preventContinuation: true` を返すと、`hook_stopped_continuation` アタッチメントが生成される(`toolHooks.ts:117-130`)。query.ts(L1388-1393)はそれを検出して `shouldPreventContinuation = true` を設定し、ループが終了する。これは「フックが Agent を優雅に停止させる」機構 — クラッシュではなく、完了。\n\n### 教育版の簡略化は意図的\n\n- 27 イベント → 4(UserPromptSubmit/PreToolUse/PostToolUse/Stop):agent cycle の重要ノードをカバー\n- 14 フィールド → 単純な戻り値(None = 続行、非 None = 中断/続行):認知負荷を最小限に\n- Hook allow vs deny/ask の不変条件 → 省略:教育版に settings.json 層はない\n- stopHookActive → 省略:教育版の Stop フックは単純な続行のみ、無限ループ防止は不要\n\n
\n\n\n" + "content": "# s04: Hooks — ループに掛ける、ループには書き込まない\n\ns01 → s02 → s03 → `s04` → [s05](/ja/s05) → s06 → ... → s20 → s21\n\n> *\"ループに掛ける、ループには書き込まない\"* — フックがツール実行の前後に拡張ロジックを注入する。\n>\n> **Harness レイヤー**: フック — ループを侵襲しない拡張ポイント。\n\n---\n\n## 課題\n\ns03 の Agent には権限チェックがある。しかし新しいチェックを追加するたび、「bash 呼び出しを毎回ログに記録」「操作後に自動 git add」、`agent_loop` 関数を修正する必要がある。\n\nループはすぐにこうなる:\n\n```python\ndef agent_loop(messages):\n while True:\n # ... LLM call ...\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n log_to_file(block) # 一行追加\n check_permission(block) # 一行追加\n notify_slack(block) # さらに一行追加\n output = execute(block)\n auto_git_add(block) # さらに一行追加\n # ... もうループが見えない\n```\n\n拡張したいのは Agent の振る舞いなのに、変更しているのはループそのもの。ループは安定した核心であるべき。拡張は外側に掛ける。\n\n---\n\n## ソリューション\n\n![Hooks Overview](/course-assets/s04_hooks/hooks-overview.ja.svg)\n\ns03 のループと権限ロジックは完全に保持される。唯一の変更点は `check_permission()` をループ本体内からフックに移動したこと。ループはもうチェック関数を直接呼び出さず、代わりに `trigger_hooks(\"PreToolUse\", block)` を呼び、登録済みのフックが何を実行するかを決める。\n\n4 つのイベントで、完全な agent cycle をカバー:\n\n| イベント | 発火タイミング | 典型的な用途 |\n|----------|--------------|-------------|\n| UserPromptSubmit | ユーザー入力後、LLM に入る前 | 入力バリデーション、コンテキスト注入 |\n| PreToolUse | ツール実行前 | 権限チェック、ログ記録 |\n| PostToolUse | ツール実行後 | 副作用(自動 git add など)、出力チェック |\n| Stop | ループが終了する直前 | 後処理、ループを続行するかの判断 |\n\n拡張は `register_hook()` で追加する。ループは `trigger_hooks()` を呼ぶだけ。\n\n---\n\n## 仕組み\n\n**フック登録簿**:イベント名をコールバックリストにマッピングする辞書。\n\n```python\nHOOKS = {\n \"UserPromptSubmit\": [],\n \"PreToolUse\": [],\n \"PostToolUse\": [],\n \"Stop\": [],\n}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # 戻り値 ≠ None → フックが「止め」と指示\n return result\n return None\n```\n\n`PreToolUse` が `None` 以外を返すと、現在のツール実行は中止される。`Stop` が `None` 以外を返すと、ループは続行する。`UserPromptSubmit` と `PostToolUse` の戻り値は制御フローに影響しない。\n\n**UserPromptSubmit** はユーザー入力後、LLM に入る前に発火する。以下の hook は現在の作業ディレクトリを記録する:\n\n```python\ndef context_inject_hook(query: str) -> str | None:\n \"\"\"Inject current working directory info into every prompt.\"\"\"\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None # return None = 変更なし、プロンプトを通す\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\n```\n\nメインループでは、ユーザー入力直後に発火:\n\n```python\nquery = input(\"s04 >> \")\ntrigger_hooks(\"UserPromptSubmit\", query) # ← LLM に入る前\nhistory.append({\"role\": \"user\", \"content\": query})\nagent_loop(history)\n```\n\n**PreToolUse / PostToolUse**、ツール実行の前後のフック。s03 の権限チェックロジックは PreToolUse フックに包まれ、さらにログフックと大出力リマインダーが追加される:\n\n```python\n# PreToolUse: 権限チェック(s03 のロジック、ループからフックに移動)\ndef permission_hook(block):\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n return \"Permission denied by deny list\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n# PreToolUse: ログ\ndef log_hook(block):\n print(f\"[HOOK] {block.name}(...)\")\n\n# PostToolUse: 大ファイルリマインダー\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"[HOOK] ⚠ Large output from {block.name}\")\n\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\n```\n\n**Stop** はループが終了する直前に発火する(`stop_reason != \"tool_use\"`)。以下の hook は終了時の統計を出力する:\n\n```python\ndef summary_hook(messages: list) -> str | None:\n \"\"\"Print a summary when the loop is about to stop.\"\"\"\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None # return None = 終了を許可、return 文字列 = 強制続行\n\nregister_hook(\"Stop\", summary_hook)\n```\n\nagent_loop 内では、終了前に発火:\n\n```python\nif response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages) # ← 終了する前に\n if force:\n # フックがメッセージを返した → 注入して続行\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n```\n\n**ループ内で変更されたのは一箇所だけ**:s03 は直接 `check_permission(block)` を呼び出していたが、s04 は `trigger_hooks(\"PreToolUse\", block)` に置き換えた:\n\n```python\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s03: if not check_permission(block): ...\n # s04: フックがハードコードを代替\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output)\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": output})\n```\n\n4 つのフックが agent cycle の重要ノードをカバー:入力→実行前→実行後→終了。ループは trigger_hooks() を呼ぶだけで、具体的なロジックは全てフックコールバックにある。\n\n---\n\n## s03 からの変更\n\n| コンポーネント | 変更前 (s03) | 変更後 (s04) |\n|--------------|-------------|-------------|\n| 拡張方式 | check_permission() をループ内にハードコード | HOOKS 登録簿 + trigger_hooks() |\n| 新規関数 | — | register_hook, trigger_hooks |\n| フックコールバック | — | context_inject_hook, permission_hook, log_hook, large_output_hook, summary_hook |\n| ループ | check_permission() を直接呼び出し | trigger_hooks(\"PreToolUse\", ...) を呼び出し |\n| 終了制御 | なし | trigger_hooks(\"Stop\", ...) が終了を阻止可能 |\n| 入力横取り | なし | trigger_hooks(\"UserPromptSubmit\", ...) がコンテキスト注入可能 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s04_hooks/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Read the file README.md`(そのまま通過するはず、フックログを観察)\n2. `Create a file called test.txt`(作成後、PostToolUse が発火するか観察)\n3. `Delete all temporary files in /tmp`(bash + rm で権限フックが発動)\n\n観察のポイント:各ツール実行前に `[HOOK]` ログが表示されるか? 権限が拒否されたとき、フックが拦截したのか、ループ内のハードコードが拦截したのか?\n\n---\n\n## 次へ\n\nAgent は安全に操作を実行できるようになった。しかし「まず何をして、次に何をすべきか」を立ち止まって考えたことはあるか? 複雑なタスクを与えたとき、すぐに取り掛かるのか、まず計画を立てるのか?\n\n→ s05 TodoWrite:Agent に計画ツールを与える。まずリストを作り、それから実行。\n\n\n\n" }, { "version": "s05", "locale": "en", "title": "s05: TodoWrite — An Agent Without a Plan Drifts Off Course", - "content": "# s05: TodoWrite — An Agent Without a Plan Drifts Off Course\n\ns01 → s02 → s03 → s04 → `s05` → [s06](/en/s06) → s07 → ... → s20 → s21 → s22\n\n> *\"An agent without a plan goes wherever the wind blows\"* — List the steps first, then execute. Complex tasks are less likely to miss steps.\n>\n> **Harness Layer**: Planning — Let the Agent think before it acts.\n\n---\n\n## The Problem\n\nGive the Agent a complex task: \"Rename all Python files to snake_case, run tests, and fix failures.\"\n\nThe Agent starts working, renames 3 files, runs a test, finds 2 failures, starts fixing. While fixing, it forgets the original goal was \"rename to snake_case\", the test failures have consumed all its attention.\n\nThe longer the conversation, the worse it gets: tool results keep filling the context, diluting the system prompt's influence. A 10-step refactoring: after steps 1-3, the Agent starts improvising because steps 4-10 have been pushed out of its attention.\n\n---\n\n## The Solution\n\n![Todo Overview](/course-assets/s05_todo_write/todo-overview.en.svg)\n\nThe minimal hook structure from the previous chapter is preserved, focusing on the new `todo_write` tool and reminder mechanism. `todo_write` does no actual work, can't read files or run commands, it simply lets the Agent organize its thoughts before diving in.\n\nThe dispatch mechanism is unchanged; the new tool is still routed through `TOOL_HANDLERS[block.name]`. However, to demonstrate the todo reminder, a counter was added to the loop: after 3 consecutive rounds without calling `todo_write`, a reminder is injected.\n\n---\n\n## How It Works\n\n**The todo_write tool** accepts a list with statuses, keeps it in the current process memory, and displays progress in the terminal:\n\n```python\nCURRENT_TODOS: list[dict] = []\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n CURRENT_TODOS = todos\n\n lines = [\"\\n## Current Tasks\"]\n for t in CURRENT_TODOS:\n icon = {\"pending\": \" \", \"in_progress\": \"▸\", \"completed\": \"✓\"}[t[\"status\"]]\n lines.append(f\" [{icon}] {t['content']}\")\n print(\"\\n\".join(lines))\n return f\"Updated {len(CURRENT_TODOS)} tasks\"\n```\n\nThe tool definition joins the other 5 in the dispatch map:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n # s05: new entry\n {\"name\": \"todo_write\", \"description\": \"Create and manage a task list ...\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"todos\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"in_progress\", \"completed\"]},\n },\n },\n },\n },\n },\n },\n]\n\nTOOL_HANDLERS[\"todo_write\"] = run_todo_write\n```\n\n**Nag reminder**, when the model hasn't called `todo_write` for 3 consecutive rounds, a reminder is automatically injected (teaching mechanism; CC source has no fixed round-count logic):\n\n```python\nif rounds_since_todo >= 3 and messages:\n messages.append({\n \"role\": \"user\",\n \"content\": \"Update your todos.\",\n })\n rounds_since_todo = 0\n```\n\nTypical flow when the Agent receives a task: first call `todo_write` to list all steps (all `pending`) → pick one step, set it to `in_progress` → complete it, set to `completed` → look at the next `pending` → continue. After 3 rounds without `todo_write`, the loop appends a reminder before the next LLM call.\n\n**Key insight**: todo_write doesn't give the Agent any additional **execution capability**. What it adds is **planning capability**.\n\n---\n\n## Changes from s04\n\n| Component | Before (s04) | After (s05) |\n|-----------|-------------|-------------|\n| Tool count | 5 (bash, read, write, edit, glob) | 6 (+todo_write) |\n| Planning | None | Stateful TODO list + nag reminder |\n| SYSTEM prompt | Generic prompt | Added \"plan before executing\" guidance |\n| Loop | Unchanged | Dispatch unchanged, added rounds_since_todo counter and reminder injection |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s05_todo_write/code.py\n```\n\nTry these prompts:\n\n1. `Refactor s05_todo_write/example/hello.py: add type hints, docstrings, and a main guard` (should list 3 steps first, then execute)\n2. `Create a Python package under s05_todo_write/example/demo_pkg with __init__.py, utils.py, and tests/test_utils.py`\n3. `Review Python files under s05_todo_write/example and fix any style issues`\n\nWhat to watch for: Was the first tool call `todo_write`? How many TODO steps were listed? Did statuses move from `pending` to `in_progress` / `completed` during execution?\n\n---\n\n## What's Next\n\nThe Agent can plan now. But if a task is too large, say \"refactor the entire auth module\", a TODO list alone isn't enough. That task is itself a collection of dozens of subtasks that would drown in a single conversation's context.\n\n→ s06 Subagent: Break large tasks into subtasks, each handled by an independent Agent with its own clean context, no cross-contamination.\n\n
\nDive into CC Source Code\n\nClaude Code has two planning surfaces with a shared intent but independent storage and tool contracts:\n\n- **TodoWrite**: A session checklist. Each call replaces the whole list, and the teaching version likewise keeps it in process memory and clears it on exit.\n- **Task tools (covered in s12)**: Individually addressable task records with stable IDs, dependency fields, ownership, and persistence.\n\nCurrent interactive sessions use the structured Task tools by default, while TodoWrite remains available on compatibility surfaces such as non-interactive and Agent SDK usage. Exact exposure can vary by release and configuration. Do not model this as one schema being upgraded in place: they are separate mechanisms, and s05 teaches the lighter checklist contract.\n\nThe teaching version omits the `activeForm` field from the real source (`utils/todo/types.ts:8-15`). CC uses it for the UI spinner to show \"what's being done\"; the teaching version only has terminal output and doesn't need this field.\n\nThe teaching version's nag reminder (3 rounds without update triggers injection) is an educational mechanism. The CC source has no fixed \"3 rounds\" logic; the closest is `TodoWriteTool.ts:72-107` which appends a verification nudge when 3+ todos are all completed without a verification item.\n\nCore increments of the Task System over TodoWrite:\n- File persistence (Claude config directory `tasks/{taskListId}/{taskId}.json`) instead of in-memory list\n- `blockedBy` dependency graph instead of flat list\n- `proper-lockfile` concurrency safety instead of no locking\n- Four separate tools (Create/Get/Update/List) instead of one\n- TaskCreated / TaskCompleted hooks (`TaskCreateTool.ts:80-129`, `TaskUpdateTool.ts:231-260`) for external system integration\n\n
\n\n\n" + "content": "# s05: TodoWrite — An Agent Without a Plan Drifts Off Course\n\ns01 → s02 → s03 → s04 → `s05` → [s06](/en/s06) → s07 → ... → s20 → s21\n\n> *\"An agent without a plan goes wherever the wind blows\"* — List the steps first, then execute. Complex tasks are less likely to miss steps.\n>\n> **Harness Layer**: Planning — Let the Agent think before it acts.\n\n---\n\n## The Problem\n\nGive the Agent a complex task: \"Rename all Python files to snake_case, run tests, and fix failures.\"\n\nThe Agent starts working, renames 3 files, runs a test, finds 2 failures, starts fixing. While fixing, it forgets the original goal was \"rename to snake_case\", the test failures have consumed all its attention.\n\nThe longer the conversation, the worse it gets: tool results keep filling the context, diluting the system prompt's influence. A 10-step refactoring: after steps 1-3, the Agent starts improvising because steps 4-10 have been pushed out of its attention.\n\n---\n\n## The Solution\n\n![Todo Overview](/course-assets/s05_todo_write/todo-overview.en.svg)\n\nThe minimal hook structure from the previous chapter is preserved, focusing on the new `todo_write` tool and reminder mechanism. `todo_write` does no actual work, can't read files or run commands, it simply lets the Agent organize its thoughts before diving in.\n\nThe dispatch mechanism is unchanged; the new tool is still routed through `TOOL_HANDLERS[block.name]`. However, to demonstrate the todo reminder, a counter was added to the loop: after 3 consecutive rounds without calling `todo_write`, a reminder is injected.\n\n---\n\n## How It Works\n\n**The todo_write tool** accepts a list with statuses, keeps it in the current process memory, and displays progress in the terminal:\n\n```python\nCURRENT_TODOS: list[dict] = []\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n CURRENT_TODOS = todos\n\n lines = [\"\\n## Current Tasks\"]\n for t in CURRENT_TODOS:\n icon = {\"pending\": \" \", \"in_progress\": \"▸\", \"completed\": \"✓\"}[t[\"status\"]]\n lines.append(f\" [{icon}] {t['content']}\")\n print(\"\\n\".join(lines))\n return f\"Updated {len(CURRENT_TODOS)} tasks\"\n```\n\nThe tool definition joins the other 5 in the dispatch map:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n # s05: new entry\n {\"name\": \"todo_write\", \"description\": \"Create and manage a task list ...\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"todos\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"in_progress\", \"completed\"]},\n },\n },\n },\n },\n },\n },\n]\n\nTOOL_HANDLERS[\"todo_write\"] = run_todo_write\n```\n\n**Nag reminder**: when the model has not called `todo_write` for 3 consecutive rounds, a reminder is automatically injected:\n\n```python\nif rounds_since_todo >= 3 and messages:\n messages.append({\n \"role\": \"user\",\n \"content\": \"Update your todos.\",\n })\n rounds_since_todo = 0\n```\n\nTypical flow when the Agent receives a task: first call `todo_write` to list all steps (all `pending`) → pick one step, set it to `in_progress` → complete it, set to `completed` → look at the next `pending` → continue. After 3 rounds without `todo_write`, the loop appends a reminder before the next LLM call.\n\n**Key insight**: todo_write doesn't give the Agent any additional **execution capability**. What it adds is **planning capability**.\n\n---\n\n## Changes from s04\n\n| Component | Before (s04) | After (s05) |\n|-----------|-------------|-------------|\n| Tool count | 5 (bash, read, write, edit, glob) | 6 (+todo_write) |\n| Planning | None | Stateful TODO list + nag reminder |\n| SYSTEM prompt | Generic prompt | Added \"plan before executing\" guidance |\n| Loop | Unchanged | Dispatch unchanged, added rounds_since_todo counter and reminder injection |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s05_todo_write/code.py\n```\n\nTry these prompts:\n\n1. `Refactor s05_todo_write/example/hello.py: add type hints, docstrings, and a main guard` (should list 3 steps first, then execute)\n2. `Create a Python package under s05_todo_write/example/demo_pkg with __init__.py, utils.py, and tests/test_utils.py`\n3. `Review Python files under s05_todo_write/example and fix any style issues`\n\nWhat to watch for: Was the first tool call `todo_write`? How many TODO steps were listed? Did statuses move from `pending` to `in_progress` / `completed` during execution?\n\n---\n\n## What's Next\n\nThe Agent can plan now. But if a task is too large, say \"refactor the entire auth module\", a TODO list alone isn't enough. That task is itself a collection of dozens of subtasks that would drown in a single conversation's context.\n\n→ s06 Subagent: Break large tasks into subtasks, each handled by an independent Agent with its own clean context, no cross-contamination.\n\n\n\n" }, { "version": "s05", "locale": "zh", "title": "s05: TodoWrite — 没有计划的 Agent,做着做着就偏了", - "content": "# s05: TodoWrite — 没有计划的 Agent,做着做着就偏了\n\ns01 → s02 → s03 → s04 → `s05` → [s06](/zh/s06) → s07 → ... → s20 → s21 → s22\n\n> *\"没有计划的 agent 走哪算哪\"* — 先列步骤再动手,长任务更不容易漏项。\n>\n> **Harness 层**: 规划 — 让 Agent 在动手之前先想清楚。\n\n---\n\n## 问题\n\n给 Agent 一个复杂任务:\"把所有 Python 文件改成 snake_case 命名,然后跑测试,修好失败。\"\n\nAgent 开始干活,改了 3 个文件,跑了个测试,发现 2 个失败,开始修。修着修着,它忘了最初是\"改成 snake_case\",测试失败把注意力全吸走了。\n\n对话越长越严重:工具结果不断填满上下文,系统提示的影响力被稀释。一个 10 步重构,做完 1-3 步就开始即兴发挥,因为 4-10 步已经被挤出注意力了。\n\n---\n\n## 解决方案\n\n![Todo Overview](/course-assets/s05_todo_write/todo-overview.svg)\n\n保留上一章的最小 hook 结构,重点看新增的 `todo_write` 工具和 reminder 机制。`todo_write` 本身不做任何实际工作,不能读文件、不能跑命令,只是让 Agent 在动手之前先理清思路。\n\ndispatch 机制不变,新工具仍然走 `TOOL_HANDLERS[block.name]` 分发。但为了演示 todo reminder,循环里加了一个计数器:连续 3 轮没调 `todo_write` 就注入一条提醒。\n\n---\n\n## 工作原理\n\n**todo_write 工具**,接收一个带状态的列表,保存在当前进程内存中,同时在终端显示进度:\n\n```python\nCURRENT_TODOS: list[dict] = []\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n CURRENT_TODOS = todos\n\n lines = [\"\\n## Current Tasks\"]\n for t in CURRENT_TODOS:\n icon = {\"pending\": \" \", \"in_progress\": \"▸\", \"completed\": \"✓\"}[t[\"status\"]]\n lines.append(f\" [{icon}] {t['content']}\")\n print(\"\\n\".join(lines))\n return f\"Updated {len(CURRENT_TODOS)} tasks\"\n```\n\n工具定义和其他 5 个工具一起加入 dispatch map:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n # s05: 新增一条\n {\"name\": \"todo_write\", \"description\": \"Create and manage a task list ...\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"todos\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"in_progress\", \"completed\"]},\n },\n },\n },\n },\n },\n },\n]\n\nTOOL_HANDLERS[\"todo_write\"] = run_todo_write\n```\n\n**Nag reminder**,模型连续 3 轮没调 `todo_write` 时,自动注入一条提醒(教学版机制,CC 源码中没有这个固定轮数逻辑):\n\n```python\nif rounds_since_todo >= 3 and messages:\n messages.append({\n \"role\": \"user\",\n \"content\": \"Update your todos.\",\n })\n rounds_since_todo = 0\n```\n\nAgent 收到任务后的典型流程:先调 `todo_write` 列出所有步骤(全 `pending`)→ 做一个步骤,改成 `in_progress` → 做完改成 `completed` → 看下一个 `pending` → 继续。连续 3 轮没有调用 `todo_write` 时,循环会在下一次 LLM 调用前追加一条 reminder。\n\n**关键洞察**:todo_write 不给 Agent 增加任何**执行能力**。它增加的是**规划能力**。\n\n---\n\n## 相对 s04 的变更\n\n| 组件 | 之前 (s04) | 之后 (s05) |\n|------|-----------|-----------|\n| 工具数量 | 5 (bash, read, write, edit, glob) | 6 (+todo_write) |\n| 规划能力 | 无 | 带状态的 TODO 列表 + nag reminder |\n| SYSTEM 提示 | 通用提示 | 加入 \"先计划再执行\" 引导 |\n| 循环 | 不变 | dispatch 不变,新增 rounds_since_todo 计数器和 reminder 注入 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s05_todo_write/code.py\n```\n\n试试这些 prompt:\n\n1. `Refactor s05_todo_write/example/hello.py: add type hints, docstrings, and a main guard`(先列 3 步再执行)\n2. `Create a Python package under s05_todo_write/example/demo_pkg with __init__.py, utils.py, and tests/test_utils.py`\n3. `Review Python files under s05_todo_write/example and fix any style issues`\n\n观察重点:第一次工具调用是不是 `todo_write`?TODO 列了几步?执行过程中状态有没有从 `pending` 变成 `in_progress` / `completed`?\n\n---\n\n## 接下来\n\nAgent 能计划了。但如果一个任务太大,比如\"重构整个认证模块\",光靠 TODO 列表不够。这个任务本身就是几十个小任务的集合,放在同一个对话里会被上下文淹没。\n\ns06 Subagent → 把大任务拆成子任务,每个子任务派一个独立的 Agent。它们有自己的干净上下文,不会互相污染。\n\n
\n深入 CC 源码\n\nClaude Code 有两种目标相近、但存储与工具契约相互独立的规划机制:\n\n- **TodoWrite**:当前会话的轻量清单。每次调用替换整个列表;教学版同样保存在进程内存,退出后清空\n- **Task 工具(s12)**:带稳定 ID 的独立任务记录,支持依赖、ownership 与持久化\n\n当前交互式会话默认使用结构化 Task 工具;TodoWrite 仍保留在非交互式、Agent SDK 等兼容表面。具体暴露方式会随版本与配置变化。不要把它理解成同一个 schema 原地升级:两者是独立机制,s05 只教授较轻的清单契约。\n\n教学版省略了真实源码中的 `activeForm` 字段(`utils/todo/types.ts:8-15`)。CC 用它给 UI spinner 展示\"正在做什么\",教学版只有终端输出,不需要这个字段。\n\n教学版的 nag reminder(3 轮未更新就注入提醒)是教学机制。CC 源码中没有固定的\"3 轮\"逻辑,更接近的是 `TodoWriteTool.ts:72-107` 中当 3 个以上 todo 全部完成但没有 verification 项时,追加 verification nudge。\n\nTask System 相比 TodoWrite 的核心增量:\n- 文件持久化(Claude 配置目录下 `tasks/{taskListId}/{taskId}.json`)而非内存列表\n- `blockedBy` 依赖图而非平铺列表\n- `proper-lockfile` 并发安全而非无锁\n- 四个独立工具(Create/Get/Update/List)而非一个\n- TaskCreated / TaskCompleted hooks(`TaskCreateTool.ts:80-129`、`TaskUpdateTool.ts:231-260`)供外部系统集成\n\n
\n\n\n" + "content": "# s05: TodoWrite — 没有计划的 Agent,做着做着就偏了\n\ns01 → s02 → s03 → s04 → `s05` → [s06](/zh/s06) → s07 → ... → s20 → s21\n\n> *\"没有计划的 agent 走哪算哪\"* — 先列步骤再动手,长任务更不容易漏项。\n>\n> **Harness 层**: 规划 — 让 Agent 在动手之前先想清楚。\n\n---\n\n## 问题\n\n给 Agent 一个复杂任务:\"把所有 Python 文件改成 snake_case 命名,然后跑测试,修好失败。\"\n\nAgent 开始干活,改了 3 个文件,跑了个测试,发现 2 个失败,开始修。修着修着,它忘了最初是\"改成 snake_case\",测试失败把注意力全吸走了。\n\n对话越长越严重:工具结果不断填满上下文,系统提示的影响力被稀释。一个 10 步重构,做完 1-3 步就开始即兴发挥,因为 4-10 步已经被挤出注意力了。\n\n---\n\n## 解决方案\n\n![Todo Overview](/course-assets/s05_todo_write/todo-overview.svg)\n\n保留上一章的最小 hook 结构,重点看新增的 `todo_write` 工具和 reminder 机制。`todo_write` 本身不做任何实际工作,不能读文件、不能跑命令,只是让 Agent 在动手之前先理清思路。\n\ndispatch 机制不变,新工具仍然走 `TOOL_HANDLERS[block.name]` 分发。但为了演示 todo reminder,循环里加了一个计数器:连续 3 轮没调 `todo_write` 就注入一条提醒。\n\n---\n\n## 工作原理\n\n**todo_write 工具**,接收一个带状态的列表,保存在当前进程内存中,同时在终端显示进度:\n\n```python\nCURRENT_TODOS: list[dict] = []\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n CURRENT_TODOS = todos\n\n lines = [\"\\n## Current Tasks\"]\n for t in CURRENT_TODOS:\n icon = {\"pending\": \" \", \"in_progress\": \"▸\", \"completed\": \"✓\"}[t[\"status\"]]\n lines.append(f\" [{icon}] {t['content']}\")\n print(\"\\n\".join(lines))\n return f\"Updated {len(CURRENT_TODOS)} tasks\"\n```\n\n工具定义和其他 5 个工具一起加入 dispatch map:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n # s05: 新增一条\n {\"name\": \"todo_write\", \"description\": \"Create and manage a task list ...\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"todos\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"in_progress\", \"completed\"]},\n },\n },\n },\n },\n },\n },\n]\n\nTOOL_HANDLERS[\"todo_write\"] = run_todo_write\n```\n\n**Nag reminder**:模型连续 3 轮未调用 `todo_write` 时,自动注入提醒:\n\n```python\nif rounds_since_todo >= 3 and messages:\n messages.append({\n \"role\": \"user\",\n \"content\": \"Update your todos.\",\n })\n rounds_since_todo = 0\n```\n\nAgent 收到任务后的典型流程:先调 `todo_write` 列出所有步骤(全 `pending`)→ 做一个步骤,改成 `in_progress` → 做完改成 `completed` → 看下一个 `pending` → 继续。连续 3 轮没有调用 `todo_write` 时,循环会在下一次 LLM 调用前追加一条 reminder。\n\n**关键洞察**:todo_write 不给 Agent 增加任何**执行能力**。它增加的是**规划能力**。\n\n---\n\n## 相对 s04 的变更\n\n| 组件 | 之前 (s04) | 之后 (s05) |\n|------|-----------|-----------|\n| 工具数量 | 5 (bash, read, write, edit, glob) | 6 (+todo_write) |\n| 规划能力 | 无 | 带状态的 TODO 列表 + nag reminder |\n| SYSTEM 提示 | 通用提示 | 加入 \"先计划再执行\" 引导 |\n| 循环 | 不变 | dispatch 不变,新增 rounds_since_todo 计数器和 reminder 注入 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s05_todo_write/code.py\n```\n\n试试这些 prompt:\n\n1. `Refactor s05_todo_write/example/hello.py: add type hints, docstrings, and a main guard`(先列 3 步再执行)\n2. `Create a Python package under s05_todo_write/example/demo_pkg with __init__.py, utils.py, and tests/test_utils.py`\n3. `Review Python files under s05_todo_write/example and fix any style issues`\n\n观察重点:第一次工具调用是不是 `todo_write`?TODO 列了几步?执行过程中状态有没有从 `pending` 变成 `in_progress` / `completed`?\n\n---\n\n## 接下来\n\nAgent 能计划了。但如果一个任务太大,比如\"重构整个认证模块\",光靠 TODO 列表不够。这个任务本身就是几十个小任务的集合,放在同一个对话里会被上下文淹没。\n\ns06 Subagent → 把大任务拆成子任务,每个子任务派一个独立的 Agent。它们有自己的干净上下文,不会互相污染。\n\n\n\n" }, { "version": "s05", "locale": "ja", "title": "s05: TodoWrite — 計画なき Agent は途中で道を外れる", - "content": "# s05: TodoWrite — 計画なき Agent は途中で道を外れる\n\ns01 → s02 → s03 → s04 → `s05` → [s06](/ja/s06) → s07 → ... → s20 → s21 → s22\n\n> *\"計画なき agent は風の向くままに\"* — まず手順を列挙してから実行。長いタスクで見落としが減る。\n>\n> **Harness レイヤー**: 計画 — Agent が行動する前に考えさせる。\n\n---\n\n## 課題\n\nAgent に複雑なタスクを与える:「全 Python ファイルを snake_case にリネームし、テストを実行し、失敗を修正して。」\n\nAgent は作業を開始する。3 つのファイルをリネーム、テストを実行、2 つの失敗を発見、修正を開始。修正しているうちに、本来の目的が「snake_case にリネーム」だったことを忘れる。テストの失敗に注意を全て持っていかれる。\n\n会話が長くなるほど悪化する:ツールの結果がコンテキストを埋め続け、システムプロンプトの影響力が希釈される。10 ステップのリファクタリング:ステップ 1-3 を終えた時点で Agent は即興で動き始める。ステップ 4-10 は既に注意の外に追い出されているから。\n\n---\n\n## ソリューション\n\n![Todo Overview](/course-assets/s05_todo_write/todo-overview.ja.svg)\n\n前章の最小フック構造を保持し、本章では新規の `todo_write` ツールとリマインダー機構に注目する。`todo_write` は実際の作業を何もしない。ファイルを読めない、コマンドを実行できない。Agent が手を動かす前に思考を整理できるようにするだけ。\n\nディスパッチ機構は変わらず、新ツールも `TOOL_HANDLERS[block.name]` を経由する。ただし、todo リマインダーのデモのため、ループにカウンターを追加した:連続 3 ラウンド `todo_write` を呼び出さないとリマインダーが注入される。\n\n---\n\n## 仕組み\n\n**todo_write ツール**は、ステータス付きのリストを受け取り、現在のプロセスメモリに保持し、端末に進捗を表示する:\n\n```python\nCURRENT_TODOS: list[dict] = []\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n CURRENT_TODOS = todos\n\n lines = [\"\\n## Current Tasks\"]\n for t in CURRENT_TODOS:\n icon = {\"pending\": \" \", \"in_progress\": \"▸\", \"completed\": \"✓\"}[t[\"status\"]]\n lines.append(f\" [{icon}] {t['content']}\")\n print(\"\\n\".join(lines))\n return f\"Updated {len(CURRENT_TODOS)} tasks\"\n```\n\nツール定義は他の 5 つと一緒にディスパッチマップに追加される:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n # s05: 新規追加\n {\"name\": \"todo_write\", \"description\": \"Create and manage a task list ...\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"todos\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"in_progress\", \"completed\"]},\n },\n },\n },\n },\n },\n },\n]\n\nTOOL_HANDLERS[\"todo_write\"] = run_todo_write\n```\n\n**Nag リマインダー**、モデルが連続 3 ラウンド `todo_write` を呼び出さないとき、リマインダーが自動的に注入される(教育用機構、CC ソースコードに固定ラウンド数のロジックはない):\n\n```python\nif rounds_since_todo >= 3 and messages:\n messages.append({\n \"role\": \"user\",\n \"content\": \"Update your todos.\",\n })\n rounds_since_todo = 0\n```\n\nAgent がタスクを受け取った後の典型的な流れ:まず `todo_write` を呼び出して全手順を列挙(全て `pending`)→ 一つの手順に取り掛かり、`in_progress` に変更 → 完了したら `completed` に変更 → 次の `pending` を見る → 続行。3 ラウンド `todo_write` がない場合、次の LLM 呼び出し前にリマインダーが追加される。\n\n**重要な洞察**:todo_write は Agent に**実行能力**を何も追加しない。追加するのは**計画能力**だ。\n\n---\n\n## s04 からの変更\n\n| コンポーネント | 変更前 (s04) | 変更後 (s05) |\n|--------------|-------------|-------------|\n| ツール数 | 5 (bash, read, write, edit, glob) | 6 (+todo_write) |\n| 計画能力 | なし | ステータス付き TODO リスト + Nag リマインダー |\n| SYSTEM プロンプト | 汎用プロンプト | 「先に計画してから実行」のガイダンスを追加 |\n| ループ | 不変 | ディスパッチは不変、rounds_since_todo カウンターとリマインダー注入を追加 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s05_todo_write/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Refactor s05_todo_write/example/hello.py: add type hints, docstrings, and a main guard`(まず 3 手順を列挙してから実行するはず)\n2. `Create a Python package under s05_todo_write/example/demo_pkg with __init__.py, utils.py, and tests/test_utils.py`\n3. `Review Python files under s05_todo_write/example and fix any style issues`\n\n観察のポイント:最初のツール呼び出しは `todo_write` か? TODO は何手順列挙されたか? 実行中にステータスが `pending` から `in_progress` / `completed` に変わったか?\n\n---\n\n## 次へ\n\nAgent は計画できるようになった。しかしタスクが大きすぎる場合、例えば「認証モジュール全体をリファクタリング」、TODO リストだけでは不十分。そのタスク自体が数十のサブタスクの集合体で、同じ会話のコンテキストに押し込めると溢れてしまう。\n\n→ s06 Subagent:大きなタスクをサブタスクに分割し、それぞれを独立した Agent に任せる。それぞれが独自のクリーンなコンテキストを持ち、相互汚染がない。\n\n
\nCC ソースコードを深掘り\n\nClaude Code には、目的は近いがストレージとツール契約が独立した二つの計画機構がある:\n\n- **TodoWrite**:現在のセッション向けの軽量チェックリスト。呼び出しごとにリスト全体を置き換え、教育版もプロセスメモリに保持して終了時に消える\n- **Task ツール(s12)**:安定 ID を持つ個別タスクレコードで、依存関係、ownership、永続化を扱う\n\n現在の対話型セッションは構造化 Task ツールを既定で使い、TodoWrite は非対話型や Agent SDK などの互換サーフェスに残る。公開範囲はリリースや設定で変わり得る。同じ schema のインプレース更新ではなく独立した機構であり、s05 は軽量なチェックリスト契約だけを扱う。\n\n教育版は実際のソースコードにある `activeForm` フィールドを省略している(`utils/todo/types.ts:8-15`)。CC は UI スピナーに「何をしているか」を表示するために使用するが、教育版は端末出力のみでこのフィールドは不要。\n\n教育版の Nag リマインダー(3 ラウンド未更新で注入)は教育用機構。CC ソースコードに固定「3 ラウンド」のロジックはなく、最も近いのは `TodoWriteTool.ts:72-107` で 3 つ以上の todo が全て完了しているのに verification 項目がない場合に verification nudge を追加する処理。\n\nTask System の TodoWrite に対する核心的な増分:\n- メモリリストではなくファイル永続化(Claude 設定ディレクトリ下 `tasks/{taskListId}/{taskId}.json`)\n- 平坦なリストではなく `blockedBy` 依存グラフ\n- ロックなしではなく `proper-lockfile` による並行安全性\n- 一つのツールではなく四つの独立ツール(Create/Get/Update/List)\n- TaskCreated / TaskCompleted フック(`TaskCreateTool.ts:80-129`、`TaskUpdateTool.ts:231-260`)による外部システム統合\n\n
\n\n\n" + "content": "# s05: TodoWrite — 計画なき Agent は途中で道を外れる\n\ns01 → s02 → s03 → s04 → `s05` → [s06](/ja/s06) → s07 → ... → s20 → s21\n\n> *\"計画なき agent は風の向くままに\"* — まず手順を列挙してから実行。長いタスクで見落としが減る。\n>\n> **Harness レイヤー**: 計画 — Agent が行動する前に考えさせる。\n\n---\n\n## 課題\n\nAgent に複雑なタスクを与える:「全 Python ファイルを snake_case にリネームし、テストを実行し、失敗を修正して。」\n\nAgent は作業を開始する。3 つのファイルをリネーム、テストを実行、2 つの失敗を発見、修正を開始。修正しているうちに、本来の目的が「snake_case にリネーム」だったことを忘れる。テストの失敗に注意を全て持っていかれる。\n\n会話が長くなるほど悪化する:ツールの結果がコンテキストを埋め続け、システムプロンプトの影響力が希釈される。10 ステップのリファクタリング:ステップ 1-3 を終えた時点で Agent は即興で動き始める。ステップ 4-10 は既に注意の外に追い出されているから。\n\n---\n\n## ソリューション\n\n![Todo Overview](/course-assets/s05_todo_write/todo-overview.ja.svg)\n\n前章の最小フック構造を保持し、本章では新規の `todo_write` ツールとリマインダー機構に注目する。`todo_write` は実際の作業を何もしない。ファイルを読めない、コマンドを実行できない。Agent が手を動かす前に思考を整理できるようにするだけ。\n\nディスパッチ機構は変わらず、新ツールも `TOOL_HANDLERS[block.name]` を経由する。ただし、todo リマインダーのデモのため、ループにカウンターを追加した:連続 3 ラウンド `todo_write` を呼び出さないとリマインダーが注入される。\n\n---\n\n## 仕組み\n\n**todo_write ツール**は、ステータス付きのリストを受け取り、現在のプロセスメモリに保持し、端末に進捗を表示する:\n\n```python\nCURRENT_TODOS: list[dict] = []\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n CURRENT_TODOS = todos\n\n lines = [\"\\n## Current Tasks\"]\n for t in CURRENT_TODOS:\n icon = {\"pending\": \" \", \"in_progress\": \"▸\", \"completed\": \"✓\"}[t[\"status\"]]\n lines.append(f\" [{icon}] {t['content']}\")\n print(\"\\n\".join(lines))\n return f\"Updated {len(CURRENT_TODOS)} tasks\"\n```\n\nツール定義は他の 5 つと一緒にディスパッチマップに追加される:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n # s05: 新規追加\n {\"name\": \"todo_write\", \"description\": \"Create and manage a task list ...\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"todos\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"in_progress\", \"completed\"]},\n },\n },\n },\n },\n },\n },\n]\n\nTOOL_HANDLERS[\"todo_write\"] = run_todo_write\n```\n\n**Nag リマインダー**:モデルが 3 ラウンド連続で `todo_write` を呼び出さなかった場合、リマインダーが自動的に注入される:\n\n```python\nif rounds_since_todo >= 3 and messages:\n messages.append({\n \"role\": \"user\",\n \"content\": \"Update your todos.\",\n })\n rounds_since_todo = 0\n```\n\nAgent がタスクを受け取った後の典型的な流れ:まず `todo_write` を呼び出して全手順を列挙(全て `pending`)→ 一つの手順に取り掛かり、`in_progress` に変更 → 完了したら `completed` に変更 → 次の `pending` を見る → 続行。3 ラウンド `todo_write` がない場合、次の LLM 呼び出し前にリマインダーが追加される。\n\n**重要な洞察**:todo_write は Agent に**実行能力**を何も追加しない。追加するのは**計画能力**だ。\n\n---\n\n## s04 からの変更\n\n| コンポーネント | 変更前 (s04) | 変更後 (s05) |\n|--------------|-------------|-------------|\n| ツール数 | 5 (bash, read, write, edit, glob) | 6 (+todo_write) |\n| 計画能力 | なし | ステータス付き TODO リスト + Nag リマインダー |\n| SYSTEM プロンプト | 汎用プロンプト | 「先に計画してから実行」のガイダンスを追加 |\n| ループ | 不変 | ディスパッチは不変、rounds_since_todo カウンターとリマインダー注入を追加 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s05_todo_write/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Refactor s05_todo_write/example/hello.py: add type hints, docstrings, and a main guard`(まず 3 手順を列挙してから実行するはず)\n2. `Create a Python package under s05_todo_write/example/demo_pkg with __init__.py, utils.py, and tests/test_utils.py`\n3. `Review Python files under s05_todo_write/example and fix any style issues`\n\n観察のポイント:最初のツール呼び出しは `todo_write` か? TODO は何手順列挙されたか? 実行中にステータスが `pending` から `in_progress` / `completed` に変わったか?\n\n---\n\n## 次へ\n\nAgent は計画できるようになった。しかしタスクが大きすぎる場合、例えば「認証モジュール全体をリファクタリング」、TODO リストだけでは不十分。そのタスク自体が数十のサブタスクの集合体で、同じ会話のコンテキストに押し込めると溢れてしまう。\n\n→ s06 Subagent:大きなタスクをサブタスクに分割し、それぞれを独立した Agent に任せる。それぞれが独自のクリーンなコンテキストを持ち、相互汚染がない。\n\n\n\n" }, { "version": "s06", "locale": "en", "title": "s06: Subagent — Break Large Tasks into Small Ones with Clean Context", - "content": "# s06: Subagent — Break Large Tasks into Small Ones with Clean Context\n\ns01 → s02 → s03 → s04 → s05 → `s06` → [s07](/en/s07) → s08 → ... → s20 → s21 → s22\n\n> *\"Break large tasks small, each with clean context\"* — Subagent uses an independent messages[], no pollution in the main conversation.\n>\n> **Harness Layer**: Sub-Agent — Context isolation, attention doesn't drift.\n\n---\n\n## The Problem\n\nThe Agent is fixing a bug. It reads 30 files to trace the call chain, chatting for 60 rounds along the way. The messages list grows to 120 entries, most of which are intermediate steps from \"tracing the call chain\" — unrelated to the final goal of \"fixing the bug.\"\n\nThese intermediate steps occupy context space, making the Agent increasingly \"forgetful\" — it can no longer remember what the original problem was.\n\nThink of it differently: when you fix a bug, you'd \"open a new terminal\" to trace the call chain. When done, close the terminal, write the result into your notes, and return to the original terminal to keep fixing. The Agent needs this ability too — **open an independent sub-process, give it an independent message list, let it focus on one thing.**\n\n---\n\n## The Solution\n\n![Subagent Overview](/course-assets/s06_subagent/subagent-overview.en.svg)\n\nThe minimal hook structure and `todo_write` tool from the previous chapter are preserved; this chapter focuses on the new `task` tool. When called, it spawns a sub-Agent with a fresh `messages[]`, running its own loop, and returning only a summary text to the main Agent. Conversation context is discarded, but file system side effects (writes, edits, commands) remain in the working directory.\n\nThe sub-Agent's tools are restricted: it has bash/read/write/edit/glob, but no task, preventing recursive spawning. The sub-Agent's tool calls still go through permission hooks; context isolation does not bypass security.\n\n---\n\n## How It Works\n\n**spawn_subagent**, gives the sub-Agent a fresh messages list, runs its own loop, returns only the conclusion:\n\n```python\ndef spawn_subagent(description: str) -> str:\n # Sub-Agent tools: base tools, but no task (no recursion)\n sub_tools = [...]\n messages = [{\"role\": \"user\", \"content\": description}] # fresh messages[]\n\n for _ in range(30): # safety limit\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM,\n messages=messages, tools=sub_tools, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({... \"content\": str(blocked)})\n continue\n handler = SUB_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown\"\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({... \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # Return only the final text conclusion, all intermediate steps discarded\n return extract_text(messages[-1][\"content\"])\n```\n\nThe main Agent calls it just like any other tool:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n {\"name\": \"todo_write\", ...},\n # s06: new task tool\n {\"name\": \"task\",\n \"description\": \"Launch a subagent to handle a complex subtask. Returns only the final conclusion.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"description\": {\"type\": \"string\"}}, \"required\": [\"description\"]}},\n]\n\nTOOL_HANDLERS[\"task\"] = spawn_subagent\n```\n\nThree key design decisions:\n\n| Decision | Choice | Reason |\n|----------|--------|--------|\n| Context isolation | Fresh `messages[]` | Sub-Agent's intermediate steps don't pollute main Agent's context |\n| Return only conclusion | `extract_text(last_message)` | Not returning the entire messages list |\n| No recursion | Sub-Agent has no task tool | Prevents sub-Agent from spawning further sub-Agents |\n| Security not bypassed | Sub-Agent tool calls go through PreToolUse hook | Context isolation does not mean permission isolation |\n\nThe dispatch mechanism is unchanged; the task tool is routed through `TOOL_HANDLERS[block.name]`. The sub-Agent has its own `SUB_SYSTEM` prompt, explicitly instructing \"complete the task, do not delegate further.\"\n\n---\n\n## Changes from s05\n\n| Component | Before (s05) | After (s06) |\n|-----------|-------------|-------------|\n| Tool count | 6 (bash, read, write, edit, glob, todo_write) | 7 (+task) |\n| New function | — | spawn_subagent (independent messages[] + 30-round safety limit) |\n| Context isolation | Everything in the main conversation | Sub-Agent uses fresh messages[] |\n| Loop | Unchanged | Dispatch unchanged, sub-Agent has independent SUB_SYSTEM and hook-protected loop |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s06_subagent/code.py\n```\n\nTry these prompts:\n\n1. `Use a subtask to find what testing framework this project uses` (sub-Agent reads files, main Agent receives only the conclusion)\n2. `Delegate: read all .py files in agents/ and summarize what each one does`\n3. `Use a task to create s06_subagent/example/string_tools.py with a slugify(text: str) function, then verify it from the parent agent`\n\nWhat to watch for: Do `[Subagent spawned]` / `[Subagent done]` appear? Do sub-Agent tool calls print as `[sub] ...`? Does the parent Agent continue with only the summary returned by the sub-Agent?\n\n---\n\n## What's Next\n\nThe Agent can now break tasks apart. But different tasks require different knowledge: editing frontend components needs React conventions, writing SQL needs table schemas. Stuffing all this knowledge into the system prompt would blow up the context.\n\n→ s07 Skill Loading: Inject skills on demand instead of piling documents into the system prompt. Load only when needed, as natural as reading a file.\n\n
\nDive into CC Source Code\n\n> The following is based on a complete analysis of CC source code `AgentTool.tsx`, `runAgent.ts`, `forkSubagent.ts`, and `forkedAgent.ts`.\n\n### 1. Not One Pattern, but Three\n\nThe teaching version covers only \"fresh messages[]\". CC actually has three execution modes:\n\n| Mode | Trigger | Context |\n|------|---------|---------|\n| **Normal Subagent** | `subagent_type` specified (normal path) | Truly fresh messages[], only the prompt |\n| **Fork Subagent** | No `subagent_type`, fork gate enabled | Constructs cache-friendly prefix via `buildForkedMessages()`, shares prompt cache |\n| **General-Purpose** | No `subagent_type`, fork gate disabled | Same as Normal |\n\n### 2. Fork Mode: Sharing Prompt Cache\n\nThis is a core concept the teaching version omits. Fork mode (`forkSubagent.ts:60-71`) doesn't create a fresh context. Instead, it constructs a cache-friendly message prefix via `buildForkedMessages()` (`forkSubagent.ts:107-168`), preserving the parent assistant message and generating placeholder tool results. The goal isn't isolation, but making the Anthropic API's prompt cache hit: parent and child Agent's system prompt, tools, and message prefix are byte-identical, so the API doesn't need to recompute.\n\nFive key components for cache hit (`forkedAgent.ts:57-68`): system prompt, tools, model, message prefix, thinking config, must be byte-identical.\n\n### 3. Context Isolation's Precise Granularity\n\n`createSubagentContext()` (`forkedAgent.ts:345-462`) creates the sub-Agent's `ToolUseContext`:\n\n| Field | Behavior |\n|-------|----------|\n| `abortController` | New child controller; parent abort propagates down |\n| `setAppState` | Default no-op; but sync agents share via `shareSetAppState` (`runAgent.ts:697-714`) |\n| `readFileState` | **Cloned from parent** (avoids re-reading same files) |\n| `queryTracking` | New chainId, `depth = parentDepth + 1` |\n\nThe sub-Agent isn't fully isolated: file read state is shared. The degree of UI and notification isolation varies by execution path (sync/async/fork/teammate differ).\n\n### 4. Recursive Fork Protection\n\nThe teaching version uses \"sub-Agent has no task tool\" for recursion protection. The real implementation is more nuanced: `isInForkChild()` (`forkSubagent.ts:78-89`) checks for `FORK_BOILERPLATE_TAG` in history. But `constants/tools.ts:36-46` defaults `Agent` to all agents' disabled set (with `USER_TYPE === 'ant'` exception); `forkSubagent.ts:73-89` has fork-child-specific recursion protection; `agentToolUtils.ts:100-110` has special allowances in teammate scenarios. Not simply \"no further sub-Agents.\"\n\n### 5. Permission Bubbling\n\nFork Agent's `permissionMode: 'bubble'` (`forkSubagent.ts:67`) means the sub-Agent's permission prompts bubble up to the parent terminal: the user approves sub-Agent operations in the main terminal.\n\n### 6. Async vs Sync\n\nThe teaching version only shows synchronous sub-Agents (parent waits for child to finish). CC also supports async paths (`AgentTool.tsx:686-764`): when `run_in_background: true`, the sub-Agent launches asynchronously, returning `{ status: 'async_launched' }` immediately to the parent, and notifies the parent when complete. Actual triggers go beyond `run_in_background`, including auto-background, assistant force async, and coordinator/proactive paths.\n\n### Teaching Version Simplifications Are Intentional\n\n- Three modes → one (fresh messages): conceptually clear\n- Prompt cache sharing → omitted: teaching version doesn't involve API-layer optimization\n- Recursive fork protection → simplified to \"sub-Agent has no task tool\"\n- Async → omitted (left for s13): s06 focuses on the synchronous model first\n\n
\n\n\n" + "content": "# s06: Subagent — Break Large Tasks into Small Ones with Clean Context\n\ns01 → s02 → s03 → s04 → s05 → `s06` → [s07](/en/s07) → s08 → ... → s20 → s21\n\n> *\"Break large tasks small, each with clean context\"* — Subagent uses an independent messages[], no pollution in the main conversation.\n>\n> **Harness Layer**: Sub-Agent — Context isolation, attention doesn't drift.\n\n---\n\n## The Problem\n\nThe Agent is fixing a bug. It reads 30 files to trace the call chain, chatting for 60 rounds along the way. The messages list grows to 120 entries, most of which are intermediate steps from \"tracing the call chain\" — unrelated to the final goal of \"fixing the bug.\"\n\nThese intermediate steps occupy context space, making the Agent increasingly \"forgetful\" — it can no longer remember what the original problem was.\n\nThink of it differently: when you fix a bug, you'd \"open a new terminal\" to trace the call chain. When done, close the terminal, write the result into your notes, and return to the original terminal to keep fixing. The Agent needs this ability too — **open an independent sub-process, give it an independent message list, let it focus on one thing.**\n\n---\n\n## The Solution\n\n![Subagent Overview](/course-assets/s06_subagent/subagent-overview.en.svg)\n\nThe minimal hook structure and `todo_write` tool from the previous chapter are preserved; this chapter focuses on the new `task` tool. When called, it spawns a sub-Agent with a fresh `messages[]`, running its own loop, and returning only a summary text to the main Agent. Conversation context is discarded, but file system side effects (writes, edits, commands) remain in the working directory.\n\nThe sub-Agent's tools are restricted: it has bash/read/write/edit/glob, but no task, preventing recursive spawning. The sub-Agent's tool calls still go through permission hooks; context isolation does not bypass security.\n\n---\n\n## How It Works\n\n**spawn_subagent**, gives the sub-Agent a fresh messages list, runs its own loop, returns only the conclusion:\n\n```python\ndef spawn_subagent(description: str) -> str:\n # Sub-Agent tools: base tools, but no task (no recursion)\n sub_tools = [...]\n messages = [{\"role\": \"user\", \"content\": description}] # fresh messages[]\n\n for _ in range(30): # safety limit\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM,\n messages=messages, tools=sub_tools, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({... \"content\": str(blocked)})\n continue\n handler = SUB_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown\"\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({... \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # Return only the final text conclusion, all intermediate steps discarded\n return extract_text(messages[-1][\"content\"])\n```\n\nThe main Agent calls it just like any other tool:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n {\"name\": \"todo_write\", ...},\n # s06: new task tool\n {\"name\": \"task\",\n \"description\": \"Launch a subagent to handle a complex subtask. Returns only the final conclusion.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"description\": {\"type\": \"string\"}}, \"required\": [\"description\"]}},\n]\n\nTOOL_HANDLERS[\"task\"] = spawn_subagent\n```\n\nThree key design decisions:\n\n| Decision | Choice | Reason |\n|----------|--------|--------|\n| Context isolation | Fresh `messages[]` | Sub-Agent's intermediate steps don't pollute main Agent's context |\n| Return only conclusion | `extract_text(last_message)` | Not returning the entire messages list |\n| No recursion | Sub-Agent has no task tool | Prevents sub-Agent from spawning further sub-Agents |\n| Security not bypassed | Sub-Agent tool calls go through PreToolUse hook | Context isolation does not mean permission isolation |\n\nThe dispatch mechanism is unchanged; the task tool is routed through `TOOL_HANDLERS[block.name]`. The sub-Agent has its own `SUB_SYSTEM` prompt, explicitly instructing \"complete the task, do not delegate further.\"\n\n---\n\n## Changes from s05\n\n| Component | Before (s05) | After (s06) |\n|-----------|-------------|-------------|\n| Tool count | 6 (bash, read, write, edit, glob, todo_write) | 7 (+task) |\n| New function | — | spawn_subagent (independent messages[] + 30-round safety limit) |\n| Context isolation | Everything in the main conversation | Sub-Agent uses fresh messages[] |\n| Loop | Unchanged | Dispatch unchanged, sub-Agent has independent SUB_SYSTEM and hook-protected loop |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s06_subagent/code.py\n```\n\nTry these prompts:\n\n1. `Use a subtask to find what testing framework this project uses` (sub-Agent reads files, main Agent receives only the conclusion)\n2. `Delegate: read all .py files in agents/ and summarize what each one does`\n3. `Use a task to create s06_subagent/example/string_tools.py with a slugify(text: str) function, then verify it from the parent agent`\n\nWhat to watch for: Do `[Subagent spawned]` / `[Subagent done]` appear? Do sub-Agent tool calls print as `[sub] ...`? Does the parent Agent continue with only the summary returned by the sub-Agent?\n\n---\n\n## What's Next\n\nThe Agent can now break tasks apart. But different tasks require different knowledge: editing frontend components needs React conventions, writing SQL needs table schemas. Stuffing all this knowledge into the system prompt would blow up the context.\n\n→ s07 Skill Loading: Inject skills on demand instead of piling documents into the system prompt. Load only when needed, as natural as reading a file.\n\n\n\n" }, { "version": "s06", "locale": "zh", "title": "s06: Subagent — 大任务拆小,每个拿到的都是干净上下文", - "content": "# s06: Subagent — 大任务拆小,每个拿到的都是干净上下文\n\ns01 → s02 → s03 → s04 → s05 → `s06` → [s07](/zh/s07) → s08 → ... → s20 → s21 → s22\n\n> *\"大任务拆小, 每个小任务干净的上下文\"* — Subagent 用独立 messages[], 不污染主对话。\n>\n> **Harness 层**: 子 Agent — 上下文隔离, 注意力不漂移。\n\n---\n\n## 问题\n\nAgent 在修一个 bug。它读了 30 个文件来追踪调用链,中间聊了 60 轮。messages 列表涨到 120 条,其中大部分是\"追踪调用链\"的中间过程,和\"修 bug\"这个最终目标无关。\n\n这些中间过程占着上下文位置,让 Agent 越来越\"健忘\",它记不住最初的问题是什么了。\n\n换个角度:你修 bug 的时候,会\"开一个新终端\"来追踪调用链。追踪完了,终端关掉,结果写进笔记,回到原来的终端继续修 bug。Agent 也需要这个能力:开一个独立的子进程,给它一个独立的消息列表,让它专心做一件事。\n\n---\n\n## 解决方案\n\n![Subagent Overview](/course-assets/s06_subagent/subagent-overview.svg)\n\n保留上一章的最小 hook 结构和 `todo_write` 工具,本章重点转向新增的 `task` 工具。调用它时,spawn 一个子 Agent,拥有全新的 `messages[]`,跑自己的循环,结束后只把摘要文本回传给主 Agent。对话上下文被丢弃,但文件系统的副作用(写文件、改文件、跑命令)保留在工作目录中。\n\n子 Agent 的工具受限:有 bash/read/write/edit/glob,但没有 task,不能递归 spawn 新的子 Agent。子 Agent 的工具调用仍经过权限 hook,安全策略不因上下文隔离而跳过。\n\n---\n\n## 工作原理\n\n**spawn_subagent**,给子 Agent 一个全新的 messages 列表,跑自己的循环,只回传结论:\n\n```python\ndef spawn_subagent(description: str) -> str:\n # 子 Agent 的工具:基础工具,但没有 task(禁止递归)\n sub_tools = [\n {\"name\": \"bash\", ...}, {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...}, {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n ]\n messages = [{\"role\": \"user\", \"content\": description}] # 全新 messages[]\n\n for _ in range(30): # safety limit\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM,\n messages=messages, tools=sub_tools, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({... \"content\": str(blocked)})\n continue\n handler = SUB_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown\"\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({... \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # 只返回最后的文本结论,中间过程全部丢弃\n return extract_text(messages[-1][\"content\"])\n```\n\n主 Agent 调用时,跟调其他工具一样:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n {\"name\": \"todo_write\", ...},\n # s06: 新增 task 工具\n {\"name\": \"task\",\n \"description\": \"Launch a subagent to handle a complex subtask. Returns only the final conclusion.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"description\": {\"type\": \"string\"}}, \"required\": [\"description\"]}},\n]\n\nTOOL_HANDLERS[\"task\"] = spawn_subagent\n```\n\n三个关键设计决策:\n\n| 决策 | 选择 | 原因 |\n|------|------|------|\n| 上下文隔离 | 全新 `messages[]` | 子 Agent 的中间过程不污染主 Agent 的上下文 |\n| 只回传结论 | `extract_text(last_message)` | 不是回传整个 messages 列表 |\n| 禁止递归 | 子 Agent 无 task 工具 | 防止子 Agent 再 spawn 新的子 Agent |\n| 安全策略不跳过 | 子 Agent 工具调用也走 PreToolUse hook | 上下文隔离不代表权限隔离 |\n\ndispatch 机制不变,task 工具通过 `TOOL_HANDLERS[block.name]` 分发。子 Agent 有独立的 `SUB_SYSTEM` 提示,明确要求\"直接完成任务,不要再委派\"。\n\n---\n\n## 相对 s05 的变更\n\n| 组件 | 之前 (s05) | 之后 (s06) |\n|------|-----------|-----------|\n| 工具数量 | 6 (bash, read, write, edit, glob, todo_write) | 7 (+task) |\n| 新函数 | — | spawn_subagent(独立 messages[] + 30 轮安全限制) |\n| 上下文隔离 | 全部在主对话中 | 子 Agent 用全新的 messages[] |\n| 循环 | 不变 | dispatch 不变,子 Agent 有独立 SUB_SYSTEM 和 hook 保护的循环 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s06_subagent/code.py\n```\n\n试试这些 prompt:\n\n1. `Use a subtask to find what testing framework this project uses`(子 Agent 去读文件,主 Agent 只收结论)\n2. `Delegate: read all .py files in agents/ and summarize what each one does`\n3. `Use a task to create s06_subagent/example/string_tools.py with a slugify(text: str) function, then verify it from the parent agent`\n\n观察重点:是否出现 `[Subagent spawned]` / `[Subagent done]`?子 Agent 的工具调用是否以 `[sub] ...` 输出?主 Agent 最后是否只继续处理子 Agent 返回的摘要?\n\n---\n\n## 接下来\n\nAgent 现在能拆任务了。但每个任务需要的知识不一样:改前端组件需要知道 React 规范,写 SQL 需要知道表结构。这些知识全塞进 system prompt,上下文直接爆了。\n\ns07 Skill Loading → 技能按需注入,不在 system prompt 里堆文档。用到的时候才加载,和读文件一样自然。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `AgentTool.tsx`、`runAgent.ts`、`forkSubagent.ts`、`forkedAgent.ts` 的完整分析。\n\n### 一、不是一种模式,是三种\n\n教学版只讲了\"全新的 messages[]\"。CC 实际有三种执行模式:\n\n| 模式 | 触发条件 | 上下文 |\n|------|---------|--------|\n| **Normal Subagent** | 指定了 `subagent_type`(normal path) | 全新 messages[],只有 prompt |\n| **Fork Subagent** | 没指定 `subagent_type`,fork gate 开启 | 通过 `buildForkedMessages()` 构造 cache-friendly 前缀,共享 prompt cache |\n| **General-Purpose** | 没指定 `subagent_type`,fork gate 关闭 | 同 Normal |\n\n### 二、Fork 模式:为了共享 Prompt Cache\n\n这是教学版没有的核心概念。Fork 模式(`forkSubagent.ts:60-71`)不创建全新上下文,而是通过 `buildForkedMessages()`(`forkSubagent.ts:107-168`)构造 cache-friendly 消息前缀,保留父 assistant message 并生成 placeholder tool results。目的不是隔离,而是让 Anthropic API 的 prompt cache 命中:父子 Agent 的 system prompt、tools、messages 前缀完全一致,API 端不需要重算。\n\n缓存命中的五个关键组件(`forkedAgent.ts:57-68`):system prompt、tools、model、messages 前缀、thinking config,必须字节级一致。\n\n### 三、Context Isolation 的精确粒度\n\n`createSubagentContext()`(`forkedAgent.ts:345-462`)创建子 Agent 的 `ToolUseContext`:\n\n| 字段 | 行为 |\n|------|------|\n| `abortController` | 新的 child controller,父 abort 向下传播 |\n| `setAppState` | 默认 no-op;但 sync agent 通过 `shareSetAppState` 共享(`runAgent.ts:697-714`) |\n| `readFileState` | **从父克隆**(避免重复读相同文件) |\n| `queryTracking` | 新 chainId,`depth = parentDepth + 1` |\n\n子 Agent 不是完全隔离的:文件读取状态是共享的。UI 和通知的隔离程度取决于执行路径(sync/async/fork/teammate 各不同)。\n\n### 四、递归 Fork 防护\n\n教学版用\"子 Agent 不给 task 工具\"表达递归保护。真实实现更精细:`isInForkChild()`(`forkSubagent.ts:78-89`)检查对话历史中是否有 `FORK_BOILERPLATE_TAG`,有就拒绝。但 `constants/tools.ts:36-46` 中 `Agent` 工具默认在所有 agent 的禁用集合里,`USER_TYPE === 'ant'` 时例外;`forkSubagent.ts:73-89` 针对 fork child 有专门的递归保护;`agentToolUtils.ts:100-110` 在 teammate 场景下有特殊放行。不是简单的\"禁止新的子 Agent\"。\n\n### 五、Permission Bubbling\n\nFork Agent 的 `permissionMode: 'bubble'`(`forkSubagent.ts:67`)意味着子 Agent 的权限弹窗冒泡到父终端,用户在主终端里审批子 Agent 的操作。\n\n### 六、Async vs Sync\n\n教学版只展示了同步子 Agent(父等着子跑完)。CC 还支持异步路径(`AgentTool.tsx:686-764`):`run_in_background: true` 时异步启动,返回 `{ status: 'async_launched' }` 立即给父 Agent,子 Agent 完成后通过通知机制告知父 Agent。实际触发条件不止 `run_in_background`,还有 auto-background、assistant force async、coordinator/proactive 等路径。\n\n### 教学版的简化是刻意的\n\n- 三种模式 → 一种(fresh messages):概念清晰\n- Prompt cache 共享 → 省略:教学版不涉及 API 层优化\n- 递归 fork 防护 → 简化为\"子 Agent 无 task 工具\"\n- Async → 省略(留给 s13):s06 先理解同步模型\n\n
\n\n\n" + "content": "# s06: Subagent — 大任务拆小,每个拿到的都是干净上下文\n\ns01 → s02 → s03 → s04 → s05 → `s06` → [s07](/zh/s07) → s08 → ... → s20 → s21\n\n> *\"大任务拆小, 每个小任务干净的上下文\"* — Subagent 用独立 messages[], 不污染主对话。\n>\n> **Harness 层**: 子 Agent — 上下文隔离, 注意力不漂移。\n\n---\n\n## 问题\n\nAgent 在修一个 bug。它读了 30 个文件来追踪调用链,中间聊了 60 轮。messages 列表涨到 120 条,其中大部分是\"追踪调用链\"的中间过程,和\"修 bug\"这个最终目标无关。\n\n这些中间过程占着上下文位置,让 Agent 越来越\"健忘\",它记不住最初的问题是什么了。\n\n换个角度:你修 bug 的时候,会\"开一个新终端\"来追踪调用链。追踪完了,终端关掉,结果写进笔记,回到原来的终端继续修 bug。Agent 也需要这个能力:开一个独立的子进程,给它一个独立的消息列表,让它专心做一件事。\n\n---\n\n## 解决方案\n\n![Subagent Overview](/course-assets/s06_subagent/subagent-overview.svg)\n\n保留上一章的最小 hook 结构和 `todo_write` 工具,本章重点转向新增的 `task` 工具。调用它时,spawn 一个子 Agent,拥有全新的 `messages[]`,跑自己的循环,结束后只把摘要文本回传给主 Agent。对话上下文被丢弃,但文件系统的副作用(写文件、改文件、跑命令)保留在工作目录中。\n\n子 Agent 的工具受限:有 bash/read/write/edit/glob,但没有 task,不能递归 spawn 新的子 Agent。子 Agent 的工具调用仍经过权限 hook,安全策略不因上下文隔离而跳过。\n\n---\n\n## 工作原理\n\n**spawn_subagent**,给子 Agent 一个全新的 messages 列表,跑自己的循环,只回传结论:\n\n```python\ndef spawn_subagent(description: str) -> str:\n # 子 Agent 的工具:基础工具,但没有 task(禁止递归)\n sub_tools = [\n {\"name\": \"bash\", ...}, {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...}, {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n ]\n messages = [{\"role\": \"user\", \"content\": description}] # 全新 messages[]\n\n for _ in range(30): # safety limit\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM,\n messages=messages, tools=sub_tools, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({... \"content\": str(blocked)})\n continue\n handler = SUB_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown\"\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({... \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # 只返回最后的文本结论,中间过程全部丢弃\n return extract_text(messages[-1][\"content\"])\n```\n\n主 Agent 调用时,跟调其他工具一样:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n {\"name\": \"todo_write\", ...},\n # s06: 新增 task 工具\n {\"name\": \"task\",\n \"description\": \"Launch a subagent to handle a complex subtask. Returns only the final conclusion.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"description\": {\"type\": \"string\"}}, \"required\": [\"description\"]}},\n]\n\nTOOL_HANDLERS[\"task\"] = spawn_subagent\n```\n\n三个关键设计决策:\n\n| 决策 | 选择 | 原因 |\n|------|------|------|\n| 上下文隔离 | 全新 `messages[]` | 子 Agent 的中间过程不污染主 Agent 的上下文 |\n| 只回传结论 | `extract_text(last_message)` | 不是回传整个 messages 列表 |\n| 禁止递归 | 子 Agent 无 task 工具 | 防止子 Agent 再 spawn 新的子 Agent |\n| 安全策略不跳过 | 子 Agent 工具调用也走 PreToolUse hook | 上下文隔离不代表权限隔离 |\n\ndispatch 机制不变,task 工具通过 `TOOL_HANDLERS[block.name]` 分发。子 Agent 有独立的 `SUB_SYSTEM` 提示,明确要求\"直接完成任务,不要再委派\"。\n\n---\n\n## 相对 s05 的变更\n\n| 组件 | 之前 (s05) | 之后 (s06) |\n|------|-----------|-----------|\n| 工具数量 | 6 (bash, read, write, edit, glob, todo_write) | 7 (+task) |\n| 新函数 | — | spawn_subagent(独立 messages[] + 30 轮安全限制) |\n| 上下文隔离 | 全部在主对话中 | 子 Agent 用全新的 messages[] |\n| 循环 | 不变 | dispatch 不变,子 Agent 有独立 SUB_SYSTEM 和 hook 保护的循环 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s06_subagent/code.py\n```\n\n试试这些 prompt:\n\n1. `Use a subtask to find what testing framework this project uses`(子 Agent 去读文件,主 Agent 只收结论)\n2. `Delegate: read all .py files in agents/ and summarize what each one does`\n3. `Use a task to create s06_subagent/example/string_tools.py with a slugify(text: str) function, then verify it from the parent agent`\n\n观察重点:是否出现 `[Subagent spawned]` / `[Subagent done]`?子 Agent 的工具调用是否以 `[sub] ...` 输出?主 Agent 最后是否只继续处理子 Agent 返回的摘要?\n\n---\n\n## 接下来\n\nAgent 现在能拆任务了。但每个任务需要的知识不一样:改前端组件需要知道 React 规范,写 SQL 需要知道表结构。这些知识全塞进 system prompt,上下文直接爆了。\n\ns07 Skill Loading → 技能按需注入,不在 system prompt 里堆文档。用到的时候才加载,和读文件一样自然。\n\n\n\n" }, { "version": "s06", "locale": "ja", "title": "s06: Subagent — 大きなタスクを分割、それぞれがクリーンなコンテキストを取得", - "content": "# s06: Subagent — 大きなタスクを分割、それぞれがクリーンなコンテキストを取得\n\ns01 → s02 → s03 → s04 → s05 → `s06` → [s07](/ja/s07) → s08 → ... → s20 → s21 → s22\n\n> *\"大きなタスクは小さく、小さなタスクごとにクリーンなコンテキスト\"* — Subagent は独立した messages[] を使い、メイン会話を汚染しない。\n>\n> **Harness レイヤー**: サブエージェント — コンテキストの隔離、注意の散漫を防ぐ。\n\n---\n\n## 課題\n\nAgent がバグを修正している。呼び出しチェーンを追跡するために 30 のファイルを読み、途中で 60 ラウンドやり取りした。messages リストは 120 件に膨らみ、その大部分は「呼び出しチェーンの追跡」という中間過程 — 「バグ修正」という最終目標とは無関係。\n\nこの中間過程がコンテキストの席を占め、Agent はますます「健忘」になる — 最初の問題が何だったか覚えていられない。\n\n別の見方をすると:バグを修正するとき、あなたは「新しいターミナルを開いて」呼び出しチェーンを追跡するだろう。追跡が終わったらターミナルを閉じ、結果をメモに書き、元のターミナルに戻ってバグ修正を続ける。Agent にもこの能力が必要 — **独立したサブプロセスを開き、独立したメッセージリストを与え、一つのことに集中させる。**\n\n---\n\n## ソリューション\n\n![Subagent Overview](/course-assets/s06_subagent/subagent-overview.ja.svg)\n\n前章の最小フック構造と `todo_write` ツールを保持し、本章は新規の `task` ツールに注目する。呼び出されると、サブエージェントを spawn する。新しい `messages[]` を持ち、自分自身のループを実行し、終了後に要約テキストのみをメイン Agent に返す。会話コンテキストは破棄されるが、ファイルシステムの副作用(書き込み、編集、コマンド実行)は作業ディレクトリに残る。\n\nサブエージェントのツールは制限される:bash/read/write/edit/glob を持つが、task はない。再帰 spawn を防止する。サブエージェントのツール呼び出しも権限フックを経由する。コンテキスト分離は権限のバイパスではない。\n\n---\n\n## 仕組み\n\n**spawn_subagent**、サブエージェントに新しいメッセージリストを与え、自分自身のループを実行し、結論のみを返す:\n\n```python\ndef spawn_subagent(description: str) -> str:\n # サブエージェントのツール:基本ツールのみ、task なし(再帰禁止)\n sub_tools = [...]\n messages = [{\"role\": \"user\", \"content\": description}] # 新規 messages[]\n\n for _ in range(30): # safety limit\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM,\n messages=messages, tools=sub_tools, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({... \"content\": str(blocked)})\n continue\n handler = SUB_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown\"\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({... \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # 最後のテキスト結論のみを返す、中間過程はすべて破棄\n return extract_text(messages[-1][\"content\"])\n```\n\nメイン Agent の呼び出しは、他のツールと同じ:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n {\"name\": \"todo_write\", ...},\n # s06: 新規 task ツール\n {\"name\": \"task\",\n \"description\": \"Launch a subagent to handle a complex subtask. Returns only the final conclusion.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"description\": {\"type\": \"string\"}}, \"required\": [\"description\"]}},\n]\n\nTOOL_HANDLERS[\"task\"] = spawn_subagent\n```\n\n三つの重要な設計決定:\n\n| 決定 | 選択 | 理由 |\n|------|------|------|\n| コンテキスト隔離 | 新規 `messages[]` | サブエージェントの中間過程がメイン Agent のコンテキストを汚染しない |\n| 結論のみ返却 | `extract_text(last_message)` | messages リスト全体を返すのではない |\n| 再帰禁止 | サブエージェントに task ツールなし | サブエージェントがさらにサブエージェントを spawn するのを防止 |\n| セキュリティのバイパスなし | サブエージェントのツール呼び出しも PreToolUse フックを経由 | コンテキスト分離は権限分離ではない |\n\nディスパッチ機構は変わらず、task ツールは `TOOL_HANDLERS[block.name]` を経由する。サブエージェントは独立した `SUB_SYSTEM` プロンプトを持ち、「タスクを完了し、さらに委託しない」と明示される。\n\n---\n\n## s05 からの変更\n\n| コンポーネント | 変更前 (s05) | 変更後 (s06) |\n|--------------|-------------|-------------|\n| ツール数 | 6 (bash, read, write, edit, glob, todo_write) | 7 (+task) |\n| 新規関数 | — | spawn_subagent(独立 messages[] + 30 ラウンド安全制限) |\n| コンテキスト隔離 | すべてメイン会話内 | サブエージェントが新規 messages[] を使用 |\n| ループ | 不変 | ディスパッチは不変、サブエージェントに独立した SUB_SYSTEM とフック保護されたループ |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s06_subagent/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Use a subtask to find what testing framework this project uses`(サブエージェントがファイルを読み、メイン Agent は結論のみ受け取る)\n2. `Delegate: read all .py files in agents/ and summarize what each one does`\n3. `Use a task to create s06_subagent/example/string_tools.py with a slugify(text: str) function, then verify it from the parent agent`\n\n観察のポイント:`[Subagent spawned]` / `[Subagent done]` が表示されるか? サブエージェントのツール呼び出しが `[sub] ...` として出力されるか? 親 Agent はサブエージェントが返した要約だけを受け取って続行するか?\n\n---\n\n## 次へ\n\nAgent はタスクを分割できるようになった。しかし各タスクに必要な知識は異なる。フロントエンドコンポーネントの変更には React 規約が必要で、SQL を書くにはテーブル構造を知る必要がある。これらの知識をすべて system prompt に詰め込むと、コンテキストが溢れてしまう。\n\n→ s07 Skill Loading:スキルをオンデマンドで注入する。system prompt にドキュメントを積み上げるのではなく、必要なときだけ読み込む。ファイルを読むのと同じくらい自然に。\n\n
\nCC ソースコードを深掘り\n\n> 以下は CC ソースコード `AgentTool.tsx`、`runAgent.ts`、`forkSubagent.ts`、`forkedAgent.ts` の完全分析に基づく。\n\n### 一、一つのパターンではなく三つ\n\n教育版は「新規 messages[]」のみを取り上げる。CC には実際に三つの実行モードがある:\n\n| モード | トリガー | コンテキスト |\n|--------|---------|-------------|\n| **Normal Subagent** | `subagent_type` 指定時(normal path) | 新規 messages[]、プロンプトのみ |\n| **Fork Subagent** | `subagent_type` 未指定、fork gate 有効時 | `buildForkedMessages()` でキャッシュフレンドリーなプレフィックスを構築、プロンプトキャッシュを共有 |\n| **General-Purpose** | `subagent_type` 未指定、fork gate 無効時 | Normal と同じ |\n\n### 二、Fork モード:プロンプトキャッシュの共有のため\n\nこれは教育版にはない核心概念。Fork モード(`forkSubagent.ts:60-71`)は新規コンテキストを作成せず、`buildForkedMessages()`(`forkSubagent.ts:107-168`)でキャッシュフレンドリーなメッセージプレフィックスを構築する。親の assistant message を保持し、placeholder tool results を生成する。目的は隔離ではなく、Anthropic API のプロンプトキャッシュをヒットさせること:親子 Agent の system prompt、tools、messages プレフィックスがバイトレベルで一致するため、API 側で再計算が不要になる。\n\nキャッシュヒットの五つの重要コンポーネント(`forkedAgent.ts:57-68`):system prompt、tools、model、messages プレフィックス、thinking config、バイトレベルで一致する必要がある。\n\n### 三、コンテキスト隔離の精密な粒度\n\n`createSubagentContext()`(`forkedAgent.ts:345-462`)はサブエージェントの `ToolUseContext` を作成:\n\n| フィールド | 挙動 |\n|-----------|------|\n| `abortController` | 新しい子コントローラ、親の abort は下に伝播 |\n| `setAppState` | デフォルトは no-op、ただし sync agent は `shareSetAppState` で共有(`runAgent.ts:697-714`) |\n| `readFileState` | **親からクローン**(同じファイルの再読み込みを回避) |\n| `queryTracking` | 新しい chainId、`depth = parentDepth + 1` |\n\nサブエージェントは完全に隔離されているわけではない。ファイル読み取り状態は共有される。UI と通知の隔離度は実行パスにより異なる(sync/async/fork/teammate でそれぞれ異なる)。\n\n### 四、再帰 Fork 防護\n\n教育版は「サブエージェントに task ツールなし」で再帰防止を表現する。実際の実装はより精密:`isInForkChild()`(`forkSubagent.ts:78-89`)が会話履歴内の `FORK_BOILERPLATE_TAG` をチェックする。しかし `constants/tools.ts:36-46` では `Agent` ツールが全エージェントの無効セットにデフォルト設定(`USER_TYPE === 'ant'` 時は例外)、`forkSubagent.ts:73-89` は fork child 向けの専用再帰保護があり、`agentToolUtils.ts:100-110` は teammate シナリオで特別な許可がある。単純な「サブエージェントの再 spawn 禁止」ではない。\n\n### 五、Permission Bubbling\n\nFork Agent の `permissionMode: 'bubble'`(`forkSubagent.ts:67`)は、サブエージェントの権限プロンプトが親ターミナルにバブルアップすることを意味する。ユーザーはメインターミナルでサブエージェントの操作を承認する。\n\n### 六、Async vs Sync\n\n教育版は同期サブエージェントのみ(親が子の完了を待つ)を示す。CC は非同期パスもサポート(`AgentTool.tsx:686-764`):`run_in_background: true` の場合、サブエージェントは非同期で起動し、`{ status: 'async_launched' }` を直ちに親に返し、完了時に通知機構で親に知らせる。実際のトリガーは `run_in_background` だけでなく、auto-background、assistant force async、coordinator/proactive パスもある。\n\n### 教育版の簡略化は意図的\n\n- 三つのモード → 一つ(新規 messages):概念的に明確\n- プロンプトキャッシュ共有 → 省略:教育版は API 層の最適化を扱わない\n- 再帰 fork 防護 → 「サブエージェントに task ツールなし」に簡略化\n- Async → 省略(s13 に委ねる):s06 はまず同期モデルを理解する\n\n
\n\n\n" + "content": "# s06: Subagent — 大きなタスクを分割、それぞれがクリーンなコンテキストを取得\n\ns01 → s02 → s03 → s04 → s05 → `s06` → [s07](/ja/s07) → s08 → ... → s20 → s21\n\n> *\"大きなタスクは小さく、小さなタスクごとにクリーンなコンテキスト\"* — Subagent は独立した messages[] を使い、メイン会話を汚染しない。\n>\n> **Harness レイヤー**: サブエージェント — コンテキストの隔離、注意の散漫を防ぐ。\n\n---\n\n## 課題\n\nAgent がバグを修正している。呼び出しチェーンを追跡するために 30 のファイルを読み、途中で 60 ラウンドやり取りした。messages リストは 120 件に膨らみ、その大部分は「呼び出しチェーンの追跡」という中間過程 — 「バグ修正」という最終目標とは無関係。\n\nこの中間過程がコンテキストの席を占め、Agent はますます「健忘」になる — 最初の問題が何だったか覚えていられない。\n\n別の見方をすると:バグを修正するとき、あなたは「新しいターミナルを開いて」呼び出しチェーンを追跡するだろう。追跡が終わったらターミナルを閉じ、結果をメモに書き、元のターミナルに戻ってバグ修正を続ける。Agent にもこの能力が必要 — **独立したサブプロセスを開き、独立したメッセージリストを与え、一つのことに集中させる。**\n\n---\n\n## ソリューション\n\n![Subagent Overview](/course-assets/s06_subagent/subagent-overview.ja.svg)\n\n前章の最小フック構造と `todo_write` ツールを保持し、本章は新規の `task` ツールに注目する。呼び出されると、サブエージェントを spawn する。新しい `messages[]` を持ち、自分自身のループを実行し、終了後に要約テキストのみをメイン Agent に返す。会話コンテキストは破棄されるが、ファイルシステムの副作用(書き込み、編集、コマンド実行)は作業ディレクトリに残る。\n\nサブエージェントのツールは制限される:bash/read/write/edit/glob を持つが、task はない。再帰 spawn を防止する。サブエージェントのツール呼び出しも権限フックを経由する。コンテキスト分離は権限のバイパスではない。\n\n---\n\n## 仕組み\n\n**spawn_subagent**、サブエージェントに新しいメッセージリストを与え、自分自身のループを実行し、結論のみを返す:\n\n```python\ndef spawn_subagent(description: str) -> str:\n # サブエージェントのツール:基本ツールのみ、task なし(再帰禁止)\n sub_tools = [...]\n messages = [{\"role\": \"user\", \"content\": description}] # 新規 messages[]\n\n for _ in range(30): # safety limit\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM,\n messages=messages, tools=sub_tools, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({... \"content\": str(blocked)})\n continue\n handler = SUB_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown\"\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({... \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # 最後のテキスト結論のみを返す、中間過程はすべて破棄\n return extract_text(messages[-1][\"content\"])\n```\n\nメイン Agent の呼び出しは、他のツールと同じ:\n\n```python\nTOOLS = [\n {\"name\": \"bash\", ...},\n {\"name\": \"read_file\", ...},\n {\"name\": \"write_file\", ...},\n {\"name\": \"edit_file\", ...},\n {\"name\": \"glob\", ...},\n {\"name\": \"todo_write\", ...},\n # s06: 新規 task ツール\n {\"name\": \"task\",\n \"description\": \"Launch a subagent to handle a complex subtask. Returns only the final conclusion.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"description\": {\"type\": \"string\"}}, \"required\": [\"description\"]}},\n]\n\nTOOL_HANDLERS[\"task\"] = spawn_subagent\n```\n\n三つの重要な設計決定:\n\n| 決定 | 選択 | 理由 |\n|------|------|------|\n| コンテキスト隔離 | 新規 `messages[]` | サブエージェントの中間過程がメイン Agent のコンテキストを汚染しない |\n| 結論のみ返却 | `extract_text(last_message)` | messages リスト全体を返すのではない |\n| 再帰禁止 | サブエージェントに task ツールなし | サブエージェントがさらにサブエージェントを spawn するのを防止 |\n| セキュリティのバイパスなし | サブエージェントのツール呼び出しも PreToolUse フックを経由 | コンテキスト分離は権限分離ではない |\n\nディスパッチ機構は変わらず、task ツールは `TOOL_HANDLERS[block.name]` を経由する。サブエージェントは独立した `SUB_SYSTEM` プロンプトを持ち、「タスクを完了し、さらに委託しない」と明示される。\n\n---\n\n## s05 からの変更\n\n| コンポーネント | 変更前 (s05) | 変更後 (s06) |\n|--------------|-------------|-------------|\n| ツール数 | 6 (bash, read, write, edit, glob, todo_write) | 7 (+task) |\n| 新規関数 | — | spawn_subagent(独立 messages[] + 30 ラウンド安全制限) |\n| コンテキスト隔離 | すべてメイン会話内 | サブエージェントが新規 messages[] を使用 |\n| ループ | 不変 | ディスパッチは不変、サブエージェントに独立した SUB_SYSTEM とフック保護されたループ |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s06_subagent/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `Use a subtask to find what testing framework this project uses`(サブエージェントがファイルを読み、メイン Agent は結論のみ受け取る)\n2. `Delegate: read all .py files in agents/ and summarize what each one does`\n3. `Use a task to create s06_subagent/example/string_tools.py with a slugify(text: str) function, then verify it from the parent agent`\n\n観察のポイント:`[Subagent spawned]` / `[Subagent done]` が表示されるか? サブエージェントのツール呼び出しが `[sub] ...` として出力されるか? 親 Agent はサブエージェントが返した要約だけを受け取って続行するか?\n\n---\n\n## 次へ\n\nAgent はタスクを分割できるようになった。しかし各タスクに必要な知識は異なる。フロントエンドコンポーネントの変更には React 規約が必要で、SQL を書くにはテーブル構造を知る必要がある。これらの知識をすべて system prompt に詰め込むと、コンテキストが溢れてしまう。\n\n→ s07 Skill Loading:スキルをオンデマンドで注入する。system prompt にドキュメントを積み上げるのではなく、必要なときだけ読み込む。ファイルを読むのと同じくらい自然に。\n\n\n\n" }, { "version": "s07", "locale": "en", "title": "s07: Skill Loading — Load Only When Needed", - "content": "# s07: Skill Loading — Load Only When Needed\n\ns01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](/en/s08) → s09 → ... → s20 → s21 → s22\n> *\"Load when needed, don't stuff the prompt\"* — Inject via tool_result, not system prompt.\n>\n> **Harness Layer**: Knowledge — load on demand, don't fill the context.\n\n---\n\n## The Problem\n\nYour project has a React component spec, a SQL style guide, and an API design doc. You want the Agent to follow these specs automatically. The most straightforward idea — stuff them all into the system prompt:\n\n```python\nSYSTEM = (\n f\"You are a coding agent. \"\n + open(\"docs/react-style.md\").read() # 2000 lines\n + open(\"docs/sql-style.md\").read() # 1500 lines\n + open(\"docs/api-design.md\").read() # 3000 lines\n)\n```\n\n6500 lines of system prompt. The Agent carries these docs on every LLM call — whether it's changing a CSS color or fixing a SQL query. 99% of the content is irrelevant to the current task, burning tokens for nothing.\n\n---\n\n## The Solution\n\n![Skill Overview](/course-assets/s07_skill_loading/skill-overview.en.svg)\n\nThe minimal hook structure, `todo_write`, and sub-Agent from the previous chapter are preserved. This chapter focuses on the new `load_skill` tool. At startup, inject the skill catalog into the SYSTEM prompt; at runtime, register one more tool to load full content, spending tokens only when used.\n\nTwo-level design:\n\n| Level | Location | Timing | Cost |\n|-------|----------|--------|------|\n| 1. Catalog | system prompt | Injected at startup (harness scans skills/) | ~100 tokens/skill, carried every turn |\n| 2. Content | tool_result | When Agent calls load_skill; SKILL.md can guide later read_file/bash access to extra resources | ~2000 tokens/skill, on demand |\n\nThe dispatch mechanism is unchanged, `load_skill` auto-dispatches via `TOOL_HANDLERS[block.name]`.\n\n---\n\n## How It Works\n\n**skills/ directory**, one subdirectory per skill, each containing a `SKILL.md` file:\n\n```\nskills/\n agent-builder/SKILL.md\n code-review/SKILL.md\n mcp-builder/SKILL.md\n pdf/SKILL.md\n```\n\n**Level 1: Inject catalog at startup**: the harness calls `_scan_skills()` at startup to scan the skills/ directory, parsing each SKILL.md's YAML frontmatter (`name`, `description`) into a `SKILL_REGISTRY` dictionary. `list_skills()` generates the catalog from the registry, injected into the SYSTEM prompt. The Agent sees \"which skills I have available\" every turn, with no extra API calls:\n\n```python\nSKILL_REGISTRY: dict[str, dict] = {}\n\ndef _scan_skills():\n if not SKILLS_DIR.exists():\n return\n for d in sorted(SKILLS_DIR.iterdir()):\n if not d.is_dir():\n continue\n manifest = d / \"SKILL.md\"\n if manifest.exists():\n raw = manifest.read_text()\n meta, body = _parse_frontmatter(raw)\n name = meta.get(\"name\", d.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\"name\": name, \"description\": desc, \"content\": raw}\n\n_scan_skills() # runs once at startup\n\ndef list_skills() -> str:\n return \"\\n\".join(f\"- **{s['name']}**: {s['description']}\" for s in SKILL_REGISTRY.values())\n\ndef build_system() -> str:\n catalog = list_skills()\n return (\n f\"You are a coding agent at {WORKDIR}. \"\n f\"Skills available:\\n{catalog}\\n\"\n \"Use load_skill to get full details when needed.\"\n )\n\nSYSTEM = build_system()\n```\n\n**Level 2: load_skill**: the Agent decides \"I need the SQL style guide\" and calls `load_skill(\"sql-style\")`. Lookup goes through the registry, not file paths, eliminating path traversal risk. The SKILL.md content is injected via `tool_result`, and can include later access to referenced `references/`, `scripts/`, or `assets/` through the existing file and bash tools.\n\n```python\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n return f\"Skill not found: {name}\"\n return skill[\"content\"]\n```\n\nThe key distinction: skill content is not part of the system prompt. It enters the current messages as a tool result. Subsequent calls carry it along with the history until context compaction, truncation, or session end. This naturally connects to s08's compact: on-demand loading solves \"don't carry what you shouldn't\", compact solves \"how to drop what you should.\"\n\n---\n\n## Changes from s06\n\n| Component | Before (s06) | After (s07) |\n|-----------|-------------|-------------|\n| Tool count | 7 (bash, read, write, edit, glob, todo_write, task) | 8 (+load_skill) |\n| Knowledge loading | None | Two-level: startup catalog in SYSTEM + runtime load_skill; SKILL.md may guide later resource access |\n| SYSTEM prompt | Static string | Startup scan of skills/ injects catalog |\n| Skill registry | None | SKILL_REGISTRY (populated at startup, prevents path traversal) |\n| Loop | Unchanged | Unchanged (skill tool auto-dispatches) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s07_skill_loading/code.py\n```\n\nTry these prompts:\n\n1. `What skills are available?`\n2. `Load the code-review skill and follow its instructions`\n3. `I need to do a code review -- load the relevant skill first`\n\nWhat to watch for: Does the Agent know available skills from the SYSTEM catalog? Does `[HOOK] load_skill` appear when full instructions are needed? Does the answer use the loaded skill's instructions?\n\n---\n\n## What's Next\n\nOn-demand loading solved \"don't carry what you shouldn't.\" But another problem looms: after the Agent works for 30 minutes, the messages list fills up with intermediate process. Old tool_results, stale file contents, occupying context but adding no value.\n\n→ s08 Context Compact: A four-layer compaction strategy. Cheap layers run first, expensive layers run last.\n\n
\nDive into CC Source Code\n\n> The following is based on analysis of CC source code `loadSkillsDir.ts`, `SkillTool.ts`, `bundledSkills.ts`, `commands.ts`.\n\n### 1. Skill Sources: Not Just One skills/ Directory\n\nThe teaching version assumes all skills live in a `skills/` directory. CC loads from multiple sources spread across multiple files: `loadSkillsDir.ts` handles user/project/`--add-dir` directories and legacy commands (`.claude/commands/`); `bundledSkills.ts` handles built-in skills; `SkillTool.ts` handles MCP remote skills; `commands.ts` handles command aggregation. Types include managed/policy skills, user skills (`~/.claude/skills/`), project skills (`.claude/skills/`), `--add-dir` skills, legacy commands, dynamic skills, conditional skills (with `paths` frontmatter, activated by file path), bundled skills, plugin skills, MCP skills.\n\n### 2. SKILL.md Frontmatter — Common Fields\n\nCC's SKILL.md YAML frontmatter is parsed by `parseSkillFrontmatterFields()` in `loadSkillsDir.ts`. Common fields include:\n\n| Field | Purpose |\n|-------|---------|\n| `name` / `description` | Display name and description |\n| `when_to_use` | Guides the model on when to invoke |\n| `allowed-tools` | Auto-allow list of tools available to the skill |\n| `context` | `inline` (default) or `fork` (run as sub-Agent) |\n| `model` | Model override (haiku/sonnet/opus/inherit) |\n| `hooks` | Skill-level hook configuration |\n| `paths` | Glob patterns for conditional activation |\n| `user-invocable` | Users can invoke via `/name` |\n\nThe complete field list changes across versions; above are the core fields relevant to the teaching version.\n\n### 3. Precise Implementation of Two-Level Loading\n\n1. **Catalog (at startup)**: `getSkillDirCommands()` scans directory → registers as `Command` objects containing only metadata. `getSkillListingAttachments()` formats the skill list as attachments, budgeted at ~1% of the context window (cap 8000 characters).\n2. **Load (on invocation)**: Model calls `Skill` tool (input fields are `skill` + optional `args`; teaching version uses `name`) → `getPromptForCommand()` expands full SKILL.md content → `SkillTool` returns a tool_result with display text `\"Launching skill: {name}\"`, while the actual skill content is injected via `newMessages`. The teaching version merges both into \"injected via tool_result\" as a simplification; the loaded SKILL.md can still guide later access to referenced resources through existing file/bash tools.\n\n### The Teaching Version's Simplification Is Intentional\n\n- Multiple files and sources → 1 `skills/` directory: sufficient to demonstrate the core concept of two-level loading\n- Multiple frontmatter fields → only parse name/description: reduces parsing complexity\n- Forked skills (`context: 'fork'`) → omitted: the teaching version only expands inline skill loading\n- `Skill` tool input `skill`+`args` → teaching version uses `name`: avoids extra argument parsing complexity\n\n
\n\n\n" + "content": "# s07: Skill Loading — Load Only When Needed\n\ns01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](/en/s08) → s09 → ... → s20 → s21\n> *\"Load when needed, don't stuff the prompt\"* — Inject via tool_result, not system prompt.\n>\n> **Harness Layer**: Knowledge — load on demand, don't fill the context.\n\n---\n\n## The Problem\n\nYour project has a React component spec, a SQL style guide, and an API design doc. You want the Agent to follow these specs automatically. The most straightforward idea — stuff them all into the system prompt:\n\n```python\nSYSTEM = (\n f\"You are a coding agent. \"\n + open(\"docs/react-style.md\").read() # 2000 lines\n + open(\"docs/sql-style.md\").read() # 1500 lines\n + open(\"docs/api-design.md\").read() # 3000 lines\n)\n```\n\n6500 lines of system prompt. The Agent carries these docs on every LLM call — whether it's changing a CSS color or fixing a SQL query. 99% of the content is irrelevant to the current task, burning tokens for nothing.\n\n---\n\n## The Solution\n\n![Skill Overview](/course-assets/s07_skill_loading/skill-overview.en.svg)\n\nThe minimal hook structure, `todo_write`, and sub-Agent from the previous chapter are preserved. This chapter focuses on the new `load_skill` tool. At startup, inject the skill catalog into the SYSTEM prompt; at runtime, register one more tool to load full content, spending tokens only when used.\n\nTwo-level design:\n\n| Level | Location | Timing | Cost |\n|-------|----------|--------|------|\n| 1. Catalog | system prompt | Injected at startup (harness scans skills/) | ~100 tokens/skill, carried every turn |\n| 2. Content | tool_result | When Agent calls load_skill; SKILL.md can guide later read_file/bash access to extra resources | ~2000 tokens/skill, on demand |\n\nThe dispatch mechanism is unchanged, `load_skill` auto-dispatches via `TOOL_HANDLERS[block.name]`.\n\n---\n\n## How It Works\n\n**skills/ directory**, one subdirectory per skill, each containing a `SKILL.md` file:\n\n```\nskills/\n agent-builder/SKILL.md\n code-review/SKILL.md\n mcp-builder/SKILL.md\n pdf/SKILL.md\n```\n\n**Level 1: Inject catalog at startup**: the harness calls `_scan_skills()` at startup to scan the skills/ directory, parsing each SKILL.md's YAML frontmatter (`name`, `description`) into a `SKILL_REGISTRY` dictionary. `list_skills()` generates the catalog from the registry, injected into the SYSTEM prompt. The Agent sees \"which skills I have available\" every turn, with no extra API calls:\n\n```python\nSKILL_REGISTRY: dict[str, dict] = {}\n\ndef _scan_skills():\n if not SKILLS_DIR.exists():\n return\n for d in sorted(SKILLS_DIR.iterdir()):\n if not d.is_dir():\n continue\n manifest = d / \"SKILL.md\"\n if manifest.exists():\n raw = manifest.read_text()\n meta, body = _parse_frontmatter(raw)\n name = meta.get(\"name\", d.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\"name\": name, \"description\": desc, \"content\": raw}\n\n_scan_skills() # runs once at startup\n\ndef list_skills() -> str:\n return \"\\n\".join(f\"- **{s['name']}**: {s['description']}\" for s in SKILL_REGISTRY.values())\n\ndef build_system() -> str:\n catalog = list_skills()\n return (\n f\"You are a coding agent at {WORKDIR}. \"\n f\"Skills available:\\n{catalog}\\n\"\n \"Use load_skill to get full details when needed.\"\n )\n\nSYSTEM = build_system()\n```\n\n**Level 2: load_skill**: the Agent decides \"I need the SQL style guide\" and calls `load_skill(\"sql-style\")`. Lookup goes through the registry, not file paths, eliminating path traversal risk. The SKILL.md content is injected via `tool_result`, and can include later access to referenced `references/`, `scripts/`, or `assets/` through the existing file and bash tools.\n\n```python\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n return f\"Skill not found: {name}\"\n return skill[\"content\"]\n```\n\nThe key distinction: skill content is not part of the system prompt. It enters the current messages as a tool result. Subsequent calls carry it along with the history until context compaction, truncation, or session end. This naturally connects to s08's compact: on-demand loading solves \"don't carry what you shouldn't\", compact solves \"how to drop what you should.\"\n\n---\n\n## Changes from s06\n\n| Component | Before (s06) | After (s07) |\n|-----------|-------------|-------------|\n| Tool count | 7 (bash, read, write, edit, glob, todo_write, task) | 8 (+load_skill) |\n| Knowledge loading | None | Two-level: startup catalog in SYSTEM + runtime load_skill; SKILL.md may guide later resource access |\n| SYSTEM prompt | Static string | Startup scan of skills/ injects catalog |\n| Skill registry | None | SKILL_REGISTRY (populated at startup, prevents path traversal) |\n| Loop | Unchanged | Unchanged (skill tool auto-dispatches) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s07_skill_loading/code.py\n```\n\nTry these prompts:\n\n1. `What skills are available?`\n2. `Load the code-review skill and follow its instructions`\n3. `I need to do a code review -- load the relevant skill first`\n\nWhat to watch for: Does the Agent know available skills from the SYSTEM catalog? Does `[HOOK] load_skill` appear when full instructions are needed? Does the answer use the loaded skill's instructions?\n\n---\n\n## What's Next\n\nOn-demand loading solved \"don't carry what you shouldn't.\" But another problem looms: after the Agent works for 30 minutes, the messages list fills up with intermediate process. Old tool_results, stale file contents, occupying context but adding no value.\n\n→ s08 Context Compact: A four-layer compaction strategy. Cheap layers run first, expensive layers run last.\n\n\n\n" }, { "version": "s07", "locale": "zh", "title": "s07: Skill Loading — 用到的时候才加载", - "content": "# s07: Skill Loading — 用到的时候才加载\n\ns01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](/zh/s08) → s09 → ... → s20 → s21 → s22\n> *\"用到时再加载, 别全塞 prompt 里\"* — 通过 tool_result 注入, 不塞 system prompt。\n>\n> **Harness 层**: 知识 — 按需加载, 不堆满上下文。\n\n---\n\n## 问题\n\n你的项目有一套 React 组件规范、一份 SQL 风格指南、一份 API 设计文档。你希望 Agent 自动遵守这些规范。最直接的想法,全塞进 system prompt:\n\n```python\nSYSTEM = (\n f\"You are a coding agent. \"\n + open(\"docs/react-style.md\").read() # 2000 行\n + open(\"docs/sql-style.md\").read() # 1500 行\n + open(\"docs/api-design.md\").read() # 3000 行\n)\n```\n\n6500 行 system prompt。Agent 每次调用 LLM 都带着这些文档——不管是在改 CSS 颜色还是修 SQL 查询。99% 的内容和当前任务无关,白白消耗 token。\n\n---\n\n## 解决方案\n\n![Skill Overview](/course-assets/s07_skill_loading/skill-overview.svg)\n\n保留上一章的最小 hook 结构、`todo_write` 和子 Agent,本章重点转向新增的 `load_skill` 工具。启动时把技能目录注入 SYSTEM prompt,运行时多注册一个工具加载完整内容,用到才花 token。\n\n两层设计:\n\n| 层 | 位置 | 时机 | 代价 |\n|---|------|------|------|\n| 1. 目录 | system prompt | 启动时注入(harness 扫描 skills/) | ~100 tokens/skill,每轮都带 |\n| 2. 内容 | tool_result | Agent 调用 load_skill 时;SKILL.md 可指引后续的 read_file/bash 调用,用于按需访问额外资源 | ~2000 tokens/skill,按需 |\n\ndispatch 机制不变,load_skill 通过 `TOOL_HANDLERS[block.name]` 分发。\n\n---\n\n## 工作原理\n\n**skills/ 目录**,每个技能一个子目录,包含 `SKILL.md` 文件:\n\n```\nskills/\n agent-builder/SKILL.md\n code-review/SKILL.md\n mcp-builder/SKILL.md\n pdf/SKILL.md\n```\n\n**第一级:启动时注入目录**:harness 启动时调用 `_scan_skills()` 扫描 skills/ 目录,解析每个 SKILL.md 的 YAML frontmatter(`name`、`description`),存入 `SKILL_REGISTRY` 字典。`list_skills()` 从注册表生成目录,注入 SYSTEM prompt。Agent 每轮都能看到\"我有哪些技能可用\",不花额外 API 调用:\n\n```python\nSKILL_REGISTRY: dict[str, dict] = {}\n\ndef _scan_skills():\n if not SKILLS_DIR.exists():\n return\n for d in sorted(SKILLS_DIR.iterdir()):\n if not d.is_dir():\n continue\n manifest = d / \"SKILL.md\"\n if manifest.exists():\n raw = manifest.read_text()\n meta, body = _parse_frontmatter(raw)\n name = meta.get(\"name\", d.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\"name\": name, \"description\": desc, \"content\": raw}\n\n_scan_skills() # runs once at startup\n\ndef list_skills() -> str:\n return \"\\n\".join(f\"- **{s['name']}**: {s['description']}\" for s in SKILL_REGISTRY.values())\n\ndef build_system() -> str:\n catalog = list_skills()\n return (\n f\"You are a coding agent at {WORKDIR}. \"\n f\"Skills available:\\n{catalog}\\n\"\n \"Use load_skill to get full details when needed.\"\n )\n\nSYSTEM = build_system()\n```\n\n**第二级:load_skill**:Agent 决定\"我需要 SQL 风格指南\",调用 `load_skill(\"sql-style\")`。通过注册表查找,不走文件路径,没有路径遍历风险。SKILL.md 内容通过 `tool_result` 注入,并可通过现有的 file 和 bash 工具进一步访问引用的 `references/`、`scripts/` 或 `assets/`。\n\n```python\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n return f\"Skill not found: {name}\"\n return skill[\"content\"]\n```\n\n关键区别:技能内容不是 system prompt 的一部分,它作为一次工具结果进入当前 messages。后续调用会随历史一起携带,直到上下文压缩、截断或会话结束。这和 s08 的 compact 自然衔接:按需加载解决了\"不该提前带的不要带\",compact 解决\"该丢的怎么丢\"。\n\n---\n\n## 相对 s06 的变更\n\n| 组件 | 之前 (s06) | 之后 (s07) |\n|------|-----------|-----------|\n| 工具数量 | 7 (bash, read, write, edit, glob, todo_write, task) | 8 (+load_skill) |\n| 知识加载 | 无 | 两级:启动时目录注入 SYSTEM + 运行时 load_skill;SKILL.md 可指引后续资源访问 |\n| SYSTEM 提示 | 静态字符串 | 启动时扫描 skills/ 注入目录 |\n| 技能注册表 | 无 | SKILL_REGISTRY(启动时填充,防路径遍历) |\n| 循环 | 不变 | 不变(skill 工具自动分发) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s07_skill_loading/code.py\n```\n\n试试这些 prompt:\n\n1. `What skills are available?`\n2. `Load the code-review skill and follow its instructions`\n3. `I need to do a code review -- load the relevant skill first`\n\n观察重点:Agent 是否直接从 SYSTEM 里的目录知道有哪些技能?需要完整规范时是否出现 `[HOOK] load_skill`?加载后回答是否使用了对应 skill 的说明?\n\n---\n\n## 接下来\n\n按需加载解决了\"不该带的不要带\"。但另一个问题来了:Agent 连续工作 30 分钟后,messages 列表塞满了中间过程。旧的 tool_result、过时的文件内容,占着上下文但不产生价值。\n\ns08 Context Compact → 四层压缩策略。便宜的先跑,贵的后跑。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `loadSkillsDir.ts`、`SkillTool.ts`、`bundledSkills.ts`、`commands.ts` 的分析。\n\n### 一、技能来源:不是只有一个 skills/ 目录\n\n教学版假设所有技能在 `skills/` 目录下。CC 实际从多个来源加载,分布在多个文件中:`loadSkillsDir.ts` 负责从 user/project/`--add-dir` 目录和 legacy commands(`.claude/commands/`)加载;`bundledSkills.ts` 负责内置技能;`SkillTool.ts` 处理 MCP 远程技能;`commands.ts` 负责命令聚合。类型包括 managed/policy skills、user skills(`~/.claude/skills/`)、project skills(`.claude/skills/`)、`--add-dir` skills、legacy commands、dynamic skills、conditional skills(带 `paths` frontmatter,按文件路径激活)、bundled skills、plugin skills、MCP skills。\n\n### 二、SKILL.md Frontmatter 常见字段\n\nCC 的 SKILL.md YAML frontmatter 由 `parseSkillFrontmatterFields()` 解析(`loadSkillsDir.ts`),常见字段包括:\n\n| 字段 | 用途 |\n|------|------|\n| `name` / `description` | 显示名称和描述 |\n| `when_to_use` | 指导模型何时调用 |\n| `allowed-tools` | 技能可用工具的自动允许列表 |\n| `context` | `inline`(默认)或 `fork`(作为子 Agent 运行) |\n| `model` | 模型覆盖(haiku/sonnet/opus/inherit) |\n| `hooks` | 技能级别的 hook 配置 |\n| `paths` | 条件激活的 glob 模式 |\n| `user-invocable` | 用户可以通过 `/name` 调用 |\n\n完整字段列表随版本迭代会变化,以上仅列出教学版涉及的核心字段。\n\n### 三、两级加载的精确实现\n\n1. **Catalog(启动时)**:`getSkillDirCommands()` 扫描目录 → 注册为 `Command` 对象,只包含元数据。`getSkillListingAttachments()` 把技能列表格式化为附件,预算为上下文窗口的 ~1%(上限 8000 字符)。\n2. **Load(调用时)**:模型调 `Skill` 工具(输入字段是 `skill` + 可选 `args`,教学版用 `name`)→ `getPromptForCommand()` 展开完整 SKILL.md 内容 → `SkillTool` 返回的 tool_result 展示文本只是 `\"Launching skill: {name}\"`,真正的技能内容通过 `newMessages` 注入对话。教学版把两者合并为\"通过 tool_result 注入\"是一种简化;加载后的 SKILL.md 仍可作为指引,帮助模型后续通过现有 file/bash 工具访问相关资源。\n\n### 教学版的简化是刻意的\n\n- 多文件多来源 → 1 个 `skills/` 目录:足以展示两级加载的核心概念\n- 多个 frontmatter 字段 → 只解析 name/description:减少解析复杂度\n- forked skills(`context: 'fork'`)→ 省略:教学版只展开 inline 技能加载\n- `Skill` 工具输入 `skill`+`args` → 教学版用 `name`:避免参数解析的额外复杂度\n\n
\n\n\n" + "content": "# s07: Skill Loading — 用到的时候才加载\n\ns01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](/zh/s08) → s09 → ... → s20 → s21\n> *\"用到时再加载, 别全塞 prompt 里\"* — 通过 tool_result 注入, 不塞 system prompt。\n>\n> **Harness 层**: 知识 — 按需加载, 不堆满上下文。\n\n---\n\n## 问题\n\n你的项目有一套 React 组件规范、一份 SQL 风格指南、一份 API 设计文档。你希望 Agent 自动遵守这些规范。最直接的想法,全塞进 system prompt:\n\n```python\nSYSTEM = (\n f\"You are a coding agent. \"\n + open(\"docs/react-style.md\").read() # 2000 行\n + open(\"docs/sql-style.md\").read() # 1500 行\n + open(\"docs/api-design.md\").read() # 3000 行\n)\n```\n\n6500 行 system prompt。Agent 每次调用 LLM 都带着这些文档——不管是在改 CSS 颜色还是修 SQL 查询。99% 的内容和当前任务无关,白白消耗 token。\n\n---\n\n## 解决方案\n\n![Skill Overview](/course-assets/s07_skill_loading/skill-overview.svg)\n\n保留上一章的最小 hook 结构、`todo_write` 和子 Agent,本章重点转向新增的 `load_skill` 工具。启动时把技能目录注入 SYSTEM prompt,运行时多注册一个工具加载完整内容,用到才花 token。\n\n两层设计:\n\n| 层 | 位置 | 时机 | 代价 |\n|---|------|------|------|\n| 1. 目录 | system prompt | 启动时注入(harness 扫描 skills/) | ~100 tokens/skill,每轮都带 |\n| 2. 内容 | tool_result | Agent 调用 load_skill 时;SKILL.md 可指引后续的 read_file/bash 调用,用于按需访问额外资源 | ~2000 tokens/skill,按需 |\n\ndispatch 机制不变,load_skill 通过 `TOOL_HANDLERS[block.name]` 分发。\n\n---\n\n## 工作原理\n\n**skills/ 目录**,每个技能一个子目录,包含 `SKILL.md` 文件:\n\n```\nskills/\n agent-builder/SKILL.md\n code-review/SKILL.md\n mcp-builder/SKILL.md\n pdf/SKILL.md\n```\n\n**第一级:启动时注入目录**:harness 启动时调用 `_scan_skills()` 扫描 skills/ 目录,解析每个 SKILL.md 的 YAML frontmatter(`name`、`description`),存入 `SKILL_REGISTRY` 字典。`list_skills()` 从注册表生成目录,注入 SYSTEM prompt。Agent 每轮都能看到\"我有哪些技能可用\",不花额外 API 调用:\n\n```python\nSKILL_REGISTRY: dict[str, dict] = {}\n\ndef _scan_skills():\n if not SKILLS_DIR.exists():\n return\n for d in sorted(SKILLS_DIR.iterdir()):\n if not d.is_dir():\n continue\n manifest = d / \"SKILL.md\"\n if manifest.exists():\n raw = manifest.read_text()\n meta, body = _parse_frontmatter(raw)\n name = meta.get(\"name\", d.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\"name\": name, \"description\": desc, \"content\": raw}\n\n_scan_skills() # runs once at startup\n\ndef list_skills() -> str:\n return \"\\n\".join(f\"- **{s['name']}**: {s['description']}\" for s in SKILL_REGISTRY.values())\n\ndef build_system() -> str:\n catalog = list_skills()\n return (\n f\"You are a coding agent at {WORKDIR}. \"\n f\"Skills available:\\n{catalog}\\n\"\n \"Use load_skill to get full details when needed.\"\n )\n\nSYSTEM = build_system()\n```\n\n**第二级:load_skill**:Agent 决定\"我需要 SQL 风格指南\",调用 `load_skill(\"sql-style\")`。通过注册表查找,不走文件路径,没有路径遍历风险。SKILL.md 内容通过 `tool_result` 注入,并可通过现有的 file 和 bash 工具进一步访问引用的 `references/`、`scripts/` 或 `assets/`。\n\n```python\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n return f\"Skill not found: {name}\"\n return skill[\"content\"]\n```\n\n关键区别:技能内容不是 system prompt 的一部分,它作为一次工具结果进入当前 messages。后续调用会随历史一起携带,直到上下文压缩、截断或会话结束。这和 s08 的 compact 自然衔接:按需加载解决了\"不该提前带的不要带\",compact 解决\"该丢的怎么丢\"。\n\n---\n\n## 相对 s06 的变更\n\n| 组件 | 之前 (s06) | 之后 (s07) |\n|------|-----------|-----------|\n| 工具数量 | 7 (bash, read, write, edit, glob, todo_write, task) | 8 (+load_skill) |\n| 知识加载 | 无 | 两级:启动时目录注入 SYSTEM + 运行时 load_skill;SKILL.md 可指引后续资源访问 |\n| SYSTEM 提示 | 静态字符串 | 启动时扫描 skills/ 注入目录 |\n| 技能注册表 | 无 | SKILL_REGISTRY(启动时填充,防路径遍历) |\n| 循环 | 不变 | 不变(skill 工具自动分发) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s07_skill_loading/code.py\n```\n\n试试这些 prompt:\n\n1. `What skills are available?`\n2. `Load the code-review skill and follow its instructions`\n3. `I need to do a code review -- load the relevant skill first`\n\n观察重点:Agent 是否直接从 SYSTEM 里的目录知道有哪些技能?需要完整规范时是否出现 `[HOOK] load_skill`?加载后回答是否使用了对应 skill 的说明?\n\n---\n\n## 接下来\n\n按需加载解决了\"不该带的不要带\"。但另一个问题来了:Agent 连续工作 30 分钟后,messages 列表塞满了中间过程。旧的 tool_result、过时的文件内容,占着上下文但不产生价值。\n\ns08 Context Compact → 四层压缩策略。便宜的先跑,贵的后跑。\n\n\n\n" }, { "version": "s07", "locale": "ja", "title": "s07: Skill Loading — 必要なときにだけ読み込む", - "content": "# s07: Skill Loading — 必要なときにだけ読み込む\n\ns01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](/ja/s08) → s09 → ... → s20 → s21 → s22\n> *\"Load when needed, don't stuff the prompt\"* — tool_result で注入、system prompt には詰め込まない。\n>\n> **Harness レイヤー**: 知識 — 必要に応じて読み込み、コンテキストに詰め込まない。\n\n---\n\n## 課題\n\nプロジェクトには React コンポーネント仕様、SQL スタイルガイド、API 設計ドキュメントがある。Agent にこれらの仕様を自動的に守らせたい。最も直接的な方法 — すべて system prompt に詰め込む:\n\n```python\nSYSTEM = (\n f\"You are a coding agent. \"\n + open(\"docs/react-style.md\").read() # 2000 行\n + open(\"docs/sql-style.md\").read() # 1500 行\n + open(\"docs/api-design.md\").read() # 3000 行\n)\n```\n\n6500 行の system prompt。Agent は LLM を呼び出すたびにこれらのドキュメントを運ぶ — CSS の色を変えるときも SQL クエリを修正するときも。99% の内容が現在のタスクと無関係で、トークンを無駄に消費する。\n\n---\n\n## ソリューション\n\n![Skill Overview](/course-assets/s07_skill_loading/skill-overview.ja.svg)\n\n前章の最小フック構造、`todo_write`、サブ Agent を維持し、本章は新規の `load_skill` ツールに注目する。起動時にスキルカタログを SYSTEM prompt に注入し、実行時に完全な内容を読み込むツールを登録する。使ったときだけトークンを消費。\n\n2 層設計:\n\n| 層 | 場所 | タイミング | コスト |\n|---|------|-----------|--------|\n| 1. カタログ | system prompt | 起動時に注入(harness が skills/ をスキャン) | ~100 トークン/スキル、毎ターン携帯 |\n| 2. 内容 | tool_result | Agent が load_skill を呼び出したとき。SKILL.md は、必要に応じて read_file/bash で追加リソースへアクセスするための手がかりになる | ~2000 トークン/スキル、オンデマンド |\n\nディスパッチ機構は変わらず、`load_skill` は `TOOL_HANDLERS[block.name]` を通じて自動的にディスパッチされる。\n\n---\n\n## 仕組み\n\n**skills/ ディレクトリ**、スキルごとに 1 つのサブディレクトリ、それぞれに `SKILL.md` ファイルを含む:\n\n```\nskills/\n agent-builder/SKILL.md\n code-review/SKILL.md\n mcp-builder/SKILL.md\n pdf/SKILL.md\n```\n\n**第 1 層:起動時にカタログを注入**:harness は起動時に `_scan_skills()` を呼び出して skills/ ディレクトリをスキャンし、各 SKILL.md の YAML frontmatter(`name`、`description`)を解析して `SKILL_REGISTRY` 辞書に格納する。`list_skills()` はレジストリからカタログを生成し、SYSTEM prompt に注入する。Agent は毎ターン「どのスキルが利用可能か」を確認できる。追加の API 呼び出しは不要:\n\n```python\nSKILL_REGISTRY: dict[str, dict] = {}\n\ndef _scan_skills():\n if not SKILLS_DIR.exists():\n return\n for d in sorted(SKILLS_DIR.iterdir()):\n if not d.is_dir():\n continue\n manifest = d / \"SKILL.md\"\n if manifest.exists():\n raw = manifest.read_text()\n meta, body = _parse_frontmatter(raw)\n name = meta.get(\"name\", d.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\"name\": name, \"description\": desc, \"content\": raw}\n\n_scan_skills() # runs once at startup\n\ndef list_skills() -> str:\n return \"\\n\".join(f\"- **{s['name']}**: {s['description']}\" for s in SKILL_REGISTRY.values())\n\ndef build_system() -> str:\n catalog = list_skills()\n return (\n f\"You are a coding agent at {WORKDIR}. \"\n f\"Skills available:\\n{catalog}\\n\"\n \"Use load_skill to get full details when needed.\"\n )\n\nSYSTEM = build_system()\n```\n\n**第 2 層:load_skill**:Agent が「SQL スタイルガイドが必要」と判断し、`load_skill(\"sql-style\")` を呼び出す。レジストリを通じて検索し、ファイルパスを経由しないため、パストラバーサルのリスクがない。SKILL.md の内容は `tool_result` を通じて注入され、既存の file および bash ツールを通じて、参照される `references/`、`scripts/`、`assets/` へのその後のアクセスも含められる。\n\n```python\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n return f\"Skill not found: {name}\"\n return skill[\"content\"]\n```\n\n重要な違い:スキル内容は system prompt の一部ではなく、ツール結果として現在の messages に入る。後続の呼び出しでは履歴とともに携帯され、コンテキスト圧縮、切り捨て、またはセッション終了まで保持される。これは s08 の compact と自然に接続する:オンデマンド読み込みで「運ぶべきでないものは運ばない」を解決し、compact が「捨てるべきものをどう捨てるか」を解決する。\n\n---\n\n## s06 からの変更点\n\n| コンポーネント | 変更前 (s06) | 変更後 (s07) |\n|---------------|-------------|-------------|\n| ツール数 | 7 (bash, read, write, edit, glob, todo_write, task) | 8 (+load_skill) |\n| 知識読み込み | なし | 2 層:起動時カタログ注入 SYSTEM + 実行時 load_skill。SKILL.md がその後のリソースアクセスを案内できる |\n| SYSTEM プロンプト | 静的文字列 | 起動時に skills/ をスキャンしてカタログ注入 |\n| スキルレジストリ | なし | SKILL_REGISTRY(起動時に充填、パストラバーサル防止) |\n| ループ | 変更なし | 変更なし(スキルツールは自動ディスパッチ) |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s07_skill_loading/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `What skills are available?`\n2. `Load the code-review skill and follow its instructions`\n3. `I need to do a code review -- load the relevant skill first`\n\n観察のポイント:Agent は SYSTEM 内のカタログから利用可能なスキルを知っているか? 完全な手順が必要なときに `[HOOK] load_skill` が表示されるか? 読み込んだスキルの説明を使って回答しているか?\n\n---\n\n## 次へ\n\nオンデマンド読み込みで「運ぶべきでないものは運ばない」問題は解決した。しかし別の問題が待っている:Agent が 30 分連続で作業すると、messages リストが中間プロセスで埋め尽くされる。古い tool_result、期限切れのファイル内容、コンテキストを占領しているが価値を生まない。\n\n→ s08 Context Compact:4 層圧縮戦略。安価な層を先に実行、高価な層を後に実行。\n\n
\nCC ソースコードを深掘り\n\n> 以下は CC ソースコード `loadSkillsDir.ts`、`SkillTool.ts`、`bundledSkills.ts`、`commands.ts` の分析に基づく。\n\n### 一、スキルソース:skills/ ディレクトリだけではない\n\n教育版はすべてのスキルが `skills/` ディレクトリにあると想定している。CC は実際に複数のファイルに分散したソースから読み込む:`loadSkillsDir.ts` は user/project/`--add-dir` ディレクトリと legacy commands(`.claude/commands/`)を担当、`bundledSkills.ts` は組み込みスキル、`SkillTool.ts` は MCP リモートスキル、`commands.ts` はコマンド集約を担当。タイプには managed/policy skills、user skills(`~/.claude/skills/`)、project skills(`.claude/skills/`)、`--add-dir` skills、legacy commands、dynamic skills、conditional skills(`paths` frontmatter を持ち、ファイルパスでアクティベート)、bundled skills、plugin skills、MCP skills が含まれる。\n\n### 二、SKILL.md Frontmatter の一般的なフィールド\n\nCC の SKILL.md YAML frontmatter は `parseSkillFrontmatterFields()`(`loadSkillsDir.ts`)で解析される。一般的なフィールド:\n\n| フィールド | 用途 |\n|-----------|------|\n| `name` / `description` | 表示名と説明 |\n| `when_to_use` | モデルにいつ呼び出すかを指導 |\n| `allowed-tools` | スキルが使用可能なツールの自動許可リスト |\n| `context` | `inline`(デフォルト)または `fork`(サブ Agent として実行) |\n| `model` | モデルオーバーライド(haiku/sonnet/opus/inherit) |\n| `hooks` | スキルレベルのフック設定 |\n| `paths` | 条件付きアクティベーションの glob パターン |\n| `user-invocable` | ユーザーが `/name` で呼び出し可能 |\n\n完全なフィールドリストはバージョンによって変動する。上記は教育版に関連するコアフィールドのみ。\n\n### 三、2 層読み込みの正確な実装\n\n1. **カタログ(起動時)**:`getSkillDirCommands()` がディレクトリをスキャン → メタデータのみを含む `Command` オブジェクトとして登録。`getSkillListingAttachments()` がスキルリストを添付ファイルとしてフォーマット、コンテキストウィンドウの ~1% を予算とする(上限 8000 文字)。\n2. **読み込み(呼び出し時)**:モデルが `Skill` ツールを呼び出す(入力フィールドは `skill` + オプションの `args`、教育版は `name` を使用)→ `getPromptForCommand()` が完全な SKILL.md 内容を展開 → `SkillTool` が返す tool_result の表示テキストは `\"Launching skill: {name}\"` のみ、実際のスキル内容は `newMessages` を通じて注入される。教育版では両者を「tool_result を通じて注入」として簡略化している。読み込まれた SKILL.md は、モデルが後続で既存の file/bash ツールから関連リソースへアクセスする際の手がかりにもなる。\n\n### 教育版の単純化は意図的\n\n- 複数ファイル・複数ソース → 1 つの `skills/` ディレクトリ:2 層読み込みの核心概念を示すのに十分\n- 複数の frontmatter フィールド → name/description のみ解析:解析の複雑さを削減\n- forked skills(`context: 'fork'`)→ 省略:教育版では inline skill loading のみ展開する\n- `Skill` ツールの入力 `skill`+`args` → 教育版は `name` を使用:追加の引数解析の複雑さを回避\n\n
\n\n\n" + "content": "# s07: Skill Loading — 必要なときにだけ読み込む\n\ns01 → s02 → s03 → s04 → s05 → s06 → `s07` → [s08](/ja/s08) → s09 → ... → s20 → s21\n> *\"Load when needed, don't stuff the prompt\"* — tool_result で注入、system prompt には詰め込まない。\n>\n> **Harness レイヤー**: 知識 — 必要に応じて読み込み、コンテキストに詰め込まない。\n\n---\n\n## 課題\n\nプロジェクトには React コンポーネント仕様、SQL スタイルガイド、API 設計ドキュメントがある。Agent にこれらの仕様を自動的に守らせたい。最も直接的な方法 — すべて system prompt に詰め込む:\n\n```python\nSYSTEM = (\n f\"You are a coding agent. \"\n + open(\"docs/react-style.md\").read() # 2000 行\n + open(\"docs/sql-style.md\").read() # 1500 行\n + open(\"docs/api-design.md\").read() # 3000 行\n)\n```\n\n6500 行の system prompt。Agent は LLM を呼び出すたびにこれらのドキュメントを運ぶ — CSS の色を変えるときも SQL クエリを修正するときも。99% の内容が現在のタスクと無関係で、トークンを無駄に消費する。\n\n---\n\n## ソリューション\n\n![Skill Overview](/course-assets/s07_skill_loading/skill-overview.ja.svg)\n\n前章の最小フック構造、`todo_write`、サブ Agent を維持し、本章は新規の `load_skill` ツールに注目する。起動時にスキルカタログを SYSTEM prompt に注入し、実行時に完全な内容を読み込むツールを登録する。使ったときだけトークンを消費。\n\n2 層設計:\n\n| 層 | 場所 | タイミング | コスト |\n|---|------|-----------|--------|\n| 1. カタログ | system prompt | 起動時に注入(harness が skills/ をスキャン) | ~100 トークン/スキル、毎ターン携帯 |\n| 2. 内容 | tool_result | Agent が load_skill を呼び出したとき。SKILL.md は、必要に応じて read_file/bash で追加リソースへアクセスするための手がかりになる | ~2000 トークン/スキル、オンデマンド |\n\nディスパッチ機構は変わらず、`load_skill` は `TOOL_HANDLERS[block.name]` を通じて自動的にディスパッチされる。\n\n---\n\n## 仕組み\n\n**skills/ ディレクトリ**、スキルごとに 1 つのサブディレクトリ、それぞれに `SKILL.md` ファイルを含む:\n\n```\nskills/\n agent-builder/SKILL.md\n code-review/SKILL.md\n mcp-builder/SKILL.md\n pdf/SKILL.md\n```\n\n**第 1 層:起動時にカタログを注入**:harness は起動時に `_scan_skills()` を呼び出して skills/ ディレクトリをスキャンし、各 SKILL.md の YAML frontmatter(`name`、`description`)を解析して `SKILL_REGISTRY` 辞書に格納する。`list_skills()` はレジストリからカタログを生成し、SYSTEM prompt に注入する。Agent は毎ターン「どのスキルが利用可能か」を確認できる。追加の API 呼び出しは不要:\n\n```python\nSKILL_REGISTRY: dict[str, dict] = {}\n\ndef _scan_skills():\n if not SKILLS_DIR.exists():\n return\n for d in sorted(SKILLS_DIR.iterdir()):\n if not d.is_dir():\n continue\n manifest = d / \"SKILL.md\"\n if manifest.exists():\n raw = manifest.read_text()\n meta, body = _parse_frontmatter(raw)\n name = meta.get(\"name\", d.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\"name\": name, \"description\": desc, \"content\": raw}\n\n_scan_skills() # runs once at startup\n\ndef list_skills() -> str:\n return \"\\n\".join(f\"- **{s['name']}**: {s['description']}\" for s in SKILL_REGISTRY.values())\n\ndef build_system() -> str:\n catalog = list_skills()\n return (\n f\"You are a coding agent at {WORKDIR}. \"\n f\"Skills available:\\n{catalog}\\n\"\n \"Use load_skill to get full details when needed.\"\n )\n\nSYSTEM = build_system()\n```\n\n**第 2 層:load_skill**:Agent が「SQL スタイルガイドが必要」と判断し、`load_skill(\"sql-style\")` を呼び出す。レジストリを通じて検索し、ファイルパスを経由しないため、パストラバーサルのリスクがない。SKILL.md の内容は `tool_result` を通じて注入され、既存の file および bash ツールを通じて、参照される `references/`、`scripts/`、`assets/` へのその後のアクセスも含められる。\n\n```python\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n return f\"Skill not found: {name}\"\n return skill[\"content\"]\n```\n\n重要な違い:スキル内容は system prompt の一部ではなく、ツール結果として現在の messages に入る。後続の呼び出しでは履歴とともに携帯され、コンテキスト圧縮、切り捨て、またはセッション終了まで保持される。これは s08 の compact と自然に接続する:オンデマンド読み込みで「運ぶべきでないものは運ばない」を解決し、compact が「捨てるべきものをどう捨てるか」を解決する。\n\n---\n\n## s06 からの変更点\n\n| コンポーネント | 変更前 (s06) | 変更後 (s07) |\n|---------------|-------------|-------------|\n| ツール数 | 7 (bash, read, write, edit, glob, todo_write, task) | 8 (+load_skill) |\n| 知識読み込み | なし | 2 層:起動時カタログ注入 SYSTEM + 実行時 load_skill。SKILL.md がその後のリソースアクセスを案内できる |\n| SYSTEM プロンプト | 静的文字列 | 起動時に skills/ をスキャンしてカタログ注入 |\n| スキルレジストリ | なし | SKILL_REGISTRY(起動時に充填、パストラバーサル防止) |\n| ループ | 変更なし | 変更なし(スキルツールは自動ディスパッチ) |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s07_skill_loading/code.py\n```\n\n以下のプロンプトを試してみよう:\n\n1. `What skills are available?`\n2. `Load the code-review skill and follow its instructions`\n3. `I need to do a code review -- load the relevant skill first`\n\n観察のポイント:Agent は SYSTEM 内のカタログから利用可能なスキルを知っているか? 完全な手順が必要なときに `[HOOK] load_skill` が表示されるか? 読み込んだスキルの説明を使って回答しているか?\n\n---\n\n## 次へ\n\nオンデマンド読み込みで「運ぶべきでないものは運ばない」問題は解決した。しかし別の問題が待っている:Agent が 30 分連続で作業すると、messages リストが中間プロセスで埋め尽くされる。古い tool_result、期限切れのファイル内容、コンテキストを占領しているが価値を生まない。\n\n→ s08 Context Compact:4 層圧縮戦略。安価な層を先に実行、高価な層を後に実行。\n\n\n\n" }, { "version": "s08", "locale": "en", "title": "s08: Context Compact — Context Will Fill Up, Have a Way to Make Room", - "content": "# s08: Context Compact — Context Will Fill Up, Have a Way to Make Room\n\ns01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](/en/s09) → s10 → ... → s20 → s21 → s22\n> *\"Context will fill up — have a way to make room\"* — Four-layer compression pipeline: cheap first, expensive last.\n>\n> **Harness Layer**: Compression — clean memory, unlimited sessions.\n\n---\n\n## The Problem\n\nThe agent is running along, then freezes.\n\nIt has bash, read, write — all the capabilities it needs. But it read a 1000-line file (~4000 tokens), then read 30 more files, ran 20 commands. Every command's output, every file's contents, all pile up in the `messages` list.\n\nThe context window is finite. Once full, the API outright rejects the call: `prompt_too_long`.\n\nWithout compression, an agent simply cannot work on large projects.\n\n---\n\n## The Solution\n\n![Compact Overview](/course-assets/s08_context_compact/compact-overview.en.svg)\n\nThe hook structure, skill loading, and sub-Agent from s07 are preserved, with some tools omitted to focus on compaction. The core change: insert three pre-processors (0 API calls) before each LLM call, trigger an LLM summary (1 API call) when tokens still exceed the threshold, and emergency-trim if the API throws an error.\n\nCore design: cheap first, expensive last.\n\n> **Boundary with s09:** s08 manages the current session's finite context and may lose detail while compressing it. s09 adds a separate durable store for selected information that must survive compaction and future sessions. They solve different failure modes, so they remain separate lessons.\n\n---\n\n## How It Works\n\n![Four-layer compression pipeline](/course-assets/s08_context_compact/compaction-layers.en.svg)\n\n### L1: snip_compact — Trim Irrelevant Old Conversation\n\nThe agent ran 80 turns of conversation, accumulating 160 `messages`. The very first \"help me create hello.py\" is barely relevant to current work, yet it still occupies space.\n\nMessage count exceeds 50 → keep the first 3 (initial context) and the last 47 (current work), trim the middle; the only extra boundary rule is that `assistant(tool_use)` must not be separated from the following `user(tool_result)`:\n\n```python\ndef snip_compact(messages, max_messages=50):\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and _is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n snipped = tail_start - head_end\n placeholder = {\"role\": \"user\", \"content\": f\"[snipped {snipped} messages from conversation middle]\"}\n return messages[:head_end] + [placeholder] + messages[tail_start:]\n```\n\nMessages are still trimmed directly; this just adds one boundary guard. `tool_result` content within remaining messages still keeps accumulating — message #34 may still hold 30KB of old file contents. → L2.\n\n### L2: micro_compact — Placeholder for Old Tool Results\n\n![Old results placeholder](/course-assets/s08_context_compact/micro-compact.en.svg)\n\nThe agent read 10 files consecutively. The full contents of reads 1–7 are still sitting in context, no longer needed, but hogging large amounts of space.\n\nKeep only the 3 most recent `tool_result` entries intact; replace older ones with a one-line placeholder:\n\n```python\nKEEP_RECENT_TOOL_RESULTS = 3\n\ndef micro_compact(messages):\n tool_results = collect_tool_result_blocks(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(block.get(\"content\", \"\")) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n```\n\nOld results are cleared, but a single new result can be 500KB — one `cat` of a large file can max out the context. → L3.\n\n### L3: tool_result_budget — Persist Large Results to Disk\n\n![Large results to disk](/course-assets/s08_context_compact/layer1-budget.en.svg)\n\nThe model read 5 large files in one go; all `tool_result` blocks in the last user message total 500KB.\n\nSum the size of all `tool_result` blocks in the last user message. If over 200KB → sort by size, starting from the largest, persist to `.task_outputs/tool-results/`, keeping only a `` marker + a 2000-character preview in context. The model sees the marker and knows the full content is on disk, re-reading it when needed.\n\n```python\ndef tool_result_budget(messages, max_bytes=200_000):\n last = messages[-1]\n blocks = [(i, b) for i, b in enumerate(last[\"content\"])\n if b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n ranked = sorted(blocks, key=lambda p: len(str(p[1].get(\"content\", \"\"))), reverse=True)\n for idx, block in ranked:\n if total <= max_bytes:\n break\n block[\"content\"] = persist_large_output(block[\"tool_use_id\"], str(block[\"content\"]))\n total = recalculate_total(blocks)\n return messages\n```\n\nThe first three layers are all plain-text / structural operations — 0 API calls — but they cannot \"understand\" conversation content. Context may still be too large. → L4.\n\n### L4: compact_history — Full LLM Summary\n\n![Full LLM summary](/course-assets/s08_context_compact/auto-compact.en.svg)\n\nAll three previous layers have run, but after 30 minutes of continuous work on a huge project, tokens still exceed the threshold.\n\nThree-step process:\n\n1. **Save transcript**: Write the full conversation to `.transcripts/` in JSONL format. The transcript preserves a recoverable record, but the model's active context only contains the summary. For the model's current reasoning, the details are no longer in context. The teaching code does not provide a transcript retrieval tool.\n2. **LLM generates summary**: Send conversation history to the LLM, asking it to preserve key information: current goals, important findings, modified files, remaining work, user constraints, etc.\n3. **Replace message list**: All old messages are replaced with a single summary. The teaching version only keeps the summary; the real Claude Code re-attaches some recent files, plans, agent/skill/tool context after compaction.\n\n```python\ndef compact_history(messages):\n transcript_path = write_transcript(messages) # Save full conversation first\n summary = summarize_history(messages) # LLM generates summary\n return [{\"role\": \"user\",\n \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n```\n\n**Circuit breaker**: After 3 consecutive failures, stop retrying to prevent an infinite loop wasting API calls.\n\n### Reactive: reactive_compact\n\nSometimes the API still returns `prompt_too_long` (413) — when context grows faster than compression triggers.\n\nThis triggers **reactive_compact**: more aggressive than compact_history in trigger (emergency response to a 413 error), but more conservative in what it removes, keeping ~5 recent messages and only summarizing earlier history. Still avoids an orphaned `tool_result`.\n\n```python\ndef reactive_compact(messages):\n transcript = write_transcript(messages)\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n summary = summarize_history(messages[:tail_start])\n return [{\"role\": \"user\",\n \"content\": f\"[Reactive compact]\\n\\n{summary}\"}, *messages[tail_start:]]\n```\n\nReactive compact has a retry limit (default 1). If it still fails, an exception is raised instead of looping forever. Full error recovery is deferred to s11.\n\n### Putting It All Together\n\n```python\ndef agent_loop(messages):\n reactive_retries = 0\n while True:\n # Three pre-processors (0 API calls)\n # Order: budget first, so large content is persisted before placeholders\n messages[:] = tool_result_budget(messages) # L3: persist large results\n messages[:] = snip_compact(messages) # L1: trim middle\n messages[:] = micro_compact(messages) # L2: old result placeholders\n\n # Still too much? LLM summary (1 API call)\n if estimate_token_count(messages) > THRESHOLD:\n messages[:] = compact_history(messages)\n\n try:\n response = client.messages.create(...)\n except PromptTooLongError:\n if reactive_retries < MAX_REACTIVE_RETRIES:\n messages[:] = reactive_compact(messages) # Emergency\n reactive_retries += 1\n continue\n raise # retry limit exceeded, raise exception\n # ... tool execution ...\n\n # compact tool: when the model actively calls it, triggers compact_history\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n results.append({..., \"content\": \"[Compacted. History summarized.]\"})\n messages.append({\"role\": \"user\", \"content\": results})\n break # end current turn, start fresh with compacted context\n```\n\n**The order must not be swapped.** L3 (budget) runs before L2 (micro) because micro replaces old large tool_results with one-line placeholders — budget must persist the full content before that happens. This is why CC source puts `applyToolResultBudget` first.\n\n---\n\n## Changes From s07\n\n| Component | Before (s07) | After (s08) |\n|-----------|-------------|-------------|\n| Context management | None (context grows unbounded) | Four-layer compression pipeline + emergency |\n| New functions | — | snip_compact, micro_compact, tool_result_budget, compact_history, reactive_compact |\n| Tools | bash, read_file, write_file, edit_file, glob, todo_write, task, load_skill (8) | 8 + compact (9) |\n| Loop | LLM call → tool execution | Three pre-processors before each turn + threshold-triggered compact_history |\n| Design principle | — | Cheap first, expensive last |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s08_context_compact/code.py\n```\n\nTry these prompts:\n\n1. `Read the file README.md, then read code.py, then read s01_agent_loop/README.md` (read multiple files consecutively, observe L2 compressing old results)\n2. `Read every file in s08_context_compact/` (read a large amount of content at once, observe L3 persisting to disk)\n3. Chat for 20+ turns, observe whether `[auto compact]` or `[reactive compact]` appears\n\nWhat to watch for: After each tool execution, are old `tool_result` entries compressed? When tokens exceed the threshold after extended conversation, is summarization triggered automatically?\n\n---\n\n## What's Next\n\nContext compression lets an agent run for a long time without crashing. But after each compression, the preferences and constraints the user told it are also lost. Can we let the agent selectively remember important things?\n\ns09 Memory → three subsystems: choosing what to remember, extracting key information, consolidating and organizing. Across compressions, across sessions.\n\n
\nDeep Dive Into CC Source Code\n\n> The following is based on analysis of CC source code `compact.ts`, `autoCompact.ts`, `microCompact.ts`, and `query.ts`.\n\n### Execution Order Comparison\n\nThe teaching version labels layers L1/L2/L3/L4 for pedagogical clarity, but actual execution order does not match the numbering:\n\n| Dimension | Teaching Version | Claude Code |\n|-----------|-----------------|-------------|\n| Execution order | budget → snip → micro → auto | budget → snip → micro → collapse → auto (`query.ts:379-468`) |\n| snip_compact | Keep head 3 + tail 47 | CC only enables on main thread; implementation not in open-source repo (`HISTORY_SNIP` feature gate), but interface is visible: `snipCompactIfNeeded(messages)` → `{ messages, tokensFreed, boundaryMessage? }`, also exposes `SnipTool` for model-initiated snipping. Teaching version's 3/47 are simplified parameters |\n| micro_compact | Text placeholder replacement | Two paths: time-based clears content directly, cached uses API `cache_edits` (legacy path removed) |\n| micro_compact whitelist | By position (most recent 3) | time-based triggers by time threshold; cached triggers by count (`microCompact.ts`) |\n| tool_result_budget | 200KB characters | 200,000 characters (`toolLimits.ts:49`) |\n| compact_history threshold | Character count estimate | Precise tokens: `contextWindow - maxOutputTokens - 13_000` |\n| Summary requirements | 5 categories of info | 9 sections + ``/`` dual tags |\n| Compression prompt | Simple prompt | Double-ended hard guardrails forbidding tool calls |\n| PTL retry | Yes (simplified) | `truncateHeadForPTLRetry()` retreats by message groups (`compact.ts:243-290`) |\n| Post-compaction recovery | None (teaching version only keeps summary) | Auto re-read recent files, plans, agent/skill/tool context |\n| Circuit breaker | 3 times | 3 times (`autoCompact.ts:70`) |\n| Reactive retry | 1 time | CC has more granular tiered retries |\n\n### Execution Order Details\n\nThe real order in CC source `query.ts`:\n\n1. `applyToolResultBudget` (L379): persist large results first, ensuring full content is saved\n2. `snipCompact` (L403): trim middle messages\n3. `microcompact` (L414): old result placeholders\n4. `contextCollapse` (L441): independent context management system (not in teaching version)\n5. `autoCompact` (L454): LLM full summary\n\nThe teaching version's budget → snip → micro order matches this. The teaching version does not have the contextCollapse mechanism.\n\n### read_file Trade-off\n\nThe teaching version's `micro_compact` replaces old `tool_result` blocks with placeholders uniformly, including `read_file`. This usually does not affect functional correctness: if the model needs the file contents later, it can read the file again. The cost is an extra tool call and potentially lower prompt cache hit rates.\n\nClaude Code does not solve this with the teaching version's simple rule. It also puts `Read` in the microcompactable tool set, but maintains a separate `readFileState`: repeated reads of unchanged files return `FILE_UNCHANGED_STUB`, and after compaction it restores recently read file contents within a budget (for example, up to 5 files, 5K tokens per file, 50K tokens total). That is a production-level cache and recovery mechanism. The teaching version does not expand into that machinery; it keeps the simpler trade-off of compacting old results and re-reading when needed.\n\n### Full Constant Reference\n\n| Constant | Value | Source File |\n|----------|-------|-------------|\n| `AUTOCOMPACT_BUFFER_TOKENS` | 13,000 | `autoCompact.ts:62` |\n| `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` | 3 | `autoCompact.ts:70` |\n| `MAX_OUTPUT_TOKENS_FOR_SUMMARY` | 20,000 | `autoCompact.ts:30` |\n| `POST_COMPACT_TOKEN_BUDGET` | 50,000 | `compact.ts:123` |\n| `POST_COMPACT_MAX_FILES_TO_RESTORE` | 5 | `compact.ts:122` |\n| `POST_COMPACT_MAX_TOKENS_PER_FILE` | 5,000 | `compact.ts:124` |\n| Time micro_compact interval | 60 minutes | `timeBasedMCConfig.ts` |\n| `MAX_COMPACT_STREAMING_RETRIES` | 2 | `compact.ts:131` |\n\n### contextCollapse and sessionMemoryCompact\n\nCC source code has two additional mechanisms not covered in this teaching version:\n\n- **contextCollapse**: An independent context management system that, when enabled, suppresses proactive autocompact (`autoCompact.ts:215-222`), with collapse's commit/blocking flow taking over context management. Manual `/compact` and reactive fallback remain independent paths, unaffected by contextCollapse.\n- **sessionMemoryCompact**: Before compact_history, CC first attempts a lightweight summary using existing session memory (covered in s09) without calling the LLM. This mechanism becomes clearer after learning s09.\n\n### What Does the Compression Prompt Look Like?\n\nCC's compression prompt has two hard requirements:\n\n1. **Absolutely no tool calls**: It begins with `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.`, and appends another REMINDER at the end\n2. **Analyze first, then summarize**: The model must first reason in an `` tag, then output the formal summary in a `` tag. The analysis is stripped during formatting\n\n### Teaching Version Simplifications Are Intentional\n\n- micro_compact uses text placeholders → we don't have API-level `cache_edits` access\n- read_file is not special-cased → the teaching version accepts re-reading when needed instead of introducing readFileState and post-compaction recovery\n- Tokens estimated via character count → precise tokenizers are out of scope\n- Post-compaction recovery omitted → teaching version only keeps summary, does not auto re-attach files\n- Two auxiliary mechanisms not covered → they fall in the 10% detail category\n\nThe core design principle, cheap first, expensive last, is fully preserved.\n\n
\n\n\n" + "content": "# s08: Context Compact — Context Will Fill Up, Have a Way to Make Room\n\ns01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](/en/s09) → s10 → ... → s20 → s21\n> *\"Context will fill up — have a way to make room\"* — Four-layer compression pipeline: cheap first, expensive last.\n>\n> **Harness Layer**: Compression — clean memory, unlimited sessions.\n\n---\n\n## The Problem\n\nThe agent is running along, then freezes.\n\nIt has bash, read, write — all the capabilities it needs. But it read a 1000-line file (~4000 tokens), then read 30 more files, ran 20 commands. Every command's output, every file's contents, all pile up in the `messages` list.\n\nThe context window is finite. Once full, the API outright rejects the call: `prompt_too_long`.\n\nWithout compression, an agent simply cannot work on large projects.\n\n---\n\n## The Solution\n\n![Compact Overview](/course-assets/s08_context_compact/compact-overview.en.svg)\n\nThe hook structure, skill loading, and sub-Agent from s07 are preserved, with some tools omitted to focus on compaction. The core change: insert three pre-processors (0 API calls) before each LLM call, trigger an LLM summary (1 API call) when tokens still exceed the threshold, and emergency-trim if the API throws an error.\n\nCore design: cheap first, expensive last.\n\n> **Boundary with s09:** s08 manages the current session's finite context and may lose detail while compressing it. s09 adds a separate durable store for selected information that must survive compaction and future sessions. They solve different failure modes, so they remain separate lessons.\n\n---\n\n## How It Works\n\n![Four-layer compression pipeline](/course-assets/s08_context_compact/compaction-layers.en.svg)\n\n### L1: snip_compact — Trim Irrelevant Old Conversation\n\nThe agent ran 80 turns of conversation, accumulating 160 `messages`. The very first \"help me create hello.py\" is barely relevant to current work, yet it still occupies space.\n\nMessage count exceeds 50 → keep the first 3 (initial context) and the last 47 (current work), trim the middle; the only extra boundary rule is that `assistant(tool_use)` must not be separated from the following `user(tool_result)`:\n\n```python\ndef snip_compact(messages, max_messages=50):\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and _is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n snipped = tail_start - head_end\n placeholder = {\"role\": \"user\", \"content\": f\"[snipped {snipped} messages from conversation middle]\"}\n return messages[:head_end] + [placeholder] + messages[tail_start:]\n```\n\nMessages are still trimmed directly; this just adds one boundary guard. `tool_result` content within remaining messages still keeps accumulating — message #34 may still hold 30KB of old file contents. → L2.\n\n### L2: micro_compact — Placeholder for Old Tool Results\n\n![Old results placeholder](/course-assets/s08_context_compact/micro-compact.en.svg)\n\nThe agent read 10 files consecutively. The full contents of reads 1–7 are still sitting in context, no longer needed, but hogging large amounts of space.\n\nKeep only the 3 most recent `tool_result` entries intact; replace older ones with a one-line placeholder:\n\n```python\nKEEP_RECENT_TOOL_RESULTS = 3\n\ndef micro_compact(messages):\n tool_results = collect_tool_result_blocks(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(block.get(\"content\", \"\")) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n```\n\nOld results are cleared, but a single new result can be 500KB — one `cat` of a large file can max out the context. → L3.\n\n### L3: tool_result_budget — Persist Large Results to Disk\n\n![Large results to disk](/course-assets/s08_context_compact/layer1-budget.en.svg)\n\nThe model read 5 large files in one go; all `tool_result` blocks in the last user message total 500KB.\n\nSum the size of all `tool_result` blocks in the last user message. If over 200KB → sort by size, starting from the largest, persist to `.task_outputs/tool-results/`, keeping only a `` marker + a 2000-character preview in context. The model sees the marker and knows the full content is on disk, re-reading it when needed.\n\n```python\ndef tool_result_budget(messages, max_bytes=200_000):\n last = messages[-1]\n blocks = [(i, b) for i, b in enumerate(last[\"content\"])\n if b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n ranked = sorted(blocks, key=lambda p: len(str(p[1].get(\"content\", \"\"))), reverse=True)\n for idx, block in ranked:\n if total <= max_bytes:\n break\n block[\"content\"] = persist_large_output(block[\"tool_use_id\"], str(block[\"content\"]))\n total = recalculate_total(blocks)\n return messages\n```\n\nThe first three layers are all plain-text / structural operations — 0 API calls — but they cannot \"understand\" conversation content. Context may still be too large. → L4.\n\n### L4: compact_history — Full LLM Summary\n\n![Full LLM summary](/course-assets/s08_context_compact/auto-compact.en.svg)\n\nAll three previous layers have run, but after 30 minutes of continuous work on a huge project, tokens still exceed the threshold.\n\nThree-step process:\n\n1. **Save transcript**: Write the full conversation to `.transcripts/` in JSONL format. The transcript keeps a complete record; the message list keeps only the summary, so the original details no longer enter later model calls.\n2. **LLM generates summary**: Send conversation history to the LLM, asking it to preserve key information: current goals, important findings, modified files, remaining work, user constraints, etc.\n3. **Replace message list**: All old messages are replaced with a single summary.\n\n```python\ndef compact_history(messages):\n transcript_path = write_transcript(messages) # Save full conversation first\n summary = summarize_history(messages) # LLM generates summary\n return [{\"role\": \"user\",\n \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n```\n\n**Circuit breaker**: After 3 consecutive failures, stop retrying to prevent an infinite loop wasting API calls.\n\n### Reactive: reactive_compact\n\nSometimes the API still returns `prompt_too_long` (413) — when context grows faster than compression triggers.\n\nThis triggers **reactive_compact**: more aggressive than compact_history in trigger (emergency response to a 413 error), but more conservative in what it removes, keeping ~5 recent messages and only summarizing earlier history. Still avoids an orphaned `tool_result`.\n\n```python\ndef reactive_compact(messages):\n transcript = write_transcript(messages)\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n summary = summarize_history(messages[:tail_start])\n return [{\"role\": \"user\",\n \"content\": f\"[Reactive compact]\\n\\n{summary}\"}, *messages[tail_start:]]\n```\n\nReactive compact has a retry limit (default 1). If it still fails, an exception is raised instead of looping forever. Full error recovery is deferred to s11.\n\n### Putting It All Together\n\n```python\ndef agent_loop(messages):\n reactive_retries = 0\n while True:\n # Three pre-processors (0 API calls)\n # Order: budget first, so large content is persisted before placeholders\n messages[:] = tool_result_budget(messages) # L3: persist large results\n messages[:] = snip_compact(messages) # L1: trim middle\n messages[:] = micro_compact(messages) # L2: old result placeholders\n\n # Still too much? LLM summary (1 API call)\n if estimate_token_count(messages) > THRESHOLD:\n messages[:] = compact_history(messages)\n\n try:\n response = client.messages.create(...)\n except PromptTooLongError:\n if reactive_retries < MAX_REACTIVE_RETRIES:\n messages[:] = reactive_compact(messages) # Emergency\n reactive_retries += 1\n continue\n raise # retry limit exceeded, raise exception\n # ... tool execution ...\n\n # compact tool: when the model actively calls it, triggers compact_history\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n results.append({..., \"content\": \"[Compacted. History summarized.]\"})\n messages.append({\"role\": \"user\", \"content\": results})\n break # end current turn, start fresh with compacted context\n```\n\n**The order must not be swapped.** L3 (budget) runs before L2 (micro) because micro replaces old large tool_results with one-line placeholders, so budget must persist the full content first.\n\n---\n\n## Changes From s07\n\n| Component | Before (s07) | After (s08) |\n|-----------|-------------|-------------|\n| Context management | None (context grows unbounded) | Four-layer compression pipeline + emergency |\n| New functions | — | snip_compact, micro_compact, tool_result_budget, compact_history, reactive_compact |\n| Tools | bash, read_file, write_file, edit_file, glob, todo_write, task, load_skill (8) | 8 + compact (9) |\n| Loop | LLM call → tool execution | Three pre-processors before each turn + threshold-triggered compact_history |\n| Design principle | — | Cheap first, expensive last |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s08_context_compact/code.py\n```\n\nTry these prompts:\n\n1. `Read the file README.md, then read code.py, then read s01_agent_loop/README.md` (read multiple files consecutively, observe L2 compressing old results)\n2. `Read every file in s08_context_compact/` (read a large amount of content at once, observe L3 persisting to disk)\n3. Chat for 20+ turns, observe whether `[auto compact]` or `[reactive compact]` appears\n\nWhat to watch for: After each tool execution, are old `tool_result` entries compressed? When tokens exceed the threshold after extended conversation, is summarization triggered automatically?\n\n---\n\n## What's Next\n\nContext compression lets an agent run for a long time without crashing. But after each compression, the preferences and constraints the user told it are also lost. Can we let the agent selectively remember important things?\n\ns09 Memory → three subsystems: choosing what to remember, extracting key information, consolidating and organizing. Across compressions, across sessions.\n\n\n\n" }, { "version": "s08", "locale": "zh", "title": "s08: Context Compact — 上下文总会满,要有办法腾地方", - "content": "# s08: Context Compact — 上下文总会满,要有办法腾地方\n\ns01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](/zh/s09) → s10 → ... → s20 → s21 → s22\n> *\"上下文总会满, 要有办法腾地方\"* — 四层压缩策略, 便宜的先跑贵的后跑。\n>\n> **Harness 层**: 压缩 — 干净的记忆, 无限的会话。\n\n---\n\n## 问题\n\nAgent 跑着跑着,不动了。\n\n手里有 bash、有 read、有 write,能力是够的。但它读了一个 1000 行的文件(~4000 token),又读了 30 个文件,跑了 20 条命令。每条命令的输出、每个文件的内容,全都堆在 `messages` 列表里。\n\n上下文窗口是有限的。满了之后,API 直接拒绝:`prompt_too_long`。\n\n不压缩,Agent 根本没法在大项目里干活。\n\n---\n\n## 解决方案\n\n![Compact Overview](/course-assets/s08_context_compact/compact-overview.svg)\n\n保留 s07 的 hook 结构、技能加载、子 Agent 等骨架,省略部分工具细节以聚焦压缩。核心变动:每轮 LLM 调用前插入三层预处理器(0 API),token 仍超阈值时触发 LLM 摘要(1 API),API 报错时应急裁剪。\n\n核心设计:便宜的先跑,贵的后跑。\n\n> **与 s09 的边界:** s08 管理当前会话有限的上下文,压缩时允许丢失细节;s09 另建持久存储,只保留需要跨压缩、跨会话存在的信息。两章解决的是不同故障,因此不合并。\n\n---\n\n## 工作原理\n\n![四层压缩管线](/course-assets/s08_context_compact/compaction-layers.svg)\n\n### L1: snip_compact — 裁掉无关的旧对话\n\nAgent 跑了 80 轮对话,`messages` 攒了 160 条。最前面的\"帮我创建 hello.py\"和当前工作几乎无关了,但全占着位置。\n\n消息数超过 50 条 → 保留头部 3 条(初始上下文)和尾部 47 条(当前工作),中间裁掉;唯一额外边界条件是,不能把 `assistant(tool_use)` 和后面的 `user(tool_result)` 拆开:\n\n```python\ndef snip_compact(messages, max_messages=50):\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and _is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n snipped = tail_start - head_end\n placeholder = {\"role\": \"user\", \"content\": f\"[snipped {snipped} messages from conversation middle]\"}\n return messages[:head_end] + [placeholder] + messages[tail_start:]\n```\n\n裁掉的是消息本身,只是在切口处多做一步保护;剩下的消息里 `tool_result` 内容仍在累积——第 34 条消息里可能躺着 30KB 的旧文件内容。→ L2。\n\n### L2: micro_compact — 旧工具结果占位\n\n![旧结果占位](/course-assets/s08_context_compact/micro-compact.svg)\n\nAgent 连续读了 10 个文件。第 1-7 次的完整内容还躺在上下文里,早就不需要了,但占着大量空间。\n\n只保留最近 3 条 `tool_result` 的完整内容,更旧的替换为一行占位符:\n\n```python\nKEEP_RECENT_TOOL_RESULTS = 3\n\ndef micro_compact(messages):\n tool_results = collect_tool_result_blocks(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(block.get(\"content\", \"\")) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n```\n\n旧结果清掉了,但单条新结果可能就有 500KB——一个 `cat` 大文件的输出就能打满上下文。→ L3。\n\n### L3: tool_result_budget — 大结果落盘\n\n![大结果落盘](/course-assets/s08_context_compact/layer1-budget.svg)\n\n模型一次读了 5 个大文件,单条 user 消息里所有 `tool_result` 加起来 500KB。\n\n统计最后一条 user 消息里所有 `tool_result` 的总大小。超过 200KB → 按大小排序,从最大的开始落盘到 `.task_outputs/tool-results/`,上下文里只留 `` 标记 + 前 2000 字符预览。模型看到标记后知道完整内容在磁盘上,需要时可以重新读。\n\n```python\ndef tool_result_budget(messages, max_bytes=200_000):\n last = messages[-1]\n blocks = [(i, b) for i, b in enumerate(last[\"content\"])\n if b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n ranked = sorted(blocks, key=lambda p: len(str(p[1].get(\"content\", \"\"))), reverse=True)\n for idx, block in ranked:\n if total <= max_bytes:\n break\n block[\"content\"] = persist_large_output(block[\"tool_use_id\"], str(block[\"content\"]))\n total = recalculate_total(blocks)\n return messages\n```\n\n前三层都是纯文本/结构操作,0 API 调用,但也无法\"理解\"对话内容。上下文可能仍然太大。→ L4。\n\n### L4: compact_history — LLM 全量摘要\n\n![LLM 全量摘要](/course-assets/s08_context_compact/auto-compact.svg)\n\n前三层全跑完了,但在超大项目中连续工作 30 分钟后,token 仍然超过阈值。\n\n三步流程:\n\n1. **保存 transcript**:完整对话写入 `.transcripts/`,JSONL 格式。transcript 保留了可恢复记录,但模型的活跃上下文里只剩摘要。对模型当下推理来说,细节已经不在上下文中了。教学代码没有提供 transcript 检索工具。\n2. **LLM 生成摘要**:把对话历史发给 LLM,要求保留当前目标、重要发现、已改文件、剩余工作、用户约束等关键信息。\n3. **替换消息列表**:所有旧消息被替换为一条摘要。教学版只保留摘要;真实 Claude Code 会在 compact 后重新附加部分最近文件、计划、agent/skill/tool 等上下文。\n\n```python\ndef compact_history(messages):\n transcript_path = write_transcript(messages) # 先保存完整对话\n summary = summarize_history(messages) # LLM 生成摘要\n return [{\"role\": \"user\",\n \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n```\n\n**熔断器**:连续失败 3 次后停止重试,防止死循环浪费 API 调用。\n\n### 应急: reactive_compact\n\n有时候 API 还是返回 `prompt_too_long`(413),上下文增长速度快于压缩触发速度时。\n\n这时触发 **reactive_compact**:触发方式比 compact_history 更激进(API 报错后的应急手段),但压缩策略更温和,保留最近约 5 条原始消息,只总结较早历史。同样避免留下孤立 `tool_result`。\n\n```python\ndef reactive_compact(messages):\n transcript = write_transcript(messages)\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n summary = summarize_history(messages[:tail_start])\n return [{\"role\": \"user\",\n \"content\": f\"[Reactive compact]\\n\\n{summary}\"}, *messages[tail_start:]]\n```\n\nreactive compact 有重试上限(默认 1 次)。再失败就抛出异常,不无限循环。完整的错误恢复逻辑留给 s11。\n\n### 合起来跑\n\n```python\ndef agent_loop(messages):\n reactive_retries = 0\n while True:\n # 三个预处理器(0 API 调用)\n # 顺序:budget 先跑,确保大内容落盘后再做占位和裁剪\n messages[:] = tool_result_budget(messages) # L3: 大结果落盘\n messages[:] = snip_compact(messages) # L1: 裁中间\n messages[:] = micro_compact(messages) # L2: 旧结果占位\n\n # 还不够?LLM 摘要(1 API 调用)\n if estimate_token_count(messages) > THRESHOLD:\n messages[:] = compact_history(messages)\n\n try:\n response = client.messages.create(...)\n except PromptTooLongError:\n if reactive_retries < MAX_REACTIVE_RETRIES:\n messages[:] = reactive_compact(messages) # 应急\n reactive_retries += 1\n continue\n raise # 超过重试上限,抛出异常\n # ... 工具执行 ...\n\n # compact 工具:模型主动调用时触发 compact_history\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n results.append({..., \"content\": \"[Compacted. History summarized.]\"})\n messages.append({\"role\": \"user\", \"content\": results})\n break # 结束当前 turn,用压缩后的上下文开始新一轮\n```\n\n**顺序不能换。** L3(budget)在 L2(micro)前面,因为 micro 会把旧的大 tool_result 替换成一行占位符,budget 必须在那之前把完整内容落盘。这也是为什么 CC 源码把 `applyToolResultBudget` 放在最前面。\n\n---\n\n## 相对 s07 的变更\n\n| 组件 | 之前 (s07) | 之后 (s08) |\n|------|-----------|-----------|\n| 上下文管理 | 无(上下文无限膨胀) | 四层压缩管线 + 应急 |\n| 新函数 | — | snip_compact, micro_compact, tool_result_budget, compact_history, reactive_compact |\n| 工具 | bash, read, write, edit, glob, todo_write, task, load_skill (8) | 8 + compact (9) |\n| 循环 | LLM 调用 → 工具执行 | 每轮前跑三层预处理器 + 阈值触发 compact_history |\n| 设计原则 | — | 便宜的先跑,贵的后跑 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s08_context_compact/code.py\n```\n\n试试这些 prompt:\n\n1. `Read the file README.md, then read code.py, then read s01_agent_loop/README.md`(连续读多个文件,观察 L2 压缩旧结果)\n2. `Read every file in s08_context_compact/`(一次性读大量内容,观察 L3 落盘)\n3. 反复对话 20+ 轮,观察是否出现 `[auto compact]` 或 `[reactive compact]`\n\n观察重点:每次工具执行后,旧 tool_result 是否被压缩?连续对话后 token 超阈值时,是否自动触发了摘要?\n\n---\n\n## 接下来\n\n上下文压缩让 Agent 能跑很久不会崩。但每次压缩后,用户之前告诉它的偏好、约束也跟着丢了。能不能让 Agent 有选择地记住重要的事?\n\ns09 Memory → 三个子系统:选择记什么、提取关键信息、整理巩固。跨压缩、跨会话。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `compact.ts`、`autoCompact.ts`、`microCompact.ts`、`query.ts` 的分析。\n\n### 执行顺序对照\n\n教学版为了讲解方便按 L1/L2/L3/L4 编号,但实际执行顺序和编号不完全对应:\n\n| 维度 | 教学版 | Claude Code |\n|------|--------|-------------|\n| 执行顺序 | budget → snip → micro → auto | budget → snip → micro → collapse → auto(`query.ts:379-468`) |\n| snip_compact | 保留头 3 + 尾 47 | CC 仅主线程启用;实现不在开源仓库中(`HISTORY_SNIP` feature gate),但接口可见:`snipCompactIfNeeded(messages)` → `{ messages, tokensFreed, boundaryMessage? }`,还暴露了 `SnipTool` 工具让模型主动调用。教学版的 3/47 是简化参数 |\n| micro_compact | 文本占位符替换 | 两条路径:time-based 直接清内容,cached 走 API `cache_edits`(legacy path 已移除) |\n| micro_compact 白名单 | 按位置(最近 3 条) | time-based 按时间阈值触发;cached 按计数触发(`microCompact.ts`) |\n| tool_result_budget | 200KB 字符 | 200,000 字符(`toolLimits.ts:49`) |\n| compact_history 阈值 | 字符数估算 | 精确 token:`contextWindow - maxOutputTokens - 13_000` |\n| 摘要要求 | 5 类信息 | 9 个部分 + ``/`` 双标签 |\n| 压缩 prompt | 简单 prompt | 首尾双重防呆禁止调工具 |\n| PTL retry | 有(简化) | `truncateHeadForPTLRetry()` 按消息组回退(`compact.ts:243-290`) |\n| 后压缩恢复 | 无(教学版只保留摘要) | 自动重新读取最近文件、计划、agent/skill/tool 等 |\n| 熔断器 | 3 次 | 3 次(`autoCompact.ts:70`) |\n| reactive 重试 | 1 次 | CC 有更精细的分级重试 |\n\n### 执行顺序详解\n\nCC 源码 `query.ts` 中的真实顺序:\n\n1. `applyToolResultBudget`(L379):先处理大结果,确保完整内容落盘\n2. `snipCompact`(L403):裁中间消息\n3. `microcompact`(L414):旧结果占位\n4. `contextCollapse`(L441):独立的上下文管理系统(教学版无)\n5. `autoCompact`(L454):LLM 全量摘要\n\n教学版的 budget → snip → micro 顺序与此一致。教学版没有 contextCollapse 机制。\n\n### read_file 的取舍\n\n教学版的 `micro_compact` 会把旧 `tool_result` 统一替换成占位符,包括 `read_file`。这通常不影响功能正确性:如果后续还需要文件内容,模型可以重新读一次。代价是可能多一次工具调用,也可能降低 prompt cache 命中率。\n\nClaude Code 没有用教学版这种简单规则解决这个问题。它把 `Read` 也放进可 microcompact 的工具集合,但同时维护 `readFileState`:重复读取未变化文件时返回 `FILE_UNCHANGED_STUB`,compact 后再按预算恢复最近读过的文件内容(例如最多 5 个文件、每个 5K token、总预算 50K token)。这是生产级实现里的缓存和恢复机制,教学版不展开,保留“压缩旧结果,必要时重新读取”的简单 trade-off。\n\n### 完整常量参考\n\n| 常量 | 值 | 源文件 |\n|------|-----|--------|\n| `AUTOCOMPACT_BUFFER_TOKENS` | 13,000 | `autoCompact.ts:62` |\n| `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` | 3 | `autoCompact.ts:70` |\n| `MAX_OUTPUT_TOKENS_FOR_SUMMARY` | 20,000 | `autoCompact.ts:30` |\n| `POST_COMPACT_TOKEN_BUDGET` | 50,000 | `compact.ts:123` |\n| `POST_COMPACT_MAX_FILES_TO_RESTORE` | 5 | `compact.ts:122` |\n| `POST_COMPACT_MAX_TOKENS_PER_FILE` | 5,000 | `compact.ts:124` |\n| 时间 micro_compact 间隔 | 60 分钟 | `timeBasedMCConfig.ts` |\n| `MAX_COMPACT_STREAMING_RETRIES` | 2 | `compact.ts:131` |\n\n### contextCollapse 和 sessionMemoryCompact\n\nCC 源码中还有两个机制本教学版没有展开:\n\n- **contextCollapse**:独立的上下文管理系统,启用时抑制 proactive autocompact(`autoCompact.ts:215-222`),由 collapse 的 commit/blocking 流程接管上下文管理。但 manual `/compact` 和 reactive fallback 仍是独立路径,不受 contextCollapse 影响。\n- **sessionMemoryCompact**:compact_history 之前,CC 会先尝试用已有的 session memory(s09 会讲到)做轻量摘要,不调 LLM。这个机制等学完 s09 之后回头看会更清楚。\n\n### 压缩 prompt 长什么样?\n\nCC 的压缩 prompt 有两个硬性要求:\n\n1. **绝对禁止调用工具**:开头就是 `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.`,末尾还会再 REMINDER 一次\n2. **先分析再总结**:模型需要先在 `` 标签里理清思路,然后在 `` 标签里输出正式摘要。analysis 在格式化时被剥离\n\n### 教学版的简化是刻意的\n\n- micro_compact 用文本占位 → 我们没有 API 层的 `cache_edits` 权限\n- read_file 不特殊处理 → 教学版接受必要时重新读取,避免引入 readFileState 和后压缩恢复机制\n- token 用字符数估算 → 精确 tokenizer 不在教学范围内\n- 后压缩恢复省略 → 教学版只保留摘要,不自动重新附加文件\n- 两个辅助机制不展开 → 属于 10% 的细节\n\n核心设计思想,便宜的先跑贵的后跑,完整保留。\n\n
\n\n\n" + "content": "# s08: Context Compact — 上下文总会满,要有办法腾地方\n\ns01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](/zh/s09) → s10 → ... → s20 → s21\n> *\"上下文总会满, 要有办法腾地方\"* — 四层压缩策略, 便宜的先跑贵的后跑。\n>\n> **Harness 层**: 压缩 — 干净的记忆, 无限的会话。\n\n---\n\n## 问题\n\nAgent 跑着跑着,不动了。\n\n手里有 bash、有 read、有 write,能力是够的。但它读了一个 1000 行的文件(~4000 token),又读了 30 个文件,跑了 20 条命令。每条命令的输出、每个文件的内容,全都堆在 `messages` 列表里。\n\n上下文窗口是有限的。满了之后,API 直接拒绝:`prompt_too_long`。\n\n不压缩,Agent 根本没法在大项目里干活。\n\n---\n\n## 解决方案\n\n![Compact Overview](/course-assets/s08_context_compact/compact-overview.svg)\n\n保留 s07 的 hook 结构、技能加载、子 Agent 等骨架,省略部分工具细节以聚焦压缩。核心变动:每轮 LLM 调用前插入三层预处理器(0 API),token 仍超阈值时触发 LLM 摘要(1 API),API 报错时应急裁剪。\n\n核心设计:便宜的先跑,贵的后跑。\n\n> **与 s09 的边界:** s08 管理当前会话有限的上下文,压缩时允许丢失细节;s09 另建持久存储,只保留需要跨压缩、跨会话存在的信息。两章解决的是不同故障,因此不合并。\n\n---\n\n## 工作原理\n\n![四层压缩管线](/course-assets/s08_context_compact/compaction-layers.svg)\n\n### L1: snip_compact — 裁掉无关的旧对话\n\nAgent 跑了 80 轮对话,`messages` 攒了 160 条。最前面的\"帮我创建 hello.py\"和当前工作几乎无关了,但全占着位置。\n\n消息数超过 50 条 → 保留头部 3 条(初始上下文)和尾部 47 条(当前工作),中间裁掉;唯一额外边界条件是,不能把 `assistant(tool_use)` 和后面的 `user(tool_result)` 拆开:\n\n```python\ndef snip_compact(messages, max_messages=50):\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and _is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n snipped = tail_start - head_end\n placeholder = {\"role\": \"user\", \"content\": f\"[snipped {snipped} messages from conversation middle]\"}\n return messages[:head_end] + [placeholder] + messages[tail_start:]\n```\n\n裁掉的是消息本身,只是在切口处多做一步保护;剩下的消息里 `tool_result` 内容仍在累积——第 34 条消息里可能躺着 30KB 的旧文件内容。→ L2。\n\n### L2: micro_compact — 旧工具结果占位\n\n![旧结果占位](/course-assets/s08_context_compact/micro-compact.svg)\n\nAgent 连续读了 10 个文件。第 1-7 次的完整内容还躺在上下文里,早就不需要了,但占着大量空间。\n\n只保留最近 3 条 `tool_result` 的完整内容,更旧的替换为一行占位符:\n\n```python\nKEEP_RECENT_TOOL_RESULTS = 3\n\ndef micro_compact(messages):\n tool_results = collect_tool_result_blocks(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(block.get(\"content\", \"\")) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n```\n\n旧结果清掉了,但单条新结果可能就有 500KB——一个 `cat` 大文件的输出就能打满上下文。→ L3。\n\n### L3: tool_result_budget — 大结果落盘\n\n![大结果落盘](/course-assets/s08_context_compact/layer1-budget.svg)\n\n模型一次读了 5 个大文件,单条 user 消息里所有 `tool_result` 加起来 500KB。\n\n统计最后一条 user 消息里所有 `tool_result` 的总大小。超过 200KB → 按大小排序,从最大的开始落盘到 `.task_outputs/tool-results/`,上下文里只留 `` 标记 + 前 2000 字符预览。模型看到标记后知道完整内容在磁盘上,需要时可以重新读。\n\n```python\ndef tool_result_budget(messages, max_bytes=200_000):\n last = messages[-1]\n blocks = [(i, b) for i, b in enumerate(last[\"content\"])\n if b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n ranked = sorted(blocks, key=lambda p: len(str(p[1].get(\"content\", \"\"))), reverse=True)\n for idx, block in ranked:\n if total <= max_bytes:\n break\n block[\"content\"] = persist_large_output(block[\"tool_use_id\"], str(block[\"content\"]))\n total = recalculate_total(blocks)\n return messages\n```\n\n前三层都是纯文本/结构操作,0 API 调用,但也无法\"理解\"对话内容。上下文可能仍然太大。→ L4。\n\n### L4: compact_history — LLM 全量摘要\n\n![LLM 全量摘要](/course-assets/s08_context_compact/auto-compact.svg)\n\n前三层全跑完了,但在超大项目中连续工作 30 分钟后,token 仍然超过阈值。\n\n三步流程:\n\n1. **保存 transcript**:完整对话写入 `.transcripts/`,JSONL 格式。transcript 保留完整记录;消息列表只保留摘要,原始细节不再进入后续模型调用。\n2. **LLM 生成摘要**:把对话历史发给 LLM,要求保留当前目标、重要发现、已改文件、剩余工作、用户约束等关键信息。\n3. **替换消息列表**:所有旧消息被替换为一条摘要。\n\n```python\ndef compact_history(messages):\n transcript_path = write_transcript(messages) # 先保存完整对话\n summary = summarize_history(messages) # LLM 生成摘要\n return [{\"role\": \"user\",\n \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n```\n\n**熔断器**:连续失败 3 次后停止重试,防止死循环浪费 API 调用。\n\n### 应急: reactive_compact\n\n有时候 API 还是返回 `prompt_too_long`(413),上下文增长速度快于压缩触发速度时。\n\n这时触发 **reactive_compact**:触发方式比 compact_history 更激进(API 报错后的应急手段),但压缩策略更温和,保留最近约 5 条原始消息,只总结较早历史。同样避免留下孤立 `tool_result`。\n\n```python\ndef reactive_compact(messages):\n transcript = write_transcript(messages)\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n summary = summarize_history(messages[:tail_start])\n return [{\"role\": \"user\",\n \"content\": f\"[Reactive compact]\\n\\n{summary}\"}, *messages[tail_start:]]\n```\n\nreactive compact 有重试上限(默认 1 次)。再失败就抛出异常,不无限循环。完整的错误恢复逻辑留给 s11。\n\n### 合起来跑\n\n```python\ndef agent_loop(messages):\n reactive_retries = 0\n while True:\n # 三个预处理器(0 API 调用)\n # 顺序:budget 先跑,确保大内容落盘后再做占位和裁剪\n messages[:] = tool_result_budget(messages) # L3: 大结果落盘\n messages[:] = snip_compact(messages) # L1: 裁中间\n messages[:] = micro_compact(messages) # L2: 旧结果占位\n\n # 还不够?LLM 摘要(1 API 调用)\n if estimate_token_count(messages) > THRESHOLD:\n messages[:] = compact_history(messages)\n\n try:\n response = client.messages.create(...)\n except PromptTooLongError:\n if reactive_retries < MAX_REACTIVE_RETRIES:\n messages[:] = reactive_compact(messages) # 应急\n reactive_retries += 1\n continue\n raise # 超过重试上限,抛出异常\n # ... 工具执行 ...\n\n # compact 工具:模型主动调用时触发 compact_history\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n results.append({..., \"content\": \"[Compacted. History summarized.]\"})\n messages.append({\"role\": \"user\", \"content\": results})\n break # 结束当前 turn,用压缩后的上下文开始新一轮\n```\n\n**顺序不能换。** L3(budget)在 L2(micro)前面,因为 micro 会把旧的大 `tool_result` 替换成一行占位符,budget 必须在那之前保存完整内容。\n\n---\n\n## 相对 s07 的变更\n\n| 组件 | 之前 (s07) | 之后 (s08) |\n|------|-----------|-----------|\n| 上下文管理 | 无(上下文无限膨胀) | 四层压缩管线 + 应急 |\n| 新函数 | — | snip_compact, micro_compact, tool_result_budget, compact_history, reactive_compact |\n| 工具 | bash, read, write, edit, glob, todo_write, task, load_skill (8) | 8 + compact (9) |\n| 循环 | LLM 调用 → 工具执行 | 每轮前跑三层预处理器 + 阈值触发 compact_history |\n| 设计原则 | — | 便宜的先跑,贵的后跑 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s08_context_compact/code.py\n```\n\n试试这些 prompt:\n\n1. `Read the file README.md, then read code.py, then read s01_agent_loop/README.md`(连续读多个文件,观察 L2 压缩旧结果)\n2. `Read every file in s08_context_compact/`(一次性读大量内容,观察 L3 落盘)\n3. 反复对话 20+ 轮,观察是否出现 `[auto compact]` 或 `[reactive compact]`\n\n观察重点:每次工具执行后,旧 tool_result 是否被压缩?连续对话后 token 超阈值时,是否自动触发了摘要?\n\n---\n\n## 接下来\n\n上下文压缩让 Agent 能跑很久不会崩。但每次压缩后,用户之前告诉它的偏好、约束也跟着丢了。能不能让 Agent 有选择地记住重要的事?\n\ns09 Memory → 三个子系统:选择记什么、提取关键信息、整理巩固。跨压缩、跨会话。\n\n\n\n" }, { "version": "s08", "locale": "ja", "title": "s08: Context Compact — コンテキストはいつか満杯になる、場所を空ける方法が必要", - "content": "# s08: Context Compact — コンテキストはいつか満杯になる、場所を空ける方法が必要\n\ns01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](/ja/s09) → s10 → ... → s20 → s21 → s22\n> *\"Context will fill up — have a way to make room\"* — 4層圧縮戦略、安価なものを先に、高価なものを後に実行。\n>\n> **Harness レイヤー**: 圧縮 — クリーンな記憶、無限のセッション。\n\n---\n\n## 課題\n\nAgent が動いている途中で、止まってしまう。\n\nbash、read、write は揃っており、能力は十分。しかし 1000 行のファイル(~4000 token)を読み、さらに 30 のファイルを読み、20 のコマンドを実行したとします。各コマンドの出力、各ファイルの内容がすべて `messages` リストに蓄積されます。\n\nコンテキストウィンドウには上限があります。満杯になると、API は即座に拒否します:`prompt_too_long`。\n\n圧縮しなければ、Agent は大規模プロジェクトではまともに動けません。\n\n---\n\n## ソリューション\n\n![Compact Overview](/course-assets/s08_context_compact/compact-overview.ja.svg)\n\ns07 のフック構造、スキルロード、サブ Agent の骨格を維持し、圧縮に焦点を当てるため一部のツールは省略。コアの変更点:各 LLM 呼び出し前に 3 層のプリプロセッサ(0 API)を挿入し、token が閾値を超えた場合は LLM 要約(1 API)をトリガー、API エラー時には緊急トリムを実行。\n\nコア設計:安価なものを先に、高価なものを後に。\n\n> **s09 との境界:** s08 は現在のセッションの有限なコンテキストを管理し、圧縮では詳細を失うことがある。s09 は圧縮後や将来のセッションにも残す情報だけを別の永続ストアに保存する。異なる障害を解くため、別のセッションとして扱う。\n\n---\n\n## 仕組み\n\n![4層圧縮パイプライン](/course-assets/s08_context_compact/compaction-layers.ja.svg)\n\n### L1: snip_compact — 無関係な古い会話を切り捨て\n\nAgent が 80 ラウンドの会話を実行し、`messages` が 160 件まで溜まった。先頭の「hello.py を作って」は現在の作業とほぼ無関係だが、スペースを占有し続けている。\n\nメッセージ数が 50 を超えた場合 → 先頭 3 件(初期コンテキスト)と末尾 47 件(現在の作業)を保持して中間を切り詰める。ただし切れ目だけは調整し、`assistant(tool_use)` と後続の `user(tool_result)` を分断しない:\n\n```python\ndef snip_compact(messages, max_messages=50):\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and _is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n snipped = tail_start - head_end\n placeholder = {\"role\": \"user\", \"content\": f\"[snipped {snipped} messages from conversation middle]\"}\n return messages[:head_end] + [placeholder] + messages[tail_start:]\n```\n\n切り捨て自体は単純なままで、境界だけを保護する。残ったメッセージ内の `tool_result` 内容はまだ蓄積され続けている。34 番目のメッセージに 30KB の古いファイル内容が残っているかもしれない。→ L2。\n\n### L2: micro_compact — 古いツール結果をプレースホルダに置換\n\n![古い結果のプレースホルダ](/course-assets/s08_context_compact/micro-compact.ja.svg)\n\nAgent が連続して 10 個のファイルを読んだ。1〜7 回目の完全な内容はまだコンテキストに残っており、もう不要だが、大量のスペースを占有している。\n\n直近 3 件の `tool_result` の完全な内容のみを保持し、それより古いものは 1 行のプレースホルダに置換:\n\n```python\nKEEP_RECENT_TOOL_RESULTS = 3\n\ndef micro_compact(messages):\n tool_results = collect_tool_result_blocks(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(block.get(\"content\", \"\")) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n```\n\n古い結果はクリーンアップされたが、1 件の新しい結果だけで 500KB の可能性がある。大きなファイルを `cat` するだけでコンテキストがいっぱいになる。→ L3。\n\n### L3: tool_result_budget — 大きな結果をディスクに退避\n\n![大きな結果のディスク退避](/course-assets/s08_context_compact/layer1-budget.ja.svg)\n\nモデルが一度に 5 つの大きなファイルを読み、1 つの user メッセージ内の全 `tool_result` の合計が 500KB に達した。\n\n最後の user メッセージ内のすべての `tool_result` の合計サイズを集計。200KB を超えた場合 → サイズ順にソートし、最大のものから順に `.task_outputs/tool-results/` に退避。コンテキストには `` マーカー + 先頭 2000 文字のプレビューのみを残す。モデルはマーカーを見て完全な内容がディスク上にあることを認識し、必要に応じて再読み込みできる。\n\n```python\ndef tool_result_budget(messages, max_bytes=200_000):\n last = messages[-1]\n blocks = [(i, b) for i, b in enumerate(last[\"content\"])\n if b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n ranked = sorted(blocks, key=lambda p: len(str(p[1].get(\"content\", \"\"))), reverse=True)\n for idx, block in ranked:\n if total <= max_bytes:\n break\n block[\"content\"] = persist_large_output(block[\"tool_use_id\"], str(block[\"content\"]))\n total = recalculate_total(blocks)\n return messages\n```\n\n最初の 3 層はすべて純粋なテキスト/構造操作(0 API 呼び出し)だが、会話内容を「理解」することはできない。コンテキストがまだ大きすぎる可能性がある。→ L4。\n\n### L4: compact_history — LLM 全量要約\n\n![LLM 全量要約](/course-assets/s08_context_compact/auto-compact.ja.svg)\n\n最初の 3 層がすべて実行されたが、超大規模プロジェクトで 30 分間連続作業すると、token がまだ閾値を超えている。\n\n3 ステップのフロー:\n\n1. **transcript を保存**:完全な会話を `.transcripts/` に JSONL 形式で書き出す。transcript は回復可能な記録として保存されるが、モデルのアクティブなコンテキストには要約しか残らない。モデルの現在の推論にとって、詳細はすでにコンテキストにない。教学コードは transcript 検索ツールを提供しない。\n2. **LLM で要約を生成**:会話履歴を LLM に送り、現在の目標、重要な発見、変更済みファイル、残りの作業、ユーザーの制約などの重要な情報を保持するよう指示。\n3. **メッセージリストを置換**:すべての古いメッセージが 1 件の要約に置き換えられる。教学版は要約のみを保持する。実際の Claude Code は compact 後に直近のファイル、計画、agent/skill/tool などのコンテキストを再付加する。\n\n```python\ndef compact_history(messages):\n transcript_path = write_transcript(messages) # 先に完全な会話を保存\n summary = summarize_history(messages) # LLM で要約を生成\n return [{\"role\": \"user\",\n \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n```\n\n**サーキットブレーカー**:連続 3 回失敗したらリトライを停止し、無限ループによる API 呼び出しの浪費を防止。\n\n### 緊急: reactive_compact\n\nAPI がまだ `prompt_too_long`(413)を返すことがある。コンテキストの増加速度が圧縮のトリガー速度を上回る場合。\n\nこの時 **reactive_compact** がトリガーされる。トリガー方式は compact_history より積極的(413 エラー後の緊急対応)だが、圧縮方針はより温和で、末尾約 5 件のメッセージを保持し、早期の履歴だけを要約する。孤立した `tool_result` を残さないよう配慮する。\n\n```python\ndef reactive_compact(messages):\n transcript = write_transcript(messages)\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n summary = summarize_history(messages[:tail_start])\n return [{\"role\": \"user\",\n \"content\": f\"[Reactive compact]\\n\\n{summary}\"}, *messages[tail_start:]]\n```\n\nreactive compact にはリトライ上限がある(デフォルト 1 回)。さらに失敗した場合は例外をスローし、無限ループしない。完全なエラー回復ロジックは s11 に委ねる。\n\n### 合わせて実行\n\n```python\ndef agent_loop(messages):\n reactive_retries = 0\n while True:\n # 3 つのプリプロセッサ(0 API 呼び出し)\n # 順序:budget を先に実行し、大きな内容をプレースホルダ化する前に退避\n messages[:] = tool_result_budget(messages) # L3: 大きな結果を退避\n messages[:] = snip_compact(messages) # L1: 中間を切り捨て\n messages[:] = micro_compact(messages) # L2: 古い結果をプレースホルダに\n\n # まだ足りない?LLM 要約(1 API 呼び出し)\n if estimate_token_count(messages) > THRESHOLD:\n messages[:] = compact_history(messages)\n\n try:\n response = client.messages.create(...)\n except PromptTooLongError:\n if reactive_retries < MAX_REACTIVE_RETRIES:\n messages[:] = reactive_compact(messages) # 緊急対応\n reactive_retries += 1\n continue\n raise # リトライ上限超過、例外をスロー\n # ... ツール実行 ...\n\n # compact ツール:モデルが能動的に呼び出した場合、compact_history をトリガー\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n results.append({..., \"content\": \"[Compacted. History summarized.]\"})\n messages.append({\"role\": \"user\", \"content\": results})\n break # 現在のターンを終了し、圧縮後のコンテキストで新しく開始\n```\n\n**順序は変えられない。** L3(budget)が L2(micro)の前に実行される理由:micro は古い大きな tool_result を 1 行のプレースホルダに置換するため、budget はその前に完全な内容を退避させる必要がある。CC ソースが `applyToolResultBudget` を最初に配置する理由も同じ。\n\n---\n\n## s07 からの変更点\n\n| コンポーネント | 変更前 (s07) | 変更後 (s08) |\n|------|-----------|-----------|\n| コンテキスト管理 | なし(コンテキストが無限に膨張) | 4 層圧縮パイプライン + 緊急対応 |\n| 新規関数 | — | snip_compact, micro_compact, tool_result_budget, compact_history, reactive_compact |\n| ツール | bash, read_file, write_file, edit_file, glob, todo_write, task, load_skill (8) | 8 + compact (9) |\n| ループ | LLM 呼び出し → ツール実行 | 各ラウンド前に 3 層プリプロセッサを実行 + 閾値で compact_history をトリガー |\n| 設計原則 | — | 安価なものを先に、高価なものを後に |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s08_context_compact/code.py\n```\n\n以下のプロンプトを試してみてください:\n\n1. `Read the file README.md, then read code.py, then read s01_agent_loop/README.md`(連続して複数のファイルを読み、L2 の古い結果圧縮を観察)\n2. `Read every file in s08_context_compact/`(一度に大量の内容を読み込み、L3 のディスク退避を観察)\n3. 20+ ラウンドの対話を繰り返し、`[auto compact]` または `[reactive compact]` が表示されるか観察\n\n観察のポイント:ツール実行のたびに、古い tool_result は圧縮されているか?連続対話で token が閾値を超えたとき、要約が自動的にトリガーされたか?\n\n---\n\n## 次へ\n\nコンテキスト圧縮により、Agent は長時間クラッシュせずに動けるようになった。しかし、圧縮のたびにユーザーが以前に伝えた偏好や制約も一緒に失われてしまう。Agent が重要なことを選択的に記憶できるようにできないか?\n\ns09 Memory → 3 つのサブシステム:何を記憶するかの選択、重要情報の抽出、整理と統合。圧縮を越え、セッションを越えて。\n\n
\nCC ソースコードの詳細\n\n> 以下は CC ソースコード `compact.ts`、`autoCompact.ts`、`microCompact.ts`、`query.ts` の分析に基づく。\n\n### 実行順序の対応\n\n教学版は説明の便宜上 L1/L2/L3/L4 と番号を振っているが、実際の実行順序は番号と完全には一致しない:\n\n| 項目 | 教学版 | Claude Code |\n|------|--------|-------------|\n| 実行順序 | budget → snip → micro → auto | budget → snip → micro → collapse → auto(`query.ts:379-468`) |\n| snip_compact | 先頭 3 + 末尾 47 を保持 | CC はメインスレッドのみ有効;実装はオープンソースリポジトリにない(`HISTORY_SNIP` feature gate)、インターフェースは確認可能:`snipCompactIfNeeded(messages)` → `{ messages, tokensFreed, boundaryMessage? }`、`SnipTool` もモデルが能動的に呼び出し可能。教学版の 3/47 は簡略パラメータ |\n| micro_compact | テキストプレースホルダで置換 | 2 つのパス:time-based は直接内容をクリア、cached は API の `cache_edits` を使用(legacy パスは削除済み) |\n| micro_compact ホワイトリスト | 位置による(直近 3 件) | time-based は時間閾値でトリガー、cached はカウントでトリガー(`microCompact.ts`) |\n| tool_result_budget | 200KB 文字 | 200,000 文字(`toolLimits.ts:49`) |\n| compact_history 閾値 | 文字数で推定 | 精密な token 数:`contextWindow - maxOutputTokens - 13_000` |\n| 要約の要求 | 5 種類の情報 | 9 つのセクション + ``/`` デュアルタグ |\n| 圧縮プロンプト | シンプルなプロンプト | 先頭と末尾に二重の安全ガードでツール呼び出しを禁止 |\n| PTL retry | あり(簡略版) | `truncateHeadForPTLRetry()` がメッセージグループ単位でロールバック(`compact.ts:243-290`) |\n| 圧縮後のリカバリ | なし(教学版は要約のみ保持) | 直近のファイル、計画、agent/skill/tool などの自動再付加 |\n| サーキットブレーカー | 3 回 | 3 回(`autoCompact.ts:70`) |\n| reactive リトライ | 1 回 | CC にはより精緻な段階別リトライがある |\n\n### 実行順序の詳細\n\nCC ソース `query.ts` での実際の順序:\n\n1. `applyToolResultBudget`(L379):まず大きな結果を処理し、完全な内容を退避\n2. `snipCompact`(L403):中間メッセージを切り捨て\n3. `microcompact`(L414):古い結果のプレースホルダ化\n4. `contextCollapse`(L441):独立したコンテキスト管理システム(教学版にはなし)\n5. `autoCompact`(L454):LLM 全量要約\n\n教学版の budget → snip → micro の順序はこれと一致する。教学版には contextCollapse メカニズムがない。\n\n### read_file のトレードオフ\n\n教学版の `micro_compact` は、古い `tool_result` を一律にプレースホルダへ置き換える。`read_file` も例外ではない。これは通常、機能的な正しさには影響しない。後でファイル内容が必要になれば、モデルはもう一度そのファイルを読めばよい。代償は、追加のツール呼び出しが発生し得ることと、prompt cache のヒット率が下がり得ること。\n\nClaude Code は、この問題を教学版のような単純なルールでは処理していない。`Read` も microcompact 可能なツール集合に入れる一方で、別途 `readFileState` を維持している。変更されていないファイルの再読込では `FILE_UNCHANGED_STUB` を返し、compact 後には予算内で直近に読んだファイル内容を復元する(例:最大 5 ファイル、1 ファイル 5K token、合計 50K token)。これは本番実装向けのキャッシュと復元メカニズムである。教学版ではそこまで展開せず、「古い結果を圧縮し、必要なら再読込する」という単純な trade-off を残している。\n\n### 完全な定数リファレンス\n\n| 定数 | 値 | ソースファイル |\n|------|-----|--------|\n| `AUTOCOMPACT_BUFFER_TOKENS` | 13,000 | `autoCompact.ts:62` |\n| `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` | 3 | `autoCompact.ts:70` |\n| `MAX_OUTPUT_TOKENS_FOR_SUMMARY` | 20,000 | `autoCompact.ts:30` |\n| `POST_COMPACT_TOKEN_BUDGET` | 50,000 | `compact.ts:123` |\n| `POST_COMPACT_MAX_FILES_TO_RESTORE` | 5 | `compact.ts:122` |\n| `POST_COMPACT_MAX_TOKENS_PER_FILE` | 5,000 | `compact.ts:124` |\n| 時間ベース micro_compact 間隔 | 60 分 | `timeBasedMCConfig.ts` |\n| `MAX_COMPACT_STREAMING_RETRIES` | 2 | `compact.ts:131` |\n\n### contextCollapse と sessionMemoryCompact\n\nCC ソースコードには、この教学版では展開していない 2 つのメカニズムが存在する:\n\n- **contextCollapse**:独立したコンテキスト管理システム。有効時には proactive autocompact を抑制し(`autoCompact.ts:215-222`)、collapse の commit/blocking フローがコンテキスト管理を引き継ぐ。ただし manual `/compact` と reactive fallback は独立パスのままで、contextCollapse の影響を受けない。\n- **sessionMemoryCompact**:compact_history の前に、CC は既存の session memory(s09 で解説)を使った軽量要約を先に試みる。LLM を呼び出さない。このメカニズムは s09 を学んだ後に振り返るとより理解しやすい。\n\n### 圧縮プロンプトの中身\n\nCC の圧縮プロンプトには 2 つの厳格な要件がある:\n\n1. **ツール呼び出しの絶対禁止**:冒頭が `CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.` で、末尾にも再度 REMINDER がある\n2. **先に分析してから要約**:モデルはまず `` タグで思考を整理し、その後 `` タグで正式な要約を出力する。analysis はフォーマット時に除去される\n\n### 教学版の簡略化は意図的\n\n- micro_compact でテキストプレースホルダを使用 → API 層の `cache_edits` 権限がないため\n- read_file は特別扱いしない → 教学版では必要時の再読込を受け入れ、readFileState と圧縮後復元の仕組みを導入しない\n- token を文字数で推定 → 精密な tokenizer は教学の対象外\n- 圧縮後のリカバリを省略 → 教学版は要約のみを保持し、ファイルの自動再付加を行わない\n- 2 つの補助メカニズムを展開しない → 10% の細部に属する\n\nコア設計思想、安価なものを先に高価なものを後に、は完全に保持されている。\n\n
\n\n\n" + "content": "# s08: Context Compact — コンテキストはいつか満杯になる、場所を空ける方法が必要\n\ns01 → s02 → s03 → s04 → s05 → s06 → s07 → `s08` → [s09](/ja/s09) → s10 → ... → s20 → s21\n> *\"Context will fill up — have a way to make room\"* — 4層圧縮戦略、安価なものを先に、高価なものを後に実行。\n>\n> **Harness レイヤー**: 圧縮 — クリーンな記憶、無限のセッション。\n\n---\n\n## 課題\n\nAgent が動いている途中で、止まってしまう。\n\nbash、read、write は揃っており、能力は十分。しかし 1000 行のファイル(~4000 token)を読み、さらに 30 のファイルを読み、20 のコマンドを実行したとします。各コマンドの出力、各ファイルの内容がすべて `messages` リストに蓄積されます。\n\nコンテキストウィンドウには上限があります。満杯になると、API は即座に拒否します:`prompt_too_long`。\n\n圧縮しなければ、Agent は大規模プロジェクトではまともに動けません。\n\n---\n\n## ソリューション\n\n![Compact Overview](/course-assets/s08_context_compact/compact-overview.ja.svg)\n\ns07 のフック構造、スキルロード、サブ Agent の骨格を維持し、圧縮に焦点を当てるため一部のツールは省略。コアの変更点:各 LLM 呼び出し前に 3 層のプリプロセッサ(0 API)を挿入し、token が閾値を超えた場合は LLM 要約(1 API)をトリガー、API エラー時には緊急トリムを実行。\n\nコア設計:安価なものを先に、高価なものを後に。\n\n> **s09 との境界:** s08 は現在のセッションの有限なコンテキストを管理し、圧縮では詳細を失うことがある。s09 は圧縮後や将来のセッションにも残す情報だけを別の永続ストアに保存する。異なる障害を解くため、別のセッションとして扱う。\n\n---\n\n## 仕組み\n\n![4層圧縮パイプライン](/course-assets/s08_context_compact/compaction-layers.ja.svg)\n\n### L1: snip_compact — 無関係な古い会話を切り捨て\n\nAgent が 80 ラウンドの会話を実行し、`messages` が 160 件まで溜まった。先頭の「hello.py を作って」は現在の作業とほぼ無関係だが、スペースを占有し続けている。\n\nメッセージ数が 50 を超えた場合 → 先頭 3 件(初期コンテキスト)と末尾 47 件(現在の作業)を保持して中間を切り詰める。ただし切れ目だけは調整し、`assistant(tool_use)` と後続の `user(tool_result)` を分断しない:\n\n```python\ndef snip_compact(messages, max_messages=50):\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and _message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and _is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n snipped = tail_start - head_end\n placeholder = {\"role\": \"user\", \"content\": f\"[snipped {snipped} messages from conversation middle]\"}\n return messages[:head_end] + [placeholder] + messages[tail_start:]\n```\n\n切り捨て自体は単純なままで、境界だけを保護する。残ったメッセージ内の `tool_result` 内容はまだ蓄積され続けている。34 番目のメッセージに 30KB の古いファイル内容が残っているかもしれない。→ L2。\n\n### L2: micro_compact — 古いツール結果をプレースホルダに置換\n\n![古い結果のプレースホルダ](/course-assets/s08_context_compact/micro-compact.ja.svg)\n\nAgent が連続して 10 個のファイルを読んだ。1〜7 回目の完全な内容はまだコンテキストに残っており、もう不要だが、大量のスペースを占有している。\n\n直近 3 件の `tool_result` の完全な内容のみを保持し、それより古いものは 1 行のプレースホルダに置換:\n\n```python\nKEEP_RECENT_TOOL_RESULTS = 3\n\ndef micro_compact(messages):\n tool_results = collect_tool_result_blocks(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(block.get(\"content\", \"\")) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n```\n\n古い結果はクリーンアップされたが、1 件の新しい結果だけで 500KB の可能性がある。大きなファイルを `cat` するだけでコンテキストがいっぱいになる。→ L3。\n\n### L3: tool_result_budget — 大きな結果をディスクに退避\n\n![大きな結果のディスク退避](/course-assets/s08_context_compact/layer1-budget.ja.svg)\n\nモデルが一度に 5 つの大きなファイルを読み、1 つの user メッセージ内の全 `tool_result` の合計が 500KB に達した。\n\n最後の user メッセージ内のすべての `tool_result` の合計サイズを集計。200KB を超えた場合 → サイズ順にソートし、最大のものから順に `.task_outputs/tool-results/` に退避。コンテキストには `` マーカー + 先頭 2000 文字のプレビューのみを残す。モデルはマーカーを見て完全な内容がディスク上にあることを認識し、必要に応じて再読み込みできる。\n\n```python\ndef tool_result_budget(messages, max_bytes=200_000):\n last = messages[-1]\n blocks = [(i, b) for i, b in enumerate(last[\"content\"])\n if b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n ranked = sorted(blocks, key=lambda p: len(str(p[1].get(\"content\", \"\"))), reverse=True)\n for idx, block in ranked:\n if total <= max_bytes:\n break\n block[\"content\"] = persist_large_output(block[\"tool_use_id\"], str(block[\"content\"]))\n total = recalculate_total(blocks)\n return messages\n```\n\n最初の 3 層はすべて純粋なテキスト/構造操作(0 API 呼び出し)だが、会話内容を「理解」することはできない。コンテキストがまだ大きすぎる可能性がある。→ L4。\n\n### L4: compact_history — LLM 全量要約\n\n![LLM 全量要約](/course-assets/s08_context_compact/auto-compact.ja.svg)\n\n最初の 3 層がすべて実行されたが、超大規模プロジェクトで 30 分間連続作業すると、token がまだ閾値を超えている。\n\n3 ステップのフロー:\n\n1. **transcript を保存**:完全な会話を `.transcripts/` に JSONL 形式で書き出す。transcript は完全な記録を保持する。メッセージリストには要約だけが残り、元の詳細は以降のモデル呼び出しに入らない。\n2. **LLM で要約を生成**:会話履歴を LLM に送り、現在の目標、重要な発見、変更済みファイル、残りの作業、ユーザーの制約などの重要な情報を保持するよう指示。\n3. **メッセージリストを置換**:すべての古いメッセージを 1 件の要約に置き換える。\n\n```python\ndef compact_history(messages):\n transcript_path = write_transcript(messages) # 先に完全な会話を保存\n summary = summarize_history(messages) # LLM で要約を生成\n return [{\"role\": \"user\",\n \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n```\n\n**サーキットブレーカー**:連続 3 回失敗したらリトライを停止し、無限ループによる API 呼び出しの浪費を防止。\n\n### 緊急: reactive_compact\n\nAPI がまだ `prompt_too_long`(413)を返すことがある。コンテキストの増加速度が圧縮のトリガー速度を上回る場合。\n\nこの時 **reactive_compact** がトリガーされる。トリガー方式は compact_history より積極的(413 エラー後の緊急対応)だが、圧縮方針はより温和で、末尾約 5 件のメッセージを保持し、早期の履歴だけを要約する。孤立した `tool_result` を残さないよう配慮する。\n\n```python\ndef reactive_compact(messages):\n transcript = write_transcript(messages)\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and _is_tool_result_message(messages[tail_start])\n and _message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n summary = summarize_history(messages[:tail_start])\n return [{\"role\": \"user\",\n \"content\": f\"[Reactive compact]\\n\\n{summary}\"}, *messages[tail_start:]]\n```\n\nreactive compact にはリトライ上限がある(デフォルト 1 回)。さらに失敗した場合は例外をスローし、無限ループしない。完全なエラー回復ロジックは s11 に委ねる。\n\n### 合わせて実行\n\n```python\ndef agent_loop(messages):\n reactive_retries = 0\n while True:\n # 3 つのプリプロセッサ(0 API 呼び出し)\n # 順序:budget を先に実行し、大きな内容をプレースホルダ化する前に退避\n messages[:] = tool_result_budget(messages) # L3: 大きな結果を退避\n messages[:] = snip_compact(messages) # L1: 中間を切り捨て\n messages[:] = micro_compact(messages) # L2: 古い結果をプレースホルダに\n\n # まだ足りない?LLM 要約(1 API 呼び出し)\n if estimate_token_count(messages) > THRESHOLD:\n messages[:] = compact_history(messages)\n\n try:\n response = client.messages.create(...)\n except PromptTooLongError:\n if reactive_retries < MAX_REACTIVE_RETRIES:\n messages[:] = reactive_compact(messages) # 緊急対応\n reactive_retries += 1\n continue\n raise # リトライ上限超過、例外をスロー\n # ... ツール実行 ...\n\n # compact ツール:モデルが能動的に呼び出した場合、compact_history をトリガー\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n results.append({..., \"content\": \"[Compacted. History summarized.]\"})\n messages.append({\"role\": \"user\", \"content\": results})\n break # 現在のターンを終了し、圧縮後のコンテキストで新しく開始\n```\n\n**順序は変えられない。** L3(budget)は L2(micro)より先に実行する。micro が古い大きな `tool_result` を 1 行のプレースホルダに置き換える前に、budget が完全な内容を保存する必要があるためだ。\n\n---\n\n## s07 からの変更点\n\n| コンポーネント | 変更前 (s07) | 変更後 (s08) |\n|------|-----------|-----------|\n| コンテキスト管理 | なし(コンテキストが無限に膨張) | 4 層圧縮パイプライン + 緊急対応 |\n| 新規関数 | — | snip_compact, micro_compact, tool_result_budget, compact_history, reactive_compact |\n| ツール | bash, read_file, write_file, edit_file, glob, todo_write, task, load_skill (8) | 8 + compact (9) |\n| ループ | LLM 呼び出し → ツール実行 | 各ラウンド前に 3 層プリプロセッサを実行 + 閾値で compact_history をトリガー |\n| 設計原則 | — | 安価なものを先に、高価なものを後に |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s08_context_compact/code.py\n```\n\n以下のプロンプトを試してみてください:\n\n1. `Read the file README.md, then read code.py, then read s01_agent_loop/README.md`(連続して複数のファイルを読み、L2 の古い結果圧縮を観察)\n2. `Read every file in s08_context_compact/`(一度に大量の内容を読み込み、L3 のディスク退避を観察)\n3. 20+ ラウンドの対話を繰り返し、`[auto compact]` または `[reactive compact]` が表示されるか観察\n\n観察のポイント:ツール実行のたびに、古い tool_result は圧縮されているか?連続対話で token が閾値を超えたとき、要約が自動的にトリガーされたか?\n\n---\n\n## 次へ\n\nコンテキスト圧縮により、Agent は長時間クラッシュせずに動けるようになった。しかし、圧縮のたびにユーザーが以前に伝えた偏好や制約も一緒に失われてしまう。Agent が重要なことを選択的に記憶できるようにできないか?\n\ns09 Memory → 3 つのサブシステム:何を記憶するかの選択、重要情報の抽出、整理と統合。圧縮を越え、セッションを越えて。\n\n\n\n" }, { "version": "s09", "locale": "en", "title": "s09: Memory — Compression Loses Details, Keep a Layer That Doesn't", - "content": "# s09: Memory — Compression Loses Details, Keep a Layer That Doesn't\n\ns01 → ... → s07 → s08 → `s09` → [s10](/en/s10) → s11 → ... → s20 → s21 → s22\n> *\"Compression loses details, keep a layer that doesn't\"* — File store + index + on-demand loading, across compactions, across sessions.\n>\n> **Harness Layer**: Memory — knowledge that survives compaction and sessions.\n\n---\n\n## The Problem\n\ns08's autoCompact preserves current goals, remaining work, and user constraints in the summary, but details get lost: \"use tabs not spaces\" might get simplified to \"user has code style preferences\". And when you start a new session, even the summary is gone.\n\nLLMs have no persistent state; all information lives in the context window. When context fills up, it gets compressed, and compression is lossy. What's needed is a storage layer that doesn't participate in compression and persists across sessions.\n\n---\n\n## The Solution\n\n![Memory Overview](/course-assets/s09_memory/memory-overview.en.svg)\n\nThe s08 compression pipeline is preserved, focusing on memory. Storage uses the filesystem: a `.memory/` directory where each memory is a `.md` file with YAML frontmatter (`name` / `description` / `type`). When files accumulate, an index is needed: `MEMORY.md` holds one link per line and gets injected into the SYSTEM.\n\nKey design: the index stays in SYSTEM prompt (cacheable by prompt cache), file content is injected on demand (matched by filename/description to the current conversation, without breaking the cache). Writing has two paths: the user explicitly says \"remember\", or extraction runs in the background after each turn. When files accumulate, periodic consolidation deduplicates.\n\n> **Boundary with s08:** compaction still owns the current transcript and token budget. Memory does not replace that pipeline; it selectively persists facts outside the transcript and recalls them later.\n\nFour memory types, each answering a different question:\n\n| Type | Answers | Example |\n|------|---------|---------|\n| user | Who you are | \"Use tabs not spaces\" |\n| feedback | How to work | \"Don't mock the database\" |\n| project | What's happening | \"Auth rewrite is compliance-driven\" |\n| reference | Where to find things | \"Pipeline bugs are in Linear INGEST\" |\n\n---\n\n## How It Works\n\n![Memory Subsystems](/course-assets/s09_memory/memory-subsystems.en.svg)\n\n### Storage: Markdown Files + Index\n\nEach memory is a `.md` file with YAML frontmatter for metadata:\n\n```markdown\n---\nname: user-preference-tabs\ndescription: User prefers tabs for indentation\ntype: user\n---\n\nUser prefers using tabs, not spaces, for indentation.\n**Why:** Consistency with existing codebase conventions.\n**How to apply:** Always use tabs when writing or editing files.\n```\n\n`MEMORY.md` is the index, one link per line:\n\n```markdown\n- [user-preference-tabs](user-preference-tabs.md) — User prefers tabs for indentation\n```\n\nWriting a new memory automatically rebuilds the index:\n\n```python\ndef write_memory_file(name, mem_type, description, body):\n slug = name.lower().replace(\" \", \"-\")\n filepath = MEMORY_DIR / f\"{slug}.md\"\n filepath.write_text(\n f\"---\\nname: {name}\\ndescription: {description}\\ntype: {mem_type}\\n---\\n\\n{body}\\n\"\n )\n _rebuild_index()\n```\n\n### Loading: Two Paths\n\n**Path 1: Index in SYSTEM.** `build_system()` reads `MEMORY.md` once at the start of each user request and injects the memory catalog into the SYSTEM prompt. Memory extraction and consolidation run only when the turn ends, so SYSTEM does not need to be rebuilt repeatedly within the same user request.\n\n**Path 2: Relevant memories on demand.** At the start of each user request, `load_memories()` sends the recent conversation and the memory catalog (name + description) to the LLM as a lightweight side-query, selects relevant filenames, then reads and injects their contents. Capped at 5 to control cost.\n\n```python\ndef select_relevant_memories(messages, max_items=5):\n files = list_memory_files()\n if not files:\n return []\n\n # Build catalog: \"0: user-preference-tabs — User prefers tabs...\"\n catalog = \"\\n\".join(f\"{i}: {f['name']} — {f['description']}\" for i, f in enumerate(files))\n\n response = client.messages.create(model=MODEL, messages=[{\"role\": \"user\",\n \"content\": f\"Select relevant memory indices. Return JSON array.\\n\\n\"\n f\"Recent conversation:\\n{recent}\\n\\nMemory catalog:\\n{catalog}\"}],\n max_tokens=200)\n indices = json.loads(re.search(r'\\[.*?\\]', response.content[0].text).group())\n return [files[i][\"filename\"] for i in indices if 0 <= i < len(files)]\n```\n\nIf the side-query fails (API error, JSON parse failure), it falls back to keyword matching on name + description.\n\n### Writing: Extraction After Each Turn\n\nUsers don't always say \"remember this\". Preferences are usually scattered across normal dialogue: \"tabs are better than spaces\", \"let's use single quotes from now on\".\n\n`extract_memories()` runs when each turn ends, triggered when the model stops without a tool_use (indicating the conversation has reached a natural break):\n\n```python\n# In agent_loop:\nif response.stop_reason != \"tool_use\":\n extract_memories(messages) # Extract new memories from recent dialogue\n consolidate_memories() # Check if consolidation is needed\n return\n```\n\nBefore extraction, existing memories are checked to avoid duplicates. The extraction prompt asks the LLM to return a JSON array of `{name, type, description, body}`, writing files only when genuinely new information is found.\n\n```python\ndef extract_memories(messages):\n dialogue = format_recent_messages(messages[-10:])\n existing = \"\\n\".join(f\"- {m['name']}: {m['description']}\" for m in list_memory_files())\n\n prompt = (\n \"Extract user preferences, constraints, or project facts.\\n\"\n \"Return JSON array: [{name, type, description, body}].\\n\"\n \"If nothing new or already covered, return [].\\n\\n\"\n f\"Existing memories:\\n{existing}\\n\\nDialogue:\\n{dialogue[:4000]}\"\n )\n # ... parse response, write files ...\n```\n\n### Consolidation: Low-Frequency Deduplication\n\nMemory files accumulate. `consolidate_memories()` triggers when the file count reaches a threshold (default 10), asking the LLM to deduplicate, merge contradictions, and prune stale memories:\n\n```python\nCONSOLIDATE_THRESHOLD = 10\n\ndef consolidate_memories():\n files = list_memory_files()\n if len(files) < CONSOLIDATE_THRESHOLD:\n return # Too few, not worth consolidating\n # Send all memories to LLM, get back deduplicated list\n # Replace all files with consolidated results\n```\n\nCC calls this process **Dream**, with four gates in practice: time interval, scan throttle, session count, file lock. The teaching version simplifies to a file-count threshold.\n\n### What Memory Stores\n\nMemory stores information that remains useful across sessions: user preferences, recurring feedback, project background, common entry points, and investigation clues. It focuses on \"what will be useful later\" and brings that information back through an index plus on-demand loading.\n\nSession memory focuses on continuity inside one session: what context should survive after compaction. The two work together: Memory handles long-term knowledge; session memory handles the current session across compaction.\n\n---\n\n## Changes From s08\n\n| Component | Before (s08) | After (s09) |\n|-----------|-------------|-------------|\n| Memory capability | None (preferences degrade with compaction) | Storage + loading + extraction + consolidation |\n| New functions | — | write_memory_file, select_relevant_memories, load_memories, extract_memories, consolidate_memories |\n| Storage | — | .memory/MEMORY.md index + .memory/*.md files |\n| Tools | bash, read, write, edit, glob, todo_write, task, load_skill, compact (9) | bash, read_file, write_file, edit_file, glob, task (6) |\n| Loop | Only compression each turn | Memory injection + compression + post-turn extraction + periodic consolidation |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s09_memory/code.py\n```\n\nTry these prompts (enter across multiple turns, observe memory accumulation and loading):\n\n1. `I prefer using tabs for indentation, not spaces. Remember that.`\n2. `Create a Python file called test.py` (observe whether the Agent uses tabs)\n3. `What did I tell you about my preferences?` (observe whether the Agent remembers)\n4. `I also prefer single quotes over double quotes for strings.`\n\nWhat to watch for: Does `[Memory: extracted N new memories]` appear after each turn? Are `.md` files generated in `.memory/`? Is `MEMORY.md` index updated? Does the Agent automatically load previous memories in new conversations?\n\n---\n\n## What's Next\n\nMemory, compression, and tools are all in place. But the system prompt is still a hardcoded string. Adding a new tool means manually adding a description; switching projects means rewriting the whole prompt. Prompts should be assembled at runtime.\n\ns10 System Prompt → segments + runtime assembly. Different projects, different tools, different prompts.\n\n
\nDeep Dive Into CC Source Code\n\n> The following is based on analysis of CC source code under `src/` in `memdir/`, `services/`, `utils/`, `query/`. Line numbers verified against source.\n\n### Source Code Paths\n\n| File | Lines | Responsibility |\n|------|-------|---------------|\n| `memdir/memdir.ts` | 507 | Core: MEMORY.md definition (`34-38`), memory behavior instructions distinguishing memory/plan/tasks (`199-266`), `loadMemoryPrompt()` three paths (`419-490`) |\n| `memdir/findRelevantMemories.ts` | 141 | Sonnet side-query memory selection (`18-24` system prompt, `97-122` call logic) |\n| `memdir/memoryTypes.ts` | 271 | Type definitions, frontmatter fields |\n| `memdir/memoryScan.ts` | — | Scan .md files, exclude MEMORY.md, read frontmatter, max 200 files, sorted by mtime desc (`35-94`) |\n| `services/extractMemories/extractMemories.ts` | 615 | Forked agent extraction, restricted permissions, `skipTranscript: true`, `maxTurns: 5` (`371-427`) |\n| `services/autoDream/autoDream.ts` | 324 | Dream consolidation, four-layer gating (`63-66` defaults, `130-190` gating, `224-233` forked agent) |\n| `services/SessionMemory/sessionMemory.ts` | 495 | Session-level memory management |\n| `services/compact/sessionMemoryCompact.ts` | — | Session memory lightweight summary, thresholds 10K/5/40K (`56-61`) |\n| `utils/attachments.ts` | — | Injection budget: 200 lines / 4096 bytes per file, 60KB per session (`269-288`); find relevant memory by query (`2196-2241`) |\n| `query.ts` | — | Memory prefetch at start of each user turn (`301-304`), non-blocking collection (`1592-1614`) |\n| `query/stopHooks.ts` | — | Stop hook fire-and-forget triggers extraction and Dream (`141-155`) |\n\n### Memory Selection: LLM, Not Embedding\n\nCC uses **Sonnet itself to select** (`findRelevantMemories.ts`), not embedding vector similarity:\n\n1. `memoryScan.ts` scans all `.md` files in `.memory/` (excluding MEMORY.md), max 200 files, sorted by mtime descending\n2. Lists all memory files' `name` + `description` as a catalog\n3. Sends to Sonnet side-query: \"Select truly useful memories by name and description (max 5). Skip if unsure.\"\n4. Sonnet returns `{ selected_memories: [\"file1.md\", ...] }`\n5. Selected files' full contents are read (≤ 200 lines / 4096 bytes per file) and injected. Total session budget: 60KB\n\nAt the start of each user turn, `query.ts:301-304` starts memory prefetch (async); after tool execution, `1592-1614` collects completed results non-blocking.\n\n### Extraction Timing: Stop Hook, Not After autoCompact\n\nTrigger location (`stopHooks.ts:141-155`): inside `handleStopHooks()`, fire-and-forget triggers extraction and Dream. The teaching version places extraction in the `stop_reason != \"tool_use\"` branch, matching the direction.\n\nCC's extraction runs via forked agent (`extractMemories.ts:371-427`): restricted permissions, `skipTranscript: true`, `maxTurns: 5`. Also has overlap protection: if the main Agent already wrote memory files, extraction is skipped.\n\n### Memory File Format\n\nCC uses Markdown + YAML frontmatter, consistent with the teaching version. Four types: `user`, `feedback`, `project`, `reference`.\n\n`memdir.ts:34-38` defines index constraints: `MEMORY.md` max 200 lines / 25KB. `memdir.ts:199-266` builds memory behavior instructions, explicitly distinguishing memory from plan and tasks. Storage location: `~/.claude/projects//memory/`.\n\n### Dream: Four-Layer Gating\n\nNot \"triggered when idle\" or \"consolidate when count is enough\", but four gates (`autoDream.ts`, defaults `63-66`, gating logic `130-190`):\n\n1. **Time gate**: ≥ 24 hours since last consolidation\n2. **Scan throttle**: Avoid frequent filesystem scans\n3. **Session gate**: ≥ 5 session transcripts modified since last consolidation\n4. **Lock gate**: No other process currently consolidating (`.consolidate-lock` file)\n\nThe merge itself runs via forked agent (`224-233`): locate → collect recent signals → merge and write files → prune and update index. Lock file mtime serves as lastConsolidatedAt. Crash recovery: lock auto-expires after 1 hour.\n\n### User Memory vs Session Memory\n\n| | User Memory | Session Memory |\n|---|---|---|\n| Persistence | Cross-session | Single session |\n| Storage | Multiple .md files in `memory/` | `session-memory//memory.md` |\n| Loaded into | system prompt | compact summary |\n| Purpose | Cross-session knowledge accumulation | Cross-compact context continuity |\n\nsessionMemoryCompact (mentioned in s08) uses Session Memory: before autoCompact, it reads the session memory file and, if sufficient (≥ 10K tokens, ≥ 5 text messages, ≤ 40K tokens, `sessionMemoryCompact.ts:56-61`), uses it as a summary without calling the LLM.\n\n### Where the Real Implementation Is More Complex\n\n- **Feature flags**: Memory features have multiple feature gate layers\n- **Team memory**: Shared team memories, `loadMemoryPrompt()` has a dedicated path (not covered in teaching version)\n- **KAIROS**: Timing-aware memory extraction strategy, daily-log mode in `loadMemoryPrompt()`\n- **Prompt cache**: Memory injection must account for prompt cache TTL, avoiding full system prompt rewrites each turn\n- **File locks**: Concurrency control for multi-process scenarios\n- **Memory prefetch**: Async prefetch, non-blocking main flow\n\n### Teaching Version Simplifications Are Intentional\n\n- LLM side-query → LLM side-query + keyword fallback: teaching version keeps LLM selection, adds fallback path\n- Memory JSON → Markdown + frontmatter: teaching version matches CC\n- Stop hook trigger → `stop_reason != \"tool_use\"` branch: same direction\n- Four-layer gating → file-count threshold: teaching version lacks transcript system and multi-session concepts\n- Forked agent + restricted permissions → direct call: teaching version has no subprocess isolation\n\n
\n\n\n" + "content": "# s09: Memory — Compression Loses Details, Keep a Layer That Doesn't\n\ns01 → ... → s07 → s08 → `s09` → [s10](/en/s10) → s11 → ... → s20 → s21\n> *\"Compression loses details, keep a layer that doesn't\"* — File store + index + on-demand loading, across compactions, across sessions.\n>\n> **Harness Layer**: Memory — knowledge that survives compaction and sessions.\n\n---\n\n## The Problem\n\ns08's autoCompact preserves current goals, remaining work, and user constraints in the summary, but details get lost: \"use tabs not spaces\" might get simplified to \"user has code style preferences\". And when you start a new session, even the summary is gone.\n\nLLMs have no persistent state; all information lives in the context window. When context fills up, it gets compressed, and compression is lossy. What's needed is a storage layer that doesn't participate in compression and persists across sessions.\n\n---\n\n## The Solution\n\n![Memory Overview](/course-assets/s09_memory/memory-overview.en.svg)\n\nThe s08 compression pipeline is preserved, focusing on memory. Storage uses the filesystem: a `.memory/` directory where each memory is a `.md` file with YAML frontmatter (`name` / `description` / `type`). When files accumulate, an index is needed: `MEMORY.md` holds one link per line and gets injected into the SYSTEM.\n\nKey design: the index stays in SYSTEM prompt (cacheable by prompt cache), file content is injected on demand (matched by filename/description to the current conversation, without breaking the cache). Writing has two paths: the user explicitly says \"remember\", or extraction runs in the background after each turn. When files accumulate, periodic consolidation deduplicates.\n\n> **Boundary with s08:** compaction still owns the current transcript and token budget. Memory does not replace that pipeline; it selectively persists facts outside the transcript and recalls them later.\n\nFour memory types, each answering a different question:\n\n| Type | Answers | Example |\n|------|---------|---------|\n| user | Who you are | \"Use tabs not spaces\" |\n| feedback | How to work | \"Don't mock the database\" |\n| project | What's happening | \"Auth rewrite is compliance-driven\" |\n| reference | Where to find things | \"Pipeline bugs are in Linear INGEST\" |\n\n---\n\n## How It Works\n\n![Memory Subsystems](/course-assets/s09_memory/memory-subsystems.en.svg)\n\n### Storage: Markdown Files + Index\n\nEach memory is a `.md` file with YAML frontmatter for metadata:\n\n```markdown\n---\nname: user-preference-tabs\ndescription: User prefers tabs for indentation\ntype: user\n---\n\nUser prefers using tabs, not spaces, for indentation.\n**Why:** Consistency with existing codebase conventions.\n**How to apply:** Always use tabs when writing or editing files.\n```\n\n`MEMORY.md` is the index, one link per line:\n\n```markdown\n- [user-preference-tabs](user-preference-tabs.md) — User prefers tabs for indentation\n```\n\nWriting a new memory automatically rebuilds the index:\n\n```python\ndef write_memory_file(name, mem_type, description, body):\n slug = name.lower().replace(\" \", \"-\")\n filepath = MEMORY_DIR / f\"{slug}.md\"\n filepath.write_text(\n f\"---\\nname: {name}\\ndescription: {description}\\ntype: {mem_type}\\n---\\n\\n{body}\\n\"\n )\n _rebuild_index()\n```\n\n### Loading: Two Paths\n\n**Path 1: Index in SYSTEM.** `build_system()` reads `MEMORY.md` once at the start of each user request and injects the memory catalog into the SYSTEM prompt. Memory extraction and consolidation run only when the turn ends, so SYSTEM does not need to be rebuilt repeatedly within the same user request.\n\n**Path 2: Relevant memories on demand.** At the start of each user request, `load_memories()` sends the recent conversation and the memory catalog (name + description) to the LLM as a lightweight side-query, selects relevant filenames, then reads and injects their contents. Capped at 5 to control cost.\n\n```python\ndef select_relevant_memories(messages, max_items=5):\n files = list_memory_files()\n if not files:\n return []\n\n # Build catalog: \"0: user-preference-tabs — User prefers tabs...\"\n catalog = \"\\n\".join(f\"{i}: {f['name']} — {f['description']}\" for i, f in enumerate(files))\n\n response = client.messages.create(model=MODEL, messages=[{\"role\": \"user\",\n \"content\": f\"Select relevant memory indices. Return JSON array.\\n\\n\"\n f\"Recent conversation:\\n{recent}\\n\\nMemory catalog:\\n{catalog}\"}],\n max_tokens=200)\n indices = json.loads(re.search(r'\\[.*?\\]', response.content[0].text).group())\n return [files[i][\"filename\"] for i in indices if 0 <= i < len(files)]\n```\n\nIf the side-query fails (API error, JSON parse failure), it falls back to keyword matching on name + description.\n\n### Writing: Extraction After Each Turn\n\nUsers don't always say \"remember this\". Preferences are usually scattered across normal dialogue: \"tabs are better than spaces\", \"let's use single quotes from now on\".\n\n`extract_memories()` runs when each turn ends, triggered when the model stops without a tool_use (indicating the conversation has reached a natural break):\n\n```python\n# In agent_loop:\nif response.stop_reason != \"tool_use\":\n extract_memories(messages) # Extract new memories from recent dialogue\n consolidate_memories() # Check if consolidation is needed\n return\n```\n\nBefore extraction, existing memories are checked to avoid duplicates. The extraction prompt asks the LLM to return a JSON array of `{name, type, description, body}`, writing files only when genuinely new information is found.\n\n```python\ndef extract_memories(messages):\n dialogue = format_recent_messages(messages[-10:])\n existing = \"\\n\".join(f\"- {m['name']}: {m['description']}\" for m in list_memory_files())\n\n prompt = (\n \"Extract user preferences, constraints, or project facts.\\n\"\n \"Return JSON array: [{name, type, description, body}].\\n\"\n \"If nothing new or already covered, return [].\\n\\n\"\n f\"Existing memories:\\n{existing}\\n\\nDialogue:\\n{dialogue[:4000]}\"\n )\n # ... parse response, write files ...\n```\n\n### Consolidation: Low-Frequency Deduplication\n\nMemory files accumulate. `consolidate_memories()` triggers when the file count reaches a threshold (default 10), asking the LLM to deduplicate, merge contradictions, and prune stale memories:\n\n```python\nCONSOLIDATE_THRESHOLD = 10\n\ndef consolidate_memories():\n files = list_memory_files()\n if len(files) < CONSOLIDATE_THRESHOLD:\n return # Too few, not worth consolidating\n # Send all memories to LLM, get back deduplicated list\n # Replace all files with consolidated results\n```\n\n### What Memory Stores\n\nMemory stores information that remains useful across sessions: user preferences, recurring feedback, project background, common entry points, and investigation clues. It focuses on \"what will be useful later\" and brings that information back through an index plus on-demand loading.\n\nSession memory focuses on continuity inside one session: what context should survive after compaction. The two work together: Memory handles long-term knowledge; session memory handles the current session across compaction.\n\n---\n\n## Changes From s08\n\n| Component | Before (s08) | After (s09) |\n|-----------|-------------|-------------|\n| Memory capability | None (preferences degrade with compaction) | Storage + loading + extraction + consolidation |\n| New functions | — | write_memory_file, select_relevant_memories, load_memories, extract_memories, consolidate_memories |\n| Storage | — | .memory/MEMORY.md index + .memory/*.md files |\n| Tools | bash, read, write, edit, glob, todo_write, task, load_skill, compact (9) | bash, read_file, write_file, edit_file, glob, task (6) |\n| Loop | Only compression each turn | Memory injection + compression + post-turn extraction + periodic consolidation |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s09_memory/code.py\n```\n\nTry these prompts (enter across multiple turns, observe memory accumulation and loading):\n\n1. `I prefer using tabs for indentation, not spaces. Remember that.`\n2. `Create a Python file called test.py` (observe whether the Agent uses tabs)\n3. `What did I tell you about my preferences?` (observe whether the Agent remembers)\n4. `I also prefer single quotes over double quotes for strings.`\n\nWhat to watch for: Does `[Memory: extracted N new memories]` appear after each turn? Are `.md` files generated in `.memory/`? Is `MEMORY.md` index updated? Does the Agent automatically load previous memories in new conversations?\n\n---\n\n## What's Next\n\nMemory, compression, and tools are all in place. But the system prompt is still a hardcoded string. Adding a new tool means manually adding a description; switching projects means rewriting the whole prompt. Prompts should be assembled at runtime.\n\ns10 System Prompt → segments + runtime assembly. Different projects, different tools, different prompts.\n\n\n\n" }, { "version": "s09", "locale": "zh", "title": "s09: Memory — 压缩会丢细节,要有一层不丢的", - "content": "# s09: Memory — 压缩会丢细节,要有一层不丢的\n\ns01 → ... → s07 → s08 → `s09` → [s10](/zh/s10) → s11 → ... → s20 → s21 → s22\n> *\"压缩会丢细节, 要有一层不丢的\"* — 文件仓库 + 索引 + 按需加载,跨压缩、跨会话。\n>\n> **Harness 层**: 记忆 — 跨压缩、跨会话的知识积累。\n\n---\n\n## 问题\n\ns08 的 autoCompact 会把当前目标、剩余工作、用户约束写进摘要,但细节会丢失:\"用 tab 缩进不要用空格\"可能被简化成\"用户有代码风格偏好\"。而且新开一个会话,连摘要也没了。\n\nLLM 没有持久状态,所有信息都在上下文窗口里。上下文满了要压缩,压缩就有损。需要一层不参与压缩、跨会话保留的存储。\n\n---\n\n## 解决方案\n\n![Memory Overview](/course-assets/s09_memory/memory-overview.svg)\n\ns08 的压缩管线保留,聚焦记忆。存储选文件系统:`.memory/` 目录下,每个记忆一个 `.md` 文件,带 YAML frontmatter(`name` / `description` / `type`)。文件多了需要索引:`MEMORY.md` 一行一个链接,注入 SYSTEM。\n\n关键设计:索引常驻 SYSTEM prompt(可被 prompt cache 缓存),文件内容按需注入到当前 user turn(按 filename/description 匹配当前对话,不破坏 cache)。写入由每轮结束后的提取器完成:用户显式说\"记住\"或表达稳定偏好时,提取器会保存为记忆。文件积累多了,定期整理去重。\n\n> **与 s08 的边界:** 压缩仍负责当前对话和 token 预算;记忆不会取代压缩管线,而是把选中的事实存到对话之外,并在之后按需召回。\n\n四类记忆,各有用途:\n\n| 类型 | 回答什么 | 示例 |\n|------|---------|------|\n| user | 你是谁 | \"用 tab 不用空格\" |\n| feedback | 怎么做事 | \"别 mock 数据库\" |\n| project | 正在发生什么 | \"auth 重写是合规驱动\" |\n| reference | 东西在哪找 | \"pipeline bug 在 Linear INGEST\" |\n\n---\n\n## 工作原理\n\n![Memory Subsystems](/course-assets/s09_memory/memory-subsystems.svg)\n\n### 存储:Markdown 文件 + 索引\n\n每个记忆是一个 `.md` 文件,YAML frontmatter 记录元数据:\n\n```markdown\n---\nname: user-preference-tabs\ndescription: User prefers tabs for indentation\ntype: user\n---\n\nUser prefers using tabs, not spaces, for indentation.\n**Why:** Consistency with existing codebase conventions.\n**How to apply:** Always use tabs when writing or editing files.\n```\n\n`MEMORY.md` 是索引,一行一个链接:\n\n```markdown\n- [user-preference-tabs](user-preference-tabs.md) — User prefers tabs for indentation\n```\n\n写入新记忆时自动重建索引:\n\n```python\ndef write_memory_file(name, mem_type, description, body):\n slug = name.lower().replace(\" \", \"-\")\n filepath = MEMORY_DIR / f\"{slug}.md\"\n filepath.write_text(\n f\"---\\nname: {name}\\ndescription: {description}\\ntype: {mem_type}\\n---\\n\\n{body}\\n\"\n )\n _rebuild_index()\n```\n\n### 加载:两条路径\n\n**路径一:索引常驻 SYSTEM。** `build_system()` 在每次用户请求开始时读取 `MEMORY.md`,把记忆清单注入。记忆提取和整理只在本轮结束时触发,因此同一轮用户请求中不需要重复重建 SYSTEM。\n\n**路径二:相关记忆按需注入。** 每次用户请求开始时,`load_memories()` 把最近对话和记忆目录(name + description)一起发给 LLM 做一次轻量 side-query,选出相关的文件名,再读文件内容临时注入到当前 user turn。最多 5 条,控制开销。\n\n```python\ndef select_relevant_memories(messages, max_items=5):\n files = list_memory_files()\n if not files:\n return []\n\n # Build catalog: \"0: user-preference-tabs — User prefers tabs...\"\n catalog = \"\\n\".join(f\"{i}: {f['name']} — {f['description']}\" for i, f in enumerate(files))\n\n response = client.messages.create(model=MODEL, messages=[{\"role\": \"user\",\n \"content\": f\"Select relevant memory indices. Return JSON array.\\n\\n\"\n f\"Recent conversation:\\n{recent}\\n\\nMemory catalog:\\n{catalog}\"}],\n max_tokens=200)\n text = extract_text(response.content).strip()\n indices = json.loads(re.search(r'\\[.*?\\]', text).group())\n return [files[i][\"filename\"] for i in indices if 0 <= i < len(files)]\n```\n\n如果 side-query 失败(API 错误、JSON 解析失败),降级到关键词匹配 name + description。\n\n### 写入:每轮结束后提取\n\n用户不会每次都说\"记住这个\"。偏好通常散落在正常对话中:\"用 tab 比空格好\"、\"以后都用单引号\"。\n\n`extract_memories()` 在每轮结束时运行,条件是模型停止且没有 tool_use(说明对话告一段落):\n\n```python\n# In agent_loop:\nif response.stop_reason != \"tool_use\":\n extract_memories(pre_compress) # 从压缩前快照提取新记忆\n consolidate_memories() # 检查是否需要整理\n return\n```\n\n提取前先检查已有记忆,避免重复。提取 prompt 要求 LLM 返回 `{name, type, description, body}` 的 JSON 数组,只有确实有新信息时才写文件。\n\n```python\ndef extract_memories(messages):\n dialogue = format_recent_messages(messages[-10:])\n existing = \"\\n\".join(f\"- {m['name']}: {m['description']}\" for m in list_memory_files())\n\n prompt = (\n \"Extract user preferences, constraints, or project facts.\\n\"\n \"Return JSON array: [{name, type, description, body}].\\n\"\n \"If nothing new or already covered, return [].\\n\\n\"\n f\"Existing memories:\\n{existing}\\n\\nDialogue:\\n{dialogue[:4000]}\"\n )\n # ... parse response, write files ...\n```\n\n### 整理:低频合并去重\n\n记忆文件会积累。`consolidate_memories()` 在文件数达到阈值(默认 10)时触发,让 LLM 去重、合并矛盾、淘汰过时记忆:\n\n```python\nCONSOLIDATE_THRESHOLD = 10\n\ndef consolidate_memories():\n files = list_memory_files()\n if len(files) < CONSOLIDATE_THRESHOLD:\n return # 太少,不值得整理\n # Send all memories to LLM, get back deduplicated list\n # Replace all files with consolidated results\n```\n\nCC 把这个过程叫 Dream,实际有四层门控:时间间隔、扫描节流、会话数、文件锁。教学版简化为文件数阈值。\n\n### Memory 适合保存什么\n\nMemory 保存跨会话仍然有用的信息:用户偏好、反复出现的反馈、项目背景、常用入口和排查线索。它关注“以后还会用到什么”,并通过索引 + 按需加载把这些信息带回当前对话。\n\nsession memory 关注同一会话内的连续性:compact 之后,当前会话还需要保留哪些上下文。两者配合使用:Memory 管长期知识,session memory 管当前会话的压缩续接。\n\n---\n\n## 相对 s08 的变更\n\n| 组件 | 之前 (s08) | 之后 (s09) |\n|------|-----------|-----------|\n| 记忆能力 | 无(压缩后偏好随摘要退化) | 存储 + 加载 + 提取 + 整理 |\n| 新函数 | — | write_memory_file, select_relevant_memories, load_memories, extract_memories, consolidate_memories |\n| 存储 | — | .memory/MEMORY.md 索引 + .memory/*.md 文件 |\n| 工具 | bash, read, write, edit, glob, todo_write, task, load_skill, compact (9) | bash, read_file, write_file, edit_file, glob, task (6) |\n| 循环 | 每轮只做压缩 | 每轮注入记忆 + 压缩 + 每轮结束后提取 + 定期整理 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s09_memory/code.py\n```\n\n试试这些 prompt(分多轮输入,观察记忆的累积和加载):\n\n1. `I prefer using tabs for indentation, not spaces. Remember that.`\n2. `Create a Python file called test.py`(观察 Agent 是否用了 tab)\n3. `What did I tell you about my preferences?`(观察 Agent 是否记得)\n4. `I also prefer single quotes over double quotes for strings.`\n\n观察重点:每轮结束后是否出现 `[Memory: extracted N new memories]`?`.memory/` 目录下是否生成了 `.md` 文件?`MEMORY.md` 索引是否更新?新一轮对话时 Agent 是否自动加载了之前的记忆?\n\n---\n\n## 接下来\n\n记忆、压缩、工具都已就绪。但 system prompt 还是硬编码的一大段字符串。加了新工具要手动加描述,换了项目要重写整个 prompt。prompt 应该运行时组装。\n\ns10 System Prompt → 分段 + 运行时组装。不同项目、不同工具,拼出不同的 prompt。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `src/` 下 `memdir/`、`services/`、`utils/`、`query/` 的分析,行号已对照核实。\n\n### 源码路径\n\n| 文件 | 行数 | 职责 |\n|------|------|------|\n| `memdir/memdir.ts` | 507 | 核心:MEMORY.md 定义(`34-38`)、记忆行为指令区分 memory/plan/tasks(`199-266`)、`loadMemoryPrompt()` 三条路径(`419-490`) |\n| `memdir/findRelevantMemories.ts` | 141 | Sonnet side-query 选记忆(`18-24` 系统提示、`97-122` 调用逻辑) |\n| `memdir/memoryTypes.ts` | 271 | 类型定义,frontmatter 字段 |\n| `memdir/memoryScan.ts` | — | 扫描 .md 文件,排除 MEMORY.md,读 frontmatter,最多 200 个,按 mtime 降序(`35-94`) |\n| `services/extractMemories/extractMemories.ts` | 615 | forked agent 提取记忆,受限权限,`skipTranscript: true`,`maxTurns: 5`(`371-427`) |\n| `services/autoDream/autoDream.ts` | 324 | Dream 整理,四层门控(`63-66` 默认值、`130-190` 门控、`224-233` forked agent) |\n| `services/SessionMemory/sessionMemory.ts` | 495 | 会话级记忆管理 |\n| `services/compact/sessionMemoryCompact.ts` | — | session memory 轻量摘要,阈值 10K/5/40K(`56-61`) |\n| `utils/attachments.ts` | — | 注入预算:200 行 / 4096 字节每文件,60KB 每 session(`269-288`);按 query 找相关 memory(`2196-2241`) |\n| `query.ts` | — | memory prefetch 每轮启动(`301-304`),非阻塞收集(`1592-1614`) |\n| `query/stopHooks.ts` | — | stop hook fire-and-forget 触发提取和 Dream(`141-155`) |\n\n### 记忆选择:LLM 选,不是 embedding\n\nCC 用 **Sonnet 本身来选**(`findRelevantMemories.ts`),不是 embedding 向量相似度:\n\n1. `memoryScan.ts` 扫描 `.memory/` 下所有 `.md` 文件(排除 MEMORY.md),最多 200 个,按 mtime 降序\n2. 把 `name` + `description` 列成清单\n3. 发给 Sonnet side-query:\"根据名称和描述选出真正有用的记忆(最多 5 个)。不确定就不要选。\"\n4. Sonnet 返回 `{ selected_memories: [\"file1.md\", ...] }`\n5. 选中文件读取完整内容(每文件 ≤ 200 行 / 4096 字节),注入上下文。单 session 总预算 60KB\n\n每轮用户 turn 开始时,`query.ts:301-304` 启动 memory prefetch(异步);工具执行后 `1592-1614` 非阻塞收集结果,不卡主流程。\n\n### 提取时机:stop hook,不是 autoCompact 后\n\n触发位置(`stopHooks.ts:141-155`):在 `handleStopHooks()` 中,fire-and-forget 触发提取和 Dream。教学版把提取放在 `stop_reason != \"tool_use\"` 分支里,方向一致。\n\nCC 的提取通过 forked agent 执行(`extractMemories.ts:371-427`):受限权限、`skipTranscript: true`、`maxTurns: 5`。还有重叠保护:如果主 Agent 已经写入了记忆文件,跳过提取。\n\n### 记忆文件格式\n\nCC 用 Markdown + YAML frontmatter,和教学版一致。四种类型:`user`、`feedback`、`project`、`reference`。\n\n`memdir.ts:34-38` 定义索引约束:`MEMORY.md` 最多 200 行 / 25KB。`memdir.ts:199-266` 构建记忆行为指令,明确区分 memory、plan、tasks。存储位置:`~/.claude/projects//memory/`。\n\n### Dream:四层门控\n\n不是\"空闲时触发\"或\"数量够了就合并\",而是四层门控(`autoDream.ts`,默认值 `63-66`,门控逻辑 `130-190`):\n\n1. **时间门控**:距上次合并 ≥ 24 小时\n2. **扫描节流**:避免频繁扫描文件系统\n3. **会话门控**:自上次合并以来修改了 ≥ 5 个会话 transcript\n4. **锁门控**:没有其他进程正在合并(`.consolidate-lock` 文件)\n\n合并本身通过 forked agent 执行(`224-233`):定位 → 收集近期信号 → 合并写文件 → 剪枝更新索引。锁文件 mtime 就是 lastConsolidatedAt。崩溃恢复:1 小时后锁自动过期。\n\n### User Memory vs Session Memory\n\n| | User Memory | Session Memory |\n|---|---|---|\n| 持久性 | 跨会话 | 单会话 |\n| 存储 | `memory/` 下多个 .md 文件 | `session-memory//memory.md` |\n| 加载到 | system prompt | compact 摘要 |\n| 用途 | 跨会话的知识积累 | 跨 compact 的上下文连续性 |\n\nsessionMemoryCompact(s08 中提到的机制)正是使用了 Session Memory:autoCompact 前先读 session memory 文件,如果内容足够(≥ 10K token、≥ 5 条文本消息、≤ 40K token,`sessionMemoryCompact.ts:56-61`),就用它做摘要,不调 LLM。\n\n### 真实实现比教学版复杂的地方\n\n- **Feature flags**:记忆相关功能有多层 feature gate 控制\n- **Team memory**:团队共享记忆,`loadMemoryPrompt()` 有专门路径(教学版未涉及)\n- **KAIROS**:时机感知的记忆提取策略,`loadMemoryPrompt()` 中 daily-log 模式\n- **Prompt cache**:记忆注入需要考虑 prompt cache 的 TTL,避免每次都重写 system prompt 的大段内容\n- **文件锁**:多进程并发时的锁机制\n- **Memory prefetch**:异步预取,不阻塞主流程\n\n### 教学版的简化是刻意的\n\n- LLM side-query → LLM side-query + 关键词降级:教学版保留了 LLM 选择,加了降级路径\n- 记忆 JSON → Markdown + frontmatter:教学版与 CC 一致\n- stop hook 触发 → `stop_reason != \"tool_use\"` 分支:方向一致\n- 四层门控 → 文件数阈值:教学版没有 transcript 系统和多会话概念\n- forked agent + 受限权限 → 直接调用:教学版没有子进程隔离\n\n
\n\n\n" + "content": "# s09: Memory — 压缩会丢细节,要有一层不丢的\n\ns01 → ... → s07 → s08 → `s09` → [s10](/zh/s10) → s11 → ... → s20 → s21\n> *\"压缩会丢细节, 要有一层不丢的\"* — 文件仓库 + 索引 + 按需加载,跨压缩、跨会话。\n>\n> **Harness 层**: 记忆 — 跨压缩、跨会话的知识积累。\n\n---\n\n## 问题\n\ns08 的 autoCompact 会把当前目标、剩余工作、用户约束写进摘要,但细节会丢失:\"用 tab 缩进不要用空格\"可能被简化成\"用户有代码风格偏好\"。而且新开一个会话,连摘要也没了。\n\nLLM 没有持久状态,所有信息都在上下文窗口里。上下文满了要压缩,压缩就有损。需要一层不参与压缩、跨会话保留的存储。\n\n---\n\n## 解决方案\n\n![Memory Overview](/course-assets/s09_memory/memory-overview.svg)\n\ns08 的压缩管线保留,聚焦记忆。存储选文件系统:`.memory/` 目录下,每个记忆一个 `.md` 文件,带 YAML frontmatter(`name` / `description` / `type`)。文件多了需要索引:`MEMORY.md` 一行一个链接,注入 SYSTEM。\n\n关键设计:索引常驻 SYSTEM prompt(可被 prompt cache 缓存),文件内容按需注入到当前 user turn(按 filename/description 匹配当前对话,不破坏 cache)。写入由每轮结束后的提取器完成:用户显式说\"记住\"或表达稳定偏好时,提取器会保存为记忆。文件积累多了,定期整理去重。\n\n> **与 s08 的边界:** 压缩仍负责当前对话和 token 预算;记忆不会取代压缩管线,而是把选中的事实存到对话之外,并在之后按需召回。\n\n四类记忆,各有用途:\n\n| 类型 | 回答什么 | 示例 |\n|------|---------|------|\n| user | 你是谁 | \"用 tab 不用空格\" |\n| feedback | 怎么做事 | \"别 mock 数据库\" |\n| project | 正在发生什么 | \"auth 重写是合规驱动\" |\n| reference | 东西在哪找 | \"pipeline bug 在 Linear INGEST\" |\n\n---\n\n## 工作原理\n\n![Memory Subsystems](/course-assets/s09_memory/memory-subsystems.svg)\n\n### 存储:Markdown 文件 + 索引\n\n每个记忆是一个 `.md` 文件,YAML frontmatter 记录元数据:\n\n```markdown\n---\nname: user-preference-tabs\ndescription: User prefers tabs for indentation\ntype: user\n---\n\nUser prefers using tabs, not spaces, for indentation.\n**Why:** Consistency with existing codebase conventions.\n**How to apply:** Always use tabs when writing or editing files.\n```\n\n`MEMORY.md` 是索引,一行一个链接:\n\n```markdown\n- [user-preference-tabs](user-preference-tabs.md) — User prefers tabs for indentation\n```\n\n写入新记忆时自动重建索引:\n\n```python\ndef write_memory_file(name, mem_type, description, body):\n slug = name.lower().replace(\" \", \"-\")\n filepath = MEMORY_DIR / f\"{slug}.md\"\n filepath.write_text(\n f\"---\\nname: {name}\\ndescription: {description}\\ntype: {mem_type}\\n---\\n\\n{body}\\n\"\n )\n _rebuild_index()\n```\n\n### 加载:两条路径\n\n**路径一:索引常驻 SYSTEM。** `build_system()` 在每次用户请求开始时读取 `MEMORY.md`,把记忆清单注入。记忆提取和整理只在本轮结束时触发,因此同一轮用户请求中不需要重复重建 SYSTEM。\n\n**路径二:相关记忆按需注入。** 每次用户请求开始时,`load_memories()` 把最近对话和记忆目录(name + description)一起发给 LLM 做一次轻量 side-query,选出相关的文件名,再读文件内容临时注入到当前 user turn。最多 5 条,控制开销。\n\n```python\ndef select_relevant_memories(messages, max_items=5):\n files = list_memory_files()\n if not files:\n return []\n\n # Build catalog: \"0: user-preference-tabs — User prefers tabs...\"\n catalog = \"\\n\".join(f\"{i}: {f['name']} — {f['description']}\" for i, f in enumerate(files))\n\n response = client.messages.create(model=MODEL, messages=[{\"role\": \"user\",\n \"content\": f\"Select relevant memory indices. Return JSON array.\\n\\n\"\n f\"Recent conversation:\\n{recent}\\n\\nMemory catalog:\\n{catalog}\"}],\n max_tokens=200)\n text = extract_text(response.content).strip()\n indices = json.loads(re.search(r'\\[.*?\\]', text).group())\n return [files[i][\"filename\"] for i in indices if 0 <= i < len(files)]\n```\n\n如果 side-query 失败(API 错误、JSON 解析失败),降级到关键词匹配 name + description。\n\n### 写入:每轮结束后提取\n\n用户不会每次都说\"记住这个\"。偏好通常散落在正常对话中:\"用 tab 比空格好\"、\"以后都用单引号\"。\n\n`extract_memories()` 在每轮结束时运行,条件是模型停止且没有 tool_use(说明对话告一段落):\n\n```python\n# In agent_loop:\nif response.stop_reason != \"tool_use\":\n extract_memories(pre_compress) # 从压缩前快照提取新记忆\n consolidate_memories() # 检查是否需要整理\n return\n```\n\n提取前先检查已有记忆,避免重复。提取 prompt 要求 LLM 返回 `{name, type, description, body}` 的 JSON 数组,只有确实有新信息时才写文件。\n\n```python\ndef extract_memories(messages):\n dialogue = format_recent_messages(messages[-10:])\n existing = \"\\n\".join(f\"- {m['name']}: {m['description']}\" for m in list_memory_files())\n\n prompt = (\n \"Extract user preferences, constraints, or project facts.\\n\"\n \"Return JSON array: [{name, type, description, body}].\\n\"\n \"If nothing new or already covered, return [].\\n\\n\"\n f\"Existing memories:\\n{existing}\\n\\nDialogue:\\n{dialogue[:4000]}\"\n )\n # ... parse response, write files ...\n```\n\n### 整理:低频合并去重\n\n记忆文件会积累。`consolidate_memories()` 在文件数达到阈值(默认 10)时触发,让 LLM 去重、合并矛盾、淘汰过时记忆:\n\n```python\nCONSOLIDATE_THRESHOLD = 10\n\ndef consolidate_memories():\n files = list_memory_files()\n if len(files) < CONSOLIDATE_THRESHOLD:\n return # 太少,不值得整理\n # Send all memories to LLM, get back deduplicated list\n # Replace all files with consolidated results\n```\n\n### Memory 适合保存什么\n\nMemory 保存跨会话仍然有用的信息:用户偏好、反复出现的反馈、项目背景、常用入口和排查线索。它关注“以后还会用到什么”,并通过索引 + 按需加载把这些信息带回当前对话。\n\nsession memory 关注同一会话内的连续性:compact 之后,当前会话还需要保留哪些上下文。两者配合使用:Memory 管长期知识,session memory 管当前会话的压缩续接。\n\n---\n\n## 相对 s08 的变更\n\n| 组件 | 之前 (s08) | 之后 (s09) |\n|------|-----------|-----------|\n| 记忆能力 | 无(压缩后偏好随摘要退化) | 存储 + 加载 + 提取 + 整理 |\n| 新函数 | — | write_memory_file, select_relevant_memories, load_memories, extract_memories, consolidate_memories |\n| 存储 | — | .memory/MEMORY.md 索引 + .memory/*.md 文件 |\n| 工具 | bash, read, write, edit, glob, todo_write, task, load_skill, compact (9) | bash, read_file, write_file, edit_file, glob, task (6) |\n| 循环 | 每轮只做压缩 | 每轮注入记忆 + 压缩 + 每轮结束后提取 + 定期整理 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s09_memory/code.py\n```\n\n试试这些 prompt(分多轮输入,观察记忆的累积和加载):\n\n1. `I prefer using tabs for indentation, not spaces. Remember that.`\n2. `Create a Python file called test.py`(观察 Agent 是否用了 tab)\n3. `What did I tell you about my preferences?`(观察 Agent 是否记得)\n4. `I also prefer single quotes over double quotes for strings.`\n\n观察重点:每轮结束后是否出现 `[Memory: extracted N new memories]`?`.memory/` 目录下是否生成了 `.md` 文件?`MEMORY.md` 索引是否更新?新一轮对话时 Agent 是否自动加载了之前的记忆?\n\n---\n\n## 接下来\n\n记忆、压缩、工具都已就绪。但 system prompt 还是硬编码的一大段字符串。加了新工具要手动加描述,换了项目要重写整个 prompt。prompt 应该运行时组装。\n\ns10 System Prompt → 分段 + 运行时组装。不同项目、不同工具,拼出不同的 prompt。\n\n\n\n" }, { "version": "s09", "locale": "ja", "title": "s09: Memory — 圧縮は詳細を失う、失わない層が必要", - "content": "# s09: Memory — 圧縮は詳細を失う、失わない層が必要\n\ns01 → ... → s07 → s08 → `s09` → [s10](/ja/s10) → s11 → ... → s20 → s21 → s22\n> *\"圧縮は詳細を失う、失わない層が必要\"* — ファイルストア + インデックス + オンデマンド読み込み。圧縮を越え、セッションを越えて。\n>\n> **Harness レイヤー**: 記憶 — 圧縮とセッションを越える知識の蓄積。\n\n---\n\n## 課題\n\ns08 の autoCompact は現在の目標、残りの作業、ユーザーの制約をサマリに保持するが、詳細は失われる:「タブでインデント、スペース不可」が「ユーザーにコードスタイルの好みあり」と簡略化される。そして新しいセッションを開始すると、サマリすらない。\n\nLLM には永続状態がなく、すべての情報はコンテキストウィンドウ内にある。コンテキストが満杯になれば圧縮され、圧縮は非可逆。圧縮に参加せず、セッションを越えて保持されるストレージ層が必要。\n\n---\n\n## ソリューション\n\n![Memory Overview](/course-assets/s09_memory/memory-overview.ja.svg)\n\ns08 の圧縮パイプラインを維持し、記憶に焦点を当てる。ストレージにはファイルシステムを採用:`.memory/` ディレクトリに各記憶を `.md` ファイルとして保存、YAML frontmatter(`name` / `description` / `type`)付き。ファイルが増えたらインデックスが必要:`MEMORY.md` に 1 行 1 リンクを記録し、SYSTEM に注入。\n\n重要な設計:インデックスは SYSTEM prompt に常駐(prompt cache でキャッシュ可能)、ファイル内容はオンデマンド注入(filename/description で現在の会話にマッチ、cache を破壊しない)。書き込みは 2 つのパス:ユーザーが明示的に「覚えて」と言うか、毎ターン終了後にバックグラウンドで抽出。ファイルが蓄積されたら、定期的に整理して重複排除。\n\n> **s08 との境界:** 圧縮は引き続き現在の会話と token 予算を担当する。記憶は圧縮を置き換えず、選んだ事実を会話の外に保存し、後から必要に応じて呼び戻す。\n\n4 種類の記憶、それぞれ異なる質問に答える:\n\n| タイプ | 何に答えるか | 例 |\n|--------|-------------|-----|\n| user | あなたは誰か | \"タブでスペース不可\" |\n| feedback | どう作業するか | \"DB をモックしない\" |\n| project | 何が起きているか | \"auth 書き直しはコンプライアンス主導\" |\n| reference | どこで探すか | \"パイプラインのバグは Linear INGEST\" |\n\n---\n\n## 仕組み\n\n![Memory Subsystems](/course-assets/s09_memory/memory-subsystems.ja.svg)\n\n### ストレージ:Markdown ファイル + インデックス\n\n各記憶は `.md` ファイル、YAML frontmatter でメタデータを記録:\n\n```markdown\n---\nname: user-preference-tabs\ndescription: User prefers tabs for indentation\ntype: user\n---\n\nUser prefers using tabs, not spaces, for indentation.\n**Why:** Consistency with existing codebase conventions.\n**How to apply:** Always use tabs when writing or editing files.\n```\n\n`MEMORY.md` はインデックス、1 行に 1 リンク:\n\n```markdown\n- [user-preference-tabs](user-preference-tabs.md) — User prefers tabs for indentation\n```\n\n新しい記憶を書き込むとインデックスを自動再構築:\n\n```python\ndef write_memory_file(name, mem_type, description, body):\n slug = name.lower().replace(\" \", \"-\")\n filepath = MEMORY_DIR / f\"{slug}.md\"\n filepath.write_text(\n f\"---\\nname: {name}\\ndescription: {description}\\ntype: {mem_type}\\n---\\n\\n{body}\\n\"\n )\n _rebuild_index()\n```\n\n### 読み込み:2 つのパス\n\n**パス 1:インデックスを SYSTEM に常駐。** `build_system()` は各ユーザーリクエストの開始時に 1 回だけ `MEMORY.md` を読み込み、記憶カタログを SYSTEM prompt に注入。記憶の抽出と整理はターン終了時にだけ実行されるため、同じユーザーリクエスト内で SYSTEM を繰り返し再構築する必要はない。\n\n**パス 2:関連記憶をオンデマンド注入。** 各ユーザーリクエストの開始時に、`load_memories()` は最近の会話と記憶カタログ(name + description)を LLM に軽量 side-query として送信し、関連するファイル名を選択、ファイル内容を読み込んで注入。上限 5 件でコストを制御。\n\n```python\ndef select_relevant_memories(messages, max_items=5):\n files = list_memory_files()\n if not files:\n return []\n\n # Build catalog: \"0: user-preference-tabs — User prefers tabs...\"\n catalog = \"\\n\".join(f\"{i}: {f['name']} — {f['description']}\" for i, f in enumerate(files))\n\n response = client.messages.create(model=MODEL, messages=[{\"role\": \"user\",\n \"content\": f\"Select relevant memory indices. Return JSON array.\\n\\n\"\n f\"Recent conversation:\\n{recent}\\n\\nMemory catalog:\\n{catalog}\"}],\n max_tokens=200)\n indices = json.loads(re.search(r'\\[.*?\\]', response.content[0].text).group())\n return [files[i][\"filename\"] for i in indices if 0 <= i < len(files)]\n```\n\nside-query が失敗した場合(API エラー、JSON パース失敗)、name + description のキーワードマッチにフォールバック。\n\n### 書き込み:毎ターン終了後の抽出\n\nユーザーが毎回「これを覚えて」と言うわけではない。好みは通常、通常の会話の中に散らばっている:「タブの方がスペースより良い」「これからはシングルクォートにしよう」。\n\n`extract_memories()` は各ターン終了時に実行、モデルが tool_use なしで停止した場合にトリガー(会話が自然な区切りに達したことを示す):\n\n```python\n# In agent_loop:\nif response.stop_reason != \"tool_use\":\n extract_memories(messages) # 最近の会話から新しい記憶を抽出\n consolidate_memories() # 整理が必要かチェック\n return\n```\n\n抽出前に既存の記憶を確認し、重複を回避。抽出プロンプトは LLM に `{name, type, description, body}` の JSON 配列を要求、本当に新しい情報がある場合のみファイルに書き込む。\n\n```python\ndef extract_memories(messages):\n dialogue = format_recent_messages(messages[-10:])\n existing = \"\\n\".join(f\"- {m['name']}: {m['description']}\" for m in list_memory_files())\n\n prompt = (\n \"Extract user preferences, constraints, or project facts.\\n\"\n \"Return JSON array: [{name, type, description, body}].\\n\"\n \"If nothing new or already covered, return [].\\n\\n\"\n f\"Existing memories:\\n{existing}\\n\\nDialogue:\\n{dialogue[:4000]}\"\n )\n # ... parse response, write files ...\n```\n\n### 整理:低頻度の重複排除\n\n記憶ファイルは蓄積される。`consolidate_memories()` はファイル数が閾値(デフォルト 10)に達した時にトリガー、LLM に重複排除、矛盾の統合、古い記憶の剪定を依頼:\n\n```python\nCONSOLIDATE_THRESHOLD = 10\n\ndef consolidate_memories():\n files = list_memory_files()\n if len(files) < CONSOLIDATE_THRESHOLD:\n return # 少なすぎる、整理する価値なし\n # Send all memories to LLM, get back deduplicated list\n # Replace all files with consolidated results\n```\n\nCC はこのプロセスを **Dream** と呼び、実際には 4 層のゲートがある:時間間隔、スキャンスロットル、セッション数、ファイルロック。教学版はファイル数閾値に簡略化。\n\n### Memory に保存するもの\n\nMemory はセッションを越えて有用な情報を保存する:ユーザーの好み、繰り返し出るフィードバック、プロジェクト背景、よく使う入口、調査の手がかりなど。「あとでまた使うもの」を対象にし、インデックス + オンデマンド読み込みで現在の会話に戻す。\n\nsession memory は 1 つのセッション内の連続性を扱う:compact 後も現在の会話に残すべき文脈を保持する。両者は役割が分かれている。Memory は長期知識を扱い、session memory は現在のセッションを compact 越しにつなぐ。\n\n---\n\n## s08 からの変更点\n\n| コンポーネント | 変更前 (s08) | 変更後 (s09) |\n|-----------|-------------|-------------|\n| 記憶能力 | なし(圧縮後、好みはサマリと共に劣化) | ストレージ + 読み込み + 抽出 + 整理 |\n| 新規関数 | — | write_memory_file, select_relevant_memories, load_memories, extract_memories, consolidate_memories |\n| ストレージ | — | .memory/MEMORY.md インデックス + .memory/*.md ファイル |\n| ツール | bash, read, write, edit, glob, todo_write, task, load_skill, compact (9) | bash, read_file, write_file, edit_file, glob, task (6) |\n| ループ | 毎ターン圧縮のみ | 記憶注入 + 圧縮 + ターン終了後の抽出 + 定期整理 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s09_memory/code.py\n```\n\n以下のプロンプトを試してみてください(複数ターンに分けて入力し、記憶の蓄積と読み込みを観察):\n\n1. `I prefer using tabs for indentation, not spaces. Remember that.`\n2. `Create a Python file called test.py`(Agent がタブを使用したか観察)\n3. `What did I tell you about my preferences?`(Agent が覚えているか観察)\n4. `I also prefer single quotes over double quotes for strings.`\n\n観察のポイント:各ターン終了後に `[Memory: extracted N new memories]` が表示されるか?`.memory/` ディレクトリに `.md` ファイルが生成されたか?`MEMORY.md` インデックスが更新されたか?新しい会話で Agent が以前の記憶を自動的に読み込んだか?\n\n---\n\n## 次へ\n\n記憶、圧縮、ツールはすべて揃った。しかし system prompt はまだハードコードされた文字列。新しいツールを追加するには手動で説明を書き、プロジェクトを変えるにはプロンプト全体を書き直す。プロンプトは実行時に組み立てられるべき。\n\ns10 System Prompt → セグメント + 実行時組み立て。異なるプロジェクト、異なるツール、異なるプロンプト。\n\n
\nCC ソースコードの詳細\n\n> 以下は CC ソースコード `src/` 下の `memdir/`、`services/`、`utils/`、`query/` の分析に基づく。行番号はソースコードと照合済み。\n\n### ソースコードパス\n\n| ファイル | 行数 | 職責 |\n|------|------|------|\n| `memdir/memdir.ts` | 507 | 核心:MEMORY.md 定義(`34-38`)、記憶動作指示で memory/plan/tasks を区別(`199-266`)、`loadMemoryPrompt()` 3 パス(`419-490`) |\n| `memdir/findRelevantMemories.ts` | 141 | Sonnet side-query で記憶選択(`18-24` システムプロンプト、`97-122` 呼び出しロジック) |\n| `memdir/memoryTypes.ts` | 271 | 型定義、frontmatter フィールド |\n| `memdir/memoryScan.ts` | — | .md ファイルをスキャン、MEMORY.md を除外、frontmatter を読み取り、最大 200 ファイル、mtime 降順(`35-94`) |\n| `services/extractMemories/extractMemories.ts` | 615 | forked agent で記憶を抽出、制限付き権限、`skipTranscript: true`、`maxTurns: 5`(`371-427`) |\n| `services/autoDream/autoDream.ts` | 324 | Dream 整理、4 層ゲート(`63-66` デフォルト値、`130-190` ゲート、`224-233` forked agent) |\n| `services/SessionMemory/sessionMemory.ts` | 495 | セッションレベルの記憶管理 |\n| `services/compact/sessionMemoryCompact.ts` | — | session memory 軽量サマリ、閾値 10K/5/40K(`56-61`) |\n| `utils/attachments.ts` | — | 注入予算:200 行 / 4096 バイト/ファイル、60KB/セッション(`269-288`);query で関連記憶を検索(`2196-2241`) |\n| `query.ts` | — | memory prefetch を毎ターン開始時に起動(`301-304`)、非ブロッキング収集(`1592-1614`) |\n| `query/stopHooks.ts` | — | stop hook fire-and-forget で抽出と Dream をトリガー(`141-155`) |\n\n### 記憶選択:embedding ではなく LLM\n\nCC は **Sonnet 自身で選択**(`findRelevantMemories.ts`)、embedding ベクトル類似度ではない:\n\n1. `memoryScan.ts` が `.memory/` 下のすべての `.md` ファイルをスキャン(MEMORY.md を除外)、最大 200 ファイル、mtime 降順\n2. `name` + `description` をカタログとしてリスト化\n3. Sonnet side-query に送信:「名前と説明から本当に有用な記憶を選択(最大 5 件)。不明ならスキップ。」\n4. Sonnet が `{ selected_memories: [\"file1.md\", ...] }` を返却\n5. 選択されたファイルの完全な内容を読み込み(≤ 200 行 / 4096 バイト/ファイル)、注入。セッション総予算:60KB\n\n毎ターンのユーザー turn 開始時、`query.ts:301-304` が memory prefetch を起動(非同期);ツール実行後、`1592-1614` が非ブロッキングで結果を収集。\n\n### 抽出タイミング:stop hook、autoCompact 後ではない\n\nトリガー位置(`stopHooks.ts:141-155`):`handleStopHooks()` 内で、fire-and-forget で抽出と Dream をトリガー。教学版は `stop_reason != \"tool_use\"` 分岐に抽出を配置、方向は一致。\n\nCC の抽出は forked agent で実行(`extractMemories.ts:371-427`):制限付き権限、`skipTranscript: true`、`maxTurns: 5`。重複保護もある:メイン Agent が既に記憶ファイルを書き込んだ場合、抽出をスキップ。\n\n### 記憶ファイル形式\n\nCC は Markdown + YAML frontmatter を使用、教学版と一致。4 種類:`user`、`feedback`、`project`、`reference`。\n\n`memdir.ts:34-38` がインデックス制約を定義:`MEMORY.md` 最大 200 行 / 25KB。`memdir.ts:199-266` が記憶動作指示を構築、memory と plan と tasks を明確に区別。保存場所:`~/.claude/projects//memory/`。\n\n### Dream:4 層ゲート\n\n「アイドル時にトリガー」や「数が足りたら統合」ではなく、4 層のゲート(`autoDream.ts`、デフォルト値 `63-66`、ゲートロジック `130-190`):\n\n1. **時間ゲート**:前回の統合から ≥ 24 時間\n2. **スキャンスロットル**:頻繁なファイルシステムスキャンを回避\n3. **セッションゲート**:前回の統合以降 ≥ 5 セッションの transcript が変更された\n4. **ロックゲート**:他のプロセスが統合中でない(`.consolidate-lock` ファイル)\n\n統合自体は forked agent で実行(`224-233`):定位 → 直近のシグナル収集 → 統合してファイル書き込み → 剪定してインデックス更新。ロックファイルの mtime が lastConsolidatedAt。クラッシュリカバリ:1 時間後にロックが自動期限切れ。\n\n### User Memory vs Session Memory\n\n| | User Memory | Session Memory |\n|---|---|---|\n| 永続性 | セッション間 | 単一セッション |\n| ストレージ | `memory/` 下の複数 .md ファイル | `session-memory//memory.md` |\n| 注入先 | system prompt | compact サマリ |\n| 目的 | セッション間の知識蓄積 | compact を越えたコンテキストの連続性 |\n\nsessionMemoryCompact(s08 で触れた仕組み)は Session Memory を活用:autoCompact の前に session memory ファイルを読み込み、内容が十分であれば(≥ 10K token、≥ 5 テキストメッセージ、≤ 40K token、`sessionMemoryCompact.ts:56-61`)、LLM を呼び出さずにサマリとして使用。\n\n### 実際の実装が教学版より複雑な点\n\n- **Feature flags**:記憶関連機能には複数の feature gate 層がある\n- **Team memory**:チーム共有記憶、`loadMemoryPrompt()` に専用パスあり(教学版では未カバー)\n- **KAIROS**:タイミング認識型の記憶抽出戦略、`loadMemoryPrompt()` の daily-log モード\n- **Prompt cache**:記憶注入は prompt cache の TTL を考慮する必要があり、毎ターン system prompt の大部分を書き直すことを避ける\n- **ファイルロック**:マルチプロセス時の並行制御\n- **Memory prefetch**:非同期プレフェッチ、メインフローをブロックしない\n\n### 教学版の簡略化は意図的\n\n- LLM side-query → LLM side-query + キーワードフォールバック:教学版は LLM 選択を維持し、フォールバックパスを追加\n- 記憶 JSON → Markdown + frontmatter:教学版は CC と一致\n- stop hook トリガー → `stop_reason != \"tool_use\"` 分岐:方向は一致\n- 4 層ゲート → ファイル数閾値:教学版には transcript システムやマルチセッションの概念がない\n- forked agent + 制限付き権限 → 直接呼び出し:教学版にはサブプロセス分離がない\n\n
\n\n\n" + "content": "# s09: Memory — 圧縮は詳細を失う、失わない層が必要\n\ns01 → ... → s07 → s08 → `s09` → [s10](/ja/s10) → s11 → ... → s20 → s21\n> *\"圧縮は詳細を失う、失わない層が必要\"* — ファイルストア + インデックス + オンデマンド読み込み。圧縮を越え、セッションを越えて。\n>\n> **Harness レイヤー**: 記憶 — 圧縮とセッションを越える知識の蓄積。\n\n---\n\n## 課題\n\ns08 の autoCompact は現在の目標、残りの作業、ユーザーの制約をサマリに保持するが、詳細は失われる:「タブでインデント、スペース不可」が「ユーザーにコードスタイルの好みあり」と簡略化される。そして新しいセッションを開始すると、サマリすらない。\n\nLLM には永続状態がなく、すべての情報はコンテキストウィンドウ内にある。コンテキストが満杯になれば圧縮され、圧縮は非可逆。圧縮に参加せず、セッションを越えて保持されるストレージ層が必要。\n\n---\n\n## ソリューション\n\n![Memory Overview](/course-assets/s09_memory/memory-overview.ja.svg)\n\ns08 の圧縮パイプラインを維持し、記憶に焦点を当てる。ストレージにはファイルシステムを採用:`.memory/` ディレクトリに各記憶を `.md` ファイルとして保存、YAML frontmatter(`name` / `description` / `type`)付き。ファイルが増えたらインデックスが必要:`MEMORY.md` に 1 行 1 リンクを記録し、SYSTEM に注入。\n\n重要な設計:インデックスは SYSTEM prompt に常駐(prompt cache でキャッシュ可能)、ファイル内容はオンデマンド注入(filename/description で現在の会話にマッチ、cache を破壊しない)。書き込みは 2 つのパス:ユーザーが明示的に「覚えて」と言うか、毎ターン終了後にバックグラウンドで抽出。ファイルが蓄積されたら、定期的に整理して重複排除。\n\n> **s08 との境界:** 圧縮は引き続き現在の会話と token 予算を担当する。記憶は圧縮を置き換えず、選んだ事実を会話の外に保存し、後から必要に応じて呼び戻す。\n\n4 種類の記憶、それぞれ異なる質問に答える:\n\n| タイプ | 何に答えるか | 例 |\n|--------|-------------|-----|\n| user | あなたは誰か | \"タブでスペース不可\" |\n| feedback | どう作業するか | \"DB をモックしない\" |\n| project | 何が起きているか | \"auth 書き直しはコンプライアンス主導\" |\n| reference | どこで探すか | \"パイプラインのバグは Linear INGEST\" |\n\n---\n\n## 仕組み\n\n![Memory Subsystems](/course-assets/s09_memory/memory-subsystems.ja.svg)\n\n### ストレージ:Markdown ファイル + インデックス\n\n各記憶は `.md` ファイル、YAML frontmatter でメタデータを記録:\n\n```markdown\n---\nname: user-preference-tabs\ndescription: User prefers tabs for indentation\ntype: user\n---\n\nUser prefers using tabs, not spaces, for indentation.\n**Why:** Consistency with existing codebase conventions.\n**How to apply:** Always use tabs when writing or editing files.\n```\n\n`MEMORY.md` はインデックス、1 行に 1 リンク:\n\n```markdown\n- [user-preference-tabs](user-preference-tabs.md) — User prefers tabs for indentation\n```\n\n新しい記憶を書き込むとインデックスを自動再構築:\n\n```python\ndef write_memory_file(name, mem_type, description, body):\n slug = name.lower().replace(\" \", \"-\")\n filepath = MEMORY_DIR / f\"{slug}.md\"\n filepath.write_text(\n f\"---\\nname: {name}\\ndescription: {description}\\ntype: {mem_type}\\n---\\n\\n{body}\\n\"\n )\n _rebuild_index()\n```\n\n### 読み込み:2 つのパス\n\n**パス 1:インデックスを SYSTEM に常駐。** `build_system()` は各ユーザーリクエストの開始時に 1 回だけ `MEMORY.md` を読み込み、記憶カタログを SYSTEM prompt に注入。記憶の抽出と整理はターン終了時にだけ実行されるため、同じユーザーリクエスト内で SYSTEM を繰り返し再構築する必要はない。\n\n**パス 2:関連記憶をオンデマンド注入。** 各ユーザーリクエストの開始時に、`load_memories()` は最近の会話と記憶カタログ(name + description)を LLM に軽量 side-query として送信し、関連するファイル名を選択、ファイル内容を読み込んで注入。上限 5 件でコストを制御。\n\n```python\ndef select_relevant_memories(messages, max_items=5):\n files = list_memory_files()\n if not files:\n return []\n\n # Build catalog: \"0: user-preference-tabs — User prefers tabs...\"\n catalog = \"\\n\".join(f\"{i}: {f['name']} — {f['description']}\" for i, f in enumerate(files))\n\n response = client.messages.create(model=MODEL, messages=[{\"role\": \"user\",\n \"content\": f\"Select relevant memory indices. Return JSON array.\\n\\n\"\n f\"Recent conversation:\\n{recent}\\n\\nMemory catalog:\\n{catalog}\"}],\n max_tokens=200)\n indices = json.loads(re.search(r'\\[.*?\\]', response.content[0].text).group())\n return [files[i][\"filename\"] for i in indices if 0 <= i < len(files)]\n```\n\nside-query が失敗した場合(API エラー、JSON パース失敗)、name + description のキーワードマッチにフォールバック。\n\n### 書き込み:毎ターン終了後の抽出\n\nユーザーが毎回「これを覚えて」と言うわけではない。好みは通常、通常の会話の中に散らばっている:「タブの方がスペースより良い」「これからはシングルクォートにしよう」。\n\n`extract_memories()` は各ターン終了時に実行、モデルが tool_use なしで停止した場合にトリガー(会話が自然な区切りに達したことを示す):\n\n```python\n# In agent_loop:\nif response.stop_reason != \"tool_use\":\n extract_memories(messages) # 最近の会話から新しい記憶を抽出\n consolidate_memories() # 整理が必要かチェック\n return\n```\n\n抽出前に既存の記憶を確認し、重複を回避。抽出プロンプトは LLM に `{name, type, description, body}` の JSON 配列を要求、本当に新しい情報がある場合のみファイルに書き込む。\n\n```python\ndef extract_memories(messages):\n dialogue = format_recent_messages(messages[-10:])\n existing = \"\\n\".join(f\"- {m['name']}: {m['description']}\" for m in list_memory_files())\n\n prompt = (\n \"Extract user preferences, constraints, or project facts.\\n\"\n \"Return JSON array: [{name, type, description, body}].\\n\"\n \"If nothing new or already covered, return [].\\n\\n\"\n f\"Existing memories:\\n{existing}\\n\\nDialogue:\\n{dialogue[:4000]}\"\n )\n # ... parse response, write files ...\n```\n\n### 整理:低頻度の重複排除\n\n記憶ファイルは蓄積される。`consolidate_memories()` はファイル数が閾値(デフォルト 10)に達した時にトリガー、LLM に重複排除、矛盾の統合、古い記憶の剪定を依頼:\n\n```python\nCONSOLIDATE_THRESHOLD = 10\n\ndef consolidate_memories():\n files = list_memory_files()\n if len(files) < CONSOLIDATE_THRESHOLD:\n return # 少なすぎる、整理する価値なし\n # Send all memories to LLM, get back deduplicated list\n # Replace all files with consolidated results\n```\n\n### Memory に保存するもの\n\nMemory はセッションを越えて有用な情報を保存する:ユーザーの好み、繰り返し出るフィードバック、プロジェクト背景、よく使う入口、調査の手がかりなど。「あとでまた使うもの」を対象にし、インデックス + オンデマンド読み込みで現在の会話に戻す。\n\nsession memory は 1 つのセッション内の連続性を扱う:compact 後も現在の会話に残すべき文脈を保持する。両者は役割が分かれている。Memory は長期知識を扱い、session memory は現在のセッションを compact 越しにつなぐ。\n\n---\n\n## s08 からの変更点\n\n| コンポーネント | 変更前 (s08) | 変更後 (s09) |\n|-----------|-------------|-------------|\n| 記憶能力 | なし(圧縮後、好みはサマリと共に劣化) | ストレージ + 読み込み + 抽出 + 整理 |\n| 新規関数 | — | write_memory_file, select_relevant_memories, load_memories, extract_memories, consolidate_memories |\n| ストレージ | — | .memory/MEMORY.md インデックス + .memory/*.md ファイル |\n| ツール | bash, read, write, edit, glob, todo_write, task, load_skill, compact (9) | bash, read_file, write_file, edit_file, glob, task (6) |\n| ループ | 毎ターン圧縮のみ | 記憶注入 + 圧縮 + ターン終了後の抽出 + 定期整理 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s09_memory/code.py\n```\n\n以下のプロンプトを試してみてください(複数ターンに分けて入力し、記憶の蓄積と読み込みを観察):\n\n1. `I prefer using tabs for indentation, not spaces. Remember that.`\n2. `Create a Python file called test.py`(Agent がタブを使用したか観察)\n3. `What did I tell you about my preferences?`(Agent が覚えているか観察)\n4. `I also prefer single quotes over double quotes for strings.`\n\n観察のポイント:各ターン終了後に `[Memory: extracted N new memories]` が表示されるか?`.memory/` ディレクトリに `.md` ファイルが生成されたか?`MEMORY.md` インデックスが更新されたか?新しい会話で Agent が以前の記憶を自動的に読み込んだか?\n\n---\n\n## 次へ\n\n記憶、圧縮、ツールはすべて揃った。しかし system prompt はまだハードコードされた文字列。新しいツールを追加するには手動で説明を書き、プロジェクトを変えるにはプロンプト全体を書き直す。プロンプトは実行時に組み立てられるべき。\n\ns10 System Prompt → セグメント + 実行時組み立て。異なるプロジェクト、異なるツール、異なるプロンプト。\n\n\n\n" }, { "version": "s10", "locale": "en", "title": "s10: Context Assembly — Build Model Input at Runtime", - "content": "# s10: Context Assembly — Build Model Input at Runtime\n\ns01 → ... → s08 → s09 → `s10` → [s11](/en/s11) → s12 → ... → s20 → s21 → s22\n> *\"Model input is assembled, not hardcoded\"* — Stable sections + runtime state + caching.\n>\n> **Harness Layer**: Context assembly — turn stable instructions and dynamic state into model input.\n\n---\n\n## The Problem\n\nFrom s01 to s09, the system prompt was always one hardcoded line:\n\n```python\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks.\"\n```\n\nThat worked for s01 — only bash, read, write. But by s09, the agent has memory, compression, skill loading. The prompt needs to describe more and more capabilities:\n\n```python\nSYSTEM = (\n f\"You are a coding agent at {WORKDIR}. \"\n \"Use tools to solve tasks. Act, don't explain. \"\n \"Before starting any multi-step task, use todo_write. \"\n \"Skills are available via list_skills and load_skill. \"\n \"Relevant memories are injected below when available. \"\n # ... add a capability, add a line\n)\n```\n\nThree problems:\n\n1. **Switching projects requires rewriting the entire prompt** — no way to know what to change and what to keep\n2. **One change can break others** — adding a tool description might conflict with earlier instructions\n3. **Every request carries everything** — even when the current conversation doesn't need certain sections, they waste tokens\n\nThe system prompt should be a configuration assembled at runtime based on current state: which tools are enabled, which context is visible, which memories are relevant, and which content must remain stable to hit prompt cache.\n\n---\n\n## The Solution\n\n![System Prompt Overview](/course-assets/s10_system_prompt/system-prompt-overview.en.svg)\n\ns10 is a short bridge between context management and recovery. It does not add another storage system or merge s08 with s09. It shows where their outputs meet the model boundary: split the hardcoded `SYSTEM` into independent sections, assemble them from real runtime state, and cache the result.\n\nFour sections, two loading strategies:\n\n| Section | Strategy | Content | Condition |\n|---------|----------|---------|-----------|\n| identity | always | who you are, how to work | always present |\n| tools | always | available tool list | `enabled_tools` |\n| workspace | always | working directory | always present |\n| memory | on-demand | relevant memory content | whether `.memory/MEMORY.md` exists |\n\nKey design: whether a section loads depends on real state (tools exist, files exist), not keywords in messages.\n\n---\n\n## How It Works\n\n### PROMPT_SECTIONS: Topic-Keyed Fragments\n\nSplit the monolithic string into a dictionary, each key is a topic:\n\n```python\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n```\n\nEach section is maintained independently. Changing `tools` doesn't affect `identity`; adding `memory` doesn't touch `workspace`.\n\n### assemble_system_prompt: On-Demand Assembly\n\nNot every section is needed every turn. No memory files? Loading the memory section just wastes tokens. Assembly is based on real state in context:\n\n```python\ndef assemble_system_prompt(context: dict) -> str:\n sections = []\n\n # Always loaded\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # Dynamic — tools and workspace from context\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # On-demand — based on real state, not keywords\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n```\n\n\"Always loaded\" sections are needed every turn: identity, tools, workspace. \"On-demand\" sections are only useful under specific conditions.\n\nWhy not load everything? Tokens have cost (system prompt is billed every turn), and fewer instructions means more focused output (irrelevant instructions are noise).\n\n### get_system_prompt: Cache to Avoid Re-Assembly\n\nWhen context hasn't changed (multiple LLM calls in the same turn with the same context), re-assembling is wasteful. Use deterministic serialization to detect changes and return cached result:\n\n```python\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n```\n\n`json.dumps` instead of `hash()`: Python's built-in `hash()` has process randomization (unsuitable for stable cache keys) and throws `unhashable type` on nested dicts/lists.\n\nNote: this cache only avoids redundant string assembly within a process. It's not the same as CC's API prompt cache, which uses `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` to separate static and dynamic parts — the static parts hit global cache and don't invalidate when dynamic content changes.\n\n### context: Real State, Not Keyword Guessing\n\nContext reflects the actual runtime state:\n\n```python\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n```\n\n`enabled_tools` lists actually registered tools. `memories` checks whether `.memory/MEMORY.md` exists. Section loading is based on this real state, not searching for keywords in messages.\n\n### Putting It Together\n\n```python\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n # ... tool execution ...\n context = update_context(context, messages)\n system = get_system_prompt(context)\n```\n\nAt the start of each loop iteration, get the system prompt. If context changed, re-assemble; if not, return cached version.\n\n---\n\n## Changes From s09\n\n| Component | Before (s09) | After (s10) |\n|-----------|-------------|-------------|\n| prompt | Hardcoded SYSTEM string | PROMPT_SECTIONS + assemble_system_prompt |\n| caching | None | get_system_prompt (json.dumps detection + cache) |\n| new functions | — | assemble_system_prompt, get_system_prompt, update_context |\n| tools | bash, read_file, write_file (3) | bash, read_file, write_file (3) — unchanged |\n| loop | Uses fixed SYSTEM | Uses get_system_prompt(context) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s10_system_prompt/code.py\n```\n\nSafety note: this focused teaching script still executes the model's `bash` string with `shell=True` and omits s03's permission gate. Run it only in a disposable workspace; production harnesses must restore permission and sandbox boundaries.\n\nWhat to watch for:\n\n1. Output shows which sections were loaded (`[assembled] sections: ...` label)\n2. Cache hits show `[cache hit]` during continued conversation\n3. Creating `.memory/MEMORY.md` makes the memory section appear on the next turn\n\nTry these prompts:\n\n1. `Read the file README.md` (observe the three always-loaded sections)\n2. `Create a file called .memory/MEMORY.md with content \"- [test](test.md) — test memory\"` (write a memory index)\n3. `Read the file code.py` (observe whether the memory section appears)\n\n---\n\n## What's Next\n\nThe model input can now be assembled at runtime. But the agent still crashes on errors. Network hiccups, API rate limits, truncated output, context overflow — these aren't bugs, they're normal.\n\ns11 Error Recovery → four recovery paths. Upgrade tokens, compress context, exponential backoff, switch models.\n\n\n" + "content": "# s10: Context Assembly — Build Model Input at Runtime\n\ns01 → ... → s08 → s09 → `s10` → [s11](/en/s11) → s12 → ... → s20 → s21\n> *\"Model input is assembled, not hardcoded\"* — Stable sections + runtime state + caching.\n>\n> **Harness Layer**: Context assembly — turn stable instructions and dynamic state into model input.\n\n---\n\n## The Problem\n\nFrom s01 to s09, the system prompt was always one hardcoded line:\n\n```python\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks.\"\n```\n\nThat worked for s01 — only bash, read, write. But by s09, the agent has memory, compression, skill loading. The prompt needs to describe more and more capabilities:\n\n```python\nSYSTEM = (\n f\"You are a coding agent at {WORKDIR}. \"\n \"Use tools to solve tasks. Act, don't explain. \"\n \"Before starting any multi-step task, use todo_write. \"\n \"Skills are available via list_skills and load_skill. \"\n \"Relevant memories are injected below when available. \"\n # ... add a capability, add a line\n)\n```\n\nThree problems:\n\n1. **Switching projects requires rewriting the entire prompt** — no way to know what to change and what to keep\n2. **One change can break others** — adding a tool description might conflict with earlier instructions\n3. **Every request carries everything** — even when the current conversation doesn't need certain sections, they waste tokens\n\nThe system prompt should be a configuration assembled at runtime based on current state: which tools are enabled, which context is visible, which memories are relevant, and which content must remain stable to hit prompt cache.\n\n---\n\n## The Solution\n\n![System Prompt Overview](/course-assets/s10_system_prompt/system-prompt-overview.en.svg)\n\ns10 is a short bridge between context management and recovery. It does not add another storage system or merge s08 with s09. It shows where their outputs meet the model boundary: split the hardcoded `SYSTEM` into independent sections, assemble them from real runtime state, and cache the result.\n\nFour sections, two loading strategies:\n\n| Section | Strategy | Content | Condition |\n|---------|----------|---------|-----------|\n| identity | always | who you are, how to work | always present |\n| tools | always | available tool list | `enabled_tools` |\n| workspace | always | working directory | always present |\n| memory | on-demand | relevant memory content | whether `.memory/MEMORY.md` exists |\n\nKey design: whether a section loads depends on real state (tools exist, files exist), not keywords in messages.\n\n---\n\n## How It Works\n\n### PROMPT_SECTIONS: Topic-Keyed Fragments\n\nSplit the monolithic string into a dictionary, each key is a topic:\n\n```python\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n```\n\nEach section is maintained independently. Changing `tools` doesn't affect `identity`; adding `memory` doesn't touch `workspace`.\n\n### assemble_system_prompt: On-Demand Assembly\n\nNot every section is needed every turn. No memory files? Loading the memory section just wastes tokens. Assembly is based on real state in context:\n\n```python\ndef assemble_system_prompt(context: dict) -> str:\n sections = []\n\n # Always loaded\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # Dynamic — tools and workspace from context\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # On-demand — based on real state, not keywords\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n```\n\n\"Always loaded\" sections are needed every turn: identity, tools, workspace. \"On-demand\" sections are only useful under specific conditions.\n\nWhy not load everything? Tokens have cost (system prompt is billed every turn), and fewer instructions means more focused output (irrelevant instructions are noise).\n\n### get_system_prompt: Cache to Avoid Re-Assembly\n\nWhen context hasn't changed (multiple LLM calls in the same turn with the same context), re-assembling is wasteful. Use deterministic serialization to detect changes and return cached result:\n\n```python\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n```\n\n`json.dumps` instead of `hash()`: Python's built-in `hash()` has process randomization (unsuitable for stable cache keys) and throws `unhashable type` on nested dicts/lists.\n\n### context: Real State, Not Keyword Guessing\n\nContext reflects the actual runtime state:\n\n```python\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n```\n\n`enabled_tools` lists actually registered tools. `memories` checks whether `.memory/MEMORY.md` exists. Section loading is based on this real state, not searching for keywords in messages.\n\n### Putting It Together\n\n```python\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n # ... tool execution ...\n context = update_context(context, messages)\n system = get_system_prompt(context)\n```\n\nAt the start of each loop iteration, get the system prompt. If context changed, re-assemble; if not, return cached version.\n\n---\n\n## Changes From s09\n\n| Component | Before (s09) | After (s10) |\n|-----------|-------------|-------------|\n| prompt | Hardcoded SYSTEM string | PROMPT_SECTIONS + assemble_system_prompt |\n| caching | None | get_system_prompt (json.dumps detection + cache) |\n| new functions | — | assemble_system_prompt, get_system_prompt, update_context |\n| tools | bash, read_file, write_file (3) | bash, read_file, write_file (3) — unchanged |\n| loop | Uses fixed SYSTEM | Uses get_system_prompt(context) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s10_system_prompt/code.py\n```\n\n**Safety note**: The script executes model-generated `bash` strings with `shell=True` and does not include the permission gate from s03. Run it only in a disposable workspace.\n\nWhat to watch for:\n\n1. Output shows which sections were loaded (`[assembled] sections: ...` label)\n2. Cache hits show `[cache hit]` during continued conversation\n3. Creating `.memory/MEMORY.md` makes the memory section appear on the next turn\n\nTry these prompts:\n\n1. `Read the file README.md` (observe the three always-loaded sections)\n2. `Create a file called .memory/MEMORY.md with content \"- [test](test.md) — test memory\"` (write a memory index)\n3. `Read the file code.py` (observe whether the memory section appears)\n\n---\n\n## What's Next\n\nThe model input can now be assembled at runtime. But the agent still crashes on errors. Network hiccups, API rate limits, truncated output, context overflow — these aren't bugs, they're normal.\n\ns11 Error Recovery → four recovery paths. Upgrade tokens, compress context, exponential backoff, switch models.\n\n\n" }, { "version": "s10", "locale": "zh", "title": "s10: Context Assembly — 在运行时组装模型输入", - "content": "# s10: Context Assembly — 在运行时组装模型输入\n\ns01 → ... → s08 → s09 → `s10` → [s11](/zh/s11) → s12 → ... → s20 → s21 → s22\n> *\"模型输入是组装出来的,不是写死的\"* — 稳定分段 + 运行时状态 + 缓存。\n>\n> **Harness 层**: 上下文组装 — 把稳定指令和动态状态组成模型输入。\n\n---\n\n## 问题\n\n从 s01 到 s09,system prompt 都是一行硬编码:\n\n```python\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks.\"\n```\n\ns01 够用,只有 bash、read、write 三个工具。但到 s09,Agent 已经有记忆、有压缩、有技能加载。prompt 该提的能力越来越多:\n\n```python\nSYSTEM = (\n f\"You are a coding agent at {WORKDIR}. \"\n \"Use tools to solve tasks. Act, don't explain. \"\n \"Before starting any multi-step task, use todo_write. \"\n \"Skills are available via list_skills and load_skill. \"\n \"Relevant memories are injected below when available. \"\n # ... 加一个能力就多一段\n)\n```\n\n三个问题:\n\n1. **换项目要重写整个 prompt**,不知道哪些该改、哪些该留\n2. **修改一处可能影响全局**,加一段工具描述可能跟前面的指令冲突\n3. **每次请求都带全部内容**,即使当前对话用不到某些段落也浪费 token\n\nSystem prompt 应该是运行时根据当前状态组装的配置:哪些工具启用、哪些上下文可见、哪些记忆相关、哪些内容必须保持稳定以命中 prompt cache。\n\n---\n\n## 解决方案\n\n![System Prompt Overview](/course-assets/s10_system_prompt/system-prompt-overview.svg)\n\ns10 是上下文管理与错误恢复之间的一节短桥接课。它不增加新的存储系统,也不把 s08 与 s09 合并;它只展示两者的输出如何在模型边界汇合:把硬编码的 `SYSTEM` 拆成独立段落(section),运行时根据真实状态按需拼接,并缓存结果。\n\n四个 section,两种加载策略:\n\n| Section | 加载策略 | 内容 | 判断依据 |\n|---------|---------|------|---------|\n| identity | 始终 | 你是谁、怎么做事 | 始终存在 |\n| tools | 始终 | 可用工具列表 | `enabled_tools` |\n| workspace | 始终 | 工作目录 | 始终存在 |\n| memory | 按需 | 相关记忆内容 | `.memory/MEMORY.md` 是否存在 |\n\n关键设计:section 是否加载取决于真实状态(工具是否存在、文件是否存在),不是消息里的关键词。\n\n---\n\n## 工作原理\n\n### PROMPT_SECTIONS: 分段定义\n\n把一大段字符串拆成字典,每个 key 是一个主题:\n\n```python\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n```\n\n每个 section 独立维护。修改 `tools` 不影响 `identity`,新增 `memory` 不动 `workspace`。\n\n### assemble_system_prompt: 按需拼接\n\n不是所有 section 每次都需要。当前没有记忆文件,加载 memory section 只是浪费 token。根据 context 的真实状态决定加载哪些:\n\n```python\ndef assemble_system_prompt(context: dict) -> str:\n sections = []\n\n # 始终加载\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # 从 context 动态获取 tools 和 workspace\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # 按需加载 — 基于真实状态,不是关键词\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n```\n\n\"始终加载\"的是每轮都需要的:身份、工具、工作目录。\"按需加载\"的只在特定条件下才有用。\n\n为什么不全加载?token 有成本(system prompt 每轮计费),信息越少 LLM 越专注(无关指令是噪音)。\n\n### get_system_prompt: 缓存避免重复拼接\n\n上下文没变时(同一轮对话的多次 LLM 调用,context 相同),重新拼接是浪费。用确定性序列化检测变化,命中缓存直接返回:\n\n```python\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n```\n\n用 `json.dumps` 而不是 `hash()`:Python 内置 `hash()` 有进程随机化,不适合做稳定 cache key,而且遇到 list/dict 会报 `unhashable type`。\n\n注意:这里的缓存只是\"避免重复拼接字符串\",和 CC 的 API prompt cache 不是一回事。CC 的 prompt cache 通过 `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` 分隔静态和动态部分,静态部分命中 global cache,不因动态内容变化而失效。\n\n### context: 真实状态,不是关键词猜测\n\ncontext 反映当前运行态的真实状态:\n\n```python\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n```\n\n`enabled_tools` 列出实际注册的工具。`memories` 检查 `.memory/MEMORY.md` 是否存在。section 加载基于这些真实状态,不在消息里搜关键词。\n\n### 合起来跑\n\n```python\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n # ... 工具执行 ...\n context = update_context(context, messages)\n system = get_system_prompt(context)\n```\n\n每轮循环开头拿一次 system prompt。context 变了就重新组装,没变就返回缓存。\n\n---\n\n## 相对 s09 的变更\n\n| 组件 | 之前 (s09) | 之后 (s10) |\n|------|-----------|-----------|\n| prompt | 硬编码 SYSTEM 字符串 | PROMPT_SECTIONS + assemble_system_prompt |\n| 缓存 | 无 | get_system_prompt(json.dumps 检测 + 缓存) |\n| 新函数 | — | assemble_system_prompt, get_system_prompt, update_context |\n| 工具 | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 不变 |\n| 循环 | 用固定 SYSTEM | 用 get_system_prompt(context) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s10_system_prompt/code.py\n```\n\n安全说明:这份聚焦教学脚本仍用 `shell=True` 执行模型给出的 `bash` 字符串,并省略了 s03 的权限闸门。只在可丢弃工作区运行;生产 harness 必须恢复权限与沙箱边界。\n\n观察重点:\n\n1. 输出中能看到哪些 section 被加载了(`[assembled] sections: ...` 标签)\n2. 连续对话时,缓存命中显示 `[cache hit]`\n3. 创建 `.memory/MEMORY.md` 文件后,下一轮 memory section 自动加载\n\n试试这些 prompt:\n\n1. `Read the file README.md`(观察始终加载的三个 section)\n2. `Create a file called .memory/MEMORY.md with content \"- [test](test.md) — test memory\"`(写入记忆索引)\n3. `Read the file code.py`(观察 memory section 是否出现)\n\n---\n\n## 接下来\n\n模型输入可以在运行时组装了,但 Agent 碰到错误还是会崩。网络抖动、API 限流、输出被截断、上下文超限,这些不是 bug,是常态。\n\ns11 Error Recovery → 四条恢复路径。升级 token、压缩上下文、指数退避、切换模型。\n\n\n" + "content": "# s10: Context Assembly — 在运行时组装模型输入\n\ns01 → ... → s08 → s09 → `s10` → [s11](/zh/s11) → s12 → ... → s20 → s21\n> *\"模型输入是组装出来的,不是写死的\"* — 稳定分段 + 运行时状态 + 缓存。\n>\n> **Harness 层**: 上下文组装 — 把稳定指令和动态状态组成模型输入。\n\n---\n\n## 问题\n\n从 s01 到 s09,system prompt 都是一行硬编码:\n\n```python\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks.\"\n```\n\ns01 够用,只有 bash、read、write 三个工具。但到 s09,Agent 已经有记忆、有压缩、有技能加载。prompt 该提的能力越来越多:\n\n```python\nSYSTEM = (\n f\"You are a coding agent at {WORKDIR}. \"\n \"Use tools to solve tasks. Act, don't explain. \"\n \"Before starting any multi-step task, use todo_write. \"\n \"Skills are available via list_skills and load_skill. \"\n \"Relevant memories are injected below when available. \"\n # ... 加一个能力就多一段\n)\n```\n\n三个问题:\n\n1. **换项目要重写整个 prompt**,不知道哪些该改、哪些该留\n2. **修改一处可能影响全局**,加一段工具描述可能跟前面的指令冲突\n3. **每次请求都带全部内容**,即使当前对话用不到某些段落也浪费 token\n\nSystem prompt 应该是运行时根据当前状态组装的配置:哪些工具启用、哪些上下文可见、哪些记忆相关、哪些内容必须保持稳定以命中 prompt cache。\n\n---\n\n## 解决方案\n\n![System Prompt Overview](/course-assets/s10_system_prompt/system-prompt-overview.svg)\n\ns10 是上下文管理与错误恢复之间的一节短桥接课。它不增加新的存储系统,也不把 s08 与 s09 合并;它只展示两者的输出如何在模型边界汇合:把硬编码的 `SYSTEM` 拆成独立段落(section),运行时根据真实状态按需拼接,并缓存结果。\n\n四个 section,两种加载策略:\n\n| Section | 加载策略 | 内容 | 判断依据 |\n|---------|---------|------|---------|\n| identity | 始终 | 你是谁、怎么做事 | 始终存在 |\n| tools | 始终 | 可用工具列表 | `enabled_tools` |\n| workspace | 始终 | 工作目录 | 始终存在 |\n| memory | 按需 | 相关记忆内容 | `.memory/MEMORY.md` 是否存在 |\n\n关键设计:section 是否加载取决于真实状态(工具是否存在、文件是否存在),不是消息里的关键词。\n\n---\n\n## 工作原理\n\n### PROMPT_SECTIONS: 分段定义\n\n把一大段字符串拆成字典,每个 key 是一个主题:\n\n```python\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n```\n\n每个 section 独立维护。修改 `tools` 不影响 `identity`,新增 `memory` 不动 `workspace`。\n\n### assemble_system_prompt: 按需拼接\n\n不是所有 section 每次都需要。当前没有记忆文件,加载 memory section 只是浪费 token。根据 context 的真实状态决定加载哪些:\n\n```python\ndef assemble_system_prompt(context: dict) -> str:\n sections = []\n\n # 始终加载\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # 从 context 动态获取 tools 和 workspace\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # 按需加载 — 基于真实状态,不是关键词\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n```\n\n\"始终加载\"的是每轮都需要的:身份、工具、工作目录。\"按需加载\"的只在特定条件下才有用。\n\n为什么不全加载?token 有成本(system prompt 每轮计费),信息越少 LLM 越专注(无关指令是噪音)。\n\n### get_system_prompt: 缓存避免重复拼接\n\n上下文没变时(同一轮对话的多次 LLM 调用,context 相同),重新拼接是浪费。用确定性序列化检测变化,命中缓存直接返回:\n\n```python\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n```\n\n用 `json.dumps` 而不是 `hash()`:Python 内置 `hash()` 有进程随机化,不适合做稳定 cache key,而且遇到 list/dict 会报 `unhashable type`。\n\n### context: 真实状态,不是关键词猜测\n\ncontext 反映当前运行态的真实状态:\n\n```python\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n```\n\n`enabled_tools` 列出实际注册的工具。`memories` 检查 `.memory/MEMORY.md` 是否存在。section 加载基于这些真实状态,不在消息里搜关键词。\n\n### 合起来跑\n\n```python\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n # ... 工具执行 ...\n context = update_context(context, messages)\n system = get_system_prompt(context)\n```\n\n每轮循环开头拿一次 system prompt。context 变了就重新组装,没变就返回缓存。\n\n---\n\n## 相对 s09 的变更\n\n| 组件 | 之前 (s09) | 之后 (s10) |\n|------|-----------|-----------|\n| prompt | 硬编码 SYSTEM 字符串 | PROMPT_SECTIONS + assemble_system_prompt |\n| 缓存 | 无 | get_system_prompt(json.dumps 检测 + 缓存) |\n| 新函数 | — | assemble_system_prompt, get_system_prompt, update_context |\n| 工具 | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 不变 |\n| 循环 | 用固定 SYSTEM | 用 get_system_prompt(context) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s10_system_prompt/code.py\n```\n\n**安全说明**:脚本使用 `shell=True` 执行模型生成的 `bash` 字符串,并未接入 s03 的权限闸门。请只在可丢弃的工作区中运行。\n\n观察重点:\n\n1. 输出中能看到哪些 section 被加载了(`[assembled] sections: ...` 标签)\n2. 连续对话时,缓存命中显示 `[cache hit]`\n3. 创建 `.memory/MEMORY.md` 文件后,下一轮 memory section 自动加载\n\n试试这些 prompt:\n\n1. `Read the file README.md`(观察始终加载的三个 section)\n2. `Create a file called .memory/MEMORY.md with content \"- [test](test.md) — test memory\"`(写入记忆索引)\n3. `Read the file code.py`(观察 memory section 是否出现)\n\n---\n\n## 接下来\n\n模型输入可以在运行时组装了,但 Agent 碰到错误还是会崩。网络抖动、API 限流、输出被截断、上下文超限,这些不是 bug,是常态。\n\ns11 Error Recovery → 四条恢复路径。升级 token、压缩上下文、指数退避、切换模型。\n\n\n" }, { "version": "s10", "locale": "ja", "title": "s10: Context Assembly — 実行時にモデル入力を組み立てる", - "content": "# s10: Context Assembly — 実行時にモデル入力を組み立てる\n\ns01 → ... → s08 → s09 → `s10` → [s11](/ja/s11) → s12 → ... → s20 → s21 → s22\n> *\"モデル入力は組み立てるもの、固定するものではない\"* — 安定セクション + 実行時状態 + キャッシュ。\n>\n> **Harness レイヤー**: コンテキスト組み立て — 安定した指示と動的状態をモデル入力にまとめる。\n\n---\n\n## 課題\n\ns01 から s09 まで、system prompt は常に 1 行のハードコード:\n\n```python\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks.\"\n```\n\ns01 では十分だった。bash、read、write の 3 ツールのみ。しかし s09 では、Agent に記憶、圧縮、スキル読み込みがある。prompt が説明すべき能力が増え続ける:\n\n```python\nSYSTEM = (\n f\"You are a coding agent at {WORKDIR}. \"\n \"Use tools to solve tasks. Act, don't explain. \"\n \"Before starting any multi-step task, use todo_write. \"\n \"Skills are available via list_skills and load_skill. \"\n \"Relevant memories are injected below when available. \"\n # ... 能力を追加するたびに 1 行増える\n)\n```\n\n3 つの問題:\n\n1. **プロジェクトを変えるには prompt 全体を書き直す**必要がある。何を変え、何を残すべきか不明\n2. **一箇所の変更が全体に影響する**。ツール説明を追加すると、前の指示と矛盾する可能性\n3. **毎回のリクエストが全内容を送信する**。現在の会話で不要なセクションも token を無駄に消費\n\nSystem prompt は、実行時の現在状態に基づいて組み立てられる設定であるべき:どのツールが有効か、どのコンテキストが可視か、どの記憶が関連するか、どの内容を prompt cache に命中させるために安定させるべきか。\n\n---\n\n## ソリューション\n\n![System Prompt Overview](/course-assets/s10_system_prompt/system-prompt-overview.ja.svg)\n\ns10 はコンテキスト管理とエラー回復をつなぐ短い橋渡しセッションである。新しいストレージを追加せず、s08 と s09 も統合しない。両者の出力がモデル境界でどう合流するかを示す:ハードコードされた `SYSTEM` を独立セクションに分割し、実際の実行時状態から組み立て、結果をキャッシュする。\n\n4 つのセクション、2 つの読み込み戦略:\n\n| セクション | 戦略 | 内容 | 判断基準 |\n|-----------|------|------|---------|\n| identity | 常に | あなたは誰か、どう作業するか | 常に存在 |\n| tools | 常に | 利用可能ツール一覧 | `enabled_tools` |\n| workspace | 常に | 作業ディレクトリ | 常に存在 |\n| memory | オンデマンド | 関連記憶内容 | `.memory/MEMORY.md` が存在するか |\n\n重要な設計:セクションをロードするかどうかは実際の状態(ツールが存在するか、ファイルが存在するか)で決まり、メッセージ内のキーワードではない。\n\n---\n\n## 仕組み\n\n### PROMPT_SECTIONS: トピック別フラグメント\n\n単一の文字列を辞書に分割、各キーがトピック:\n\n```python\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n```\n\n各セクションは独立して管理。`tools` を変更しても `identity` に影響しない。`memory` を追加しても `workspace` はそのまま。\n\n### assemble_system_prompt: オンデマンド組み立て\n\nすべてのセクションが毎ターン必要なわけではない。記憶ファイルがなければ、memory セクションをロードしても token の無駄。context の実際の状態に基づいて組み立てる:\n\n```python\ndef assemble_system_prompt(context: dict) -> str:\n sections = []\n\n # 常にロード\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # context から動的に tools と workspace を取得\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # オンデマンド — 実際の状態に基づく、キーワードではない\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n```\n\n「常にロード」は毎ターン必要なもの:アイデンティティ、ツール、作業ディレクトリ。「オンデマンド」は特定条件下でのみ有用。\n\nなぜ全部ロードしないのか?token にはコストがあり(system prompt は毎ターン課金)、情報が少ないほど LLM は集中する(無関係な指示はノイズ)。\n\n### get_system_prompt: キャッシュで再組み立てを回避\n\nコンテキストが変わっていない時(同じターン内で複数の LLM 呼び出し、context が同じ)、再組み立ては無駄。確定的シリアライズで変化を検出し、キャッシュヒット時は即座に返却:\n\n```python\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n```\n\n`hash()` ではなく `json.dumps` を使用:Python 組み込みの `hash()` にはプロセスランダム化があり(安定したキャッシュキーに不適切)、list/dict で `unhashable type` エラーになる。\n\n注意:このキャッシュは「プロセス内での文字列再組み立ての回避」のみ。CC の API prompt cache とは別物。CC の prompt cache は `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` で静的/動的部分を分離し、静的部分が global cache に命中する。動的内容が変化しても静的部分は無効化されない。\n\n### context: 実際の状態、キーワード推測ではない\n\ncontext は現在の実行時状態の実際の状態を反映:\n\n```python\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n```\n\n`enabled_tools` は実際に登録されたツールを一覧。`memories` は `.memory/MEMORY.md` が存在するかを確認。セクションの読み込みはこの実際の状態に基づき、メッセージ内のキーワード検索ではない。\n\n### 組み合わせて実行\n\n```python\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n # ... ツール実行 ...\n context = update_context(context, messages)\n system = get_system_prompt(context)\n```\n\n各ループ反復の開始時に system prompt を取得。context が変わっていれば再組み立て、変わっていなければキャッシュを返却。\n\n---\n\n## s09 からの変更点\n\n| コンポーネント | 変更前 (s09) | 変更後 (s10) |\n|-----------|-------------|-------------|\n| prompt | ハードコード SYSTEM 文字列 | PROMPT_SECTIONS + assemble_system_prompt |\n| キャッシュ | なし | get_system_prompt(json.dumps 検出 + キャッシュ) |\n| 新規関数 | — | assemble_system_prompt, get_system_prompt, update_context |\n| ツール | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 変更なし |\n| ループ | 固定 SYSTEM を使用 | get_system_prompt(context) を使用 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s10_system_prompt/code.py\n```\n\n安全上の注意:この集中教材はモデルが渡す `bash` 文字列を `shell=True` で実行し、s03 の permission gate を省略している。破棄可能な workspace だけで実行し、本番 harness では permission と sandbox の境界を戻すこと。\n\n観察のポイント:\n\n1. 出力にロードされたセクションが表示される(`[assembled] sections: ...` ラベル)\n2. 継続会話でキャッシュヒット時は `[cache hit]` と表示\n3. `.memory/MEMORY.md` を作成すると、次のターンで memory セクションが自動ロード\n\n以下のプロンプトを試してみてください:\n\n1. `Read the file README.md`(常にロードされる 3 つのセクションを観察)\n2. `Create a file called .memory/MEMORY.md with content \"- [test](test.md) — test memory\"`(記憶インデックスを書き込み)\n3. `Read the file code.py`(memory セクションが表示されるか観察)\n\n---\n\n## 次へ\n\nモデル入力を実行時に組み立てられるようになった。しかし Agent はエラーでまだクラッシュする。ネットワークの不安定性、API レート制限、出力の切り詰め、コンテキスト超過、これらはバグではなく日常。\n\ns11 Error Recovery → 4 つのリカバリパス。token のアップグレード、コンテキスト圧縮、指数バックオフ、モデル切り替え。\n\n\n" + "content": "# s10: Context Assembly — 実行時にモデル入力を組み立てる\n\ns01 → ... → s08 → s09 → `s10` → [s11](/ja/s11) → s12 → ... → s20 → s21\n> *\"モデル入力は組み立てるもの、固定するものではない\"* — 安定セクション + 実行時状態 + キャッシュ。\n>\n> **Harness レイヤー**: コンテキスト組み立て — 安定した指示と動的状態をモデル入力にまとめる。\n\n---\n\n## 課題\n\ns01 から s09 まで、system prompt は常に 1 行のハードコード:\n\n```python\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks.\"\n```\n\ns01 では十分だった。bash、read、write の 3 ツールのみ。しかし s09 では、Agent に記憶、圧縮、スキル読み込みがある。prompt が説明すべき能力が増え続ける:\n\n```python\nSYSTEM = (\n f\"You are a coding agent at {WORKDIR}. \"\n \"Use tools to solve tasks. Act, don't explain. \"\n \"Before starting any multi-step task, use todo_write. \"\n \"Skills are available via list_skills and load_skill. \"\n \"Relevant memories are injected below when available. \"\n # ... 能力を追加するたびに 1 行増える\n)\n```\n\n3 つの問題:\n\n1. **プロジェクトを変えるには prompt 全体を書き直す**必要がある。何を変え、何を残すべきか不明\n2. **一箇所の変更が全体に影響する**。ツール説明を追加すると、前の指示と矛盾する可能性\n3. **毎回のリクエストが全内容を送信する**。現在の会話で不要なセクションも token を無駄に消費\n\nSystem prompt は、実行時の現在状態に基づいて組み立てられる設定であるべき:どのツールが有効か、どのコンテキストが可視か、どの記憶が関連するか、どの内容を prompt cache に命中させるために安定させるべきか。\n\n---\n\n## ソリューション\n\n![System Prompt Overview](/course-assets/s10_system_prompt/system-prompt-overview.ja.svg)\n\ns10 はコンテキスト管理とエラー回復をつなぐ短い橋渡しセッションである。新しいストレージを追加せず、s08 と s09 も統合しない。両者の出力がモデル境界でどう合流するかを示す:ハードコードされた `SYSTEM` を独立セクションに分割し、実際の実行時状態から組み立て、結果をキャッシュする。\n\n4 つのセクション、2 つの読み込み戦略:\n\n| セクション | 戦略 | 内容 | 判断基準 |\n|-----------|------|------|---------|\n| identity | 常に | あなたは誰か、どう作業するか | 常に存在 |\n| tools | 常に | 利用可能ツール一覧 | `enabled_tools` |\n| workspace | 常に | 作業ディレクトリ | 常に存在 |\n| memory | オンデマンド | 関連記憶内容 | `.memory/MEMORY.md` が存在するか |\n\n重要な設計:セクションをロードするかどうかは実際の状態(ツールが存在するか、ファイルが存在するか)で決まり、メッセージ内のキーワードではない。\n\n---\n\n## 仕組み\n\n### PROMPT_SECTIONS: トピック別フラグメント\n\n単一の文字列を辞書に分割、各キーがトピック:\n\n```python\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n```\n\n各セクションは独立して管理。`tools` を変更しても `identity` に影響しない。`memory` を追加しても `workspace` はそのまま。\n\n### assemble_system_prompt: オンデマンド組み立て\n\nすべてのセクションが毎ターン必要なわけではない。記憶ファイルがなければ、memory セクションをロードしても token の無駄。context の実際の状態に基づいて組み立てる:\n\n```python\ndef assemble_system_prompt(context: dict) -> str:\n sections = []\n\n # 常にロード\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # context から動的に tools と workspace を取得\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # オンデマンド — 実際の状態に基づく、キーワードではない\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n```\n\n「常にロード」は毎ターン必要なもの:アイデンティティ、ツール、作業ディレクトリ。「オンデマンド」は特定条件下でのみ有用。\n\nなぜ全部ロードしないのか?token にはコストがあり(system prompt は毎ターン課金)、情報が少ないほど LLM は集中する(無関係な指示はノイズ)。\n\n### get_system_prompt: キャッシュで再組み立てを回避\n\nコンテキストが変わっていない時(同じターン内で複数の LLM 呼び出し、context が同じ)、再組み立ては無駄。確定的シリアライズで変化を検出し、キャッシュヒット時は即座に返却:\n\n```python\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n```\n\n`hash()` ではなく `json.dumps` を使用:Python 組み込みの `hash()` にはプロセスランダム化があり(安定したキャッシュキーに不適切)、list/dict で `unhashable type` エラーになる。\n\n### context: 実際の状態、キーワード推測ではない\n\ncontext は現在の実行時状態の実際の状態を反映:\n\n```python\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n```\n\n`enabled_tools` は実際に登録されたツールを一覧。`memories` は `.memory/MEMORY.md` が存在するかを確認。セクションの読み込みはこの実際の状態に基づき、メッセージ内のキーワード検索ではない。\n\n### 組み合わせて実行\n\n```python\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n # ... ツール実行 ...\n context = update_context(context, messages)\n system = get_system_prompt(context)\n```\n\n各ループ反復の開始時に system prompt を取得。context が変わっていれば再組み立て、変わっていなければキャッシュを返却。\n\n---\n\n## s09 からの変更点\n\n| コンポーネント | 変更前 (s09) | 変更後 (s10) |\n|-----------|-------------|-------------|\n| prompt | ハードコード SYSTEM 文字列 | PROMPT_SECTIONS + assemble_system_prompt |\n| キャッシュ | なし | get_system_prompt(json.dumps 検出 + キャッシュ) |\n| 新規関数 | — | assemble_system_prompt, get_system_prompt, update_context |\n| ツール | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 変更なし |\n| ループ | 固定 SYSTEM を使用 | get_system_prompt(context) を使用 |\n\n---\n\n## 試してみよう\n\n```sh\ncd learn-claude-code\npython s10_system_prompt/code.py\n```\n\n**安全上の注意**:このスクリプトはモデルが生成した `bash` 文字列を `shell=True` で実行し、s03 の permission gate を含まない。破棄可能な workspace でのみ実行すること。\n\n観察のポイント:\n\n1. 出力にロードされたセクションが表示される(`[assembled] sections: ...` ラベル)\n2. 継続会話でキャッシュヒット時は `[cache hit]` と表示\n3. `.memory/MEMORY.md` を作成すると、次のターンで memory セクションが自動ロード\n\n以下のプロンプトを試してみてください:\n\n1. `Read the file README.md`(常にロードされる 3 つのセクションを観察)\n2. `Create a file called .memory/MEMORY.md with content \"- [test](test.md) — test memory\"`(記憶インデックスを書き込み)\n3. `Read the file code.py`(memory セクションが表示されるか観察)\n\n---\n\n## 次へ\n\nモデル入力を実行時に組み立てられるようになった。しかし Agent はエラーでまだクラッシュする。ネットワークの不安定性、API レート制限、出力の切り詰め、コンテキスト超過、これらはバグではなく日常。\n\ns11 Error Recovery → 4 つのリカバリパス。token のアップグレード、コンテキスト圧縮、指数バックオフ、モデル切り替え。\n\n\n" }, { "version": "s11", "locale": "en", "title": "s11: Error Recovery — Errors aren't the end, they're the start of a retry", - "content": "# s11: Error Recovery — Errors aren't the end, they're the start of a retry\n\ns01 → ... → s09 → s10 → `s11` → [s12](/en/s12) → s13 → ... → s20 → s21 → s22\n> *\"Errors aren't the end, they're the start of a retry\"* — escalate tokens, compact context, switch models.\n>\n> **Harness layer**: Resilience — classify and recover when the main loop hits errors.\n\n---\n\n## The Problem\n\nThe Agent is running along and then errors out:\n\n```\nError: 529 overloaded\n```\n\nThe Agent crashes. It doesn't retry, doesn't switch models, doesn't reduce context — it just crashes.\n\nIn production, API errors are the norm. The three most common failure modes: **truncated output** (the model runs out of tokens mid-sentence), **context overflow** (still too long even after compaction), and **transient failures** (429 rate limiting / 529 overload). An Agent that doesn't handle errors is like a car that stalls at the slightest touch.\n\n---\n\n## Solution\n\n![Error Recovery Overview](/course-assets/s11_error_recovery/error-recovery-overview.en.svg)\n\nThe loop and prompt assembly from s10 are fully preserved. The only change: the LLM call is wrapped in try/except, with different recovery paths based on error type. After recovery, `continue` loops back to the top to call the LLM again.\n\nThe three most common recovery patterns (the teaching version only handles 429/529; real systems also cover connection errors, timeouts, cloud vendor credential caches, etc. CC actually has 13+ reason codes; see the Deep Dive for the rest):\n\n| Pattern | Trigger | Recovery Action |\n|----------|---------|-----------------|\n| Output truncated | `max_tokens` | Escalate 8K→64K / continuation prompt |\n| Context overflow | `prompt_too_long` | Reactive compact → retry |\n| Transient failure | 429 / 529 | Exponential backoff + jitter, fallback model on consecutive 529 |\n\n---\n\n## How It Works\n\n### Path 1: Output Truncated\n\nThe model runs out of tokens mid-sentence — `max_tokens` is exhausted. The default 8000 tokens isn't enough for a complete response.\n\nOn the first occurrence, escalate `max_tokens` from 8K to 64K (8x the space) and retry the same request — the truncated output is NOT appended to messages, keeping the original request intact. If 64K is still not enough, save the truncated output and inject a continuation prompt telling the model to pick up where it left off, up to 3 times:\n\n```python\nif response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n continue # messages unchanged, same request with more tokens\n # 64K still truncated: save output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\":\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"})\n state.recovery_count += 1\n continue\n return # still truncated after 3 continuations\n# Normal: append after max_tokens check\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\n```\n\nEscalation gets one chance; continuation gets up to 3. After that, exit — further continuations won't produce meaningful output.\n\n### Path 2: Context Overflow\n\nThe LLM says \"your context is too long\" (`prompt_too_long`). All four compaction layers from s08 have already run, and it's still over the limit.\n\nTrigger reactive compact — more aggressive than auto compact. The teaching version keeps only the last 5 messages to simulate compaction; real CC generates a compact summary via LLM, then retries with the compacted message list. Retry after compacting. But if it's still over the limit after one compaction, the only option is to exit — compacting again won't make it any smaller:\n\n```python\nexcept PromptTooLongError:\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return # Already compacted and still over limit — must exit\n```\n\n### Path 3: Transient Failures\n\nNetwork blips, 429 rate limiting, 529 overload — these aren't bugs, they're normal in distributed systems.\n\nBoth 429 and 529 use exponential backoff + jitter: wait 0.5 seconds on the first attempt, 1 second on the second, 2 seconds on the third, up to 10 retries. Random jitter prevents concurrent requests from all retrying at the same instant. Three consecutive 529 overload errors → switch to the fallback model (if `FALLBACK_MODEL_ID` environment variable is configured):\n\n```python\ndef retry_delay(attempt, retry_after=None):\n if retry_after:\n return retry_after\n base = min(500 * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\ndef with_retry(fn, state, max_retries=10):\n for attempt in range(max_retries):\n try:\n return fn()\n except (RateLimitError, OverloadedError):\n delay = retry_delay(attempt)\n time.sleep(delay)\n if is_overloaded:\n state.consecutive_529 += 1\n if state.consecutive_529 >= 3 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n raise MaxRetriesExceeded()\n```\n\nBackoff formula: `min(500 × 2^attempt, 32000) + random(0~25%)`. If the server returns a `Retry-After` header, that value takes priority.\n\n### Putting It All Together\n\n```python\ndef agent_loop(messages, context):\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = 8000\n\n while True:\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return\n log_error(e)\n return\n\n # max_tokens check BEFORE appending to messages\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = 64000\n state.has_escalated = True\n continue # retry same request, messages unchanged\n # save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n continue\n # Normal completion\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n # ... tool execution ...\n```\n\nThe outer try/except catches API exceptions (prompt_too_long, etc.), `with_retry` handles transient errors (429/529), and `stop_reason` checks handle truncation. Three recovery mechanisms, each handling its own error type.\n\n---\n\n## Changes from s10\n\n| Component | Before (s10) | After (s11) |\n|-----------|-------------|-------------|\n| Error handling | None (crashes on any error) | Three recovery patterns + exponential backoff |\n| New constants | — | ESCALATED_MAX_TOKENS=64000, MAX_RETRIES=10, BASE_DELAY_MS=500, FALLBACK_MODEL |\n| New functions | — | with_retry, retry_delay, reactive_compact, is_prompt_too_long_error, RecoveryState |\n| Tools | bash, read_file, write_file (3) | bash, read_file, write_file (3) — unchanged |\n| Loop | Bare LLM call | Wrapped in try/except + continue retry |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s11_error_recovery/code.py\n```\n\nTry these prompts:\n\n1. Ask the Agent to generate a very long piece of code, and observe whether it automatically continues after truncation (look for the `[max_tokens] escalating` log)\n2. Read many files consecutively to bloat the context, and observe reactive compact\n3. If you encounter 429/529, observe the exponential backoff log output\n\n---\n\n## What's Next\n\nThe Agent can now automatically recover from errors. But the tasks it handles are still one-shot — you give it a task, it finishes, it's done.\n\nWhat if the Agent could manage a **task list** — with dependencies, persisted to disk, resumable across sessions? A TODO list is not a task system.\n\ns12 Task System → Tasks form a dependency graph with state and persistence. This is the foundation for multi-Agent collaboration.\n\n
\nDeep Dive into CC Source\n\n> The following is based on CC source code: `query.ts` (1729 lines), `services/api/withRetry.ts` (822 lines), `query/tokenBudget.ts` (93 lines), and `utils/tokenBudget.ts` (73 lines).\n\n### 1. A Dozen-Plus Reason/Transition Codes (Not Just 3)\n\nThe teaching version covers 3 of the most common recovery patterns. CC actually has a dozen-plus reason/transition codes, evaluated after every LLM call:\n\n| Reason/Transition | Teaching Version | CC Behavior |\n|---|---|---|\n| `completed` | Normal completion | Return result |\n| `next_turn` | Normal tool call | Continue to next tool execution round |\n| `max_output_tokens_escalate` | Path 1 | 8K→64K escalation |\n| `max_output_tokens_recovery` | Path 1 continuation | Continuation prompt (up to 3 times) |\n| `reactive_compact_retry` | Path 2 | Reactive compact → retry |\n| `prompt_too_long` | Path 2 | Same as above |\n| `collapse_drain_retry` | Not covered | Context collapse — commit staged content first |\n| `model_error` | Not covered | Retry |\n| `image_error` | Not covered | `ImageSizeError` / `ImageResizeError` handled specifically |\n| `aborted_streaming` | Not covered | Streaming abort recovery |\n| `aborted_tools` | Not covered | Tool abort |\n| `stop_hook_blocking` | Not covered | Inject blocking error → model self-corrects |\n| `stop_hook_prevented` | Not covered | Hooks prevent execution |\n| `hook_stopped` | Not covered | Hook stopped execution |\n| `token_budget_continuation` | Not covered | Continue when token usage < 90% |\n| `blocking_limit` | Not covered | Blocking limit reached |\n| `max_turns` | Not covered | Maximum turns reached |\n\nThe teaching version only expands on the first 5 (most common); each of the rest has its own dedicated handling logic.\n\n### 2. Precise Exponential Backoff Formula\n\nCC's backoff delay (`withRetry.ts:530-548`):\n\n```\ndelay = min(500 × 2^(attempt-1), 32000) + random(0~25%)\n```\n\n| Attempt | Base Delay | + Jitter |\n|---------|-----------|----------|\n| 1 | 500ms | 0-125ms |\n| 2 | 1000ms | 0-250ms |\n| 4 | 4000ms | 0-1000ms |\n| 7+ | 32000ms (cap) | 0-8000ms |\n\nIf the server returns a `Retry-After` header, that value takes priority.\n\n### 3. Original CONTINUATION Prompt\n\nCC's continuation prompt (`query.ts:1225-1227`):\n\n```\nOutput token limit hit. Resume directly — no apology, no recap of what\nyou were doing. Pick up mid-thought if that is where the cut happened.\nBreak remaining work into smaller pieces.\n```\n\nToken budget nudge prompt (`tokenBudget.ts:72`):\n\n```\nStopped at {pct}% of token target. Keep working — do not summarize.\n```\n\n### 4. Streaming Error Handling\n\nIn CC's streaming path, recoverable errors (413, max_tokens, media errors) are **withheld from display** during streaming (`query.ts:788-822`) — SDK consumers don't see them, only the recovery logic does. After streaming ends, the system determines whether recovery is needed.\n\n### 5. 529 → Fallback Model Switch\n\nAfter 3 consecutive 529 overload errors (`MAX_529_RETRIES = 3`), CC automatically switches to the fallback model (e.g., Opus → Sonnet). On switch, all pending messages and tool results are cleared, and the user sees \"Switched to {model} due to high demand\".\n\n### 6. Diminishing Returns Detection\n\nToken budget \"continuations\" aren't unlimited. When there are 3 consecutive continuations with a token increment < 500, the system determines \"continuing won't produce meaningful output\" and stops continuation (`tokenBudget.ts:60-62`).\n\n
\n\n\n" + "content": "# s11: Error Recovery — Errors aren't the end, they're the start of a retry\n\ns01 → ... → s09 → s10 → `s11` → [s12](/en/s12) → s13 → ... → s20 → s21\n> *\"Errors aren't the end, they're the start of a retry\"* — escalate tokens, compact context, switch models.\n>\n> **Harness layer**: Resilience — classify and recover when the main loop hits errors.\n\n---\n\n## The Problem\n\nThe Agent is running along and then errors out:\n\n```\nError: 529 overloaded\n```\n\nThe Agent crashes. It doesn't retry, doesn't switch models, doesn't reduce context — it just crashes.\n\nLLM API calls can fail. This chapter handles three cases: truncated output, context overflow, and transient failures (429/529).\n\n---\n\n## Solution\n\n![Error Recovery Overview](/course-assets/s11_error_recovery/error-recovery-overview.en.svg)\n\nThe loop and prompt assembly from s10 are fully preserved. The only change: the LLM call is wrapped in try/except, with different recovery paths based on error type. After recovery, `continue` loops back to the top to call the LLM again.\n\nThis chapter implements three recovery patterns:\n\n| Pattern | Trigger | Recovery Action |\n|----------|---------|-----------------|\n| Output truncated | `max_tokens` | Escalate 8K→64K / continuation prompt |\n| Context overflow | `prompt_too_long` | Reactive compact → retry |\n| Transient failure | 429 / 529 | Exponential backoff + jitter, fallback model on consecutive 529 |\n\n---\n\n## How It Works\n\n### Path 1: Output Truncated\n\nThe model runs out of tokens mid-sentence — `max_tokens` is exhausted. The default 8000 tokens isn't enough for a complete response.\n\nOn the first occurrence, escalate `max_tokens` from 8K to 64K (8x the space) and retry the same request — the truncated output is NOT appended to messages, keeping the original request intact. If 64K is still not enough, save the truncated output and inject a continuation prompt telling the model to pick up where it left off, up to 3 times:\n\n```python\nif response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n continue # messages unchanged, same request with more tokens\n # 64K still truncated: save output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\":\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"})\n state.recovery_count += 1\n continue\n return # still truncated after 3 continuations\n# Normal: append after max_tokens check\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\n```\n\nEscalation gets one chance; continuation gets up to 3. After that, exit — further continuations won't produce meaningful output.\n\n### Path 2: Context Overflow\n\nThe LLM says \"your context is too long\" (`prompt_too_long`). All four compaction layers from s08 have already run, and it's still over the limit.\n\nTrigger reactive compact: keep the last 5 messages and retry once. If the context is still over the limit, exit:\n\n```python\nexcept PromptTooLongError:\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return # Already compacted and still over limit — must exit\n```\n\n### Path 3: Transient Failures\n\nNetwork blips, 429 rate limiting, 529 overload — these aren't bugs, they're normal in distributed systems.\n\nBoth 429 and 529 use exponential backoff + jitter: wait 0.5 seconds on the first attempt, 1 second on the second, 2 seconds on the third, up to 10 retries. Random jitter prevents concurrent requests from all retrying at the same instant. Three consecutive 529 overload errors → switch to the fallback model (if `FALLBACK_MODEL_ID` environment variable is configured):\n\n```python\ndef retry_delay(attempt, retry_after=None):\n if retry_after:\n return retry_after\n base = min(500 * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\ndef with_retry(fn, state, max_retries=10):\n for attempt in range(max_retries):\n try:\n return fn()\n except (RateLimitError, OverloadedError):\n delay = retry_delay(attempt)\n time.sleep(delay)\n if is_overloaded:\n state.consecutive_529 += 1\n if state.consecutive_529 >= 3 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n raise MaxRetriesExceeded()\n```\n\nBackoff formula: `min(500 × 2^attempt, 32000) + random(0~25%)`. If the server returns a `Retry-After` header, that value takes priority.\n\n### Putting It All Together\n\n```python\ndef agent_loop(messages, context):\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = 8000\n\n while True:\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return\n log_error(e)\n return\n\n # max_tokens check BEFORE appending to messages\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = 64000\n state.has_escalated = True\n continue # retry same request, messages unchanged\n # save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n continue\n # Normal completion\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n # ... tool execution ...\n```\n\nThe outer try/except catches API exceptions (prompt_too_long, etc.), `with_retry` handles transient errors (429/529), and `stop_reason` checks handle truncation. Three recovery mechanisms, each handling its own error type.\n\n---\n\n## Changes from s10\n\n| Component | Before (s10) | After (s11) |\n|-----------|-------------|-------------|\n| Error handling | None (crashes on any error) | Three recovery patterns + exponential backoff |\n| New constants | — | ESCALATED_MAX_TOKENS=64000, MAX_RETRIES=10, BASE_DELAY_MS=500, FALLBACK_MODEL |\n| New functions | — | with_retry, retry_delay, reactive_compact, is_prompt_too_long_error, RecoveryState |\n| Tools | bash, read_file, write_file (3) | bash, read_file, write_file (3) — unchanged |\n| Loop | Bare LLM call | Wrapped in try/except + continue retry |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s11_error_recovery/code.py\n```\n\nTry these prompts:\n\n1. Ask the Agent to generate a very long piece of code, and observe whether it automatically continues after truncation (look for the `[max_tokens] escalating` log)\n2. Read many files consecutively to bloat the context, and observe reactive compact\n3. If you encounter 429/529, observe the exponential backoff log output\n\n---\n\n## What's Next\n\nThe Agent can now automatically recover from errors. But the tasks it handles are still one-shot — you give it a task, it finishes, it's done.\n\nWhat if the Agent could manage a **task list** — with dependencies, persisted to disk, resumable across sessions? A TODO list is not a task system.\n\ns12 Task System → Tasks form a dependency graph with state and persistence. This is the foundation for multi-Agent collaboration.\n\n\n\n" }, { "version": "s11", "locale": "zh", "title": "s11: Error Recovery — 错误不是结束,是重试的开始", - "content": "# s11: Error Recovery — 错误不是结束,是重试的开始\n\ns01 → ... → s09 → s10 → `s11` → [s12](/zh/s12) → s13 → ... → s20 → s21 → s22\n> *\"错误不是终点, 是重试的起点\"* — 升级 token、压缩上下文、切换模型。\n>\n> **Harness 层**: 韧性 — 主循环遇到错误时分类并恢复。\n\n---\n\n## 问题\n\nAgent 跑着跑着报错了:\n\n```\nError: 529 overloaded\n```\n\nAgent 崩溃了。它没有重试,没有换模型,没有减少上下文——直接崩溃。\n\n生产环境中 API 错误是常态。三种最常见的故障模式:**输出被截断**(模型话说一半 token 用完了)、**上下文超限**(压缩后还是太长)、**临时故障**(429 限流 / 529 过载)。一个不处理错误的 Agent 就像一个一碰就熄火的车。\n\n---\n\n## 解决方案\n\n![Error Recovery Overview](/course-assets/s11_error_recovery/error-recovery-overview.svg)\n\ns10 的循环、prompt 组装全部保留。唯一的变动:LLM 调用包裹在 try/except 里,根据错误类型走不同的恢复路径。恢复后 `continue` 回到循环开头重新调用 LLM。\n\n三种最常见的恢复模式(教学版只处理 429/529;真实系统还覆盖连接错误、超时、云厂商认证缓存等。CC 实际有 13+ reason code,其余见 Deep dive):\n\n| 模式 | 触发 | 恢复动作 |\n|------|------|---------|\n| 输出截断 | `max_tokens` | 升级 8K→64K / 续写提示 |\n| 上下文超限 | `prompt_too_long` | reactive compact → 重试 |\n| 临时故障 | 429 / 529 | 指数退避 + 抖动,连续 529 可切换备用模型 |\n\n---\n\n## 工作原理\n\n### 路径 1: 输出被截断\n\n模型话说一半,`max_tokens` 用完了。默认 8000 token 不够它输出完整回答。\n\n第一次发生时,直接把 `max_tokens` 从 8K 升级到 64K(8 倍空间),重试同一请求——此时不追加截断输出到 messages,保持原始请求不变。如果 64K 还是不够,才保存截断输出并注入续写提示让模型接着刚才的话继续说,最多 3 次:\n\n```python\nif response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n continue # messages unchanged, same request with more tokens\n # 64K still truncated: save output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\":\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"})\n state.recovery_count += 1\n continue\n return # still truncated after 3 continuations\n# Normal: append after max_tokens check\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\n```\n\n升级只有一次机会,续写最多 3 次。超过就退出——继续续写也不会有实质产出。\n\n### 路径 2: 上下文超限\n\nLLM 说\"你的上下文太长了\"(`prompt_too_long`)。s08 的四层压缩全跑过了,还是超。\n\n触发 reactive compact——比 auto compact 更激进。教学版只保留最后 5 条消息模拟压缩效果;真实实现会调用 LLM 生成 compact 摘要再重试。压缩后重试。但如果压缩过一次还是超限,只能退出——再压缩也不会变小:\n\n```python\nexcept PromptTooLongError:\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return # 压缩过了还是超限,只能退出\n```\n\n### 路径 3: 临时故障\n\n网络抖动、429 限流、529 过载——这些不是 bug,是分布式系统的常态。\n\n429 和 529 统一走指数退避 + 抖动:第一次等 0.5 秒,第二次等 1 秒,第三次等 2 秒,最多 10 次。加随机抖动让并发请求不在同一时刻重试。连续 3 次 529 过载 → 切换到备用模型(若配置了 `FALLBACK_MODEL_ID` 环境变量):\n\n```python\ndef retry_delay(attempt, retry_after=None):\n if retry_after:\n return retry_after\n base = min(500 * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\ndef with_retry(fn, state, max_retries=10):\n for attempt in range(max_retries):\n try:\n return fn()\n except (RateLimitError, OverloadedError):\n delay = retry_delay(attempt)\n time.sleep(delay)\n if is_overloaded:\n state.consecutive_529 += 1\n if state.consecutive_529 >= 3 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n raise MaxRetriesExceeded()\n```\n\n退避公式:`min(500 × 2^attempt, 32000) + random(0~25%)`。如果服务器返回 `Retry-After` header,优先用那个值。\n\n### 合起来跑\n\n```python\ndef agent_loop(messages, context):\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = 8000\n\n while True:\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return\n log_error(e)\n return\n\n # max_tokens check BEFORE appending to messages\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = 64000\n state.has_escalated = True\n continue # retry same request, messages unchanged\n # save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n continue\n # Normal completion\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n # ... tool execution ...\n```\n\n外层 try/except 捕获 API 异常(prompt_too_long 等),`with_retry` 处理瞬态错误(429/529),`stop_reason` 检查处理截断。三种恢复机制各管各的错误类型。\n\n---\n\n## 相对 s10 的变更\n\n| 组件 | 之前 (s10) | 之后 (s11) |\n|------|-----------|-----------|\n| 错误处理 | 无(一碰就崩溃) | 三种恢复模式 + 指数退避 |\n| 新常量 | — | ESCALATED_MAX_TOKENS=64000, MAX_RETRIES=10, BASE_DELAY_MS=500, FALLBACK_MODEL |\n| 新函数 | — | with_retry, retry_delay, reactive_compact, is_prompt_too_long_error, RecoveryState |\n| 工具 | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 不变 |\n| 循环 | 裸调用 LLM | try/except 包裹 + continue 重试 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s11_error_recovery/code.py\n```\n\n试试这些 prompt:\n\n1. 让 Agent 生成一段很长的代码,观察截断后是否自动续写(看 `[max_tokens] escalating` 日志)\n2. 连续读取大量文件撑大上下文,观察 reactive compact\n3. 如果遇到 429/529,观察指数退避的日志输出\n\n---\n\n## 接下来\n\nAgent 现在能在错误中自动恢复了。但它处理的任务仍然是\"一次性\"的——你给它一个任务,它做完,结束。\n\n能不能让 Agent 管理一个**任务列表**——有依赖关系、持久化到磁盘、跨会话能恢复?TODO 列表不是任务系统。\n\ns12 Task System → 任务是有依赖、有状态、持久化的图。这是多 Agent 协作的基础。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `query.ts`(1729 行)、`services/api/withRetry.ts`(822 行)、`query/tokenBudget.ts`(93 行)、`utils/tokenBudget.ts`(73 行)的分析。\n\n### 一、十几种 reason/transition(不只是 3 条)\n\n教学版讲了 3 种最常见的恢复模式。CC 实际有十几种 reason/transition,每轮 LLM 调用后都会判断:\n\n| reason/transition | 教学版对应 | CC 行为 |\n|---|---|---|\n| `completed` | 正常完成 | 返回结果 |\n| `next_turn` | 正常工具调用 | 继续下一轮工具执行 |\n| `max_output_tokens_escalate` | 路径 1 | 8K→64K 升级 |\n| `max_output_tokens_recovery` | 路径 1 续写 | 续写提示(最多 3 次) |\n| `reactive_compact_retry` | 路径 2 | reactive compact → 重试 |\n| `prompt_too_long` | 路径 2 | 同上 |\n| `collapse_drain_retry` | 未展开 | context collapse 先提交暂存 |\n| `model_error` | 未展开 | 重试 |\n| `image_error` | 未展开 | `ImageSizeError` / `ImageResizeError` 专门处理 |\n| `aborted_streaming` | 未展开 | 流式中止恢复 |\n| `aborted_tools` | 未展开 | 工具中止 |\n| `stop_hook_blocking` | 未展开 | 注入 blocking error → 模型自纠 |\n| `stop_hook_prevented` | 未展开 | hooks 阻止 |\n| `hook_stopped` | 未展开 | hook 停止执行 |\n| `token_budget_continuation` | 未展开 | token 用量 < 90% 时继续 |\n| `blocking_limit` | 未展开 | 阻塞限制 |\n| `max_turns` | 未展开 | 达到最大轮次 |\n\n教学版只展开了前 5 种(最常见的),其余各有专门处理逻辑。\n\n### 二、指数退避的精确公式\n\nCC 的退避延迟(`withRetry.ts:530-548`):\n\n```\ndelay = min(500 × 2^(attempt-1), 32000) + random(0~25%)\n```\n\n| 尝试 | 基础延迟 | + 抖动 |\n|------|---------|--------|\n| 1 | 500ms | 0-125ms |\n| 2 | 1000ms | 0-250ms |\n| 4 | 4000ms | 0-1000ms |\n| 7+ | 32000ms(上限) | 0-8000ms |\n\n如果服务器返回 `Retry-After` header,优先用那个值。\n\n### 三、CONTINUATION 提示原文\n\nCC 的续写提示(`query.ts:1225-1227`):\n\n```\nOutput token limit hit. Resume directly — no apology, no recap of what\nyou were doing. Pick up mid-thought if that is where the cut happened.\nBreak remaining work into smaller pieces.\n```\n\nToken budget 的 nudge 提示(`tokenBudget.ts:72`):\n\n```\nStopped at {pct}% of token target. Keep working — do not summarize.\n```\n\n### 四、流式错误处理\n\nCC 的流式路径中,可恢复的错误(413、max_tokens、media error)在 streaming 期间**被暂扣不展示**(`query.ts:788-822`)——SDK 消费者看不到,只有恢复逻辑能看到。等 streaming 结束后才判断是否需要恢复。\n\n### 五、529 → Fallback Model 切换\n\n连续 3 次 529 过载错误后(`MAX_529_RETRIES = 3`),CC 自动切换到 fallback model(如 Opus → Sonnet)。切换时清除所有 pending 消息和 tool 结果,给用户展示 \"Switched to {model} due to high demand\"。\n\n### 六、Diminishing Returns 检测\n\nToken budget 的\"继续\"不是无限的。当连续 3 次 continuation 且 token 增量 < 500 时,系统判断\"继续也没有实质性产出\",停止 continuation(`tokenBudget.ts:60-62`)。\n\n
\n\n\n" + "content": "# s11: Error Recovery — 错误不是结束,是重试的开始\n\ns01 → ... → s09 → s10 → `s11` → [s12](/zh/s12) → s13 → ... → s20 → s21\n> *\"错误不是终点, 是重试的起点\"* — 升级 token、压缩上下文、切换模型。\n>\n> **Harness 层**: 韧性 — 主循环遇到错误时分类并恢复。\n\n---\n\n## 问题\n\nAgent 跑着跑着报错了:\n\n```\nError: 529 overloaded\n```\n\nAgent 崩溃了。它没有重试,没有换模型,没有减少上下文——直接崩溃。\n\nLLM API 调用可能失败。本章处理三种情况:输出截断、上下文超限和临时故障(429/529)。\n\n---\n\n## 解决方案\n\n![Error Recovery Overview](/course-assets/s11_error_recovery/error-recovery-overview.svg)\n\ns10 的循环、prompt 组装全部保留。唯一的变动:LLM 调用包裹在 try/except 里,根据错误类型走不同的恢复路径。恢复后 `continue` 回到循环开头重新调用 LLM。\n\n本章实现三种恢复模式:\n\n| 模式 | 触发 | 恢复动作 |\n|------|------|---------|\n| 输出截断 | `max_tokens` | 升级 8K→64K / 续写提示 |\n| 上下文超限 | `prompt_too_long` | reactive compact → 重试 |\n| 临时故障 | 429 / 529 | 指数退避 + 抖动,连续 529 可切换备用模型 |\n\n---\n\n## 工作原理\n\n### 路径 1: 输出被截断\n\n模型话说一半,`max_tokens` 用完了。默认 8000 token 不够它输出完整回答。\n\n第一次发生时,直接把 `max_tokens` 从 8K 升级到 64K(8 倍空间),重试同一请求——此时不追加截断输出到 messages,保持原始请求不变。如果 64K 还是不够,才保存截断输出并注入续写提示让模型接着刚才的话继续说,最多 3 次:\n\n```python\nif response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n continue # messages unchanged, same request with more tokens\n # 64K still truncated: save output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\":\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"})\n state.recovery_count += 1\n continue\n return # still truncated after 3 continuations\n# Normal: append after max_tokens check\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\n```\n\n升级只有一次机会,续写最多 3 次。超过就退出——继续续写也不会有实质产出。\n\n### 路径 2: 上下文超限\n\nLLM 说\"你的上下文太长了\"(`prompt_too_long`)。s08 的四层压缩全跑过了,还是超。\n\n触发 reactive compact:保留最后 5 条消息后重试一次。如果仍然超限,则退出:\n\n```python\nexcept PromptTooLongError:\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return # 压缩过了还是超限,只能退出\n```\n\n### 路径 3: 临时故障\n\n网络抖动、429 限流、529 过载——这些不是 bug,是分布式系统的常态。\n\n429 和 529 统一走指数退避 + 抖动:第一次等 0.5 秒,第二次等 1 秒,第三次等 2 秒,最多 10 次。加随机抖动让并发请求不在同一时刻重试。连续 3 次 529 过载 → 切换到备用模型(若配置了 `FALLBACK_MODEL_ID` 环境变量):\n\n```python\ndef retry_delay(attempt, retry_after=None):\n if retry_after:\n return retry_after\n base = min(500 * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\ndef with_retry(fn, state, max_retries=10):\n for attempt in range(max_retries):\n try:\n return fn()\n except (RateLimitError, OverloadedError):\n delay = retry_delay(attempt)\n time.sleep(delay)\n if is_overloaded:\n state.consecutive_529 += 1\n if state.consecutive_529 >= 3 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n raise MaxRetriesExceeded()\n```\n\n退避公式:`min(500 × 2^attempt, 32000) + random(0~25%)`。如果服务器返回 `Retry-After` header,优先用那个值。\n\n### 合起来跑\n\n```python\ndef agent_loop(messages, context):\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = 8000\n\n while True:\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return\n log_error(e)\n return\n\n # max_tokens check BEFORE appending to messages\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = 64000\n state.has_escalated = True\n continue # retry same request, messages unchanged\n # save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n continue\n # Normal completion\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n # ... tool execution ...\n```\n\n外层 try/except 捕获 API 异常(prompt_too_long 等),`with_retry` 处理瞬态错误(429/529),`stop_reason` 检查处理截断。三种恢复机制各管各的错误类型。\n\n---\n\n## 相对 s10 的变更\n\n| 组件 | 之前 (s10) | 之后 (s11) |\n|------|-----------|-----------|\n| 错误处理 | 无(一碰就崩溃) | 三种恢复模式 + 指数退避 |\n| 新常量 | — | ESCALATED_MAX_TOKENS=64000, MAX_RETRIES=10, BASE_DELAY_MS=500, FALLBACK_MODEL |\n| 新函数 | — | with_retry, retry_delay, reactive_compact, is_prompt_too_long_error, RecoveryState |\n| 工具 | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 不变 |\n| 循环 | 裸调用 LLM | try/except 包裹 + continue 重试 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s11_error_recovery/code.py\n```\n\n试试这些 prompt:\n\n1. 让 Agent 生成一段很长的代码,观察截断后是否自动续写(看 `[max_tokens] escalating` 日志)\n2. 连续读取大量文件撑大上下文,观察 reactive compact\n3. 如果遇到 429/529,观察指数退避的日志输出\n\n---\n\n## 接下来\n\nAgent 现在能在错误中自动恢复了。但它处理的任务仍然是\"一次性\"的——你给它一个任务,它做完,结束。\n\n能不能让 Agent 管理一个**任务列表**——有依赖关系、持久化到磁盘、跨会话能恢复?TODO 列表不是任务系统。\n\ns12 Task System → 任务是有依赖、有状态、持久化的图。这是多 Agent 协作的基础。\n\n\n\n" }, { "version": "s11", "locale": "ja", "title": "s11: Error Recovery — エラーは終わりではなく、リトライの始まり", - "content": "# s11: Error Recovery — エラーは終わりではなく、リトライの始まり\n\ns01 → ... → s09 → s10 → `s11` → [s12](/ja/s12) → s13 → ... → s20 → s21 → s22\n> *\"エラーは終わりではなく、リトライの始まり\"* — トークン拡張、コンテキスト圧縮、モデル切り替え。\n>\n> **Harness 層**: 耐障害性 — メインループのエラーを分類し復旧。\n\n---\n\n## 課題\n\nAgent が動いている途中でエラーが出た:\n\n```\nError: 529 overloaded\n```\n\nAgent がクラッシュした。リトライもしない、モデルも切り替えない、コンテキストも減らさない——そのままクラッシュ。\n\n本番環境では API エラーが日常茶飯事。最も一般的な 3 つの障害パターン:**出力の切り詰め**(モデルが途中まで出力して token が尽きた)、**コンテキスト超過**(圧縮後も長すぎる)、**一時的障害**(429 レート制限 / 529 過負荷)。エラーを処理しない Agent は、一度触れただけで止まる車のようなものだ。\n\n---\n\n## 解決策\n\n![Error Recovery Overview](/course-assets/s11_error_recovery/error-recovery-overview.ja.svg)\n\ns10 のループ、prompt 組み立てはすべてそのまま。唯一の変更点:LLM 呼び出しを try/except で包み、エラータイプに応じて異なる復旧パスに振り分ける。復旧後は `continue` でループ先頭に戻り、再度 LLM を呼び出す。\n\n最も一般的な 3 つの復旧パターン(教学版は 429/529 のみ対応;実際のシステムは接続エラー、タイムアウト、クラウドベンダーの認証キャッシュ等もカバー。CC には実際 13 以上の reason code があるが、残りは Deep dive で解説):\n\n| パターン | トリガー | 復旧アクション |\n|----------|----------|---------------|\n| 出力切り詰め | `max_tokens` | 8K→64K に拡張 / 続きのプロンプト注入 |\n| コンテキスト超過 | `prompt_too_long` | reactive compact → リトライ |\n| 一時的障害 | 429 / 529 | 指数バックオフ + ジッター、連続 529 でフォールバックモデルに切り替え可能 |\n\n---\n\n## 仕組み\n\n### パス 1: 出力が切り詰められた\n\nモデルが途中まで出力して、`max_tokens` に達した。デフォルトの 8000 token では完全な回答を出力しきれない。\n\n初回発生時、`max_tokens` を 8K から 64K に拡張(8 倍の空間)し、同じリクエストをリトライする——この時、切り詰められた出力は messages に追加せず、元のリクエストをそのまま維持する。64K でも足りない場合にのみ、切り詰められた出力を保存し、続きのプロンプトを注入してモデルに先ほどの続きを出力させる。最大 3 回まで:\n\n```python\nif response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n continue # messages unchanged, same request with more tokens\n # 64K still truncated: save output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\":\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"})\n state.recovery_count += 1\n continue\n return # still truncated after 3 continuations\n# Normal: append after max_tokens check\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\n```\n\n拡張は 1 回だけ、続きの出力は最大 3 回。超過したら終了——これ以上続けても実質的な出力は得られない。\n\n### パス 2: コンテキスト超過\n\nLLM が「コンテキストが長すぎる」と返す(`prompt_too_long`)。s08 の 4 層圧縮をすべて実行したのに、まだ超えている。\n\nreactive compact をトリガー——auto compact よりも積極的。教学版は最後の 5 メッセージだけを残して圧縮をシミュレート;実際の CC は LLM で compact サマリを生成してからリトライする。圧縮後にリトライ。ただし、一度圧縮してもまだ超過している場合は終了するしかない——再度圧縮しても小さくはならない:\n\n```python\nexcept PromptTooLongError:\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return # 圧縮済みでも超過、終了するしかない\n```\n\n### パス 3: 一時的障害\n\nネットワークの揺らぎ、429 レート制限、529 過負荷——これらはバグではなく、分散システムの日常だ。\n\n429 と 529 は統一して指数バックオフ + ジッターを使用:1 回目は 0.5 秒待機、2 回目は 1 秒、3 回目は 2 秒、最大 10 回。ランダムジッターを加えることで、並行リクエストが同時にリトライするのを防ぐ。3 回連続で 529 過負荷 → フォールバックモデルに切り替え(`FALLBACK_MODEL_ID` 環境変数が設定されている場合):\n\n```python\ndef retry_delay(attempt, retry_after=None):\n if retry_after:\n return retry_after\n base = min(500 * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\ndef with_retry(fn, state, max_retries=10):\n for attempt in range(max_retries):\n try:\n return fn()\n except (RateLimitError, OverloadedError):\n delay = retry_delay(attempt)\n time.sleep(delay)\n if is_overloaded:\n state.consecutive_529 += 1\n if state.consecutive_529 >= 3 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n raise MaxRetriesExceeded()\n```\n\nバックオフの公式:`min(500 × 2^attempt, 32000) + random(0~25%)`。サーバーが `Retry-After` ヘッダーを返した場合、その値を優先して使用する。\n\n### 統合して実行\n\n```python\ndef agent_loop(messages, context):\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = 8000\n\n while True:\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return\n log_error(e)\n return\n\n # max_tokens check BEFORE appending to messages\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = 64000\n state.has_escalated = True\n continue # retry same request, messages unchanged\n # save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n continue\n # Normal completion\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n # ... tool execution ...\n```\n\n外側の try/except が API 例外(prompt_too_long 等)を捕捉し、`with_retry` が一時的エラー(429/529)を処理し、`stop_reason` のチェックが切り詰めを処理する。3 つの復旧メカニズムがそれぞれ異なるエラータイプを担当する。\n\n---\n\n## s10 からの変更点\n\n| コンポーネント | 変更前 (s10) | 変更後 (s11) |\n|---------------|-------------|-------------|\n| エラー処理 | なし(エラーで即クラッシュ) | 3 つの復旧パターン + 指数バックオフ |\n| 新規定数 | — | ESCALATED_MAX_TOKENS=64000, MAX_RETRIES=10, BASE_DELAY_MS=500, FALLBACK_MODEL |\n| 新規関数 | — | with_retry, retry_delay, reactive_compact, is_prompt_too_long_error, RecoveryState |\n| ツール | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 変更なし |\n| ループ | LLM を直接呼び出し | try/except で包み + continue でリトライ |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s11_error_recovery/code.py\n```\n\n以下の prompt を試してみよう:\n\n1. Agent に長いコードを生成させ、切り詰め後に自動で続きが出力されるか観察する(`[max_tokens] escalating` ログを確認)\n2. 連続して大量のファイルを読み込みコンテキストを肥大化させ、reactive compact の動作を観察する\n3. 429/529 が発生した場合、指数バックオフのログ出力を観察する\n\n---\n\n## 次のステップ\n\nAgent はエラーから自動的に復旧できるようになった。しかし、まだ処理するタスクは「使い捨て」だ——タスクを与えると実行し、終わる。\n\nAgent に**タスクリスト**を管理させられないだろうか——依存関係があり、ディスクに永続化され、セッションをまたいで復旧できる?TODO リストはタスクシステムではない。\n\ns12 Task System → タスクとは依存関係があり、状態があり、永続化されたグラフだ。これはマルチ Agent 協調の基盤となる。\n\n
\nCC ソースコード深掘り\n\n> 以下は CC ソースコード `query.ts`(1729 行)、`services/api/withRetry.ts`(822 行)、`query/tokenBudget.ts`(93 行)、`utils/tokenBudget.ts`(73 行)の分析に基づく。\n\n### 一、十数種の reason/transition(3 つだけではない)\n\n教学版では最も一般的な 3 つの復旧パターンを解説した。CC には実際十数種の reason/transition があり、毎回の LLM 呼び出し後に判定される:\n\n| reason/transition | 教学版の対応 | CC の動作 |\n|---|---|---|\n| `completed` | 正常終了 | 結果を返す |\n| `next_turn` | 通常のツール呼び出し | 次のツール実行ラウンドへ |\n| `max_output_tokens_escalate` | パス 1 | 8K→64K に拡張 |\n| `max_output_tokens_recovery` | パス 1 続き出力 | 続きのプロンプト注入(最大 3 回) |\n| `reactive_compact_retry` | パス 2 | reactive compact → リトライ |\n| `prompt_too_long` | パス 2 | 同上 |\n| `collapse_drain_retry` | 未展開 | context collapse 時にまず保留中の内容をコミット |\n| `model_error` | 未展開 | リトライ |\n| `image_error` | 未展開 | `ImageSizeError` / `ImageResizeError` の専用処理 |\n| `aborted_streaming` | 未展開 | ストリーミング中断の復旧 |\n| `aborted_tools` | 未展開 | ツール中断 |\n| `stop_hook_blocking` | 未展開 | blocking error を注入 → モデルが自己修正 |\n| `stop_hook_prevented` | 未展開 | hooks によるブロック |\n| `hook_stopped` | 未展開 | hook による実行停止 |\n| `token_budget_continuation` | 未展開 | token 使用量 < 90% の時に継続 |\n| `blocking_limit` | 未展開 | ブロック制限 |\n| `max_turns` | 未展開 | 最大ターン数に到達 |\n\n教学版では最初の 5 つ(最も一般的なもの)だけを展開した。残りはそれぞれ専用の処理ロジックを持つ。\n\n### 二、指数バックオフの正確な公式\n\nCC のバックオフ遅延(`withRetry.ts:530-548`):\n\n```\ndelay = min(500 × 2^(attempt-1), 32000) + random(0~25%)\n```\n\n| 試行 | 基本遅延 | + ジッター |\n|------|---------|-----------|\n| 1 | 500ms | 0-125ms |\n| 2 | 1000ms | 0-250ms |\n| 4 | 4000ms | 0-1000ms |\n| 7+ | 32000ms(上限) | 0-8000ms |\n\nサーバーが `Retry-After` ヘッダーを返した場合、その値を優先して使用する。\n\n### 三、CONTINUATION プロンプト原文\n\nCC の続き出力プロンプト(`query.ts:1225-1227`):\n\n```\nOutput token limit hit. Resume directly — no apology, no recap of what\nyou were doing. Pick up mid-thought if that is where the cut happened.\nBreak remaining work into smaller pieces.\n```\n\nToken budget のナッジプロンプト(`tokenBudget.ts:72`):\n\n```\nStopped at {pct}% of token target. Keep working — do not summarize.\n```\n\n### 四、ストリーミングエラー処理\n\nCC のストリーミングパスでは、復旧可能なエラー(413、max_tokens、media error)はストリーミング中**表示を保留される**(`query.ts:788-822`)——SDK コンシューマーには見えず、復旧ロジックだけが認識できる。ストリーミング終了後に復旧が必要かどうかを判断する。\n\n### 五、529 → フォールバックモデル切り替え\n\n3 回連続で 529 過負荷エラーが発生した後(`MAX_529_RETRIES = 3`)、CC は自動的にフォールバックモデルに切り替える(例:Opus → Sonnet)。切り替え時にすべての保留中のメッセージと tool 結果をクリアし、ユーザーに \"Switched to {model} due to high demand\" と表示する。\n\n### 六、収穫逓減の検出\n\nToken budget の「継続」は無限ではない。連続 3 回の continuation で token 増分が 500 未満の場合、システムは「続けても実質的な出力は得られない」と判断し、continuation を停止する(`tokenBudget.ts:60-62`)。\n\n
\n\n\n" + "content": "# s11: Error Recovery — エラーは終わりではなく、リトライの始まり\n\ns01 → ... → s09 → s10 → `s11` → [s12](/ja/s12) → s13 → ... → s20 → s21\n> *\"エラーは終わりではなく、リトライの始まり\"* — トークン拡張、コンテキスト圧縮、モデル切り替え。\n>\n> **Harness 層**: 耐障害性 — メインループのエラーを分類し復旧。\n\n---\n\n## 課題\n\nAgent が動いている途中でエラーが出た:\n\n```\nError: 529 overloaded\n```\n\nAgent がクラッシュした。リトライもしない、モデルも切り替えない、コンテキストも減らさない——そのままクラッシュ。\n\nLLM API の呼び出しは失敗することがある。この章では、出力の切り詰め、コンテキスト超過、一時的障害(429/529)の 3 つを扱う。\n\n---\n\n## 解決策\n\n![Error Recovery Overview](/course-assets/s11_error_recovery/error-recovery-overview.ja.svg)\n\ns10 のループ、prompt 組み立てはすべてそのまま。唯一の変更点:LLM 呼び出しを try/except で包み、エラータイプに応じて異なる復旧パスに振り分ける。復旧後は `continue` でループ先頭に戻り、再度 LLM を呼び出す。\n\nこの章では 3 つの復旧パターンを実装する:\n\n| パターン | トリガー | 復旧アクション |\n|----------|----------|---------------|\n| 出力切り詰め | `max_tokens` | 8K→64K に拡張 / 続きのプロンプト注入 |\n| コンテキスト超過 | `prompt_too_long` | reactive compact → リトライ |\n| 一時的障害 | 429 / 529 | 指数バックオフ + ジッター、連続 529 でフォールバックモデルに切り替え可能 |\n\n---\n\n## 仕組み\n\n### パス 1: 出力が切り詰められた\n\nモデルが途中まで出力して、`max_tokens` に達した。デフォルトの 8000 token では完全な回答を出力しきれない。\n\n初回発生時、`max_tokens` を 8K から 64K に拡張(8 倍の空間)し、同じリクエストをリトライする——この時、切り詰められた出力は messages に追加せず、元のリクエストをそのまま維持する。64K でも足りない場合にのみ、切り詰められた出力を保存し、続きのプロンプトを注入してモデルに先ほどの続きを出力させる。最大 3 回まで:\n\n```python\nif response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n continue # messages unchanged, same request with more tokens\n # 64K still truncated: save output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\":\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"})\n state.recovery_count += 1\n continue\n return # still truncated after 3 continuations\n# Normal: append after max_tokens check\nmessages.append({\"role\": \"assistant\", \"content\": response.content})\n```\n\n拡張は 1 回だけ、続きの出力は最大 3 回。超過したら終了——これ以上続けても実質的な出力は得られない。\n\n### パス 2: コンテキスト超過\n\nLLM が「コンテキストが長すぎる」と返す(`prompt_too_long`)。s08 の 4 層圧縮をすべて実行したのに、まだ超えている。\n\nreactive compact を実行し、最後の 5 メッセージを残して 1 回だけ再試行する。それでも上限を超える場合は終了する:\n\n```python\nexcept PromptTooLongError:\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return # 圧縮済みでも超過、終了するしかない\n```\n\n### パス 3: 一時的障害\n\nネットワークの揺らぎ、429 レート制限、529 過負荷——これらはバグではなく、分散システムの日常だ。\n\n429 と 529 は統一して指数バックオフ + ジッターを使用:1 回目は 0.5 秒待機、2 回目は 1 秒、3 回目は 2 秒、最大 10 回。ランダムジッターを加えることで、並行リクエストが同時にリトライするのを防ぐ。3 回連続で 529 過負荷 → フォールバックモデルに切り替え(`FALLBACK_MODEL_ID` 環境変数が設定されている場合):\n\n```python\ndef retry_delay(attempt, retry_after=None):\n if retry_after:\n return retry_after\n base = min(500 * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\ndef with_retry(fn, state, max_retries=10):\n for attempt in range(max_retries):\n try:\n return fn()\n except (RateLimitError, OverloadedError):\n delay = retry_delay(attempt)\n time.sleep(delay)\n if is_overloaded:\n state.consecutive_529 += 1\n if state.consecutive_529 >= 3 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n raise MaxRetriesExceeded()\n```\n\nバックオフの公式:`min(500 × 2^attempt, 32000) + random(0~25%)`。サーバーが `Retry-After` ヘッダーを返した場合、その値を優先して使用する。\n\n### 統合して実行\n\n```python\ndef agent_loop(messages, context):\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = 8000\n\n while True:\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n return\n log_error(e)\n return\n\n # max_tokens check BEFORE appending to messages\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = 64000\n state.has_escalated = True\n continue # retry same request, messages unchanged\n # save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n continue\n # Normal completion\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n # ... tool execution ...\n```\n\n外側の try/except が API 例外(prompt_too_long 等)を捕捉し、`with_retry` が一時的エラー(429/529)を処理し、`stop_reason` のチェックが切り詰めを処理する。3 つの復旧メカニズムがそれぞれ異なるエラータイプを担当する。\n\n---\n\n## s10 からの変更点\n\n| コンポーネント | 変更前 (s10) | 変更後 (s11) |\n|---------------|-------------|-------------|\n| エラー処理 | なし(エラーで即クラッシュ) | 3 つの復旧パターン + 指数バックオフ |\n| 新規定数 | — | ESCALATED_MAX_TOKENS=64000, MAX_RETRIES=10, BASE_DELAY_MS=500, FALLBACK_MODEL |\n| 新規関数 | — | with_retry, retry_delay, reactive_compact, is_prompt_too_long_error, RecoveryState |\n| ツール | bash, read_file, write_file (3) | bash, read_file, write_file (3) — 変更なし |\n| ループ | LLM を直接呼び出し | try/except で包み + continue でリトライ |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s11_error_recovery/code.py\n```\n\n以下の prompt を試してみよう:\n\n1. Agent に長いコードを生成させ、切り詰め後に自動で続きが出力されるか観察する(`[max_tokens] escalating` ログを確認)\n2. 連続して大量のファイルを読み込みコンテキストを肥大化させ、reactive compact の動作を観察する\n3. 429/529 が発生した場合、指数バックオフのログ出力を観察する\n\n---\n\n## 次のステップ\n\nAgent はエラーから自動的に復旧できるようになった。しかし、まだ処理するタスクは「使い捨て」だ——タスクを与えると実行し、終わる。\n\nAgent に**タスクリスト**を管理させられないだろうか——依存関係があり、ディスクに永続化され、セッションをまたいで復旧できる?TODO リストはタスクシステムではない。\n\ns12 Task System → タスクとは依存関係があり、状態があり、永続化されたグラフだ。これはマルチ Agent 協調の基盤となる。\n\n\n\n" }, { "version": "s12", "locale": "en", "title": "s12: Task System — Break Big Goals into Small Tasks", - "content": "# s12: Task System — Break Big Goals into Small Tasks\n\ns01 → ... → s10 → s11 → `s12` → [s13](/en/s13) → s14 → ... → s20 → s21 → s22\n\n> *\"Break big goals into small tasks, order them, persist\"* — File-persisted task graph, the foundation for multi-agent collaboration.\n>\n> **Harness Layer**: Tasks — Persisted goals, recoverable progress.\n\n---\n\n## The Problem\n\nThe agent receives a project: set up a database, write APIs, add tests. It uses s05's TodoWrite to create a checklist, then starts writing the API first, gets halfway through and realizes there are no database tables, goes back to fix them; when adding tests, discovers the API interface signatures have changed again...\n\nYou can't build the roof before laying the foundation. Tasks have ordering. Task dependencies should form a Directed Acyclic Graph (DAG); the teaching version only demonstrates `blockedBy` checking, without cycle detection.\n\ns05's TodoWrite is an execution checklist for the current task, kept in session memory. What you need here is a **task system**: each task is a JSON file, tasks have `blockedBy` dependencies, and they persist across sessions on disk.\n\n---\n\n## The Solution\n\n![Task System Overview](/course-assets/s12_task_system/task-system-overview.en.svg)\n\nTeaching code keeps a basic agent loop, omitting S11's full error recovery (RecoveryState, backoff, escalation, reactive compact, fallback model) to stay focused on the task system. Added: 5 teaching tools + `.tasks/` directory for persistence + `blockedBy` dependency checking. The task system and error recovery are independent layers: in CC source, `utils/tasks.ts` handles task state while query recovery handles model-call failures.\n\nTodoWrite vs Task System:\n\n| | TodoWrite (s05) | Task System (s12) |\n|---|---|---|\n| Role | Execution checklist for the current task | Recoverable task system |\n| Storage | In-process / session state | `.tasks/{id}.json` |\n| Dependencies | None | `blockedBy` / `blocks` graph |\n| Lifecycle | Current session / current task | Cross-session |\n| Coordination | No task claiming | `owner` / claim |\n| Status | pending / in_progress / completed | pending / in_progress / completed |\n| Granularity | The agent's own steps | Tasks that can be claimed, tracked, and unblocked |\n| Update contract | Replace the whole checklist | Create/get/update/list individual records |\n\nThe teaching API spells the lifecycle out as `create_task`, `list_tasks`, `get_task`, `claim_task`, and `complete_task`. Claude Code's product surface groups those operations into four tools: `TaskCreate`, `TaskGet`, `TaskUpdate`, and `TaskList`; claiming and completion are updates, not separate official tools.\n\n---\n\n## How It Works\n\n![Task DAG](/course-assets/s12_task_system/task-dag.en.svg)\n\n### Task: Data Structure\n\nEach task is a JSON file, stored in the `.tasks/` directory:\n\n```python\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent name (multi-agent scenarios)\n blockedBy: list[str] # List of dependency task IDs\n```\n\nIDs are generated with `timestamp + random hex`, simple but sufficient. CC uses sequential IDs + a highwatermark file to prevent ID reuse, which is a more rigorous design.\n\n### create_task: Create Tasks\n\n```python\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random_hex(4)}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n```\n\nAutomatically calls `save_task` on creation to write `.tasks/{id}.json`. `blockedBy` declares dependencies, for example \"write API\" has `blockedBy: [\"task_schema\"]`.\n\n### can_start: Dependency Check\n\nA task can only start after all its `blockedBy` dependencies are **completed**:\n\n```python\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False # missing dependency = blocked\n dep = load_task(dep_id)\n if dep.status != \"completed\":\n return False\n return True\n```\n\n`can_start` is a prerequisite check for `claim_task`: if any `blockedBy` dependency is not completed, the task cannot be claimed. Missing dependencies are treated as blocked, avoiding crashes from referencing wrong IDs.\n\n### claim_task: Claim a Task\n\nWhen the agent starts working on a task, it calls `claim_task`: sets `owner`, changes status from `pending` → `in_progress`. The `owner` field records who is working on the task, preventing duplicate claims in multi-agent scenarios:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task_id} ({task.subject})\"\n```\n\nIf the task is already claimed by someone else (`status != \"pending\"`), or dependencies aren't met (`can_start` returns False), the claim is rejected.\n\n### complete_task: Complete and Unblock\n\nWhen a task is done, set it to `completed`. Simultaneously scan all other tasks to find downstream tasks that were **just unblocked**:\n\n```python\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n task.status = \"completed\"\n save_task(task)\n # Find newly unblocked downstream tasks\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy\n and can_start(t.id)]\n msg = f\"Completed {task_id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n```\n\nAfter completing \"schema\", `can_start` returns True for \"endpoints\" and \"docs\"; they can begin.\n\n### get_task: View Full Details\n\n`list_tasks` only shows a one-line summary. `get_task` returns the full task JSON, including description and dependency details. When recovering across sessions, the agent needs to read the full description to continue work:\n\n```python\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n```\n\n### State Machine: Two Actions, Three States\n\n```\npending ──claim──→ in_progress ──complete──→ completed\n```\n\nHere `claim` / `complete` are actions, while `pending` / `in_progress` / `completed` are states:\n\n- **claim_task**: `pending` → `in_progress`. Sets owner, begins work.\n- **complete_task**: `in_progress` → `completed`. Marks the task done and unblocks downstream.\n\nCC has no `in_progress → pending` release path. If a teammate terminates or shuts down, CC unassigns its unfinished tasks (clears owner) and resets status to `pending`, allowing other agents to reclaim them. The teaching version omits this recovery path.\n\n### Putting It Together\n\n```python\n# Create tasks with dependencies\nschema = create_task(\"setup database schema\")\nendpoints = create_task(\"create API endpoints\", blockedBy=[schema.id])\ntests = create_task(\"write tests\", blockedBy=[endpoints.id])\ndocs = create_task(\"write docs\", blockedBy=[schema.id])\n\n# Agent claims the first available task\nclaim_task(schema.id) # ✓ Claimed (no dependencies)\ncomplete_task(schema.id) # ✓ Completed → unblocks endpoints, docs\n\nclaim_task(endpoints.id) # ✓ Claimed (schema completed)\ncomplete_task(endpoints.id) # ✓ Completed → unblocks tests\n\nclaim_task(docs.id) # ✓ Claimed (schema completed)\ncomplete_task(docs.id) # ✓ Completed\n\nclaim_task(tests.id) # ✓ Claimed (endpoints completed)\ncomplete_task(tests.id) # ✓ Completed\n```\n\nEach `create_task` writes a JSON file, each `claim_task` / `complete_task` updates the file. Across sessions, the `.tasks/` directory persists — the agent reads the files to recover progress.\n\n---\n\n## Changes from s11\n\n| Component | Before (s11) | After (s12) |\n|-----------|-------------|-------------|\n| Task management | None | Task dataclass + 5 tools |\n| New types | — | Task (id, subject, description, status, owner, blockedBy) |\n| Storage | No persistence | `.tasks/{id}.json` cross-session |\n| Dependencies | None | `blockedBy` graph + `can_start` check |\n| Tools | bash, read_file, write_file (3) | + create_task, list_tasks, get_task, claim_task, complete_task (8) |\n| Lifecycle | — | pending → in_progress → completed (no release rollback) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s12_task_system/code.py\n```\n\nTry these prompts:\n\n1. `Create tasks: setup database schema, create API endpoints (depends on schema), write tests (depends on endpoints), write docs (depends on schema)`\n2. `List all tasks and their statuses`\n3. `Claim the first unblocked task and complete it`\n4. `List tasks again — which ones are now unblocked?`\n\nWhat to observe: Are JSON files generated in the `.tasks/` directory? After completing a task, are the blocked tasks unblocked?\n\n---\n\n## What's Next\n\nThe task graph is in place. But some tasks take a long time — like running full test suites or deploying to a server. The agent calls the LLM billed by token, it can't afford to wait on a slow operation.\n\ns13 Background Tasks → Slow operations go to the background. The agent continues processing other tasks, and gets notified when the background work is done.\n\n
\nDeep Dive into CC Source\n\n> The following is a complete analysis based on CC source code `utils/tasks.ts` (862 lines), `tools/TaskCreateTool/TaskCreateTool.ts` (138 lines), `tools/TaskUpdateTool/TaskUpdateTool.ts` (406 lines), `tools/TaskGetTool/TaskGetTool.ts` (128 lines), `tools/TaskListTool/TaskListTool.ts` (116 lines), `hooks/useTaskListWatcher.ts` (221 lines).\n\n### 1. TaskRecord's Full Fields\n\nThe tutorial only covers id, subject, status, owner, blockedBy. CC actually has 9 fields (`utils/tasks.ts:76-89`):\n\n| Field | Type | Purpose |\n|------|------|---------|\n| `id` | string | Incrementing integer ID |\n| `subject` | string | Short title |\n| `description` | string | Free-form description |\n| `activeForm` | string? | Present tense form, shown in spinner when in_progress |\n| `owner` | string? | Assigned agent ID |\n| `status` | pending/in_progress/completed | Lifecycle |\n| `blocks` | string[] | Task IDs blocked by this task (downstream) |\n| `blockedBy` | string[] | Task IDs blocking this task (upstream) |\n| `metadata` | Record? | Arbitrary extension key-value pairs |\n\nStorage location: `~/.claude/tasks/{taskListId}/{id}.json`. One file per task.\n\n### 2. Same Intent, Independent Mechanisms\n\nTask tools and TodoWrite can coexist, but they do not share one storage model. Current interactive sessions default to structured Task tools, while TodoWrite remains on compatibility surfaces such as non-interactive and Agent SDK usage; exact exposure varies by release and configuration. Task records add file-lock concurrency protection, dependency enforcement, ownership, reactive monitoring, and lifecycle hooks. TodoWrite remains a whole-list session checklist.\n\n### 3. Concurrent Claim Locking\n\n`claimTask()` (`utils/tasks.ts:541-612`) uses dual locking to prevent races:\n\n**Task file lock**: `proper-lockfile` locks `{taskId}.json` (up to 30 retries, exponential backoff 5-100ms). Inside the lock:\n1. Re-read task (prevent TOCTOU)\n2. Check already claimed by another → `already_claimed`\n3. Check already completed → `already_resolved`\n4. Check upstream not completed → `blocked`\n5. Set owner\n\n**List-level lock** (agent busy check): `.lock` file, atomic scan of all tasks to check if the agent already has other open tasks.\n\nNote: The teaching version combines claiming and starting work into one step (claim = set owner + in_progress); real CC's `claimTask` primarily resolves owner competition — it only sets owner without changing status. Status updates are handled by `TaskUpdate`.\n\n### 4. High-Water Mark to Prevent ID Reuse\n\nThe `.highwatermark` file records the highest task ID ever assigned. Even if a task is deleted, its ID won't be reused.\n\n### 5. Four Task Tools\n\nCC's task system has four tools (not the tutorial's single generic Task tool): `TaskCreate`, `TaskGet`, `TaskUpdate`, `TaskList`. All set `isConcurrencySafe: true` and `shouldDefer: true` (tool schemas aren't in the initial prompt; only visible after ToolSearch).\n\nThe teaching version's `create_task(blockedBy=...)` declares dependencies at creation time, which is a reasonable simplification. Real CC's `TaskCreate` only accepts subject/description/activeForm/metadata — dependencies are maintained via `TaskUpdate`'s `addBlocks/addBlockedBy`.\n\n
\n\n\n" + "content": "# s12: Task System — Break Big Goals into Small Tasks\n\ns01 → ... → s10 → s11 → `s12` → [s13](/en/s13) → s14 → ... → s20 → s21\n\n> *\"Break big goals into small tasks, order them, persist\"* — File-persisted task graph, the foundation for multi-agent collaboration.\n>\n> **Harness Layer**: Tasks — Persisted goals, recoverable progress.\n\n---\n\n## The Problem\n\nThe agent receives a project: set up a database, write APIs, add tests. It uses s05's TodoWrite to create a checklist, then starts writing the API first, gets halfway through and realizes there are no database tables, goes back to fix them; when adding tests, discovers the API interface signatures have changed again...\n\nYou can't build the roof before laying the foundation. Tasks have ordering. Task prerequisites can be represented as a Directed Acyclic Graph (DAG); this chapter records them with `blockedBy`.\n\ns05's TodoWrite is an execution checklist for the current task, kept in session memory. What you need here is a **task system**: each task is a JSON file, tasks have `blockedBy` dependencies, and they persist across sessions on disk.\n\n---\n\n## The Solution\n\n![Task System Overview](/course-assets/s12_task_system/task-system-overview.en.svg)\n\nThis chapter adds 5 task tools, persistence in the `.tasks/` directory, and `blockedBy` dependency checks.\n\nTodoWrite vs Task System:\n\n| | TodoWrite (s05) | Task System (s12) |\n|---|---|---|\n| Role | Execution checklist for the current task | Recoverable task system |\n| Storage | In-process / session state | `.tasks/{id}.json` |\n| Dependencies | None | `blockedBy` / `blocks` graph |\n| Lifecycle | Current session / current task | Cross-session |\n| Coordination | No task claiming | `owner` / claim |\n| Status | pending / in_progress / completed | pending / in_progress / completed |\n| Granularity | The agent's own steps | Tasks that can be claimed, tracked, and unblocked |\n| Update contract | Replace the whole checklist | Create/get/update/list individual records |\n\n---\n\n## How It Works\n\n![Task DAG](/course-assets/s12_task_system/task-dag.en.svg)\n\n### Task: Data Structure\n\nEach task is a JSON file, stored in the `.tasks/` directory:\n\n```python\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent name (multi-agent scenarios)\n blockedBy: list[str] # List of dependency task IDs\n```\n\nIDs are generated with `timestamp + random hex`.\n\n### create_task: Create Tasks\n\n```python\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random_hex(4)}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n```\n\nAutomatically calls `save_task` on creation to write `.tasks/{id}.json`. `blockedBy` declares dependencies, for example \"write API\" has `blockedBy: [\"task_schema\"]`.\n\n### can_start: Dependency Check\n\nA task can only start after all its `blockedBy` dependencies are **completed**:\n\n```python\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False # missing dependency = blocked\n dep = load_task(dep_id)\n if dep.status != \"completed\":\n return False\n return True\n```\n\n`can_start` is a prerequisite check for `claim_task`: if any `blockedBy` dependency is not completed, the task cannot be claimed. Missing dependencies are treated as blocked, avoiding crashes from referencing wrong IDs.\n\n### claim_task: Claim a Task\n\nWhen the agent starts working on a task, it calls `claim_task`: sets `owner`, changes status from `pending` → `in_progress`. The `owner` field records who is working on the task, preventing duplicate claims in multi-agent scenarios:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task_id} ({task.subject})\"\n```\n\nIf the task is already claimed by someone else (`status != \"pending\"`), or dependencies aren't met (`can_start` returns False), the claim is rejected.\n\n### complete_task: Complete and Unblock\n\nWhen a task is done, set it to `completed`. Simultaneously scan all other tasks to find downstream tasks that were **just unblocked**:\n\n```python\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n task.status = \"completed\"\n save_task(task)\n # Find newly unblocked downstream tasks\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy\n and can_start(t.id)]\n msg = f\"Completed {task_id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n```\n\nAfter completing \"schema\", `can_start` returns True for \"endpoints\" and \"docs\"; they can begin.\n\n### get_task: View Full Details\n\n`list_tasks` only shows a one-line summary. `get_task` returns the full task JSON, including description and dependency details. When recovering across sessions, the agent needs to read the full description to continue work:\n\n```python\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n```\n\n### State Machine: Two Actions, Three States\n\n```\npending ──claim──→ in_progress ──complete──→ completed\n```\n\nHere `claim` / `complete` are actions, while `pending` / `in_progress` / `completed` are states:\n\n- **claim_task**: `pending` → `in_progress`. Sets owner, begins work.\n- **complete_task**: `in_progress` → `completed`. Marks the task done and unblocks downstream.\n\n### Putting It Together\n\n```python\n# Create tasks with dependencies\nschema = create_task(\"setup database schema\")\nendpoints = create_task(\"create API endpoints\", blockedBy=[schema.id])\ntests = create_task(\"write tests\", blockedBy=[endpoints.id])\ndocs = create_task(\"write docs\", blockedBy=[schema.id])\n\n# Agent claims the first available task\nclaim_task(schema.id) # ✓ Claimed (no dependencies)\ncomplete_task(schema.id) # ✓ Completed → unblocks endpoints, docs\n\nclaim_task(endpoints.id) # ✓ Claimed (schema completed)\ncomplete_task(endpoints.id) # ✓ Completed → unblocks tests\n\nclaim_task(docs.id) # ✓ Claimed (schema completed)\ncomplete_task(docs.id) # ✓ Completed\n\nclaim_task(tests.id) # ✓ Claimed (endpoints completed)\ncomplete_task(tests.id) # ✓ Completed\n```\n\nEach `create_task` writes a JSON file, each `claim_task` / `complete_task` updates the file. Across sessions, the `.tasks/` directory persists — the agent reads the files to recover progress.\n\n---\n\n## Changes from s11\n\n| Component | Before (s11) | After (s12) |\n|-----------|-------------|-------------|\n| Task management | None | Task dataclass + 5 tools |\n| New types | — | Task (id, subject, description, status, owner, blockedBy) |\n| Storage | No persistence | `.tasks/{id}.json` cross-session |\n| Dependencies | None | `blockedBy` graph + `can_start` check |\n| Tools | bash, read_file, write_file (3) | + create_task, list_tasks, get_task, claim_task, complete_task (8) |\n| Lifecycle | — | pending → in_progress → completed (no release rollback) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s12_task_system/code.py\n```\n\nTry these prompts:\n\n1. `Create tasks: setup database schema, create API endpoints (depends on schema), write tests (depends on endpoints), write docs (depends on schema)`\n2. `List all tasks and their statuses`\n3. `Claim the first unblocked task and complete it`\n4. `List tasks again — which ones are now unblocked?`\n\nWhat to observe: Are JSON files generated in the `.tasks/` directory? After completing a task, are the blocked tasks unblocked?\n\n---\n\n## What's Next\n\nThe task graph is in place. But some tasks take a long time — like running full test suites or deploying to a server. The agent calls the LLM billed by token, it can't afford to wait on a slow operation.\n\ns13 Background Tasks → Slow operations go to the background. The agent continues processing other tasks, and gets notified when the background work is done.\n\n\n\n" }, { "version": "s12", "locale": "zh", "title": "s12: Task System — 目标太大,拆成小任务", - "content": "# s12: Task System — 目标太大,拆成小任务\n\ns01 → ... → s10 → s11 → `s12` → [s13](/zh/s13) → s14 → ... → s20 → s21 → s22\n\n> *\"大目标拆成小任务, 排好序, 持久化\"* — 文件持久化的任务图, 多 agent 协作的基础。\n>\n> **Harness 层**: 任务 — 持久化的目标, 可恢复的进度。\n\n---\n\n## 问题\n\nAgent 接到一个项目:搭数据库、写 API、加测试。它用 s05 的 TodoWrite 列了一张清单,然后开始写 API,写到一半发现没数据库表,回头补;加测试时发现 API 接口签名又变了...\n\n盖房子不能先盖屋顶再打地基。任务之间有先后。任务依赖应该形成有向无环图(DAG);教学版只演示 `blockedBy` 检查,没有实现环检测。\n\ns05 的 TodoWrite 是当前任务的执行清单,保存在会话内存中。这里需要的是**任务系统**:每个任务是一个 JSON 文件,任务之间有 `blockedBy` 依赖,跨会话持久化在磁盘上。\n\n---\n\n## 解决方案\n\n![Task System Overview](/course-assets/s12_task_system/task-system-overview.svg)\n\n教学代码保留基础 agent loop,为聚焦任务系统省略了 S11 的完整错误恢复(RecoveryState、退避、升级、reactive compact、fallback model)。新增 5 个教学工具 + `.tasks/` 目录持久化 + `blockedBy` 依赖检查。任务系统与错误恢复是独立层:CC 源码中的任务模块管理任务状态,query recovery 管理模型调用失败。\n\nTodoWrite vs Task System:\n\n| | TodoWrite (s05) | Task System (s12) |\n|---|---|---|\n| 定位 | 当前任务的执行清单 | 可恢复的任务系统 |\n| 存储 | 进程内 / 会话状态 | `.tasks/{id}.json` |\n| 依赖 | 无 | `blockedBy` / `blocks` 依赖图 |\n| 生命周期 | 当前会话 / 当前任务 | 跨会话保留 |\n| 分工 | 不负责任务认领 | `owner` / claim |\n| 状态 | pending / in_progress / completed | pending / in_progress / completed |\n| 粒度 | Agent 自己的步骤 | 可被认领、追踪、解锁的任务 |\n| 更新契约 | 整表替换 | 对单条记录执行创建、读取、更新、列举 |\n\n教学 API 用 `create_task`、`list_tasks`、`get_task`、`claim_task`、`complete_task` 把生命周期展开。Claude Code 的产品表面把这些操作归入四个工具:`TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList`;认领与完成属于更新,不是独立的官方工具。\n\n---\n\n## 工作原理\n\n![Task DAG](/course-assets/s12_task_system/task-dag.svg)\n\n### Task: 数据结构\n\n每个任务是一个 JSON 文件,存于 `.tasks/` 目录:\n\n```python\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent 名(多 Agent 场景)\n blockedBy: list[str] # 依赖的任务 ID 列表\n```\n\nID 用 `timestamp + random hex` 生成,简单但够用。CC 用顺序 ID + highwatermark 文件防止 ID 重用,是更严谨的设计。\n\n### create_task: 创建任务\n\n```python\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random_hex(4)}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n```\n\n创建时自动 `save_task` 到 `.tasks/{id}.json`。`blockedBy` 声明依赖,比如 \"写 API\" 的 `blockedBy` 是 `[\"task_schema\"]`。\n\n### can_start: 依赖检查\n\n一个任务只能在它的 `blockedBy` **全部 completed** 之后才能开始:\n\n```python\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False # missing dependency = blocked\n dep = load_task(dep_id)\n if dep.status != \"completed\":\n return False\n return True\n```\n\n`can_start` 是 `claim_task` 的前置检查:`blockedBy` 里有任何一个不是 completed,就不能认领。不存在的依赖视为 blocked,避免引用错误 ID 时崩溃。\n\n### claim_task: 认领任务\n\nAgent 开始做一个任务时,调用 `claim_task`:设置 `owner`,状态从 `pending` → `in_progress`。`owner` 字段记录谁在做这个任务,多 Agent 场景下防止重复认领:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task_id} ({task.subject})\"\n```\n\n如果任务已被别人认领(`status != \"pending\"`),或者依赖没完成(`can_start` 返回 False),拒绝认领。\n\n### complete_task: 完成与解锁\n\n任务做完后,设为 `completed`。同时扫描所有其他任务,找出**刚刚被解锁**的下游任务:\n\n```python\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n task.status = \"completed\"\n save_task(task)\n # 找出被解锁的下游任务\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy\n and can_start(t.id)]\n msg = f\"Completed {task_id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n```\n\n完成 \"schema\" 后,\"endpoints\" 和 \"docs\" 的 `can_start` 返回 True,它们可以开始。\n\n### get_task: 查看完整细节\n\n`list_tasks` 只显示一行摘要。`get_task` 返回完整的任务 JSON,包括 description 和依赖细节。跨会话恢复时,Agent 需要读取完整描述才能继续工作:\n\n```python\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n```\n\n### 状态机: 两个动作,三个状态\n\n```\npending ──claim──→ in_progress ──complete──→ completed\n```\n\n这里的 `claim` / `complete` 是动作,`pending` / `in_progress` / `completed` 是状态:\n\n- **claim_task**: `pending` → `in_progress`。设置 owner,开始工作。\n- **complete_task**: `in_progress` → `completed`。把任务标记为完成,并解锁下游。\n\nCC 没有 `in_progress → pending` 的 release 路径。如果 teammate 终止或 shutdown,CC 会把它未完成的任务 unassign(清除 owner),并将 status 重置为 `pending`,方便其他 agent 重新认领。教学版省略了这一恢复路径。\n\n### 合起来跑\n\n```python\n# 创建有依赖的任务\nschema = create_task(\"setup database schema\")\nendpoints = create_task(\"create API endpoints\", blockedBy=[schema.id])\ntests = create_task(\"write tests\", blockedBy=[endpoints.id])\ndocs = create_task(\"write docs\", blockedBy=[schema.id])\n\n# Agent 认领第一个可做的任务\nclaim_task(schema.id) # ✓ Claimed (无依赖)\ncomplete_task(schema.id) # ✓ Completed → 解锁 endpoints, docs\n\nclaim_task(endpoints.id) # ✓ Claimed (schema 已完成)\ncomplete_task(endpoints.id) # ✓ Completed → 解锁 tests\n\nclaim_task(docs.id) # ✓ Claimed (schema 已完成)\ncomplete_task(docs.id) # ✓ Completed\n\nclaim_task(tests.id) # ✓ Claimed (endpoints 已完成)\ncomplete_task(tests.id) # ✓ Completed\n```\n\n每个 `create_task` 写一个 JSON 文件,每个 `claim_task` / `complete_task` 更新文件。跨会话时,`.tasks/` 目录还在,Agent 读文件就能恢复进度。\n\n---\n\n## 相对 s11 的变更\n\n| 组件 | 之前 (s11) | 之后 (s12) |\n|------|-----------|-----------|\n| 任务管理 | 无 | Task dataclass + 5 个工具 |\n| 新类型 | — | Task(id, subject, description, status, owner, blockedBy) |\n| 存储 | 无持久化 | `.tasks/{id}.json` 跨会话 |\n| 依赖 | 无 | `blockedBy` 图 + `can_start` 检查 |\n| 工具 | bash, read_file, write_file (3) | + create_task, list_tasks, get_task, claim_task, complete_task (8) |\n| 生命周期 | — | pending → in_progress → completed(无 release 回退) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s12_task_system/code.py\n```\n\n试试这些 prompt:\n\n1. `Create tasks: setup database schema, create API endpoints (depends on schema), write tests (depends on endpoints), write docs (depends on schema)`\n2. `List all tasks and their statuses`\n3. `Claim the first unblocked task and complete it`\n4. `List tasks again — which ones are now unblocked?`\n\n观察重点:`.tasks/` 目录下是否生成了 JSON 文件?完成任务后,被阻塞的任务是否解锁?\n\n---\n\n## 接下来\n\n任务图有了。但有些任务要跑很久——比如全量测试、部署到服务器。Agent 调 LLM 按量计费,不能干等一个慢操作。\n\ns13 Background Tasks → 慢操作放后台。Agent 继续处理其他任务,后台跑完了通知它。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `utils/tasks.ts`(862 行)、`tools/TaskCreateTool/TaskCreateTool.ts`(138 行)、`tools/TaskUpdateTool/TaskUpdateTool.ts`(406 行)、`tools/TaskGetTool/TaskGetTool.ts`(128 行)、`tools/TaskListTool/TaskListTool.ts`(116 行)、`hooks/useTaskListWatcher.ts`(221 行)的分析。\n\n### 一、TaskRecord 的完整字段\n\n教学版只讲了 id、subject、status、owner、blockedBy。CC 实际有 9 个字段(`utils/tasks.ts:76-89`):\n\n| 字段 | 类型 | 用途 |\n|------|------|------|\n| `id` | string | 递增整数 ID |\n| `subject` | string | 简短标题 |\n| `description` | string | 自由格式描述 |\n| `activeForm` | string? | 进行时态,in_progress 时在 spinner 显示 |\n| `owner` | string? | 分配的 agent ID |\n| `status` | pending/in_progress/completed | 生命周期 |\n| `blocks` | string[] | 此任务阻塞的任务 ID(下游) |\n| `blockedBy` | string[] | 阻塞此任务的任务 ID(上游) |\n| `metadata` | Record? | 任意扩展键值对 |\n\n存储位置:`~/.claude/tasks/{taskListId}/{id}.json`。每个任务一个文件。\n\n### 二、目标相近,机制独立\n\nTask 工具与 TodoWrite 可以同时存在,但不共享一套存储模型。当前交互式会话默认使用结构化 Task 工具;TodoWrite 仍位于非交互式、Agent SDK 等兼容表面,具体暴露方式会随版本和配置变化。Task 记录增加了文件锁并发保护、依赖强制执行、ownership、响应式监听和生命周期 hooks;TodoWrite 仍是整表替换的会话清单。\n\n### 三、并发认领的锁机制\n\n`claimTask()`(`utils/tasks.ts:541-612`)用双重锁防竞争:\n\n**任务文件锁**:`proper-lockfile` 锁住 `{taskId}.json`(最多重试 30 次,指数退避 5-100ms)。锁内:\n1. 重新读取任务(防 TOCTOU)\n2. 检查已被他人认领 → `already_claimed`\n3. 检查已完成 → `already_resolved`\n4. 检查上游未完成 → `blocked`\n5. 设置 owner\n\n**列表级锁**(agent busy 检查时):`.lock` 文件,原子性扫描所有任务并检查该 agent 是否已有其他 open task。\n\n注意:教学版把 claim 和开始工作合成一步(claim = set owner + in_progress);真实 CC 的 `claimTask` 主要解决 owner 竞争,只设 owner 不改 status,状态更新由 `TaskUpdate` 完成。\n\n### 四、高水位标防 ID 重用\n\n`.highwatermark` 文件记录曾分配过的最高任务 ID。即使任务被删除,ID 也不会被重用。\n\n### 五、四个 Task 工具\n\nCC 的任务系统有四个工具(不是教学版的一个通用 Task 工具):`TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList`。全部设置 `isConcurrencySafe: true` 和 `shouldDefer: true`(工具 schema 不在初始 prompt 中,需 ToolSearch 后才可见)。\n\n教学版的 `create_task(blockedBy=...)` 在创建时直接声明依赖,是合理简化。真实 CC 的 `TaskCreate` 只接受 subject/description/activeForm/metadata,依赖关系由 `TaskUpdate` 的 `addBlocks/addBlockedBy` 维护。\n\n
\n\n\n" + "content": "# s12: Task System — 目标太大,拆成小任务\n\ns01 → ... → s10 → s11 → `s12` → [s13](/zh/s13) → s14 → ... → s20 → s21\n\n> *\"大目标拆成小任务, 排好序, 持久化\"* — 文件持久化的任务图, 多 agent 协作的基础。\n>\n> **Harness 层**: 任务 — 持久化的目标, 可恢复的进度。\n\n---\n\n## 问题\n\nAgent 接到一个项目:搭数据库、写 API、加测试。它用 s05 的 TodoWrite 列了一张清单,然后开始写 API,写到一半发现没数据库表,回头补;加测试时发现 API 接口签名又变了...\n\n盖房子不能先盖屋顶再打地基。任务之间有先后。任务之间的前置依赖可以表示为有向无环图(DAG),本章用 `blockedBy` 记录这些依赖。\n\ns05 的 TodoWrite 是当前任务的执行清单,保存在会话内存中。这里需要的是**任务系统**:每个任务是一个 JSON 文件,任务之间有 `blockedBy` 依赖,跨会话持久化在磁盘上。\n\n---\n\n## 解决方案\n\n![Task System Overview](/course-assets/s12_task_system/task-system-overview.svg)\n\n本章新增 5 个任务工具、`.tasks/` 目录持久化和 `blockedBy` 依赖检查。\n\nTodoWrite vs Task System:\n\n| | TodoWrite (s05) | Task System (s12) |\n|---|---|---|\n| 定位 | 当前任务的执行清单 | 可恢复的任务系统 |\n| 存储 | 进程内 / 会话状态 | `.tasks/{id}.json` |\n| 依赖 | 无 | `blockedBy` / `blocks` 依赖图 |\n| 生命周期 | 当前会话 / 当前任务 | 跨会话保留 |\n| 分工 | 不负责任务认领 | `owner` / claim |\n| 状态 | pending / in_progress / completed | pending / in_progress / completed |\n| 粒度 | Agent 自己的步骤 | 可被认领、追踪、解锁的任务 |\n| 更新契约 | 整表替换 | 对单条记录执行创建、读取、更新、列举 |\n\n---\n\n## 工作原理\n\n![Task DAG](/course-assets/s12_task_system/task-dag.svg)\n\n### Task: 数据结构\n\n每个任务是一个 JSON 文件,存于 `.tasks/` 目录:\n\n```python\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent 名(多 Agent 场景)\n blockedBy: list[str] # 依赖的任务 ID 列表\n```\n\nID 使用 `timestamp + random hex` 生成。\n\n### create_task: 创建任务\n\n```python\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random_hex(4)}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n```\n\n创建时自动 `save_task` 到 `.tasks/{id}.json`。`blockedBy` 声明依赖,比如 \"写 API\" 的 `blockedBy` 是 `[\"task_schema\"]`。\n\n### can_start: 依赖检查\n\n一个任务只能在它的 `blockedBy` **全部 completed** 之后才能开始:\n\n```python\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False # missing dependency = blocked\n dep = load_task(dep_id)\n if dep.status != \"completed\":\n return False\n return True\n```\n\n`can_start` 是 `claim_task` 的前置检查:`blockedBy` 里有任何一个不是 completed,就不能认领。不存在的依赖视为 blocked,避免引用错误 ID 时崩溃。\n\n### claim_task: 认领任务\n\nAgent 开始做一个任务时,调用 `claim_task`:设置 `owner`,状态从 `pending` → `in_progress`。`owner` 字段记录谁在做这个任务,多 Agent 场景下防止重复认领:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task_id} ({task.subject})\"\n```\n\n如果任务已被别人认领(`status != \"pending\"`),或者依赖没完成(`can_start` 返回 False),拒绝认领。\n\n### complete_task: 完成与解锁\n\n任务做完后,设为 `completed`。同时扫描所有其他任务,找出**刚刚被解锁**的下游任务:\n\n```python\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n task.status = \"completed\"\n save_task(task)\n # 找出被解锁的下游任务\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy\n and can_start(t.id)]\n msg = f\"Completed {task_id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n```\n\n完成 \"schema\" 后,\"endpoints\" 和 \"docs\" 的 `can_start` 返回 True,它们可以开始。\n\n### get_task: 查看完整细节\n\n`list_tasks` 只显示一行摘要。`get_task` 返回完整的任务 JSON,包括 description 和依赖细节。跨会话恢复时,Agent 需要读取完整描述才能继续工作:\n\n```python\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n```\n\n### 状态机: 两个动作,三个状态\n\n```\npending ──claim──→ in_progress ──complete──→ completed\n```\n\n这里的 `claim` / `complete` 是动作,`pending` / `in_progress` / `completed` 是状态:\n\n- **claim_task**: `pending` → `in_progress`。设置 owner,开始工作。\n- **complete_task**: `in_progress` → `completed`。把任务标记为完成,并解锁下游。\n\n### 合起来跑\n\n```python\n# 创建有依赖的任务\nschema = create_task(\"setup database schema\")\nendpoints = create_task(\"create API endpoints\", blockedBy=[schema.id])\ntests = create_task(\"write tests\", blockedBy=[endpoints.id])\ndocs = create_task(\"write docs\", blockedBy=[schema.id])\n\n# Agent 认领第一个可做的任务\nclaim_task(schema.id) # ✓ Claimed (无依赖)\ncomplete_task(schema.id) # ✓ Completed → 解锁 endpoints, docs\n\nclaim_task(endpoints.id) # ✓ Claimed (schema 已完成)\ncomplete_task(endpoints.id) # ✓ Completed → 解锁 tests\n\nclaim_task(docs.id) # ✓ Claimed (schema 已完成)\ncomplete_task(docs.id) # ✓ Completed\n\nclaim_task(tests.id) # ✓ Claimed (endpoints 已完成)\ncomplete_task(tests.id) # ✓ Completed\n```\n\n每个 `create_task` 写一个 JSON 文件,每个 `claim_task` / `complete_task` 更新文件。跨会话时,`.tasks/` 目录还在,Agent 读文件就能恢复进度。\n\n---\n\n## 相对 s11 的变更\n\n| 组件 | 之前 (s11) | 之后 (s12) |\n|------|-----------|-----------|\n| 任务管理 | 无 | Task dataclass + 5 个工具 |\n| 新类型 | — | Task(id, subject, description, status, owner, blockedBy) |\n| 存储 | 无持久化 | `.tasks/{id}.json` 跨会话 |\n| 依赖 | 无 | `blockedBy` 图 + `can_start` 检查 |\n| 工具 | bash, read_file, write_file (3) | + create_task, list_tasks, get_task, claim_task, complete_task (8) |\n| 生命周期 | — | pending → in_progress → completed(无 release 回退) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s12_task_system/code.py\n```\n\n试试这些 prompt:\n\n1. `Create tasks: setup database schema, create API endpoints (depends on schema), write tests (depends on endpoints), write docs (depends on schema)`\n2. `List all tasks and their statuses`\n3. `Claim the first unblocked task and complete it`\n4. `List tasks again — which ones are now unblocked?`\n\n观察重点:`.tasks/` 目录下是否生成了 JSON 文件?完成任务后,被阻塞的任务是否解锁?\n\n---\n\n## 接下来\n\n任务图有了。但有些任务要跑很久——比如全量测试、部署到服务器。Agent 调 LLM 按量计费,不能干等一个慢操作。\n\ns13 Background Tasks → 慢操作放后台。Agent 继续处理其他任务,后台跑完了通知它。\n\n\n\n" }, { "version": "s12", "locale": "ja", "title": "s12: Task System — 大きな目標を小さなタスクに分割", - "content": "# s12: Task System — 大きな目標を小さなタスクに分割\n\ns01 → ... → s10 → s11 → `s12` → [s13](/ja/s13) → s14 → ... → s20 → s21 → s22\n\n> *\"大きな目標を小さなタスクに分け、順序付け、永続化\"* — ファイル永続化タスクグラフ、マルチ Agent 協調の基盤。\n>\n> **Harness 層**: タスク — 永続化された目標、復旧可能な進捗。\n\n---\n\n## 課題\n\nAgent がプロジェクトを受けた:データベース構築、API 実装、テスト追加。s05 の TodoWrite でリストを作り、まず API を書き始め、途中でデータベーステーブルがないことに気づいて戻る。テスト追加時に API インターフェースのシグネチャがまた変わっている...\n\n屋根を先に建てて基礎を後から打つことはできない。タスクには順序がある。タスクの依存関係は有向非巡回グラフ(DAG)を形成すべき;教学版は `blockedBy` チェックのみをデモし、循環検出は実装していない。\n\ns05 の TodoWrite は現在のタスクの実行チェックリストで、セッションメモリに保持される。ここで必要なのは**タスクシステム**:各タスクは JSON ファイル、タスク間に `blockedBy` 依存関係、ディスク上でセッションをまたいで永続化。\n\n---\n\n## ソリューション\n\n![Task System Overview](/course-assets/s12_task_system/task-system-overview.ja.svg)\n\n教育版は基本 agent loop を維持し、タスクシステムに集中するため S11 の完全なエラーリカバリ(RecoveryState、バックオフ、エスカレーション、reactive compact、フォールバックモデル)を省略。追加:5 つの教育用ツール + `.tasks/` ディレクトリによる永続化 + `blockedBy` 依存チェック。タスクシステムとエラーリカバリは独立したレイヤーで、タスクモジュールは状態を、query recovery はモデル呼び出し失敗を扱う。\n\nTodoWrite vs Task System:\n\n| | TodoWrite (s05) | Task System (s12) |\n|---|---|---|\n| 位置づけ | 現在のタスクの実行チェックリスト | 復旧可能なタスクシステム |\n| ストレージ | プロセス内 / セッション状態 | `.tasks/{id}.json` |\n| 依存関係 | なし | `blockedBy` / `blocks` グラフ |\n| ライフサイクル | 現在のセッション / 現在のタスク | セッション横断 |\n| 分担 | タスク認識を扱わない | `owner` / claim |\n| ステータス | pending / in_progress / completed | pending / in_progress / completed |\n| 粒度 | Agent 自身の手順 | 認識・追跡・アンロックできるタスク |\n| 更新契約 | リスト全体を置換 | 個別レコードを作成・取得・更新・一覧 |\n\n教育用 API は `create_task`、`list_tasks`、`get_task`、`claim_task`、`complete_task` としてライフサイクルを明示する。Claude Code の製品サーフェスはこれらを `TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList` の 4 ツールにまとめ、認識と完了は独立した公式ツールではなく更新操作として扱う。\n\n---\n\n## 仕組み\n\n![Task DAG](/course-assets/s12_task_system/task-dag.ja.svg)\n\n### Task: データ構造\n\n各タスクは JSON ファイル、`.tasks/` ディレクトリに保存:\n\n```python\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent 名(マルチ Agent シナリオ)\n blockedBy: list[str] # 依存タスク ID のリスト\n```\n\nID は `timestamp + random hex` で生成、シンプルだが十分。CC は順次 ID + highwatermark ファイルで ID 再利用を防止する、より厳密な設計。\n\n### create_task: タスク作成\n\n```python\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random_hex(4)}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n```\n\n作成時に自動的に `save_task` で `.tasks/{id}.json` に書き込み。`blockedBy` で依存を宣言、例えば \"API を書く\" の `blockedBy` は `[\"task_schema\"]`。\n\n### can_start: 依存チェック\n\nタスクは `blockedBy` が**すべて completed** になってからでないと開始できない:\n\n```python\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False # missing dependency = blocked\n dep = load_task(dep_id)\n if dep.status != \"completed\":\n return False\n return True\n```\n\n`can_start` は `claim_task` の事前チェック:`blockedBy` に一つでも completed でないものがあれば、認識不可。存在しない依存は blocked として扱い、誤った ID 参照時のクラッシュを防ぐ。\n\n### claim_task: タスク認識\n\nAgent がタスクに取り掛かる時、`claim_task` を呼び出し:`owner` を設定、ステータスを `pending` → `in_progress` に変更。`owner` フィールドは誰が作業中かを記録し、マルチ Agent シナリオで重複認識を防止:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task_id} ({task.subject})\"\n```\n\nタスクが既に他者に認識されている(`status != \"pending\"`)、または依存が未完了(`can_start` が False)の場合、認識を拒否。\n\n### complete_task: 完了とアンロック\n\nタスク完了後、`completed` に設定。同時に他の全タスクを走査し、**直前にアンロックされた**下流タスクを特定:\n\n```python\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n task.status = \"completed\"\n save_task(task)\n # アンロックされた下流タスクを検索\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy\n and can_start(t.id)]\n msg = f\"Completed {task_id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n```\n\n\"schema\" 完了後、\"endpoints\" と \"docs\" の `can_start` が True を返し、開始可能になる。\n\n### get_task: 完全な詳細を確認\n\n`list_tasks` は 1 行サマリのみ表示。`get_task` は description と依存関係の詳細を含む完全なタスク JSON を返す。セッションをまたいで復旧する際、Agent は完全な説明を読んで作業を継続する必要がある:\n\n```python\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n```\n\n### 状態マシン: 2 つのアクション、3 つの状態\n\n```\npending ──claim──→ in_progress ──complete──→ completed\n```\n\nここで `claim` / `complete` はアクション、`pending` / `in_progress` / `completed` は状態:\n\n- **claim_task**: `pending` → `in_progress`。owner を設定し、作業を開始。\n- **complete_task**: `in_progress` → `completed`。タスクを完了済みにし、下流をアンロック。\n\nCC には `in_progress → pending` の release パスがない。teammate が終了または shutdown した場合、CC は未完了タスクの owner をクリアし、status を `pending` にリセットし、他の agent が再認識できるようにする。教学版はこの復旧パスを省略。\n\n### 組み合わせて実行\n\n```python\n# 依存関係のあるタスクを作成\nschema = create_task(\"setup database schema\")\nendpoints = create_task(\"create API endpoints\", blockedBy=[schema.id])\ntests = create_task(\"write tests\", blockedBy=[endpoints.id])\ndocs = create_task(\"write docs\", blockedBy=[schema.id])\n\n# Agent が最初に実行可能なタスクを認識\nclaim_task(schema.id) # ✓ Claimed(依存なし)\ncomplete_task(schema.id) # ✓ Completed → endpoints, docs をアンロック\n\nclaim_task(endpoints.id) # ✓ Claimed(schema 完了済み)\ncomplete_task(endpoints.id) # ✓ Completed → tests をアンロック\n\nclaim_task(docs.id) # ✓ Claimed(schema 完了済み)\ncomplete_task(docs.id) # ✓ Completed\n\nclaim_task(tests.id) # ✓ Claimed(endpoints 完了済み)\ncomplete_task(tests.id) # ✓ Completed\n```\n\n各 `create_task` が JSON ファイルを書き込み、各 `claim_task` / `complete_task` がファイルを更新。セッションをまたいでも `.tasks/` ディレクトリが残り、Agent はファイルを読んで進捗を復旧。\n\n---\n\n## s11 からの変更\n\n| コンポーネント | 変更前 (s11) | 変更後 (s12) |\n|--------------|------------|------------|\n| タスク管理 | なし | Task dataclass + 5 ツール |\n| 新規型 | — | Task(id, subject, description, status, owner, blockedBy) |\n| ストレージ | 永続化なし | `.tasks/{id}.json` セッション横断 |\n| 依存関係 | なし | `blockedBy` グラフ + `can_start` チェック |\n| ツール | bash, read_file, write_file (3) | + create_task, list_tasks, get_task, claim_task, complete_task (8) |\n| ライフサイクル | — | pending → in_progress → completed(release ロールバックなし) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s12_task_system/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Create tasks: setup database schema, create API endpoints (depends on schema), write tests (depends on endpoints), write docs (depends on schema)`\n2. `List all tasks and their statuses`\n3. `Claim the first unblocked task and complete it`\n4. `List tasks again — which ones are now unblocked?`\n\n観察ポイント:`.tasks/` ディレクトリに JSON ファイルが生成されているか?タスク完了後、ブロックされていたタスクがアンロックされているか?\n\n---\n\n## 次の章\n\nタスクグラフができた。しかし、一部のタスクは長時間かかる — 全テスト実行やサーバーデプロイなど。Agent は LLM をトークン課金で呼び出しており、遅い操作を待つ余裕はない。\n\ns13 Background Tasks → 遅い操作はバックグラウンドへ。Agent は他のタスクの処理を続け、バックグラウンドの完了を通知で受け取る。\n\n
\nCC ソースコード深掘り\n\n> 以下は CC ソースコード `utils/tasks.ts`(862 行)、`tools/TaskCreateTool/TaskCreateTool.ts`(138 行)、`tools/TaskUpdateTool/TaskUpdateTool.ts`(406 行)、`tools/TaskGetTool/TaskGetTool.ts`(128 行)、`tools/TaskListTool/TaskListTool.ts`(116 行)、`hooks/useTaskListWatcher.ts`(221 行)の完全分析に基づく。\n\n### 一、TaskRecord の完全フィールド\n\nチュートリアルでは id、subject、status、owner、blockedBy のみ解説。CC は実際に 9 フィールドを持つ(`utils/tasks.ts:76-89`):\n\n| フィールド | 型 | 用途 |\n|------|------|------|\n| `id` | string | 昇順整数 ID |\n| `subject` | string | 短いタイトル |\n| `description` | string | 自由形式の説明 |\n| `activeForm` | string? | 現在進行形、in_progress 時にスピナーに表示 |\n| `owner` | string? | 割り当てられた agent ID |\n| `status` | pending/in_progress/completed | ライフサイクル |\n| `blocks` | string[] | このタスクがブロックするタスク ID(下流) |\n| `blockedBy` | string[] | このタスクをブロックするタスク ID(上流) |\n| `metadata` | Record? | 任意の拡張キーバリューペア |\n\n保存場所:`~/.claude/tasks/{taskListId}/{id}.json`。タスクごとに 1 ファイル。\n\n### 二、目的は近いが、機構は独立\n\nTask ツールと TodoWrite は共存できるが、同じストレージモデルを共有しない。現在の対話型セッションは構造化 Task ツールを既定で使い、TodoWrite は非対話型や Agent SDK などの互換サーフェスに残る。公開範囲はリリースや設定で変わり得る。Task レコードはファイルロック、依存関係、ownership、リアクティブ監視、ライフサイクルフックを追加し、TodoWrite はリスト全体を置換するセッションチェックリストである。\n\n### 三、並行認識のロック機構\n\n`claimTask()`(`utils/tasks.ts:541-612`)は二重ロックで競合を防止:\n\n**タスクファイルロック**:`proper-lockfile` で `{taskId}.json` をロック(最大 30 リトライ、指数バックオフ 5-100ms)。ロック内:\n1. タスクを再読込(TOCTOU 防止)\n2. 既に他者が認識済み → `already_claimed`\n3. 既に完了済み → `already_resolved`\n4. 上流が未完了 → `blocked`\n5. owner を設定\n\n**リストレベルロック**(agent busy チェック時):`.lock` ファイル、全タスクを原子的に走査し該当 agent が他の open task を持つか確認。\n\n注意:教学版は認識と作業開始を 1 ステップに統合(claim = owner 設定 + in_progress);実際の CC の `claimTask` は主に owner 競合を解決し、owner のみを設定して status は変更しない。status の更新は `TaskUpdate` が担当。\n\n### 四、高水位標による ID 再利用防止\n\n`.highwatermark` ファイルが過去に割り当てられた最大タスク ID を記録。タスクが削除されても ID は再利用されない。\n\n### 五、4 つの Task ツール\n\nCC のタスクシステムは 4 つのツールを持つ(チュートリアルの汎用 Task ツールとは異なる):`TaskCreate`、`TaskGet`、`TaskUpdate`、`TaskList`。すべて `isConcurrencySafe: true` と `shouldDefer: true` が設定(ツールスキーマは初期プロンプトに含まれず、ToolSearch 後にのみ可視)。\n\n教学版の `create_task(blockedBy=...)` は作成時に直接依存を宣言する合理な簡略化。実際の CC の `TaskCreate` は subject/description/activeForm/metadata のみを受け付け、依存関係は `TaskUpdate` の `addBlocks/addBlockedBy` で管理される。\n\n
\n\n\n" + "content": "# s12: Task System — 大きな目標を小さなタスクに分割\n\ns01 → ... → s10 → s11 → `s12` → [s13](/ja/s13) → s14 → ... → s20 → s21\n\n> *\"大きな目標を小さなタスクに分け、順序付け、永続化\"* — ファイル永続化タスクグラフ、マルチ Agent 協調の基盤。\n>\n> **Harness 層**: タスク — 永続化された目標、復旧可能な進捗。\n\n---\n\n## 課題\n\nAgent がプロジェクトを受けた:データベース構築、API 実装、テスト追加。s05 の TodoWrite でリストを作り、まず API を書き始め、途中でデータベーステーブルがないことに気づいて戻る。テスト追加時に API インターフェースのシグネチャがまた変わっている...\n\n屋根を先に建てて基礎を後から打つことはできない。タスクには順序がある。タスク間の前提依存関係は有向非巡回グラフ(DAG)として表現でき、この章では `blockedBy` でそれらを記録する。\n\ns05 の TodoWrite は現在のタスクの実行チェックリストで、セッションメモリに保持される。ここで必要なのは**タスクシステム**:各タスクは JSON ファイル、タスク間に `blockedBy` 依存関係、ディスク上でセッションをまたいで永続化。\n\n---\n\n## ソリューション\n\n![Task System Overview](/course-assets/s12_task_system/task-system-overview.ja.svg)\n\nこの章では、5 つのタスクツール、`.tasks/` ディレクトリへの永続化、`blockedBy` の依存チェックを追加する。\n\nTodoWrite vs Task System:\n\n| | TodoWrite (s05) | Task System (s12) |\n|---|---|---|\n| 位置づけ | 現在のタスクの実行チェックリスト | 復旧可能なタスクシステム |\n| ストレージ | プロセス内 / セッション状態 | `.tasks/{id}.json` |\n| 依存関係 | なし | `blockedBy` / `blocks` グラフ |\n| ライフサイクル | 現在のセッション / 現在のタスク | セッション横断 |\n| 分担 | タスク認識を扱わない | `owner` / claim |\n| ステータス | pending / in_progress / completed | pending / in_progress / completed |\n| 粒度 | Agent 自身の手順 | 認識・追跡・アンロックできるタスク |\n| 更新契約 | リスト全体を置換 | 個別レコードを作成・取得・更新・一覧 |\n\n---\n\n## 仕組み\n\n![Task DAG](/course-assets/s12_task_system/task-dag.ja.svg)\n\n### Task: データ構造\n\n各タスクは JSON ファイル、`.tasks/` ディレクトリに保存:\n\n```python\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent 名(マルチ Agent シナリオ)\n blockedBy: list[str] # 依存タスク ID のリスト\n```\n\nID は `timestamp + random hex` で生成する。\n\n### create_task: タスク作成\n\n```python\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random_hex(4)}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n```\n\n作成時に自動的に `save_task` で `.tasks/{id}.json` に書き込み。`blockedBy` で依存を宣言、例えば \"API を書く\" の `blockedBy` は `[\"task_schema\"]`。\n\n### can_start: 依存チェック\n\nタスクは `blockedBy` が**すべて completed** になってからでないと開始できない:\n\n```python\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False # missing dependency = blocked\n dep = load_task(dep_id)\n if dep.status != \"completed\":\n return False\n return True\n```\n\n`can_start` は `claim_task` の事前チェック:`blockedBy` に一つでも completed でないものがあれば、認識不可。存在しない依存は blocked として扱い、誤った ID 参照時のクラッシュを防ぐ。\n\n### claim_task: タスク認識\n\nAgent がタスクに取り掛かる時、`claim_task` を呼び出し:`owner` を設定、ステータスを `pending` → `in_progress` に変更。`owner` フィールドは誰が作業中かを記録し、マルチ Agent シナリオで重複認識を防止:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task_id} ({task.subject})\"\n```\n\nタスクが既に他者に認識されている(`status != \"pending\"`)、または依存が未完了(`can_start` が False)の場合、認識を拒否。\n\n### complete_task: 完了とアンロック\n\nタスク完了後、`completed` に設定。同時に他の全タスクを走査し、**直前にアンロックされた**下流タスクを特定:\n\n```python\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n task.status = \"completed\"\n save_task(task)\n # アンロックされた下流タスクを検索\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy\n and can_start(t.id)]\n msg = f\"Completed {task_id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n```\n\n\"schema\" 完了後、\"endpoints\" と \"docs\" の `can_start` が True を返し、開始可能になる。\n\n### get_task: 完全な詳細を確認\n\n`list_tasks` は 1 行サマリのみ表示。`get_task` は description と依存関係の詳細を含む完全なタスク JSON を返す。セッションをまたいで復旧する際、Agent は完全な説明を読んで作業を継続する必要がある:\n\n```python\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n```\n\n### 状態マシン: 2 つのアクション、3 つの状態\n\n```\npending ──claim──→ in_progress ──complete──→ completed\n```\n\nここで `claim` / `complete` はアクション、`pending` / `in_progress` / `completed` は状態:\n\n- **claim_task**: `pending` → `in_progress`。owner を設定し、作業を開始。\n- **complete_task**: `in_progress` → `completed`。タスクを完了済みにし、下流をアンロック。\n\n### 組み合わせて実行\n\n```python\n# 依存関係のあるタスクを作成\nschema = create_task(\"setup database schema\")\nendpoints = create_task(\"create API endpoints\", blockedBy=[schema.id])\ntests = create_task(\"write tests\", blockedBy=[endpoints.id])\ndocs = create_task(\"write docs\", blockedBy=[schema.id])\n\n# Agent が最初に実行可能なタスクを認識\nclaim_task(schema.id) # ✓ Claimed(依存なし)\ncomplete_task(schema.id) # ✓ Completed → endpoints, docs をアンロック\n\nclaim_task(endpoints.id) # ✓ Claimed(schema 完了済み)\ncomplete_task(endpoints.id) # ✓ Completed → tests をアンロック\n\nclaim_task(docs.id) # ✓ Claimed(schema 完了済み)\ncomplete_task(docs.id) # ✓ Completed\n\nclaim_task(tests.id) # ✓ Claimed(endpoints 完了済み)\ncomplete_task(tests.id) # ✓ Completed\n```\n\n各 `create_task` が JSON ファイルを書き込み、各 `claim_task` / `complete_task` がファイルを更新。セッションをまたいでも `.tasks/` ディレクトリが残り、Agent はファイルを読んで進捗を復旧。\n\n---\n\n## s11 からの変更\n\n| コンポーネント | 変更前 (s11) | 変更後 (s12) |\n|--------------|------------|------------|\n| タスク管理 | なし | Task dataclass + 5 ツール |\n| 新規型 | — | Task(id, subject, description, status, owner, blockedBy) |\n| ストレージ | 永続化なし | `.tasks/{id}.json` セッション横断 |\n| 依存関係 | なし | `blockedBy` グラフ + `can_start` チェック |\n| ツール | bash, read_file, write_file (3) | + create_task, list_tasks, get_task, claim_task, complete_task (8) |\n| ライフサイクル | — | pending → in_progress → completed(release ロールバックなし) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s12_task_system/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Create tasks: setup database schema, create API endpoints (depends on schema), write tests (depends on endpoints), write docs (depends on schema)`\n2. `List all tasks and their statuses`\n3. `Claim the first unblocked task and complete it`\n4. `List tasks again — which ones are now unblocked?`\n\n観察ポイント:`.tasks/` ディレクトリに JSON ファイルが生成されているか?タスク完了後、ブロックされていたタスクがアンロックされているか?\n\n---\n\n## 次の章\n\nタスクグラフができた。しかし、一部のタスクは長時間かかる — 全テスト実行やサーバーデプロイなど。Agent は LLM をトークン課金で呼び出しており、遅い操作を待つ余裕はない。\n\ns13 Background Tasks → 遅い操作はバックグラウンドへ。Agent は他のタスクの処理を続け、バックグラウンドの完了を通知で受け取る。\n\n\n\n" }, { "version": "s13", "locale": "en", "title": "s13: Background Tasks — Slow Operations Go to the Background", - "content": "# s13: Background Tasks — Slow Operations Go to the Background\n\ns01 → ... → s11 → s12 → `s13` → [s14](/en/s14) → s15 → ... → s20 → s21 → s22\n\n> *\"Slow operations go to the background, agent continues processing\"* — Background threads run commands, inject notifications when done.\n>\n> **Harness Layer**: Background — Async execution, doesn't block the main loop.\n\n---\n\n## The Problem\n\nEver used a washing machine? Throw clothes in, press start, then go do other things — cook, reply to messages, read papers. 30 minutes later the machine beeps: done. You don't stand there waiting for 30 minutes.\n\nThe agent's bash tool is the same. `pip install torch` takes 10 minutes, `npm run build` takes 3 minutes. While these commands run, the agent waits for bash to return, unable to use that time to process other tasks.\n\nReading files is milliseconds, no wait. `git status` returns in under a second, no wait. But `npm install`? Minutes. The agent waits 10 minutes doing nothing, and LLM calls are billed by token — idle time is waste.\n\n---\n\n## The Solution\n\n![Background Tasks Overview](/course-assets/s13_background_tasks/background-tasks-overview.en.svg)\n\nTeaching code carries forward S12's simplified task system and prompt assembly; to stay focused on background tasks, it omits full error recovery, memory, and skill systems. The only change: slow operations go to background threads, the agent continues running the loop, and background results are injected as notifications.\n\nSync vs Background:\n\n| | Sync (s12) | Background (s13) |\n|---|---|---|\n| Slow operations | Agent waits | Background thread executes |\n| Agent idle | Yes | No, continues processing |\n| Result | Immediate return | Notification injected next turn |\n| Decision criteria | — | `run_in_background` param (model explicit request), heuristic fallback |\n\n---\n\n## How It Works\n\n### should_run_background: Explicit Request First, Heuristic Fallback\n\nThe model explicitly requests background execution via the bash tool's `run_in_background` parameter. If the model doesn't specify, the teaching version falls back to keyword heuristics:\n\n```python\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n```\n\nCC's bash tool schema has a `run_in_background: boolean` parameter (`BashTool.tsx:241`). The model decides which commands go to background, no keyword guessing. The teaching version keeps heuristics as fallback, but the primary path is explicit model request.\n\n### start_background_task: Background Execution and Lifecycle\n\nWraps the tool call in a worker function, dispatches to a daemon thread. Each background task gets a unique ID, with state tracked in the `background_tasks` dict:\n\n```python\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": block.input.get(\"command\", \"\"),\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n return bg_id\n```\n\nReturns `bg_id` instead of just `[Running in background...]`. `daemon=True` ensures threads exit when the agent process exits. The teaching version uses in-memory dicts for tracking; real CC has `LocalShellTaskState`, output redirected to files, with full lifecycle including stopping tasks and reading subsequent output.\n\n### collect_background_results: Notification Collection\n\nWhen background tasks complete, results are collected and formatted as `` messages:\n\n```python\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {output[:200]}\\n\"\n f\"\")\n return notifications\n```\n\nNotifications don't reuse the original `tool_use_id`. The original tool call was already answered with a placeholder `tool_result`; background completion is an independent event, injected in `task_notification` format. This respects Messages API tool pairing: one `tool_use` gets exactly one `tool_result`.\n\n### Loop Integration\n\nIn the agent loop, tool execution splits into two paths. Notifications and results merge into a single user message:\n\n```python\nresults = []\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n# Merge notifications and tool results into one user message\nuser_content = []\nbg_notifications = collect_background_results()\nif bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\nuser_content.extend(results)\nmessages.append({\"role\": \"user\", \"content\": user_content})\n```\n\nSlow operations get a placeholder tool_result with `bg_id`, so the LLM knows this command is still running and can do other things first. When background completes, the notification is injected as an independent text block alongside the current turn's tool_results in one user message.\n\nThe teaching version polls background results while the agent loop continues running. Real CC uses a notification queue (`messageQueueManager.ts`) to deliver background completion events to subsequent turns, without waiting for the tool loop.\n\n### Putting It Together\n\n```\nTurn 1:\n LLM → bash \"npm install\" (run_in_background=true)\n → start_background_task → bg_0001\n → tool_result: \"[Background task bg_0001 started]...\"\n → LLM: \"OK, I'll check later. Let me also read the config.\"\n\nTurn 2:\n LLM → read_file \"package.json\" (fast, sync)\n → tool_result: file content\n → collect: bg_0001 done! inject \n → LLM sees: config file + install notification in one message\n```\n\nThe agent didn't wait — while npm install ran in the background, it read the config file.\n\n---\n\n## Changes from s12\n\n| Component | Before (s12) | After (s13) |\n|-----------|-------------|-------------|\n| Execution model | All synchronous | Slow ops to background thread + notification injection |\n| bash schema | `command` | `command` + `run_in_background` |\n| New functions | — | `should_run_background`, `is_slow_operation`, `start_background_task`, `collect_background_results` |\n| New types | — | `background_tasks: dict`, `background_results: dict`, `background_lock: Lock` |\n| Notification format | — | `` (doesn't reuse tool_use_id) |\n| Loop behavior | Tools execute serially | Slow ops async, fast ops sync, notifications collected each turn |\n| Tools | 8 (s12) | 8 (unchanged, execution strategy changed) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s13_background_tasks/code.py\n```\n\nTry these prompts:\n\n1. `Run pip list in the background and find all Python files in this directory`\n2. `Run npm install (use run_in_background) and while waiting, read package.json`\n3. `Create a task to setup the project, then run pip list in the background`\n\nWhat to observe: Are slow operations dispatched to background? Is a `bg_id` returned? Are background notifications injected in `` format?\n\n---\n\n## What's Next\n\nBackground tasks solved \"slow operations don't block.\" But what if you want to do something on a schedule? Like \"run tests every morning at 9am\" or \"check server status every 5 minutes.\"\n\ns14 Cron Scheduler → Give the agent an alarm clock.\n\n
\nDeep Dive into CC Source\n\n> The following is a complete analysis based on CC source code `query.ts` (lines 211, 1054-1060, 1411-1482), `services/toolUseSummary/toolUseSummaryGenerator.ts` (L15 prompt text), `LocalShellTask.tsx` (L24-25 constants, L59-98 watchdog logic), `messageQueueManager.ts` (notification queue), `utils/task/framework.ts` (L267 `enqueueTaskNotification`).\n\n### 1. pendingToolUseSummary: Haiku Background Generation\n\nCC starts a Haiku side-query after each batch of tool executions to generate a tool use summary. Initiated at `query.ts:1411-1482`, prompt text defined at `services/toolUseSummary/toolUseSummaryGenerator.ts:15` (variable `TOOL_USE_SUMMARY_SYSTEM_PROMPT`). The prompt is \"Write a short summary label... think git-commit-subject, not sentence\", past tense, ~30 characters.\n\nHaiku summary (~1s) completes during the main model's streaming output (5-30s). Before the next turn starts, the summary is yielded. SDK consumers use these summaries for mobile progress display.\n\n### 2. Thread Model: No Real Threads\n\nCC runs on Node.js/Bun's single-threaded event loop. \"Background\" just means \"don't await\". `ShellCommand.background(taskId)` redirects stdout/stderr to files, letting the process run independently.\n\n### 3. Seven Background Task Types\n\nCC defines 7 background task types (`Task.ts:7-13`): `local_bash`, `local_agent`, `remote_agent`, `in_process_teammate`, `local_workflow`, `monitor_mcp`, `dream`. Each has its own registration, lifecycle, and notification mechanism.\n\n### 4. Notification Injection: Command Queue\n\nWhen a background task completes, it's enqueued via `enqueueTaskNotification` (`utils/task/framework.ts:267`) or `enqueuePendingNotification` (`messageQueueManager.ts`) into a shared command queue. The notification format is structured XML:\n\n```xml\n\n completed\n Background command \"npm test\" completed (exit code 0)\n\n```\n\nPriority is `next` > `later` (`messageQueueManager.ts`). Background tasks default to `later` (don't block user input). Consumption point at `query.ts:1566-1593`.\n\n### 5. Stall Watchdog\n\nBackground bash tasks have a watchdog (`LocalShellTask.tsx` L24-25 constants, L59-98 logic) that periodically checks if output has stalled. After 45 seconds with no growth, it detects interactive prompts (`(y/n)` etc.), preventing background tasks from getting stuck on unanswered interactive dialogs.\n\n### 6. Concurrency Limits\n\nForeground tool calls: `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` (default 10 concurrent safe tools). Background bash tasks: no hard limit, they're independent subprocesses.\n\n
\n\n\n" + "content": "# s13: Background Tasks — Slow Operations Go to the Background\n\ns01 → ... → s11 → s12 → `s13` → [s14](/en/s14) → s15 → ... → s20 → s21\n\n> *\"Slow operations go to the background, agent continues processing\"* — Background threads run commands, inject notifications when done.\n>\n> **Harness Layer**: Background — Async execution, doesn't block the main loop.\n\n---\n\n## The Problem\n\nEver used a washing machine? Throw clothes in, press start, then go do other things — cook, reply to messages, read papers. 30 minutes later the machine beeps: done. You don't stand there waiting for 30 minutes.\n\nThe agent's bash tool is the same. `pip install torch` takes 10 minutes, `npm run build` takes 3 minutes. While these commands run, the agent waits for bash to return, unable to use that time to process other tasks.\n\nReading files is milliseconds, no wait. `git status` returns in under a second, no wait. But `npm install`? Minutes. The agent waits 10 minutes doing nothing, and LLM calls are billed by token — idle time is waste.\n\n---\n\n## The Solution\n\n![Background Tasks Overview](/course-assets/s13_background_tasks/background-tasks-overview.en.svg)\n\nThis chapter sends slow operations to background threads so the agent can keep running the loop. When a task finishes, its result is injected as a notification.\n\nSync vs Background:\n\n| | Sync (s12) | Background (s13) |\n|---|---|---|\n| Slow operations | Agent waits | Background thread executes |\n| Agent idle | Yes | No, continues processing |\n| Result | Immediate return | Notification injected next turn |\n| Decision criteria | — | `run_in_background` param (model explicit request), heuristic fallback |\n\n---\n\n## How It Works\n\n### should_run_background: Explicit Request First, Heuristic Fallback\n\nThe model explicitly requests background execution via the bash tool's `run_in_background` parameter. If the model does not specify it, keyword heuristics decide:\n\n```python\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n```\n\n### start_background_task: Background Execution and Lifecycle\n\nWraps the tool call in a worker function, dispatches to a daemon thread. Each background task gets a unique ID, with state tracked in the `background_tasks` dict:\n\n```python\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": block.input.get(\"command\", \"\"),\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n return bg_id\n```\n\n`start_background_task()` returns `bg_id`. `daemon=True` ensures the thread exits with the agent process.\n\n### collect_background_results: Notification Collection\n\nWhen background tasks complete, results are collected and formatted as `` messages:\n\n```python\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {output[:200]}\\n\"\n f\"\")\n return notifications\n```\n\nNotifications don't reuse the original `tool_use_id`. The original tool call was already answered with a placeholder `tool_result`; background completion is an independent event, injected in `task_notification` format. This respects Messages API tool pairing: one `tool_use` gets exactly one `tool_result`.\n\n### Loop Integration\n\nIn the agent loop, tool execution splits into two paths. Notifications and results merge into a single user message:\n\n```python\nresults = []\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n# Merge notifications and tool results into one user message\nuser_content = []\nbg_notifications = collect_background_results()\nif bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\nuser_content.extend(results)\nmessages.append({\"role\": \"user\", \"content\": user_content})\n```\n\nSlow operations get a placeholder tool_result with `bg_id`, so the LLM knows this command is still running and can do other things first. When background completes, the notification is injected as an independent text block alongside the current turn's tool_results in one user message.\n\n### Putting It Together\n\n```\nTurn 1:\n LLM → bash \"npm install\" (run_in_background=true)\n → start_background_task → bg_0001\n → tool_result: \"[Background task bg_0001 started]...\"\n → LLM: \"OK, I'll check later. Let me also read the config.\"\n\nTurn 2:\n LLM → read_file \"package.json\" (fast, sync)\n → tool_result: file content\n → collect: bg_0001 done! inject \n → LLM sees: config file + install notification in one message\n```\n\nThe agent didn't wait — while npm install ran in the background, it read the config file.\n\n---\n\n## Changes from s12\n\n| Component | Before (s12) | After (s13) |\n|-----------|-------------|-------------|\n| Execution model | All synchronous | Slow ops to background thread + notification injection |\n| bash schema | `command` | `command` + `run_in_background` |\n| New functions | — | `should_run_background`, `is_slow_operation`, `start_background_task`, `collect_background_results` |\n| New types | — | `background_tasks: dict`, `background_results: dict`, `background_lock: Lock` |\n| Notification format | — | `` (doesn't reuse tool_use_id) |\n| Loop behavior | Tools execute serially | Slow ops async, fast ops sync, notifications collected each turn |\n| Tools | 8 (s12) | 8 (unchanged, execution strategy changed) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s13_background_tasks/code.py\n```\n\nTry these prompts:\n\n1. `Run pip list in the background and find all Python files in this directory`\n2. `Run npm install (use run_in_background) and while waiting, read package.json`\n3. `Create a task to setup the project, then run pip list in the background`\n\nWhat to observe: Are slow operations dispatched to background? Is a `bg_id` returned? Are background notifications injected in `` format?\n\n---\n\n## What's Next\n\nBackground tasks solved \"slow operations don't block.\" But what if you want to do something on a schedule? Like \"run tests every morning at 9am\" or \"check server status every 5 minutes.\"\n\ns14 Cron Scheduler → Give the agent an alarm clock.\n\n\n\n" }, { "version": "s13", "locale": "zh", "title": "s13: Background Tasks — 慢操作放后台", - "content": "# s13: Background Tasks — 慢操作放后台\n\ns01 → ... → s11 → s12 → `s13` → [s14](/zh/s14) → s15 → ... → s20 → s21 → s22\n\n> *\"慢操作丢后台, agent 继续处理\"* — 后台线程跑命令, 完成后注入通知。\n>\n> **Harness 层**: 后台 — 异步执行, 不阻塞主循环。\n\n---\n\n## 问题\n\n你用过洗衣机吗?把衣服扔进去,按下启动,然后去干别的——做饭、回消息、看论文。30 分钟后洗衣机\"滴滴滴\"提醒你:好了。你不会站在洗衣机前面干等 30 分钟。\n\nAgent 的 bash 工具也一样。`pip install torch` 要 10 分钟,`npm run build` 要 3 分钟。这些命令一跑,Agent 就在等 bash 工具返回,没法利用这段时间处理别的任务。\n\n读文件是毫秒级,不等。`git status` 一秒内返回,不等。但 `npm install`?分钟级。Agent 等 10 分钟什么都不做,而 LLM 按 token 计费,空转就是浪费。\n\n---\n\n## 解决方案\n\n![Background Tasks Overview](/course-assets/s13_background_tasks/background-tasks-overview.svg)\n\n教学代码沿用 S12 的简化任务系统和 prompt 组装;为了聚焦后台任务,省略完整错误恢复、记忆和技能系统。唯一的变动:慢操作扔到后台线程,Agent 继续跑循环,后台完成后把通知注入到对话里。\n\n同步 vs 后台:\n\n| | 同步 (s12) | 后台 (s13) |\n|---|---|---|\n| 慢操作 | Agent 干等 | 后台线程执行 |\n| Agent 空闲 | 是 | 否,继续处理 |\n| 结果 | 立即返回 | 下轮注入通知 |\n| 判断标准 | — | `run_in_background` 参数(模型显式请求),启发式兜底 |\n\n---\n\n## 工作原理\n\n### should_run_background: 显式请求优先,启发式兜底\n\n模型通过 bash 工具的 `run_in_background` 参数显式请求后台执行。如果模型没指定,教学版用关键词启发式兜底:\n\n```python\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n```\n\nCC 的 bash 工具 schema 里有 `run_in_background: boolean` 参数(`BashTool.tsx:241`)。模型自己决定哪些命令丢后台,不靠关键词猜。教学版保留启发式作为兜底,但主路径是模型显式请求。\n\n### start_background_task: 后台执行与生命周期\n\n把工具调用包装成 worker 函数,扔到 daemon 线程里执行。每个后台任务有唯一 ID,状态存在 `background_tasks` 字典里:\n\n```python\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": block.input.get(\"command\", \"\"),\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n return bg_id\n```\n\n返回 `bg_id` 而不是只返回 `[Running in background...]`。`daemon=True` 确保 Agent 进程退出时线程跟着退出。教学版用内存字典追踪状态;真实 CC 有 `LocalShellTaskState`,输出重定向到文件,支持停止任务、读取后续输出等完整生命周期。\n\n### collect_background_results: 通知收集\n\n后台任务完成后,收集结果并格式化为 `` 通知:\n\n```python\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {output[:200]}\\n\"\n f\"\")\n return notifications\n```\n\n通知不复用原始 `tool_use_id`。原始 tool call 已经用占位 `tool_result` 回复了,后台完成是独立事件,用 `task_notification` 格式注入。这符合 Messages API 的工具配对语义:一个 `tool_use` 只对应一个 `tool_result`。\n\n### 循环中的集成\n\nagent_loop 里,工具执行分两条路,通知和结果合并为一条 user 消息:\n\n```python\nresults = []\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n# 通知和工具结果合入同一条 user 消息\nuser_content = []\nbg_notifications = collect_background_results()\nif bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\nuser_content.extend(results)\nmessages.append({\"role\": \"user\", \"content\": user_content})\n```\n\n慢操作先回一个带 `bg_id` 的占位 tool_result,LLM 知道这个命令还在跑,可以先做别的事。后台完成后,通知作为独立 text block 和当前轮的 tool_result 一起组成 user 消息。\n\n教学版在 agent loop 继续运行时轮询后台结果。真实 CC 通过通知队列(`messageQueueManager.ts`)把后台完成事件送入后续 turn,不需要等工具循环。\n\n### 合起来跑\n\n```\nTurn 1:\n LLM → bash \"npm install\" (run_in_background=true)\n → start_background_task → bg_0001\n → tool_result: \"[Background task bg_0001 started]...\"\n → LLM: \"OK, I'll check later. Let me also read the config.\"\n\nTurn 2:\n LLM → read_file \"package.json\" (fast, sync)\n → tool_result: file content\n → collect: bg_0001 done! inject \n → LLM sees: config file + install notification in one message\n```\n\nAgent 没干等,npm install 跑后台的时候,它去读了配置文件。\n\n---\n\n## 相对 s12 的变更\n\n| 组件 | 之前 (s12) | 之后 (s13) |\n|------|-----------|-----------|\n| 执行模型 | 全部同步 | 慢操作后台线程 + 通知注入 |\n| bash schema | `command` | `command` + `run_in_background` |\n| 新函数 | — | `should_run_background`, `is_slow_operation`, `start_background_task`, `collect_background_results` |\n| 新类型 | — | `background_tasks: dict`, `background_results: dict`, `background_lock: Lock` |\n| 通知格式 | — | ``(不复用 tool_use_id) |\n| 循环行为 | 工具串行执行 | 慢操作异步,快操作同步,通知每轮收集 |\n| 工具 | 8 (s12) | 8(不变,执行策略变了) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s13_background_tasks/code.py\n```\n\n试试这些 prompt:\n\n1. `Run pip list in the background and find all Python files in this directory`\n2. `Run npm install (use run_in_background) and while waiting, read package.json`\n3. `Create a task to setup the project, then run pip list in the background`\n\n观察重点:慢操作有没有被送到后台?`bg_id` 是否返回?后台通知有没有以 `` 格式注入?\n\n---\n\n## 接下来\n\n后台任务解决了\"慢操作不阻塞\"。但如果想定时做某件事呢?比如\"每天早上 9 点跑测试\"、\"每 5 分钟检查一次服务器状态\"。\n\ns14 Cron Scheduler → 给 Agent 装一个闹钟。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `query.ts`(211, 1054-1060, 1411-1482 行)、`services/toolUseSummary/toolUseSummaryGenerator.ts`(L15 prompt 文本)、`LocalShellTask.tsx`(L24-25 常量, L59-98 看门狗逻辑)、`messageQueueManager.ts`(通知队列)、`utils/task/framework.ts`(L267 `enqueueTaskNotification`)的完整分析。\n\n### 一、pendingToolUseSummary:Haiku 后台生成\n\nCC 在每批工具执行完后,启动一个 Haiku side-query 生成工具使用摘要。发起代码在 `query.ts:1411-1482`,prompt 文本定义在 `services/toolUseSummary/toolUseSummaryGenerator.ts:15`(变量名 `TOOL_USE_SUMMARY_SYSTEM_PROMPT`)。提示是 \"Write a short summary label... think git-commit-subject, not sentence\",过去时态,约 30 字符。\n\nHaiku 摘要(~1s)在主模型流式生成(5-30s)期间完成。下一轮开始前,把摘要 yield 出去。SDK 消费这些摘要做移动端进度展示。\n\n### 二、线程模型:没有真正的线程\n\nCC 运行在 Node.js/Bun 单线程事件循环中。\"后台\"只是 \"不 await\"。`ShellCommand.background(taskId)` 把 stdout/stderr 重定向到文件,让进程独立运行。\n\n### 三、七种后台任务类型\n\nCC 定义了 7 种后台任务(`Task.ts:7-13`):`local_bash`、`local_agent`、`remote_agent`、`in_process_teammate`、`local_workflow`、`monitor_mcp`、`dream`。每种有自己的注册、生命周期和通知机制。\n\n### 四、通知注入:命令队列\n\n后台任务完成后通过 `enqueueTaskNotification`(`utils/task/framework.ts:267`)或 `enqueuePendingNotification`(`messageQueueManager.ts`)入队到共享命令队列。通知格式是结构化的 XML:\n\n```xml\n\n completed\n Background command \"npm test\" completed (exit code 0)\n\n```\n\n优先级分 `next` > `later`(`messageQueueManager.ts`)。后台任务默认 `later`(不阻塞用户输入)。消费点在 `query.ts:1566-1593`。\n\n### 五、停滞看门狗\n\n后台 bash 任务有一个看门狗(`LocalShellTask.tsx` L24-25 常量, L59-98 逻辑),定期检查输出是否停滞,45 秒无增长后检测交互式提示(`(y/n)` 等),防止后台任务卡在无人响应的交互式对话框。\n\n### 六、并发限制\n\n前台工具调用:`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`(默认 10 个并发安全工具)。后台 bash 任务:没有硬性限制,它们是独立的子进程。\n\n
\n\n\n" + "content": "# s13: Background Tasks — 慢操作放后台\n\ns01 → ... → s11 → s12 → `s13` → [s14](/zh/s14) → s15 → ... → s20 → s21\n\n> *\"慢操作丢后台, agent 继续处理\"* — 后台线程跑命令, 完成后注入通知。\n>\n> **Harness 层**: 后台 — 异步执行, 不阻塞主循环。\n\n---\n\n## 问题\n\n你用过洗衣机吗?把衣服扔进去,按下启动,然后去干别的——做饭、回消息、看论文。30 分钟后洗衣机\"滴滴滴\"提醒你:好了。你不会站在洗衣机前面干等 30 分钟。\n\nAgent 的 bash 工具也一样。`pip install torch` 要 10 分钟,`npm run build` 要 3 分钟。这些命令一跑,Agent 就在等 bash 工具返回,没法利用这段时间处理别的任务。\n\n读文件是毫秒级,不等。`git status` 一秒内返回,不等。但 `npm install`?分钟级。Agent 等 10 分钟什么都不做,而 LLM 按 token 计费,空转就是浪费。\n\n---\n\n## 解决方案\n\n![Background Tasks Overview](/course-assets/s13_background_tasks/background-tasks-overview.svg)\n\n本章把慢操作放入后台线程,Agent 继续运行循环;任务完成后,结果以通知形式注入对话。\n\n同步 vs 后台:\n\n| | 同步 (s12) | 后台 (s13) |\n|---|---|---|\n| 慢操作 | Agent 干等 | 后台线程执行 |\n| Agent 空闲 | 是 | 否,继续处理 |\n| 结果 | 立即返回 | 下轮注入通知 |\n| 判断标准 | — | `run_in_background` 参数(模型显式请求),启发式兜底 |\n\n---\n\n## 工作原理\n\n### should_run_background: 显式请求优先,启发式兜底\n\n模型通过 bash 工具的 `run_in_background` 参数显式请求后台执行。如果模型没有指定,则使用关键词启发式判断:\n\n```python\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n```\n\n### start_background_task: 后台执行与生命周期\n\n把工具调用包装成 worker 函数,扔到 daemon 线程里执行。每个后台任务有唯一 ID,状态存在 `background_tasks` 字典里:\n\n```python\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": block.input.get(\"command\", \"\"),\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n return bg_id\n```\n\n`start_background_task()` 返回 `bg_id`。`daemon=True` 确保 Agent 进程退出时线程一起退出。\n\n### collect_background_results: 通知收集\n\n后台任务完成后,收集结果并格式化为 `` 通知:\n\n```python\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {output[:200]}\\n\"\n f\"\")\n return notifications\n```\n\n通知不复用原始 `tool_use_id`。原始 tool call 已经用占位 `tool_result` 回复了,后台完成是独立事件,用 `task_notification` 格式注入。这符合 Messages API 的工具配对语义:一个 `tool_use` 只对应一个 `tool_result`。\n\n### 循环中的集成\n\nagent_loop 里,工具执行分两条路,通知和结果合并为一条 user 消息:\n\n```python\nresults = []\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n# 通知和工具结果合入同一条 user 消息\nuser_content = []\nbg_notifications = collect_background_results()\nif bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\nuser_content.extend(results)\nmessages.append({\"role\": \"user\", \"content\": user_content})\n```\n\n慢操作先回一个带 `bg_id` 的占位 tool_result,LLM 知道这个命令还在跑,可以先做别的事。后台完成后,通知作为独立 text block 和当前轮的 tool_result 一起组成 user 消息。\n\n### 合起来跑\n\n```\nTurn 1:\n LLM → bash \"npm install\" (run_in_background=true)\n → start_background_task → bg_0001\n → tool_result: \"[Background task bg_0001 started]...\"\n → LLM: \"OK, I'll check later. Let me also read the config.\"\n\nTurn 2:\n LLM → read_file \"package.json\" (fast, sync)\n → tool_result: file content\n → collect: bg_0001 done! inject \n → LLM sees: config file + install notification in one message\n```\n\nAgent 没干等,npm install 跑后台的时候,它去读了配置文件。\n\n---\n\n## 相对 s12 的变更\n\n| 组件 | 之前 (s12) | 之后 (s13) |\n|------|-----------|-----------|\n| 执行模型 | 全部同步 | 慢操作后台线程 + 通知注入 |\n| bash schema | `command` | `command` + `run_in_background` |\n| 新函数 | — | `should_run_background`, `is_slow_operation`, `start_background_task`, `collect_background_results` |\n| 新类型 | — | `background_tasks: dict`, `background_results: dict`, `background_lock: Lock` |\n| 通知格式 | — | ``(不复用 tool_use_id) |\n| 循环行为 | 工具串行执行 | 慢操作异步,快操作同步,通知每轮收集 |\n| 工具 | 8 (s12) | 8(不变,执行策略变了) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s13_background_tasks/code.py\n```\n\n试试这些 prompt:\n\n1. `Run pip list in the background and find all Python files in this directory`\n2. `Run npm install (use run_in_background) and while waiting, read package.json`\n3. `Create a task to setup the project, then run pip list in the background`\n\n观察重点:慢操作有没有被送到后台?`bg_id` 是否返回?后台通知有没有以 `` 格式注入?\n\n---\n\n## 接下来\n\n后台任务解决了\"慢操作不阻塞\"。但如果想定时做某件事呢?比如\"每天早上 9 点跑测试\"、\"每 5 分钟检查一次服务器状态\"。\n\ns14 Cron Scheduler → 给 Agent 装一个闹钟。\n\n\n\n" }, { "version": "s13", "locale": "ja", "title": "s13: Background Tasks — 遅い操作はバックグラウンドへ", - "content": "# s13: Background Tasks — 遅い操作はバックグラウンドへ\n\ns01 → ... → s11 → s12 → `s13` → [s14](/ja/s14) → s15 → ... → s20 → s21 → s22\n\n> *\"遅い操作はバックグラウンドへ、agent は処理を継続\"* — バックグラウンドスレッドでコマンドを実行、完了時に通知を注入。\n>\n> **Harness 層**: バックグラウンド — 非同期実行、メインループをブロックしない。\n\n---\n\n## 課題\n\n洗濯機を使ったことがあるか?衣類を入れ、スタートを押し、他のことをする——料理、メッセージ返信、論文読み。30 分後に洗濯機が「ピッピッ」と知らせる:完了。30 分間立って待つ人はいない。\n\nAgent の bash ツールも同じ。`pip install torch` は 10 分、`npm run build` は 3 分かかる。これらのコマンドが実行中、Agent は bash の戻りを待ち、その時間を他のタスクの処理に使えない。\n\nファイル読み込みはミリ秒、待たない。`git status` は 1 秒以内に戻る、待たない。しかし `npm install` は?分単位。Agent は 10 分間何もせず待ち、LLM 呼び出しはトークン課金、アイドル時間は無駄。\n\n---\n\n## ソリューション\n\n![Background Tasks Overview](/course-assets/s13_background_tasks/background-tasks-overview.ja.svg)\n\n教学版は S12 の簡易タスクシステムとプロンプト組み立てを踏襲。バックグラウンドタスクに集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。唯一の変更:遅い操作をバックグラウンドスレッドに投げ、Agent はループを継続、バックグラウンド完了時に通知を注入。\n\n同期 vs バックグラウンド:\n\n| | 同期 (s12) | バックグラウンド (s13) |\n|---|---|---|\n| 遅い操作 | Agent が待機 | バックグラウンドスレッドで実行 |\n| Agent アイドル | はい | いいえ、処理を継続 |\n| 結果 | 即時返却 | 次ターンで通知を注入 |\n| 判断基準 | — | `run_in_background` パラメータ(モデル明示的リクエスト)、ヒューリスティックフォールバック |\n\n---\n\n## 仕組み\n\n### should_run_background: 明示的リクエスト優先、ヒューリスティックフォールバック\n\nモデルは bash ツールの `run_in_background` パラメータで明示的にバックグラウンド実行をリクエストする。モデルが指定しない場合、教学版はキーワードヒューリスティックにフォールバック:\n\n```python\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n```\n\nCC の bash ツールスキーマには `run_in_background: boolean` パラメータがある(`BashTool.tsx:241`)。モデルがどのコマンドをバックグラウンドにするかを決定、キーワード推測ではない。教学版はヒューリスティックをフォールバックとして残すが、主パスはモデルの明示的リクエスト。\n\n### start_background_task: バックグラウンド実行とライフサイクル\n\nツール呼び出しをワーカー関数にラップし、daemon スレッドにディスパッチ。各バックグラウンドタスクは一意 ID を持ち、`background_tasks` 辞書で状態を追跡:\n\n```python\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": block.input.get(\"command\", \"\"),\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n return bg_id\n```\n\n`[Running in background...]` ではなく `bg_id` を返す。`daemon=True` で Agent プロセス終了時にスレッドも終了。教学版はメモリ内辞書で追跡。実際の CC は `LocalShellTaskState` を持ち、出力をファイルにリダイレクト、タスク停止や継続出力読み取りを含む完全なライフサイクルを備える。\n\n### collect_background_results: 通知収集\n\nバックグラウンドタスク完了時、結果を収集して `` メッセージとしてフォーマット:\n\n```python\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {output[:200]}\\n\"\n f\"\")\n return notifications\n```\n\n通知は元の `tool_use_id` を再利用しない。元のツール呼び出しはプレースホルダー `tool_result` で応答済み。バックグラウンド完了は独立したイベントで、`task_notification` 形式で注入する。これは Messages API のツールペアリングに従う:1 つの `tool_use` に対して正確に 1 つの `tool_result`。\n\n### ループ統合\n\nagent_loop でツール実行は 2 つのパスに分かれる。通知と結果は 1 つの user メッセージに統合:\n\n```python\nresults = []\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n# 通知とツール結果を 1 つの user メッセージに統合\nuser_content = []\nbg_notifications = collect_background_results()\nif bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\nuser_content.extend(results)\nmessages.append({\"role\": \"user\", \"content\": user_content})\n```\n\n遅い操作は `bg_id` 付きプレースホルダー tool_result を返し、LLM はコマンドがまだ実行中だと知り、先に他のことをできる。バックグラウンド完了時、通知は独立した text block として現在のターンの tool_result と一緒に 1 つの user メッセージを構成する。\n\n教学版は agent loop が継続実行中にバックグラウンド結果をポーリングする。実際の CC は通知キュー(`messageQueueManager.ts`)でバックグラウンド完了イベントを後続ターンに配信、ツールループを待つ必要はない。\n\n### 組み合わせて実行\n\n```\nTurn 1:\n LLM → bash \"npm install\" (run_in_background=true)\n → start_background_task → bg_0001\n → tool_result: \"[Background task bg_0001 started]...\"\n → LLM: \"OK, I'll check later. Let me also read the config.\"\n\nTurn 2:\n LLM → read_file \"package.json\" (fast, sync)\n → tool_result: file content\n → collect: bg_0001 done! inject \n → LLM sees: config file + install notification in one message\n```\n\nAgent は待たなかった。npm install がバックグラウンドで実行中に、設定ファイルを読んだ。\n\n---\n\n## s12 からの変更\n\n| コンポーネント | 変更前 (s12) | 変更後 (s13) |\n|--------------|------------|------------|\n| 実行モデル | すべて同期 | 遅い操作はバックグラウンドスレッド + 通知注入 |\n| bash スキーマ | `command` | `command` + `run_in_background` |\n| 新規関数 | — | `should_run_background`, `is_slow_operation`, `start_background_task`, `collect_background_results` |\n| 新規型 | — | `background_tasks: dict`, `background_results: dict`, `background_lock: Lock` |\n| 通知形式 | — | ``(tool_use_id を再利用しない) |\n| ループ動作 | ツール直列実行 | 遅い操作は非同期、速い操作は同期、通知は毎ターン収集 |\n| ツール | 8 (s12) | 8(変更なし、実行戦略が変更) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s13_background_tasks/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Run pip list in the background and find all Python files in this directory`\n2. `Run npm install (use run_in_background) and while waiting, read package.json`\n3. `Create a task to setup the project, then run pip list in the background`\n\n観察ポイント:遅い操作はバックグラウンドにディスパッチされているか?`bg_id` は返されているか?バックグラウンド通知は `` 形式で注入されているか?\n\n---\n\n## 次の章\n\nバックグラウンドタスクは「遅い操作がブロックしない」を解決した。しかし、定期的に何かをしたい場合は?例えば「毎朝 9 時にテストを実行」「5 分ごとにサーバーステータスを確認」。\n\ns14 Cron Scheduler → Agent にアラームクロックを付ける。\n\n
\nCC ソースコード深掘り\n\n> 以下は CC ソースコード `query.ts`(211, 1054-1060, 1411-1482 行)、`services/toolUseSummary/toolUseSummaryGenerator.ts`(L15 プロンプトテキスト)、`LocalShellTask.tsx`(L24-25 定数, L59-98 ウォッチドッグロジック)、`messageQueueManager.ts`(通知キュー)、`utils/task/framework.ts`(L267 `enqueueTaskNotification`)の完全分析に基づく。\n\n### 一、pendingToolUseSummary:Haiku バックグラウンド生成\n\nCC は各ツール実行バッチの後、Haiku サイドクエリを開始してツール使用サマリを生成。開始コードは `query.ts:1411-1482`、プロンプトテキストは `services/toolUseSummary/toolUseSummaryGenerator.ts:15`(変数 `TOOL_USE_SUMMARY_SYSTEM_PROMPT`)。プロンプトは \"Write a short summary label... think git-commit-subject, not sentence\"、過去形、約 30 文字。\n\nHaiku サマリ(~1s)はメインモデルのストリーミング出力(5-30s)中に完了。次のターン開始前にサマリを yield。SDK コンシューマーはこれらのサマリをモバイル進捗表示に使用。\n\n### 二、スレッドモデル:本当のスレッドはない\n\nCC は Node.js/Bun のシングルスレッドイベントループで動作。「バックグラウンド」は単に「await しない」こと。`ShellCommand.background(taskId)` は stdout/stderr をファイルにリダイレクトし、プロセスを独立実行。\n\n### 三、7 種のバックグラウンドタスク型\n\nCC は 7 種のバックグラウンドタスク型を定義(`Task.ts:7-13`):`local_bash`、`local_agent`、`remote_agent`、`in_process_teammate`、`local_workflow`、`monitor_mcp`、`dream`。それぞれ独自の登録、ライフサイクル、通知メカニズムを持つ。\n\n### 四、通知注入:コマンドキュー\n\nバックグラウンドタスク完了時、`enqueueTaskNotification`(`utils/task/framework.ts:267`)または `enqueuePendingNotification`(`messageQueueManager.ts`)で共有コマンドキューにエンキュー。通知形式は構造化 XML:\n\n```xml\n\n completed\n Background command \"npm test\" completed (exit code 0)\n\n```\n\n優先度は `next` > `later`(`messageQueueManager.ts`)。バックグラウンドタスクはデフォルト `later`(ユーザー入力をブロックしない)。消費点は `query.ts:1566-1593`。\n\n### 五、停滞ウォッチドッグ\n\nバックグラウンド bash タスクにはウォッチドッグがある(`LocalShellTask.tsx` L24-25 定数, L59-98 ロジック)。出力の停滞を定期チェックし、45 秒間増加がない場合にインタラクティブプロンプト(`(y/n)` 等)を検出、バックグラウンドタスクが無応答のインタラクティブダイアログでスタックするのを防ぐ。\n\n### 六、同時実行制限\n\nフォアグラウンドツール呼び出し:`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`(デフォルト 10 同時実行安全ツール)。バックグラウンド bash タスク:ハードリミットなし、独立したサブプロセス。\n\n
\n\n\n" + "content": "# s13: Background Tasks — 遅い操作はバックグラウンドへ\n\ns01 → ... → s11 → s12 → `s13` → [s14](/ja/s14) → s15 → ... → s20 → s21\n\n> *\"遅い操作はバックグラウンドへ、agent は処理を継続\"* — バックグラウンドスレッドでコマンドを実行、完了時に通知を注入。\n>\n> **Harness 層**: バックグラウンド — 非同期実行、メインループをブロックしない。\n\n---\n\n## 課題\n\n洗濯機を使ったことがあるか?衣類を入れ、スタートを押し、他のことをする——料理、メッセージ返信、論文読み。30 分後に洗濯機が「ピッピッ」と知らせる:完了。30 分間立って待つ人はいない。\n\nAgent の bash ツールも同じ。`pip install torch` は 10 分、`npm run build` は 3 分かかる。これらのコマンドが実行中、Agent は bash の戻りを待ち、その時間を他のタスクの処理に使えない。\n\nファイル読み込みはミリ秒、待たない。`git status` は 1 秒以内に戻る、待たない。しかし `npm install` は?分単位。Agent は 10 分間何もせず待ち、LLM 呼び出しはトークン課金、アイドル時間は無駄。\n\n---\n\n## ソリューション\n\n![Background Tasks Overview](/course-assets/s13_background_tasks/background-tasks-overview.ja.svg)\n\nこの章では、時間のかかる操作をバックグラウンドスレッドに送り、Agent はループを続行する。タスクが完了すると、結果が通知として会話に注入される。\n\n同期 vs バックグラウンド:\n\n| | 同期 (s12) | バックグラウンド (s13) |\n|---|---|---|\n| 遅い操作 | Agent が待機 | バックグラウンドスレッドで実行 |\n| Agent アイドル | はい | いいえ、処理を継続 |\n| 結果 | 即時返却 | 次ターンで通知を注入 |\n| 判断基準 | — | `run_in_background` パラメータ(モデル明示的リクエスト)、ヒューリスティックフォールバック |\n\n---\n\n## 仕組み\n\n### should_run_background: 明示的リクエスト優先、ヒューリスティックフォールバック\n\nモデルは bash ツールの `run_in_background` パラメータで明示的にバックグラウンド実行をリクエストする。指定がない場合は、キーワードヒューリスティックで判断する:\n\n```python\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n```\n\n### start_background_task: バックグラウンド実行とライフサイクル\n\nツール呼び出しをワーカー関数にラップし、daemon スレッドにディスパッチ。各バックグラウンドタスクは一意 ID を持ち、`background_tasks` 辞書で状態を追跡:\n\n```python\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": block.input.get(\"command\", \"\"),\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n return bg_id\n```\n\n`start_background_task()` は `bg_id` を返す。`daemon=True` により、Agent プロセスの終了時にスレッドも終了する。\n\n### collect_background_results: 通知収集\n\nバックグラウンドタスク完了時、結果を収集して `` メッセージとしてフォーマット:\n\n```python\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {output[:200]}\\n\"\n f\"\")\n return notifications\n```\n\n通知は元の `tool_use_id` を再利用しない。元のツール呼び出しはプレースホルダー `tool_result` で応答済み。バックグラウンド完了は独立したイベントで、`task_notification` 形式で注入する。これは Messages API のツールペアリングに従う:1 つの `tool_use` に対して正確に 1 つの `tool_result`。\n\n### ループ統合\n\nagent_loop でツール実行は 2 つのパスに分かれる。通知と結果は 1 つの user メッセージに統合:\n\n```python\nresults = []\nfor block in response.content:\n if block.type != \"tool_use\":\n continue\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n# 通知とツール結果を 1 つの user メッセージに統合\nuser_content = []\nbg_notifications = collect_background_results()\nif bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\nuser_content.extend(results)\nmessages.append({\"role\": \"user\", \"content\": user_content})\n```\n\n遅い操作は `bg_id` 付きプレースホルダー tool_result を返し、LLM はコマンドがまだ実行中だと知り、先に他のことをできる。バックグラウンド完了時、通知は独立した text block として現在のターンの tool_result と一緒に 1 つの user メッセージを構成する。\n\n### 組み合わせて実行\n\n```\nTurn 1:\n LLM → bash \"npm install\" (run_in_background=true)\n → start_background_task → bg_0001\n → tool_result: \"[Background task bg_0001 started]...\"\n → LLM: \"OK, I'll check later. Let me also read the config.\"\n\nTurn 2:\n LLM → read_file \"package.json\" (fast, sync)\n → tool_result: file content\n → collect: bg_0001 done! inject \n → LLM sees: config file + install notification in one message\n```\n\nAgent は待たなかった。npm install がバックグラウンドで実行中に、設定ファイルを読んだ。\n\n---\n\n## s12 からの変更\n\n| コンポーネント | 変更前 (s12) | 変更後 (s13) |\n|--------------|------------|------------|\n| 実行モデル | すべて同期 | 遅い操作はバックグラウンドスレッド + 通知注入 |\n| bash スキーマ | `command` | `command` + `run_in_background` |\n| 新規関数 | — | `should_run_background`, `is_slow_operation`, `start_background_task`, `collect_background_results` |\n| 新規型 | — | `background_tasks: dict`, `background_results: dict`, `background_lock: Lock` |\n| 通知形式 | — | ``(tool_use_id を再利用しない) |\n| ループ動作 | ツール直列実行 | 遅い操作は非同期、速い操作は同期、通知は毎ターン収集 |\n| ツール | 8 (s12) | 8(変更なし、実行戦略が変更) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s13_background_tasks/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Run pip list in the background and find all Python files in this directory`\n2. `Run npm install (use run_in_background) and while waiting, read package.json`\n3. `Create a task to setup the project, then run pip list in the background`\n\n観察ポイント:遅い操作はバックグラウンドにディスパッチされているか?`bg_id` は返されているか?バックグラウンド通知は `` 形式で注入されているか?\n\n---\n\n## 次の章\n\nバックグラウンドタスクは「遅い操作がブロックしない」を解決した。しかし、定期的に何かをしたい場合は?例えば「毎朝 9 時にテストを実行」「5 分ごとにサーバーステータスを確認」。\n\ns14 Cron Scheduler → Agent にアラームクロックを付ける。\n\n\n\n" }, { "version": "s14", "locale": "en", "title": "s14: Cron Scheduler — Producing Work on a Schedule", - "content": "# s14: Cron Scheduler — Producing Work on a Schedule\n\ns01 → ... → s12 → s13 → `s14` → [s15](/en/s15) → s16 → ... → s20 → s21 → s22\n> *\"Produce work on a schedule, decouple scheduling from execution\"* — Cron scheduling, durable or session-level.\n>\n> **Harness Layer**: Scheduling — Independent thread checks time, queue delivers triggers.\n\n---\n\n## The Problem\n\nAn alarm clock doesn't need you to watch it. You set 7:00, it rings at 7:00 — you could be sleeping, showering, cooking, it rings regardless.\n\ns13 lets the agent run slow operations in the background, but every operation is still triggered manually. You say something, the agent acts. \"Run tests every morning at 9am\", \"Check CI status every 30 minutes\" — these recurring tasks shouldn't need a human to push them each time.\n\n---\n\n## The Solution\n\n![Cron Scheduler Overview](/course-assets/s14_cron_scheduler/cron-scheduler-overview.en.svg)\n\nTeaching code carries forward S13's simplified task system, background execution, and prompt assembly; to stay focused on the scheduler, it omits full error recovery, memory, and skill systems. Added: an independent cron scheduler thread that polls every second, queues matching jobs into `cron_queue`, and a queue processor that delivers them when the agent is idle.\n\nManual vs Scheduled:\n\n| | Manual (s13) | Scheduled (s14) |\n|---|---|---|\n| Triggered by | User input | Scheduler thread |\n| Trigger timing | Anytime | Specified by cron expression |\n| Human involvement | Yes | No (scheduler auto-enqueues, idle agent auto-delivers) |\n| Persistence | — | Durable survives restart |\n\n---\n\n## How It Works\n\n### Four-Layer Model\n\nCron scheduling has four layers:\n\n1. **Scheduler**: daemon thread, polls every second, checks if it's time\n2. **Queue**: `cron_queue`, scheduler writes fired jobs\n3. **Queue Processor**: sees non-empty queue and idle agent, starts one agent_loop turn\n4. **Consumer**: agent_loop consumes queue and injects into messages\n\nThe teaching version implements a minimal queue processor: `agent_lock` tells whether the agent is idle, and queued cron work is delivered automatically. Real CC's `useQueueProcessor.ts` also handles UI blocking, queue priority, and different message modes.\n\n### CronJob: Data Structure\n\nEach cron task is a `CronJob` object:\n\n```python\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\" (5-field cron expression)\n prompt: str # Message injected to the agent when fired\n recurring: bool # True=recurring, False=one-shot\n durable: bool # True=write to disk, survives sessions\n```\n\nCron expression, 5 fields, used by Unix for 50 years:\n\n```\nmin hour dom month dow\n * * * * * Every minute\n 0 9 * * * Every day at 9:00\n*/5 * * * * Every 5 minutes\n 0 9 * * 1-5 Weekdays at 9:00\n```\n\nSupports `*`, `*/N`, `N`, `N-M`, `N,M,...`.\n\n### cron_matches: 5-Field Matching\n\nStandard cron semantics: minute, hour, month must all match; day-of-month (DOM) and day-of-week (DOW) use OR when both are constrained:\n\n```python\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n if not (m and h and month_ok):\n return False\n # DOM and DOW: both constrained → either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n```\n\n### Independent Scheduler Thread: 1-Second Polling\n\nThe scheduler runs in an independent daemon thread, not dependent on whether agent_loop is executing. Individual job errors don't kill the entire thread:\n\n```python\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\"[cron error] {job.id}: {e}\")\n```\n\nKey design:\n- **Independent of agent_loop**: scheduler checks time in background even when agent_loop isn't running\n- **Date-aware minute_marker**: uses `\"YYYY-MM-DD HH:MM\"` to prevent same-minute double-fire while not skipping on the next day\n- **Per-job try/except**: one bad job doesn't crash the scheduler thread\n- **One-shot jobs**: auto-removed from scheduled_jobs after firing\n\n### Queue Processor + agent_loop: Delivery\n\nThe queue processor does not check time. It only starts a turn when queued work exists and the agent is idle:\n\n```python\ndef queue_processor_loop():\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if has_cron_queue():\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n```\n\nagent_loop also doesn't check time. It only takes fired tasks from `cron_queue` and injects them into messages:\n\n```python\nfired = consume_cron_queue()\nfor job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n```\n\nProducer (scheduler thread), deliverer (queue processor), and consumer (agent_loop) are decoupled via `cron_queue`, `cron_lock`, and `agent_lock`.\n\n### Validation: Prevent Bad Cron from Killing the Scheduler\n\n`schedule_job` validates the cron expression before registering, returning an error for invalid input:\n\n```python\ndef schedule_job(cron, prompt, recurring=True, durable=True):\n err = validate_cron(cron)\n if err:\n return err\n # ... register job\n```\n\nLoading durable jobs from disk also skips invalid expressions, preventing a single bad task from breaking startup.\n\n### Durable vs Session-only\n\n- **Durable**: Task definition written to `.scheduled_tasks.json`. Loaded on agent restart.\n- **Session-only**: In-memory only. Gone when the agent closes.\n\n> **Important caveat**: The cron scheduler must run inside the agent process. Process exits, scheduler stops. Durable only means the task definition survives restarts — next time the agent starts, the scheduler discovers \"it should fire\" and fires. If you need \"run even when the app is closed\", use system crontab or systemd timer.\n\n### Putting It Together\n\n```\n1. On startup:\n load_durable_jobs() → restore durable tasks from .scheduled_tasks.json\n Thread(cron_scheduler_loop, daemon=True).start() → scheduler begins polling\n Thread(queue_processor_loop, daemon=True).start() → processor waits to deliver\n\n2. Register a task:\n schedule_cron(cron=\"*/2 * * * *\", prompt=\"run date\", durable=True)\n → CronJob written to scheduled_jobs + .scheduled_tasks.json\n\n3. Every 2 minutes:\n Scheduler checks → cron_matches returns True → cron_queue.append(job)\n → queue processor sees idle agent → agent_loop consume_cron_queue\n → injects \"[Scheduled] run date\"\n → LLM receives message, runs date command\n\n4. Process shutdown:\n Scheduler thread stops (daemon=True)\n .scheduled_tasks.json stays on disk\n Next startup → load_durable_jobs → tasks restored\n```\n\n---\n\n## Changes from s13\n\n| Component | Before (s13) | After (s14) |\n|-----------|-------------|-------------|\n| Trigger method | User manual trigger | Scheduler thread auto-enqueues |\n| New types | — | CronJob dataclass (id, cron, prompt, recurring, durable) |\n| New functions | — | cron_matches, validate_cron, schedule_job, cancel_job, cron_scheduler_loop, queue_processor_loop |\n| New storage | — | .scheduled_tasks.json (durable) + memory (session-only) |\n| Threads | Background execution thread | + Scheduler thread (daemon, 1s polling) + queue processor thread |\n| Queue | background_results | + cron_queue (scheduler writes, queue processor delivers, agent_loop consumes) |\n| Tools | 8 (s12/s13) | + schedule_cron, list_crons, cancel_cron (11) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s14_cron_scheduler/code.py\n```\n\nTry these prompts:\n\n1. `Schedule a task to print the current date every 2 minutes`\n2. `List all cron jobs`\n3. `Create a one-shot reminder in 1 minute to check the build status`\n4. `Cancel the recurring job and verify with list_crons`\n\nWhat to observe: Is the scheduler thread running independently? Do cron tasks fire at the correct time? Without a new prompt, do you see `[queue processor]` and automatic execution? Is the durable job written to `.scheduled_tasks.json`?\n\n---\n\n## What's Next\n\nOne agent can do a lot now: plan, compress, background, schedule. But some tasks are too big for one agent.\n\n\"Refactor the entire backend\" — overhaul auth, database layer, API routes, and tests. One agent's attention is limited. This needs a team.\n\ns15 Agent Teams → One agent isn't enough, form a team. Persistent teammates + async inboxes.\n\n
\nDeep Dive into CC Source\n\n> The following is a complete analysis based on CC source code `CronCreateTool.ts`, `cronScheduler.ts`, `cron.ts`, `cronTasks.ts`, `cronTasksLock.ts`, `useScheduledTasks.ts` (139 lines).\n\n### 1. Three Cron Tools\n\nCC exposes three cron tools to the model: `CronCreate`, `CronDelete`, `CronList`. All controlled by compile-time gate `feature('AGENT_TRIGGERS')` and runtime GrowthBook flag `tengu_kairos_cron`. There's also a `CLAUDE_CODE_DISABLE_CRON` env var for local override.\n\n### 2. Storage: `.claude/scheduled_tasks.json`\n\n```json\n{ \"tasks\": [{ \"id\": \"abc12345\", \"cron\": \"0 9 * * *\", \"prompt\": \"...\", \"recurring\": true, \"durable\": true, \"createdAt\": 1714567890000 }] }\n```\n\nDurable tasks write to disk; session-only tasks live in `STATE.sessionCronTasks` memory array (lost on process restart). A `.scheduled_tasks.lock` file prevents duplicate firing across multiple sessions of the same project.\n\n### 3. Scheduler: 1-Second Polling\n\n`cronScheduler.ts` checks every second (`CHECK_INTERVAL_MS = 1000`). Whoever holds the lock triggers file tasks; all sessions trigger session-only tasks. A `chokidar` file watcher monitors `scheduled_tasks.json` changes.\n\n### 4. Cron Expression: Standard 5 Fields\n\nMinute hour day month weekday. Supports `*`, `*/N`, `N`, `N-M`, `N-M/S`, `N,M,...`. Doesn't support `L`, `W`, `?`. All times interpreted in local timezone. Day-of-month and day-of-week use OR semantics when both are constrained.\n\n### 5. Jitter (Thundering Herd Prevention)\n\n- Recurring tasks: trigger delay up to 10% of period (max 15 min), deterministic hash based on task ID\n- One-shot tasks: up to 90s early when firing time falls on `:00` or `:30`\n- Jitter config adjustable via GrowthBook, refreshed every 60 seconds\n\n### 6. Auto-Expiration\n\nRecurring tasks auto-expire after 7 days (configurable, max 30 days). Fire one last time before expiry, then auto-delete.\n\n### 7. Job Limit\n\n`MAX_JOBS = 50` (`CronCreateTool.ts:25`). Returns error when exceeded: \"Too many scheduled jobs (max 50). Cancel one first.\"\n\n### 8. Trigger Injection\n\nAfter firing, enqueued via `enqueuePendingNotification()` with `priority: 'later'` into the command queue. Tagged `workload: WORKLOAD_CRON` — API serves cron-initiated requests at lower QoS when capacity is tight.\n\n### 9. Queue Processor: Automatic Delivery\n\nReal CC auto-triggers processing through `useQueueProcessor.ts:48-60` when no query is active, UI isn't blocked, and queue is non-empty. `queueProcessor.ts:52-87` dispatches commands to `handlePromptSubmit()` by queue priority. The teaching version keeps the core behavior with `queue_processor_loop`: when queued work exists and the agent is idle, it starts one agent_loop turn automatically.\n\n
\n\n\n" + "content": "# s14: Cron Scheduler — Producing Work on a Schedule\n\ns01 → ... → s12 → s13 → `s14` → [s15](/en/s15) → s16 → ... → s20 → s21\n> *\"Produce work on a schedule, decouple scheduling from execution\"* — Cron scheduling, durable or session-level.\n>\n> **Harness Layer**: Scheduling — Independent thread checks time, queue delivers triggers.\n\n---\n\n## The Problem\n\nAn alarm clock doesn't need you to watch it. You set 7:00, it rings at 7:00 — you could be sleeping, showering, cooking, it rings regardless.\n\ns13 lets the agent run slow operations in the background, but every operation is still triggered manually. You say something, the agent acts. \"Run tests every morning at 9am\", \"Check CI status every 30 minutes\" — these recurring tasks shouldn't need a human to push them each time.\n\n---\n\n## The Solution\n\n![Cron Scheduler Overview](/course-assets/s14_cron_scheduler/cron-scheduler-overview.en.svg)\n\nThis chapter adds an independent cron scheduler thread: it checks once per second, writes due jobs to `cron_queue`, and a queue processor delivers them when the agent is idle.\n\nManual vs Scheduled:\n\n| | Manual (s13) | Scheduled (s14) |\n|---|---|---|\n| Triggered by | User input | Scheduler thread |\n| Trigger timing | Anytime | Specified by cron expression |\n| Human involvement | Yes | No (scheduler auto-enqueues, idle agent auto-delivers) |\n| Persistence | — | Durable survives restart |\n\n---\n\n## How It Works\n\n### Four-Layer Model\n\nCron scheduling has four layers:\n\n1. **Scheduler**: daemon thread, polls every second, checks if it's time\n2. **Queue**: `cron_queue`, scheduler writes fired jobs\n3. **Queue Processor**: sees non-empty queue and idle agent, starts one agent_loop turn\n4. **Consumer**: agent_loop consumes queue and injects into messages\n\n### CronJob: Data Structure\n\nEach cron task is a `CronJob` object:\n\n```python\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\" (5-field cron expression)\n prompt: str # Message injected to the agent when fired\n recurring: bool # True=recurring, False=one-shot\n durable: bool # True=write to disk, survives sessions\n```\n\nCron expression, 5 fields, used by Unix for 50 years:\n\n```\nmin hour dom month dow\n * * * * * Every minute\n 0 9 * * * Every day at 9:00\n*/5 * * * * Every 5 minutes\n 0 9 * * 1-5 Weekdays at 9:00\n```\n\nSupports `*`, `*/N`, `N`, `N-M`, `N,M,...`.\n\n### cron_matches: 5-Field Matching\n\nStandard cron semantics: minute, hour, month must all match; day-of-month (DOM) and day-of-week (DOW) use OR when both are constrained:\n\n```python\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n if not (m and h and month_ok):\n return False\n # DOM and DOW: both constrained → either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n```\n\n### Independent Scheduler Thread: 1-Second Polling\n\nThe scheduler runs in an independent daemon thread, not dependent on whether agent_loop is executing. Individual job errors don't kill the entire thread:\n\n```python\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\"[cron error] {job.id}: {e}\")\n```\n\nKey design:\n- **Independent of agent_loop**: scheduler checks time in background even when agent_loop isn't running\n- **Date-aware minute_marker**: uses `\"YYYY-MM-DD HH:MM\"` to prevent same-minute double-fire while not skipping on the next day\n- **Per-job try/except**: one bad job doesn't crash the scheduler thread\n- **One-shot jobs**: auto-removed from scheduled_jobs after firing\n\n### Queue Processor + agent_loop: Delivery\n\nThe queue processor does not check time. It only starts a turn when queued work exists and the agent is idle:\n\n```python\ndef queue_processor_loop():\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if has_cron_queue():\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n```\n\nagent_loop also doesn't check time. It only takes fired tasks from `cron_queue` and injects them into messages:\n\n```python\nfired = consume_cron_queue()\nfor job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n```\n\nProducer (scheduler thread), deliverer (queue processor), and consumer (agent_loop) are decoupled via `cron_queue`, `cron_lock`, and `agent_lock`.\n\n### Validation: Prevent Bad Cron from Killing the Scheduler\n\n`schedule_job` validates the cron expression before registering, returning an error for invalid input:\n\n```python\ndef schedule_job(cron, prompt, recurring=True, durable=True):\n err = validate_cron(cron)\n if err:\n return err\n # ... register job\n```\n\nLoading durable jobs from disk also skips invalid expressions, preventing a single bad task from breaking startup.\n\n### Durable vs Session-only\n\n- **Durable**: Task definition written to `.scheduled_tasks.json`. Loaded on agent restart.\n- **Session-only**: In-memory only. Gone when the agent closes.\n\n> **Important caveat**: The cron scheduler must run inside the agent process. Process exits, scheduler stops. Durable only means the task definition survives restarts — next time the agent starts, the scheduler discovers \"it should fire\" and fires. If you need \"run even when the app is closed\", use system crontab or systemd timer.\n\n### Putting It Together\n\n```\n1. On startup:\n load_durable_jobs() → restore durable tasks from .scheduled_tasks.json\n Thread(cron_scheduler_loop, daemon=True).start() → scheduler begins polling\n Thread(queue_processor_loop, daemon=True).start() → processor waits to deliver\n\n2. Register a task:\n schedule_cron(cron=\"*/2 * * * *\", prompt=\"run date\", durable=True)\n → CronJob written to scheduled_jobs + .scheduled_tasks.json\n\n3. Every 2 minutes:\n Scheduler checks → cron_matches returns True → cron_queue.append(job)\n → queue processor sees idle agent → agent_loop consume_cron_queue\n → injects \"[Scheduled] run date\"\n → LLM receives message, runs date command\n\n4. Process shutdown:\n Scheduler thread stops (daemon=True)\n .scheduled_tasks.json stays on disk\n Next startup → load_durable_jobs → tasks restored\n```\n\n---\n\n## Changes from s13\n\n| Component | Before (s13) | After (s14) |\n|-----------|-------------|-------------|\n| Trigger method | User manual trigger | Scheduler thread auto-enqueues |\n| New types | — | CronJob dataclass (id, cron, prompt, recurring, durable) |\n| New functions | — | cron_matches, validate_cron, schedule_job, cancel_job, cron_scheduler_loop, queue_processor_loop |\n| New storage | — | .scheduled_tasks.json (durable) + memory (session-only) |\n| Threads | Background execution thread | + Scheduler thread (daemon, 1s polling) + queue processor thread |\n| Queue | background_results | + cron_queue (scheduler writes, queue processor delivers, agent_loop consumes) |\n| Tools | 8 (s12/s13) | + schedule_cron, list_crons, cancel_cron (11) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s14_cron_scheduler/code.py\n```\n\nTry these prompts:\n\n1. `Schedule a task to print the current date every 2 minutes`\n2. `List all cron jobs`\n3. `Create a one-shot reminder in 1 minute to check the build status`\n4. `Cancel the recurring job and verify with list_crons`\n\nWhat to observe: Is the scheduler thread running independently? Do cron tasks fire at the correct time? Without a new prompt, do you see `[queue processor]` and automatic execution? Is the durable job written to `.scheduled_tasks.json`?\n\n---\n\n## What's Next\n\nOne agent can do a lot now: plan, compress, background, schedule. But some tasks are too big for one agent.\n\n\"Refactor the entire backend\" — overhaul auth, database layer, API routes, and tests. One agent's attention is limited. This needs a team.\n\ns15 Agent Teams → One agent isn't enough, form a team. Persistent teammates + async inboxes.\n\n\n\n" }, { "version": "s14", "locale": "zh", "title": "s14: Cron Scheduler — 按时间表生产工作", - "content": "# s14: Cron Scheduler — 按时间表生产工作\n\ns01 → ... → s12 → s13 → `s14` → [s15](/zh/s15) → s16 → ... → s20 → s21 → s22\n> *\"按时间表生产工作, 调度与执行解耦\"* — cron 调度, 持久化或会话级。\n>\n> **Harness 层**: 调度 — 独立线程判断时间, 队列传递触发。\n\n---\n\n## 问题\n\n闹钟不需要你盯着它才会响。你设好 7:00,到点它自己响,你在睡觉、在洗澡、在做饭,它都照响不误。\n\ns13 让 Agent 能后台执行慢操作,但所有操作仍然是你手动触发的。你说一句,Agent 动一下。\"每天早上 9 点跑测试\"、\"每 30 分钟检查 CI 状态\",这些周期性任务不该需要人每次来推。\n\n---\n\n## 解决方案\n\n![Cron Scheduler Overview](/course-assets/s14_cron_scheduler/cron-scheduler-overview.svg)\n\n教学代码沿用 S13 的简化任务系统、后台执行和 prompt 组装;为了聚焦调度器,省略完整错误恢复、记忆和技能系统。新增:独立的 cron 调度线程,每秒检查一次,时间到了把任务塞进 `cron_queue`;再由 queue processor 在 Agent 空闲时自动交付。\n\n手动 vs 定时:\n\n| | 手动触发 (s13) | 定时触发 (s14) |\n|---|---|---|\n| 触发者 | 用户输入 | 调度线程 |\n| 触发时机 | 随时 | cron 表达式指定 |\n| 需要人参与 | 是 | 否(调度器自动入队,空闲时自动交付) |\n| 持久性 | — | durable 跨重启 |\n\n---\n\n## 工作原理\n\n### 四层模型\n\nCron 调度分四层:\n\n1. **Scheduler**:daemon 线程,每秒轮询,判断时间到了没有\n2. **Queue**:`cron_queue`,调度线程写入已触发任务\n3. **Queue Processor**:发现队列非空且 Agent 空闲,启动一轮 agent_loop\n4. **Consumer**:agent_loop 从队列消费,注入到 messages\n\n教学版实现的是最小 queue processor:用 `agent_lock` 判断 Agent 是否空闲,空闲时自动交付定时任务。真实 CC 的 `useQueueProcessor.ts` 还会处理 UI 阻塞、队列优先级和不同消息模式。\n\n### CronJob: 数据结构\n\n每个 cron 任务是一个 `CronJob` 对象:\n\n```python\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\" (五段式 cron 表达式)\n prompt: str # 触发时注入给 Agent 的消息\n recurring: bool # True=周期性,False=一次性\n durable: bool # True=写磁盘,跨会话保留\n```\n\nCron 表达式,五段式,Unix 用了 50 年:\n\n```\n分钟 小时 日 月 星期\n * * * * * 每分钟\n 0 9 * * * 每天早上 9:00\n */5 * * * * 每 5 分钟\n 0 9 * * 1-5 工作日早上 9:00\n```\n\n支持 `*`、`*/N`、`N`、`N-M`、`N,M,...`。\n\n### cron_matches: 五段式匹配\n\n标准 cron 语义:分钟、小时、月必须全部匹配;日(DOM)和星期(DOW)同时被约束时任一匹配即可(OR):\n\n```python\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n if not (m and h and month_ok):\n return False\n # DOM and DOW: both constrained → either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n```\n\n### 独立调度线程: 每秒轮询\n\n调度器跑在独立的 daemon 线程里,不依赖 agent_loop 是否在执行。单个 job 异常不会杀掉整个线程:\n\n```python\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\"[cron error] {job.id}: {e}\")\n```\n\n关键设计:\n- **独立于 agent_loop**:即使 agent_loop 没在跑,调度器也在后台检查时间\n- **date-aware minute_marker**:用 `\"YYYY-MM-DD HH:MM\"` 防止同一分钟重复触发,同时不会在第二天跳过\n- **单 job try/except**:一个坏 job 不会拖垮整个调度线程\n- **一次性任务**:触发后自动从 scheduled_jobs 里删除\n\n### Queue Processor + agent_loop: 交付端\n\nqueue processor 不检查时间,只负责在队列有任务且 Agent 空闲时拉起一轮执行:\n\n```python\ndef queue_processor_loop():\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if has_cron_queue():\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n```\n\nagent_loop 也不负责检查时间,它只从 `cron_queue` 里拿已触发的任务,注入到 messages 里:\n\n```python\nfired = consume_cron_queue()\nfor job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n```\n\n生产者(调度线程)、交付者(queue processor)和消费者(agent_loop)通过 `cron_queue`、`cron_lock`、`agent_lock` 解耦。\n\n### 校验:防止坏 cron 杀掉调度器\n\n`schedule_job` 在注册前校验 cron 表达式,非法的直接返回错误:\n\n```python\ndef schedule_job(cron, prompt, recurring=True, durable=True):\n err = validate_cron(cron)\n if err:\n return err\n # ... register job\n```\n\n从磁盘加载 durable job 时也会跳过非法表达式,避免单个坏任务拖垮启动。\n\n### Durable vs Session-only\n\n- **Durable**:任务定义写进 `.scheduled_tasks.json`。Agent 重启后加载文件,恢复任务。\n- **Session-only**:只在内存里。Agent 关闭就没了。\n\n> **重要前提**:cron 调度器必须在 Agent 进程内跑。进程关闭,调度也停。Durable 只意味着任务定义跨重启保留,下次 Agent 启动时调度器才会发现\"该触发了\"并触发。如果需要\"即使应用关闭也能定时跑\",请用系统 crontab 或 systemd timer。\n\n### 合起来跑\n\n```\n1. 启动时:\n load_durable_jobs() → 从 .scheduled_tasks.json 恢复持久化任务\n Thread(cron_scheduler_loop, daemon=True).start() → 调度线程开始轮询\n Thread(queue_processor_loop, daemon=True).start() → 队列处理器等待交付\n\n2. 注册任务:\n schedule_cron(cron=\"*/2 * * * *\", prompt=\"run date\", durable=True)\n → CronJob 写入 scheduled_jobs + .scheduled_tasks.json\n\n3. 每 2 分钟:\n 调度线程检查 → cron_matches 返回 True → cron_queue.append(job)\n → queue processor 发现 Agent 空闲 → agent_loop consume_cron_queue\n → 注入 \"[Scheduled] run date\"\n → LLM 收到消息,执行 date 命令\n\n4. 关闭进程:\n 调度线程跟着停(daemon=True)\n .scheduled_tasks.json 还在磁盘上\n 下次启动 → load_durable_jobs → 任务恢复\n```\n\n---\n\n## 相对 s13 的变更\n\n| 组件 | 之前 (s13) | 之后 (s14) |\n|------|-----------|-----------|\n| 触发方式 | 用户手动触发 | 调度线程自动入队 |\n| 新类型 | — | CronJob dataclass (id, cron, prompt, recurring, durable) |\n| 新函数 | — | cron_matches, validate_cron, schedule_job, cancel_job, cron_scheduler_loop, queue_processor_loop |\n| 新存储 | — | .scheduled_tasks.json (durable) + 内存 (session-only) |\n| 线程 | 后台执行线程 | + 调度线程 (daemon, 1s 轮询) + queue processor 线程 |\n| 队列 | background_results | + cron_queue (调度线程写, queue processor 交付, agent_loop 消费) |\n| 工具 | 8 (s12/s13) | + schedule_cron, list_crons, cancel_cron (11) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s14_cron_scheduler/code.py\n```\n\n试试这些 prompt:\n\n1. `Schedule a task to print the current date every 2 minutes`\n2. `List all cron jobs`\n3. `Create a one-shot reminder in 1 minute to check the build status`\n4. `Cancel the recurring job and verify with list_crons`\n\n观察重点:调度线程是否在独立运行?cron 任务是否在正确的时间点触发?不输入新 prompt 时,是否也出现 `[queue processor]` 并自动执行?durable job 是否写入了 `.scheduled_tasks.json`?\n\n---\n\n## 接下来\n\n一个 Agent 能做很多事了,能计划、能压缩、能后台、能定时。但有些任务太大了,不是一个 Agent 能搞定的。\n\n\"重构整个后端\",把认证模块、数据库层、API 路由、测试全部翻新。一个 Agent 的注意力是有限的,这需要一个团队。\n\ns15 Agent Teams → 一个 Agent 不够,组队吧。持久队友 + 异步收件箱。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `CronCreateTool.ts`、`cronScheduler.ts`、`cron.ts`、`cronTasks.ts`、`cronTasksLock.ts`、`useScheduledTasks.ts`(139 行)的完整分析。\n\n### 一、三个 Cron 工具\n\nCC 暴露了三个 cron 工具给模型:`CronCreate`、`CronDelete`、`CronList`。全部由编译时门控 `feature('AGENT_TRIGGERS')` 和运行时 GrowthBook 标志 `tengu_kairos_cron` 控制。还有一个 `CLAUDE_CODE_DISABLE_CRON` 环境变量做本地覆盖。\n\n### 二、存储:`.claude/scheduled_tasks.json`\n\n```json\n{ \"tasks\": [{ \"id\": \"abc12345\", \"cron\": \"0 9 * * *\", \"prompt\": \"...\", \"recurring\": true, \"durable\": true, \"createdAt\": 1714567890000 }] }\n```\n\nDurable 任务写磁盘;session-only 任务存于 `STATE.sessionCronTasks` 内存数组(进程重启丢失)。还有一个 `.scheduled_tasks.lock` 文件防止同项目的多个 session 重复触发。\n\n### 三、调度器:1 秒轮询\n\n`cronScheduler.ts` 每秒检查一次(`CHECK_INTERVAL_MS = 1000`)。谁持有锁谁触发文件任务;所有 session 都触发仅 session 任务。还有一个 `chokidar` 文件观察者监视 `scheduled_tasks.json` 变更。\n\n### 四、Cron 表达式:标准 5 字段\n\n分钟 小时 日 月 星期。支持 `*`、`*/N`、`N`、`N-M`、`N-M/S`、`N,M,...`。不支持 `L`、`W`、`?`。所有时间以本地时区解释。Day-of-month 和 day-of-week 同时约束时用 OR 语义。\n\n### 五、抖动(防惊群效应)\n\n- 重复性任务:触发延迟最多可达期间的 10%(上限 15 分钟),基于任务 ID 的确定性哈希\n- 一次性任务:当触发时间落在 `:00` 或 `:30` 时,最多提前 90 秒触发\n- 抖动配置可通过 GrowthBook 实时调整,60 秒刷新一次\n\n### 六、自动过期\n\n重复性任务 7 天后自动过期(可配置,上限 30 天)。过期前最后一次触发,触发后自动删除。\n\n### 七、作业数上限\n\n`MAX_JOBS = 50`(`CronCreateTool.ts:25`)。超限时返回错误:\"Too many scheduled jobs (max 50). Cancel one first.\"\n\n### 八、触发注入\n\n触发后通过 `enqueuePendingNotification()` 以 `priority: 'later'` 入队命令队列。标记 `workload: WORKLOAD_CRON`,API 在容量紧张时以更低的 QoS 为 cron 发起的请求服务。\n\n### 九、Queue Processor:自动交付\n\n真实 CC 通过 `useQueueProcessor.ts:48-60` 在无 query、无阻塞 UI、队列非空时自动触发处理。`queueProcessor.ts:52-87` 按队列优先级把命令交给 `handlePromptSubmit()`。教学版用 `queue_processor_loop` 保留核心行为:队列有任务且 Agent 空闲时,自动启动一轮 agent_loop。\n\n
\n\n\n" + "content": "# s14: Cron Scheduler — 按时间表生产工作\n\ns01 → ... → s12 → s13 → `s14` → [s15](/zh/s15) → s16 → ... → s20 → s21\n> *\"按时间表生产工作, 调度与执行解耦\"* — cron 调度, 持久化或会话级。\n>\n> **Harness 层**: 调度 — 独立线程判断时间, 队列传递触发。\n\n---\n\n## 问题\n\n闹钟不需要你盯着它才会响。你设好 7:00,到点它自己响,你在睡觉、在洗澡、在做饭,它都照响不误。\n\ns13 让 Agent 能后台执行慢操作,但所有操作仍然是你手动触发的。你说一句,Agent 动一下。\"每天早上 9 点跑测试\"、\"每 30 分钟检查 CI 状态\",这些周期性任务不该需要人每次来推。\n\n---\n\n## 解决方案\n\n![Cron Scheduler Overview](/course-assets/s14_cron_scheduler/cron-scheduler-overview.svg)\n\n本章新增独立的 cron 调度线程:每秒检查一次,把到期任务写入 `cron_queue`,再由 queue processor 在 Agent 空闲时自动交付。\n\n手动 vs 定时:\n\n| | 手动触发 (s13) | 定时触发 (s14) |\n|---|---|---|\n| 触发者 | 用户输入 | 调度线程 |\n| 触发时机 | 随时 | cron 表达式指定 |\n| 需要人参与 | 是 | 否(调度器自动入队,空闲时自动交付) |\n| 持久性 | — | durable 跨重启 |\n\n---\n\n## 工作原理\n\n### 四层模型\n\nCron 调度分四层:\n\n1. **Scheduler**:daemon 线程,每秒轮询,判断时间到了没有\n2. **Queue**:`cron_queue`,调度线程写入已触发任务\n3. **Queue Processor**:发现队列非空且 Agent 空闲,启动一轮 agent_loop\n4. **Consumer**:agent_loop 从队列消费,注入到 messages\n\n### CronJob: 数据结构\n\n每个 cron 任务是一个 `CronJob` 对象:\n\n```python\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\" (五段式 cron 表达式)\n prompt: str # 触发时注入给 Agent 的消息\n recurring: bool # True=周期性,False=一次性\n durable: bool # True=写磁盘,跨会话保留\n```\n\nCron 表达式,五段式,Unix 用了 50 年:\n\n```\n分钟 小时 日 月 星期\n * * * * * 每分钟\n 0 9 * * * 每天早上 9:00\n */5 * * * * 每 5 分钟\n 0 9 * * 1-5 工作日早上 9:00\n```\n\n支持 `*`、`*/N`、`N`、`N-M`、`N,M,...`。\n\n### cron_matches: 五段式匹配\n\n标准 cron 语义:分钟、小时、月必须全部匹配;日(DOM)和星期(DOW)同时被约束时任一匹配即可(OR):\n\n```python\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n if not (m and h and month_ok):\n return False\n # DOM and DOW: both constrained → either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n```\n\n### 独立调度线程: 每秒轮询\n\n调度器跑在独立的 daemon 线程里,不依赖 agent_loop 是否在执行。单个 job 异常不会杀掉整个线程:\n\n```python\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\"[cron error] {job.id}: {e}\")\n```\n\n关键设计:\n- **独立于 agent_loop**:即使 agent_loop 没在跑,调度器也在后台检查时间\n- **date-aware minute_marker**:用 `\"YYYY-MM-DD HH:MM\"` 防止同一分钟重复触发,同时不会在第二天跳过\n- **单 job try/except**:一个坏 job 不会拖垮整个调度线程\n- **一次性任务**:触发后自动从 scheduled_jobs 里删除\n\n### Queue Processor + agent_loop: 交付端\n\nqueue processor 不检查时间,只负责在队列有任务且 Agent 空闲时拉起一轮执行:\n\n```python\ndef queue_processor_loop():\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if has_cron_queue():\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n```\n\nagent_loop 也不负责检查时间,它只从 `cron_queue` 里拿已触发的任务,注入到 messages 里:\n\n```python\nfired = consume_cron_queue()\nfor job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n```\n\n生产者(调度线程)、交付者(queue processor)和消费者(agent_loop)通过 `cron_queue`、`cron_lock`、`agent_lock` 解耦。\n\n### 校验:防止坏 cron 杀掉调度器\n\n`schedule_job` 在注册前校验 cron 表达式,非法的直接返回错误:\n\n```python\ndef schedule_job(cron, prompt, recurring=True, durable=True):\n err = validate_cron(cron)\n if err:\n return err\n # ... register job\n```\n\n从磁盘加载 durable job 时也会跳过非法表达式,避免单个坏任务拖垮启动。\n\n### Durable vs Session-only\n\n- **Durable**:任务定义写进 `.scheduled_tasks.json`。Agent 重启后加载文件,恢复任务。\n- **Session-only**:只在内存里。Agent 关闭就没了。\n\n> **重要前提**:cron 调度器必须在 Agent 进程内跑。进程关闭,调度也停。Durable 只意味着任务定义跨重启保留,下次 Agent 启动时调度器才会发现\"该触发了\"并触发。如果需要\"即使应用关闭也能定时跑\",请用系统 crontab 或 systemd timer。\n\n### 合起来跑\n\n```\n1. 启动时:\n load_durable_jobs() → 从 .scheduled_tasks.json 恢复持久化任务\n Thread(cron_scheduler_loop, daemon=True).start() → 调度线程开始轮询\n Thread(queue_processor_loop, daemon=True).start() → 队列处理器等待交付\n\n2. 注册任务:\n schedule_cron(cron=\"*/2 * * * *\", prompt=\"run date\", durable=True)\n → CronJob 写入 scheduled_jobs + .scheduled_tasks.json\n\n3. 每 2 分钟:\n 调度线程检查 → cron_matches 返回 True → cron_queue.append(job)\n → queue processor 发现 Agent 空闲 → agent_loop consume_cron_queue\n → 注入 \"[Scheduled] run date\"\n → LLM 收到消息,执行 date 命令\n\n4. 关闭进程:\n 调度线程跟着停(daemon=True)\n .scheduled_tasks.json 还在磁盘上\n 下次启动 → load_durable_jobs → 任务恢复\n```\n\n---\n\n## 相对 s13 的变更\n\n| 组件 | 之前 (s13) | 之后 (s14) |\n|------|-----------|-----------|\n| 触发方式 | 用户手动触发 | 调度线程自动入队 |\n| 新类型 | — | CronJob dataclass (id, cron, prompt, recurring, durable) |\n| 新函数 | — | cron_matches, validate_cron, schedule_job, cancel_job, cron_scheduler_loop, queue_processor_loop |\n| 新存储 | — | .scheduled_tasks.json (durable) + 内存 (session-only) |\n| 线程 | 后台执行线程 | + 调度线程 (daemon, 1s 轮询) + queue processor 线程 |\n| 队列 | background_results | + cron_queue (调度线程写, queue processor 交付, agent_loop 消费) |\n| 工具 | 8 (s12/s13) | + schedule_cron, list_crons, cancel_cron (11) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s14_cron_scheduler/code.py\n```\n\n试试这些 prompt:\n\n1. `Schedule a task to print the current date every 2 minutes`\n2. `List all cron jobs`\n3. `Create a one-shot reminder in 1 minute to check the build status`\n4. `Cancel the recurring job and verify with list_crons`\n\n观察重点:调度线程是否在独立运行?cron 任务是否在正确的时间点触发?不输入新 prompt 时,是否也出现 `[queue processor]` 并自动执行?durable job 是否写入了 `.scheduled_tasks.json`?\n\n---\n\n## 接下来\n\n一个 Agent 能做很多事了,能计划、能压缩、能后台、能定时。但有些任务太大了,不是一个 Agent 能搞定的。\n\n\"重构整个后端\",把认证模块、数据库层、API 路由、测试全部翻新。一个 Agent 的注意力是有限的,这需要一个团队。\n\ns15 Agent Teams → 一个 Agent 不够,组队吧。持久队友 + 异步收件箱。\n\n\n\n" }, { "version": "s14", "locale": "ja", "title": "s14: Cron Scheduler — スケジュールに従って作業を生産", - "content": "# s14: Cron Scheduler — スケジュールに従って作業を生産\n\ns01 → ... → s12 → s13 → `s14` → [s15](/ja/s15) → s16 → ... → s20 → s21 → s22\n> *\"スケジュールに従って作業を生産、スケジューリングと実行を分離\"* — cron スケジューリング、永続またはセッションレベル。\n>\n> **Harness 層**: スケジューリング — 独立スレッドが時刻を判定、キューがトリガーを配信。\n\n---\n\n## 課題\n\n目覚まし時計はあなたが見ていないと鳴らないわけではない。7:00 にセットすれば、7:00 に鳴る。寝ていても、シャワーを浴びていても、料理をしていても、鳴る。\n\ns13 で Agent は遅い操作をバックグラウンドで実行できるようになった。しかし、すべての操作は手動でトリガーされる。一言言えば、Agent が動く。「毎朝 9 時にテストを実行」「30 分ごとに CI ステータスを確認」、これらの定期的なタスクに人が毎回押す必要はないはずだ。\n\n---\n\n## ソリューション\n\n![Cron Scheduler Overview](/course-assets/s14_cron_scheduler/cron-scheduler-overview.ja.svg)\n\n教学版は S13 の簡易タスクシステム、バックグラウンド実行、プロンプト組み立てを踏襲。スケジューラに集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。追加:独立した cron スケジューラスレッド、1 秒ごとにポーリング、時間が来たらタスクを `cron_queue` に投入し、queue processor が Agent のアイドル時に自動配信。\n\n手動 vs スケジュール:\n\n| | 手動 (s13) | スケジュール (s14) |\n|---|---|---|\n| トリガー | ユーザー入力 | スケジューラスレッド |\n| トリガー時刻 | いつでも | cron 式で指定 |\n| 人の関与 | あり | なし(スケジューラが自動キュー投入、アイドル時に自動配信) |\n| 永続性 | — | durable は再起動後も保持 |\n\n---\n\n## 仕組み\n\n### 4 層モデル\n\ncron スケジューリングは 4 層に分かれる:\n\n1. **Scheduler**:daemon スレッド、1 秒ごとにポーリング、時刻が来たか判定\n2. **Queue**:`cron_queue`、スケジューラが発火済みタスクを書き込み\n3. **Queue Processor**:キューが空でなく Agent がアイドルなら、一回の agent_loop を開始\n4. **Consumer**:agent_loop がキューから消費、messages に注入\n\n教学版は最小の queue processor を実装する。`agent_lock` で Agent がアイドルかを判定し、キューに入った cron 作業を自動配信する。実際の CC の `useQueueProcessor.ts` はさらに UI ブロック、キュープライオリティ、メッセージモードを扱う。\n\n### CronJob: データ構造\n\n各 cron タスクは `CronJob` オブジェクト:\n\n```python\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"(5 フィールド cron 式)\n prompt: str # 発火時に Agent に注入するメッセージ\n recurring: bool # True=定期的、False=一回限り\n durable: bool # True=ディスク書き込み、セッション横断\n```\n\ncron 式、5 フィールド、Unix で 50 年使われている:\n\n```\n分 時 日 月 曜日\n * * * * * 毎分\n 0 9 * * * 毎日 9:00\n*/5 * * * * 5 分ごと\n 0 9 * * 1-5 平日 9:00\n```\n\n`*`、`*/N`、`N`、`N-M`、`N,M,...` をサポート。\n\n### cron_matches: 5 フィールドマッチング\n\n標準 cron セマンティクス:分、時、月はすべてマッチ必須。日(DOM)と曜日(DOW)が両方制約されている場合は、いずれかのマッチで十分(OR):\n\n```python\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n if not (m and h and month_ok):\n return False\n # DOM and DOW: both constrained → either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n```\n\n### 独立スケジューラスレッド:1 秒ポーリング\n\nスケジューラは独立した daemon スレッドで動作、agent_loop が実行中かどうかに依存しない。個々のジョブエラーはスレッド全体を殺さない:\n\n```python\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\"[cron error] {job.id}: {e}\")\n```\n\n重要な設計:\n- **agent_loop から独立**:agent_loop が動いていなくても、スケジューラはバックグラウンドで時刻をチェック\n- **日付認識 minute_marker**:`\"YYYY-MM-DD HH:MM\"` を使用、同じ分の重複発火を防ぎつつ翌日のスキップも防止\n- **ジョブ単位の try/except**:一つの悪いジョブがスケジューラスレッド全体をクラッシュさせない\n- **一回限りジョブ**:発火後、scheduled_jobs から自動削除\n\n### Queue Processor + agent_loop: 配信側\n\nqueue processor は時刻をチェックしない。キューに作業があり、Agent がアイドルの時だけ一回の実行を開始する:\n\n```python\ndef queue_processor_loop():\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if has_cron_queue():\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n```\n\nagent_loop も時刻をチェックしない。`cron_queue` から発火済みタスクを取り出し、messages に注入するだけ:\n\n```python\nfired = consume_cron_queue()\nfor job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n```\n\n生産者(スケジューラスレッド)、配信者(queue processor)、消費者(agent_loop)は `cron_queue`、`cron_lock`、`agent_lock` で分離されている。\n\n### バリデーション:不正 cron がスケジューラを殺すのを防止\n\n`schedule_job` は登録前に cron 式をバリデーションし、不正な場合はエラーを返す:\n\n```python\ndef schedule_job(cron, prompt, recurring=True, durable=True):\n err = validate_cron(cron)\n if err:\n return err\n # ... ジョブ登録\n```\n\nディスクから durable ジョブを読み込む際も不正な式をスキップし、一つの悪いタスクが起動を妨げない。\n\n### Durable vs Session-only\n\n- **Durable**:タスク定義を `.scheduled_tasks.json` に書き込み。Agent 再起動後にファイルから復元。\n- **Session-only**:メモリ内のみ。Agent 終了で消失。\n\n> **重要な前提**:cron スケジューラは Agent プロセス内で実行される必要がある。プロセスが終了するとスケジューラも停止。Durable はタスク定義が再起動後も保持されることを意味するだけで、次回 Agent 起動時にスケジューラが「発火すべき」と判定して初めて発火する。「アプリケーションが閉じていても定期的に実行」が必要な場合は、システム crontab または systemd timer を使用。\n\n### 組み合わせて実行\n\n```\n1. 起動時:\n load_durable_jobs() → .scheduled_tasks.json から永続タスクを復元\n Thread(cron_scheduler_loop, daemon=True).start() → スケジューラスレッドがポーリング開始\n Thread(queue_processor_loop, daemon=True).start() → processor が配信待機\n\n2. タスク登録:\n schedule_cron(cron=\"*/2 * * * *\", prompt=\"run date\", durable=True)\n → CronJob を scheduled_jobs + .scheduled_tasks.json に書き込み\n\n3. 2 分ごと:\n スケジューラチェック → cron_matches が True → cron_queue.append(job)\n → queue processor がアイドル状態を検知 → agent_loop consume_cron_queue\n → \"[Scheduled] run date\" を注入\n → LLM がメッセージを受信、date コマンドを実行\n\n4. プロセス終了:\n スケジューラスレッドも停止(daemon=True)\n .scheduled_tasks.json はディスクに残存\n 次回起動 → load_durable_jobs → タスク復元\n```\n\n---\n\n## s13 からの変更\n\n| コンポーネント | 変更前 (s13) | 変更後 (s14) |\n|--------------|------------|------------|\n| トリガー方式 | ユーザー手動トリガー | スケジューラスレッドが自動キュー投入 |\n| 新規型 | — | CronJob データクラス (id, cron, prompt, recurring, durable) |\n| 新規関数 | — | cron_matches, validate_cron, schedule_job, cancel_job, cron_scheduler_loop, queue_processor_loop |\n| 新規ストレージ | — | .scheduled_tasks.json (durable) + メモリ (session-only) |\n| スレッド | バックグラウンド実行スレッド | + スケジューラスレッド (daemon, 1s ポーリング) + queue processor スレッド |\n| キュー | background_results | + cron_queue(スケジューラ書き込み、queue processor 配信、agent_loop 消費) |\n| ツール | 8 (s12/s13) | + schedule_cron, list_crons, cancel_cron (11) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s14_cron_scheduler/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Schedule a task to print the current date every 2 minutes`\n2. `List all cron jobs`\n3. `Create a one-shot reminder in 1 minute to check the build status`\n4. `Cancel the recurring job and verify with list_crons`\n\n観察ポイント:スケジューラスレッドが独立して動いているか?cron タスクが正しい時刻に発火しているか?新しい prompt を入力しなくても `[queue processor]` が出て自動実行されるか?durable ジョブが `.scheduled_tasks.json` に書き込まれているか?\n\n---\n\n## 次の章\n\n一つの Agent でできることは増えた。計画、圧縮、バックグラウンド、スケジューリング。しかし、一部のタスクは一つの Agent では大きすぎる。\n\n「バックエンド全体をリファクタリング」、認証モジュール、データベース層、API ルート、テストを全面的に刷新。一つの Agent の注意力には限界がある。これにはチームが必要だ。\n\ns15 Agent Teams → 一人の Agent では足りない、チームを組もう。永続的なチームメイト + 非同期受信箱。\n\n
\nCC ソースコード深掘り\n\n> 以下は CC ソースコード `CronCreateTool.ts`、`cronScheduler.ts`、`cron.ts`、`cronTasks.ts`、`cronTasksLock.ts`、`useScheduledTasks.ts`(139 行)の完全分析に基づく。\n\n### 一、3 つの Cron ツール\n\nCC はモデルに 3 つの cron ツールを公開:`CronCreate`、`CronDelete`、`CronList`。すべてコンパイル時ゲート `feature('AGENT_TRIGGERS')` とランタイム GrowthBook フラグ `tengu_kairos_cron` で制御。`CLAUDE_CODE_DISABLE_CRON` 環境変数でローカル上書きも可能。\n\n### 二、ストレージ:`.claude/scheduled_tasks.json`\n\n```json\n{ \"tasks\": [{ \"id\": \"abc12345\", \"cron\": \"0 9 * * *\", \"prompt\": \"...\", \"recurring\": true, \"durable\": true, \"createdAt\": 1714567890000 }] }\n```\n\ndurable タスクはディスクに書き込み。session-only タスクは `STATE.sessionCronTasks` メモリ配列に格納(プロセス再起動で消失)。`.scheduled_tasks.lock` ファイルで同じプロジェクトの複数セッション間の重複発火を防止。\n\n### 三、スケジューラ:1 秒ポーリング\n\n`cronScheduler.ts` は毎秒チェック(`CHECK_INTERVAL_MS = 1000`)。ロックを保持しているセッションがファイルタスクをトリガー。すべてのセッションが session-only タスクをトリガー。`chokidar` ファイルウォッチャーが `scheduled_tasks.json` の変更を監視。\n\n### 四、cron 式:標準 5 フィールド\n\n分 時 日 月 曜日。`*`、`*/N`、`N`、`N-M`、`N-M/S`、`N,M,...` をサポート。`L`、`W`、`?` は非サポート。すべての時間はローカルタイムゾーンで解釈。day-of-month と day-of-week が両方制約されている場合は OR セマンティクス。\n\n### 五、ジッター(サンダリングハード防止)\n\n- 定期タスク:トリガー遅延は期間の最大 10%(上限 15 分)、タスク ID ベースの決定的ハッシュ\n- 一回限りタスク:発火時刻が `:00` または `:30` の場合、最大 90 秒早く発火\n- ジッター設定は GrowthBook でリアルタイム調整可能、60 秒ごとにリフレッシュ\n\n### 六、自動期限切れ\n\n定期タスクは 7 日後に自動期限切れ(設定可能、上限 30 日)。期限切れ前に最後の一回を発火、その後自動削除。\n\n### 七、ジョブ数上限\n\n`MAX_JOBS = 50`(`CronCreateTool.ts:25`)。超過時はエラーを返す:\"Too many scheduled jobs (max 50). Cancel one first.\"\n\n### 八、トリガー注入\n\n発火後、`enqueuePendingNotification()` で `priority: 'later'` としてコマンドキューにエンキュー。`workload: WORKLOAD_CRON` タグ付き、API は容量が逼迫している時に cron 発信リクエストを低い QoS で処理。\n\n### 九、Queue Processor:自動配信\n\n実際の CC は `useQueueProcessor.ts:48-60` により、アクティブな query がなく、UI がブロックされておらず、キューが空でない場合に自動的に処理をトリガーする。`queueProcessor.ts:52-87` がキュープライオリティに従ってコマンドを `handlePromptSubmit()` にディスパッチ。教学版は `queue_processor_loop` で核心動作を保つ:キューに作業があり Agent がアイドルなら、自動的に一回の agent_loop を開始する。\n\n
\n\n\n" + "content": "# s14: Cron Scheduler — スケジュールに従って作業を生産\n\ns01 → ... → s12 → s13 → `s14` → [s15](/ja/s15) → s16 → ... → s20 → s21\n> *\"スケジュールに従って作業を生産、スケジューリングと実行を分離\"* — cron スケジューリング、永続またはセッションレベル。\n>\n> **Harness 層**: スケジューリング — 独立スレッドが時刻を判定、キューがトリガーを配信。\n\n---\n\n## 課題\n\n目覚まし時計はあなたが見ていないと鳴らないわけではない。7:00 にセットすれば、7:00 に鳴る。寝ていても、シャワーを浴びていても、料理をしていても、鳴る。\n\ns13 で Agent は遅い操作をバックグラウンドで実行できるようになった。しかし、すべての操作は手動でトリガーされる。一言言えば、Agent が動く。「毎朝 9 時にテストを実行」「30 分ごとに CI ステータスを確認」、これらの定期的なタスクに人が毎回押す必要はないはずだ。\n\n---\n\n## ソリューション\n\n![Cron Scheduler Overview](/course-assets/s14_cron_scheduler/cron-scheduler-overview.ja.svg)\n\nこの章では独立した cron スケジューラスレッドを追加する。1 秒ごとに確認し、期限に達したジョブを `cron_queue` に書き込み、queue processor が Agent のアイドル時に自動配信する。\n\n手動 vs スケジュール:\n\n| | 手動 (s13) | スケジュール (s14) |\n|---|---|---|\n| トリガー | ユーザー入力 | スケジューラスレッド |\n| トリガー時刻 | いつでも | cron 式で指定 |\n| 人の関与 | あり | なし(スケジューラが自動キュー投入、アイドル時に自動配信) |\n| 永続性 | — | durable は再起動後も保持 |\n\n---\n\n## 仕組み\n\n### 4 層モデル\n\ncron スケジューリングは 4 層に分かれる:\n\n1. **Scheduler**:daemon スレッド、1 秒ごとにポーリング、時刻が来たか判定\n2. **Queue**:`cron_queue`、スケジューラが発火済みタスクを書き込み\n3. **Queue Processor**:キューが空でなく Agent がアイドルなら、一回の agent_loop を開始\n4. **Consumer**:agent_loop がキューから消費、messages に注入\n\n### CronJob: データ構造\n\n各 cron タスクは `CronJob` オブジェクト:\n\n```python\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"(5 フィールド cron 式)\n prompt: str # 発火時に Agent に注入するメッセージ\n recurring: bool # True=定期的、False=一回限り\n durable: bool # True=ディスク書き込み、セッション横断\n```\n\ncron 式、5 フィールド、Unix で 50 年使われている:\n\n```\n分 時 日 月 曜日\n * * * * * 毎分\n 0 9 * * * 毎日 9:00\n*/5 * * * * 5 分ごと\n 0 9 * * 1-5 平日 9:00\n```\n\n`*`、`*/N`、`N`、`N-M`、`N,M,...` をサポート。\n\n### cron_matches: 5 フィールドマッチング\n\n標準 cron セマンティクス:分、時、月はすべてマッチ必須。日(DOM)と曜日(DOW)が両方制約されている場合は、いずれかのマッチで十分(OR):\n\n```python\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n if not (m and h and month_ok):\n return False\n # DOM and DOW: both constrained → either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n```\n\n### 独立スケジューラスレッド:1 秒ポーリング\n\nスケジューラは独立した daemon スレッドで動作、agent_loop が実行中かどうかに依存しない。個々のジョブエラーはスレッド全体を殺さない:\n\n```python\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\"[cron error] {job.id}: {e}\")\n```\n\n重要な設計:\n- **agent_loop から独立**:agent_loop が動いていなくても、スケジューラはバックグラウンドで時刻をチェック\n- **日付認識 minute_marker**:`\"YYYY-MM-DD HH:MM\"` を使用、同じ分の重複発火を防ぎつつ翌日のスキップも防止\n- **ジョブ単位の try/except**:一つの悪いジョブがスケジューラスレッド全体をクラッシュさせない\n- **一回限りジョブ**:発火後、scheduled_jobs から自動削除\n\n### Queue Processor + agent_loop: 配信側\n\nqueue processor は時刻をチェックしない。キューに作業があり、Agent がアイドルの時だけ一回の実行を開始する:\n\n```python\ndef queue_processor_loop():\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if has_cron_queue():\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n```\n\nagent_loop も時刻をチェックしない。`cron_queue` から発火済みタスクを取り出し、messages に注入するだけ:\n\n```python\nfired = consume_cron_queue()\nfor job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n```\n\n生産者(スケジューラスレッド)、配信者(queue processor)、消費者(agent_loop)は `cron_queue`、`cron_lock`、`agent_lock` で分離されている。\n\n### バリデーション:不正 cron がスケジューラを殺すのを防止\n\n`schedule_job` は登録前に cron 式をバリデーションし、不正な場合はエラーを返す:\n\n```python\ndef schedule_job(cron, prompt, recurring=True, durable=True):\n err = validate_cron(cron)\n if err:\n return err\n # ... ジョブ登録\n```\n\nディスクから durable ジョブを読み込む際も不正な式をスキップし、一つの悪いタスクが起動を妨げない。\n\n### Durable vs Session-only\n\n- **Durable**:タスク定義を `.scheduled_tasks.json` に書き込み。Agent 再起動後にファイルから復元。\n- **Session-only**:メモリ内のみ。Agent 終了で消失。\n\n> **重要な前提**:cron スケジューラは Agent プロセス内で実行される必要がある。プロセスが終了するとスケジューラも停止。Durable はタスク定義が再起動後も保持されることを意味するだけで、次回 Agent 起動時にスケジューラが「発火すべき」と判定して初めて発火する。「アプリケーションが閉じていても定期的に実行」が必要な場合は、システム crontab または systemd timer を使用。\n\n### 組み合わせて実行\n\n```\n1. 起動時:\n load_durable_jobs() → .scheduled_tasks.json から永続タスクを復元\n Thread(cron_scheduler_loop, daemon=True).start() → スケジューラスレッドがポーリング開始\n Thread(queue_processor_loop, daemon=True).start() → processor が配信待機\n\n2. タスク登録:\n schedule_cron(cron=\"*/2 * * * *\", prompt=\"run date\", durable=True)\n → CronJob を scheduled_jobs + .scheduled_tasks.json に書き込み\n\n3. 2 分ごと:\n スケジューラチェック → cron_matches が True → cron_queue.append(job)\n → queue processor がアイドル状態を検知 → agent_loop consume_cron_queue\n → \"[Scheduled] run date\" を注入\n → LLM がメッセージを受信、date コマンドを実行\n\n4. プロセス終了:\n スケジューラスレッドも停止(daemon=True)\n .scheduled_tasks.json はディスクに残存\n 次回起動 → load_durable_jobs → タスク復元\n```\n\n---\n\n## s13 からの変更\n\n| コンポーネント | 変更前 (s13) | 変更後 (s14) |\n|--------------|------------|------------|\n| トリガー方式 | ユーザー手動トリガー | スケジューラスレッドが自動キュー投入 |\n| 新規型 | — | CronJob データクラス (id, cron, prompt, recurring, durable) |\n| 新規関数 | — | cron_matches, validate_cron, schedule_job, cancel_job, cron_scheduler_loop, queue_processor_loop |\n| 新規ストレージ | — | .scheduled_tasks.json (durable) + メモリ (session-only) |\n| スレッド | バックグラウンド実行スレッド | + スケジューラスレッド (daemon, 1s ポーリング) + queue processor スレッド |\n| キュー | background_results | + cron_queue(スケジューラ書き込み、queue processor 配信、agent_loop 消費) |\n| ツール | 8 (s12/s13) | + schedule_cron, list_crons, cancel_cron (11) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s14_cron_scheduler/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Schedule a task to print the current date every 2 minutes`\n2. `List all cron jobs`\n3. `Create a one-shot reminder in 1 minute to check the build status`\n4. `Cancel the recurring job and verify with list_crons`\n\n観察ポイント:スケジューラスレッドが独立して動いているか?cron タスクが正しい時刻に発火しているか?新しい prompt を入力しなくても `[queue processor]` が出て自動実行されるか?durable ジョブが `.scheduled_tasks.json` に書き込まれているか?\n\n---\n\n## 次の章\n\n一つの Agent でできることは増えた。計画、圧縮、バックグラウンド、スケジューリング。しかし、一部のタスクは一つの Agent では大きすぎる。\n\n「バックエンド全体をリファクタリング」、認証モジュール、データベース層、API ルート、テストを全面的に刷新。一つの Agent の注意力には限界がある。これにはチームが必要だ。\n\ns15 Agent Teams → 一人の Agent では足りない、チームを組もう。永続的なチームメイト + 非同期受信箱。\n\n\n\n" }, { "version": "s15", "locale": "en", - "title": "s15: Agent Teams — Runtime Lab: Persistent Teammates", - "content": "# s15: Agent Teams — Runtime Lab: Persistent Teammates\n\ns01 → ... → s13 → s14 → `s15` → [s16](/en/s16) → s17 → s18 → s19 → s20 → s21 → s22\n> *\"One agent isn't enough, form a team\"* — File-based inboxes + teammate threads.\n>\n> **Harness Layer**: Teams — Multi-agent collaboration, message bus.\n\n> **Module 1 of 2:** s15 and s16 are two focused labs in one Agent Teams module. This lab builds the runtime; s16 adds typed coordination protocols without repeating the runtime.\n\n---\n\n## The Problem\n\n\"Refactor the entire backend\" touches auth, database layer, API routes, and tests. One agent working on API routes no longer has auth module details in context. The context window is limited, a single agent can't cover every module.\n\ns06's sub-agents are temps, called in for one job, then gone. Some tasks need teammates that can communicate and collaborate.\n\n---\n\n## The Solution\n\n![Agent Teams Overview](/course-assets/s15_agent_teams/agent-teams-overview.en.svg)\n\nTeaching code carries forward S14's capabilities (prompt assembly, task system, background execution, cron scheduling). To stay focused on the team mechanism, it omits full error recovery, memory, and skill systems. Added: **MessageBus** (file-based inboxes), **spawn_teammate_thread** (launch teammate threads), **inbox injection** (Lead receives teammate messages and injects into history).\n\nSub-agent vs Teammate:\n\n| | s06 Sub-agent | s15 Teammate |\n|---|---|---|\n| Lifetime | One-shot, destroyed after use | Multi-turn (teaching: 10 rounds; real CC: idle loop) |\n| Communication | Only returns conclusion | Async inbox, communicate anytime |\n| Context | Fully isolated | Shared via messages |\n| Count | One lead + occasional sub-agent | One Lead + multiple teammates |\n\n---\n\n## How It Works\n\n![Team Topology](/course-assets/s15_agent_teams/team-topology.en.svg)\n\n### MessageBus: File-Based Inboxes\n\nEach agent (including Lead and teammates) has a `.jsonl` inbox. Send = append a JSON line to the target's file. Read = read file + delete (consumption):\n\n```python\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str,\n content: str, msg_type: str = \"message\"):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time()}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()]\n inbox.unlink() # consume: read + delete\n return msgs\n```\n\nWhy files instead of in-memory queues? Teaching code uses files because they're intuitive and observable across threads. Real CC also uses file inboxes (`~/.claude/teams/{team}/inboxes/`) but adds `proper-lockfile` for concurrent write safety. The teaching version's `read_inbox` has a read + unlink race, concurrent reads could lose messages, acceptable for teaching purposes.\n\n### spawn_teammate_thread: Launching a Teammate\n\nLead calls the `spawn_teammate` tool to start a teammate. The teammate runs in its own daemon thread with its own system prompt, messages, and simplified tool set:\n\n```python\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n system = f\"You are '{name}', a {role}. Use tools to complete tasks.\"\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [bash, read_file, write_file, send_message]\n for _ in range(10): # max 10 rounds\n inbox = BUS.read_inbox(name)\n if inbox:\n messages.append({\"role\": \"user\",\n \"content\": f\"{json.dumps(inbox)}\"})\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n # ... execute tools, process results\n # Send final summary to Lead\n BUS.send(name, \"lead\", summary, \"result\")\n\n threading.Thread(target=run, daemon=True).start()\n```\n\nKey design:\n- **Simplified tool set**: bash, read, write, send_message. Teaching code omits tasks and cron to focus on communication. Real CC teammates also have TaskCreate, TaskUpdate, etc., the task system is shared across the team\n- **Teaching: 10 rounds max**: prevents infinite loops. Real CC uses idle loop: after each round, send `idle_notification`, wait for inbox messages, resume on arrival, exit only on `shutdown_request`\n- **Auto-report on completion**: `BUS.send(name, \"lead\", summary)` sends the final result to Lead's inbox\n\n### Lead's Inbox Injection\n\nLead checks inbox after each main loop iteration. Teammate messages are injected into history so the LLM can see and react to them:\n\n```python\n# After main loop iteration\ninbox = BUS.read_inbox(\"lead\")\nif inbox:\n inbox_text = \"\\n\".join(\n f\"From {m['from']}: {m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n```\n\nTeaching code injects in the user input loop. Real CC is more refined, Lead's `useInboxPoller` checks every 1 second, submitting messages as new turns without waiting for user input.\n\n### Permission Bubbling\n\nTeaching code omits permission bubbling. Real CC's flow (`permissionSync.ts`, `useSwarmPermissionPoller.ts`):\n\n1. Teammate encounters an operation needing approval → sends `permission_request` to Lead's inbox\n2. Lead's `useInboxPoller` detects the request → routes to approval queue\n3. User approves → Lead sends `permission_response` back to teammate\n4. Teammate's `useSwarmPermissionPoller` (polls every 500ms) receives reply → continue or reject\n\n### Putting It Together\n\n```\n1. Lead: \"Build the backend: one agent isn't enough, form a team\"\n2. Lead → spawn_teammate(\"alice\", \"backend dev\", \"Create database schema\")\n3. Lead → spawn_teammate(\"bob\", \"frontend dev\", \"Write API client\")\n4. Alice thread starts → her own LLM call → bash \"python manage.py migrate\"\n5. Bob thread starts → his own LLM call → write_file(\"client.ts\", ...)\n6. Alice done → BUS.send(\"alice\", \"lead\", \"Schema done: users, orders tables\")\n7. Bob done → BUS.send(\"bob\", \"lead\", \"Client written with types\")\n8. Lead next iteration → inbox injected into history → LLM sees both results\n```\n\nTwo teammates work in parallel.\n\n---\n\n## Changes from s14\n\n| Component | Before (s14) | After (s15) |\n|-----------|-------------|-------------|\n| Agent count | 1 | 1 Lead + N teammate threads |\n| Communication | None | MessageBus + .mailboxes/*.jsonl |\n| New classes | — | MessageBus, active_teammates dict |\n| New functions | — | spawn_teammate_thread, run_send_message, run_check_inbox |\n| Lead tools | 11 (s14) | + spawn_teammate, send_message, check_inbox (14) |\n| Teammate tools | — | bash, read_file, write_file, send_message (4) |\n| Permissions | Local decisions | Teaching code omits (real CC has bubbling) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s15_agent_teams/code.py\n```\n\nTry these prompts:\n\n1. `Spawn alice as a backend developer. Ask her to create a file called schema.sql with a users table.`\n2. `Check your inbox for alice's result.`\n3. `Spawn bob as a tester. Ask him to check if schema.sql exists and list its contents.`\n\nWhat to observe: How does Lead spawn teammates? What do the `.mailboxes/` JSONL files look like? After teammates finish, is Lead's inbox injected into history?\n\n---\n\n## What's Next\n\nTeammates can work and communicate. But if Lead wants Alice to shut down, killing the thread outright could leave half-written files. A graceful shutdown protocol is needed: Lead sends shutdown_request, teammate wraps up and exits.\n\ns16 Agent Teams Protocol Lab → keep this runtime and add shutdown handshakes, plan approval, and typed request-reply messages.\n\n
\nDeep Dive into CC Source\n\n> The following is a complete analysis based on CC source code `spawnMultiAgent.ts`, `useInboxPoller.ts` (969 lines), `useSwarmPermissionPoller.ts` (330 lines), `teammateMailbox.ts`, `teamHelpers.ts`.\n\n### 1. No Central Message Bus, It's the Filesystem\n\nTeaching code uses a `MessageBus` class to send and receive messages. Real CC is more direct, each agent writes directly to other agents' inbox files.\n\nInbox path: `~/.claude/teams/{teamName}/inboxes/{agentName}.json`\n\nWrites use `proper-lockfile` for concurrent write safety (up to 10 retries). Each file is a JSON array; appending reads → appends → writes back.\n\n### 2. 15 Message Types\n\nCC team communication has 15 structured message types (`teammateMailbox.ts`):\n\n| Type | Direction | Purpose |\n|------|-----------|---------|\n| `plain text` | Both ways | Normal inter-teammate communication |\n| `idle_notification` | Teammate→Lead | Teammate finished a turn, now idle |\n| `permission_request` | Teammate→Lead | Teammate needs operation approval |\n| `permission_response` | Lead→Teammate | Lead's approval result |\n| `plan_approval_request` | Teammate→Lead | Teammate submits plan for review |\n| `plan_approval_response` | Lead→Teammate | Lead's plan review |\n| `shutdown_request` | Lead→Teammate | Request graceful shutdown |\n| `shutdown_approved` | Teammate→Lead | Confirm shutdown |\n| `shutdown_rejected` | Teammate→Lead | Reject shutdown (with reason) |\n| `task_assignment` | Lead→Teammate | Assign a task |\n| `team_permission_update` | Lead→Teammate | Broadcast permission changes |\n| `mode_set_request` | Lead→Teammate | Change teammate's permission mode |\n| `sandbox_permission_*` | Both ways | Network permission request/reply |\n| `teammate_terminated` | System | Teammate removed notification |\n\nText messages are wrapped in `` XML tags for delivery to the model.\n\n### 3. Permission Bubbling: Bidirectional Polling\n\nTeaching code omits permission bubbling. Real CC's flow (`permissionSync.ts`):\n\n1. **Teammate** encounters operation needing approval → sends `permission_request` to Lead's inbox\n2. **Lead's** `useInboxPoller` (polls every 1s) detects request → routes to `ToolUseConfirmQueue`\n3. Lead's UI shows approval dialog with teammate name and color\n4. User approves → Lead sends `permission_response` back to teammate's inbox\n5. **Teammate's** `useSwarmPermissionPoller` (polls every 500ms) receives reply → continue or reject\n\n### 4. Teammate Lifecycle\n\nCC teammates are created by `spawnTeammate()` (`spawnMultiAgent.ts`):\n\n1. **Spawn**: Create tmux pane (or in-process), assign color, write team config\n2. **Work**: `useInboxPoller` checks inbox every 1s → submit as new turn when messages arrive\n3. **Idle**: Stop hook fires → send `idle_notification` to Lead\n4. **Shutdown**: Lead sends `shutdown_request` → teammate replies `shutdown_approved` → Lead cleans up\n\n### 5. Team Config\n\nTeam registry at `~/.claude/teams/{teamName}/config.json` (`teamHelpers.ts`):\n\n```json\n{\n \"name\": \"my-team\",\n \"leadAgentId\": \"lead@my-team\",\n \"members\": [{\n \"agentId\": \"researcher@my-team\",\n \"name\": \"researcher\",\n \"agentType\": \"general-purpose\",\n \"color\": \"blue\",\n \"isActive\": true\n }]\n}\n```\n\nTeammates cannot be nested (`AgentTool.tsx:273` explicitly forbids \"teammates spawning other teammates\").\n\n
\n\n\n" + "title": "s15: Agent Teams — Runtime and Coordination Protocols", + "content": "# s15: Agent Teams — Runtime and Coordination Protocols\n\ns01 → ... → s13 → s14 → `s15` → [s16](/en/s16) → s17 → s18 → s19 → s20 → s21\n\n> *\"When one agent cannot hold the whole job, let teammates divide the work.\"* — Persistent teammates, message delivery, and coordination protocols.\n>\n> **Harness layer**: Team — how multiple agents work in parallel without losing control.\n\n---\n\n## The Problem\n\nSuppose we ask an agent to refactor an entire backend. The work may cover configuration loading, authentication, and tests. One agent can process those areas sequentially, but it takes longer and earlier details gradually leave its context.\n\nThis is a good candidate for parallel work, yet users normally describe the goal rather than design the team:\n\n```text\nRefactor this sample backend. Clean up configuration loading,\nauthentication, and tests, preserve the existing interfaces,\nand make sure the tests pass.\n```\n\nThe harness therefore has to solve four connected problems:\n\n1. Who decides that parallel work is useful, and who confirms the extra agents?\n2. How does each teammate keep its identity and context across assignments?\n3. How do results return to Lead automatically, without asking the model to poll an inbox?\n4. How do shutdown and plan approval become traceable, enforceable protocols?\n\n---\n\n## The Solution\n\n![Agent Teams Overview](/course-assets/s15_agent_teams/agent-teams-overview.en.svg)\n\ns15 adds a Lead-managed team runtime around the single-agent harness:\n\n- **Lead** owns the user conversation, proposes a division of work, and waits for confirmation.\n- **Teammates** run independent agent loops in background threads and become idle after an assignment.\n- **MessageBus** carries ordinary messages, results, and control events through file-backed mailboxes.\n- **Runtime delivery** consumes Lead's mailbox and injects team events into the next turn.\n- **Coordination protocols** use `type`, `request_id`, and state transitions for shutdown and plan approval.\n- **A plan gate** blocks teammate `bash` and `write_file` calls until a required plan is approved.\n\nThe model understands tasks and chooses a useful division of work. Code owns delivery, lifecycle, and protocol constraints.\n\n---\n\n## How It Works\n\n### 1. Lead proposes a team and waits for confirmation\n\nStarting teammates changes cost, concurrency, and the set of actors that may edit the workspace. That boundary should not be hidden inside an ordinary tool call. Lead's system prompt says:\n\n```python\n\"When parallel work would help, first propose a small team with clear \"\n\"responsibilities and wait for the user's confirmation. Do not call \"\n\"spawn_teammate before the user confirms.\"\n```\n\nFor the first request, Lead only proposes a split:\n\n```text\nI suggest three parallel areas:\n- config: clean up configuration loading\n- auth: refactor authentication\n- tests: add regression coverage\n\nI will start the teammates after you confirm.\n```\n\nAfter the user says \"Go ahead,\" Lead can call `spawn_teammate`. The user states the goal, Lead designs the team, and the user confirms the execution boundary.\n\n### 2. Every teammate owns an independent loop\n\nAn s06 subagent is a one-shot call. A teammate is a persistent execution unit:\n\n| | s06 Subagent | s15 Teammate |\n|---|---|---|\n| Lifecycle | Ends after one call | `WORK → IDLE → WORK` until shutdown |\n| Context | Exists for one task | Persists across assignments |\n| Communication | Returns one result | Receives messages and emits events |\n| Coordination | One-way delegation | Two-way collaboration with Lead |\n\n`spawn_teammate_thread()` gives each teammate its own system prompt, messages, and tools, then runs its loop in a daemon thread. Lead can keep coordinating while teammates work.\n\n### 3. MessageBus keeps communication outside model context\n\nLead and teammates cannot share one messages array. Otherwise one teammate's tool results would leak into another teammate's reasoning. `MessageBus` gives each agent a `.mailboxes/.jsonl` inbox:\n\n```python\nclass MessageBus:\n def send(self, from_agent, to_agent, content,\n msg_type=\"message\", metadata=None):\n msg = {\n \"from\": from_agent,\n \"to\": to_agent,\n \"content\": content,\n \"type\": msg_type,\n \"metadata\": metadata or {},\n }\n with self._changed:\n append_jsonl(self._path(to_agent), msg)\n self._changed.notify_all()\n\n def wait_for_messages(self, agent):\n with self._changed:\n while not self.peek(agent):\n self._changed.wait()\n return self._read_unlocked(agent)\n```\n\nA lock protects mailbox files from concurrent teammate access. A `Condition` lets idle teammates sleep until an event arrives instead of polling continuously.\n\n### 4. The runtime delivers inbox events automatically\n\n`read_inbox()` consumes messages by reading and deleting the mailbox file, so Lead keeps a single consumer, `consume_lead_inbox()`:\n\n```python\ndef consume_lead_inbox():\n messages = BUS.read_inbox(\"lead\")\n for message in messages:\n if message[\"type\"].endswith(\"_response\"):\n match_response(...)\n return messages\n```\n\nAn event thread beside the main loop wakes Lead when a new message arrives:\n\n```text\nMessageBus → consume_lead_inbox\n → update protocol state\n → inject [Team events] into history\n → start another Lead turn\n```\n\n`check_inbox` is not a model tool. Message arrival belongs to the runtime; the model only handles events that have already been delivered into its context.\n\n### 5. Result and idle are separate events\n\nWhen a teammate finishes one assignment, the runtime sends two events in order:\n\n```text\nresult: \"Authentication refactored; related tests pass.\"\nidle_notification: \"Waiting for more work.\"\n```\n\n`result` answers \"What did this assignment produce?\" `idle_notification` answers \"Can this teammate accept more work?\" A single vague \"done\" cannot represent both facts.\n\nAn idle teammate does not exit. An ordinary message returns it to WORK; a `shutdown_request` starts a graceful shutdown handshake.\n\n### 6. Control messages use types and request IDs\n\nFree-form text is fine for ordinary collaboration, but shutdown and approval should not depend on guessing intent. They use structured messages:\n\n![Team Protocols](/course-assets/s15_agent_teams/team-protocols-overview.en.svg)\n\n```python\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n\n\npending_requests: dict[str, ProtocolState] = {}\n```\n\nThe shutdown path is:\n\n```text\nLead creates a pending shutdown request\n → shutdown_request(request_id) enters the teammate inbox\n → the teammate finishes its current step\n → shutdown_response(request_id) returns to Lead\n → request_id locates the original request\n → pending becomes approved and the teammate loop exits\n```\n\nThe ID correlates one reply with one request, the type prevents a mismatched reply from changing state, and the status prevents duplicate responses from being applied twice.\n\n### 7. Plan approval constrains execution\n\nThe plan protocol runs in the opposite direction:\n\n```text\nLead → plan_request\nteammate → plan_approval_request(request_id, plan)\nLead → plan_approval_response(request_id, approve, feedback)\n```\n\nMerely telling a teammate to wait is not a reliable gate, so tool dispatch checks the plan state:\n\n```python\ndef _run_teammate_tool(name, block, handlers):\n gate = plan_gates.get(name, \"not_required\")\n if block.name in {\"bash\", \"write_file\"} and gate not in {\n \"not_required\", \"approved\"\n }:\n return f\"Blocked: plan status is {gate}.\"\n return handlers[block.name](**block.input)\n```\n\nWhile the state is `required`, `pending`, or `rejected`, the teammate can read files and submit or revise a plan, but it cannot run Shell commands or write files. The tools are released only after an approval response changes the state to `approved`.\n\n---\n\n## One Complete Run\n\n```text\ns15 >> Refactor this sample backend. Clean up configuration loading,\n authentication, and tests, preserve existing interfaces,\n and make sure the tests pass.\n\nLead: I suggest config, auth, and tests as three parallel areas.\n Shall I start the team?\n\ns15 >> Go ahead.\n\n[teammate] config spawned\n[teammate] auth spawned\n[teammate] tests spawned\n[bus] auth → lead (result) ...\n[bus] auth → lead (idle_notification) ...\n[wake: 2 team events → new turn]\nLead: I received the authentication result and will coordinate the rest.\n```\n\nThe terminal exposes the user request, Lead's split, teammate startup, messages, results, idle transitions, and shutdown events. The user does not have to name a Lead or ask it to check an inbox.\n\n---\n\n## What Changed from s14\n\n| Component | s14 | s15 |\n|---|---|---|\n| Agents | One agent | One Lead plus persistent teammates |\n| User flow | Execute the request | Propose a team, then confirm startup |\n| Communication | None | File mailboxes plus automatic delivery |\n| Lifecycle | One loop | Teammate `WORK / IDLE / shutdown` |\n| Reporting | Current agent output | Separate `result` and `idle_notification` |\n| Control | None | Shutdown and plan approval protocols |\n| Enforcement | No team constraint | Required plans gate mutating tools |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s15_agent_teams/code.py\n```\n\nStart with an ordinary request:\n\n```text\nRefactor this sample backend. Clean up configuration loading,\nauthentication, and tests, preserve the existing interfaces,\nand make sure the tests pass.\n```\n\nAfter Lead proposes the team, reply:\n\n```text\nGo ahead.\n```\n\nWatch for `spawned`, `result`, `idle_notification`, `plan_approval_*`, and `shutdown_*` events, along with mailbox files appearing and being consumed under `.mailboxes/`.\n\n---\n\n## Next\n\nIn s15, Lead still assigns each teammate explicitly. The next lesson gives idle teammates access to the shared task board so they can discover and claim ready work themselves.\n\nNext: [s16 Autonomous Agents](/en/s16).\n\n\n" }, { "version": "s15", "locale": "zh", - "title": "s15: Agent Teams — 运行时实验:持久队友", - "content": "# s15: Agent Teams — 运行时实验:持久队友\n\ns01 → ... → s13 → s14 → `s15` → [s16](/zh/s16) → s17 → s18 → s19 → s20 → s21 → s22\n> *\"一个搞不定, 组队来\"* — 文件收件箱 + 队友线程。\n>\n> **Harness 层**: 团队 — 多 Agent 协作, 消息总线。\n\n> **模块 1/2:** s15 与 s16 是同一个 Agent Teams 模块中的两次聚焦实验。本章搭建运行时;s16 在不重复运行时的前提下增加带类型的协作协议。\n\n---\n\n## 问题\n\n\"重构整个后端\"涉及认证模块、数据库层、API 路由、测试。一个 Agent 在修 API 路由时,认证模块的细节已经不在上下文里了。上下文窗口就那么大,单个 Agent 的注意力覆盖不了所有模块。\n\ns06 的子 Agent 是临时工,叫来干一件事就走了。但有些任务需要能通信、能协作的队友。\n\n---\n\n## 解决方案\n\n![Agent Teams Overview](/course-assets/s15_agent_teams/agent-teams-overview.svg)\n\n教学代码沿用 S14 的能力(prompt 组装、任务系统、后台执行、cron 调度)。为了聚焦团队机制,省略了完整错误恢复、记忆和技能系统。新增三样:**MessageBus**(文件收件箱)、**spawn_teammate_thread**(启动队友线程)、**inbox 注入**(Lead 接收队友消息并注入 history)。\n\n子 Agent vs 队友:\n\n| | s06 子 Agent | s15 队友 |\n|---|---|---|\n| 生命周期 | 一次性,用完销毁 | 多轮(教学版限 10 轮,真实 CC 用 idle loop) |\n| 通信 | 只回传结论 | 异步收件箱,随时通信 |\n| 上下文 | 完全隔离 | 通过消息共享信息 |\n| 数量 | 一个主 Agent + 偶尔子 Agent | 一个 Lead + 多个队友 |\n\n---\n\n## 工作原理\n\n![Team Topology](/course-assets/s15_agent_teams/team-topology.svg)\n\n### MessageBus: 文件收件箱\n\n每个 Agent(包括 Lead 和队友)有一个 `.jsonl` 邮箱。发消息 = 往对方的文件里 append 一行 JSON。读消息 = 读文件 + 删除(消费式):\n\n```python\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str,\n content: str, msg_type: str = \"message\"):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time()}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()]\n inbox.unlink() # 消费式:读完删除\n return msgs\n```\n\n为什么用文件而不是内存队列?教学版选文件是因为直观、跨线程可观察。真实 CC 也用文件收件箱(`~/.claude/teams/{team}/inboxes/`),但加了 `proper-lockfile` 防并发写冲突。教学版的 `read_inbox` 有 read + unlink 竞态,多线程同时读可能丢消息,对教学场景可以接受。\n\n### spawn_teammate_thread: 启动队友\n\nLead 调用 `spawn_teammate` 工具启动一个队友。队友跑在自己的 daemon 线程里,有自己的 system prompt、自己的 messages、自己的简化工具集:\n\n```python\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n system = f\"You are '{name}', a {role}. Use tools to complete tasks.\"\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [bash, read_file, write_file, send_message]\n for _ in range(10): # 最多 10 轮\n inbox = BUS.read_inbox(name)\n if inbox:\n messages.append({\"role\": \"user\",\n \"content\": f\"{json.dumps(inbox)}\"})\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n # ... 执行工具、处理结果\n # 完成后发 summary 给 Lead\n BUS.send(name, \"lead\", summary, \"result\")\n\n threading.Thread(target=run, daemon=True).start()\n```\n\n关键设计:\n- **队友有简化工具集**:bash、read、write、send_message。教学版省略了任务和 cron,聚焦通信机制。真实 CC 的队友也有 TaskCreate、TaskUpdate 等工具,任务系统是团队共享的\n- **教学版限 10 轮**:防止队友无限循环。真实 CC 用 idle loop:跑完一轮后发 `idle_notification`,等 inbox 消息,收到后继续,直到 `shutdown_request` 才退出\n- **完成后自动汇报**:`BUS.send(name, \"lead\", summary)` 把最终结果发到 Lead 的收件箱\n\n### Lead 的 inbox 注入\n\nLead 在每轮主循环结束后检查收件箱。队友发来的消息注入到 history 里,让 LLM 能看到并做出反应:\n\n```python\n# 主循环结束后\ninbox = BUS.read_inbox(\"lead\")\nif inbox:\n inbox_text = \"\\n\".join(\n f\"From {m['from']}: {m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n```\n\n教学版在用户输入循环外注入。CC 更精细,Lead 的 `useInboxPoller` 每 1 秒检查一次,有消息就提交为新的 turn,不需要等用户输入。\n\n### 权限冒泡\n\n教学版省略了权限冒泡。真实 CC 的流程(`permissionSync.ts`、`useSwarmPermissionPoller.ts`):\n\n1. 队友遇到需要审批的操作 → 发 `permission_request` 到 Lead 收件箱\n2. Lead 的 `useInboxPoller` 检测到请求 → 路由到审批队列\n3. 用户审批后 → Lead 发 `permission_response` 回队友\n4. 队友的 `useSwarmPermissionPoller`(每 500ms 轮询)收到回复 → 继续或拒绝\n\n### 合起来跑\n\n```\n1. Lead: \"搭建后端:一个人搞不定,组队吧\"\n2. Lead → spawn_teammate(\"alice\", \"backend dev\", \"创建数据库 schema\")\n3. Lead → spawn_teammate(\"bob\", \"frontend dev\", \"写 API 客户端\")\n4. alice 线程启动 → 自己的 LLM 调用 → bash \"python manage.py migrate\"\n5. bob 线程启动 → 自己的 LLM 调用 → write_file(\"client.ts\", ...)\n6. alice 完成 → BUS.send(\"alice\", \"lead\", \"Schema done: users, orders tables\")\n7. bob 完成 → BUS.send(\"bob\", \"lead\", \"Client written with types\")\n8. Lead 下次循环 → inbox 注入 history → LLM 看到 alice 和 bob 的结果\n```\n\n两个队友并行工作。\n\n---\n\n## 相对 s14 的变更\n\n| 组件 | 之前 (s14) | 之后 (s15) |\n|------|-----------|-----------|\n| Agent 数量 | 1 | 1 Lead + N 队友线程 |\n| 通信 | 无 | MessageBus + .mailboxes/*.jsonl |\n| 新类 | — | MessageBus, active_teammates dict |\n| 新函数 | — | spawn_teammate_thread, run_send_message, run_check_inbox |\n| Lead 工具 | 11 (s14) | + spawn_teammate, send_message, check_inbox (14) |\n| 队友工具 | — | bash, read_file, write_file, send_message (4) |\n| 权限 | 本地决策 | 教学版省略(真实 CC 有冒泡机制) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s15_agent_teams/code.py\n```\n\n试试这些 prompt:\n\n1. `Spawn alice as a backend developer. Ask her to create a file called schema.sql with a users table.`\n2. `Check your inbox for alice's result.`\n3. `Spawn bob as a tester. Ask him to check if schema.sql exists and list its contents.`\n\n观察重点:Lead 如何启动队友?`.mailboxes/` 目录下的 JSONL 文件长什么样?队友完成后 Lead 的 inbox 有没有注入到 history?\n\n---\n\n## 接下来\n\n队友能干活、能通信。但如果 Lead 想让 Alice 关机,直接杀线程会留下写到一半的文件。需要一个体面的关机协议:Lead 发 shutdown_request,队友收尾后退出。\n\ns16 Agent Teams 协议实验 → 沿用本章运行时,加入关机握手、计划审批与带类型的请求-回复消息。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `spawnMultiAgent.ts`、`useInboxPoller.ts`(969 行)、`useSwarmPermissionPoller.ts`(330 行)、`teammateMailbox.ts`、`teamHelpers.ts` 的完整分析。\n\n### 一、没有中央消息总线,是文件系统\n\n教学版用 `MessageBus` 类收发消息。CC 的做法更直接,每个 Agent 直接写其他 Agent 的收件箱文件。\n\n收件箱路径:`~/.claude/teams/{teamName}/inboxes/{agentName}.json`\n\n写入时用 `proper-lockfile` 文件锁保证并发安全(最多重试 10 次)。每个文件是一个 JSON 数组,append 新消息时读→追加→写回。\n\n### 二、15 种消息类型\n\nCC 的团队通信有 15 种结构化消息(`teammateMailbox.ts`):\n\n| 类型 | 方向 | 用途 |\n|------|------|------|\n| `plain text` | 双向 | 普通队友间通信 |\n| `idle_notification` | 队友→Lead | 队友完成一轮工作,进入空闲 |\n| `permission_request` | 队友→Lead | 队友需要操作审批 |\n| `permission_response` | Lead→队友 | Lead 审批结果 |\n| `plan_approval_request` | 队友→Lead | 队友提交计划待审 |\n| `plan_approval_response` | Lead→队友 | Lead 审批计划 |\n| `shutdown_request` | Lead→队友 | 请求体面关机 |\n| `shutdown_approved` | 队友→Lead | 确认关机 |\n| `shutdown_rejected` | 队友→Lead | 拒绝关机(附原因) |\n| `task_assignment` | Lead→队友 | 分配任务 |\n| `team_permission_update` | Lead→队友 | 广播权限变更 |\n| `mode_set_request` | Lead→队友 | 修改队友的权限模式 |\n| `sandbox_permission_*` | 双向 | 网络权限请求/回复 |\n| `teammate_terminated` | 系统 | 队友被移除通知 |\n\n文本消息被包装在 `` XML 标签中交付给模型。\n\n### 三、权限冒泡:双向轮询\n\n教学版省略了权限冒泡。CC 的实际流程(`permissionSync.ts`):\n\n1. **队友**遇到需要审批的操作 → 发 `permission_request` 到 Lead 的收件箱\n2. **Lead** 的 `useInboxPoller`(每 1 秒轮询)检测到请求 → 路由到 `ToolUseConfirmQueue`\n3. Lead 的 UI 显示审批对话框,带队友名字和颜色\n4. 用户审批后 → Lead 发 `permission_response` 回队友的收件箱\n5. **队友**的 `useSwarmPermissionPoller`(每 500ms 轮询)收到回复 → 继续或拒绝执行\n\n### 四、队友生命周期\n\nCC 的队友由 `spawnTeammate()`(`spawnMultiAgent.ts`)创建:\n\n1. **Spawn**:创建 tmux 窗格(或进程内),分配颜色,写入 team config\n2. **Work**:`useInboxPoller` 每 1 秒检查收件箱 → 有消息就提交为新的 turn\n3. **Idle**:Stop hook 触发 → 发 `idle_notification` 给 Lead\n4. **Shutdown**:Lead 发 `shutdown_request` → 队友回复 `shutdown_approved` → Lead 清理\n\n### 五、Team Config\n\n团队注册表在 `~/.claude/teams/{teamName}/config.json`(`teamHelpers.ts`):\n\n```json\n{\n \"name\": \"my-team\",\n \"leadAgentId\": \"lead@my-team\",\n \"members\": [{\n \"agentId\": \"researcher@my-team\",\n \"name\": \"researcher\",\n \"agentType\": \"general-purpose\",\n \"color\": \"blue\",\n \"isActive\": true\n }]\n}\n```\n\n队友之间不能嵌套(`AgentTool.tsx:273` 明确禁止 \"teammates spawning other teammates\")。\n\n
\n\n\n" + "title": "s15: Agent Teams — 团队运行时与协作协议", + "content": "# s15: Agent Teams — 团队运行时与协作协议\n\ns01 → ... → s13 → s14 → `s15` → [s16](/zh/s16) → s17 → s18 → s19 → s20 → s21\n\n> *\"一个 Agent 顾不过来,就让队友分工协作。\"* — 持久队友、消息投递与协作协议。\n>\n> **Harness 层**:团队 — 多个 Agent 如何并行工作,又如何保持可控。\n\n---\n\n## 问题\n\n当我们需要 Agent 帮助我们重构整个后端时,任务可能同时涉及配置加载、认证逻辑和测试。一个 Agent 依次处理所有模块,不但耗时更长,早期细节也会逐渐退出上下文。\n\n这类任务适合拆给多个 Agent,但用户通常只会描述需求,不会先设计一套团队:\n\n```text\n请重构这个示例后端,分别整理配置加载、认证逻辑和测试,\n保持现有接口兼容,并确保测试通过。\n```\n\n因此,Harness 需要解决的不只是“再启动几个 Agent”,而是四个连续问题:\n\n1. 谁判断任务是否值得并行,以及如何征得用户确认?\n2. 队友如何保留自己的身份和上下文,持续接收工作?\n3. 队友的结果如何自动回到 Lead,而不是依赖模型反复检查邮箱?\n4. 关机与计划审批如何变成可追踪、可执行的协议?\n\n---\n\n## 解决方案\n\n![Agent Teams Overview](/course-assets/s15_agent_teams/agent-teams-overview.svg)\n\ns15 在单 Agent Harness 外增加一个由 Lead 管理的团队运行时:\n\n- **Lead** 保持用户对话,判断是否需要团队,提出分工并等待确认。\n- **队友** 在独立线程中运行自己的 Agent Loop,完成工作后进入空闲。\n- **MessageBus** 用文件邮箱传递普通消息、结果和控制事件。\n- **运行时投递** 自动消费 Lead 的邮箱,把团队事件注入下一轮上下文。\n- **协作协议** 用 `type`、`request_id` 和状态机处理关机与计划审批。\n- **计划闸门** 在计划未批准时拦截队友的 `bash` 和 `write_file`。\n\n模型负责理解任务与分工,代码负责消息投递、生命周期和协议约束。\n\n---\n\n## 工作原理\n\n### 1. Lead 先提出团队,再等待用户确认\n\n是否创建团队会改变成本、并发度和可写入范围,不应该被隐藏在一次普通工具调用里。Lead 的 system prompt 明确规定:\n\n```python\n\"When parallel work would help, first propose a small team with clear \"\n\"responsibilities and wait for the user's confirmation. Do not call \"\n\"spawn_teammate before the user confirms.\"\n```\n\n第一次输入需求时,Lead 只需要说明建议的拆分:\n\n```text\n我建议分成三个方向并行处理:\n- config:整理配置加载\n- auth:重构认证逻辑\n- tests:补齐回归测试\n\n确认后我会启动队友并协调结果。\n```\n\n用户回复“开始吧”后,Lead 才调用 `spawn_teammate`。用户表达目标,Lead 设计团队,用户确认执行边界;三者的职责不会混在一起。\n\n### 2. 每个队友拥有独立循环\n\ns06 的子 Agent 是一次性调用,返回结果后就结束。队友则是持久执行单元:\n\n| | s06 子 Agent | s15 队友 |\n|---|---|---|\n| 生命周期 | 完成一次调用后结束 | `WORK → IDLE → WORK`,直到收到关机请求 |\n| 上下文 | 只服务当前任务 | 在多轮协作中保留 |\n| 通信 | 返回一次结果 | 持续接收消息并上报事件 |\n| 协调 | 主 Agent 单向委派 | Lead 与队友双向协作 |\n\n`spawn_teammate_thread()` 为队友创建独立的 system prompt、messages 和工具集,并把循环放入 daemon 线程。Lead 不必等待某个队友结束,仍可继续派发任务或处理其他结果。\n\n### 3. MessageBus 把通信放在上下文之外\n\nLead 和队友不能共享同一份 messages,否则一个队友的工具结果会混入另一个队友的推理。`MessageBus` 为每个 Agent 建立 `.mailboxes/.jsonl`:\n\n```python\nclass MessageBus:\n def send(self, from_agent, to_agent, content,\n msg_type=\"message\", metadata=None):\n msg = {\n \"from\": from_agent,\n \"to\": to_agent,\n \"content\": content,\n \"type\": msg_type,\n \"metadata\": metadata or {},\n }\n with self._changed:\n append_jsonl(self._path(to_agent), msg)\n self._changed.notify_all()\n\n def wait_for_messages(self, agent):\n with self._changed:\n while not self.peek(agent):\n self._changed.wait()\n return self._read_unlocked(agent)\n```\n\n锁保证同一进程中的多个队友不会同时破坏邮箱文件,`Condition` 让空闲队友等待事件,而不是持续轮询。\n\n### 4. 收件箱由运行时自动投递\n\n`read_inbox()` 是消费式读取:读出后删除邮箱文件。因此,Lead 只保留一个消费入口 `consume_lead_inbox()`:\n\n```python\ndef consume_lead_inbox():\n messages = BUS.read_inbox(\"lead\")\n for message in messages:\n if message[\"type\"].endswith(\"_response\"):\n match_response(...)\n return messages\n```\n\n主循环旁的事件线程发现新消息后,会唤醒 Lead:\n\n```text\nMessageBus → consume_lead_inbox\n → 更新协议状态\n → [Team events] 注入 history\n → Lead 开始新一轮\n```\n\n`check_inbox` 不再是模型工具。消息何时到达属于运行时职责;模型只需要处理已经送入上下文的事件。\n\n### 5. 结果与空闲是两个不同事件\n\n队友完成一项工作时,运行时依次发送:\n\n```text\nresult: \"认证逻辑已重构,相关测试通过。\"\nidle_notification: \"Waiting for more work.\"\n```\n\n`result` 回答“这次工作产出了什么”,`idle_notification` 表示“这个队友现在可以接新任务”。如果把两者合成一个模糊的“done”,Lead 就无法区分任务结果和资源状态。\n\n队友进入 IDLE 后不会退出。新普通消息会让它回到 WORK;`shutdown_request` 则让它完成关机握手并结束线程。\n\n### 6. 控制消息使用类型和 request_id\n\n普通消息可以交给模型理解,关机和审批不能依赖自由文本猜测。它们使用结构化消息:\n\n![Team Protocols](/course-assets/s15_agent_teams/team-protocols-overview.svg)\n\n```python\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n\n\npending_requests: dict[str, ProtocolState] = {}\n```\n\n关机协议的完整路径是:\n\n```text\nLead 创建 shutdown 请求,状态为 pending\n → shutdown_request(request_id) 发给队友\n → 队友完成当前步骤并回复 shutdown_response(request_id)\n → Lead 用 request_id 找到原请求\n → pending 变为 approved,队友线程退出\n```\n\n`request_id` 负责关联请求与回复,`type` 防止错误类型的回复修改状态,`status` 防止重复响应被再次处理。\n\n### 7. 计划审批不仅传消息,还约束执行\n\n计划协议沿相反方向流动:\n\n```text\nLead → plan_request\n队友 → plan_approval_request(request_id, plan)\nLead → plan_approval_response(request_id, approve, feedback)\n```\n\n只告诉队友“请等待批准”并不可靠,所以工具分发器检查计划状态:\n\n```python\ndef _run_teammate_tool(name, block, handlers):\n gate = plan_gates.get(name, \"not_required\")\n if block.name in {\"bash\", \"write_file\"} and gate not in {\n \"not_required\", \"approved\"\n }:\n return f\"Blocked: plan status is {gate}.\"\n return handlers[block.name](**block.input)\n```\n\n当状态为 `required`、`pending` 或 `rejected` 时,队友仍可读取文件、提交或修改计划,但不能执行 Shell 或写文件。批准消息到达后,状态变为 `approved`,工具才会放行。\n\n---\n\n## 一次完整运行\n\n```text\ns15 >> 请重构这个示例后端,分别整理配置加载、认证逻辑和测试,\n 保持现有接口兼容,并确保测试通过。\n\nLead: 建议由 config、auth、tests 三个方向并行处理,是否开始?\n\ns15 >> 开始吧\n\n[teammate] config spawned\n[teammate] auth spawned\n[teammate] tests spawned\n[bus] auth → lead (result) ...\n[bus] auth → lead (idle_notification) ...\n[wake: 2 team events → new turn]\nLead: 已收到认证部分结果,继续等待并协调其他队友。\n```\n\n终端中显示的是用户需求、Lead 分工、队友启动、消息流、结果、空闲和关机事件。用户不需要在提示词里指定谁是 Lead,也不需要手动要求检查邮箱。\n\n---\n\n## 相对 s14 的变化\n\n| 组件 | s14 | s15 |\n|---|---|---|\n| Agent 数量 | 一个 Agent | 一个 Lead + 多个持久队友 |\n| 用户交互 | 直接执行任务 | 先提出团队方案,再确认启动 |\n| 通信 | 无 | 文件邮箱 + 自动事件投递 |\n| 生命周期 | 单循环 | 队友 `WORK / IDLE / shutdown` |\n| 结果上报 | 当前 Agent 输出 | `result` 与 `idle_notification` 分离 |\n| 控制协议 | 无 | 关机与计划审批 |\n| 执行约束 | 无团队约束 | 未批准计划会拦截写入类工具 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s15_agent_teams/code.py\n```\n\n先输入一个自然需求:\n\n```text\n请重构这个示例后端,分别整理配置加载、认证逻辑和测试,\n保持现有接口兼容,并确保测试通过。\n```\n\n看到 Lead 给出分工后,再回复:\n\n```text\n开始吧\n```\n\n观察终端中的 `spawned`、`result`、`idle_notification`、`plan_approval_*` 和 `shutdown_*` 事件,以及 `.mailboxes/` 中消息写入和消费的过程。\n\n---\n\n## 接下来\n\ns15 中,Lead 仍然要明确告诉每个队友做什么。下一章把共享任务看板交给空闲队友,让它们自己发现并认领可执行任务。\n\n下一章:[s16 Autonomous Agents](/zh/s16)。\n\n\n" }, { "version": "s15", "locale": "ja", - "title": "s15: Agent Teams — ランタイム実験:永続チームメイト", - "content": "# s15: Agent Teams — ランタイム実験:永続チームメイト\n\ns01 → ... → s13 → s14 → `s15` → [s16](/ja/s16) → s17 → s18 → s19 → s20 → s21 → s22\n> *\"一人では無理、チームを組もう\"* — ファイル受信箱 + チームメイトスレッド。\n>\n> **Harness 層**: チーム — マルチ Agent 協調、メッセージバス。\n\n> **モジュール 1/2:** s15 と s16 は一つの Agent Teams モジュールに含まれる二つの集中実験。この章でランタイムを構築し、s16 はランタイムを繰り返さず型付き協調プロトコルを追加する。\n\n---\n\n## 課題\n\n「バックエンド全体をリファクタリング」は認証モジュール、データベース層、API ルート、テストに及ぶ。一つの Agent が API ルートを修正中、認証モジュールの詳細はコンテキストから外れている。コンテキストウィンドウには限界があり、単一 Agent の注意は全モジュールをカバーできない。\n\ns06 のサブ Agent は臨時スタッフ、一つの仕事を終えたら去る。だが、通信でき、協力できるチームメイトが必要なタスクもある。\n\n---\n\n## ソリューション\n\n![Agent Teams Overview](/course-assets/s15_agent_teams/agent-teams-overview.ja.svg)\n\n教学版は S14 の能力(プロンプト組み立て、タスクシステム、バックグラウンド実行、cron スケジューリング)を踏襲。チーム機構に集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。追加:**MessageBus**(ファイル受信箱)、**spawn_teammate_thread**(チームメイトスレッド起動)、**inbox 注入**(Lead がチームメイトメッセージを受信し history に注入)。\n\nサブ Agent vs チームメイト:\n\n| | s06 サブ Agent | s15 チームメイト |\n|---|---|---|\n| ライフサイクル | 一回きり、終了後に破棄 | マルチターン(教学版は 10 ラウンド制限、真实 CC は idle loop) |\n| 通信 | 結果のみ返却 | 非同期受信箱、いつでも通信可能 |\n| コンテキスト | 完全に隔離 | メッセージで情報共有 |\n| 数 | メイン Agent + たまにサブ Agent | 1 Lead + 複数チームメイト |\n\n---\n\n## 仕組み\n\n![Team Topology](/course-assets/s15_agent_teams/team-topology.ja.svg)\n\n### MessageBus: ファイル受信箱\n\n各 Agent(Lead とチームメイトを含む)には `.jsonl` 受信箱がある。メッセージ送信 = 相手のファイルに 1 行 JSON を append。メッセージ読み取り = ファイル読み込み + 削除(消費式):\n\n```python\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str,\n content: str, msg_type: str = \"message\"):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time()}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()]\n inbox.unlink() # 消費式:読んだら削除\n return msgs\n```\n\nなぜファイルか、メモリキューではなく?教学版がファイルを選ぶ理由は、直感的でスレッドをまたいで観察可能だから。真实 CC もファイル受信箱(`~/.claude/teams/{team}/inboxes/`)を使うが、`proper-lockfile` で並行書き込みの安全性を確保。教学版の `read_inbox` には read + unlink の競合状態があり、マルチスレッド同時読みでメッセージを損失する可能性があるが、教学目的には許容範囲。\n\n### spawn_teammate_thread: チームメイト起動\n\nLead が `spawn_teammate` ツールを呼び出してチームメイトを起動。チームメイトは独自の daemon スレッドで動作、独自の system prompt、messages、簡易ツールセットを持つ:\n\n```python\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n system = f\"You are '{name}', a {role}. Use tools to complete tasks.\"\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [bash, read_file, write_file, send_message]\n for _ in range(10): # 最大 10 ラウンド\n inbox = BUS.read_inbox(name)\n if inbox:\n messages.append({\"role\": \"user\",\n \"content\": f\"{json.dumps(inbox)}\"})\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n # ... ツール実行、結果処理\n # 完了後 summary を Lead に送信\n BUS.send(name, \"lead\", summary, \"result\")\n\n threading.Thread(target=run, daemon=True).start()\n```\n\n重要な設計:\n- **チームメイトの簡易ツールセット**:bash、read、write、send_message。教学版は通信機構に集中するためタスクと cron を省略。真实 CC のチームメイトには TaskCreate、TaskUpdate 等のツールもあり、タスクシステムはチーム全体で共有\n- **教学版は 10 ラウンド制限**:無限ループを防止。真实 CC は idle loop:1 ラウンド終了後に `idle_notification` を送信、inbox メッセージを待機、到着後に再開、`shutdown_request` でのみ終了\n- **完了時自動報告**:`BUS.send(name, \"lead\", summary)` で最終結果を Lead の受信箱に送信\n\n### Lead の inbox 注入\n\nLead はメインループの各反復後に受信箱を確認。チームメイトからのメッセージを history に注入し、LLM が確認して反応できるようにする:\n\n```python\n# メインループ反復後\ninbox = BUS.read_inbox(\"lead\")\nif inbox:\n inbox_text = \"\\n\".join(\n f\"From {m['from']}: {m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n```\n\n教学版はユーザー入力ループ内で注入。真实 CC はより精密、Lead の `useInboxPoller` が毎秒チェックし、ユーザー入力を待たずにメッセージを新しい turn として送信。\n\n### 権限バブリング\n\n教学版は権限バブリングを省略。真实 CC のフロー(`permissionSync.ts`、`useSwarmPermissionPoller.ts`):\n\n1. チームメイトが承認が必要な操作に遭遇 → `permission_request` を Lead の受信箱に送信\n2. Lead の `useInboxPoller` がリクエストを検出 → 承認キューにルーティング\n3. ユーザーが承認 → Lead が `permission_response` をチームメイトに返信\n4. チームメイトの `useSwarmPermissionPoller`(500ms ごとにポーリング)が返信を受信 → 続行または拒否\n\n### 組み合わせて実行\n\n```\n1. Lead: \"バックエンド構築:一人では無理、チームを組もう\"\n2. Lead → spawn_teammate(\"alice\", \"backend dev\", \"データベーススキーマを作成\")\n3. Lead → spawn_teammate(\"bob\", \"frontend dev\", \"API クライアントを作成\")\n4. alice スレッド起動 → 独自の LLM 呼び出し → bash \"python manage.py migrate\"\n5. bob スレッド起動 → 独自の LLM 呼び出し → write_file(\"client.ts\", ...)\n6. alice 完了 → BUS.send(\"alice\", \"lead\", \"Schema done: users, orders tables\")\n7. bob 完了 → BUS.send(\"bob\", \"lead\", \"Client written with types\")\n8. Lead 次回反復 → inbox を history に注入 → LLM が alice と bob の結果を確認\n```\n\n2 人のチームメイトが並行作業。\n\n---\n\n## s14 からの変更\n\n| コンポーネント | 変更前 (s14) | 変更後 (s15) |\n|--------------|------------|------------|\n| Agent 数 | 1 | 1 Lead + N チームメイトスレッド |\n| 通信 | なし | MessageBus + .mailboxes/*.jsonl |\n| 新規クラス | — | MessageBus, active_teammates dict |\n| 新規関数 | — | spawn_teammate_thread, run_send_message, run_check_inbox |\n| Lead ツール | 11 (s14) | + spawn_teammate, send_message, check_inbox (14) |\n| チームメイトツール | — | bash, read_file, write_file, send_message (4) |\n| 権限 | ローカル判断 | 教学版は省略(真实 CC はバブリング機構あり) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s15_agent_teams/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Spawn alice as a backend developer. Ask her to create a file called schema.sql with a users table.`\n2. `Check your inbox for alice's result.`\n3. `Spawn bob as a tester. Ask him to check if schema.sql exists and list its contents.`\n\n観察ポイント:Lead はチームメイトをどう起動するか?`.mailboxes/` ディレクトリの JSONL ファイルの中身は?チームメイト完了後、Lead の inbox は history に注入されているか?\n\n---\n\n## 次の章\n\nチームメイトは仕事をし、通信できる。しかし、Lead が Alice にシャットダウンを頼む場合、スレッドを強制終了すると書きかけのファイルが残る。丁寧なシャットダウンプロトコルが必要:Lead が shutdown_request を送信、チームメイトは收尾後に終了。\n\ns16 Agent Teams プロトコル実験 → このランタイムにシャットダウンハンドシェイク、計画承認、型付きリクエスト-返信を追加する。\n\n
\nCC ソースコード深掘り\n\n> 以下は CC ソースコード `spawnMultiAgent.ts`、`useInboxPoller.ts`(969 行)、`useSwarmPermissionPoller.ts`(330 行)、`teammateMailbox.ts`、`teamHelpers.ts` の完全分析に基づく。\n\n### 一、中央メッセージバスはない、ファイルシステム\n\n教学版は `MessageBus` クラスでメッセージを送受信。真实 CC はもっと直接的、各 Agent が他の Agent の受信箱ファイルに直接書き込む。\n\n受信箱パス:`~/.claude/teams/{teamName}/inboxes/{agentName}.json`\n\n書き込み時は `proper-lockfile` で並行安全性を確保(最大 10 回リトライ)。各ファイルは JSON 配列、append 時に読み取り→追加→書き戻し。\n\n### 二、15 種のメッセージ型\n\nCC のチーム通信には 15 種の構造化メッセージ(`teammateMailbox.ts`)がある:\n\n| 型 | 方向 | 用途 |\n|------|------|------|\n| `plain text` | 双方向 | 通常のチームメイト間通信 |\n| `idle_notification` | チームメイト→Lead | チームメイトが 1 ターン完了、アイドル状態に |\n| `permission_request` | チームメイト→Lead | 操作承認が必要 |\n| `permission_response` | Lead→チームメイト | Lead の承認結果 |\n| `plan_approval_request` | チームメイト→Lead | 計画提出、審査待ち |\n| `plan_approval_response` | Lead→チームメイト | Lead の計画審査 |\n| `shutdown_request` | Lead→チームメイト | 丁寧なシャットダウン要求 |\n| `shutdown_approved` | チームメイト→Lead | シャットダウン確認 |\n| `shutdown_rejected` | チームメイト→Lead | シャットダウン拒否(理由付き) |\n| `task_assignment` | Lead→チームメイト | タスク割り当て |\n| `team_permission_update` | Lead→チームメイト | 権限変更のブロードキャスト |\n| `mode_set_request` | Lead→チームメイト | チームメイトの権限モード変更 |\n| `sandbox_permission_*` | 双方向 | ネットワーク権限リクエスト/返信 |\n| `teammate_terminated` | システム | チームメイト削除通知 |\n\nテキストメッセージは `` XML タグでラップされモデルに配信。\n\n### 三、権限バブリング:双方向ポーリング\n\n教学版は権限バブリングを省略。真实 CC のフロー(`permissionSync.ts`):\n\n1. **チームメイト**が承認が必要な操作に遭遇 → `permission_request` を Lead の受信箱に送信\n2. **Lead** の `useInboxPoller`(1 秒ごとにポーリング)がリクエストを検出 → `ToolUseConfirmQueue` にルーティング\n3. Lead の UI にチームメイト名と色付きの承認ダイアログを表示\n4. ユーザー承認後 → Lead が `permission_response` をチームメイトの受信箱に返信\n5. **チームメイト**の `useSwarmPermissionPoller`(500ms ごとにポーリング)が返信を受信 → 続行または拒否\n\n### 四、チームメイトライフサイクル\n\nCC のチームメイトは `spawnTeammate()`(`spawnMultiAgent.ts`)で作成:\n\n1. **Spawn**:tmux ペイン(またはプロセス内)を作成、色を割り当て、team config に書き込み\n2. **Work**:`useInboxPoller` が毎秒受信箱をチェック → メッセージ到着時に新しい turn として送信\n3. **Idle**:Stop hook 発火 → `idle_notification` を Lead に送信\n4. **Shutdown**:Lead が `shutdown_request` を送信 → チームメイトが `shutdown_approved` で返信 → Lead がクリーンアップ\n\n### 五、Team Config\n\nチーム登録は `~/.claude/teams/{teamName}/config.json`(`teamHelpers.ts`):\n\n```json\n{\n \"name\": \"my-team\",\n \"leadAgentId\": \"lead@my-team\",\n \"members\": [{\n \"agentId\": \"researcher@my-team\",\n \"name\": \"researcher\",\n \"agentType\": \"general-purpose\",\n \"color\": \"blue\",\n \"isActive\": true\n }]\n}\n```\n\nチームメイトのネストは禁止(`AgentTool.tsx:273` で \"teammates spawning other teammates\" を明示的に禁止)。\n\n
\n\n\n" + "title": "s15: Agent Teams — チームランタイムと協調プロトコル", + "content": "# s15: Agent Teams — チームランタイムと協調プロトコル\n\ns01 → ... → s13 → s14 → `s15` → [s16](/ja/s16) → s17 → s18 → s19 → s20 → s21\n\n> *「1 つの Agent だけでは扱いきれないなら、チームメイトで分担する。」* — 永続チームメイト、メッセージ配信、協調プロトコル。\n>\n> **Harness レイヤー**:チーム — 複数 Agent を並行動作させながら制御を保つ。\n\n---\n\n## 問題\n\nAgent にバックエンド全体のリファクタリングを頼む場合、設定読み込み、認証、テストを同時に扱うことになる。1 つの Agent が順番に処理することもできるが、時間がかかり、初期の詳細は徐々にコンテキストから抜けていく。\n\nこのような仕事は並列化に向いている。しかし、通常のユーザーはチーム構成ではなく目的だけを伝える:\n\n```text\nこのサンプルバックエンドをリファクタリングしてください。\n設定読み込み、認証ロジック、テストを整理し、\n既存インターフェースを保ったままテストを通してください。\n```\n\nそのため Harness は、単に Agent を増やすだけでなく、次の 4 点を解決する必要がある:\n\n1. 並列化が有効かを誰が判断し、追加 Agent の起動を誰が確認するか。\n2. チームメイトが複数の依頼にまたがって、どう身元とコンテキストを保つか。\n3. モデルに受信箱を繰り返し確認させず、結果をどう Lead へ戻すか。\n4. 終了と計画承認を、どう追跡可能で強制可能なプロトコルにするか。\n\n---\n\n## 解決策\n\n![Agent Teams Overview](/course-assets/s15_agent_teams/agent-teams-overview.ja.svg)\n\ns15 は単一 Agent の Harness の外側に、Lead が管理するチームランタイムを追加する:\n\n- **Lead** はユーザーとの会話を維持し、分担案を提示して確認を待つ。\n- **チームメイト** は独立した Agent Loop をバックグラウンドスレッドで実行し、作業後は IDLE になる。\n- **MessageBus** はファイル受信箱を通して、通常メッセージ、結果、制御イベントを運ぶ。\n- **ランタイム配信** は Lead の受信箱を消費し、チームイベントを次のターンへ注入する。\n- **協調プロトコル** は `type`、`request_id`、状態遷移で終了と計画承認を扱う。\n- **計画ゲート** は、必要な計画が承認されるまで `bash` と `write_file` を遮断する。\n\nモデルはタスクを理解して分担を決める。コードは配信、ライフサイクル、プロトコル制約を担う。\n\n---\n\n## 仕組み\n\n### 1. Lead はチーム案を示し、確認を待つ\n\nチームメイトの起動は、コスト、並行度、ワークスペースを書き換える主体を変える。この境界を通常のツール呼び出しの中に隠してはいけない。Lead の system prompt は次のように定める:\n\n```python\n\"When parallel work would help, first propose a small team with clear \"\n\"responsibilities and wait for the user's confirmation. Do not call \"\n\"spawn_teammate before the user confirms.\"\n```\n\n最初の依頼に対して、Lead はまず分担案だけを返す:\n\n```text\n次の 3 方向で並行処理することを提案します。\n- config:設定読み込みの整理\n- auth:認証ロジックのリファクタリング\n- tests:回帰テストの追加\n\n確認後にチームメイトを起動します。\n```\n\nユーザーが「始めてください」と返した後で、Lead は `spawn_teammate` を呼ぶ。ユーザーが目的を示し、Lead がチームを設計し、ユーザーが実行境界を確認する。\n\n### 2. 各チームメイトは独立したループを持つ\n\ns06 の Subagent は 1 回限りの呼び出しだが、チームメイトは永続する実行単位である:\n\n| | s06 Subagent | s15 チームメイト |\n|---|---|---|\n| ライフサイクル | 1 回の呼び出し後に終了 | 終了要求まで `WORK → IDLE → WORK` |\n| コンテキスト | 1 つのタスクだけ | 複数の依頼をまたいで保持 |\n| 通信 | 1 回だけ結果を返す | メッセージを受け取り、イベントを送る |\n| 協調 | 一方向の委任 | Lead との双方向協調 |\n\n`spawn_teammate_thread()` はチームメイトごとに system prompt、messages、ツールを作り、daemon thread でループを実行する。Lead はチームメイトの終了を待たずに、別の依頼や結果を調整できる。\n\n### 3. MessageBus は通信をモデルのコンテキスト外に置く\n\nLead とチームメイトが同じ messages 配列を共有すると、あるチームメイトのツール結果が別のチームメイトの推論へ混ざる。`MessageBus` は各 Agent に `.mailboxes/.jsonl` 受信箱を与える:\n\n```python\nclass MessageBus:\n def send(self, from_agent, to_agent, content,\n msg_type=\"message\", metadata=None):\n msg = {\n \"from\": from_agent,\n \"to\": to_agent,\n \"content\": content,\n \"type\": msg_type,\n \"metadata\": metadata or {},\n }\n with self._changed:\n append_jsonl(self._path(to_agent), msg)\n self._changed.notify_all()\n\n def wait_for_messages(self, agent):\n with self._changed:\n while not self.peek(agent):\n self._changed.wait()\n return self._read_unlocked(agent)\n```\n\nロックは複数スレッドによる受信箱ファイルの破損を防ぐ。`Condition` により、IDLE のチームメイトはポーリングせずイベント到着まで待機できる。\n\n### 4. 受信イベントはランタイムが自動配信する\n\n`read_inbox()` はメッセージを読み、受信箱ファイルを削除する。そのため Lead の消費入口は `consume_lead_inbox()` だけにする:\n\n```python\ndef consume_lead_inbox():\n messages = BUS.read_inbox(\"lead\")\n for message in messages:\n if message[\"type\"].endswith(\"_response\"):\n match_response(...)\n return messages\n```\n\nメインループのイベントスレッドは、新しいメッセージが届くと Lead を起こす:\n\n```text\nMessageBus → consume_lead_inbox\n → プロトコル状態を更新\n → [Team events] を history へ注入\n → Lead の次ターンを開始\n```\n\n`check_inbox` はモデルのツールではない。メッセージの到着はランタイムの責務であり、モデルはコンテキストへ配信済みのイベントだけを処理する。\n\n### 5. 結果と IDLE は別のイベント\n\nチームメイトが 1 件の作業を終えると、ランタイムは次の順序で 2 つのイベントを送る:\n\n```text\nresult: \"認証をリファクタリングし、関連テストが通りました。\"\nidle_notification: \"Waiting for more work.\"\n```\n\n`result` は「今回の作業で何が得られたか」、`idle_notification` は「新しい仕事を受けられるか」を表す。1 つの曖昧な「done」では両者を区別できない。\n\nIDLE になったチームメイトは終了しない。通常メッセージで WORK に戻り、`shutdown_request` で終了ハンドシェイクを始める。\n\n### 6. 制御メッセージには型と request_id を使う\n\n通常の協調は自由文でよいが、終了と承認を意図の推測に任せてはいけない。制御イベントは構造化する:\n\n![Team Protocols](/course-assets/s15_agent_teams/team-protocols-overview.ja.svg)\n\n```python\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n\n\npending_requests: dict[str, ProtocolState] = {}\n```\n\n終了プロトコルは次の経路を通る:\n\n```text\nLead が pending の shutdown request を作る\n → shutdown_request(request_id) をチームメイトへ送る\n → チームメイトが現在の手順を終える\n → shutdown_response(request_id) を Lead へ返す\n → request_id で元の要求を特定する\n → pending が approved になり、チームメイトループが終了する\n```\n\nID は要求と応答を対応付け、型は誤った応答による状態変更を防ぎ、状態は重複応答の再適用を防ぐ。\n\n### 7. 計画承認は実行も制約する\n\n計画プロトコルは逆方向に流れる:\n\n```text\nLead → plan_request\nチームメイト → plan_approval_request(request_id, plan)\nLead → plan_approval_response(request_id, approve, feedback)\n```\n\n「承認まで待つ」と伝えるだけでは確実なゲートにならない。そこでツール dispatch が計画状態を検査する:\n\n```python\ndef _run_teammate_tool(name, block, handlers):\n gate = plan_gates.get(name, \"not_required\")\n if block.name in {\"bash\", \"write_file\"} and gate not in {\n \"not_required\", \"approved\"\n }:\n return f\"Blocked: plan status is {gate}.\"\n return handlers[block.name](**block.input)\n```\n\n状態が `required`、`pending`、`rejected` の間、チームメイトはファイルを読み、計画を提出または修正できるが、Shell 実行やファイル書き込みはできない。承認応答で `approved` になった後にだけツールが解放される。\n\n---\n\n## 一連の実行例\n\n```text\ns15 >> このサンプルバックエンドをリファクタリングしてください。\n 設定読み込み、認証、テストを整理し、\n 既存インターフェースを保ってテストを通してください。\n\nLead: config、auth、tests の 3 方向で並行処理することを提案します。\n チームを開始しますか?\n\ns15 >> 始めてください\n\n[teammate] config spawned\n[teammate] auth spawned\n[teammate] tests spawned\n[bus] auth → lead (result) ...\n[bus] auth → lead (idle_notification) ...\n[wake: 2 team events → new turn]\nLead: 認証の結果を受け取りました。残りの作業も調整します。\n```\n\n端末には、ユーザー要求、Lead の分担、起動、メッセージ、結果、IDLE、終了イベントが表示される。ユーザーが Lead を指名したり、受信箱の確認を頼んだりする必要はない。\n\n---\n\n## s14 からの変更\n\n| コンポーネント | s14 | s15 |\n|---|---|---|\n| Agent | 1 つ | 1 つの Lead + 永続チームメイト |\n| ユーザーフロー | 依頼を直接実行 | チーム案を提示してから起動を確認 |\n| 通信 | なし | ファイル受信箱 + 自動イベント配信 |\n| ライフサイクル | 1 つのループ | チームメイトの `WORK / IDLE / shutdown` |\n| 結果通知 | 現在の Agent の出力 | `result` と `idle_notification` を分離 |\n| 制御 | なし | 終了と計画承認プロトコル |\n| 強制 | チーム制約なし | 必須計画が変更系ツールをゲート |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s15_agent_teams/code.py\n```\n\nまず通常の依頼を入力する:\n\n```text\nこのサンプルバックエンドをリファクタリングしてください。\n設定読み込み、認証ロジック、テストを整理し、\n既存インターフェースを保ったままテストを通してください。\n```\n\nLead がチーム案を示したら、次のように返す:\n\n```text\n始めてください\n```\n\n`spawned`、`result`、`idle_notification`、`plan_approval_*`、`shutdown_*` の各イベントと、`.mailboxes/` のファイルが生成・消費される流れを確認する。\n\n---\n\n## 次へ\n\ns15 では、Lead が各チームメイトへ明示的に仕事を割り当てる。次のセッションでは共有タスクボードを IDLE のチームメイトに公開し、実行可能な仕事を自ら見つけて claim できるようにする。\n\n次へ:[s16 Autonomous Agents](/ja/s16)。\n\n\n" }, { "version": "s16", "locale": "en", - "title": "s16: Agent Teams — Protocol Lab: Typed Coordination", - "content": "# s16: Agent Teams — Protocol Lab: Typed Coordination\n\ns01 → ... → s14 → s15 → `s16` → [s17](/en/s17) → s18 → s19 → s20 → s21 → s22\n> *\"Teammates need agreements\"* — request-response pattern drives all negotiation.\n>\n> **Harness Layer**: Protocols — Structured handshakes between agents.\n\n> **Module 2 of 2:** s15 built the teammate runtime and mailbox. This lab changes only the coordination contract: requests, replies, correlation IDs, and state transitions.\n\n---\n\n## The Problem\n\ns15's teammates can work, but coordination is loose: Lead sends a message, teammate replies, no structured protocol. Two scenarios expose the gap:\n\n**Shutdown**: Lead wants Alice to shut down. Killing the thread outright leaves half-written files on disk. A handshake is needed: Lead sends a request, Alice confirms after wrapping up.\n\n**Plan approval**: Bob wants to refactor the auth module, a high-risk operation. Lead should review Bob's plan first, approve before Bob proceeds.\n\nBoth scenarios share the same structure: one side sends a request, the other replies, both linked by the same ID. A state machine tracks: pending → approved / rejected.\n\n---\n\n## The Solution\n\n![Team Protocols Overview](/course-assets/s16_team_protocols/team-protocols-overview.en.svg)\n\nTeaching code continues the agent capability arc from earlier chapters and adds structured protocols on top of S15's team communication. To stay focused on the protocol mechanism, it omits full error recovery, memory, and skill systems. Added: **ProtocolState** (request state tracking), **dispatch_message** (routes incoming messages by type to handlers), **match_response** (correlates response to request via request_id, with type validation).\n\nTwo protocols, one mechanism:\n\n| Protocol | Direction | Purpose |\n|----------|-----------|---------|\n| shutdown_request / response | Lead → Teammate | Graceful shutdown handshake |\n| plan_approval_request / response | Teammate → Lead | Plan approval protocol example |\n\n> Teaching version demonstrates the request-response message flow for plan approval, but does not implement execution gating (intercepting bash/write_file when not approved). Real CC has a permission gating mechanism for teammates.\n\n---\n\n## How It Works\n\n### ProtocolState: Request State\n\nEach protocol request creates a state record tracking who sent it, to whom, current status, and payload:\n\n```python\n@dataclass\nclass ProtocolState:\n request_id: str # Unique ID, e.g. \"req_004281\"\n type: str # \"shutdown\" | \"plan_approval\"\n sender: str # Sender\n target: str # Recipient\n status: str # pending | approved | rejected\n payload: str # Plan text or shutdown reason\n created_at: float # Timestamp\n\npending_requests: dict[str, ProtocolState] = {}\n```\n\nA record is created when sending a request, found via `request_id` when receiving a response, and its status updated.\n\n### Four-Step Protocol Flow\n\nUsing shutdown as an example, the full chain:\n\n```\n1. Lead sends request\n req_id = new_request_id() # \"req_004281\"\n pending_requests[req_id] = ProtocolState(type=\"shutdown\", status=\"pending\", ...)\n BUS.send(\"lead\", \"alice\", \"shutdown_request\", metadata={\"request_id\": req_id})\n\n2. Teammate receives → dispatch\n inbox = BUS.read_inbox(\"alice\")\n msg_type = msg[\"type\"] # \"shutdown_request\"\n → routed to handle_shutdown_request()\n\n3. Teammate replies\n BUS.send(\"alice\", \"lead\", \"shutdown_response\",\n metadata={\"request_id\": req_id, \"approve\": True})\n\n4. Lead receives response → match\n match_response(\"shutdown_response\", req_id, approve=True)\n pending_requests[req_id].status = \"approved\"\n```\n\n`request_id` is the correlation key across the entire chain: the request carries it out, the response carries it back.\n\n### dispatch_message: Route by Type\n\nA teammate's inbox receives both plain messages and protocol messages. `handle_inbox_message` dispatches by message type:\n\n```python\ndef handle_inbox_message(name, msg, messages):\n msg_type = msg.get(\"type\", \"message\")\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down.\", \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return True # Stop the loop\n\n if msg_type == \"plan_approval_response\":\n approve = msg[\"metadata\"].get(\"approve\", False)\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved]\" if approve else \"[Plan rejected]\"})\n return False # Continue\n```\n\nAdding a new protocol type means adding a new `if` branch.\n\n### match_response: Type Validation\n\n`match_response` doesn't just find state by `request_id`, it also validates that the response type matches the request type:\n\n```python\ndef match_response(response_type, request_id, approve):\n state = pending_requests.get(request_id)\n if not state:\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n return # type mismatch, skip\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n return\n if state.status != \"pending\":\n return # already resolved, skip duplicate\n state.status = \"approved\" if approve else \"rejected\"\n```\n\nA shutdown_response cannot accidentally approve a plan_approval request.\n\n### Unified Inbox Consumer: consume_lead_inbox\n\nBoth the `check_inbox` tool and the main loop call the same `consume_lead_inbox()` function, routing protocol messages before returning remaining content. This prevents messages from being consumed without protocol state updates:\n\n```python\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n```\n\nThe main loop also injects inbox messages into `history` so the LLM can see and react to them.\n\n### Teammate Idle Loop: Wait Instead of Exit\n\ns15's teammates exit after 10 rounds. s16's teammates enter idle waiting after the LLM returns a non-tool_use response: poll inbox, respond to shutdown_request and exit, or continue working on new messages.\n\n```\nLLM returns non-tool_use\n → idle: poll inbox every second\n → receives shutdown_request → reply shutdown_response → exit\n → receives new message → inject into messages → continue LLM turn\n```\n\nTeaching version omits idle_notification to Lead. Real CC sends `idle_notification` when idle, so Lead knows the teammate is free for new tasks.\n\n### Putting It Together\n\n```\n1. Lead: \"Have Alice create a file, then shut her down\"\n2. Lead → spawn_teammate(\"alice\", \"backend\", \"Create config.py\")\n3. alice thread starts → write_file(\"config.py\", \"...\") → done → idle\n4. Lead → request_shutdown(\"alice\")\n → BUS.send(\"shutdown_request\", {request_id: \"req_000142\"})\n5. alice idle poll receives → handle_shutdown_request\n → BUS.send(\"shutdown_response\", {request_id: \"req_000142\", approve: True})\n6. Lead consume_lead_inbox → match_response(\"req_000142\", approve=True)\n → pending_requests[\"req_000142\"].status = \"approved\"\n → inbox message injected into history, LLM sees shutdown result\n```\n\nShutdown handshake complete: request → confirm → shutdown. Every step tracked by `request_id`.\n\n---\n\n## Changes from s15\n\n| Component | Before (s15) | After (s16) |\n|-----------|-------------|-------------|\n| Coordination | Loose text messages | Structured request-response protocol |\n| Request tracking | None | ProtocolState + pending_requests dict |\n| Message routing | All treated as text | dispatch_message routes by type |\n| Shutdown | Natural exit or kill thread | request_id handshake mechanism |\n| Plan approval | None | Message flow example (no execution gating) |\n| New message types | message, result | + shutdown_request/response, plan_approval_request/response |\n| Teammate lifecycle | Max 10 rounds | Idle loop (waits for inbox messages) |\n| Lead inbox | check_inbox and main loop read separately | Unified consume_lead_inbox |\n| Lead tools | 14 (s15) | 14 (core tool set plus request_shutdown, request_plan, review_plan) |\n| Teammate tools | 4 (s15) | + submit_plan (5) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s16_team_protocols/code.py\n```\n\nTry these prompts:\n\n1. `Spawn alice as a backend dev. Ask her to create a file. Then request her shutdown.`\n2. `Spawn bob with a refactoring task. Have him submit a plan first. Then review and approve it.`\n\nWhat to observe: Is the shutdown handshake complete (request → confirm → shutdown)? Does `pending_requests` state transition correctly? Is `request_id` consistent between request and response? Can the idle teammate receive shutdown_request?\n\n---\n\n## What's Next\n\nIn s15-s16, Lead must assign tasks to each teammate. \"Alice does this, Bob does that.\" With 10 unclaimed tasks on the board, Lead has to manually assign each one.\n\nWhat if teammates could check the board and claim tasks themselves? Lead only needs to create tasks; teammates discover, claim, and complete them on their own.\n\ns17 Autonomous Agents → Self-organizing teammates, no leader assignment needed.\n\n
\nDeep Dive into CC Source\n\nCC's team protocol implementation (`teammateMailbox.ts`, 1184 lines) shares the same core structure as the teaching version: request_id + approve/reject request-response pattern. Differences:\n\n**Shutdown protocol**: CC's shutdown is three-way communication (`teammateMailbox.ts:720-763`, `SendMessageTool.ts:268-430`). Lead sends `shutdown_request`, teammate replies `shutdown_approved` (or `shutdown_rejected` with reason), system sends `teammate_terminated` to notify all parties. After confirmation, system cleans up pane (tmux/iTerm2), unassigns tasks, removes member from team config (`useInboxPoller.ts:677-800`). Teaching version uses `shutdown_response` as a unified name; real source splits into `shutdown_approved` and `shutdown_rejected` as two separate message types.\n\n**Plan approval**: In the real source, plan approval request is generated by `ExitPlanModeV2Tool.ts:263-312` when a plan-mode-required teammate exits plan mode. `useInboxPoller.ts:599-661` currently auto-writes approval and passes the request to Lead as context (regular message). `SendMessageTool.ts:434-518` retains explicit approve/reject response capability — approval can simultaneously set `permissionMode` (e.g. \"approved but run in plan mode\"), response can include `feedback` string for teammate to revise and resubmit. Not a simple \"Lead manually uses review_plan tool\" flow.\n\n**Message format**: CC's protocol messages are structured JSON (with Zod schema validation), teaching version uses simple type + metadata dict. Field names are also inconsistent: permission uses `request_id` (`teammateMailbox.ts:453-462`), shutdown and plan approval use `requestId` (`teammateMailbox.ts:684-763`).\n\n**Execution gating**: CC's teammates have full permission gating. Unapproved high-risk operations are intercepted, not optional. Teaching version only demonstrates the message flow without execution interception.\n\n**Generality**: Teaching version's single FSM (pending → approved | rejected) maps to two protocols. This simplification is correct. CC's protocol messages all share the same request id correlation mechanism.\n\n
\n\n\n" + "title": "s16: Autonomous Agents — Check the Board, Claim the Work", + "content": "# s16: Autonomous Agents — Check the Board, Claim the Work\n\ns01 → ... → s14 → s15 → `s16` → [s17](/en/s17) → s18 → s19 → s20 → s21\n\n> *\"Idle does not only mean waiting for a message; it can also mean looking for ready work.\"* — Shared task board, automatic discovery, and atomic claims.\n>\n> **Harness layer**: Autonomy — Lead owns the goal while teammates discover the next step from shared state.\n\n---\n\n## The Problem\n\nIn s15, a teammate enters IDLE after finishing an assignment and waits for Lead to send more work. If the task board already contains ten pending tasks, Lead still has to choose a teammate, send a message, and wait for a result ten times.\n\nOnce work has been decomposed and dependencies are recorded on the task board, assigning the next ready task does not always need another model decision. An idle teammate can read shared state and claim work whose prerequisites are complete.\n\n---\n\n## The Solution\n\n![Autonomous Agents Overview](/course-assets/s16_autonomous_agents/autonomous-agents-overview.en.svg)\n\ns16 keeps the s15 team lifecycle and extends only the IDLE state:\n\n```text\ns15: WORK → result → IDLE → wait for a message\ns16: WORK → result → IDLE → wait for a message\n └→ scan board → claim → WORK\n```\n\nIt adds two functions:\n\n- `scan_unclaimed_tasks()` finds tasks that can start now.\n- `claim_next_task(name)` attempts to claim one candidate atomically.\n\nTeammates also receive `list_tasks`, `claim_task`, and `complete_task`, allowing the claimed work to close inside the same loop.\n\n---\n\n## How It Works\n\n### 1. Discovery and ownership are separate steps\n\nScanning reads state without changing it:\n\n```python\ndef scan_unclaimed_tasks() -> list[Task]:\n return [\n task for task in list_tasks()\n if (\n task.status == \"pending\"\n and task.owner is None\n and can_start(task.id)\n )\n ]\n```\n\nA candidate must be `pending`, have no owner, and have every `blockedBy` dependency completed.\n\nThe resulting list is only a snapshot. Another teammate may claim the same task immediately afterward, so \"discovered\" must never mean \"owned.\"\n\n### 2. Claim performs read, validation, and write under one lock\n\n`claim_task()` protects the full state transition with `task_lock`:\n\n```python\ndef claim_task(task_id: str, owner: str) -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\" or task.owner:\n return \"Task is no longer available\"\n if not can_start(task_id):\n return \"Task is blocked\"\n\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task.id}\"\n```\n\n`claim_next_task()` tries candidates until one claim succeeds:\n\n```python\ndef claim_next_task(name: str) -> Task | None:\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n```\n\nMany teammates may observe the board at once, but the claim function gives each task one final owner.\n\n### 3. Messages take priority over board scans\n\nIn IDLE, a teammate first waits briefly for mailbox events:\n\n```python\nwhile True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n handle_messages(inbox)\n break\n\n task = claim_next_task(name)\n if task:\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}\"\n ),\n })\n break\n```\n\nThis ordering matters:\n\n- Shutdown, plan approval, and direct Lead messages should be handled promptly.\n- Only otherwise idle time is used to look for shared work.\n\nIf there is neither a message nor a ready task, the teammate stays idle. An empty scan is not a reason to exit because a blocked task may become ready later.\n\n### 4. A claimed task reuses the same WORK loop\n\nAfter a successful claim, the runtime injects the task ID, subject, and description into the teammate's messages. The existing file tools, Shell, plan gate, result reporting, and shutdown protocol all remain unchanged.\n\n```text\nready task appears\n → idle teammate discovers it\n → claim_task writes owner and in_progress\n → task enters teammate messages\n → WORK\n → complete_task\n → result + idle_notification\n → scan again\n```\n\nAutonomy does not require another agent loop. It adds a shared-state entry point to the loop that already exists.\n\n---\n\n## Why This Design\n\n**Why not ask Lead to assign every task?**\n\nThe task's `status`, `owner`, and `blockedBy` already encode whether it can run. Reinterpreting that same state through Lead adds coordination turns without adding judgment.\n\n**Why not set the owner during scanning?**\n\nScans may overlap. Keeping ownership changes in one locked function gives every caller the same rule.\n\n**Why keep teammates alive when no task is ready?**\n\nAn empty candidate list may only mean that prerequisites are still running. IDLE teammates can pick up downstream work as soon as it becomes ready.\n\n---\n\n## What Changed from s15\n\n| Component | s15 | s16 |\n|---|---|---|\n| IDLE behavior | Wait for team messages | Wait for messages, then scan the board |\n| Assignment | Lead sends work explicitly | Teammates may auto-claim |\n| Ownership | Caller initiates claim | `task_lock` makes claim atomic |\n| Teammate tools | Files, Shell, messages, plans | Adds list / claim / complete task |\n| Result and shutdown | `result`, `idle_notification`, shutdown protocol | Unchanged |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s16_autonomous_agents/code.py\n```\n\nEnter an ordinary request:\n\n```text\nPut the backend refactor on a shared task board. Complete configuration,\nauthentication, and tests in parallel where dependencies allow, preserve\nexisting interfaces, and summarize the result.\n```\n\nAfter Lead proposes a team, reply:\n\n```text\nGo ahead.\n```\n\nWatch tasks move from `pending` to `in_progress` and `completed` under `.tasks/`. Two idle teammates should claim different tasks, and a task with `blockedBy` should become a candidate only after its prerequisites finish.\n\n---\n\n## Next\n\nTeammates can now discover work, but they still edit files in the same directory. The next lesson binds task ownership to isolated working directories.\n\nNext: [s17 Worktree Isolation](/en/s17).\n\n\n" }, { "version": "s16", "locale": "zh", - "title": "s16: Agent Teams — 协议实验:带类型的协作", - "content": "# s16: Agent Teams — 协议实验:带类型的协作\n\ns01 → ... → s14 → s15 → `s16` → [s17](/zh/s17) → s18 → s19 → s20 → s21 → s22\n> *\"队友之间要有约定\"* — request-response 模式驱动协商。\n>\n> **Harness 层**: 协议 — Agent 之间的结构化握手。\n\n> **模块 2/2:** s15 已经搭好队友运行时与邮箱。本章只改变协作契约:请求、回复、关联 ID 和状态迁移。\n\n---\n\n## 问题\n\ns15 的队友能干活了,但协调是松散的:Lead 发消息,队友回复,没有结构化的协议。两个场景暴露了问题:\n\n**关机**:Lead 想让 Alice 关机。直接杀线程,Alice 写了一半的文件留在磁盘上。需要握手:Lead 发请求,Alice 确认收尾后关机。\n\n**计划审批**:Bob 想重构认证模块,属于高风险操作。应该先让 Lead 看 Bob 的计划,审批通过后再动手。\n\n这两个场景结构完全一样:一方发请求,另一方给回复,请求和回复通过同一个 ID 关联。有状态机追踪:pending → approved / rejected。\n\n---\n\n## 解决方案\n\n![Team Protocols Overview](/course-assets/s16_team_protocols/team-protocols-overview.svg)\n\n教学代码承接前面章节的 Agent 能力脉络,在 S15 团队通信基础上加入结构化协议。为了聚焦协议机制,省略了完整错误恢复、记忆和技能系统。新增三样:**ProtocolState**(请求状态追踪)、**dispatch_message**(按消息类型路由到处理器)、**match_response**(通过 request_id 关联回复与请求,含类型校验)。\n\n两种协议,一套机制:\n\n| 协议 | 方向 | 用途 |\n|------|------|------|\n| shutdown_request / response | Lead → 队友 | 体面关机握手 |\n| plan_approval_request / response | 队友 → Lead | 计划审批协议示例 |\n\n> 教学版演示了计划审批的请求-响应消息流程,没有实现执行门控(未 approved 时拦截 bash/write_file)。真实 CC 的队友有 permission gating 机制。\n\n---\n\n## 工作原理\n\n### ProtocolState: 请求状态\n\n每个协议请求创建一条状态记录,记录谁发的、发给谁、当前状态、附带内容:\n\n```python\n@dataclass\nclass ProtocolState:\n request_id: str # 唯一 ID,如 \"req_004281\"\n type: str # \"shutdown\" | \"plan_approval\"\n sender: str # 发起方\n target: str # 接收方\n status: str # pending | approved | rejected\n payload: str # 计划文本或关机原因\n created_at: float # 时间戳\n\npending_requests: dict[str, ProtocolState] = {}\n```\n\n发请求时创建记录,收回复时通过 `request_id` 找到对应记录,更新状态。\n\n### 四步协议流程\n\n以关机为例,完整链路:\n\n```\n① Lead 发请求\n req_id = new_request_id() # \"req_004281\"\n pending_requests[req_id] = ProtocolState(type=\"shutdown\", status=\"pending\", ...)\n BUS.send(\"lead\", \"alice\", \"shutdown_request\", metadata={\"request_id\": req_id})\n\n② 队友收到 → dispatch\n inbox = BUS.read_inbox(\"alice\")\n msg_type = msg[\"type\"] # \"shutdown_request\"\n → 路由到 handle_shutdown_request()\n\n③ 队友回复\n BUS.send(\"alice\", \"lead\", \"shutdown_response\",\n metadata={\"request_id\": req_id, \"approve\": True})\n\n④ Lead 收响应 → match\n match_response(\"shutdown_response\", req_id, approve=True)\n pending_requests[req_id].status = \"approved\"\n```\n\n`request_id` 是贯穿全链路的关联键,请求带着它出去,回复带着它回来。\n\n> 教学版用 `shutdown_response` 统一命名(approve 字段区分同意/拒绝)。真实源码拆成 `shutdown_approved` 和 `shutdown_rejected` 两种独立消息类型(`teammateMailbox.ts:720-763`)。\n\n### dispatch_message: 按类型路由\n\n队友的 inbox 不只收普通消息,还收协议消息。`handle_inbox_message` 按消息类型分发:\n\n```python\ndef handle_inbox_message(name, msg, messages):\n msg_type = msg.get(\"type\", \"message\")\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down.\", \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return True # 停止循环\n\n if msg_type == \"plan_approval_response\":\n approve = msg[\"metadata\"].get(\"approve\", False)\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved]\" if approve else \"[Plan rejected]\"})\n return False # 继续循环\n```\n\n新增协议类型只需加新的 `if` 分支。\n\n### match_response: 类型校验\n\n`match_response` 不只按 `request_id` 找状态,还会校验响应类型是否匹配请求类型:\n\n```python\ndef match_response(response_type, request_id, approve):\n state = pending_requests.get(request_id)\n if not state:\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n return # type mismatch, skip\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n return\n if state.status != \"pending\":\n return # already resolved, skip duplicate\n state.status = \"approved\" if approve else \"rejected\"\n```\n\n一个 shutdown_response 不会意外 approve 一个 plan_approval 请求。\n\n### 统一 inbox 消费:consume_lead_inbox\n\n`check_inbox` 工具和主循环末尾都调用同一个 `consume_lead_inbox()` 函数,先路由协议消息再返回剩余内容,避免消息被读走但协议状态没更新:\n\n```python\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n```\n\n主循环末尾还会把 inbox 消息注入到 `history`,让 LLM 能看到并做出反应。\n\n### 队友 idle loop:等待而不是退出\n\ns15 的队友跑完 10 轮就退出。s16 的队友在 LLM 返回非 tool_use 后进入 idle 等待:轮询 inbox,收到 shutdown_request 就响应退出,收到新消息就继续工作。\n\n```\nLLM 返回非 tool_use\n → idle: 每秒轮询 inbox\n → 收到 shutdown_request → 回复 shutdown_response → 退出\n → 收到新消息 → 注入 messages → 继续 LLM turn\n```\n\n教学版省略了 idle_notification 给 Lead 的通知。真实 CC 在 idle 时发 `idle_notification`,Lead 收到后知道队友空闲,可以分配新任务。\n\n### 合起来跑\n\n```\n1. Lead: \"让 Alice 创建一个文件,然后关机\"\n2. Lead → spawn_teammate(\"alice\", \"backend\", \"创建 config.py\")\n3. alice 线程启动 → write_file(\"config.py\", \"...\") → 完成 → idle\n4. Lead → request_shutdown(\"alice\")\n → BUS.send(\"shutdown_request\", {request_id: \"req_000142\"})\n5. alice idle 轮询收到 → handle_shutdown_request\n → BUS.send(\"shutdown_response\", {request_id: \"req_000142\", approve: True})\n6. Lead consume_lead_inbox → match_response(\"req_000142\", approve=True)\n → pending_requests[\"req_000142\"].status = \"approved\"\n → inbox 消息注入 history,LLM 看到关机结果\n```\n\n关机握手完整:请求 → 确认 → 关机。每一步有 `request_id` 追溯。\n\n---\n\n## 相对 s15 的变更\n\n| 组件 | 之前 (s15) | 之后 (s16) |\n|------|-----------|-----------|\n| 协调方式 | 松散文本消息 | 结构化请求-响应协议 |\n| 请求追踪 | 无 | ProtocolState + pending_requests dict |\n| 消息路由 | 全部当文本处理 | dispatch_message 按类型分发 |\n| 关机 | 自然退出或杀线程 | request_id 握手机制 |\n| 计划审批 | 无 | 消息流程示例(未实现执行门控) |\n| 新消息类型 | message, result | + shutdown_request/response, plan_approval_request/response |\n| 队友生命周期 | 最多 10 轮 | idle loop(等待 inbox 消息) |\n| Lead inbox | check_inbox 和主循环分别读 | 统一 consume_lead_inbox |\n| Lead 工具 | 14 (s15) | 14(核心工具集加入 request_shutdown, request_plan, review_plan) |\n| 队友工具 | 4 (s15) | + submit_plan (5) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s16_team_protocols/code.py\n```\n\n试试这些 prompt:\n\n1. `Spawn alice as a backend dev. Ask her to create a file. Then request her shutdown.`\n2. `Spawn bob with a refactoring task. Have him submit a plan first. Then review and approve it.`\n\n观察重点:关机握手是否完整(请求 → 确认 → 关机)?`pending_requests` 的状态是否正确转换?`request_id` 是否在请求和响应之间保持一致?队友 idle 后是否能收到 shutdown_request?\n\n---\n\n## 接下来\n\ns15-s16 中,Lead 必须给每个队友分配任务。\"Alice 做这个,Bob 做那个\"。任务看板上有 10 个未认领的任务,Lead 得手动 assign。\n\n能不能让队友自己看板、自己认领?Lead 只需要创建任务,队友自己发现、自己认领、自己完成。\n\ns17 Autonomous Agents → 队友自组织,不需要领导分配。\n\n
\n深入 CC 源码\n\nCC 的团队协议实现(`teammateMailbox.ts`,1184 行)和教学版在核心结构上一致:request_id + approve/reject 的请求-响应模式。差异在于:\n\n**关机协议**:CC 的 shutdown 是三向通信(`teammateMailbox.ts:720-763`、`SendMessageTool.ts:268-430`)。Lead 发 `shutdown_request`,队友回复 `shutdown_approved`(或 `shutdown_rejected` 附原因),系统发送 `teammate_terminated` 通知所有相关方。关机确认后系统自动清理 pane(tmux/iTerm2)、unassign 任务、从 team config 移除成员(`useInboxPoller.ts:677-800`)。教学版用 `shutdown_response` 统一命名,真实源码拆成 approved/rejected 两种独立消息。\n\n**计划审批**:真实源码里 plan approval request 由 `ExitPlanModeV2Tool.ts:263-312` 在 plan-mode-required 队友退出 plan mode 时产生。`useInboxPoller.ts:599-661` 当前会自动回写 approval,并把请求交给 Lead 作为上下文(regular message)。`SendMessageTool.ts:434-518` 仍保留显式 approve/reject response 能力,审批时可同时设置 `permissionMode`(如\"批准但以 plan mode 运行\"),响应中可包含 `feedback` 字符串供队友修正后重新提交。不是简单的\"Lead 手动 review_plan 工具\"流程。\n\n**消息格式**:CC 的协议消息是结构化的 JSON(有 Zod schema 验证),教学版用简单的 type + metadata 字典。字段名也不统一:permission 用 `request_id`(`teammateMailbox.ts:453-462`),shutdown 和 plan approval 用 `requestId`(`teammateMailbox.ts:684-763`)。\n\n**执行门控**:CC 的队友有完整的 permission gating。未获批准的高风险操作会被拦截,不是可选的。教学版只演示了消息流程,没有实现执行拦截。\n\n**通用性**:教学版的一个 FSM(pending → approved | rejected)对应两种协议,这个简化完全正确。CC 的所有协议消息共用同一个 request id 关联机制。\n\n
\n\n\n" + "title": "s16: Autonomous Agents — 自己看板,自己认领", + "content": "# s16: Autonomous Agents — 自己看板,自己认领\n\ns01 → ... → s14 → s15 → `s16` → [s17](/zh/s17) → s18 → s19 → s20 → s21\n\n> *\"空闲时不只等消息,也主动寻找可以开始的工作。\"* — 共享任务板、自动发现与原子认领。\n>\n> **Harness 层**:自治 — Lead 管目标,队友从任务状态中发现下一步。\n\n---\n\n## 问题\n\ns15 的队友会在完成一项工作后进入 IDLE,等待 Lead 继续派发。如果任务板上已经有十个待办任务,Lead 仍然要逐个选择队友、发送消息,再等待结果。\n\n当任务已经被拆分,并且依赖关系也写进了任务板,谁来执行下一项工作不一定需要 Lead 再做一次模型决策。空闲队友可以直接读取共享状态,找到已经满足条件的任务并认领它。\n\n---\n\n## 解决方案\n\n![Autonomous Agents Overview](/course-assets/s16_autonomous_agents/autonomous-agents-overview.svg)\n\ns16 不改变 s15 的团队生命周期,只扩展 IDLE 状态:\n\n```text\ns15: WORK → result → IDLE → 等待消息\ns16: WORK → result → IDLE → 等待消息\n └→ 扫描任务板 → 认领 → WORK\n```\n\n新增两个函数:\n\n- `scan_unclaimed_tasks()`:找出当前可以开始的任务。\n- `claim_next_task(name)`:尝试原子认领其中一个任务。\n\n队友工具集同时增加 `list_tasks`、`claim_task` 和 `complete_task`,让认领后的工作能在同一个循环中闭合。\n\n---\n\n## 工作原理\n\n### 1. 发现任务和认领任务是两步\n\n扫描只读取状态,不修改任务:\n\n```python\ndef scan_unclaimed_tasks() -> list[Task]:\n return [\n task for task in list_tasks()\n if (\n task.status == \"pending\"\n and task.owner is None\n and can_start(task.id)\n )\n ]\n```\n\n一个任务必须同时满足三个条件:\n\n- 状态是 `pending`;\n- 还没有 `owner`;\n- `blockedBy` 中的任务都已经完成。\n\n扫描得到的只是候选列表。另一个队友可能在下一瞬间认领同一任务,因此不能把“扫描到”当成“已经拥有”。\n\n### 2. claim 在锁内完成读、检查和写入\n\n`claim_task()` 使用同一把 `task_lock` 包住完整的读改写过程:\n\n```python\ndef claim_task(task_id: str, owner: str) -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\" or task.owner:\n return \"Task is no longer available\"\n if not can_start(task_id):\n return \"Task is blocked\"\n\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task.id}\"\n```\n\n`claim_next_task()` 依次尝试候选任务。某次认领失败时,它会继续尝试下一个,而不是把失败误当成成功:\n\n```python\ndef claim_next_task(name: str) -> Task | None:\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n```\n\n扫描负责发现,claim 负责所有权。把两者分开后,多个队友可以同时观察任务板,但每个任务只能有一个最终 owner。\n\n### 3. 消息优先,任务扫描其次\n\n队友进入 IDLE 后,先等待一小段时间的收件箱事件:\n\n```python\nwhile True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n handle_messages(inbox)\n break\n\n task = claim_next_task(name)\n if task:\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}\"\n ),\n })\n break\n```\n\n这样安排有两个原因:\n\n- 关机、计划审批和 Lead 的直接消息应该尽快响应;\n- 没有消息时,空闲时间才用于寻找共享任务。\n\n如果既没有消息也没有可认领任务,队友继续保持 IDLE,不会因为一次扫描为空就退出。\n\n### 4. 自动认领后复用同一个 WORK 循环\n\n认领成功后,运行时把任务 ID、标题和描述写入队友 messages。对模型来说,它只是收到了一项新工作;文件、Shell、计划闸门、结果上报都继续使用 s15 的机制。\n\n```text\n任务板出现 ready task\n → 空闲队友扫描到候选\n → claim_task 写入 owner 和 in_progress\n → 任务进入队友 messages\n → WORK\n → complete_task\n → result + idle_notification\n → 再次扫描\n```\n\n自治不是再造一个 Agent Loop,而是给既有循环增加一个由共享状态触发的入口。\n\n---\n\n## 为什么这样设计\n\n**为什么不是 Lead 每次分配?**\n\n任务依赖已经编码在 `status`、`owner` 和 `blockedBy` 中。让 Lead 反复解释同一状态,只会增加协调轮次。\n\n**为什么不是扫描时直接改 owner?**\n\n扫描可能并发发生。把认领集中到带锁的函数中,所有调用方共享同一个所有权规则。\n\n**为什么不在没有任务时关闭队友?**\n\n暂时没有 ready task 可能只是因为依赖尚未完成。保持 IDLE 后,前置任务完成时队友可以自动接上后续工作。\n\n---\n\n## 相对 s15 的变化\n\n| 组件 | s15 | s16 |\n|---|---|---|\n| IDLE 行为 | 等待团队消息 | 先等消息,再扫描任务板 |\n| 任务分配 | Lead 明确派发 | 队友可自动认领 |\n| 任务所有权 | 调用方发起 claim | `task_lock` 保证认领原子性 |\n| 队友工具 | 文件、Shell、消息、计划 | 增加 list / claim / complete task |\n| 结果与关机 | `result`、`idle_notification`、shutdown 协议 | 保持不变 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s16_autonomous_agents/code.py\n```\n\n输入一个自然需求:\n\n```text\n请把后端改造拆到共享任务板,按依赖关系并行完成配置、认证和测试,\n保持现有接口兼容,并在最后汇总结果。\n```\n\nLead 提出团队方案后回复:\n\n```text\n开始吧\n```\n\n观察 `.tasks/` 中任务如何从 `pending` 进入 `in_progress` 和 `completed`,以及两个空闲队友是否会认领不同任务。带 `blockedBy` 的任务应该只在前置任务完成后出现为候选。\n\n---\n\n## 接下来\n\n队友已经能自己找到任务,但仍然在同一个工作目录里修改文件。下一章把任务所有权和工作目录绑定起来,让并行工作彼此隔离。\n\n下一章:[s17 Worktree Isolation](/zh/s17)。\n\n\n" }, { "version": "s16", "locale": "ja", - "title": "s16: Agent Teams — プロトコル実験:型付き協調", - "content": "# s16: Agent Teams — プロトコル実験:型付き協調\n\ns01 → ... → s14 → s15 → `s16` → [s17](/ja/s17) → s18 → s19 → s20 → s21 → s22\n> *\"チームメイト間には取り決めが必要\"* — request-response パターンが全てのネゴシエーションを駆動。\n>\n> **Harness 層**: プロトコル — Agent 間の構造化ハンドシェイク。\n\n> **モジュール 2/2:** s15 でチームメイトランタイムとメールボックスを構築した。この章で変えるのは協調契約だけであり、リクエスト、返信、相関 ID、状態遷移を扱う。\n\n---\n\n## 課題\n\ns15 のチームメイトは仕事ができるが、連携は緩い:Lead がメッセージを送り、チームメイトが返信するだけで、構造化されたプロトコルがない。2 つのシナリオで問題が露呈する:\n\n**シャットダウン**:Lead が Alice にシャットダウンを頼む。スレッドを強制終了すると、書きかけのファイルがディスクに残る。ハンドシェイクが必要:Lead がリクエストを送信、Alice が收尾後に確認。\n\n**計画承認**:Bob が認証モジュールのリファクタリングを提案、高リスク操作。Lead が Bob の計画を確認し、承認後に実行すべき。\n\nこれら 2 つのシナリオは同じ構造:一方がリクエストを送信、もう一方が返信、両者は同じ ID で関連付けられる。状態機械が追跡:pending → approved / rejected。\n\n---\n\n## ソリューション\n\n![Team Protocols Overview](/course-assets/s16_team_protocols/team-protocols-overview.ja.svg)\n\n教学版は前章までの Agent 能力の流れを受け継ぎ、S15 のチーム通信の上に構造化プロトコルを追加する。プロトコル機構に集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。追加:**ProtocolState**(リクエスト状態追跡)、**dispatch_message**(メッセージタイプ別ルーティング)、**match_response**(request_id でリクエストとレスポンスを関連付け、型検証付き)。\n\n2 つのプロトコル、1 つの仕組み:\n\n| プロトコル | 方向 | 用途 |\n|-----------|------|------|\n| shutdown_request / response | Lead → チームメイト | 丁寧なシャットダウンハンドシェイク |\n| plan_approval_request / response | チームメイト → Lead | 計画承認プロトコルの例 |\n\n> 教学版は計画承認の request-response メッセージフローをデモするが、実行ゲーティング(未承認時の bash/write_file 拦截)は未実装。真实 CC にはチームメイト向けの permission gating 機構がある。\n\n---\n\n## 仕組み\n\n### ProtocolState: リクエスト状態\n\n各プロトコルリクエストは、送信者、受信者、現在の状態、ペイロードを記録する状態レコードを作成:\n\n```python\n@dataclass\nclass ProtocolState:\n request_id: str # 一意 ID、例 \"req_004281\"\n type: str # \"shutdown\" | \"plan_approval\"\n sender: str # 送信者\n target: str # 受信者\n status: str # pending | approved | rejected\n payload: str # 計画テキストまたはシャットダウン理由\n created_at: float # タイムスタンプ\n\npending_requests: dict[str, ProtocolState] = {}\n```\n\nリクエスト送信時にレコードを作成、レスポンス受信時に `request_id` で該当レコードを見つけて状態を更新。\n\n### 4 ステッププロトコルフロー\n\nシャットダウンを例にした完全な流れ:\n\n```\n1. Lead がリクエスト送信\n req_id = new_request_id() # \"req_004281\"\n pending_requests[req_id] = ProtocolState(type=\"shutdown\", status=\"pending\", ...)\n BUS.send(\"lead\", \"alice\", \"shutdown_request\", metadata={\"request_id\": req_id})\n\n2. チームメイト受信 → dispatch\n inbox = BUS.read_inbox(\"alice\")\n msg_type = msg[\"type\"] # \"shutdown_request\"\n → handle_shutdown_request() にルーティング\n\n3. チームメイト返信\n BUS.send(\"alice\", \"lead\", \"shutdown_response\",\n metadata={\"request_id\": req_id, \"approve\": True})\n\n4. Lead がレスポンス受信 → match\n match_response(\"shutdown_response\", req_id, approve=True)\n pending_requests[req_id].status = \"approved\"\n```\n\n`request_id` はチェーン全体を貫く関連キー、リクエストが持ち出し、レスポンスが持ち帰る。\n\n### dispatch_message: タイプ別ルーティング\n\nチームメイトの inbox は通常メッセージとプロトコルメッセージの両方を受信。`handle_inbox_message` がメッセージタイプで振り分け:\n\n```python\ndef handle_inbox_message(name, msg, messages):\n msg_type = msg.get(\"type\", \"message\")\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down.\", \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return True # ループ停止\n\n if msg_type == \"plan_approval_response\":\n approve = msg[\"metadata\"].get(\"approve\", False)\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved]\" if approve else \"[Plan rejected]\"})\n return False # 継続\n```\n\n新しいプロトコルタイプの追加は新しい `if` 分岐を追加するだけ。\n\n### match_response: 型検証\n\n`match_response` は `request_id` で状態を見つけるだけでなく、レスポンスタイプがリクエストタイプと一致するか検証:\n\n```python\ndef match_response(response_type, request_id, approve):\n state = pending_requests.get(request_id)\n if not state:\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n return # タイプ不一致、スキップ\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n return\n if state.status != \"pending\":\n return # 既に解決済み、重複をスキップ\n state.status = \"approved\" if approve else \"rejected\"\n```\n\nshutdown_response が誤って plan_approval リクエストを承認することはない。\n\n### 統一 inbox コンシューマ:consume_lead_inbox\n\n`check_inbox` ツールとメインループ末尾の両方が同じ `consume_lead_inbox()` 関数を呼び出す。プロトコルメッセージを先にルーティングしてから残りの内容を返す。メッセージが消費されてもプロトコル状態が更新されない問題を防ぐ:\n\n```python\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n```\n\nメインループは inbox メッセージを `history` に注入し、LLM が確認して反応できるようにする。\n\n### チームメイト idle loop:終了ではなく待機\n\ns15 のチームメイトは 10 ラウンドで終了。s16 のチームメイトは LLM が非 tool_use を返した後 idle 待機に入る:inbox をポーリング、shutdown_request に応答して終了、または新メッセージで作業継続。\n\n```\nLLM が非 tool_use を返す\n → idle: 毎秒 inbox をポーリング\n → shutdown_request 受信 → shutdown_response 返信 → 終了\n → 新メッセージ受信 → messages に注入 → LLM ターン継続\n```\n\n教学版は Lead への idle_notification を省略。真实 CC は idle 時に `idle_notification` を送信、Lead はチームメイトが空いていることを知り、新しいタスクを割り当て可能。\n\n### 組み合わせて実行\n\n```\n1. Lead: \"Alice にファイルを作成させ、その後シャットダウン\"\n2. Lead → spawn_teammate(\"alice\", \"backend\", \"config.py を作成\")\n3. alice スレッド起動 → write_file(\"config.py\", \"...\") → 完了 → idle\n4. Lead → request_shutdown(\"alice\")\n → BUS.send(\"shutdown_request\", {request_id: \"req_000142\"})\n5. alice idle ポーリング受信 → handle_shutdown_request\n → BUS.send(\"shutdown_response\", {request_id: \"req_000142\", approve: True})\n6. Lead consume_lead_inbox → match_response(\"req_000142\", approve=True)\n → pending_requests[\"req_000142\"].status = \"approved\"\n → inbox メッセージが history に注入、LLM がシャットダウン結果を確認\n```\n\nシャットダウンハンドシェイク完了:リクエスト → 確認 → シャットダウン。各ステップは `request_id` で追跡。\n\n---\n\n## s15 からの変更\n\n| コンポーネント | 変更前 (s15) | 変更後 (s16) |\n|--------------|------------|------------|\n| 連携方法 | 緩いテキストメッセージ | 構造化 request-response プロトコル |\n| リクエスト追跡 | なし | ProtocolState + pending_requests dict |\n| メッセージルーティング | 全てテキストとして処理 | dispatch_message がタイプ別にルーティング |\n| シャットダウン | 自然終了またはスレッド強制終了 | request_id ハンドシェイク機構 |\n| 計画承認 | なし | メッセージフローの例(実行ゲーティングなし) |\n| 新規メッセージ型 | message, result | + shutdown_request/response, plan_approval_request/response |\n| チームメイトライフサイクル | 最大 10 ラウンド | idle loop(inbox メッセージを待機) |\n| Lead inbox | check_inbox とメインループが別々に読み取り | 統一 consume_lead_inbox |\n| Lead ツール | 14 (s15) | 14(コアツールセットに request_shutdown、request_plan、review_plan を追加) |\n| チームメイトツール | 4 (s15) | + submit_plan (5) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s16_team_protocols/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Spawn alice as a backend dev. Ask her to create a file. Then request her shutdown.`\n2. `Spawn bob with a refactoring task. Have him submit a plan first. Then review and approve it.`\n\n観察ポイント:シャットダウンハンドシェイクは完了しているか(リクエスト → 確認 → シャットダウン)?`pending_requests` の状態は正しく遷移しているか?`request_id` はリクエストとレスポンス間で一貫しているか?idle チームメイトは shutdown_request を受信できるか?\n\n---\n\n## 次の章\n\ns15-s16 では、Lead が各チームメイトにタスクを割り当てる必要がある。\"Alice はこれ、Bob はあれ\"。ボードに 10 個の未認領タスクがあれば、Lead が手動で assign しなければならない。\n\nチームメイトが自分でボードを見て認領できたらどうか?Lead はタスクを作成するだけで、チームメイトが自分で発見、認領、完了する。\n\ns17 Autonomous Agents → チームメイトの自己組織化、リーダーの割り当て不要。\n\n
\nCC ソースコード深掘り\n\nCC のチームプロトコル実装(`teammateMailbox.ts`、1184 行)は教学版と同じコア構造:request_id + approve/reject の request-response パターン。違いは以下の通り:\n\n**シャットダウンプロトコル**:CC のシャットダウンは三方向通信(`teammateMailbox.ts:720-763`、`SendMessageTool.ts:268-430`)。Lead が `shutdown_request` を送信、チームメイトが `shutdown_approved`(または理由付き `shutdown_rejected`)で返信、システムが `teammate_terminated` で全関係者に通知。確認後、システムが自動的に pane(tmux/iTerm2)をクリーンアップ、タスクを unassign、team config からメンバーを削除(`useInboxPoller.ts:677-800`)。教学版は `shutdown_response` で統一命名、真实源码は `shutdown_approved` と `shutdown_rejected` の 2 つの独立したメッセージ型に分割。\n\n**計画承認**:真实源码では plan approval request は `ExitPlanModeV2Tool.ts:263-312` で plan-mode-required チームメイトが plan mode を終了する際に生成される。`useInboxPoller.ts:599-661` は現在自動的に approval を書き戻し、リクエストを Lead にコンテキスト(regular message)として渡す。`SendMessageTool.ts:434-518` は明示的な approve/reject response 能力を保持、承認時に同時に `permissionMode` を設定可能(例:\"承認するが plan mode で実行\")、レスポンスにはチームメイトが修正して再提出するための `feedback` 文字列を含めることができる。単純な「Lead が手動で review_plan ツールを使う」フローではない。\n\n**メッセージ形式**:CC のプロトコルメッセージは構造化 JSON(Zod schema 検証付き)、教学版はシンプルな type + metadata dict。フィールド名も統一されていない:permission は `request_id`(`teammateMailbox.ts:453-462`)、shutdown と plan approval は `requestId`(`teammateMailbox.ts:684-763`)。\n\n**実行ゲーティング**:CC のチームメイトには完全な permission gating がある。未承認の高リスク操作は拦截され、オプションではない。教学版はメッセージフローのみをデモ。\n\n**汎用性**:教学版の 1 つの FSM(pending → approved | rejected)が 2 つのプロトコルに対応する簡略化は正しい。CC の全プロトコルメッセージは同じ request id 関連機構を共有。\n\n
\n\n\n" + "title": "s16: Autonomous Agents — ボードを見て、自分で Claim する", + "content": "# s16: Autonomous Agents — ボードを見て、自分で Claim する\n\ns01 → ... → s14 → s15 → `s16` → [s17](/ja/s17) → s18 → s19 → s20 → s21\n\n> *「IDLE はメッセージを待つだけでなく、開始可能な仕事を探す時間でもある。」* — 共有タスクボード、自動発見、原子的な Claim。\n>\n> **Harness レイヤー**:自律 — Lead は目標を管理し、チームメイトは共有状態から次の仕事を見つける。\n\n---\n\n## 問題\n\ns15 のチームメイトは作業後に IDLE へ入り、Lead から次の依頼を待つ。タスクボードに 10 件の pending task があっても、Lead はチームメイトを選び、メッセージを送り、結果を待つ操作を 10 回繰り返す必要がある。\n\n仕事がすでに分解され、依存関係もタスクボードに記録されているなら、次の ready task の割り当てに毎回モデル判断は要らない。IDLE のチームメイト自身が共有状態を読み、前提条件を満たした仕事を Claim できる。\n\n---\n\n## 解決策\n\n![Autonomous Agents Overview](/course-assets/s16_autonomous_agents/autonomous-agents-overview.ja.svg)\n\ns16 は s15 のチームライフサイクルを変えず、IDLE の動作だけを拡張する:\n\n```text\ns15: WORK → result → IDLE → メッセージを待つ\ns16: WORK → result → IDLE → メッセージを待つ\n └→ ボード走査 → Claim → WORK\n```\n\n追加する関数は 2 つ:\n\n- `scan_unclaimed_tasks()`:現在開始できるタスクを探す。\n- `claim_next_task(name)`:候補の 1 件を原子的に Claim する。\n\nチームメイトのツールにも `list_tasks`、`claim_task`、`complete_task` を加え、同じループ内で作業を完了できるようにする。\n\n---\n\n## 仕組み\n\n### 1. 発見と所有権を分離する\n\n走査は状態を変更せず、読み取りだけを行う:\n\n```python\ndef scan_unclaimed_tasks() -> list[Task]:\n return [\n task for task in list_tasks()\n if (\n task.status == \"pending\"\n and task.owner is None\n and can_start(task.id)\n )\n ]\n```\n\n候補は `pending` で、owner がなく、すべての `blockedBy` が完了していなければならない。\n\nただし候補一覧は一時点のスナップショットにすぎない。直後に別のチームメイトが同じタスクを Claim する可能性があるため、「発見した」と「所有した」を同じ意味にしてはいけない。\n\n### 2. Claim はロック内で読み取り、確認、書き込みを行う\n\n`claim_task()` は状態遷移全体を `task_lock` で保護する:\n\n```python\ndef claim_task(task_id: str, owner: str) -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\" or task.owner:\n return \"Task is no longer available\"\n if not can_start(task_id):\n return \"Task is blocked\"\n\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task.id}\"\n```\n\n`claim_next_task()` は成功する候補が見つかるまで順に試す:\n\n```python\ndef claim_next_task(name: str) -> Task | None:\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n```\n\n複数のチームメイトが同時にボードを観察しても、最終的な owner は Claim 関数によって 1 人に決まる。\n\n### 3. メッセージを優先し、その後にタスクを探す\n\nIDLE に入ったチームメイトは、まず短時間だけ受信イベントを待つ:\n\n```python\nwhile True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n handle_messages(inbox)\n break\n\n task = claim_next_task(name)\n if task:\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}\"\n ),\n })\n break\n```\n\nこの順序にする理由は明確だ:\n\n- shutdown、計画承認、Lead からの直接メッセージにはすぐ応答する。\n- メッセージがない IDLE 時間だけを、共有タスクの探索に使う。\n\nメッセージも ready task もなければ IDLE を続ける。候補が空なのは、依存タスクがまだ完了していないだけかもしれない。\n\n### 4. Claim 後は同じ WORK ループを再利用する\n\nClaim に成功すると、ランタイムはタスク ID、件名、説明をチームメイトの messages へ追加する。ファイルツール、Shell、計画ゲート、結果通知、終了プロトコルはすべて s15 の仕組みをそのまま使う。\n\n```text\nready task が現れる\n → IDLE のチームメイトが発見\n → claim_task が owner と in_progress を記録\n → タスクが messages に入る\n → WORK\n → complete_task\n → result + idle_notification\n → 再び走査\n```\n\n自律のために別の Agent Loop を作る必要はない。既存ループへ共有状態から入る入口を追加すればよい。\n\n---\n\n## この設計を選ぶ理由\n\n**Lead が毎回割り当てないのはなぜか。**\n\n`status`、`owner`、`blockedBy` が実行可能性をすでに表している。同じ状態を Lead に毎回解釈させても、調整ターンが増えるだけである。\n\n**走査時に owner を設定しないのはなぜか。**\n\n走査は並行実行され得る。所有権変更を 1 つのロック付き関数に集めれば、すべての呼び出し元が同じ規則に従う。\n\n**ready task がない時に終了しないのはなぜか。**\n\n依存タスクが完了すれば、後続タスクが ready になる。IDLE を維持すれば、その瞬間に次の仕事を引き継げる。\n\n---\n\n## s15 からの変更\n\n| コンポーネント | s15 | s16 |\n|---|---|---|\n| IDLE | チームメッセージを待つ | メッセージ待機後にボードを走査 |\n| 割り当て | Lead が明示的に送る | チームメイトが自動 Claim 可能 |\n| 所有権 | 呼び出し元が Claim | `task_lock` で Claim を原子的にする |\n| チームメイトツール | ファイル、Shell、メッセージ、計画 | list / claim / complete task を追加 |\n| 結果と終了 | `result`、`idle_notification`、shutdown protocol | 変更なし |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s16_autonomous_agents/code.py\n```\n\n通常の要求を入力する:\n\n```text\nバックエンド改修を共有タスクボードへ分解し、依存関係が許す範囲で\n設定、認証、テストを並行実行してください。既存インターフェースを\n維持し、最後に結果をまとめてください。\n```\n\nLead がチーム案を示したら、次のように返す:\n\n```text\n始めてください\n```\n\n`.tasks/` のタスクが `pending`、`in_progress`、`completed` と変化する様子を確認する。2 人の IDLE チームメイトは別々のタスクを Claim し、`blockedBy` のあるタスクは前提完了後にだけ候補になるはずだ。\n\n---\n\n## 次へ\n\nチームメイトは仕事を自分で見つけられるようになったが、まだ同じディレクトリでファイルを変更する。次のセッションではタスク所有権を分離された作業ディレクトリへ結び付ける。\n\n次へ:[s17 Worktree Isolation](/ja/s17)。\n\n\n" }, { "version": "s17", "locale": "en", - "title": "s17: Autonomous Agents — Check the Board, Claim the Task", - "content": "# s17: Autonomous Agents — Check the Board, Claim the Task\n\ns01 → ... → s15 → s16 → `s17` → [s18](/en/s18) → s19 → s20 → s21 → s22\n\n> *\"Check the board, claim the task\"* — poll when idle, work when found.\n>\n> **Harness Layer**: Autonomy — Self-organizing teammates, no leader assignment needed.\n\n> **Core vs optional:** idle work discovery and atomic claiming are the lesson's core. Identity re-injection is an advanced teaching workaround and may be skipped on a first pass.\n\n---\n\n## The Problem\n\ns16's teammates can communicate and handshake shutdown. But each teammate waits for Lead to assign tasks — with 10 unclaimed tasks on the board, Lead has to manually assign 10 times. This doesn't scale. Teammates should check the task board themselves, claim unowned tasks, and look for the next one when done.\n\n---\n\n## The Solution\n\n![Autonomous Agents Overview](/course-assets/s17_autonomous_agents/autonomous-agents-overview.en.svg)\n\nCarries forward S16's teaching-version MessageBus and protocol tools. This chapter adds: **idle_poll** (poll every 5 seconds when idle), **scan_unclaimed_tasks** (scan the board for claimable tasks), **auto-claim** (claim on sight, no Lead needed).\n\nTeammate lifecycle expands from two phases to three:\n\n| Phase | Behavior | Exit condition |\n|-------|----------|----------------|\n| WORK | inbox → LLM → tool loop | `stop_reason != tool_use` |\n| IDLE | 5s poll inbox + task board | 60s timeout |\n| SHUTDOWN | Send summary, exit | — |\n\n---\n\n## How It Works\n\n### idle_poll: Idle Polling\n\nAfter completing a task, the teammate doesn't exit. It enters the IDLE phase — checking every 5 seconds for new work:\n\n```python\nIDLE_POLL_INTERVAL = 5 # seconds\nIDLE_TIMEOUT = 60 # seconds\n\ndef idle_poll(name, messages, role) -> str:\n \"\"\"Return 'work', 'shutdown', or 'timeout'.\"\"\"\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n\n # ① Check inbox (priority)\n inbox = BUS.read_inbox(name)\n if inbox:\n # shutdown_request handled immediately\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n # ... reply shutdown_response\n return \"shutdown\"\n # Regular messages: inject into context, return to WORK\n messages.append(...)\n return \"work\"\n\n # ② Scan task board\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task = unclaimed[0]\n result = claim_task(task[\"id\"], name)\n if \"Claimed\" in result:\n messages.append(...)\n return \"work\"\n return \"timeout\"\n```\n\nInbox takes priority (may contain protocol messages like shutdown_request), task board second. A shutdown_request received during IDLE is dispatched immediately — no need to wait for the next WORK phase.\n\n### scan_unclaimed_tasks: Scan the Task Board\n\nFind tasks that are pending, unowned, with all dependencies completed (`can_start`):\n\n```python\ndef scan_unclaimed_tasks() -> list[dict]:\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n```\n\nThree conditions: must be pending, no owner, all blockedBy dependencies completed. `can_start` checks dependency task status — having dependencies doesn't mean the task can't start, only unresolved dependencies block it. Teaching version picks the first by filename; CC uses file locks to prevent multiple teammates from claiming the same task.\n\n### claim_task: Owner Check\n\nAuto-claim checks the claim result, not treating failure as success:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task.id} ({task.subject})\"\n```\n\nTeaching version has no file locks, so concurrent claims may still race. But the `task.owner` check avoids the most obvious \"last writer wins\" problem. CC uses `proper-lockfile` to protect task files, with `claimTask` doing read-modify-write inside a file lock (`utils/tasks.ts:541-612`).\n\n### Teammate Lifecycle: WORK → IDLE → SHUTDOWN\n\ns16's teammates exit after finishing. s17 adds the IDLE phase — teammates cycle through WORK → IDLE in an outer loop:\n\n```python\n# Outer loop: WORK → IDLE cycle\nwhile True:\n # WORK phase: inner loop (max 10 LLM rounds)\n for _ in range(10):\n # Check inbox, dispatch protocol, call LLM, execute tools\n ...\n if response.stop_reason != \"tool_use\":\n break # WORK phase ends\n\n # IDLE phase\n idle_result = idle_poll(name, messages, role)\n if idle_result == \"shutdown\":\n break\n if idle_result == \"timeout\":\n break # 60s timeout → SHUTDOWN\n\n# SHUTDOWN: send summary to Lead\nBUS.send(name, \"lead\", summary, \"result\")\n```\n\nKey design:\n- **Outer while True**: WORK and IDLE alternate until timeout or shutdown request\n- **Inner for 10**: WORK phase caps at 10 LLM rounds (prevents infinite loops)\n- **IDLE timeout 60s**: 12 polls × 5s = 60s. Timeout sends summary and exits\n- **shutdown_request works in both phases**: WORK phase dispatches via `handle_inbox_message`; IDLE phase's `idle_poll` checks and replies directly\n\n### Advanced (Optional): Identity Re-injection\n\nAfter autoCompact (s08), a teammate's messages list may be compressed into a summary. On each new WORK phase entry, check:\n\n```python\nif len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n```\n\nShort messages suggest compression happened — re-inject identity. In real CC, context compaction preserves the system prompt; the teaching version's simplified implementation needs manual handling.\n\n### consume_lead_inbox: Unified Inbox Consumer\n\nBoth the `check_inbox` tool and the main loop call the same `consume_lead_inbox()` function: route protocol responses to update state first, then inject all messages into Lead's conversation history. Teammates' summaries and results don't just print to terminal — Lead's LLM can see them and coordinate next steps.\n\n### Putting It Together\n\n```\n1. Lead: \"Build the backend — too many tasks, let teammates self-claim\"\n2. Lead → create_task(\"Create database schema\")\n3. Lead → create_task(\"Write API routes\")\n4. Lead → create_task(\"Write unit tests\")\n5. Lead → spawn_teammate(\"alice\", \"backend\", \"You are a backend developer\")\n6. Lead → spawn_teammate(\"bob\", \"backend\", \"You are a backend developer\")\n\n7. alice thread starts → WORK: no initial inbox → spins → IDLE\n8. bob thread starts → WORK: no initial inbox → spins → IDLE\n\n9. alice IDLE poll 1 → scan_unclaimed → finds \"Create database schema\"\n10. alice → claim_task → \"Create database schema\" → back to WORK\n11. bob IDLE poll 1 → scan_unclaimed → finds \"Write API routes\"\n12. bob → claim_task → \"Write API routes\" → back to WORK\n\n13. alice WORK: write_file(\"schema.sql\", ...) → complete_task → WORK ends\n14. alice IDLE → scan → \"Write unit tests\" → claim → WORK\n15. alice WORK: write_file(\"test_api.py\", ...) → complete_task → WORK ends\n16. alice IDLE → 60s no new tasks → SHUTDOWN\n\n17. bob similar flow → done → SHUTDOWN\n18. Lead consume_lead_inbox → sees alice and bob's summaries\n```\n\nTwo teammates claim and work in parallel. Lead only creates tasks and spawns teammates — no manual assignment needed.\n\n---\n\n## Changes from s16\n\n| Component | Before (s16) | After (s17) |\n|-----------|-------------|-------------|\n| Task assignment | Lead manually assigns | Teammates auto-claim (can_start checks deps) |\n| Teammate state | WORK → IDLE (1s inbox poll) → WORK / SHUTDOWN | WORK → IDLE (5s inbox + task board poll, 60s timeout) → WORK / SHUTDOWN |\n| claim_task | No owner check | Rejects tasks that already have an owner |\n| IDLE phase shutdown | Exits after receiving shutdown_request | Dispatches shutdown immediately and exits |\n| Lead inbox | consume_lead_inbox routes protocol responses and injects into context | Reuses consume_lead_inbox mechanism |\n| New functions | consume_lead_inbox already exists | idle_poll, scan_unclaimed_tasks (reuses consume_lead_inbox) |\n| Identity persistence | System prompt only | Auto re-inject after compression |\n| Lead tools | 14 | 14 (unchanged) |\n| Teammate tools | 5 | 8 (+ list_tasks, claim_task, complete_task) |\n| Teammate exit | WORK ends → enters IDLE, waits for shutdown_request (no timeout) | Exits after 60s idle timeout or receiving shutdown_request |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s17_autonomous_agents/code.py\n```\n\nTry this prompt:\n\n`Create 3 tasks on the board, then spawn alice and bob. Watch them auto-claim and work.`\n\nWhat to observe: Do teammates auto-claim unassigned tasks? Are tasks with blockedBy dependencies claimed only after their dependencies complete? Does idle timeout trigger shutdown? Does a shutdown_request in IDLE phase get an immediate response? How do task states change in `.tasks/`?\n\n---\n\n## What's Next\n\nTeammates self-organize now. But Alice and Bob both work in the same directory — Alice edits `config.py`, Bob also edits `config.py`, overwriting each other.\n\ns18 Worktree Isolation → Each task gets its own working directory, no conflicts.\n\n
\nDeep Dive into CC Source\n\n> Teaching note: This chapter's idle_poll + auto-claim mechanism is a teaching design, using a unified polling function to demonstrate \"find work when idle.\" CC's actual implementation combines multiple mechanisms, but shares the same goal — reducing Lead's manual assignment burden.\n\n### 1. CC's Idle Mechanism: Combined Approach, Not Single Polling\n\nTeaching version uses a single `idle_poll()` to handle both inbox checking and task claiming during idle. CC's actual implementation combines four mechanisms:\n\n**idle_notification**: After completing a round of work, `sendIdleNotification()` (`inProcessRunner.ts:569-589`) sends an idle notification to Lead. Lead knows the teammate is available and can assign new tasks or request shutdown.\n\n**mailbox polling**: `waitForNextPromptOrShutdown()` (`inProcessRunner.ts:689-868`) is a **500ms polling loop** that continuously checks three sources: pending user messages, mailbox file messages, and task list. Shutdown requests are prioritized (`inProcessRunner.ts:768-804`), preventing starvation by regular messages.\n\n**task watcher**: `useTaskListWatcher` (`hooks/useTaskListWatcher.ts:34-189`) uses `fs.watch()` to monitor the `.claude/tasks/` directory with 1-second debounce, triggering checks when new tasks are created or dependencies unblock. The dependency check (`L197-207`) verifies \"no incomplete tasks in blockedBy\", not \"blockedBy is empty\".\n\n**active claiming**: The polling loop also calls `tryClaimNextTask()` (`inProcessRunner.ts:853-860`) — actively claiming tasks from the task list while waiting. So \"teammates don't actively poll for tasks\" is inaccurate; CC has both passive notification and active claiming.\n\n### 2. Task Claiming: File Locks + Atomic Operations\n\n`claimTask()` (`utils/tasks.ts:541-612`) uses `proper-lockfile` task-level locks, performing read-check-modify-write within the lock. Checks: owner already exists (`L575-576`), already completed (`L580-581`), unresolved blockers in blockedBy (`L585-594`). `claimTaskWithBusyCheck()` (`utils/tasks.ts:614-692`) uses task-list level locks, making busy check and claim atomic to avoid TOCTOU.\n\n`findAvailableTask()` (`inProcessRunner.ts:595-604`) checks \"all blockedBy completed\" using `task.blockedBy.every(id => !unresolvedTaskIds.has(id))`. `tryClaimNextTask()` (`inProcessRunner.ts:624-657`) updates status to `in_progress` after claiming, so the UI immediately reflects the change.\n\n### 3. Teaching Version vs CC Comparison\n\n| Dimension | Teaching (s17) | CC |\n|-----------|----------------|-----|\n| Idle mechanism | idle_poll unified polling (5s) | idle_notification + 500ms mailbox polling + task watcher |\n| Task discovery | scan_unclaimed_tasks (polling) | useTaskListWatcher (file watching) + tryClaimNextTask (active polling) |\n| Dependency check | can_start (all blockedBy completed) | findAvailableTask (same semantics) |\n| Concurrency safety | Owner check (no file lock) | proper-lockfile task lock + task-list lock |\n| Shutdown handling | IDLE dispatches directly, WORK via handle_inbox_message | 500ms polling loop prioritizes shutdown_request |\n| Timeout exit | 60s with no new tasks | No fixed timeout, Lead manual shutdown |\n| Identity persistence | Messages length detection | Context compaction preserves system prompt |\n| Claim failure handling | Check return value, skip on failure | File locks guarantee atomicity |\n\nTeaching version's `idle_poll()` merges CC's four mechanisms into one polling function — a reasonable simplification since the core semantics (find work when idle, claim after deps resolve, prioritize shutdown) are consistent.\n\n
\n\n\n" + "title": "s17: Worktree Isolation — Separate Directories, No Conflicts", + "content": "# s17: Worktree Isolation — Separate Directories, No Conflicts\n\ns01 → ... → s15 → s16 → `s17` → [s18](/en/s18) → s19 → s20 → s21\n\n> *\"Separate directories, no conflicts\"* — Tasks own the goal, worktrees own the directory, bound by ID.\n>\n> **Harness Layer**: Isolation — Parallel execution in separate directories.\n\n---\n\n## The Problem\n\nIn s16, Alice and Bob both work in the same directory. Alice's task is \"refactor auth module\", Bob's task is \"refactor UI login page\".\n\nAlice calls `write_file(\"config.py\", ...)`. Bob also calls `write_file(\"config.py\", ...)`. Both edit the same file, overwriting each other. And there's no clean rollback — you can't tell whose changes are whose.\n\ns15-s16 solved \"who does what\" (task system) and \"how to communicate\" (message bus), but not \"where to work\".\n\n---\n\n## The Solution\n\n![Worktree Overview](/course-assets/s17_worktree_isolation/worktree-overview.en.svg)\n\nGit worktree lets you create multiple independent working directories in the same repo, each with its own branch. Alice works in `.worktrees/auth-refactor/`, Bob in `.worktrees/ui-login/` — no conflicts.\n\nCarries forward s16's MessageBus, protocols, and autonomous claiming. This chapter adds:\n\n| Capability | Purpose |\n|------------|---------|\n| create_worktree | Create isolated directory + branch for a task |\n| bind_task_to_worktree | Bind task and directory (no status change) |\n| remove_worktree / keep_worktree | Cleanup or preserve after completion |\n| validate_worktree_name | Reject path traversal and illegal characters |\n\n---\n\n## How It Works\n\n### Creation: Task-Worktree Binding\n\n```python\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n validate_worktree_name(name) # Only [A-Za-z0-9._-]{1,64}\n path = WORKTREES_DIR / name\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n return f\"Worktree '{name}' created at {path}\"\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name # Write worktree field only\n save_task(task) # Status stays pending, waits for teammate claim\n```\n\nBinding rule: one task binds to one worktree. Binding does NOT change task status — the task stays `pending`, and advances to `in_progress` only when a teammate claims it. This way Lead can pre-create tasks and worktrees, and teammates naturally claim worktree-bound tasks during idle.\n\n### Teammate Tool Cwd Switching\n\nEach teammate keeps a `wt_ctx` dictionary with its current worktree path. When a teammate claims a task bound to a worktree, the runtime updates `wt_ctx`; that teammate's `bash`, `read_file`, and `write_file` calls then run in the worktree directory:\n\n```python\n# Inside teammate thread\nwt_ctx = {\"path\": None}\n\ndef _run_claim_task(task_id):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n return result\n\ndef _run_bash(command):\n return run_bash(command, cwd=wt_ctx[\"path\"]) # Execute in worktree\n```\n\n### Cleanup: Keep or Remove\n\nAfter task completion, two choices:\n\n```python\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n # Safety check: refuse by default if changes exist\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files > 0 or commits > 0:\n return \"Has uncommitted changes. Use discard_changes=true to force, or keep_worktree\"\n ok, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok:\n return \"Remove failed\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n\ndef keep_worktree(name: str) -> str:\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n```\n\nKeep = preserve branch for manual review and merge. Remove = refuse by default if uncommitted changes; requires `discard_changes=true` to confirm. Does NOT auto-complete task — task completion is triggered explicitly by the teammate's `complete_task`.\n\n### Event Log: Auditable\n\nEach lifecycle operation writes to a log for auditing:\n\n```python\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n # append to .worktrees/events.jsonl\n```\n\nEvent types are `create`, `remove`, and `keep`. The log supports manual auditing; a recovery flow can rebuild the current set from `git worktree list`.\n\n### run_git: Returns Success/Failure\n\n```python\ndef run_git(args: list[str]) -> tuple[bool, str]:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR, ...)\n return r.returncode == 0, output\n```\n\n`create_worktree` and `remove_worktree` only write event logs after successful git commands, ensuring logs reflect actual state.\n\n---\n\n## Changes from s16\n\n| Component | Before (s16) | After (s17) |\n|-----------|-------------|-------------|\n| Working directory | All agents share WORKDIR | Each task can bind to a git worktree |\n| Task data | id/subject/status/owner/blockedBy | + worktree field |\n| Teammate tool cwd | Always WORKDIR | Auto-switches when claiming worktree-bound task |\n| New functions | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name |\n| Worktree safety | None | Name validation + refuse removal with changes |\n| Event log | None | events.jsonl lifecycle auditing |\n| Lead tools | Team and task tools | + create_worktree, remove_worktree, keep_worktree |\n| Teammate tools | Task and file tools | Same tools; bash/read/write use the claimed worktree cwd |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s17_worktree_isolation/code.py\n```\n\nTry this prompt:\n\n`Refactor the authentication module and the login page in parallel without letting the changes interfere with each other.`\n\nWhat to observe: Do both worktrees show different branches in `git status`? After claiming a worktree-bound task, does the teammate's bash run in the worktree directory? Does `remove_worktree` refuse when there are changes? Is task status still `pending` after binding?\n\n---\n\n## What's Next\n\nAgent teams can now self-organize in isolated workspaces. But Agent capabilities are limited to the tools we wrote — bash, read, write, task...\n\nWhat if users already have their own tools? Like an internal Jira API, or a custom deployment system?\n\ns18 MCP Plugin → Give Agent a plugin system. External tools connect via standard protocol; Agent doesn't need to know who wrote them.\n\n\n\n" }, { "version": "s17", "locale": "zh", - "title": "s17: Autonomous Agents — 自己看板,自己认领", - "content": "# s17: Autonomous Agents — 自己看板,自己认领\n\ns01 → ... → s15 → s16 → `s17` → [s18](/zh/s18) → s19 → s20 → s21 → s22\n\n> *\"自己看板,自己认领\"* — 空闲时轮询,有活就干。\n>\n> **Harness 层**: 自治 — 队友自组织,不依赖 Lead 分配。\n\n> **核心与选学:** 空闲发现工作与原子认领是本章核心;身份重注入只是教学版的进阶补丁,第一次学习可以跳过。\n\n---\n\n## 问题\n\ns16 的队友能通信、能握手关机。但每个队友等 Lead 分配任务——如果任务看板上有 10 个未认领任务,Lead 得手动 assign 10 次。这不能扩展。队友应该自己看任务看板,发现没人做的任务就认领,做完再找下一个。\n\n---\n\n## 解决方案\n\n![Autonomous Agents Overview](/course-assets/s17_autonomous_agents/autonomous-agents-overview.svg)\n\n沿用 S16 的教学版 MessageBus 和协议工具。本章新增:**idle_poll**(空闲时每 5 秒轮询一次)、**scan_unclaimed_tasks**(扫描看板上可认领的任务)、**自动认领**(找到任务就 claim,不用 Lead 操心)。\n\n队友生命周期从两阶段变成三阶段:\n\n| 阶段 | 行为 | 退出条件 |\n|------|------|---------|\n| WORK | inbox → LLM → 工具循环 | `stop_reason != tool_use` |\n| IDLE | 每 5s 轮询 inbox + 任务板 | 60s 超时 |\n| SHUTDOWN | 发 summary,退出 | — |\n\n---\n\n## 工作原理\n\n### idle_poll: 空闲轮询\n\n队友完成当前任务后不退出,进入 IDLE 阶段——每 5 秒检查一次有没有新工作:\n\n```python\nIDLE_POLL_INTERVAL = 5 # seconds\nIDLE_TIMEOUT = 60 # seconds\n\ndef idle_poll(name, messages, role) -> str:\n \"\"\"Return 'work', 'shutdown', or 'timeout'.\"\"\"\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n\n # ① 检查收件箱(优先)\n inbox = BUS.read_inbox(name)\n if inbox:\n # shutdown_request 立即处理\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n # ... 回复 shutdown_response\n return \"shutdown\"\n # 普通消息注入上下文,回到 WORK\n messages.append(...)\n return \"work\"\n\n # ② 扫描任务看板\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task = unclaimed[0]\n result = claim_task(task[\"id\"], name)\n if \"Claimed\" in result:\n messages.append(...)\n return \"work\"\n return \"timeout\"\n```\n\ninbox 优先(可能包含 shutdown_request 等协议消息),任务板其次。IDLE 阶段收到 shutdown_request 会直接回复并退出,不等到下一轮 WORK。\n\n### scan_unclaimed_tasks: 扫描任务看板\n\n找 pending 状态、无 owner、所有依赖已完成(`can_start`)的任务:\n\n```python\ndef scan_unclaimed_tasks() -> list[dict]:\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n```\n\n三个条件:必须是 pending、没有 owner、所有 blockedBy 依赖已完成。`can_start` 检查依赖任务的状态——有依赖不代表不能做,只有被未完成的任务阻塞才不能做。教学版按文件名排序取第一个;CC 用文件锁防止多个队友同时认领同一个任务。\n\n### claim_task: owner 检查\n\n自动认领时检查 claim 结果,不把失败当成功:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task.id} ({task.subject})\"\n```\n\n教学版没有文件锁,并发认领可能出现竞争。但至少 `task.owner` 检查避免了最明显的\"后写覆盖\"问题。CC 用 `proper-lockfile` 保护任务文件,`claimTask` 在文件锁内完成读-改-写(`utils/tasks.ts:541-612`)。\n\n### 队友生命周期: WORK → IDLE → SHUTDOWN\n\ns16 的队友做完任务就退出。s17 加了 IDLE 阶段,队友在外层循环中反复 WORK → IDLE:\n\n```python\n# Outer loop: WORK → IDLE cycle\nwhile True:\n # WORK phase: 内层循环(最多 10 轮 LLM 调用)\n for _ in range(10):\n # 检查 inbox、处理协议消息、调 LLM、执行工具\n ...\n if response.stop_reason != \"tool_use\":\n break # WORK 阶段结束\n\n # IDLE phase\n idle_result = idle_poll(name, messages, role)\n if idle_result == \"shutdown\":\n break\n if idle_result == \"timeout\":\n break # 60s 超时 → SHUTDOWN\n\n# SHUTDOWN: 发 summary 给 Lead\nBUS.send(name, \"lead\", summary, \"result\")\n```\n\n关键设计:\n- **外层 while True**:WORK 和 IDLE 交替进行,直到超时或收到关机请求\n- **内层 for 10**:WORK 阶段最多 10 轮 LLM 调用(防止无限循环)\n- **IDLE 超时 60 秒**:12 次轮询 × 5 秒 = 60 秒。超时后发送 summary 并退出\n- **shutdown_request 两阶段都能响应**:WORK 阶段通过 `handle_inbox_message` 分发;IDLE 阶段 `idle_poll` 直接检查并回复\n\n### 进阶(选学):身份重注入\n\nautoCompact(s08)之后,队友的 messages 列表可能被压缩成一段摘要。每次进入新的 WORK 阶段时检查:\n\n```python\nif len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n```\n\n消息过短说明发生了压缩,此时重新注入身份信息。真实 CC 中 context compaction 会保留 system prompt,教学版的简化实现需要手动处理。\n\n### consume_lead_inbox: 统一 inbox 消费\n\n`check_inbox` 工具和主循环末尾都调用同一个 `consume_lead_inbox()` 函数:先路由协议 response 更新状态,再把所有消息注入 Lead 的对话历史。队友发来的 summary/result 不会只打印在终端,Lead 的 LLM 能看到并协调下一步。\n\n### 合起来跑\n\n```\n1. Lead: \"搭建后端——任务太多,让队友自己认领\"\n2. Lead → create_task(\"创建数据库 schema\")\n3. Lead → create_task(\"写 API 路由\")\n4. Lead → create_task(\"写单元测试\")\n5. Lead → spawn_teammate(\"alice\", \"backend\", \"你是后端开发者\")\n6. Lead → spawn_teammate(\"bob\", \"backend\", \"你是后端开发者\")\n\n7. alice 线程启动 → WORK: 没有初始 inbox → 空转 → IDLE\n8. bob 线程启动 → WORK: 没有初始 inbox → 空转 → IDLE\n\n9. alice IDLE 第 1 次轮询 → scan_unclaimed → 发现\"创建数据库 schema\"\n10. alice → claim_task → \"创建数据库 schema\" → 回到 WORK\n11. bob IDLE 第 1 次轮询 → scan_unclaimed → 发现\"写 API 路由\"\n12. bob → claim_task → \"写 API 路由\" → 回到 WORK\n\n13. alice WORK: write_file(\"schema.sql\", ...) → complete_task → WORK 结束\n14. alice IDLE → scan → \"写单元测试\" → claim → WORK\n15. alice WORK: write_file(\"test_api.py\", ...) → complete_task → WORK 结束\n16. alice IDLE → 60s 无新任务 → SHUTDOWN\n\n17. bob 类似流程 → 做完 → SHUTDOWN\n18. Lead consume_lead_inbox → 看到 alice 和 bob 的 summary\n```\n\n两个队友并行认领、并行工作。Lead 只需要创建任务和启动队友,不需要手动分配。\n\n---\n\n## 相对 s16 的变更\n\n| 组件 | 之前 (s16) | 之后 (s17) |\n|------|-----------|-----------|\n| 任务分配 | Lead 手动 assign | 队友自动认领(can_start 检查依赖) |\n| 队友状态 | WORK → IDLE(每 1s 轮询 inbox)→ WORK / SHUTDOWN | WORK → IDLE(每 5s 轮询 inbox + 任务板,60s 超时)→ WORK / SHUTDOWN |\n| claim_task | 无 owner 检查 | 拒绝已有 owner 的任务 |\n| IDLE 阶段关机 | 收到 shutdown_request 后退出 | 直接 dispatch shutdown 并退出 |\n| Lead inbox | consume_lead_inbox 路由协议响应并注入上下文 | 沿用 consume_lead_inbox 机制 |\n| 新函数 | 已有 consume_lead_inbox | idle_poll, scan_unclaimed_tasks(沿用 consume_lead_inbox) |\n| 身份保持 | 仅 system prompt | 压缩后自动重注入 |\n| Lead 工具 | 14 | 14(不变) |\n| 队友工具 | 5 | 8(+ list_tasks, claim_task, complete_task) |\n| 队友退出条件 | WORK 完进入 IDLE,等待 shutdown_request 后退出(无超时) | 60s 无新任务或收到 shutdown_request 后退出 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s17_autonomous_agents/code.py\n```\n\n试试这个 prompt:\n\n`Create 3 tasks on the board, then spawn alice and bob. Watch them auto-claim and work.`\n\n观察重点:队友是否自动认领了未分配的任务?有 blockedBy 依赖的任务是否在前置完成后被正确认领?空闲超时后是否自动关机?IDLE 阶段收到 shutdown_request 是否立即响应?`.tasks/` 目录下的任务状态如何变化?\n\n---\n\n## 接下来\n\n队友自组织了。但 Alice 和 Bob 都在同一个目录下工作——Alice 改 `config.py`,Bob 也改 `config.py`,互相覆盖。\n\ns18 Worktree Isolation → 每个任务有自己的工作目录,互不干扰。\n\n
\n深入 CC 源码\n\n> 教学说明:本章的 idle_poll + auto-claim 机制是教学设计,用统一的轮询函数演示\"空闲后找活干\"。CC 的实际实现是多个机制的组合,但目标一致——减少 Lead 的手动分配负担。\n\n### 一、CC 的空闲机制:组合路径,不是单一轮询\n\n教学版用一个 `idle_poll()` 统一处理空闲时的 inbox 检查和任务认领。CC 的实际实现是四个机制的组合:\n\n**idle_notification**:队友完成一轮工作后,`sendIdleNotification()`(`inProcessRunner.ts:569-589`)向 Lead 发送空闲通知。Lead 知道队友可用了,可以分配新任务或请求关机。\n\n**mailbox 轮询**:`waitForNextPromptOrShutdown()`(`inProcessRunner.ts:689-868`)是一个 **500ms 轮询循环**,持续检查三类来源:pending user messages、mailbox 文件消息、task list。shutdown_request 被优先处理(`inProcessRunner.ts:768-804`),不会被普通消息饿死。\n\n**task watcher**:`useTaskListWatcher`(`hooks/useTaskListWatcher.ts:34-189`)用 `fs.watch()` 监听 `.claude/tasks/` 目录变化,1 秒 debounce,当新任务创建或依赖解锁时触发检查。依赖判断(`L197-207`)是\"blockedBy 中没有未完成的任务\",不是\"blockedBy 为空\"。\n\n**主动 claim**:轮询循环内部也会调用 `tryClaimNextTask()`(`inProcessRunner.ts:853-860`)——在等待期间主动从 task list 领取任务。所以\"队友不主动轮询任务\"不准确,CC 同时有被动通知和主动认领。\n\n### 二、任务认领:文件锁 + 原子操作\n\n`claimTask()`(`utils/tasks.ts:541-612`)用 `proper-lockfile` 的任务文件锁,在锁内完成读-检查-改-写。检查项:owner 是否已存在(`L575-576`)、是否已完成(`L580-581`)、blockedBy 中是否有未完成任务(`L585-594`)。`claimTaskWithBusyCheck()`(`utils/tasks.ts:614-692`)用 task-list 级别锁,把 busy check 和 claim 做成原子操作,避免 TOCTOU。\n\n`findAvailableTask()`(`inProcessRunner.ts:595-604`)的依赖判断也是\"所有 blockedBy 已完成\",用 `task.blockedBy.every(id => !unresolvedTaskIds.has(id))` 实现。`tryClaimNextTask()`(`inProcessRunner.ts:624-657`)在认领后把状态更新为 `in_progress`,让 UI 立即反映变化。\n\n### 三、教学版 vs CC 对比\n\n| 维度 | 教学版 (s17) | CC |\n|------|-------------|-----|\n| 空闲机制 | idle_poll 统一轮询(5s) | idle_notification + 500ms mailbox 轮询 + task watcher |\n| 任务发现 | scan_unclaimed_tasks(轮询) | useTaskListWatcher(文件监听)+ tryClaimNextTask(主动轮询) |\n| 依赖判断 | can_start(所有 blockedBy 已完成) | findAvailableTask(同样语义) |\n| 并发安全 | owner 检查(无文件锁) | proper-lockfile 任务锁 + task-list 锁 |\n| shutdown 处理 | IDLE 直接分发,WORK 通过 handle_inbox_message | 500ms 轮询中优先处理 shutdown_request |\n| 超时退出 | 60s 无新任务 | 无固定超时,Lead 手动 shutdown |\n| 身份保持 | messages 长度检测 | context compaction 保留 system prompt |\n| claim 失败处理 | 检查返回值,失败不注入 | 文件锁保证原子性 |\n\n教学版的 `idle_poll()` 把 CC 的四个机制合并成一个轮询函数——简化合理,因为核心语义(空闲时找活干、依赖解锁后可认领、shutdown 优先)是一致的。\n\n
\n\n\n" + "title": "s17: Worktree Isolation — 各干各的,互不干扰", + "content": "# s17: Worktree Isolation — 各干各的,互不干扰\n\ns01 → ... → s15 → s16 → `s17` → [s18](/zh/s18) → s19 → s20 → s21\n\n> *\"各干各的目录, 互不干扰\"* — 任务管目标, worktree 管目录, 按 ID 绑定。\n>\n> **Harness 层**: 隔离 — 并行执行的目录隔离。\n\n---\n\n## 问题\n\ns16 中,Alice 和 Bob 都在同一个目录下工作。Alice 的任务是\"重构认证模块\",Bob 的任务是\"重构 UI 登录页\"。\n\nAlice `write_file(\"config.py\", ...)`。Bob 也 `write_file(\"config.py\", ...)`。两个人改同一个文件,互相覆盖。而且无法干净地回滚——分不清哪些改动是谁的。\n\ns15-s16 解决了\"谁干什么\"(任务系统)和\"怎么通信\"(消息总线),但没解决\"在哪干\"。\n\n---\n\n## 解决方案\n\n![Worktree Overview](/course-assets/s17_worktree_isolation/worktree-overview.svg)\n\nGit worktree 让你在同一仓库中创建多个独立的工作目录,每个有自己的分支。Alice 在 `.worktrees/auth-refactor/` 下工作,Bob 在 `.worktrees/ui-login/` 下工作——互不干扰。\n\n沿用 s16 的 MessageBus、协议和自治认领机制。本章新增:\n\n| 能力 | 作用 |\n|------|------|\n| create_worktree | 为任务创建独立目录 + 独立分支 |\n| bind_task_to_worktree | 把任务和工作目录绑定(不改状态) |\n| remove_worktree / keep_worktree | 完成后清理或保留 |\n| validate_worktree_name | 拒绝路径穿越和非法字符 |\n\n---\n\n## 工作原理\n\n### 创建:任务-Worktree 绑定\n\n```python\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n validate_worktree_name(name) # 只允许 [A-Za-z0-9._-]{1,64}\n path = WORKTREES_DIR / name\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n return f\"Worktree '{name}' created at {path}\"\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name # 只写 worktree 字段\n save_task(task) # 状态保持 pending,等队友 claim\n```\n\n绑定规则:一个任务绑定一个 worktree。绑定不改任务状态——任务仍是 `pending`,队友自动认领时才推进到 `in_progress`。这样 Lead 可以提前创建任务和 worktree,队友 idle 时自然认领带 worktree 的任务。\n\n### 队友工具的 cwd 切换\n\n每个队友都有一个 `wt_ctx` 字典,用来记录当前 worktree 路径。队友认领绑定了 worktree 的任务后,运行时会更新 `wt_ctx`;该队友的 `bash`、`read_file`、`write_file` 随后都在对应的 worktree 目录下执行:\n\n```python\n# 队友线程内部\nwt_ctx = {\"path\": None}\n\ndef _run_claim_task(task_id):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n return result\n\ndef _run_bash(command):\n return run_bash(command, cwd=wt_ctx[\"path\"]) # 在 worktree 下执行\n```\n\n### 收尾:Keep 还是 Remove\n\n任务完成后,两个选择:\n\n```python\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n # 安全检查:有改动时默认拒绝\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files > 0 or commits > 0:\n return \"有未提交改动,使用 discard_changes=true 强制删除,或 keep_worktree 保留\"\n ok, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok:\n return \"删除失败\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n\ndef keep_worktree(name: str) -> str:\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n```\n\nKeep = 留着分支,等人工 review 后合并到主分支。Remove = 有改动时默认拒绝,需要 `discard_changes=true` 确认。不自动 complete task——任务完成由队友的 `complete_task` 显式触发。\n\n### 事件流:可审计\n\n每次生命周期操作写入日志,方便排查:\n\n```python\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n # append to .worktrees/events.jsonl\n```\n\n事件类型包括 `create`(创建)、`remove`(删除)和 `keep`(保留)。日志用于人工排查;恢复流程可以通过 `git worktree list` 重建当前 worktree 集合。\n\n### run_git:返回成功/失败\n\n```python\ndef run_git(args: list[str]) -> tuple[bool, str]:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR, ...)\n return r.returncode == 0, output\n```\n\n`create_worktree` 和 `remove_worktree` 只在 git 命令成功后才写事件日志,保证日志反映真实状态。\n\n---\n\n## 相对 s16 的变更\n\n| 组件 | 之前 (s16) | 之后 (s17) |\n|------|-----------|-----------|\n| 工作目录 | 所有 Agent 共享 WORKDIR | 每个任务可绑定独立 git worktree |\n| Task 数据 | id/subject/status/owner/blockedBy | + worktree 字段 |\n| 队友工具 cwd | 始终 WORKDIR | 认领带 worktree 的任务时自动切换 |\n| 新函数 | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name |\n| worktree 安全 | 无 | name 校验 + 有改动时拒绝删除 |\n| 事件日志 | 无 | events.jsonl 生命周期审计 |\n| Lead 工具 | 团队与任务工具 | + create_worktree、remove_worktree、keep_worktree |\n| 队友工具 | 任务与文件工具 | 工具不变,bash/read/write 使用已认领任务的 worktree cwd |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s17_worktree_isolation/code.py\n```\n\n试试这个 prompt:\n\n`请并行重构认证模块和登录页面,确保两部分改动不会互相干扰。`\n\n观察重点:两个 worktree 的 `git status` 输出是否显示不同的分支?队友认领带 worktree 的任务后,bash 命令是否在 worktree 目录下执行?`remove_worktree` 对有改动的 worktree 是否拒绝?`.tasks/` 中的任务在绑定后状态是否仍为 `pending`?\n\n---\n\n## 接下来\n\nAgent 团队能在隔离的工作空间中自组织了。但 Agent 的能力受限于我们给它写的工具——bash、read、write、task...\n\n如果用户已经有了自己的工具怎么办?比如一个公司内部的 Jira API、一个自建的部署系统?\n\ns18 MCP Plugin → 给 Agent 装一个插件系统。外部工具通过标准协议接入,Agent 不需要知道它们是谁写的。\n\n\n\n" }, { "version": "s17", "locale": "ja", - "title": "s17: Autonomous Agents — ボードを見て、自分で認領", - "content": "# s17: Autonomous Agents — ボードを見て、自分で認領\n\ns01 → ... → s15 → s16 → `s17` → [s18](/ja/s18) → s19 → s20 → s21 → s22\n\n> *\"ボードを見て、自分で認領\"* — 空き時にポーリング、仕事があれば開始。\n>\n> **Harness 層**: 自治 — チームメイトが自己組織化、リーダーの割り当て不要。\n\n> **コアと任意項目:** アイドル時の仕事発見と原子的な claim が本章の中心。アイデンティティ再注入は教育版の高度な補助で、初回は読み飛ばしてよい。\n\n---\n\n## 課題\n\ns16 のチームメイトは通信でき、シャットダウンハンドシェイクもできる。しかし各チームメイトは Lead がタスクを割り当てるのを待つ——ボードに 10 個の未認領タスクがあれば、Lead は 10 回手動で assign しなければならない。これはスケールしない。チームメイトは自分でタスクボードを見て、未認領のタスクを見つけて認領し、終わったら次を探すべき。\n\n---\n\n## ソリューション\n\n![Autonomous Agents Overview](/course-assets/s17_autonomous_agents/autonomous-agents-overview.ja.svg)\n\nS16 の教学版 MessageBus とプロトコルツールを踏襲。本章の追加:**idle_poll**(空き時に 5 秒ごとにポーリング)、**scan_unclaimed_tasks**(ボード上の認領可能なタスクをスキャン)、**自動認領**(見つけたら即座に claim、Lead 不要)。\n\nチームメイトのライフサイクルは 2 フェーズから 3 フェーズに:\n\n| フェーズ | 動作 | 終了条件 |\n|----------|------|---------|\n| WORK | inbox → LLM → ツールループ | `stop_reason != tool_use` |\n| IDLE | 5s ポーリング inbox + タスクボード | 60s タイムアウト |\n| SHUTDOWN | summary を送信、終了 | — |\n\n---\n\n## 仕組み\n\n### idle_poll: 空き時ポーリング\n\nチームメイトはタスク完了後も終了せず、IDLE フェーズに入る——5 秒ごとに新しい仕事がないか確認:\n\n```python\nIDLE_POLL_INTERVAL = 5 # seconds\nIDLE_TIMEOUT = 60 # seconds\n\ndef idle_poll(name, messages, role) -> str:\n \"\"\"Return 'work', 'shutdown', or 'timeout'.\"\"\"\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n\n # ① 受信箱確認(優先)\n inbox = BUS.read_inbox(name)\n if inbox:\n # shutdown_request は即座に処理\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n # ... shutdown_response 返信\n return \"shutdown\"\n # 通常メッセージ:コンテキストに注入、WORK に戻る\n messages.append(...)\n return \"work\"\n\n # ② タスクボードスキャン\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task = unclaimed[0]\n result = claim_task(task[\"id\"], name)\n if \"Claimed\" in result:\n messages.append(...)\n return \"work\"\n return \"timeout\"\n```\n\ninbox を優先(shutdown_request 等のプロトコルメッセージの可能性)、タスクボードが次。IDLE フェーズで shutdown_request を受信すると即座に返信して終了し、次の WORK を待つ必要がない。\n\n### scan_unclaimed_tasks: タスクボードスキャン\n\npending 状態、owner なし、全依存関係完了(`can_start`)のタスクを検索:\n\n```python\ndef scan_unclaimed_tasks() -> list[dict]:\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n```\n\n3 つの条件:pending であること、owner がないこと、全 blockedBy 依存が完了していること。`can_start` は依存タスクの状態を確認——依存があるからといってタスクを開始できないわけではなく、未解決の依存のみがブロックする。教学版はファイル名順で最初のものを選択、CC はファイルロックで複数チームメイトの同時認領を防止。\n\n### claim_task: owner チェック\n\n自動認領時に claim 結果を確認し、失敗を成功として扱わない:\n\n```python\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n return f\"Claimed {task.id} ({task.subject})\"\n```\n\n教学版にはファイルロックがないため、並行認領で競合する可能性がある。しかし `task.owner` チェックで最も明白な「後書き上書き」問題を回避。CC は `proper-lockfile` でタスクファイルを保護、`claimTask` はファイルロック内で read-modify-write を実行(`utils/tasks.ts:541-612`)。\n\n### チームメイトライフサイクル: WORK → IDLE → SHUTDOWN\n\ns16 のチームメイトはタスク完了後に終了。s17 は IDLE フェーズを追加——外側ループで WORK → IDLE を繰り返す:\n\n```python\n# 外側ループ: WORK → IDLE サイクル\nwhile True:\n # WORK フェーズ: 内側ループ(最大 10 ラウンド LLM 呼び出し)\n for _ in range(10):\n # inbox 確認、プロトコルメッセージ処理、LLM 呼び出し、ツール実行\n ...\n if response.stop_reason != \"tool_use\":\n break # WORK フェーズ終了\n\n # IDLE フェーズ\n idle_result = idle_poll(name, messages, role)\n if idle_result == \"shutdown\":\n break\n if idle_result == \"timeout\":\n break # 60s タイムアウト → SHUTDOWN\n\n# SHUTDOWN: summary を Lead に送信\nBUS.send(name, \"lead\", summary, \"result\")\n```\n\n主要設計:\n- **外側 while True**:WORK と IDLE がタイムアウトまたはシャットダウン要求まで交互に続く\n- **内側 for 10**:WORK フェーズは最大 10 ラウンドの LLM 呼び出し(無限ループ防止)\n- **IDLE タイムアウト 60 秒**:12 回ポーリング × 5 秒 = 60 秒。タイムアウト後 summary を送信して終了\n- **shutdown_request は両フェーズで応答**:WORK フェーズは `handle_inbox_message` でディスパッチ、IDLE フェーズは `idle_poll` が直接確認して返信\n\n### 発展(任意):アイデンティティ再注入\n\nautoCompact(s08)後、チームメイトの messages リストが要約に圧縮される可能性がある。新しい WORK フェーズに入るたびに確認:\n\n```python\nif len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n```\n\nメッセージが短い場合、圧縮が発生したことを示す——身份情報を再注入。真实 CC では context compaction が system prompt を保持、教学版の簡略実装は手動処理が必要。\n\n### consume_lead_inbox: 統一 inbox コンシューマ\n\n`check_inbox` ツールとメインループ末尾の両方が同じ `consume_lead_inbox()` 関数を呼び出す:プロトコル response を先にルーティングして状態を更新し、全メッセージを Lead の会話履歴に注入。チームメイトからの summary/result は端末に表示されるだけでなく、Lead の LLM も確認して次のステップを調整可能。\n\n### 組み合わせて実行\n\n```\n1. Lead: \"バックエンド構築——タスクが多すぎる、チームメイトに自己認領させる\"\n2. Lead → create_task(\"データベーススキーマを作成\")\n3. Lead → create_task(\"API ルートを書く\")\n4. Lead → create_task(\"ユニットテストを書く\")\n5. Lead → spawn_teammate(\"alice\", \"backend\", \"あなたはバックエンド開発者\")\n6. Lead → spawn_teammate(\"bob\", \"backend\", \"あなたはバックエンド開発者\")\n\n7. alice スレッド起動 → WORK: 初期 inbox なし → 空転 → IDLE\n8. bob スレッド起動 → WORK: 初期 inbox なし → 空転 → IDLE\n\n9. alice IDLE ポーリング 1 回目 → scan_unclaimed → \"データベーススキーマを作成\" を発見\n10. alice → claim_task → \"データベーススキーマを作成\" → WORK に戻る\n11. bob IDLE ポーリング 1 回目 → scan_unclaimed → \"API ルートを書く\" を発見\n12. bob → claim_task → \"API ルートを書く\" → WORK に戻る\n\n13. alice WORK: write_file(\"schema.sql\", ...) → complete_task → WORK 終了\n14. alice IDLE → scan → \"ユニットテストを書く\" → claim → WORK\n15. alice WORK: write_file(\"test_api.py\", ...) → complete_task → WORK 終了\n16. alice IDLE → 60s 新しいタスクなし → SHUTDOWN\n\n17. bob も同様のフロー → 完了 → SHUTDOWN\n18. Lead consume_lead_inbox → alice と bob の summary を確認\n```\n\n2 人のチームメイトが並行して認領・作業。Lead はタスクを作成してチームメイトを起動するだけで、手動割り当て不要。\n\n---\n\n## s16 からの変更\n\n| コンポーネント | 変更前 (s16) | 変更後 (s17) |\n|--------------|------------|------------|\n| タスク割り当て | Lead が手動 assign | チームメイトが自動認領(can_start で依存確認) |\n| チームメイト状態 | WORK → IDLE(1s 間隔で inbox をポーリング)→ WORK / SHUTDOWN | WORK → IDLE(5s 間隔で inbox + タスクボードをポーリング、60s タイムアウト)→ WORK / SHUTDOWN |\n| claim_task | owner チェックなし | 既に owner があるタスクを拒否 |\n| IDLE フェーズシャットダウン | shutdown_request を受信後に終了 | 即座にシャットダウンをディスパッチして終了 |\n| Lead inbox | consume_lead_inbox がプロトコル応答をルーティングしコンテキストに注入 | consume_lead_inbox 機構を踏襲 |\n| 新規関数 | consume_lead_inbox は既存 | idle_poll, scan_unclaimed_tasks(consume_lead_inbox を踏襲) |\n| 身份保持 | system prompt のみ | 圧縮後に自動再注入 |\n| Lead ツール | 14 | 14(変更なし) |\n| チームメイトツール | 5 | 8(+ list_tasks, claim_task, complete_task) |\n| チームメイト終了条件 | WORK 完了後 IDLE に入り、shutdown_request を待って終了(タイムアウトなし) | 60s アイドルタイムアウトまたは shutdown_request 受信で終了 |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s17_autonomous_agents/code.py\n```\n\n以下のプロンプトを試してください:\n\n`Create 3 tasks on the board, then spawn alice and bob. Watch them auto-claim and work.`\n\n観察ポイント:チームメイトは未割り当てのタスクを自動認領したか?blockedBy 依存のあるタスクは依存完了後に正しく認領されたか?アイドルタイムアウトでシャットダウンしたか?IDLE フェーズで shutdown_request に即座に応答したか?`.tasks/` ディレクトリのタスク状態はどう変化したか?\n\n---\n\n## 次の章\n\nチームメイトが自己組織化した。しかし Alice も Bob も同じディレクトリで作業——Alice が `config.py` を編集し、Bob も `config.py` を編集して互いに上書きしてしまう。\n\ns18 Worktree Isolation → 各タスクに専用の作業ディレクトリ、競合なし。\n\n
\nCC ソースコード深掘り\n\n> 教学注記:本章の idle_poll + auto-claim 機構は教学設計であり、統一ポーリング関数で「空き時に仕事を探す」をデモ。CC の実際の実装は複数機構の組み合わせだが、目標は同じ——Lead の手動割り当て負担を軽減。\n\n### 一、CC の空き機構:組み合わせ路径、単一ポーリングではない\n\n教学版は 1 つの `idle_poll()` で空き時の inbox 確認とタスク認領を統一処理。CC の実際の実装は 4 つの機構の組み合わせ:\n\n**idle_notification**:チームメイトが 1 ラウンドの作業を完了後、`sendIdleNotification()`(`inProcessRunner.ts:569-589`)が Lead に空き通知を送信。Lead はチームメイトが利用可能であることを知り、新しいタスクを割り当てたりシャットダウンを要求可能。\n\n**mailbox ポーリング**:`waitForNextPromptOrShutdown()`(`inProcessRunner.ts:689-868`)は **500ms ポーリングループ**で、3 つのソースを継続チェック:pending user messages、mailbox ファイルメッセージ、task list。shutdown_request は優先処理(`inProcessRunner.ts:768-804`)、通常メッセージによる飢餓を防止。\n\n**task watcher**:`useTaskListWatcher`(`hooks/useTaskListWatcher.ts:34-189`)が `fs.watch()` で `.claude/tasks/` ディレクトリの変化を監視、1 秒 debounce で新タスク作成や依存アンロック時にチェックをトリガー。依存判断(`L197-207`)は「blockedBy に未完了タスクがない」で、「blockedBy が空」ではない。\n\n**能動 claim**:ポーリングループ内でも `tryClaimNextTask()`(`inProcessRunner.ts:853-860`)を呼び出し——待機中に task list から能動的にタスクを認領。したがって「チームメイトは能動的にタスクをポーリングしない」は不正確、CC は受動通知と能動認領の両方を持つ。\n\n### 二、タスク認領:ファイルロック + 原子操作\n\n`claimTask()`(`utils/tasks.ts:541-612`)は `proper-lockfile` のタスクファイルロックを使用、ロック内で read-check-modify-write を実行。チェック項目:owner が既に存在(`L575-576`)、完了済み(`L580-581`)、blockedBy に未完了タスクがあるか(`L585-594`)。`claimTaskWithBusyCheck()`(`utils/tasks.ts:614-692`)はタスクリストレベルロックを使用、busy check と claim を原子操作にして TOCTOU を回避。\n\n`findAvailableTask()`(`inProcessRunner.ts:595-604`)の依存判断も「全 blockedBy 完了」で、`task.blockedBy.every(id => !unresolvedTaskIds.has(id))` で実装。`tryClaimNextTask()`(`inProcessRunner.ts:624-657`)は認領後 status を `in_progress` に更新、UI に即座に反映。\n\n### 三、教学版 vs CC 対比\n\n| 次元 | 教学版 (s17) | CC |\n|------|-------------|-----|\n| 空き機構 | idle_poll 統一ポーリング(5s) | idle_notification + 500ms mailbox ポーリング + task watcher |\n| タスク発見 | scan_unclaimed_tasks(ポーリング) | useTaskListWatcher(ファイル監視)+ tryClaimNextTask(能動ポーリング) |\n| 依存チェック | can_start(全 blockedBy 完了) | findAvailableTask(同じセマンティクス) |\n| 並行安全性 | owner チェック(ファイルロックなし) | proper-lockfile タスクロック + タスクリストロック |\n| shutdown 処理 | IDLE 直接ディスパッチ、WORK は handle_inbox_message | 500ms ポーリングループで shutdown_request を優先 |\n| タイムアウト終了 | 60s 新しいタスクなし | 固定タイムアウトなし、Lead 手動 shutdown |\n| 身份保持 | messages 長さ検出 | context compaction が system prompt を保持 |\n| claim 失敗処理 | 戻り値を確認、失敗時はスキップ | ファイルロックで原子性を保証 |\n\n教学版の `idle_poll()` は CC の 4 つの機構を 1 つのポーリング関数に統合——核心セマンティクス(空き時に仕事を探す、依存アンロック後に認領、shutdown 優先)が一致するため、合理的な簡略化。\n\n
\n\n\n" + "title": "s17: Worktree Isolation — それぞれのディレクトリ、互いに干渉しない", + "content": "# s17: Worktree Isolation — それぞれのディレクトリ、互いに干渉しない\n\ns01 → ... → s15 → s16 → `s17` → [s18](/ja/s18) → s19 → s20 → s21\n\n> *\"それぞれのディレクトリ、互いに干渉しない\"* — タスクは目標を管理、worktree はディレクトリを管理、ID で紐付け。\n>\n> **Harness 層**: 隔離 — 並列実行のディレクトリ分離。\n\n---\n\n## 課題\n\ns16 では、Alice も Bob も同じディレクトリで作業。Alice のタスクは「認証モジュールのリファクタリング」、Bob のタスクは「UI ログインページのリファクタリング」。\n\nAlice が `write_file(\"config.py\", ...)` を呼び出し、Bob も `write_file(\"config.py\", ...)` を呼び出す。両者が同じファイルを編集し、互いに上書き。クリーンなロールバックもできない——どの変更が誰のものか区別できない。\n\ns15-s16 は「誰が何をするか」(タスクシステム)と「どう通信するか」(メッセージバス)を解決したが、「どこで作業するか」は未解決。\n\n---\n\n## ソリューション\n\n![Worktree Overview](/course-assets/s17_worktree_isolation/worktree-overview.ja.svg)\n\nGit worktree を使うと、同じリポジトリ内に複数の独立した作業ディレクトリを作成でき、それぞれが独自のブランチを持つ。Alice は `.worktrees/auth-refactor/` で作業、Bob は `.worktrees/ui-login/` で作業——互いに干渉しない。\n\ns16 の MessageBus、プロトコル、自動認領を引き継ぐ。本章では次を追加する:\n\n| 機能 | 目的 |\n|------|------|\n| create_worktree | タスク用の独立ディレクトリ + 独立ブランチを作成 |\n| bind_task_to_worktree | タスクとディレクトリを紐付け(状態は変更しない) |\n| remove_worktree / keep_worktree | 完了後のクリーンアップまたは保持 |\n| validate_worktree_name | パストラバーサルと不正文字を拒否 |\n\n---\n\n## 仕組み\n\n### 作成:タスク-Worktree 紐付け\n\n```python\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n validate_worktree_name(name) # [A-Za-z0-9._-]{1,64} のみ許可\n path = WORKTREES_DIR / name\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n return f\"Worktree '{name}' created at {path}\"\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name # worktree フィールドのみ書き込み\n save_task(task) # 状態は pending のまま、チームメイトの claim を待つ\n```\n\n紐付けルール:1 つのタスクに 1 つの worktree を紐付け。紐付けはタスクの状態を変更しない——タスクは `pending` のままで、チームメイトが認領した時に `in_progress` に進む。これにより Lead は事前にタスクと worktree を作成でき、チームメイトは idle 時に自然に worktree 紐付け済みタスクを認領する。\n\n### チームメイトツールの cwd 切り替え\n\n各チームメイトは、現在の worktree パスを記録する `wt_ctx` 辞書を持つ。worktree に紐付いたタスクを認領すると、ランタイムが `wt_ctx` を更新し、そのチームメイトの `bash`、`read_file`、`write_file` は対応する worktree ディレクトリで実行される:\n\n```python\n# チームメイトスレッド内部\nwt_ctx = {\"path\": None}\n\ndef _run_claim_task(task_id):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n return result\n\ndef _run_bash(command):\n return run_bash(command, cwd=wt_ctx[\"path\"]) # worktree で実行\n```\n\n### クリーンアップ:Keep または Remove\n\nタスク完了後、2 つの選択肢:\n\n```python\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n # 安全チェック:変更がある場合デフォルトで拒否\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files > 0 or commits > 0:\n return \"未コミットの変更あり。discard_changes=true で強制削除、または keep_worktree で保持\"\n ok, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok:\n return \"削除失敗\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n\ndef keep_worktree(name: str) -> str:\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n```\n\nKeep = ブランチを保持し、手動 review 後にマージ。Remove = 未コミット変更がある場合デフォルトで拒否、`discard_changes=true` で確認が必要。タスクの自動 complete はしない——タスク完了はチームメイトの `complete_task` で明示的にトリガー。\n\n### イベントログ:監査可能\n\n各ライフサイクル操作はログに記録され、監査に利用:\n\n```python\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n # .worktrees/events.jsonl に append\n```\n\nイベントタイプは `create`、`remove`、`keep`。ログは手動監査に使い、復元時は `git worktree list` から現在の worktree 一覧を再構築できる。\n\n### run_git:成功/失敗を返す\n\n```python\ndef run_git(args: list[str]) -> tuple[bool, str]:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR, ...)\n return r.returncode == 0, output\n```\n\n`create_worktree` と `remove_worktree` は git コマンド成功後のみイベントログに書き込み、ログが実際の状態を反映することを保証。\n\n---\n\n## s16 からの変更\n\n| コンポーネント | 変更前 (s16) | 変更後 (s17) |\n|--------------|------------|------------|\n| 作業ディレクトリ | 全 Agent が WORKDIR を共有 | 各タスクが git worktree に紐付け可能 |\n| タスクデータ | id/subject/status/owner/blockedBy | + worktree フィールド |\n| チームメイトツール cwd | 常に WORKDIR | worktree 紐付けタスク認領時に自動切り替え |\n| 新規関数 | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name |\n| worktree 安全性 | なし | name 検証 + 変更ありの場合削除拒否 |\n| イベントログ | なし | events.jsonl ライフサイクル監査 |\n| Lead ツール | チーム・タスクツール | + create_worktree、remove_worktree、keep_worktree |\n| チームメイトツール | タスク・ファイルツール | ツールは同じ。bash/read/write は認領した worktree の cwd を使う |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s17_worktree_isolation/code.py\n```\n\n以下のプロンプトを試してください:\n\n`認証モジュールとログインページを並行してリファクタリングし、変更が互いに干渉しないようにしてください。`\n\n観察ポイント:2 つの worktree の `git status` 出力は異なるブランチを表示しているか?チームメイトが worktree 紐付けタスクを認領後、bash コマンドは worktree ディレクトリで実行されているか?`remove_worktree` は変更がある場合に拒否するか?紐付け後のタスク状態は `pending` のままか?\n\n---\n\n## 次の章\n\nAgent チームが隔離されたワークスペースで自己組織化できるようになった。しかし Agent の能力はツールに制限される——bash、read、write、task...\n\nもしユーザーが独自のツールを持っていたら?例えば社内 Jira API や独自デプロイシステム?\n\ns18 MCP Plugin → Agent にプラグインシステムを追加。外部ツールが標準プロトコルで接続、Agent は誰が書いたか知る必要がない。\n\n\n\n" }, { "version": "s18", "locale": "en", - "title": "s18: Worktree Isolation — Separate Directories, No Conflicts", - "content": "# s18: Worktree Isolation — Separate Directories, No Conflicts\n\ns01 → ... → s16 → s17 → `s18` → [s19](/en/s19) → s20 → s21 → s22\n\n> *\"Separate directories, no conflicts\"* — Tasks own the goal, worktrees own the directory, bound by ID.\n>\n> **Harness Layer**: Isolation — Parallel execution in separate directories.\n\n---\n\n## The Problem\n\nIn s17, Alice and Bob both work in the same directory. Alice's task is \"refactor auth module\", Bob's task is \"refactor UI login page\".\n\nAlice calls `write_file(\"config.py\", ...)`. Bob also calls `write_file(\"config.py\", ...)`. Both edit the same file, overwriting each other. And there's no clean rollback — you can't tell whose changes are whose.\n\ns15-s17 solved \"who does what\" (task system) and \"how to communicate\" (message bus), but not \"where to work\".\n\n---\n\n## The Solution\n\n![Worktree Overview](/course-assets/s18_worktree_isolation/worktree-overview.en.svg)\n\nGit worktree lets you create multiple independent working directories in the same repo, each with its own branch. Alice works in `.worktrees/auth-refactor/`, Bob in `.worktrees/ui-login/` — no conflicts.\n\nCarries forward S17's teaching-version MessageBus, protocols, and autonomous claiming. This chapter adds:\n\n| Capability | Purpose |\n|------------|---------|\n| create_worktree | Create isolated directory + branch for a task |\n| bind_task_to_worktree | Bind task and directory (no status change) |\n| remove_worktree / keep_worktree | Cleanup or preserve after completion |\n| validate_worktree_name | Reject path traversal and illegal characters |\n\n---\n\n## How It Works\n\n### Creation: Task-Worktree Binding\n\n```python\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n validate_worktree_name(name) # Only [A-Za-z0-9._-]{1,64}\n path = WORKTREES_DIR / name\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n return f\"Worktree '{name}' created at {path}\"\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name # Write worktree field only\n save_task(task) # Status stays pending, waits for teammate claim\n```\n\nBinding rule: one task binds to one worktree. Binding does NOT change task status — the task stays `pending`, and advances to `in_progress` only when a teammate claims it. This way Lead can pre-create tasks and worktrees, and teammates naturally claim worktree-bound tasks during idle.\n\n### Teammate Tool Cwd Switching\n\nTeaching version maintains a `wt_ctx` dict per teammate, tracking the current worktree path. When a teammate claims a task with a worktree, `wt_ctx` is automatically set to the worktree path; the teammate's `bash`, `read_file`, `write_file` execute in the worktree directory:\n\n```python\n# Inside teammate thread\nwt_ctx = {\"path\": None}\n\ndef _run_claim_task(task_id):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n return result\n\ndef _run_bash(command):\n return run_bash(command, cwd=wt_ctx[\"path\"]) # Execute in worktree\n```\n\nThis is a teaching simplification. Real CC's EnterWorktree uses `process.chdir()` to switch the entire process directory, and AgentTool isolation uses `cwdOverride` to wrap sub-agent execution.\n\n### Cleanup: Keep or Remove\n\nAfter task completion, two choices:\n\n```python\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n # Safety check: refuse by default if changes exist\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files > 0 or commits > 0:\n return \"Has uncommitted changes. Use discard_changes=true to force, or keep_worktree\"\n ok, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok:\n return \"Remove failed\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n\ndef keep_worktree(name: str) -> str:\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n```\n\nKeep = preserve branch for manual review and merge. Remove = refuse by default if uncommitted changes; requires `discard_changes=true` to confirm. Does NOT auto-complete task — task completion is triggered explicitly by the teammate's `complete_task`.\n\n### Event Log: Auditable\n\nEach lifecycle operation writes to a log for auditing:\n\n```python\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n # append to .worktrees/events.jsonl\n```\n\nEvent types: `create`, `remove`, `keep`. Teaching version logs events for manual auditing; full recovery would need an index or `git worktree list` scanning.\n\n### run_git: Returns Success/Failure\n\n```python\ndef run_git(args: list[str]) -> tuple[bool, str]:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR, ...)\n return r.returncode == 0, output\n```\n\n`create_worktree` and `remove_worktree` only write event logs after successful git commands, ensuring logs reflect actual state.\n\n---\n\n## Changes from s17\n\n| Component | Before (s17) | After (s18) |\n|-----------|-------------|-------------|\n| Working directory | All agents share WORKDIR | Each task can bind to a git worktree |\n| Task data | id/subject/status/owner/blockedBy | + worktree field |\n| Teammate tool cwd | Always WORKDIR | Auto-switches when claiming worktree-bound task |\n| New functions | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name |\n| Worktree safety | None | Name validation + refuse removal with changes |\n| Event log | None | events.jsonl lifecycle auditing |\n| Lead tools | 14 (s17) | + create_worktree, remove_worktree, keep_worktree (17) |\n| Teammate tools | 8 (s17) | 8 (bash/read/write execute in worktree cwd) |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s18_worktree_isolation/code.py\n```\n\nTry this prompt:\n\n`Create two tasks, then create worktrees for each (bind with task_id). Spawn alice and bob. Watch them auto-claim and work in isolated directories.`\n\nWhat to observe: Do both worktrees show different branches in `git status`? After claiming a worktree-bound task, does the teammate's bash run in the worktree directory? Does `remove_worktree` refuse when there are changes? Is task status still `pending` after binding?\n\n---\n\n## What's Next\n\nAgent teams can now self-organize in isolated workspaces. But Agent capabilities are limited to the tools we wrote — bash, read, write, task...\n\nWhat if users already have their own tools? Like an internal Jira API, or a custom deployment system?\n\ns19 MCP Plugin → Give Agent a plugin system. External tools connect via standard protocol; Agent doesn't need to know who wrote them.\n\n
\nDeep Dive into CC Source\n\nCC's worktree system has two paths: **EnterWorktree** (current session switches in) and **AgentTool isolation** (sub-agent isolation).\n\n### EnterWorktree: Current Session Switch\n\n`EnterWorktreeTool.ts:92-97` after creating the worktree, immediately calls `process.chdir(worktreePath)`, `setCwd()`, `setOriginalCwd()`, `saveWorktreeState()`. The current session's working directory switches directly to the worktree — not a prompt hint, but a process-level directory change.\n\n`ExitWorktreeTool.ts:261-320` both keep and remove call `restoreSessionToOriginalCwd()` to restore the original directory. Remove checks for uncommitted changes (`ExitWorktreeTool.ts:190-220`), refusing without `discard_changes: true`.\n\n### AgentTool Isolation: Sub-Agent Isolation\n\n`AgentTool.tsx:590-641` when `isolation: \"worktree\"`, calls `createAgentWorktree()` to create a worktree, uses `cwdOverridePath` to wrap sub-agent execution. All sub-agent operations automatically run in the worktree directory. `AgentTool/prompt.ts:272` tells the model: this is a temporary worktree, auto-cleanup if no changes, return path and branch if changes exist.\n\n`worktree.ts:902-951` `createAgentWorktree()` does NOT modify global session cwd, only for sub-agent use. `worktree.ts:961-1020` `removeAgentWorktree()` deletes from the main repo root.\n\n### Name Validation\n\n`worktree.ts:76-84` validates slug: rejects `.`/`..`, allows `[a-zA-Z0-9._-]`. `worktree.ts:48` defines `VALID_WORKTREE_SLUG_SEGMENT`. Teaching version's `validate_worktree_name` uses the same rule.\n\n### Path and Branch Naming\n\nReal path is `.claude/worktrees/`, branch name `worktree-{slug}` (`worktree.ts:204-227`, slashes replaced with `+`). Teaching version uses `.worktrees/` and `wt/{name}` for simplicity.\n\nCreation uses `git worktree add -B` (`worktree.ts:326-328`), preferring `origin/` over current HEAD.\n\n### State Management\n\nCC has no task-worktree binding. Worktree state is managed through `PersistedWorktreeSession` (`worktree.ts:756-768`), with fields including `originalCwd`, `worktreePath`, `worktreeName`, `worktreeBranch`, `originalBranch`, `originalHeadCommit`, `sessionId`, etc. — no taskId field. `saveWorktreeState()` (`sessionStorage.ts:2883-2920`) writes to session transcript with `type: 'worktree-state'`.\n\nTeaching version uses the task's `worktree` field for binding, a teaching simplification. CC treats worktree and task as two independent systems, connected through the Agent's context understanding.\n\n
\n\n\n" + "title": "s18: MCP Tools — External Tools, Standard Protocol", + "content": "# s18: MCP Tools — External Tools, Standard Protocol\n\ns01 → ... → s16 → s17 → `s18` → [s19](/en/s19) → s20 → s21\n\n> *\"External tools, standard protocol\"* — Discover, assemble, invoke. Agent doesn't need to know who wrote them.\n>\n> **Harness layer**: Plugins — External capabilities via a standard protocol.\n\n---\n\n## The Problem\n\nFrom s01 through s17, every tool the agent uses was hand-written — bash, read, write, task, worktree. Input validation, execution logic, error handling — all written line by line.\n\nNow you have 3 external services to integrate: the company's Jira API (query issues, create tickets), an in-house deployment system (trigger deploys, view logs), and the team's Notion knowledge base (search docs, create pages). You don't want to rewrite tool code for every service.\n\nYou need a standard protocol — as long as an external service implements it, the agent can call its tools directly, regardless of what language the service is written in.\n\n---\n\n## The Solution\n\n![MCP Architecture](/course-assets/s18_mcp_plugin/mcp-architecture.en.svg)\n\nMCP (Model Context Protocol) defines how agents discover and invoke external tools. Core concepts:\n\n| Concept | Purpose |\n|------|------|\n| MCPClient | The agent-side client — connects to servers, discovers tools, invokes tools |\n| MCP Server | The external service — implements `tools/list` + `tools/call` |\n| assemble_tool_pool | Assembles built-in tools and MCP tools into one tool pool |\n| mcp\\_\\_server\\_\\_tool naming | Prevents tool name collisions across different servers |\n\nCarries forward s17's worktree isolation, autonomous claiming, and team protocols. This chapter adds the `connect_mcp` tool, which connects to a service, discovers its tools, and adds them to the tool pool.\n\nThe chapter registers in-process server handlers so the full discovery and invocation flow runs offline. Each handler exposes the two operations the client needs: `tools/list` and `tools/call`.\n\n---\n\n## How It Works\n\n### MCPClient: Discovery + Invocation\n\n```python\nclass MCPClient:\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs, handlers):\n \"\"\"Simulates tools/list discovery.\"\"\"\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n \"\"\"Simulates tools/call.\"\"\"\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n return handler(**args)\n```\n\nThe registered Python functions provide the server-side tool implementations used by `tools/call`.\n\n### connect_mcp: Connect + Discover\n\n```python\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n return f\"Unknown server '{name}'. Available: ...\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n return f\"Connected to '{name}'. Discovered: ...\"\n```\n\nAfter connecting, the server's tools are immediately available.\n\n### normalize_mcp_name: Name Normalization\n\n```python\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\ndef normalize_mcp_name(name: str) -> str:\n return _DISALLOWED_CHARS.sub('_', name)\n```\n\nAll non-`[a-zA-Z0-9_-]` characters are replaced with `_`. Prevents special characters in server or tool names from causing naming conflicts or injection issues.\n\n### assemble_tool_pool: Assemble Tool Pool\n\n```python\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append(...)\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw:\n c.call_tool(t, kw))\n return tools, handlers\n```\n\nThe prefix `mcp__{server}__{tool}` prevents tool name collisions across different servers. Names are normalized through `normalize_mcp_name`.\n\nMCP tool descriptions include `(readOnly)` or `(destructive)` labels, making the distinction visible in the tool metadata.\n\n### No Cache: Tool Pool Changes, Prompt Changes Too\n\ns10-s17's agent_loop used prompt caching to avoid re-serialization. s18 removes the cache:\n\n```python\ndef agent_loop(messages, context):\n tools, handlers = assemble_tool_pool() # Rebuild every time\n system = assemble_system_prompt(context) # Regenerate every time\n ...\n if any(b.name == \"connect_mcp\" ...):\n tools, handlers = assemble_tool_pool() # Rebuild after connection\n system = assemble_system_prompt(context)\n```\n\nAfter `connect_mcp`, the tool pool gains entries such as `mcp__docs__search`. Reusing the old serialized tool list would hide those entries from the model, so the loop rebuilds the pool and system prompt after every connection.\n\n### MCP Tools: Lead Only\n\n`connect_mcp` belongs to the Lead, and `assemble_tool_pool` serves the Lead's agent loop. Teammates keep their task, file, message, and plan tools; the Lead invokes external services and dispatches the resulting work.\n\n---\n\n## Changes from s17\n\n| Component | Before (s17) | After (s18) |\n|------|-----------|-----------|\n| Tool source | All hand-written built-in | Hand-written + MCP external tools with dynamic discovery |\n| Tool pool | Fixed BUILTIN_TOOLS | assemble_tool_pool dynamically assembles mcp\\_\\_ prefixed tools |\n| Name safety | None | normalize_mcp_name normalization |\n| New type | — | MCPClient class (simulates tools/list + tools/call) |\n| Namespace | — | mcp\\_\\_server\\_\\_tool prevents collisions |\n| Tool descriptions | No annotations | (readOnly)/(destructive) annotations |\n| Prompt cache | Yes (since s10) | Removed — tool pool is dynamic, cache goes stale |\n| Lead tools | Worktree and team tools | + connect_mcp and dynamically discovered MCP tools |\n| Teammate tools | Task, file, message, and plan tools | Unchanged |\n| Extension method | Write code to add tools | Standard protocol, implement servers in any language |\n\n---\n\n## Try It Out\n\n```sh\ncd learn-claude-code\npython s18_mcp_plugin/code.py\n```\n\nTry these prompts:\n\n1. `Search the docs for the worktree cleanup policy.`\n2. `Deploy the current project and report the result.`\n3. `What documentation and deployment actions can you perform?`\n\nWhat to observe: After connecting to an MCP server, do tool names have `mcp__docs__` or `mcp__deploy__` prefixes? Are both servers' tools available simultaneously? Do MCP tool descriptions include (readOnly)/(destructive) annotations?\n\n---\n\n## What's Next\n\nThe Agent can now connect external tools through a standard protocol. The first 18 chapters introduced these mechanisms one at a time so each boundary stayed visible.\n\nTools, permissions, hooks, todo, task graph, memory, compact, background work, cron, teams, worktrees, and MCP should all attach to the same loop, not live in separate examples.\n\ns19 Comprehensive Agent → Combine the mechanisms from s01-s18 into one complete harness. Many mechanisms, one loop.\n\n\n\n" }, { "version": "s18", "locale": "zh", - "title": "s18: Worktree Isolation — 各干各的,互不干扰", - "content": "# s18: Worktree Isolation — 各干各的,互不干扰\n\ns01 → ... → s16 → s17 → `s18` → [s19](/zh/s19) → s20 → s21 → s22\n\n> *\"各干各的目录, 互不干扰\"* — 任务管目标, worktree 管目录, 按 ID 绑定。\n>\n> **Harness 层**: 隔离 — 并行执行的目录隔离。\n\n---\n\n## 问题\n\ns17 中,Alice 和 Bob 都在同一个目录下工作。Alice 的任务是\"重构认证模块\",Bob 的任务是\"重构 UI 登录页\"。\n\nAlice `write_file(\"config.py\", ...)`。Bob 也 `write_file(\"config.py\", ...)`。两个人改同一个文件,互相覆盖。而且无法干净地回滚——分不清哪些改动是谁的。\n\ns15-s17 解决了\"谁干什么\"(任务系统)和\"怎么通信\"(消息总线),但没解决\"在哪干\"。\n\n---\n\n## 解决方案\n\n![Worktree Overview](/course-assets/s18_worktree_isolation/worktree-overview.svg)\n\nGit worktree 让你在同一仓库中创建多个独立的工作目录,每个有自己的分支。Alice 在 `.worktrees/auth-refactor/` 下工作,Bob 在 `.worktrees/ui-login/` 下工作——互不干扰。\n\n沿用 S17 的教学版 MessageBus、协议和自治认领机制。本章新增:\n\n| 能力 | 作用 |\n|------|------|\n| create_worktree | 为任务创建独立目录 + 独立分支 |\n| bind_task_to_worktree | 把任务和工作目录绑定(不改状态) |\n| remove_worktree / keep_worktree | 完成后清理或保留 |\n| validate_worktree_name | 拒绝路径穿越和非法字符 |\n\n---\n\n## 工作原理\n\n### 创建:任务-Worktree 绑定\n\n```python\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n validate_worktree_name(name) # 只允许 [A-Za-z0-9._-]{1,64}\n path = WORKTREES_DIR / name\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n return f\"Worktree '{name}' created at {path}\"\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name # 只写 worktree 字段\n save_task(task) # 状态保持 pending,等队友 claim\n```\n\n绑定规则:一个任务绑定一个 worktree。绑定不改任务状态——任务仍是 `pending`,队友自动认领时才推进到 `in_progress`。这样 Lead 可以提前创建任务和 worktree,队友 idle 时自然认领带 worktree 的任务。\n\n### 队友工具的 cwd 切换\n\n教学版给每个队友维护一个 `wt_ctx` 字典,记录当前 worktree 路径。队友认领带 worktree 的任务时,`wt_ctx` 自动设置为 worktree 路径;队友的 `bash`、`read_file`、`write_file` 在 worktree 目录下执行:\n\n```python\n# 队友线程内部\nwt_ctx = {\"path\": None}\n\ndef _run_claim_task(task_id):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n return result\n\ndef _run_bash(command):\n return run_bash(command, cwd=wt_ctx[\"path\"]) # 在 worktree 下执行\n```\n\n这是教学简化。真实 CC 的 EnterWorktree 用 `process.chdir()` 切换整个进程目录,AgentTool isolation 用 `cwdOverride` 包住子 agent 执行。\n\n### 收尾:Keep 还是 Remove\n\n任务完成后,两个选择:\n\n```python\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n # 安全检查:有改动时默认拒绝\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files > 0 or commits > 0:\n return \"有未提交改动,使用 discard_changes=true 强制删除,或 keep_worktree 保留\"\n ok, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok:\n return \"删除失败\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n\ndef keep_worktree(name: str) -> str:\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n```\n\nKeep = 留着分支,等人工 review 后合并到主分支。Remove = 有改动时默认拒绝,需要 `discard_changes=true` 确认。不自动 complete task——任务完成由队友的 `complete_task` 显式触发。\n\n### 事件流:可审计\n\n每次生命周期操作写入日志,方便排查:\n\n```python\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n # append to .worktrees/events.jsonl\n```\n\n事件类型:`create`(创建)、`remove`(删除)、`keep`(保留)。教学版只记录事件用于人工排查;完整恢复还需要 index 或 `git worktree list` 扫描。\n\n### run_git:返回成功/失败\n\n```python\ndef run_git(args: list[str]) -> tuple[bool, str]:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR, ...)\n return r.returncode == 0, output\n```\n\n`create_worktree` 和 `remove_worktree` 只在 git 命令成功后才写事件日志,保证日志反映真实状态。\n\n---\n\n## 相对 s17 的变更\n\n| 组件 | 之前 (s17) | 之后 (s18) |\n|------|-----------|-----------|\n| 工作目录 | 所有 Agent 共享 WORKDIR | 每个任务可绑定独立 git worktree |\n| Task 数据 | id/subject/status/owner/blockedBy | + worktree 字段 |\n| 队友工具 cwd | 始终 WORKDIR | 认领带 worktree 的任务时自动切换 |\n| 新函数 | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name |\n| worktree 安全 | 无 | name 校验 + 有改动时拒绝删除 |\n| 事件日志 | 无 | events.jsonl 生命周期审计 |\n| Lead 工具 | 14 (s17) | + create_worktree, remove_worktree, keep_worktree (17) |\n| 队友工具 | 8 (s17) | 8(bash/read/write 在 worktree cwd 执行) |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s18_worktree_isolation/code.py\n```\n\n试试这个 prompt:\n\n`Create two tasks, then create worktrees for each (bind with task_id). Spawn alice and bob. Watch them auto-claim and work in isolated directories.`\n\n观察重点:两个 worktree 的 `git status` 输出是否显示不同的分支?队友认领带 worktree 的任务后,bash 命令是否在 worktree 目录下执行?`remove_worktree` 对有改动的 worktree 是否拒绝?`.tasks/` 中的任务在绑定后状态是否仍为 `pending`?\n\n---\n\n## 接下来\n\nAgent 团队能在隔离的工作空间中自组织了。但 Agent 的能力受限于我们给它写的工具——bash、read、write、task...\n\n如果用户已经有了自己的工具怎么办?比如一个公司内部的 Jira API、一个自建的部署系统?\n\ns19 MCP Plugin → 给 Agent 装一个插件系统。外部工具通过标准协议接入,Agent 不需要知道它们是谁写的。\n\n
\n深入 CC 源码\n\nCC 的 worktree 系统有两条路径:**EnterWorktree**(当前会话切入)和 **AgentTool isolation**(子 agent 隔离)。\n\n### EnterWorktree:当前会话切换\n\n`EnterWorktreeTool.ts:92-97` 创建 worktree 后立即 `process.chdir(worktreePath)`、`setCwd()`、`setOriginalCwd()`、`saveWorktreeState()`。当前会话的工作目录直接切换到 worktree——不是 prompt 提醒,而是进程级目录变更。\n\n`ExitWorktreeTool.ts:261-320` 的 keep/remove 都会 `restoreSessionToOriginalCwd()` 恢复原目录。Remove 时检查未提交改动(`ExitWorktreeTool.ts:190-220`),没有 `discard_changes: true` 就拒绝删除。\n\n### AgentTool isolation:子 agent 隔离\n\n`AgentTool.tsx:590-641` 在 `isolation: \"worktree\"` 时调用 `createAgentWorktree()` 创建 worktree,用 `cwdOverridePath` 包住子 agent 执行。子 agent 的所有操作自动在 worktree 目录下进行。`AgentTool/prompt.ts:272` 告诉模型:这是临时 worktree,无改动自动清理,有改动返回路径和分支。\n\n`worktree.ts:902-951` 的 `createAgentWorktree()` 不修改全局 session cwd,只给子 agent 用。`worktree.ts:961-1020` 的 `removeAgentWorktree()` 从主 repo root 删除。\n\n### name 校验\n\n`worktree.ts:76-84` 校验 slug:拒绝 `.`/`..`,允许 `[a-zA-Z0-9._-]`。`worktree.ts:48` 定义 `VALID_WORKTREE_SLUG_SEGMENT`。教学版的 `validate_worktree_name` 用同样的规则。\n\n### 路径和分支命名\n\n真实路径是 `.claude/worktrees/`,分支名 `worktree-{slug}`(`worktree.ts:204-227`,斜杠用 `+` 替代)。教学版用 `.worktrees/` 和 `wt/{name}` 简化。\n\n创建时用 `git worktree add -B`(`worktree.ts:326-328`),优先基于 `origin/` 而非当前 HEAD。\n\n### 状态管理\n\nCC 没有 task-worktree 绑定。Worktree 状态通过 `PersistedWorktreeSession`(`worktree.ts:756-768`)管理,字段包括 `originalCwd`、`worktreePath`、`worktreeName`、`worktreeBranch`、`originalBranch`、`originalHeadCommit`、`sessionId` 等——没有 taskId。`saveWorktreeState()`(`sessionStorage.ts:2883-2920`)以 `type: 'worktree-state'` 写入 session transcript。\n\n教学版用 task 的 `worktree` 字段做绑定,是教学简化。CC 把 worktree 和 task 作为两个独立系统,通过 Agent 理解上下文来关联。\n\n
\n\n\n" + "title": "s18: MCP Tools — 外接工具,标准协议", + "content": "# s18: MCP Tools — 外接工具,标准协议\n\ns01 → ... → s16 → s17 → `s18` → [s19](/zh/s19) → s20 → s21\n\n> *\"外接工具, 标准协议\"* — 发现、组装、调用,Agent 不需要知道工具是谁写的。\n>\n> **Harness 层**: 插件 — 外部能力通过标准协议接入。\n\n---\n\n## 问题\n\ns01 到 s17,Agent 的所有工具都是手写的——bash、read、write、task、worktree。每个工具的输入验证、执行逻辑、错误处理,都是你一行行写的。\n\n现在你有 3 个外部服务想接入:公司的 Jira API(查 issue、建 ticket)、自建的部署系统(触发 deploy、看日志)、团队的 Notion 知识库(搜文档、建页面)。你不想为每个服务重写一套工具代码。\n\n你需要一个标准协议——外部服务只要实现它,Agent 就能直接调用,不管服务用什么语言写的。\n\n---\n\n## 解决方案\n\n![MCP Architecture](/course-assets/s18_mcp_plugin/mcp-architecture.svg)\n\nMCP(Model Context Protocol)定义了 Agent 如何发现和调用外部工具。核心概念:\n\n| 概念 | 作用 |\n|------|------|\n| MCPClient | Agent 端的客户端,连接 server、发现工具、调用工具 |\n| MCP Server | 外部服务,实现 `tools/list` + `tools/call` |\n| assemble_tool_pool | 把内置工具和 MCP 工具组装成一个工具池 |\n| mcp\\_\\_server\\_\\_tool 命名 | 避免不同 server 的工具名冲突 |\n\n沿用 s17 的 worktree 隔离、自主认领和团队协议。本章新增 `connect_mcp` 工具,用于连接服务、发现工具并加入工具池。\n\n本章注册进程内 server handler,让工具发现和调用流程可以离线运行。每个 handler 都提供客户端需要的 `tools/list` 和 `tools/call` 两个操作。\n\n---\n\n## 工作原理\n\n### MCPClient:发现 + 调用\n\n```python\nclass MCPClient:\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs, handlers):\n \"\"\"Simulates tools/list discovery.\"\"\"\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n \"\"\"Simulates tools/call.\"\"\"\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n return handler(**args)\n```\n\n注册的 Python 函数提供 `tools/call` 所调用的 server 端工具实现。\n\n### connect_mcp:连接 + 发现\n\n```python\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n return f\"Unknown server '{name}'. Available: ...\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n return f\"Connected to '{name}'. Discovered: ...\"\n```\n\n连接后,server 提供的工具立即可用。\n\n### normalize_mcp_name:名称规范化\n\n```python\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\ndef normalize_mcp_name(name: str) -> str:\n return _DISALLOWED_CHARS.sub('_', name)\n```\n\n所有非 `[a-zA-Z0-9_-]` 的字符替换为 `_`。防止 server 名或工具名中包含特殊字符导致命名冲突或注入问题。\n\n### assemble_tool_pool:组装工具池\n\n```python\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append(...)\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw:\n c.call_tool(t, kw))\n return tools, handlers\n```\n\n前缀 `mcp__{server}__{tool}` 避免不同 server 的工具名冲突。名称经过 `normalize_mcp_name` 规范化。\n\nMCP 工具的 description 带 `(readOnly)` 或 `(destructive)` 标注,让只读操作和修改操作在工具元数据中直接可见。\n\n### 无缓存:工具池变了,prompt 也变\n\ns10-s17 的 agent_loop 用 prompt cache 避免重复序列化。s18 去掉了缓存:\n\n```python\ndef agent_loop(messages, context):\n tools, handlers = assemble_tool_pool() # 每次重新构建\n system = assemble_system_prompt(context) # 每次重新生成\n ...\n if any(b.name == \"connect_mcp\" ...):\n tools, handlers = assemble_tool_pool() # 连接后重建\n system = assemble_system_prompt(context)\n```\n\n`connect_mcp` 之后,工具池会新增 `mcp__docs__search` 等条目。继续复用旧的序列化工具列表,模型就看不到这些工具,所以每次连接后都要重建工具池和 system prompt。\n\n### MCP 工具只有 Lead 可用\n\n`connect_mcp` 属于 Lead,`assemble_tool_pool` 也服务于 Lead 的 agent loop。Teammate 保留任务、文件、消息和计划工具,由 Lead 调用外部服务,再把得到的工作分派下去。\n\n---\n\n## 相对 s17 的变更\n\n| 组件 | 之前 (s17) | 之后 (s18) |\n|------|-----------|-----------|\n| 工具来源 | 全部手写 builtin | 手写 + MCP 外部工具动态发现 |\n| 工具池 | 固定 BUILTIN_TOOLS | assemble_tool_pool 动态组装 mcp\\_\\_ 前缀工具 |\n| 名称安全 | 无 | normalize_mcp_name 规范化 |\n| 新类型 | — | MCPClient 类(模拟 tools/list + tools/call) |\n| 命名空间 | — | mcp\\_\\_server\\_\\_tool 避免冲突 |\n| 工具描述 | 无标注 | (readOnly)/(destructive) 标注 |\n| prompt 缓存 | 有(s10 起) | 去掉——工具池动态变化后缓存失效 |\n| Lead 工具 | worktree 与团队工具 | + connect_mcp 和动态发现的 MCP 工具 |\n| Teammate 工具 | 任务、文件、消息与计划工具 | 不变 |\n| 扩展方式 | 写代码加工具 | 标准协议,任意语言实现 server |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s18_mcp_plugin/code.py\n```\n\n试试这些 prompt:\n\n1. `查一下文档里的 worktree 清理策略。`\n2. `部署当前项目,并告诉我结果。`\n3. `你现在可以执行哪些文档和部署操作?`\n\n观察重点:连接 MCP server 后,工具名是否带 `mcp__docs__` 或 `mcp__deploy__` 前缀?两个 server 的工具是否同时可用?MCP 工具的 description 是否带 (readOnly)/(destructive) 标注?\n\n---\n\n## 接下来\n\n现在 Agent 可以通过标准协议接入外部工具了。前 18 章逐个引入这些机制,让每个边界都能单独观察。\n\n工具、权限、hooks、todo、任务图、记忆、压缩、后台、cron、团队、worktree、MCP 这些机制应该挂在同一个循环上,而不是散在 19 个 demo 里。\n\ns19 Comprehensive Agent → 把 s01-s18 的机制合回一个完整 harness。机制很多,循环一个。\n\n\n\n" }, { "version": "s18", "locale": "ja", - "title": "s18: Worktree Isolation — それぞれのディレクトリ、互いに干渉しない", - "content": "# s18: Worktree Isolation — それぞれのディレクトリ、互いに干渉しない\n\ns01 → ... → s16 → s17 → `s18` → [s19](/ja/s19) → s20 → s21 → s22\n\n> *\"それぞれのディレクトリ、互いに干渉しない\"* — タスクは目標を管理、worktree はディレクトリを管理、ID で紐付け。\n>\n> **Harness 層**: 隔離 — 並列実行のディレクトリ分離。\n\n---\n\n## 課題\n\ns17 では、Alice も Bob も同じディレクトリで作業。Alice のタスクは「認証モジュールのリファクタリング」、Bob のタスクは「UI ログインページのリファクタリング」。\n\nAlice が `write_file(\"config.py\", ...)` を呼び出し、Bob も `write_file(\"config.py\", ...)` を呼び出す。両者が同じファイルを編集し、互いに上書き。クリーンなロールバックもできない——どの変更が誰のものか区別できない。\n\ns15-s17 は「誰が何をするか」(タスクシステム)と「どう通信するか」(メッセージバス)を解決したが、「どこで作業するか」は未解決。\n\n---\n\n## ソリューション\n\n![Worktree Overview](/course-assets/s18_worktree_isolation/worktree-overview.ja.svg)\n\nGit worktree を使うと、同じリポジトリ内に複数の独立した作業ディレクトリを作成でき、それぞれが独自のブランチを持つ。Alice は `.worktrees/auth-refactor/` で作業、Bob は `.worktrees/ui-login/` で作業——互いに干渉しない。\n\nS17 の教学版 MessageBus、プロトコル、自治認領機構を踏襲。本章の追加:\n\n| 機能 | 目的 |\n|------|------|\n| create_worktree | タスク用の独立ディレクトリ + 独立ブランチを作成 |\n| bind_task_to_worktree | タスクとディレクトリを紐付け(状態は変更しない) |\n| remove_worktree / keep_worktree | 完了後のクリーンアップまたは保持 |\n| validate_worktree_name | パストラバーサルと不正文字を拒否 |\n\n---\n\n## 仕組み\n\n### 作成:タスク-Worktree 紐付け\n\n```python\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n validate_worktree_name(name) # [A-Za-z0-9._-]{1,64} のみ許可\n path = WORKTREES_DIR / name\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n return f\"Worktree '{name}' created at {path}\"\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name # worktree フィールドのみ書き込み\n save_task(task) # 状態は pending のまま、チームメイトの claim を待つ\n```\n\n紐付けルール:1 つのタスクに 1 つの worktree を紐付け。紐付けはタスクの状態を変更しない——タスクは `pending` のままで、チームメイトが認領した時に `in_progress` に進む。これにより Lead は事前にタスクと worktree を作成でき、チームメイトは idle 時に自然に worktree 紐付け済みタスクを認領する。\n\n### チームメイトツールの cwd 切り替え\n\n教学版は各チームメイトに `wt_ctx` 辞書を維持し、現在の worktree パスを追跡。チームメイトが worktree 紐付けタスクを認領すると、`wt_ctx` が自動的に worktree パスに設定され、チームメイトの `bash`、`read_file`、`write_file` は worktree ディレクトリで実行される:\n\n```python\n# チームメイトスレッド内部\nwt_ctx = {\"path\": None}\n\ndef _run_claim_task(task_id):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n return result\n\ndef _run_bash(command):\n return run_bash(command, cwd=wt_ctx[\"path\"]) # worktree で実行\n```\n\nこれは教学簡略化。真实 CC の EnterWorktree は `process.chdir()` でプロセス全体のディレクトリを切り替え、AgentTool isolation は `cwdOverride` でサブエージェント実行をラップする。\n\n### クリーンアップ:Keep または Remove\n\nタスク完了後、2 つの選択肢:\n\n```python\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n # 安全チェック:変更がある場合デフォルトで拒否\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files > 0 or commits > 0:\n return \"未コミットの変更あり。discard_changes=true で強制削除、または keep_worktree で保持\"\n ok, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok:\n return \"削除失敗\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n\ndef keep_worktree(name: str) -> str:\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n```\n\nKeep = ブランチを保持し、手動 review 後にマージ。Remove = 未コミット変更がある場合デフォルトで拒否、`discard_changes=true` で確認が必要。タスクの自動 complete はしない——タスク完了はチームメイトの `complete_task` で明示的にトリガー。\n\n### イベントログ:監査可能\n\n各ライフサイクル操作はログに記録され、監査に利用:\n\n```python\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n # .worktrees/events.jsonl に append\n```\n\nイベントタイプ:`create`、`remove`、`keep`。教学版はイベントを記録するだけで手動監査用。完全な復元には index または `git worktree list` スキャンが必要。\n\n### run_git:成功/失敗を返す\n\n```python\ndef run_git(args: list[str]) -> tuple[bool, str]:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR, ...)\n return r.returncode == 0, output\n```\n\n`create_worktree` と `remove_worktree` は git コマンド成功後のみイベントログに書き込み、ログが実際の状態を反映することを保証。\n\n---\n\n## s17 からの変更\n\n| コンポーネント | 変更前 (s17) | 変更後 (s18) |\n|--------------|------------|------------|\n| 作業ディレクトリ | 全 Agent が WORKDIR を共有 | 各タスクが git worktree に紐付け可能 |\n| タスクデータ | id/subject/status/owner/blockedBy | + worktree フィールド |\n| チームメイトツール cwd | 常に WORKDIR | worktree 紐付けタスク認領時に自動切り替え |\n| 新規関数 | — | create_worktree, bind_task_to_worktree, remove_worktree, keep_worktree, validate_worktree_name |\n| worktree 安全性 | なし | name 検証 + 変更ありの場合削除拒否 |\n| イベントログ | なし | events.jsonl ライフサイクル監査 |\n| Lead ツール | 14 (s17) | + create_worktree, remove_worktree, keep_worktree (17) |\n| チームメイトツール | 8 (s17) | 8(bash/read/write が worktree cwd で実行) |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s18_worktree_isolation/code.py\n```\n\n以下のプロンプトを試してください:\n\n`Create two tasks, then create worktrees for each (bind with task_id). Spawn alice and bob. Watch them auto-claim and work in isolated directories.`\n\n観察ポイント:2 つの worktree の `git status` 出力は異なるブランチを表示しているか?チームメイトが worktree 紐付けタスクを認領後、bash コマンドは worktree ディレクトリで実行されているか?`remove_worktree` は変更がある場合に拒否するか?紐付け後のタスク状態は `pending` のままか?\n\n---\n\n## 次の章\n\nAgent チームが隔離されたワークスペースで自己組織化できるようになった。しかし Agent の能力はツールに制限される——bash、read、write、task...\n\nもしユーザーが独自のツールを持っていたら?例えば社内 Jira API や独自デプロイシステム?\n\ns19 MCP Plugin → Agent にプラグインシステムを追加。外部ツールが標準プロトコルで接続、Agent は誰が書いたか知る必要がない。\n\n
\nCC ソースコード深掘り\n\nCC の worktree システムには 2 つのパスがある:**EnterWorktree**(現在のセッションが切り替え)と **AgentTool isolation**(サブエージェント隔離)。\n\n### EnterWorktree:現在のセッション切り替え\n\n`EnterWorktreeTool.ts:92-97` worktree 作成後、直ちに `process.chdir(worktreePath)`、`setCwd()`、`setOriginalCwd()`、`saveWorktreeState()` を呼び出し。現在のセッションの作業ディレクトリが直接 worktree に切り替わる——プロンプトのヒントではなく、プロセスレベルのディレクトリ変更。\n\n`ExitWorktreeTool.ts:261-320` keep/remove どちらも `restoreSessionToOriginalCwd()` で元のディレクトリに復元。Remove は未コミット変更をチェック(`ExitWorktreeTool.ts:190-220`)、`discard_changes: true` なしでは拒否。\n\n### AgentTool Isolation:サブエージェント隔離\n\n`AgentTool.tsx:590-641` `isolation: \"worktree\"` の場合、`createAgentWorktree()` を呼び出して worktree を作成し、`cwdOverridePath` でサブエージェント実行をラップ。サブエージェントの全操作が自動的に worktree ディレクトリで実行される。`AgentTool/prompt.ts:272` はモデルに伝える:これは一時的な worktree、変更なしで自動クリーンアップ、変更ありの場合はパスとブランチを返す。\n\n`worktree.ts:902-951` `createAgentWorktree()` はグローバル session cwd を変更せず、サブエージェント専用。`worktree.ts:961-1020` `removeAgentWorktree()` はメインリポジトリルートから削除。\n\n### name 検証\n\n`worktree.ts:76-84` slug を検証:`.`/`..` を拒否、`[a-zA-Z0-9._-]` を許可。`worktree.ts:48` で `VALID_WORKTREE_SLUG_SEGMENT` を定義。教学版の `validate_worktree_name` も同じルールを使用。\n\n### パスとブランチ命名\n\n実際のパスは `.claude/worktrees/`、ブランチ名は `worktree-{slug}`(`worktree.ts:204-227`、スラッシュは `+` に置換)。教学版は `.worktrees/` と `wt/{name}` で簡略化。\n\n作成時は `git worktree add -B`(`worktree.ts:326-328`)を使用し、現在の HEAD より `origin/` を優先。\n\n### 状態管理\n\nCC にはタスク-worktree 紐付けがない。Worktree 状態は `PersistedWorktreeSession`(`worktree.ts:756-768`)で管理、フィールドは `originalCwd`、`worktreePath`、`worktreeName`、`worktreeBranch`、`originalBranch`、`originalHeadCommit`、`sessionId` 等を含む——taskId フィールドはない。`saveWorktreeState()`(`sessionStorage.ts:2883-2920`)は `type: 'worktree-state'` で session transcript に書き込み。\n\n教学版はタスクの `worktree` フィールドで紐付けを行う教学簡略化。CC は worktree とタスクを 2 つの独立システムとして扱い、Agent のコンテキスト理解で関連付ける。\n\n
\n\n\n" + "title": "s18: MCP Tools — 外部ツール、標準プロトコル", + "content": "# s18: MCP Tools — 外部ツール、標準プロトコル\n\ns01 → ... → s16 → s17 → `s18` → [s19](/ja/s19) → s20 → s21\n\n> *\"外部ツール、標準プロトコル\"* — 発見、組み立て、呼び出し。Agent はツールを誰が書いたか知る必要がない。\n>\n> **Harness 層**: プラグイン — 外部能力を標準プロトコルで接続。\n\n---\n\n## 課題\n\ns01 から s17 まで、Agent の全ツールは手書き — bash、read、write、task、worktree。入力検証、実行ロジック、エラーハンドリング、全て一行ずつ書いた。\n\n今、統合したい外部サービスが 3 つある:社内の Jira API(issue 検索、ticket 作成)、独自のデプロイシステム(deploy トリガー、ログ閲覧)、チームの Notion ナレッジベース(ドキュメント検索、ページ作成)。各サービスのためにツールコードを書き直したくない。\n\n標準プロトコルが必要 — 外部サービスがこのプロトコルを実装していれば、サービスが何の言語で書かれていても、Agent は直接そのツールを呼び出せる。\n\n---\n\n## ソリューション\n\n![MCP Architecture](/course-assets/s18_mcp_plugin/mcp-architecture.ja.svg)\n\nMCP(Model Context Protocol)は、Agent が外部ツールを発見・呼び出しする方法を定義。核心概念:\n\n| 概念 | 目的 |\n|------|------|\n| MCPClient | Agent 側のクライアント — server に接続、ツールを発見、ツールを呼び出し |\n| MCP Server | 外部サービス側 — `tools/list` + `tools/call` を実装 |\n| assemble_tool_pool | 組み込みツールと MCP ツールを一つのツールプールに組み立てる |\n| mcp\\_\\_server\\_\\_tool 命名 | 異なる server 間のツール名衝突を防止 |\n\ns17 の worktree 分離、自動認領、チームプロトコルを引き継ぐ。本章では `connect_mcp` ツールを追加し、サービスへの接続、ツール発見、ツールプールへの追加を行う。\n\n本章はプロセス内の server handler を登録し、発見から呼び出しまでをオフラインで実行する。各 handler はクライアントが必要とする `tools/list` と `tools/call` を提供する。\n\n---\n\n## 仕組み\n\n### MCPClient:発見 + 呼び出し\n\n```python\nclass MCPClient:\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs, handlers):\n \"\"\"Simulates tools/list discovery.\"\"\"\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n \"\"\"Simulates tools/call.\"\"\"\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n return handler(**args)\n```\n\n登録した Python 関数が、`tools/call` から呼ばれる server 側のツール実装になる。\n\n### connect_mcp:接続 + 発見\n\n```python\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n return f\"Unknown server '{name}'. Available: ...\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n return f\"Connected to '{name}'. Discovered: ...\"\n```\n\n接続後、server が提供するツールが即座に利用可能。\n\n### normalize_mcp_name:名前の正規化\n\n```python\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\ndef normalize_mcp_name(name: str) -> str:\n return _DISALLOWED_CHARS.sub('_', name)\n```\n\n`[a-zA-Z0-9_-]` 以外の全文字を `_` に置換。server 名やツール名の特殊文字による名前衝突やインジェクション問題を防止。\n\n### assemble_tool_pool:ツールプールの組み立て\n\n```python\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append(...)\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw:\n c.call_tool(t, kw))\n return tools, handlers\n```\n\nプレフィックス `mcp__{server}__{tool}` で異なる server 間のツール名衝突を防止。名前は `normalize_mcp_name` で正規化。\n\nMCP ツールの description に `(readOnly)` または `(destructive)` を付け、読み取りと変更の区別をツールメタデータ上で明示する。\n\n### キャッシュなし:ツールプールが変われば、プロンプトも変わる\n\ns10-s17 の agent_loop は prompt cache で再シリアライズを回避。s18 はキャッシュを削除:\n\n```python\ndef agent_loop(messages, context):\n tools, handlers = assemble_tool_pool() # 毎回再構築\n system = assemble_system_prompt(context) # 毎回再生成\n ...\n if any(b.name == \"connect_mcp\" ...):\n tools, handlers = assemble_tool_pool() # 接続後に再構築\n system = assemble_system_prompt(context)\n```\n\n`connect_mcp` の後には `mcp__docs__search` などがツールプールへ加わる。古いシリアライズ済みツール一覧を再利用するとモデルから新しいツールが見えないため、接続後にツールプールと system prompt を再構築する。\n\n### MCP ツールは Lead のみ利用可能\n\n`connect_mcp` は Lead のツールであり、`assemble_tool_pool` も Lead の agent loop に使われる。チームメイトはタスク、ファイル、メッセージ、プランの各ツールを保持し、Lead が外部サービスを呼び出して得た仕事を割り当てる。\n\n---\n\n## s17 からの変更\n\n| コンポーネント | 変更前 (s17) | 変更後 (s18) |\n|--------------|------------|------------|\n| ツールソース | 全て手書き builtin | 手書き + MCP 外部ツール動的発見 |\n| ツールプール | 固定 BUILTIN_TOOLS | assemble_tool_pool が動的に mcp\\_\\_ プレフィックスツールを組み立てる |\n| 名前の安全性 | なし | normalize_mcp_name 正規化 |\n| 新規タイプ | — | MCPClient クラス(tools/list + tools/call をシミュレート) |\n| 名前空間 | — | mcp\\_\\_server\\_\\_tool 衝突防止 |\n| ツール説明 | アノテーションなし | (readOnly)/(destructive) アノテーション |\n| プロンプトキャッシュ | あり(s10 から) | 削除 — ツールプールが動的、キャッシュが陳腐化 |\n| Lead ツール | worktree・チームツール | + connect_mcp と動的に発見した MCP ツール |\n| チームメイトツール | タスク、ファイル、メッセージ、プランのツール | 変更なし |\n| 拡張方法 | ツール追加のコードを書く | 標準プロトコル、任意言語で server を実装 |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s18_mcp_plugin/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `ドキュメントから worktree のクリーンアップ方針を調べてください。`\n2. `現在のプロジェクトをデプロイし、結果を報告してください。`\n3. `現在実行できるドキュメント操作とデプロイ操作を教えてください。`\n\n観察ポイント:MCP server 接続後、ツール名に `mcp__docs__` や `mcp__deploy__` プレフィックスが付いているか?両方の server のツールが同時に利用可能か?MCP ツールの description に (readOnly)/(destructive) アノテーションが付いているか?\n\n---\n\n## 次の章\n\nAgent は標準プロトコルで外部ツールに接続できるようになった。前 18 章では、各境界を観察できるように仕組みを一つずつ追加してきた。\n\ntools、permissions、hooks、todo、task graph、memory、compact、background work、cron、teams、worktree、MCP は、別々の例ではなく同じ loop に接続されるべきです。\n\ns19 Comprehensive Agent → s01-s18 の仕組みを 1 つの完全な harness に統合。仕組みは多く、loop は 1 つ。\n\n\n\n" }, { "version": "s19", "locale": "en", - "title": "s19: MCP Tools — External Tools, Standard Protocol", - "content": "# s19: MCP Tools — External Tools, Standard Protocol\n\ns01 → ... → s17 → s18 → `s19` → [s20](/en/s20) → s21 → s22\n\n> *\"External tools, standard protocol\"* — Discover, assemble, invoke. Agent doesn't need to know who wrote them.\n>\n> **Harness layer**: Plugins — External capabilities via a standard protocol.\n\n---\n\n## The Problem\n\nFrom s01 through s18, every tool the agent uses was hand-written — bash, read, write, task, worktree. Input validation, execution logic, error handling — all written line by line.\n\nNow you have 3 external services to integrate: the company's Jira API (query issues, create tickets), an in-house deployment system (trigger deploys, view logs), and the team's Notion knowledge base (search docs, create pages). You don't want to rewrite tool code for every service.\n\nYou need a standard protocol — as long as an external service implements it, the agent can call its tools directly, regardless of what language the service is written in.\n\n---\n\n## The Solution\n\n![MCP Architecture](/course-assets/s19_mcp_plugin/mcp-architecture.en.svg)\n\nMCP (Model Context Protocol) defines how agents discover and invoke external tools. Core concepts:\n\n| Concept | Purpose |\n|------|------|\n| MCPClient | The agent-side client — connects to servers, discovers tools, invokes tools |\n| MCP Server | The external service — implements `tools/list` + `tools/call` |\n| assemble_tool_pool | Assembles built-in tools and MCP tools into one tool pool |\n| mcp\\_\\_server\\_\\_tool naming | Prevents tool name collisions across different servers |\n\nCarries forward s18's teaching-version worktree isolation, autonomous claiming, idle polling, and protocol system. This chapter adds: the `connect_mcp` tool — connect to external services, discover tools, add them to the tool pool.\n\nThe tutorial uses mock handlers to simulate external servers. The real version would spawn subprocesses and communicate via stdin/stdout JSON-RPC. Mocks let you run the full flow without external dependencies; the tradeoff is you don't see real network communication or process management.\n\n---\n\n## How It Works\n\n### MCPClient: Discovery + Invocation\n\n```python\nclass MCPClient:\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs, handlers):\n \"\"\"Simulates tools/list discovery.\"\"\"\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n \"\"\"Simulates tools/call.\"\"\"\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n return handler(**args)\n```\n\nThe tutorial uses Python functions to simulate server tool implementations. The real version communicates with subprocesses via stdio JSON-RPC.\n\n### connect_mcp: Connect + Discover\n\n```python\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n return f\"Unknown server '{name}'. Available: ...\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n return f\"Connected to '{name}'. Discovered: ...\"\n```\n\nAfter connecting, the server's tools are immediately available.\n\n### normalize_mcp_name: Name Normalization\n\n```python\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\ndef normalize_mcp_name(name: str) -> str:\n return _DISALLOWED_CHARS.sub('_', name)\n```\n\nAll non-`[a-zA-Z0-9_-]` characters are replaced with `_`. Prevents special characters in server or tool names from causing naming conflicts or injection issues.\n\n### assemble_tool_pool: Assemble Tool Pool\n\n```python\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append(...)\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw:\n c.call_tool(t, kw))\n return tools, handlers\n```\n\nThe prefix `mcp__{server}__{tool}` prevents tool name collisions across different servers. Names are normalized through `normalize_mcp_name`.\n\nMCP tool descriptions include `(readOnly)` or `(destructive)` annotations — the tutorial uses text annotations, while real CC uses structured tool annotations for the permission system.\n\n### No Cache: Tool Pool Changes, Prompt Changes Too\n\ns10-s18's agent_loop used prompt caching to avoid re-serialization. s19 removes the cache:\n\n```python\ndef agent_loop(messages, context):\n tools, handlers = assemble_tool_pool() # Rebuild every time\n system = assemble_system_prompt(context) # Regenerate every time\n ...\n if any(b.name == \"connect_mcp\" ...):\n tools, handlers = assemble_tool_pool() # Rebuild after connection\n system = assemble_system_prompt(context)\n```\n\nReason: after `connect_mcp`, the tool pool changes — new tools like `mcp__docs__search` are added. The cached tool list is stale; continuing to use it means the model can't call the new tools. The tutorial simply removes caching, at the cost of slightly more serialization time.\n\n### MCP Tools: Lead Only\n\nIn the tutorial, `connect_mcp` is a Lead tool, and `assemble_tool_pool` only serves the Lead's agent_loop. Teammates still use a fixed 8-tool subset (bash, read_file, write_file, send_message, submit_plan, list_tasks, claim_task, complete_task).\n\nThis is a teaching simplification. In real CC, MCP tools are available to both the main agent and sub-agents — sub-agents inherit the parent's MCP configuration.\n\n---\n\n## Changes from s18\n\n| Component | Before (s18) | After (s19) |\n|------|-----------|-----------|\n| Tool source | All hand-written built-in | Hand-written + MCP external tools with dynamic discovery |\n| Tool pool | Fixed BUILTIN_TOOLS | assemble_tool_pool dynamically assembles mcp\\_\\_ prefixed tools |\n| Name safety | None | normalize_mcp_name normalization |\n| New type | — | MCPClient class (simulates tools/list + tools/call) |\n| Namespace | — | mcp\\_\\_server\\_\\_tool prevents collisions |\n| Tool descriptions | No annotations | (readOnly)/(destructive) annotations |\n| Prompt cache | Yes (since s10) | Removed — tool pool is dynamic, cache goes stale |\n| Lead tools | 17 (s18) | 18 (+connect_mcp) |\n| Teammate tools | 8 (s18) | 8 (unchanged, MCP tools are Lead-only) |\n| Extension method | Write code to add tools | Standard protocol, implement servers in any language |\n\n---\n\n## Try It Out\n\n```sh\ncd learn-claude-code\npython s19_mcp_plugin/code.py\n```\n\nTry these prompts:\n\n1. `Connect to the docs MCP server and search for something`\n2. `Connect to the deploy server and trigger a deployment`\n3. `Connect both servers — what tools are now available?`\n\nWhat to observe: After connecting to an MCP server, do tool names have `mcp__docs__` or `mcp__deploy__` prefixes? Are both servers' tools available simultaneously? Do MCP tool descriptions include (readOnly)/(destructive) annotations?\n\n---\n\n## What's Next\n\nThe Agent can now connect external tools through a standard protocol. But the first 19 chapters each add one mechanism in isolation; a real Agent does not run as 19 separate demos.\n\nTools, permissions, hooks, todo, task graph, memory, compact, background work, cron, teams, worktrees, and MCP should all attach to the same loop, not live in separate examples.\n\ns20 Comprehensive Agent → Combine the first 19 chapters into one complete harness. Many mechanisms, one loop.\n\n
\nDeep Dive into CC Source\n\n> The following is based on analysis of CC source: `services/mcp/client.ts`, `auth.ts`, `config.ts`, `channelNotification.ts`.\n\n### 1. Six Transport Types\n\nThe tutorial only shows a stdio mock. CC supports 6 transport types (`types.ts:23-25`):\n\n| Transport | Communication method |\n|-----------|---------|\n| `stdio` | Subprocess stdin/stdout (cross-platform default) |\n| `sse` | HTTP Server-Sent Events |\n| `http` | Streamable HTTP (POST/SSE bidirectional) |\n| `ws` | WebSocket |\n| `sse-ide` | IDE-embedded SSE transport |\n| `sdk` | In-process SDK transport |\n\nOn connection, local (stdio) and remote (http/sse/ws) servers are batched concurrently: local batch of 3, remote batch of 20.\n\n### 2. Tool Pool Merging Algorithm\n\n`assembleToolPool()` (`tools.ts:345-364`):\n\n```typescript\n// Dedup with priority: built-in tools win on name collision (sorted first)\nreturn uniqBy(\n [...builtInTools.sort(byName), ...filteredMcpTools.sort(byName)],\n 'name',\n)\n```\n\nBuilt-in and MCP tools are sorted separately, not together. The reason is CC's `claude_code_system_cache_policy` places a global cache breakpoint after the last built-in tool at a specific position — mixing the sort would break this design.\n\n### 3. Naming Convention: `mcp__server__tool`\n\n`buildMcpToolName()` (`mcpStringUtils.ts:50-52`):\n\n```\nmcp____\n```\n\nAll non-`[a-zA-Z0-9_-]` characters are replaced with `_` (`normalization.ts:17-23`). The tutorial's `normalize_mcp_name` uses the same rule.\n\n### 4. Permission Checks\n\nCC has a separate permission system for MCP tools. `checkPermissions()` applies different logic for MCP tools than for built-in tools — MCP tools can declare their own permission requirements (readOnly, destructive, etc.), and CC decides whether user confirmation is needed based on the declaration. The tutorial only uses text annotations `(readOnly)` / `(destructive)` in descriptions, without permission enforcement.\n\n### 5. Configuration Sources and Priority\n\nMCP server configuration comes from multiple sources. CC's priority from lowest to highest:\n\n```\nclaude.ai connectors < plugin < user settings.json < approved project .mcp.json < local settings.local.json\n```\n\n`claude.ai` connectors are fetched separately, deduplicated by content signature, and merged at the lowest precedence (`config.ts:1267-1289`). When enterprise `managed-mcp.json` exists, all other configurations are excluded.\n\nThe tutorial passes server names directly to the `MOCK_SERVERS` dict, without config merging.\n\n### 6. Channel Notifications: Servers Push Messages Back\n\nThe tutorial only covers agent → MCP Server unidirectional calls. CC also supports reverse notifications (`channelNotification.ts`):\n\n1. Server declares `capabilities.experimental['claude/channel']`\n2. Server sends messages to agent via MCP notification `notifications/claude/channel`\n3. Messages are wrapped in `...` XML tags\n4. Agent is woken up by SleepTool (within 1 second)\n\nServers can also request permissions: `notifications/claude/channel/permission_request` → Agent replies `notifications/claude/channel/permission`. Users confirm/deny via a 5-letter short ID.\n\n### 7. OAuth Authentication Flow\n\nCC's MCP authentication (`auth.ts`) supports a full OAuth 2.0 + PKCE flow:\n- OAuth metadata discovery via public client + PKCE (RFC 8414 / RFC 9728)\n- Local callback server receives authorization code\n- Tokens persisted via `getSecureStorage()` (macOS Keychain / Linux encrypted file / Windows Credential Manager)\n- Auto-refresh 5 minutes before expiry\n- Cross-application access (XAA): browser gets id_token → RFC 8693 + RFC 7523 exchange → no repeated browser popups\n\n### 8. Connection Lifecycle Error Handling\n\nCC has fine-grained error classification and retry for MCP connections (`client.ts:1266-1402`):\n- Terminal errors (ECONNRESET, ETIMEDOUT, EPIPE, etc.): 3 consecutive failures → close + reconnect\n- Tool call 401: Token expired → throw `McpAuthError` → trigger re-authentication\n- Tool call timeout: `Promise.race` timeout (configurable, default ~28 hours)\n- Stdio disconnect: Kill process in SIGINT → SIGTERM → SIGKILL order\n\n### The Tutorial's Simplifications\n\n- 6 transport types → 1 (mock stdio): Manageable concept count\n- Channel reverse notifications → omitted: Tutorial agent is always the initiator\n- OAuth flow → omitted: Tutorial assumes servers need no auth\n- Multi-layer config priority → omitted: Tutorial passes server name directly\n- Complex error classification → omitted: Tutorial uses try/except as fallback\n- MCP tools Lead-only → omitted sub-agent inheritance: Simplifies code structure\n\n
\n\n\n" + "title": "s19: Comprehensive Agent — All Mechanisms, One Loop", + "content": "# s19: Comprehensive Agent — All Mechanisms, One Loop\n\ns01 → ... → s17 → s18 → `s19` → [s20](/en/s20) → s21\n\n> *\"Many mechanisms, one loop\"* — tools, permissions, memory, tasks, teams, and plugins all hang off the same `while True`.\n>\n> **Harness layer**: Comprehensive — put the mechanisms from s01-s18 into one runnable system.\n\n---\n\n## Problem\n\nThe first 18 chapters add one mechanism at a time so each boundary stays visible. This chapter connects them in one runtime.\n\nA long-running coding agent needs all of these at once:\n\n- tool dispatch and permission boundaries\n- hook extension points\n- todo planning and task graphs\n- skills, memory, and runtime system prompt assembly\n- compaction and error recovery\n- background tasks and cron scheduling\n- teams, protocols, autonomous claiming\n- worktree isolation\n- MCP external tool integration\n\nThe hard part is not piling up features. The hard part is seeing where each mechanism belongs around the loop. S19 is the integration checkpoint: every earlier component is placed back into one harness before s20-s21 add orchestration and goal closure around it.\n\n---\n\n## Solution\n\n![System Architecture](/course-assets/s19_comprehensive/system-architecture.en.svg)\n\nS19 does not introduce a new mechanism. It connects the components from the earlier chapters in one complete harness:\n\n```text\nuser input\n → UserPromptSubmit hooks\n → cron/background notification injection\n → context compact\n → memory + skills + MCP state assemble the system prompt\n → LLM\n → has tool_use block?\n no → Stop hooks → return\n yes → PreToolUse hooks + permission\n → TOOL_HANDLERS / MCP handlers / background dispatch\n → PostToolUse hooks\n → tool_result / task_notification back to messages\n → next round\n```\n\nThe loop keeps the same structure: call the model, check whether the response contains a `tool_use` block, execute tools, and append results to `messages`. The presence of a `tool_use` block decides whether tool execution continues.\n\n---\n\n## Where Each Component Sits\n\n| Position | Component | Role |\n|----------|-----------|------|\n| Around user input | `UserPromptSubmit` hooks | Log, inject, or audit user input |\n| Before LLM | cron queue | Inject scheduled prompts into `messages` |\n| Before LLM | background notifications | Inject completed background work as `` |\n| Before LLM | compaction pipeline | Budget large outputs, trim history, compact old tool results, summarize when needed |\n| Before LLM | memory / skills / MCP state | Assemble the system prompt so the model sees current capabilities and long-term context |\n| LLM call | error recovery | Retry 429/529, escalate `max_tokens`, compact on prompt-too-long |\n| Before tool execution | `PreToolUse` hooks + permission | Block dangerous commands, out-of-bounds writes, destructive MCP tools |\n| Tool dispatch | `assemble_tool_pool` | Assemble built-in tools and dynamic MCP tools |\n| During tool execution | background dispatch | Move slow bash work into a daemon thread and return a placeholder result |\n| After tool execution | `PostToolUse` hooks | Large-output warnings, logs, post-processing |\n| Back to loop | tool_result | One `tool_result` per `tool_use`, then the next model round |\n| No tool_use this round / on stop | `Stop` hooks | Stats, cleanup, audit |\n\n---\n\n## What code.py Contains\n\n### Tools and Dispatch\n\nThe built-in tool pool contains 26 tools:\n\n```text\nbash, read_file, write_file, edit_file, glob\ntodo_write, task, load_skill, compact\ncreate_task, list_tasks, get_task, claim_task, complete_task\nschedule_cron, list_crons, cancel_cron\nspawn_teammate, send_message\nrequest_shutdown, request_plan, review_plan\ncreate_worktree, remove_worktree, keep_worktree\nconnect_mcp\n```\n\n`assemble_tool_pool()` assembles these every round:\n\n```text\nBUILTIN_TOOLS + connected MCP tools\nBUILTIN_HANDLERS + mcp__server__tool handlers\n```\n\nAfter `connect_mcp(\"docs\")`, the next round exposes tools like `mcp__docs__search`.\n\n### Permissions and Hooks\n\nPermission is not hardcoded into the tool execution line. It is a `PreToolUse` hook:\n\n```python\nblocked = trigger_hooks(\"PreToolUse\", block)\nif blocked:\n results.append(tool_result(block.id, blocked))\n continue\n```\n\nThat means permission, logging, and audit logic all attach to the same hook point. After execution, `PostToolUse` hooks run.\n\n### Planning and Tasks\n\nS19 keeps two planning layers:\n\n- `todo_write`: lightweight plan for the current session, kept in memory\n- task graph: cross-session, dependency-aware, claimable task files under `.tasks/task_*.json`\n\nThe first keeps a single agent from drifting. The second supports team coordination.\n\nThey share an intent, not an implementation: `todo_write` replaces one session checklist, while task records have stable IDs and individual lifecycle updates. The separate `task` tool below means \"dispatch one isolated subagent\"; it is not the Task System.\n\n### Subagents and Teams\n\nS19 has two kinds of delegation:\n\n- `task`: one-shot subagent. It uses an isolated `messages[]`, discards intermediate context, and returns only a final summary.\n- `spawn_teammate`: persistent teammate thread. The runtime delivers `MessageBus` events, and the teammate scans the task board while idle so it can claim work autonomously.\n\nOne-shot subagents solve context isolation. Persistent teammates solve long-running parallel collaboration.\n\n### Memory, Skills, and Prompt\n\n`assemble_system_prompt(context)` assembles each round from:\n\n- identity and tool guidance\n- workspace\n- skills catalog\n- `.memory/MEMORY.md`\n- connected MCP servers\n\nSkills only put their catalog into the system prompt. Full content is loaded on demand through `load_skill(name)`.\n\n### Compaction and Recovery\n\nBefore the LLM call, S19 runs the compaction pipeline:\n\n```text\ntool_result_budget → snip_compact → micro_compact → compact_history\n```\n\nThe model call is wrapped with recovery:\n\n- 429: exponential backoff retry\n- 529: exponential backoff, optionally switch to fallback model after repeated failures\n- `max_tokens`: raise max tokens, then request continuation\n- prompt too long: reactive compact and retry\n\n### Background and Cron\n\nSlow bash work does not block the main loop:\n\n```text\nshould_run_background → start_background_task → placeholder tool_result\nbackground done → task_notification → next round injects messages\n```\n\nThe cron scheduler runs as a daemon thread and checks once per second. The CLI watches `cron_queue`; when a job fires, it injects `[Scheduled] ...` and runs one agent turn automatically.\n\n### Worktree and MCP\n\nWorktree isolation owns directories:\n\n- `create_worktree(name, task_id)` creates an isolated branch and directory\n- the task `worktree` field binds a task to that directory\n- when a teammate claims a task with a worktree, its bash/read/write tools run in that directory\n\nMCP owns external capability:\n\n- `connect_mcp(name)` connects a mock server\n- `assemble_tool_pool()` assembles MCP tools into the tool pool\n- tool names use `mcp__server__tool`\n\n---\n\n## Changes from s18\n\n| Component | s18 | s19 |\n|-----------|-----|-----|\n| tool pool | built-in + MCP | built-in + MCP, with s01-s17 tools restored |\n| permission | outside s18's scope | runs inside `PreToolUse` hook |\n| hooks | outside s18's scope | UserPromptSubmit / PreToolUse / PostToolUse / Stop |\n| todo | outside s18's scope | `todo_write` + reminder |\n| skill | outside s18's scope | catalog in system prompt + `load_skill` |\n| compact | outside s18's scope | pre-LLM compaction + `compact` tool + reactive compact |\n| error recovery | simple try/except | retry / max_tokens / prompt too long |\n| background | outside s18's scope | slow-operation thread + task notification |\n| cron | outside s18's scope | daemon scheduler + durable jobs |\n| multi-agent | kept | kept; teammates use basic tools in isolated directories |\n| worktree | kept | kept |\n| MCP | new | kept as part of the final tool pool |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s19_comprehensive/code.py\n```\n\nTry:\n\n1. `Inspect this repository and tell me which Python files matter most.`\n2. `Search the connected documentation for agent loop guidance.`\n3. `Refactor the authentication module and login page in parallel in isolated worktrees. Show me each plan before editing.`\n4. `Remind me about the meeting in 3 minutes.`\n5. `Install the dependencies in the background while you read README.md.`\n\nWatch for:\n\n- whether each tool call passes through hooks/permission\n- whether MCP tools appear on the next round after `connect_mcp`\n- whether slow operations return a background placeholder\n- whether cron automatically reminds you when the time arrives\n- whether teammates submit plans and pause before approval\n- whether teammates can claim tasks after plan approval\n- whether teammates switch to the bound worktree directory\n\n---\n\n## The End Is the Beginning\n\nFrom s01 to s19, the code gets more capable, but the core remains unchanged:\n\n```python\nwhile True:\n response = LLM(messages, tools)\n if not has_tool_use(response.content):\n return\n results = execute_tools(response.content)\n messages.append(tool_results)\n```\n\nA mature harness gets its complexity from coordination around the model. The model chooses actions; the harness organizes the environment, tools, permissions, memory, teams, and external capabilities.\n\nThis is the course's integration checkpoint: many mechanisms, one loop.\n\nNext: [s20 Workflow Runtime](/en/s20) — when the orchestration shape is fixed, move it out of chat turns and into deterministic, resumable code.\n" }, { "version": "s19", "locale": "zh", - "title": "s19: MCP Tools — 外接工具,标准协议", - "content": "# s19: MCP Tools — 外接工具,标准协议\n\ns01 → ... → s17 → s18 → `s19` → [s20](/zh/s20) → s21 → s22\n\n> *\"外接工具, 标准协议\"* — 发现、组装、调用,Agent 不需要知道工具是谁写的。\n>\n> **Harness 层**: 插件 — 外部能力通过标准协议接入。\n\n---\n\n## 问题\n\ns01 到 s18,Agent 的所有工具都是手写的——bash、read、write、task、worktree。每个工具的输入验证、执行逻辑、错误处理,都是你一行行写的。\n\n现在你有 3 个外部服务想接入:公司的 Jira API(查 issue、建 ticket)、自建的部署系统(触发 deploy、看日志)、团队的 Notion 知识库(搜文档、建页面)。你不想为每个服务重写一套工具代码。\n\n你需要一个标准协议——外部服务只要实现它,Agent 就能直接调用,不管服务用什么语言写的。\n\n---\n\n## 解决方案\n\n![MCP Architecture](/course-assets/s19_mcp_plugin/mcp-architecture.svg)\n\nMCP(Model Context Protocol)定义了 Agent 如何发现和调用外部工具。核心概念:\n\n| 概念 | 作用 |\n|------|------|\n| MCPClient | Agent 端的客户端,连接 server、发现工具、调用工具 |\n| MCP Server | 外部服务,实现 `tools/list` + `tools/call` |\n| assemble_tool_pool | 把内置工具和 MCP 工具组装成一个工具池 |\n| mcp\\_\\_server\\_\\_tool 命名 | 避免不同 server 的工具名冲突 |\n\n沿用 s18 的教学版 worktree 隔离、自主认领、空闲轮询、协议系统。本章新增:`connect_mcp` 工具——连接外部服务,发现工具,加入工具池。\n\n教学版用 mock handler 模拟外部 server。真实版会启动子进程,通过 stdin/stdout 发送 JSON-RPC 请求。mock 的好处是不依赖外部服务就能跑完整流程;代价是你看不到真正的网络通信和进程管理。\n\n---\n\n## 工作原理\n\n### MCPClient:发现 + 调用\n\n```python\nclass MCPClient:\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs, handlers):\n \"\"\"Simulates tools/list discovery.\"\"\"\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n \"\"\"Simulates tools/call.\"\"\"\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n return handler(**args)\n```\n\n教学版用 Python 函数模拟 server 的工具实现。真实版通过 stdio JSON-RPC 与子进程通信。\n\n### connect_mcp:连接 + 发现\n\n```python\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n return f\"Unknown server '{name}'. Available: ...\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n return f\"Connected to '{name}'. Discovered: ...\"\n```\n\n连接后,server 提供的工具立即可用。\n\n### normalize_mcp_name:名称规范化\n\n```python\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\ndef normalize_mcp_name(name: str) -> str:\n return _DISALLOWED_CHARS.sub('_', name)\n```\n\n所有非 `[a-zA-Z0-9_-]` 的字符替换为 `_`。防止 server 名或工具名中包含特殊字符导致命名冲突或注入问题。\n\n### assemble_tool_pool:组装工具池\n\n```python\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append(...)\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw:\n c.call_tool(t, kw))\n return tools, handlers\n```\n\n前缀 `mcp__{server}__{tool}` 避免不同 server 的工具名冲突。名称经过 `normalize_mcp_name` 规范化。\n\nMCP 工具的 description 带 `(readOnly)` 或 `(destructive)` 标注——教学版用文本标注,真实 CC 用 tool annotations 结构体让权限系统判断。\n\n### 无缓存:工具池变了,prompt 也变\n\ns10-s18 的 agent_loop 用 prompt cache 避免重复序列化。s19 去掉了缓存:\n\n```python\ndef agent_loop(messages, context):\n tools, handlers = assemble_tool_pool() # 每次重新构建\n system = assemble_system_prompt(context) # 每次重新生成\n ...\n if any(b.name == \"connect_mcp\" ...):\n tools, handlers = assemble_tool_pool() # 连接后重建\n system = assemble_system_prompt(context)\n```\n\n原因:`connect_mcp` 之后工具池变化了——新增了 `mcp__docs__search` 等工具。缓存中的工具列表是旧的,继续用会导致模型调用不到新工具。教学版直接去掉缓存,代价是多花一点序列化时间。\n\n### MCP 工具只有 Lead 可用\n\n教学版中,`connect_mcp` 是 Lead 工具,`assemble_tool_pool` 也只服务于 Lead 的 agent_loop。Teammate 仍使用固定的 8 个子集工具(bash、read_file、write_file、send_message、submit_plan、list_tasks、claim_task、complete_task)。\n\n这是教学简化。真实 CC 中,MCP 工具对主 agent 和子 agent 都可用——子 agent 继承父级的 MCP 配置。\n\n---\n\n## 相对 s18 的变更\n\n| 组件 | 之前 (s18) | 之后 (s19) |\n|------|-----------|-----------|\n| 工具来源 | 全部手写 builtin | 手写 + MCP 外部工具动态发现 |\n| 工具池 | 固定 BUILTIN_TOOLS | assemble_tool_pool 动态组装 mcp\\_\\_ 前缀工具 |\n| 名称安全 | 无 | normalize_mcp_name 规范化 |\n| 新类型 | — | MCPClient 类(模拟 tools/list + tools/call) |\n| 命名空间 | — | mcp\\_\\_server\\_\\_tool 避免冲突 |\n| 工具描述 | 无标注 | (readOnly)/(destructive) 标注 |\n| prompt 缓存 | 有(s10 起) | 去掉——工具池动态变化后缓存失效 |\n| Lead 工具 | 17 (s18) | 18 (+connect_mcp) |\n| Teammate 工具 | 8 (s18) | 8(不变,MCP 工具仅 Lead 可用) |\n| 扩展方式 | 写代码加工具 | 标准协议,任意语言实现 server |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s19_mcp_plugin/code.py\n```\n\n试试这些 prompt:\n\n1. `Connect to the docs MCP server and search for something`\n2. `Connect to the deploy server and trigger a deployment`\n3. `Connect both servers — what tools are now available?`\n\n观察重点:连接 MCP server 后,工具名是否带 `mcp__docs__` 或 `mcp__deploy__` 前缀?两个 server 的工具是否同时可用?MCP 工具的 description 是否带 (readOnly)/(destructive) 标注?\n\n---\n\n## 接下来\n\n现在 Agent 可以通过标准协议接入外部工具了。但前面 19 章每章都只加一个机制,真实 Agent 不会这样拆开运行。\n\n工具、权限、hooks、todo、任务图、记忆、压缩、后台、cron、团队、worktree、MCP 这些机制应该挂在同一个循环上,而不是散在 19 个 demo 里。\n\ns20 Comprehensive Agent → 把前 19 章的机制合回一个完整 harness。机制很多,循环一个。\n\n
\n深入 CC 源码\n\n> 以下基于 CC 源码 `services/mcp/client.ts`、`auth.ts`、`config.ts`、`channelNotification.ts` 的分析。\n\n### 一、6 种 Transport 类型\n\n教学版只展示了 stdio mock。CC 支持 6 种传输(`types.ts:23-25`):\n\n| Transport | 通信方式 |\n|-----------|---------|\n| `stdio` | 子进程 stdin/stdout(跨平台默认) |\n| `sse` | HTTP Server-Sent Events |\n| `http` | Streamable HTTP(POST/SSE 双向) |\n| `ws` | WebSocket |\n| `sse-ide` | IDE 内嵌 SSE 传输 |\n| `sdk` | 进程内 SDK 传输 |\n\n连接时本地(stdio)和远程(http/sse/ws)服务器分批并发:本地批量 3 个,远程批量 20 个。\n\n### 二、工具池组装算法\n\n`assembleToolPool()`(`tools.ts:345-364`):\n\n```typescript\n// 去重时优先保留内置工具(name 相同时内置在前)\nreturn uniqBy(\n [...builtInTools.sort(byName), ...filteredMcpTools.sort(byName)],\n 'name',\n)\n```\n\n内置工具和 MCP 工具分开排序,不是合起来排。原因是 CC 的 `claude_code_system_cache_policy` 在最后一个内置工具之后的某个位置放全局缓存断点——混排会破坏这个设计。\n\n### 三、命名规则:`mcp__server__tool`\n\n`buildMcpToolName()`(`mcpStringUtils.ts:50-52`):\n\n```\nmcp____\n```\n\n所有非 `[a-zA-Z0-9_-]` 字符替换为 `_`(`normalization.ts:17-23`)。教学版的 `normalize_mcp_name` 用同样的规则。\n\n### 四、权限检查\n\nCC 对 MCP 工具有独立的权限系统。`checkPermissions()` 对 MCP 工具的检查逻辑不同于内置工具——MCP 工具可以声明自己的权限需求(readOnly、destructive 等),CC 根据声明决定是否需要用户确认。教学版只在 description 中用文本标注 `(readOnly)` / `(destructive)`,不做权限拦截。\n\n### 五、配置来源与优先级\n\nMCP 服务器配置来自多个来源。CC 的配置优先级从低到高:\n\n```\nclaude.ai 连接器 < plugin < user settings.json < approved project .mcp.json < local settings.local.json\n```\n\n`claude.ai` 连接器单独拉取、按内容签名去重,以最低优先级合并(`config.ts:1267-1289`)。企业 `managed-mcp.json` 存在时完全排除其他配置。\n\n教学版直接传 server name 给 `MOCK_SERVERS` 字典,不做配置合并。\n\n### 六、Channel 通知:服务器反向推消息\n\n教学版只讲了 Agent → MCP Server 的单向调用。CC 还支持反向通知(`channelNotification.ts`):\n\n1. Server 声明 `capabilities.experimental['claude/channel']`\n2. Server 通过 MCP 通知 `notifications/claude/channel` 给 Agent 发消息\n3. 消息包装在 `...` XML 标签中\n4. Agent 被 SleepTool 唤醒(1 秒内)\n\nServer 还可以请求权限:`notifications/claude/channel/permission_request` → Agent 回复 `notifications/claude/channel/permission`。用户通过 5 字母短 ID 确认/拒绝。\n\n### 七、OAuth 认证流程\n\nCC 的 MCP 认证(`auth.ts`)支持完整的 OAuth 2.0 + PKCE 流程:\n- 通过公钥客户端 + PKCE 发现 OAuth 元数据(RFC 8414 / RFC 9728)\n- 本地回调服务器接收授权码\n- 令牌通过 `getSecureStorage()` 持久化(macOS Keychain / Linux 加密文件 / Windows 凭据管理器)\n- 过期前 5 分钟自动刷新\n- 支持跨应用访问(XAA):浏览器获取 id_token → RFC 8693 + RFC 7523 交换 → 无需反复弹浏览器\n\n### 八、连接生命周期的错误处理\n\nCC 对 MCP 连接有精细的错误分类和重试(`client.ts:1266-1402`):\n- 终局性错误(ECONNRESET、ETIMEDOUT、EPIPE 等):连续 3 次 → 关闭 + 重连\n- 工具调用 401:令牌过期 → 抛出 `McpAuthError` → 触发重认证\n- 工具调用超时:`Promise.race` 超时(可配置,默认约 28 小时)\n- Stdio 断连:按 SIGINT → SIGTERM → SIGKILL 顺序杀进程\n\n### 教学版的简化\n\n- 6 种 transport → 1 种(mock stdio):概念量可控\n- Channel 反向通知 → 省略:教学版 Agent 是主动方\n- OAuth 流程 → 省略:教学版假设 server 不需要认证\n- 多层配置优先级 → 省略:教学版直接传 server name\n- 复杂的错误分类 → 省略:教学版用 try/except 兜底\n- MCP 工具只给 Lead → 省略子 agent 继承:简化代码结构\n\n
\n\n\n" + "title": "s19: Comprehensive Agent — 全部机制,归到一个循环", + "content": "# s19: Comprehensive Agent — 全部机制,归到一个循环\n\ns01 → ... → s17 → s18 → `s19` → [s20](/zh/s20) → s21\n\n> *\"机制很多,循环一个\"* — 工具、权限、记忆、任务、团队、插件都挂在同一个 while True 上。\n>\n> **Harness 层**: 综合 — 把 s01-s18 的机制放回同一个可运行系统。\n\n---\n\n## 问题\n\n前 18 章每章只加一个机制,让每个边界都能单独观察。本章把它们接入同一个运行时。\n\n一个能长期工作的 coding agent 需要同时拥有:\n\n- 工具分发和权限边界\n- hooks 扩展点\n- todo 计划和任务图\n- 技能、记忆、系统 prompt 组装\n- 压缩和错误恢复\n- 后台任务和 cron 调度\n- 团队、协议、自治认领\n- worktree 隔离\n- MCP 外部工具接入\n\n难点不是把功能堆起来,而是看清楚它们都挂在循环的哪个位置。S19 是集成检查点:先把此前组件归位,再由 s20-s21 在外层加入编排与目标闭环。\n\n---\n\n## 解决方案\n\n![System Architecture](/course-assets/s19_comprehensive/system-architecture.svg)\n\nS19 不再引入新机制,而是把前面各章的组件接入一个完整 harness:\n\n```text\n用户输入\n → UserPromptSubmit hooks\n → cron/background 通知注入\n → context compact\n → memory + skills + MCP 状态组装 system prompt\n → LLM\n → has tool_use block?\n 否 → Stop hooks → 返回\n 是 → PreToolUse hooks + permission\n → TOOL_HANDLERS / MCP handlers / background dispatch\n → PostToolUse hooks\n → tool_result / task_notification 回 messages\n → 下一轮\n```\n\n循环仍是同一个结构:调用模型,检查响应里是否出现 `tool_use` block,执行工具,再把结果追加回 `messages`。是否继续工具轮,由响应中有没有实际的 `tool_use` block 决定。\n\n---\n\n## 组件在循环中的位置\n\n| 位置 | 组件 | 作用 |\n|------|------|------|\n| 用户输入前后 | `UserPromptSubmit` hooks | 记录、注入、审计用户输入 |\n| LLM 前 | cron queue | 把定时触发的 prompt 注入 `messages` |\n| LLM 前 | background notifications | 后台任务完成后以 `` 注入 |\n| LLM 前 | compaction pipeline | 先压大输出,再裁历史,再压旧 tool_result,必要时摘要 |\n| LLM 前 | memory / skills / MCP state | 组装 system prompt,让模型看到当前能力和长期上下文 |\n| LLM 调用 | error recovery | 429/529 重试,`max_tokens` 升级,prompt too long 触发 reactive compact |\n| 工具执行前 | `PreToolUse` hooks + permission | 拦截危险命令、写越界、破坏性 MCP 工具 |\n| 工具分发 | `assemble_tool_pool` | 组装内置工具和 MCP 动态工具 |\n| 工具执行时 | background dispatch | 慢 bash 操作放 daemon thread,主循环先返回占位结果 |\n| 工具执行后 | `PostToolUse` hooks | 大输出告警、日志等后处理 |\n| 返回循环 | tool_result | 每个 `tool_use` 对应一个 `tool_result`,再回到下一轮 |\n| 本轮没有 tool_use / 停止时 | `Stop` hooks | 统计、清理、审计 |\n\n---\n\n## code.py 包含什么\n\n### 工具与分发\n\n内置工具池包含 26 个工具:\n\n```text\nbash, read_file, write_file, edit_file, glob\ntodo_write, task, load_skill, compact\ncreate_task, list_tasks, get_task, claim_task, complete_task\nschedule_cron, list_crons, cancel_cron\nspawn_teammate, send_message\nrequest_shutdown, request_plan, review_plan\ncreate_worktree, remove_worktree, keep_worktree\nconnect_mcp\n```\n\n`assemble_tool_pool()` 每轮组装:\n\n```text\nBUILTIN_TOOLS + connected MCP tools\nBUILTIN_HANDLERS + mcp__server__tool handlers\n```\n\n所以 `connect_mcp(\"docs\")` 后,下一轮工具池里会出现 `mcp__docs__search`。\n\n### 权限和 hooks\n\n权限不写死在工具执行行里,而是作为 `PreToolUse` hook:\n\n```python\nblocked = trigger_hooks(\"PreToolUse\", block)\nif blocked:\n results.append(tool_result(block.id, blocked))\n continue\n```\n\n这样 permission、log、审计都可以挂在同一个 hook 点上。执行后再触发 `PostToolUse`。\n\n### 计划与任务\n\nS19 同时保留两层计划:\n\n- `todo_write`:当前会话内的轻量计划,保存在内存中\n- task graph:跨会话、可依赖、可认领的任务文件,写入 `.tasks/task_*.json`\n\n前者帮助单个 Agent 不漂移;后者支撑团队协作。\n\n两者目标相近,但实现不同:`todo_write` 整表替换当前会话清单,task record 则有稳定 ID 和单条生命周期更新。下面单独出现的 `task` 工具表示“一次性派发隔离 subagent”,不是 Task System。\n\n### 子 agent 与团队\n\nS19 有两种 delegation:\n\n- `task`:一次性 subagent。独立 `messages[]`,中间过程丢弃,只返回最终摘要。\n- `spawn_teammate`:持久队友线程。运行时自动投递 MessageBus 事件,队友在 idle 时扫描任务板并自主认领。\n\n一次性 subagent 解决“上下文隔离”;持久队友解决“长期并行协作”。\n\n### 记忆、技能和 prompt\n\n`assemble_system_prompt(context)` 每轮组装:\n\n- 身份和工具说明\n- workspace\n- skills catalog\n- `.memory/MEMORY.md`\n- 已连接 MCP server\n\n技能只在 system prompt 里放目录。完整内容通过 `load_skill(name)` 按需加载。\n\n### 压缩和恢复\n\nLLM 前先跑压缩管线:\n\n```text\ntool_result_budget → snip_compact → micro_compact → compact_history\n```\n\n调用模型时再包一层恢复:\n\n- 429:指数退避重试\n- 529:指数退避,连续失败可切 fallback model\n- `max_tokens`:先提高 max_tokens,再要求 continuation\n- prompt too long:reactive compact 后重试\n\n### 后台和 cron\n\n慢 bash 操作不会阻塞主循环:\n\n```text\nshould_run_background → start_background_task → placeholder tool_result\n后台完成 → task_notification → 下一轮注入 messages\n```\n\ncron 调度器独立 daemon thread 每秒检查一次。CLI 会监听 `cron_queue`,命中后主动把 `[Scheduled] ...` 注入并运行一轮 Agent。\n\n### worktree 与 MCP\n\nworktree 负责隔离目录:\n\n- `create_worktree(name, task_id)` 创建独立分支和目录\n- task 的 `worktree` 字段绑定目录\n- 队友 claim 到带 worktree 的 task 后,bash/read/write 自动在对应目录下执行\n\nMCP 负责外部能力:\n\n- `connect_mcp(name)` 连接 mock server\n- `assemble_tool_pool()` 把 MCP 工具组装进工具池\n- 工具名统一为 `mcp__server__tool`\n\n---\n\n## 相对 s18 的变化\n\n| 组件 | s18 | s19 |\n|------|-----|-----|\n| 工具池 | 内置 + MCP | 内置 + MCP,补齐 s01-s17 的工具 |\n| 权限 | 不在 s18 范围内 | `PreToolUse` hook 中执行 |\n| hooks | 不在 s18 范围内 | UserPromptSubmit / PreToolUse / PostToolUse / Stop |\n| todo | 不在 s18 范围内 | `todo_write` + reminder |\n| skill | 不在 s18 范围内 | catalog in system prompt + `load_skill` |\n| compact | 不在 s18 范围内 | LLM 前压缩 + `compact` 工具 + reactive compact |\n| error recovery | 简化 try/except | retry / max_tokens / prompt too long |\n| background | 不在 s18 范围内 | 慢操作后台线程 + task notification |\n| cron | 不在 s18 范围内 | daemon scheduler + durable jobs |\n| multi-agent | 保留 | 保留;队友使用隔离目录下的基础工具 |\n| worktree | 保留 | 保留 |\n| MCP | 新增 | 保留,作为最终工具池的一部分 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s19_comprehensive/code.py\n```\n\n可以试:\n\n1. `检查这个仓库,告诉我哪些 Python 文件最重要。`\n2. `从已连接的文档中查一下 agent loop 的相关说明。`\n3. `请在隔离的 worktree 中并行重构认证模块和登录页,修改前先把各自的计划给我看。`\n4. `3 分钟后提醒我开会。`\n5. `在后台安装依赖,同时继续阅读 README.md。`\n\n观察重点:\n\n- 工具调用前是否经过 hooks/permission\n- `connect_mcp` 后下一轮是否出现 MCP 工具\n- 慢操作是否返回 background placeholder\n- 到点是不是自动提醒开会\n- 队友是否提交 plan,并在 approval 前暂停\n- plan 批准后,队友是否能认领任务\n- worktree 绑定后,队友是否切到对应目录\n\n---\n\n## 结束亦是开始\n\n从 s01 到 s19,代码表面越来越复杂,但核心始终没变:\n\n```python\nwhile True:\n response = LLM(messages, tools)\n if not has_tool_use(response.content):\n return\n results = execute_tools(response.content)\n messages.append(tool_results)\n```\n\n成熟 harness 的复杂性来自模型周围的协作机制。模型负责判断和行动选择,harness 负责组织环境、工具、权限、记忆、团队和外部能力。\n\n这是课程的集成检查点:机制很多,循环一个。\n\n下一章:[s20 Workflow Runtime](/zh/s20) — 当编排形状固定时,把它从多轮对话移入确定性、可恢复的代码。\n" }, { "version": "s19", "locale": "ja", - "title": "s19: MCP Tools — 外部ツール、標準プロトコル", - "content": "# s19: MCP Tools — 外部ツール、標準プロトコル\n\ns01 → ... → s17 → s18 → `s19` → [s20](/ja/s20) → s21 → s22\n\n> *\"外部ツール、標準プロトコル\"* — 発見、組み立て、呼び出し。Agent はツールを誰が書いたか知る必要がない。\n>\n> **Harness 層**: プラグイン — 外部能力を標準プロトコルで接続。\n\n---\n\n## 課題\n\ns01 から s18 まで、Agent の全ツールは手書き — bash、read、write、task、worktree。入力検証、実行ロジック、エラーハンドリング、全て一行ずつ書いた。\n\n今、統合したい外部サービスが 3 つある:社内の Jira API(issue 検索、ticket 作成)、独自のデプロイシステム(deploy トリガー、ログ閲覧)、チームの Notion ナレッジベース(ドキュメント検索、ページ作成)。各サービスのためにツールコードを書き直したくない。\n\n標準プロトコルが必要 — 外部サービスがこのプロトコルを実装していれば、サービスが何の言語で書かれていても、Agent は直接そのツールを呼び出せる。\n\n---\n\n## ソリューション\n\n![MCP Architecture](/course-assets/s19_mcp_plugin/mcp-architecture.ja.svg)\n\nMCP(Model Context Protocol)は、Agent が外部ツールを発見・呼び出しする方法を定義。核心概念:\n\n| 概念 | 目的 |\n|------|------|\n| MCPClient | Agent 側のクライアント — server に接続、ツールを発見、ツールを呼び出し |\n| MCP Server | 外部サービス側 — `tools/list` + `tools/call` を実装 |\n| assemble_tool_pool | 組み込みツールと MCP ツールを一つのツールプールに組み立てる |\n| mcp\\_\\_server\\_\\_tool 命名 | 異なる server 間のツール名衝突を防止 |\n\ns18 の教学版 worktree 隔離、自動認領、空き時ポーリング、プロトコルシステムを踏襲。本章の追加:`connect_mcp` ツール — 外部サービスに接続、ツールを発見、ツールプールに追加。\n\n教学版は mock handler で外部 server をシミュレート。実際の版はサブプロセスを起動し、stdin/stdout で JSON-RPC リクエストを送信。mock の利点は外部サービスなしで完全なフローを実行できること;代償は実際のネットワーク通信やプロセス管理が見えないこと。\n\n---\n\n## 仕組み\n\n### MCPClient:発見 + 呼び出し\n\n```python\nclass MCPClient:\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs, handlers):\n \"\"\"Simulates tools/list discovery.\"\"\"\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n \"\"\"Simulates tools/call.\"\"\"\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n return handler(**args)\n```\n\n教学版は Python 関数で server のツール実装をシミュレート。実際の版は stdio JSON-RPC でサブプロセスと通信。\n\n### connect_mcp:接続 + 発見\n\n```python\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n return f\"Unknown server '{name}'. Available: ...\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n return f\"Connected to '{name}'. Discovered: ...\"\n```\n\n接続後、server が提供するツールが即座に利用可能。\n\n### normalize_mcp_name:名前の正規化\n\n```python\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\ndef normalize_mcp_name(name: str) -> str:\n return _DISALLOWED_CHARS.sub('_', name)\n```\n\n`[a-zA-Z0-9_-]` 以外の全文字を `_` に置換。server 名やツール名の特殊文字による名前衝突やインジェクション問題を防止。\n\n### assemble_tool_pool:ツールプールの組み立て\n\n```python\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append(...)\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw:\n c.call_tool(t, kw))\n return tools, handlers\n```\n\nプレフィックス `mcp__{server}__{tool}` で異なる server 間のツール名衝突を防止。名前は `normalize_mcp_name` で正規化。\n\nMCP ツールの description に `(readOnly)` または `(destructive)` アノテーションを付与 — 教学版はテキストアノテーション、実際の CC は tool annotations 構造体で権限システムが判断。\n\n### キャッシュなし:ツールプールが変われば、プロンプトも変わる\n\ns10-s18 の agent_loop は prompt cache で再シリアライズを回避。s19 はキャッシュを削除:\n\n```python\ndef agent_loop(messages, context):\n tools, handlers = assemble_tool_pool() # 毎回再構築\n system = assemble_system_prompt(context) # 毎回再生成\n ...\n if any(b.name == \"connect_mcp\" ...):\n tools, handlers = assemble_tool_pool() # 接続後に再構築\n system = assemble_system_prompt(context)\n```\n\n理由:`connect_mcp` 後にツールプールが変化 — `mcp__docs__search` などの新ツールが追加される。キャッシュ内のツールリストは古く、使い続けるとモデルが新ツールを呼び出せない。教学版はキャッシュを単に削除、代償はシリアライズ時間の若干の増加。\n\n### MCP ツールは Lead のみ利用可能\n\n教学版では、`connect_mcp` は Lead ツール、`assemble_tool_pool` も Lead の agent_loop のみにサービスを提供。チームメイトは引き続き固定の 8 ツールサブセット(bash、read_file、write_file、send_message、submit_plan、list_tasks、claim_task、complete_task)を使用。\n\nこれは教学簡略化。実際の CC では、MCP ツールはメイン agent とサブ agent の両方で利用可能 — サブ agent は親の MCP 設定を継承。\n\n---\n\n## s18 からの変更\n\n| コンポーネント | 変更前 (s18) | 変更後 (s19) |\n|--------------|------------|------------|\n| ツールソース | 全て手書き builtin | 手書き + MCP 外部ツール動的発見 |\n| ツールプール | 固定 BUILTIN_TOOLS | assemble_tool_pool が動的に mcp\\_\\_ プレフィックスツールを組み立てる |\n| 名前の安全性 | なし | normalize_mcp_name 正規化 |\n| 新規タイプ | — | MCPClient クラス(tools/list + tools/call をシミュレート) |\n| 名前空間 | — | mcp\\_\\_server\\_\\_tool 衝突防止 |\n| ツール説明 | アノテーションなし | (readOnly)/(destructive) アノテーション |\n| プロンプトキャッシュ | あり(s10 から) | 削除 — ツールプールが動的、キャッシュが陳腐化 |\n| Lead ツール | 17 (s18) | 18 (+connect_mcp) |\n| チームメイトツール | 8 (s18) | 8(変更なし、MCP ツールは Lead のみ) |\n| 拡張方法 | ツール追加のコードを書く | 標準プロトコル、任意言語で server を実装 |\n\n---\n\n## 試してみる\n\n```sh\ncd learn-claude-code\npython s19_mcp_plugin/code.py\n```\n\n以下のプロンプトを試してください:\n\n1. `Connect to the docs MCP server and search for something`\n2. `Connect to the deploy server and trigger a deployment`\n3. `Connect both servers — what tools are now available?`\n\n観察ポイント:MCP server 接続後、ツール名に `mcp__docs__` や `mcp__deploy__` プレフィックスが付いているか?両方の server のツールが同時に利用可能か?MCP ツールの description に (readOnly)/(destructive) アノテーションが付いているか?\n\n---\n\n## 次の章\n\nAgent は標準プロトコルで外部ツールに接続できるようになりました。しかし前 19 章は各章で 1 つの仕組みだけを追加しています。実際の Agent は 19 個の demo に分かれて動くわけではありません。\n\ntools、permissions、hooks、todo、task graph、memory、compact、background work、cron、teams、worktree、MCP は、別々の例ではなく同じ loop に接続されるべきです。\n\ns20 Comprehensive Agent → 前 19 章の仕組みを 1 つの完全な harness に統合。仕組みは多く、loop は 1 つ。\n\n
\nCC ソースコード深掘り\n\n> 以下は CC ソースコード `services/mcp/client.ts`、`auth.ts`、`config.ts`、`channelNotification.ts` の分析に基づく。\n\n### 一、6 種の Transport タイプ\n\n教学版は stdio mock のみ。CC は 6 種のトランスポートをサポート(`types.ts:23-25`):\n\n| Transport | 通信方式 |\n|-----------|---------|\n| `stdio` | サブプロセス stdin/stdout(クロスプラットフォームデフォルト) |\n| `sse` | HTTP Server-Sent Events |\n| `http` | Streamable HTTP(POST/SSE 双方向) |\n| `ws` | WebSocket |\n| `sse-ide` | IDE 内蔵 SSE トランスポート |\n| `sdk` | プロセス内 SDK トランスポート |\n\n接続時、ローカル(stdio)とリモート(http/sse/ws)サーバーをバッチで並行処理:ローカルは 3 つずつ、リモートは 20 つずつ。\n\n### 二、ツールプール組み立てアルゴリズム\n\n`assembleToolPool()`(`tools.ts:345-364`):\n\n```typescript\n// 重複排除時に組み込みツールを優先(name が同じ場合、組み込みが先)\nreturn uniqBy(\n [...builtInTools.sort(byName), ...filteredMcpTools.sort(byName)],\n 'name',\n)\n```\n\n組み込みツールと MCP ツールは別々にソート、混ぜてソートしない。理由は CC の `claude_code_system_cache_policy` が最後の組み込みツールの後の特定位置にグローバルキャッシュブレークポイントを置く設計のため — ソートを混ぜるとこの設計が壊れる。\n\n### 三、命名規則:`mcp__server__tool`\n\n`buildMcpToolName()`(`mcpStringUtils.ts:50-52`):\n\n```\nmcp____\n```\n\n`[a-zA-Z0-9_-]` 以外の全文字を `_` に置換(`normalization.ts:17-23`)。教学版の `normalize_mcp_name` も同じルールを使用。\n\n### 四、権限チェック\n\nCC は MCP ツールに対して独立した権限システムを持つ。`checkPermissions()` は MCP ツールに対して組み込みツールとは異なるロジックを適用 — MCP ツールは独自の権限要件(readOnly、destructive 等)を宣言でき、CC は宣言に基づいてユーザー確認が必要かを判断。教学版は description 内のテキストアノテーション `(readOnly)` / `(destructive)` のみで、権限インターセプトは行わない。\n\n### 五、設定ソースと優先度\n\nMCP サーバー設定は複数のソースから。CC の優先度は低い順に:\n\n```\nclaude.ai コネクタ < プラグイン < ユーザー settings.json < 承認済みプロジェクト .mcp.json < ローカル settings.local.json\n```\n\n`claude.ai` コネクタは個別に取得、コンテンツ署名で重複排除し、最低優先度で統合(`config.ts:1267-1289`)。企業 `managed-mcp.json` が存在する場合、他の全設定を完全に除外。\n\n教学版は server 名を直接 `MOCK_SERVERS` 辞書に渡し、設定マージは行わない。\n\n### 六、Channel 通知:サーバーからの逆方向メッセージ\n\n教学版は Agent → MCP Server の一方向呼び出しのみ。CC は逆方向通知もサポート(`channelNotification.ts`):\n\n1. Server が `capabilities.experimental['claude/channel']` を宣言\n2. Server が MCP 通知 `notifications/claude/channel` で Agent にメッセージを送信\n3. メッセージは `...` XML タグでラップ\n4. Agent は SleepTool で起床(1 秒以内)\n\nServer は権限リクエストも可能:`notifications/claude/channel/permission_request` → Agent が `notifications/claude/channel/permission` で応答。ユーザーは 5 文字の短い ID で確認/拒否。\n\n### 七、OAuth 認証フロー\n\nCC の MCP 認証(`auth.ts`)は完全な OAuth 2.0 + PKCE フローをサポート:\n- 公開クライアント + PKCE で OAuth メタデータを発見(RFC 8414 / RFC 9728)\n- ローカルコールバックサーバーが認可コードを受信\n- トークンは `getSecureStorage()` で永続化(macOS Keychain / Linux 暗号化ファイル / Windows 資格情報マネージャー)\n- 有効期限 5 分前に自動リフレッシュ\n- クロスアプリケーションアクセス(XAA):ブラウザが id_token を取得 → RFC 8693 + RFC 7523 交換 → 繰り返しブラウザポップアップ不要\n\n### 八、接続ライフサイクルのエラーハンドリング\n\nCC は MCP 接続にきめ細かいエラー分類とリトライを行う(`client.ts:1266-1402`):\n- 終局エラー(ECONNRESET、ETIMEDOUT、EPIPE 等):連続 3 回 → クローズ + 再接続\n- ツール呼び出し 401:トークン期限切れ → `McpAuthError` スロー → 再認証トリガー\n- ツール呼び出しタイムアウト:`Promise.race` タイムアウト(設定可能、デフォルト約 28 時間)\n- Stdio 切断:SIGINT → SIGTERM → SIGKILL の順でプロセスを kill\n\n### 教学版の簡略化\n\n- 6 種のトランスポート → 1 種(mock stdio):概念量を管理可能に\n- Channel 逆方向通知 → 省略:教学版 Agent は常にイニシエータ\n- OAuth フロー → 省略:教学版は server が認証不要と仮定\n- 多層設定優先度 → 省略:教学版は直接 server 名を渡す\n- 複雑なエラー分類 → 省略:教学版は try/except でフォールバック\n- MCP ツールは Lead のみ → サブ agent 継承を省略:コード構造を簡略化\n\n
\n\n\n" + "title": "s19: Comprehensive Agent — すべての仕組みを 1 つのループへ", + "content": "# s19: Comprehensive Agent — すべての仕組みを 1 つのループへ\n\ns01 → ... → s17 → s18 → `s19` → [s20](/ja/s20) → s21\n\n> *\"仕組みは多い、ループは 1 つ\"* — tools、permissions、memory、tasks、teams、plugins はすべて同じ `while True` に接続される。\n>\n> **Harness レイヤー**: 総合 — s01-s18 の仕組みを 1 つの実行可能なシステムへ戻す。\n\n---\n\n## 問題\n\n前 18 章では、各境界を観察できるように仕組みを一つずつ追加した。本章では、それらを一つのランタイムへ接続する。\n\n長時間動く coding agent には、同時に次のものが必要になる:\n\n- tool dispatch と permission boundary\n- hook extension point\n- todo plan と task graph\n- skill、memory、runtime system prompt assembly\n- compaction と error recovery\n- background task と cron scheduling\n- team、protocol、autonomous claiming\n- worktree isolation\n- MCP external tool integration\n\n難しいのは機能を積み上げることではない。それぞれの仕組みが loop のどこに接続されるかを見抜くことだ。S19 は統合チェックポイントであり、これまでの component を 1 つの harness に戻してから、s20-s21 が編成と目標完了を外側に追加する。\n\n---\n\n## 解決策\n\n![System Architecture](/course-assets/s19_comprehensive/system-architecture.ja.svg)\n\nS19 は新しい mechanism を追加せず、前章までの component を 1 つの完全な harness に統合する:\n\n```text\nuser input\n → UserPromptSubmit hooks\n → cron/background notification injection\n → context compact\n → memory + skills + MCP state で system prompt を組み立てる\n → LLM\n → has tool_use block?\n no → Stop hooks → return\n yes → PreToolUse hooks + permission\n → TOOL_HANDLERS / MCP handlers / background dispatch\n → PostToolUse hooks\n → tool_result / task_notification を messages へ戻す\n → next round\n```\n\nloop 自体は同じ構造のままだ。model を呼び、response に `tool_use` block があるかを見て、tool を実行し、結果を `messages` に戻す。tool 実行を続けるかどうかは、実際の `tool_use` block の有無で決まる。\n\n---\n\n## 各 Component の位置\n\n| 位置 | Component | 役割 |\n|------|-----------|------|\n| user input 周辺 | `UserPromptSubmit` hooks | user input の記録、注入、監査 |\n| LLM 前 | cron queue | scheduled prompt を `messages` へ注入 |\n| LLM 前 | background notifications | 完了した background work を `` として注入 |\n| LLM 前 | compaction pipeline | 大きな出力を予算化し、履歴を切り、古い tool_result を圧縮し、必要なら要約 |\n| LLM 前 | memory / skills / MCP state | current capabilities と long-term context を system prompt に組み込む |\n| LLM call | error recovery | 429/529 retry、`max_tokens` escalation、prompt-too-long compact |\n| tool 実行前 | `PreToolUse` hooks + permission | 危険な command、範囲外 write、destructive MCP tool を止める |\n| tool dispatch | `assemble_tool_pool` | built-in tools と dynamic MCP tools を組み立てる |\n| tool 実行中 | background dispatch | 遅い bash work を daemon thread に逃がし、placeholder result を返す |\n| tool 実行後 | `PostToolUse` hooks | large-output warning、log、後処理 |\n| loop へ戻る | tool_result | 1 つの `tool_use` に 1 つの `tool_result`、そして次の model round |\n| tool_use がない round / stop 時 | `Stop` hooks | 統計、cleanup、audit |\n\n---\n\n## code.py に含まれるもの\n\n### Tools と Dispatch\n\nbuilt-in tool pool には 26 個の tool がある:\n\n```text\nbash, read_file, write_file, edit_file, glob\ntodo_write, task, load_skill, compact\ncreate_task, list_tasks, get_task, claim_task, complete_task\nschedule_cron, list_crons, cancel_cron\nspawn_teammate, send_message\nrequest_shutdown, request_plan, review_plan\ncreate_worktree, remove_worktree, keep_worktree\nconnect_mcp\n```\n\n`assemble_tool_pool()` は毎 round で次を組み立てる:\n\n```text\nBUILTIN_TOOLS + connected MCP tools\nBUILTIN_HANDLERS + mcp__server__tool handlers\n```\n\n`connect_mcp(\"docs\")` のあと、次の round では `mcp__docs__search` のような tool が出現する。\n\n### Permission と Hooks\n\npermission は tool 実行行に直接埋め込まない。`PreToolUse` hook として扱う:\n\n```python\nblocked = trigger_hooks(\"PreToolUse\", block)\nif blocked:\n results.append(tool_result(block.id, blocked))\n continue\n```\n\nこれにより permission、logging、audit が同じ hook point に接続できる。実行後には `PostToolUse` hook が走る。\n\n### Plan と Task\n\nS19 には 2 層の plan がある:\n\n- `todo_write`: current session 用の軽量 plan。メモリに保持。\n- task graph: cross-session、dependency-aware、claimable な task file。`.tasks/task_*.json` に保存。\n\n前者は単独 agent の drift を防ぐ。後者は team coordination の土台になる。\n\n目的は近いが実装は別である。`todo_write` は現在のセッションのチェックリスト全体を置き換え、task record は安定 ID と個別のライフサイクル更新を持つ。次節の独立した `task` ツールは「隔離 subagent を一度派遣する」意味であり、Task System ではない。\n\n### Subagent と Team\n\nS19 には 2 種類の delegation がある:\n\n- `task`: one-shot subagent。独立した `messages[]` を使い、中間 context を捨て、final summary だけ返す。\n- `spawn_teammate`: persistent teammate thread。ランタイムが `MessageBus` event を自動配信し、teammate は idle 中に task board を確認して自律的に claim できる。\n\none-shot subagent は context isolation を解決する。persistent teammate は長期並列協作を解決する。\n\n### Memory、Skills、Prompt\n\n`assemble_system_prompt(context)` は毎 round 次を組み立てる:\n\n- identity と tool guidance\n- workspace\n- skills catalog\n- `.memory/MEMORY.md`\n- connected MCP servers\n\nskills は system prompt には catalog だけ置く。全文は `load_skill(name)` で必要な時に読む。\n\n### Compaction と Recovery\n\nLLM call の前に compaction pipeline を走らせる:\n\n```text\ntool_result_budget → snip_compact → micro_compact → compact_history\n```\n\nmodel call は recovery で包む:\n\n- 429: exponential backoff retry\n- 529: exponential backoff、連続失敗時は fallback model へ切替可能\n- `max_tokens`: max tokens を上げ、その後 continuation を要求\n- prompt too long: reactive compact 後に retry\n\n### Background と Cron\n\n遅い bash work は main loop を止めない:\n\n```text\nshould_run_background → start_background_task → placeholder tool_result\nbackground done → task_notification → next round injects messages\n```\n\ncron scheduler は daemon thread として動き、1 秒ごとに確認する。CLI は `cron_queue` を監視し、発火した job を `[Scheduled] ...` として注入して Agent を 1 turn 自動実行する。\n\n### Worktree と MCP\n\nworktree isolation は directory を担当する:\n\n- `create_worktree(name, task_id)` が isolated branch と directory を作る\n- task の `worktree` field が task と directory を紐付ける\n- teammate が worktree 付き task を claim すると、bash/read/write はその directory で実行される\n\nMCP は external capability を担当する:\n\n- `connect_mcp(name)` が mock server に接続する\n- `assemble_tool_pool()` が MCP tools を tool pool に組み立てる\n- tool name は `mcp__server__tool` 形式に統一する\n\n---\n\n## s18 からの変化\n\n| Component | s18 | s19 |\n|-----------|-----|-----|\n| tool pool | built-in + MCP | built-in + MCP、s01-s17 の tool を補完 |\n| permission | s18 の対象外 | `PreToolUse` hook で実行 |\n| hooks | s18 の対象外 | UserPromptSubmit / PreToolUse / PostToolUse / Stop |\n| todo | s18 の対象外 | `todo_write` + reminder |\n| skill | s18 の対象外 | system prompt の catalog + `load_skill` |\n| compact | s18 の対象外 | LLM 前 compaction + `compact` tool + reactive compact |\n| error recovery | simple try/except | retry / max_tokens / prompt too long |\n| background | s18 の対象外 | slow-operation thread + task notification |\n| cron | s18 の対象外 | daemon scheduler + durable jobs |\n| multi-agent | 維持 | 維持。teammate は isolated directory 上の basic tools を使う |\n| worktree | 維持 | 維持 |\n| MCP | 新規 | final tool pool の一部として維持 |\n\n---\n\n## 試す\n\n```sh\ncd learn-claude-code\npython s19_comprehensive/code.py\n```\n\n試す prompt:\n\n1. `このリポジトリを調べ、重要な Python ファイルを教えてください。`\n2. `接続済みのドキュメントから agent loop の説明を探してください。`\n3. `認証モジュールとログインページを隔離した worktree で並行してリファクタリングし、編集前にそれぞれのプランを見せてください。`\n4. `3 分後に会議を知らせてください。`\n5. `依存関係をバックグラウンドでインストールしながら README.md を読んでください。`\n\n見るポイント:\n\n- tool call の前に hooks/permission を通るか\n- `connect_mcp` 後の次 round で MCP tool が出るか\n- 遅い operation が background placeholder を返すか\n- cron が時刻到達時に自動で reminder を返すか\n- teammate が plan を提出し、approval 前に停止するか\n- plan approval 後、teammate が task を claim できるか\n- worktree binding 後、teammate が対応 directory に切り替わるか\n\n---\n\n## 終わりは始まり\n\ns01 から s19 まで、コードの能力は増えていく。しかし中心は変わらない:\n\n```python\nwhile True:\n response = LLM(messages, tools)\n if not has_tool_use(response.content):\n return\n results = execute_tools(response.content)\n messages.append(tool_results)\n```\n\n成熟した harness の複雑さは model 周辺の協調機構から生まれる。model は判断と action selection を担当し、harness は environment、tools、permissions、memory、teams、external capabilities を整理する。\n\nこれは本コースの統合チェックポイントだ:仕組みは多い、ループは 1 つ。\n\n次へ:[s20 Workflow Runtime](/ja/s20) — 編成の形が固定なら、多数の会話ターンではなく、決定的で再開可能なコードへ移す。\n" }, { "version": "s20", "locale": "en", - "title": "s20: Comprehensive Agent — All Mechanisms, One Loop", - "content": "# s20: Comprehensive Agent — All Mechanisms, One Loop\n\ns01 → ... → s18 → s19 → `s20` → [s21](/en/s21) → s22\n\n> *\"Many mechanisms, one loop\"* — tools, permissions, memory, tasks, teams, and plugins all hang off the same `while True`.\n>\n> **Harness layer**: Comprehensive — put the previous 19 mechanisms back into one runnable system.\n\n---\n\n## Problem\n\nThe first 19 chapters add one mechanism at a time. That is the right way to learn, but a real agent does not run with only one mechanism enabled.\n\nA long-running coding agent needs all of these at once:\n\n- tool dispatch and permission boundaries\n- hook extension points\n- todo planning and task graphs\n- skills, memory, and runtime system prompt assembly\n- compaction and error recovery\n- background tasks and cron scheduling\n- teams, protocols, autonomous claiming\n- worktree isolation\n- MCP external tool integration\n\nThe hard part is not piling up features. The hard part is seeing where each mechanism belongs around the loop. S20 is the integration checkpoint: every earlier component is placed back into one harness before s21-s22 add orchestration and goal closure around it.\n\n---\n\n## Solution\n\n![System Architecture](/course-assets/s20_comprehensive/system-architecture.en.svg)\n\nS20 does not invent a new mechanism. It merges the teaching components from the earlier chapters into one complete harness:\n\n```text\nuser input\n → UserPromptSubmit hooks\n → cron/background notification injection\n → context compact\n → memory + skills + MCP state assemble the system prompt\n → LLM\n → has tool_use block?\n no → Stop hooks → return\n yes → PreToolUse hooks + permission\n → TOOL_HANDLERS / MCP handlers / background dispatch\n → PostToolUse hooks\n → tool_result / task_notification back to messages\n → next round\n```\n\nThe loop is still the same structure: call the model, check whether the response contains a `tool_use` block, execute tools, append results back to `messages`. CC source does not directly trust `stop_reason == \"tool_use\"`; the actual presence of a tool_use block is the continuation signal. What changed is that the harness around the loop is now complete.\n\n---\n\n## Where Each Component Sits\n\n| Position | Component | Role |\n|----------|-----------|------|\n| Around user input | `UserPromptSubmit` hooks | Log, inject, or audit user input |\n| Before LLM | cron queue | Inject scheduled prompts into `messages` |\n| Before LLM | background notifications | Inject completed background work as `` |\n| Before LLM | compaction pipeline | Budget large outputs, trim history, compact old tool results, summarize when needed |\n| Before LLM | memory / skills / MCP state | Assemble the system prompt so the model sees current capabilities and long-term context |\n| LLM call | error recovery | Retry 429/529, escalate `max_tokens`, compact on prompt-too-long |\n| Before tool execution | `PreToolUse` hooks + permission | Block dangerous commands, out-of-bounds writes, destructive MCP tools |\n| Tool dispatch | `assemble_tool_pool` | Assemble built-in tools and dynamic MCP tools |\n| During tool execution | background dispatch | Move slow bash work into a daemon thread and return a placeholder result |\n| After tool execution | `PostToolUse` hooks | Large-output warnings, logs, post-processing |\n| Back to loop | tool_result | One `tool_result` per `tool_use`, then the next model round |\n| No tool_use this round / on stop | `Stop` hooks | Stats, cleanup, audit |\n\n---\n\n## What code.py Contains\n\n### Tools and Dispatch\n\nThe built-in tool pool contains 27 tools:\n\n```text\nbash, read_file, write_file, edit_file, glob\ntodo_write, task, load_skill, compact\ncreate_task, list_tasks, get_task, claim_task, complete_task\nschedule_cron, list_crons, cancel_cron\nspawn_teammate, send_message, check_inbox\nrequest_shutdown, request_plan, review_plan\ncreate_worktree, remove_worktree, keep_worktree\nconnect_mcp\n```\n\n`assemble_tool_pool()` assembles these every round:\n\n```text\nBUILTIN_TOOLS + connected MCP tools\nBUILTIN_HANDLERS + mcp__server__tool handlers\n```\n\nAfter `connect_mcp(\"docs\")`, the next round exposes tools like `mcp__docs__search`.\n\n### Permissions and Hooks\n\nPermission is not hardcoded into the tool execution line. It is a `PreToolUse` hook:\n\n```python\nblocked = trigger_hooks(\"PreToolUse\", block)\nif blocked:\n results.append(tool_result(block.id, blocked))\n continue\n```\n\nThat means permission, logging, and audit logic all attach to the same hook point. After execution, `PostToolUse` hooks run.\n\n### Planning and Tasks\n\nS20 keeps two planning layers:\n\n- `todo_write`: lightweight plan for the current session, kept in memory\n- task graph: cross-session, dependency-aware, claimable task files under `.tasks/task_*.json`\n\nThe first keeps a single agent from drifting. The second supports team coordination.\n\nThey share an intent, not an implementation: `todo_write` replaces one session checklist, while task records have stable IDs and individual lifecycle updates. The separate `task` tool below means \"dispatch one isolated subagent\"; it is not the Task System.\n\n### Subagents and Teams\n\nS20 has two kinds of delegation:\n\n- `task`: one-shot subagent. It uses an isolated `messages[]`, discards intermediate context, and returns only a final summary.\n- `spawn_teammate`: persistent teammate thread. It communicates through `MessageBus`, polls the task board while idle, and can claim work autonomously.\n\nOne-shot subagents solve context isolation. Persistent teammates solve long-running parallel collaboration.\n\n### Memory, Skills, and Prompt\n\n`assemble_system_prompt(context)` assembles each round from:\n\n- identity and tool guidance\n- workspace\n- skills catalog\n- `.memory/MEMORY.md`\n- connected MCP servers\n\nSkills only put their catalog into the system prompt. Full content is loaded on demand through `load_skill(name)`.\n\n### Compaction and Recovery\n\nBefore the LLM call, S20 runs the compaction pipeline:\n\n```text\ntool_result_budget → snip_compact → micro_compact → compact_history\n```\n\nThe model call is wrapped with recovery:\n\n- 429: exponential backoff retry\n- 529: exponential backoff, optionally switch to fallback model after repeated failures\n- `max_tokens`: raise max tokens, then request continuation\n- prompt too long: reactive compact and retry\n\n### Background and Cron\n\nSlow bash work does not block the main loop:\n\n```text\nshould_run_background → start_background_task → placeholder tool_result\nbackground done → task_notification → next round injects messages\n```\n\nThe cron scheduler runs as a daemon thread and checks once per second. The CLI watches `cron_queue`; when a job fires, it injects `[Scheduled] ...` and runs one agent turn automatically.\n\n### Worktree and MCP\n\nWorktree isolation owns directories:\n\n- `create_worktree(name, task_id)` creates an isolated branch and directory\n- the task `worktree` field binds a task to that directory\n- when a teammate claims a task with a worktree, its bash/read/write tools run in that directory\n\nMCP owns external capability:\n\n- `connect_mcp(name)` connects a mock server\n- `assemble_tool_pool()` assembles MCP tools into the tool pool\n- tool names use `mcp__server__tool`\n\n---\n\n## Changes from s19\n\n| Component | s19 | s20 |\n|-----------|-----|-----|\n| tool pool | built-in + MCP | built-in + MCP, with s01-s18 tools restored |\n| permission | omitted in teaching body | runs inside `PreToolUse` hook |\n| hooks | omitted | UserPromptSubmit / PreToolUse / PostToolUse / Stop |\n| todo | omitted | `todo_write` + reminder |\n| skill | omitted | catalog in system prompt + `load_skill` |\n| compact | omitted | pre-LLM compaction + `compact` tool + reactive compact |\n| error recovery | simple try/except | retry / max_tokens / prompt too long |\n| background | omitted | slow-operation thread + task notification |\n| cron | omitted | daemon scheduler + durable jobs |\n| multi-agent | kept | kept; teammates use basic tools in isolated directories |\n| worktree | kept | kept |\n| MCP | new | kept as part of the final tool pool |\n\n---\n\n## Try It\n\n```sh\ncd learn-claude-code\npython s20_comprehensive/code.py\n```\n\nTry:\n\n1. `Create a todo list for inspecting this repo, then list Python files`\n2. `Connect to the docs MCP server and search for agent loop`\n3. `Create two tasks, create worktrees for them, then spawn alice and bob. Ask them to submit plans before claiming tasks.`\n4. `remind me of the meeting in 3 minutes.`\n5. `Run npm install in the background and continue reading README.md`\n\nWatch for:\n\n- whether each tool call passes through hooks/permission\n- whether MCP tools appear on the next round after `connect_mcp`\n- whether slow operations return a background placeholder\n- whether cron automatically reminds you when the time arrives\n- whether teammates submit plans and pause before approval\n- whether teammates can claim tasks after plan approval\n- whether teammates switch to the bound worktree directory\n\n---\n\n## The End Is the Beginning\n\nFrom s01 to s20, the code gets more capable, but the core remains unchanged:\n\n```python\nwhile True:\n response = LLM(messages, tools)\n if not has_tool_use(response.content):\n return\n results = execute_tools(response.content)\n messages.append(tool_results)\n```\n\nClaude Code's complexity is not \"another agent brain.\" It is the complexity of a mature harness. The model decides and chooses actions; the harness organizes environment, tools, permissions, memory, teams, and external capabilities.\n\nThis is the course's integration checkpoint: many mechanisms, one loop.\n\nNext: [s21 Workflow Runtime](/en/s21) — when the orchestration shape is fixed, move it out of chat turns and into deterministic, resumable code.\n" + "title": "s20: Workflow Runtime — The Model Decides Each Step; a Script Decides the Orchestration", + "content": "# s20: Workflow Runtime — The Model Decides Each Step; a Script Decides the Orchestration\n\ns01 → ... → s18 → s19 → `s20` → [s21](/en/s21)\n\n> *\"One tool_use starts an entire orchestration in the background\"* — The `Workflow` tool starts a deterministic, recoverable script runtime that dispatches many subagents in bulk.\n>\n> **Harness layer**: Orchestration — a deterministic multi-agent script runtime above the single-agent loop.\n\n`code.py` keeps the demo deterministic: it emits `async_launched` and then awaits completion in one process. This demonstrates the lifecycle and journal without requiring a long-running background service.\n\n---\n\nFrom s01 through s19, our loop has always been model-driven and step-by-step: the model chooses one tool each round, its result enters `messages[]`, and another round begins. That is ideal for open-ended tasks because the model can inspect the current context and decide the next step on the spot.\n\nSome jobs, however, require deterministic command of a group of agents. Consider reviewing a large change: inspect ten dimensions in parallel → send each finding to a separate agent for adversarial verification → combine and deduplicate the results → sort by severity. The shape is fixed, and you really need three properties:\n\n- **Parallelism**, rather than waiting for one item at a time;\n- **Determinism**, so the same input produces the same result structure;\n- **Recoverability**, so an interruption does not rerun work that is already complete.\n\nMaking the model drive this process one round at a time in the main loop is slow and nondeterministic, and an interruption starts everything over. At that point, you do not need \"one more conversation turn.\" You need to encode the orchestration directly as code.\n\n## Put the Plan in Code, Not in a Sequence of Chat Turns\n\nAdd a `Workflow` tool to the harness tool pool. The user or model provides a script that expresses deterministic orchestration through a few simple primitives: `agent()`, `parallel()`, `pipeline()`, and `phase()`.\n\nThe main loop sees only one `tool_use` and immediately receives a \"started in the background\" result. Real execution continues inside the background runtime, which reports progress in real time and records every step in a journal on disk. Intermediate script results live in variables instead of taking space in conversation history. When restarted with `resume_from_run_id`, unchanged `agent()` calls hit the journal cache and reuse previous results, resuming from the checkpoint.\n\n![Workflow Runtime Overview](/course-assets/s20_workflow_runtime/workflow-runtime-overview.svg)\n\n```python\nSAMPLE_META = {\"name\": \"review-changes\", \"description\": \"Review code changes\", \"phases\": [\"Review\", \"Verify\"]}\n\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n results = await ctx.pipeline(DIMENSIONS, audit, verify) # Each dimension independently runs audit → verify\n confirmed = [f for r in results if r for f in r[\"confirmed\"]]\n ctx.log(f\"Confirmed {len(confirmed)} real issues\")\n return {\"confirmed\": confirmed}\n```\n\n## The Workflow Tool: Start in the Background; the Main Loop Sees One Call\n\n`Workflow` lives in the main agent's tool pool. The user can request a saved workflow, or the model can select the tool when a task matches a known orchestration. In either case, the model emits one `Workflow(...)` tool call.\n\nThe tool parses the arguments, validates metadata, checks permissions, registers a local workflow task, and immediately returns \"started asynchronously.\" The main loop does not block and can continue with other work while the workflow runs in the background. This is the claim-ticket pattern from s13 at a larger scale: hand over the ticket now, notify the user when the result is ready.\n\n```python\nclass WorkflowTool:\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n run_id = resume_from_run_id or create_run_id(meta)\n task = LocalWorkflowTask(create_task_id(run_id), run_id, meta)\n task.event(\"async_launched\", runId=run_id, taskId=task.task_id) # Return immediately\n ... # The rest proceeds in the background\n```\n\n## Workflow Metadata: Validate Before Launch\n\nEach workflow registers a metadata object with `name`, `description`, and optional `phases`. The runtime validates it before executing any workflow code. `name` and `description` identify the task in the UI, while `phases` names groups in the progress display.\n\nInvalid input raises `WorkflowInputError` immediately and is rejected during registration. This is the same idea as validating cron expressions in s14: do not wait until execution to discover a bad script.\n\nBecause the runtime uses `meta.name` in local artifact filenames, it also requires a 1-64 character safe slug containing letters, numbers, `.`, `_`, or `-`.\n\n```python\ndef validate_meta(meta):\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta must be an object literal\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta requires name and description\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\"meta.name must be a safe 1-64 character slug\")\n if \"phases\" in meta and (\n not isinstance(meta[\"phases\"], list)\n or not all(isinstance(p, str) and p for p in meta[\"phases\"])\n ):\n raise WorkflowInputError(\"meta.phases must contain non-empty strings\")\n return meta\n```\n\n## Orchestration Primitives: A Small Set Is Enough for Every Flow\n\nA script runs in an isolated context with only a small set of orchestration primitives as globals. The script does not read files or run shell commands directly. All real code operations are performed by dispatched subagents under their own tool permissions. These primitives are methods on `ExecutionState`:\n\n| Primitive | Purpose |\n|------|------|\n| `agent(prompt, {schema, label, phase})` | Dispatch one subagent |\n| `parallel(thunks)` | **Barrier**: run every task concurrently and wait until all results return |\n| `pipeline(items, *stages)` | Run each item through stages **without a barrier**; finished items proceed immediately |\n| `phase(title)` | Mark the current progress phase and update the progress display |\n| `log(message)` | Emit a progress log line |\n| `workflow(name, args)` | Run a nested sub-workflow, one level only |\n\n`pipeline` should be the default. Each item independently crosses every stage. Item A may reach stage three while item B is still in stage one. Use the `parallel` barrier only when the next stage truly requires every result from the previous stage. A barrier waits for the slowest task, so do not add one without need.\n\n```python\nasync def pipeline(self, items, *stages):\n async def run_item(item, idx):\n value = item\n for stage in stages: # Each item independently completes every stage\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n```\n\n## Structured Output: Do Not Let Subagents Return Essays\n\n`agent({schema})` requires a subagent to return a JSON object matching the schema, internally through one structured-output call. The runtime validates the result and retries once if it does not match. Downstream code receives a regular object instead of a long essay that must be parsed again.\n\ns05 warned that tool arguments cannot be trusted completely. This is the same lesson in reverse: subagent output cannot be trusted completely either. Validate at the orchestration boundary, give one retry, and keep uncertainty out of the rest of the flow.\n\n```python\nresult = self.runner.run(prompt, schema, label)\nif schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # Retry once with a reminder, then fail\n result = self.runner.run(prompt + \"\\n\\nReturn valid JSON.\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) returned invalid output: {err}\")\n```\n\n## Background Tasks and Progress Events\n\n`LocalWorkflowTask` maintains status and token usage and emits an SDK-style event stream: `task_started` → a sequence of `task_progress` events containing phase changes, subagent starts, and log batches → one final `task_notification` reporting completion, failure, or stop, plus output files, token count, tool calls, and elapsed time.\n\nThe main session treats these as ordinary events. Only the final completion notification re-enters the main loop.\n\n```python\nclass LocalWorkflowTask:\n def progress_event(self, ptype, **data): # Phase/subagent/log\n self.progress.append({\"type\": ptype, **data})\n print(f\" progress {ptype} ...\")\n```\n\n## Storage: Snapshot + Journal for Resuming after Interruptions\n\nThe runtime stores each run under `s20_workflow_runtime/.runtime/`: a `.json` snapshot, `.output.json` output, and `.journal.jsonl` journal. The snapshot and journal share a stable `runId`, so resume can locate one run's state and completed steps.\n\nThe journal is the core of checkpointed resume. It records every `agent()` result one line at a time:\n\n```python\nclass WorkflowJournal:\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n```\n\n## Resume: Continue by runId and Reuse Everything Unchanged\n\nCalling the workflow again with `resume_from_run_id` reruns the script, but every `agent()` computes a deterministic semantic key. If that key is present in the journal, it returns the cached result without executing again. Every unchanged call hits the cache; only a changed call and the downstream steps that depend on it actually rerun.\n\nThe key detail is that keys cannot depend on concurrency order. Agents in `parallel` and `pipeline` finish in nondeterministic order. If \"the nth completion\" became the key, cache entries would map to the wrong calls on the next run. A key therefore uses a stable hash of call content, including type, label, prompt, and schema, rather than a shared counter:\n\n```python\ndef key(self, kind, label, prompt, schema):\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n# Inside agent():\ncached = self.journal.cached(key)\nif cached is not MISS:\n self.task.progress_event(\"workflow_agent\", label=label, status=\"cached\")\n return cached\n```\n\n## Determinism: Reproducibility Makes Resume Meaningful\n\nResume works only if the workflow is reproducible. Stable hashes and a deterministic runner make the same workflow plus the same arguments produce the same keys. Workflow code must therefore avoid uncontrolled clocks, randomness, filesystem state, and other inputs that would change those keys between runs.\n\n## See It Run\n\nThe sample `review-changes` workflow uses `pipeline` to send each review dimension independently through audit → verify. An `agent()` with a schema finds issues during audit. During verification, `parallel()` dispatches a separate adversarial subagent for every finding. Only confirmed issues remain, sorted by severity.\n\n```python\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n\n async def audit(_v, dimension, _i):\n out = await ctx.agent(f\"Inspect the changed code for {dimension} issues\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _i):\n ctx.phase(\"Verify\")\n verdicts = await ctx.parallel([ # Verify every finding independently\n (lambda f=f: ctx.agent(f\"Adversarially verify whether this issue is real: {f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\"))\n for f in audited[\"findings\"]])\n return {\"dimension\": dimension,\n \"confirmed\": [f for f, v in zip(audited[\"findings\"], verdicts) if v and v[\"isReal\"]]}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n ...\n```\n\n## Changes from s19\n\n| | s19 Comprehensive Agent | s20 Workflow Runtime |\n|--|-----------|---------------------|\n| Loop | One model-driven loop | Main loop unchanged; deterministic orchestration added above it |\n| Who decides the next step | Model decides each round | Script declares the orchestration in advance |\n| Multiple agents | One-shot s06 subagents | Scripted, reproducible, recoverable bulk orchestration |\n| New mechanisms | — | Script DSL, background tasks, progress events, journal/resume, structured output, deterministic VM |\n\ns20 does not replace the main loop. It exposes `Workflow` at the tool layer and starts a local workflow runtime behind it: one workflow deterministically drives N agent loops. An s06 subagent is dispatched once at the model's discretion; s20 turns orchestration into a replayable script.\n\n## Try It\n\n```bash\npython s20_workflow_runtime/code.py # Start review-changes and watch the event stream\npython s20_workflow_runtime/code.py resume # Resume by the last runId; every agent() hits the journal cache\n```\n\nWatch one launch produce `async_launched`, followed by background phase changes and subagent progress, then `task_notification`; the result is stored on the task object. A resumed run reports `agents=0 tokens=0` because every call hits the cache, and its result is byte-for-byte identical.\n\n## Next\n\nOrchestration adds a layer above agent capabilities: the main loop handles individual operations, while a script manages the whole team's flow. Once work becomes a deterministic, recoverable script, the model changes from the round-by-round driver into an execution unit scheduled by that script. The same `agent()` can be invoked ad hoc by the model in the main loop or orchestrated in bulk inside a workflow.\n\nNext: [s21 Goal Loop](/en/s21) — Orchestration fans work out and leaves the main loop. The next chapter moves in the opposite direction: a goal pulls control back into the main loop and refuses to let the turn end until the objective is achieved.\n\n\n" }, { "version": "s20", "locale": "zh", - "title": "s20: Comprehensive Agent — 全部机制,归到一个循环", - "content": "# s20: Comprehensive Agent — 全部机制,归到一个循环\n\ns01 → ... → s18 → s19 → `s20` → [s21](/zh/s21) → s22\n\n> *\"机制很多,循环一个\"* — 工具、权限、记忆、任务、团队、插件都挂在同一个 while True 上。\n>\n> **Harness 层**: 综合 — 把前 19 章的机制放回同一个可运行系统。\n\n---\n\n## 问题\n\n前 19 章每章只加一个机制。这样适合学习,但真实 Agent 不会只带一个机制运行。\n\n一个能长期工作的 coding agent 需要同时拥有:\n\n- 工具分发和权限边界\n- hooks 扩展点\n- todo 计划和任务图\n- 技能、记忆、系统 prompt 组装\n- 压缩和错误恢复\n- 后台任务和 cron 调度\n- 团队、协议、自治认领\n- worktree 隔离\n- MCP 外部工具接入\n\n难点不是把功能堆起来,而是看清楚它们都挂在循环的哪个位置。S20 是集成检查点:先把此前组件归位,再由 s21-s22 在外层加入编排与目标闭环。\n\n---\n\n## 解决方案\n\n![System Architecture](/course-assets/s20_comprehensive/system-architecture.svg)\n\nS20 不是再发明一个新机制,而是把前面的教学组件合成一个完整 harness:\n\n```text\n用户输入\n → UserPromptSubmit hooks\n → cron/background 通知注入\n → context compact\n → memory + skills + MCP 状态组装 system prompt\n → LLM\n → has tool_use block?\n 否 → Stop hooks → 返回\n 是 → PreToolUse hooks + permission\n → TOOL_HANDLERS / MCP handlers / background dispatch\n → PostToolUse hooks\n → tool_result / task_notification 回 messages\n → 下一轮\n```\n\n循环本身仍然是同一个结构:调用模型,检查响应里是否出现 `tool_use` block,执行工具,把结果追加回 `messages`。CC 源码里也不直接信任 `stop_reason == \"tool_use\"`,而是以实际出现的 tool_use block 作为是否继续工具轮的信号。变化的是循环周围的 harness 变完整了。\n\n---\n\n## 组件在循环中的位置\n\n| 位置 | 组件 | 作用 |\n|------|------|------|\n| 用户输入前后 | `UserPromptSubmit` hooks | 记录、注入、审计用户输入 |\n| LLM 前 | cron queue | 把定时触发的 prompt 注入 `messages` |\n| LLM 前 | background notifications | 后台任务完成后以 `` 注入 |\n| LLM 前 | compaction pipeline | 先压大输出,再裁历史,再压旧 tool_result,必要时摘要 |\n| LLM 前 | memory / skills / MCP state | 组装 system prompt,让模型看到当前能力和长期上下文 |\n| LLM 调用 | error recovery | 429/529 重试,`max_tokens` 升级,prompt too long 触发 reactive compact |\n| 工具执行前 | `PreToolUse` hooks + permission | 拦截危险命令、写越界、破坏性 MCP 工具 |\n| 工具分发 | `assemble_tool_pool` | 组装内置工具和 MCP 动态工具 |\n| 工具执行时 | background dispatch | 慢 bash 操作放 daemon thread,主循环先返回占位结果 |\n| 工具执行后 | `PostToolUse` hooks | 大输出告警、日志等后处理 |\n| 返回循环 | tool_result | 每个 `tool_use` 对应一个 `tool_result`,再回到下一轮 |\n| 本轮没有 tool_use / 停止时 | `Stop` hooks | 统计、清理、审计 |\n\n---\n\n## code.py 包含什么\n\n### 工具与分发\n\n内置工具池包含 27 个工具:\n\n```text\nbash, read_file, write_file, edit_file, glob\ntodo_write, task, load_skill, compact\ncreate_task, list_tasks, get_task, claim_task, complete_task\nschedule_cron, list_crons, cancel_cron\nspawn_teammate, send_message, check_inbox\nrequest_shutdown, request_plan, review_plan\ncreate_worktree, remove_worktree, keep_worktree\nconnect_mcp\n```\n\n`assemble_tool_pool()` 每轮组装:\n\n```text\nBUILTIN_TOOLS + connected MCP tools\nBUILTIN_HANDLERS + mcp__server__tool handlers\n```\n\n所以 `connect_mcp(\"docs\")` 后,下一轮工具池里会出现 `mcp__docs__search`。\n\n### 权限和 hooks\n\n权限不写死在工具执行行里,而是作为 `PreToolUse` hook:\n\n```python\nblocked = trigger_hooks(\"PreToolUse\", block)\nif blocked:\n results.append(tool_result(block.id, blocked))\n continue\n```\n\n这样 permission、log、审计都可以挂在同一个 hook 点上。执行后再触发 `PostToolUse`。\n\n### 计划与任务\n\nS20 同时保留两层计划:\n\n- `todo_write`:当前会话内的轻量计划,保存在内存中\n- task graph:跨会话、可依赖、可认领的任务文件,写入 `.tasks/task_*.json`\n\n前者帮助单个 Agent 不漂移;后者支撑团队协作。\n\n两者目标相近,但实现不同:`todo_write` 整表替换当前会话清单,task record 则有稳定 ID 和单条生命周期更新。下面单独出现的 `task` 工具表示“一次性派发隔离 subagent”,不是 Task System。\n\n### 子 agent 与团队\n\nS20 有两种 delegation:\n\n- `task`:一次性 subagent。独立 `messages[]`,中间过程丢弃,只返回最终摘要。\n- `spawn_teammate`:持久队友线程。通过 MessageBus 收发消息,能 idle 轮询任务板并自动认领。\n\n一次性 subagent 解决“上下文隔离”;持久队友解决“长期并行协作”。\n\n### 记忆、技能和 prompt\n\n`assemble_system_prompt(context)` 每轮组装:\n\n- 身份和工具说明\n- workspace\n- skills catalog\n- `.memory/MEMORY.md`\n- 已连接 MCP server\n\n技能只在 system prompt 里放目录。完整内容通过 `load_skill(name)` 按需加载。\n\n### 压缩和恢复\n\nLLM 前先跑压缩管线:\n\n```text\ntool_result_budget → snip_compact → micro_compact → compact_history\n```\n\n调用模型时再包一层恢复:\n\n- 429:指数退避重试\n- 529:指数退避,连续失败可切 fallback model\n- `max_tokens`:先提高 max_tokens,再要求 continuation\n- prompt too long:reactive compact 后重试\n\n### 后台和 cron\n\n慢 bash 操作不会阻塞主循环:\n\n```text\nshould_run_background → start_background_task → placeholder tool_result\n后台完成 → task_notification → 下一轮注入 messages\n```\n\ncron 调度器独立 daemon thread 每秒检查一次。CLI 会监听 `cron_queue`,命中后主动把 `[Scheduled] ...` 注入并运行一轮 Agent。\n\n### worktree 与 MCP\n\nworktree 负责隔离目录:\n\n- `create_worktree(name, task_id)` 创建独立分支和目录\n- task 的 `worktree` 字段绑定目录\n- 队友 claim 到带 worktree 的 task 后,bash/read/write 自动在对应目录下执行\n\nMCP 负责外部能力:\n\n- `connect_mcp(name)` 连接 mock server\n- `assemble_tool_pool()` 把 MCP 工具组装进工具池\n- 工具名统一为 `mcp__server__tool`\n\n---\n\n## 相对 s19 的变化\n\n| 组件 | s19 | s20 |\n|------|-----|-----|\n| 工具池 | 内置 + MCP | 内置 + MCP,补齐 s01-s18 的工具 |\n| 权限 | 教学主体省略 | `PreToolUse` hook 中执行 |\n| hooks | 省略 | UserPromptSubmit / PreToolUse / PostToolUse / Stop |\n| todo | 省略 | `todo_write` + reminder |\n| skill | 省略 | catalog in system prompt + `load_skill` |\n| compact | 省略 | LLM 前压缩 + `compact` 工具 + reactive compact |\n| error recovery | 简化 try/except | retry / max_tokens / prompt too long |\n| background | 省略 | 慢操作后台线程 + task notification |\n| cron | 省略 | daemon scheduler + durable jobs |\n| multi-agent | 保留 | 保留;队友使用隔离目录下的基础工具 |\n| worktree | 保留 | 保留 |\n| MCP | 新增 | 保留,作为最终工具池的一部分 |\n\n---\n\n## 试一下\n\n```sh\ncd learn-claude-code\npython s20_comprehensive/code.py\n```\n\n可以试:\n\n1. `Create a todo list for inspecting this repo, then list Python files`\n2. `Connect to the docs MCP server and search for agent loop`\n3. `Create two tasks, create worktrees for them, then spawn alice and bob. Ask them to submit plans before claiming tasks.`\n4. `remind me of the meeting in 3 minutes.`\n5. `Run npm install in the background and continue reading README.md`\n\n观察重点:\n\n- 工具调用前是否经过 hooks/permission\n- `connect_mcp` 后下一轮是否出现 MCP 工具\n- 慢操作是否返回 background placeholder\n- 到点是不是自动提醒开会\n- 队友是否提交 plan,并在 approval 前暂停\n- plan 批准后,队友是否能认领任务\n- worktree 绑定后,队友是否切到对应目录\n\n---\n\n## 结束亦是开始\n\n从 s01 到 s20,代码表面越来越复杂,但核心始终没变:\n\n```python\nwhile True:\n response = LLM(messages, tools)\n if not has_tool_use(response.content):\n return\n results = execute_tools(response.content)\n messages.append(tool_results)\n```\n\nClaude Code 的复杂性不是“另一个 agent 大脑”,而是一个成熟 harness 的复杂性。模型负责判断和行动选择;harness 负责把环境、工具、权限、记忆、团队和外部能力组织好。\n\n这是课程的集成检查点:机制很多,循环一个。\n\n下一章:[s21 Workflow Runtime](/zh/s21) — 当编排形状固定时,把它从多轮对话移入确定性、可恢复的代码。\n" + "title": "s20: Workflow Runtime — 模型决定单步,脚本决定编排", + "content": "# s20: Workflow Runtime — 模型决定单步,脚本决定编排\n\ns01 → ... → s18 → s19 → `s20` → [s21](/zh/s21)\n\n> *\"一次 tool_use,后台跑完一整套编排\"* — `Workflow` 工具启动一个确定、可恢复的脚本运行时,批量派出去一堆子 agent。\n>\n> **Harness 层**: 编排 — 在单 agent 循环之上,加一层确定的多 agent 脚本运行时。\n\n`code.py` 为了让演示保持确定,会先发出 `async_launched`,随后在同一进程里等待执行完成。这样不用启动常驻后台服务,也能看清生命周期和 journal。\n\n---\n\n从 s01 到 s19,我们的循环一直是模型驱动、一步一步来的:每一轮模型挑一个工具,结果塞回 `messages[]`,再来一轮。开放式任务这么干最合适,下一步做什么,让模型看着上下文临场决定就好。\n\n但有些活,你需要的是确定地指挥一群 agent 干活。比如审一个大改动:十个维度并行找问题 → 每条发现各自派一个 agent 做对抗性验证 → 结果汇总去重 → 按严重度排序。这种流程的形状是固定的,你要的其实是三样东西:\n\n- **并行**,别一个一个串着等;\n- **确定**,同样的输入跑出来同样的结果结构;\n- **可恢复**,跑到一半断了,已经做完的部分别从头再来。\n\n让模型在主循环里一步一步驱动这套流程,又慢、结果又不确定,断了还得从头跑。这时候你要的不是\"再聊一轮\",而是把这套编排直接写成代码。\n\n## 计划写在代码里,不是靠聊天一轮轮凑\n\n在 harness 的工具池里加入一个 `Workflow` 工具。用户或模型给它一段脚本,脚本用 `agent() / parallel() / pipeline() / phase()` 这几个简单的原语,把编排写成确定的代码。\n\n主循环这边只看到一次 `tool_use`,立刻拿到\"已在后台启动\"的返回:真正的执行在后台运行时里推进,实时上报进度,所有过程都写到磁盘的 journal 文件里。脚本里的中间结果存在变量里,不会塞进对话历史占地方。下次用 `resume_from_run_id` 重启时,没改过的 `agent()` 直接命中 journal 缓存,直接用之前的结果,断点续跑。\n\n![Workflow Runtime 总览](/course-assets/s20_workflow_runtime/workflow-runtime-overview.svg)\n\n```python\nSAMPLE_META = {\"name\": \"review-changes\", \"description\": \"审查代码改动\", \"phases\": [\"Review\", \"Verify\"]}\n\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n results = await ctx.pipeline(DIMENSIONS, audit, verify) # 每个维度独立走 审计 → 验证\n confirmed = [f for r in results if r for f in r[\"confirmed\"]]\n ctx.log(f\"确认了 {len(confirmed)} 个真实问题\")\n return {\"confirmed\": confirmed}\n```\n\n## Workflow 工具:后台启动,主循环只看到一次调用\n\n`Workflow` 就在主 agent 的工具池里。用户可以要求运行一个保存好的 workflow,模型也可以在任务匹配已知编排时选择这个工具;两种情况最终都只发出一次 `Workflow(...)` 工具调用。\n\n工具收到后会解析参数、校验 meta 信息、过权限检查、注册一个本地 workflow 任务,然后立刻返回\"已异步启动\"。主循环不阻塞,该干嘛干嘛;workflow 自己在后台跑。这其实就是 s13 后台任务那套\"凭条模式\"的放大版:先给你个取件条,结果好了再通知你。\n\n```python\nclass WorkflowTool:\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n run_id = resume_from_run_id or create_run_id(meta)\n task = LocalWorkflowTask(create_task_id(run_id), run_id, meta)\n task.event(\"async_launched\", runId=run_id, taskId=task.task_id) # 立刻返回\n ... # 剩下的后台慢慢跑\n```\n\n## Workflow 元数据:启动前先校验\n\n每个 workflow 都要注册一个元数据对象,包含 `name`、`description` 和可选的 `phases`。运行时会在执行任何 workflow 代码之前校验它:`name` 和 `description` 用来标识任务,`phases` 给进度条分组命名。\n\n不对的输入直接抛 `WorkflowInputError`,注册的时候就拦住——这和 s14 校验 cron 表达式是一个思路:坏脚本别让它跑到执行的时候才炸。\n\n运行时会把 `meta.name` 用在本地产物文件名中,因此还要求它是 1-64 个字符的安全 slug,只能包含字母、数字、`.`、`_`、`-`。\n\n```python\ndef validate_meta(meta):\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta 必须是对象字面量\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta 必须包含 name 和 description\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\"meta.name 必须是 1-64 字符的安全 slug\")\n if \"phases\" in meta and (\n not isinstance(meta[\"phases\"], list)\n or not all(isinstance(p, str) and p for p in meta[\"phases\"])\n ):\n raise WorkflowInputError(\"meta.phases 必须包含非空字符串\")\n return meta\n```\n\n## 编排原语:就这几个,够写所有流程\n\n脚本跑在一个独立的上下文里,能用的全局变量就这几个编排原语。脚本本身不直接读写文件、不跑 shell,真正的代码操作都由派出去的子 agent 用它们自己的工具权限完成。这些原语都是 `ExecutionState` 上的方法:\n\n| 原语 | 作用 |\n|------|------|\n| `agent(prompt, {schema, label, phase})` | 派一个子 agent 干活 |\n| `parallel(thunks)` | **等齐屏障**:所有任务并行跑完,一起等结果回来 |\n| `pipeline(items, *stages)` | 每个 item 分阶段跑,**不等齐**,跑完一个往下走一个 |\n| `phase(title)` | 标记当前进度阶段(更新进度条) |\n| `log(message)` | 打一行进度日志 |\n| `workflow(name, args)` | 嵌套子工作流(只支持一层) |\n\n`pipeline` 是你默认该用的:每个 item 独立穿过所有 stage,item A 跑到第 3 阶段的时候,item B 可能还在第 1 阶段;只有真的需要\"拿到上一阶段所有结果才能往下走\"的时候,才用 `parallel` 这个屏障。屏障的代价是等最慢的那个任务,没必要就别立。\n\n```python\nasync def pipeline(self, items, *stages):\n async def run_item(item, idx):\n value = item\n for stage in stages: # 每个 item 独立跑完所有 stage\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n```\n\n## 结构化输出:别让子 agent 回来写散文\n\n`agent({schema})` 会强制子 agent 返回一个匹配 schema 的 JSON 对象(内部通过一次结构化输出调用实现),运行时会按 schema 校验结果,不对就重试一次。这样下游代码拿到的是规整的对象,不是需要再解析的一大段散文。\n\ns05 就说过,工具的参数不能全信;这里是同一个道理反过来:子 agent 的输出也不能全信。加一层校验,不对就给一次机会重试,把不确定性挡在编排层外面。\n\n```python\nresult = self.runner.run(prompt, schema, label)\nif schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # 提醒一次重试,再不对就报错\n result = self.runner.run(prompt + \"\\n\\n返回合法的 JSON。\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) 输出不合法: {err}\")\n```\n\n## 后台任务和进度事件\n\n`LocalWorkflowTask` 维护状态和 token 用量,向外发一条 SDK 风格的事件流:`task_started` → 一串 `task_progress`(包含阶段切换、子 agent 启动、日志输出这些批次)→ 最后一个 `task_notification`(完成/失败/停止,带输出文件、token 数、工具调用数、耗时)。\n\n主会话把这些当普通事件处理;只有最终的完成通知会重新进入主循环。\n\n```python\nclass LocalWorkflowTask:\n def progress_event(self, ptype, **data): # 阶段/子agent/日志\n self.progress.append({\"type\": ptype, **data})\n print(f\" 进度 {ptype} ...\")\n```\n\n## 存储:快照 + journal,断了能续\n\n运行时把每次运行的数据存在 `s20_workflow_runtime/.runtime/`:快照 `.json`、输出 `.output.json` 和 journal `.journal.jsonl`。快照与 journal 共享稳定的 `runId`,续跑时才能找到同一次运行的状态和已完成步骤。\n\njournal 是断点续跑的核心,它一条一条记下来每个 `agent()` 的结果:\n\n```python\nclass WorkflowJournal:\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n```\n\n## resume:用 runId 续跑,没改的直接用缓存\n\n带着 `resume_from_run_id` 再次调用 workflow 时,脚本会重新执行,但每个 `agent()` 都会计算一个确定的语义 key:key 在 journal 里有记录,就直接返回缓存结果;只有改过的调用以及依赖它的后续步骤才会真的运行。\n\n这里有个关键点:key 不能依赖并发顺序。`parallel` 和 `pipeline` 里 agent 完成的顺序是不确定的,用\"第几个完成\"当 key,两次跑缓存就对错位了。所以 key 是根据调用内容(类型、标签、prompt、schema)算的稳定哈希,不是一个会竞争的计数器:\n\n```python\ndef key(self, kind, label, prompt, schema):\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n# agent() 内部:\ncached = self.journal.cached(key)\nif cached is not MISS:\n self.task.progress_event(\"workflow_agent\", label=label, status=\"cached\")\n return cached\n```\n\n## 确定性:能复现,续跑才有意义\n\n续跑要能工作,workflow 首先得可复现。稳定哈希和确定性的 runner 让同一份 workflow + 同样的参数产生同样的 key。因此 workflow 代码要避免不受控的时钟、随机数、文件系统状态等会让 key 在两次运行间变化的输入。\n\n## 跑起来看看\n\n示例 workflow `review-changes`:用 `pipeline` 让每个审查维度独立走\"审计 → 验证\"流程。审计用一个带 schema 的 `agent()` 找问题,验证用 `parallel()` 给每条发现各派一个对抗性验证的子 agent,最后只留确认真实的问题,按严重度排序。\n\n```python\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n\n async def audit(_v, dimension, _i):\n out = await ctx.agent(f\"检查改动的代码里有没有{dimension}相关的问题\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _i):\n ctx.phase(\"Verify\")\n verdicts = await ctx.parallel([ # 每条发现独立做对抗性验证\n (lambda f=f: ctx.agent(f\"请对抗性验证这个问题是不是真的:{f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\"))\n for f in audited[\"findings\"]])\n return {\"dimension\": dimension,\n \"confirmed\": [f for f, v in zip(audited[\"findings\"], verdicts) if v and v[\"isReal\"]]}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n ...\n```\n\n## 相对 s19 的变更\n\n| | s19 综合体 | s20 Workflow Runtime |\n|--|-----------|---------------------|\n| 循环 | 单个、模型驱动 | 主循环不变;上面加一层确定的编排 |\n| 谁决定下一步 | 模型逐轮决定 | 脚本预先写好编排流程 |\n| 多 agent | s06 子 agent,一次性派出去 | 脚本化、可复现、可恢复的批量编排 |\n| 新增机制 | — | 脚本 DSL、后台任务、进度事件、journal/续跑、结构化输出、确定性 VM |\n\ns20 不替换主循环,它只是在工具层暴露了 `Workflow`,背后启动一个本地 workflow 运行时:一个 workflow 确定地驱动 N 个 agent 循环。s06 的子 agent 是模型临场派一次;s20 是把编排写成可以重放的脚本。\n\n## 试一下\n\n```bash\npython s20_workflow_runtime/code.py # 启动 review-changes,看事件流\npython s20_workflow_runtime/code.py resume # 用上次的 runId 续跑,每个 agent() 都命中 journal 缓存\n```\n\n观察:一次启动 → `async_launched` → 后台阶段切换/子agent进度推进 → `task_notification`;结果存在任务对象上。续跑的时候会显示 `agents=0 tokens=0`(全部命中缓存),结果和上次一字不差。\n\n## 接下来\n\n编排是在 agent 能力之上又加了一层:主循环管单步操作,脚本管整支队伍的流程。把工作写成确定、可恢复的脚本,模型就从\"逐轮驱动者\"变成了\"被脚本调度的执行单元\"。同一个 `agent()`,既能在主循环里被模型临场调用,也能在 workflow 里被脚本批量编排。\n\n下一章:[s21 Goal Loop](/zh/s21) — 编排是把工作扇出去、脱离主循环;下一章反过来,一个目标把控制权重拉回主循环,没达成就不让这一轮结束。\n\n\n" }, { "version": "s20", "locale": "ja", - "title": "s20: Comprehensive Agent — すべての仕組みを 1 つのループへ", - "content": "# s20: Comprehensive Agent — すべての仕組みを 1 つのループへ\n\ns01 → ... → s18 → s19 → `s20` → [s21](/ja/s21) → s22\n\n> *\"仕組みは多い、ループは 1 つ\"* — tools、permissions、memory、tasks、teams、plugins はすべて同じ `while True` に接続される。\n>\n> **Harness レイヤー**: 総合 — 前 19 章の仕組みを 1 つの実行可能なシステムへ戻す。\n\n---\n\n## 問題\n\n前 19 章では、各章が 1 つの仕組みだけを追加した。学習にはその形が適している。しかし実際の agent は、1 つの仕組みだけで動くわけではない。\n\n長時間動く coding agent には、同時に次のものが必要になる:\n\n- tool dispatch と permission boundary\n- hook extension point\n- todo plan と task graph\n- skill、memory、runtime system prompt assembly\n- compaction と error recovery\n- background task と cron scheduling\n- team、protocol、autonomous claiming\n- worktree isolation\n- MCP external tool integration\n\n難しいのは機能を積み上げることではない。それぞれの仕組みが loop のどこに接続されるかを見抜くことだ。S20 は統合チェックポイントであり、これまでの component を 1 つの harness に戻してから、s21-s22 が編成と目標完了を外側に追加する。\n\n---\n\n## 解決策\n\n![System Architecture](/course-assets/s20_comprehensive/system-architecture.ja.svg)\n\nS20 は新しい単独 mechanism を発明しない。前章までの teaching component を 1 つの完全な harness に統合する:\n\n```text\nuser input\n → UserPromptSubmit hooks\n → cron/background notification injection\n → context compact\n → memory + skills + MCP state で system prompt を組み立てる\n → LLM\n → has tool_use block?\n no → Stop hooks → return\n yes → PreToolUse hooks + permission\n → TOOL_HANDLERS / MCP handlers / background dispatch\n → PostToolUse hooks\n → tool_result / task_notification を messages へ戻す\n → next round\n```\n\nloop 自体は同じ構造のままだ。model を呼び、response に `tool_use` block があるかを見て、tool を実行し、結果を `messages` に戻す。CC source でも `stop_reason == \"tool_use\"` を直接信頼せず、実際に tool_use block が出たかを continuation signal として扱う。変わったのは、loop の周囲の harness が完成形になったことだけ。\n\n---\n\n## 各 Component の位置\n\n| 位置 | Component | 役割 |\n|------|-----------|------|\n| user input 周辺 | `UserPromptSubmit` hooks | user input の記録、注入、監査 |\n| LLM 前 | cron queue | scheduled prompt を `messages` へ注入 |\n| LLM 前 | background notifications | 完了した background work を `` として注入 |\n| LLM 前 | compaction pipeline | 大きな出力を予算化し、履歴を切り、古い tool_result を圧縮し、必要なら要約 |\n| LLM 前 | memory / skills / MCP state | current capabilities と long-term context を system prompt に組み込む |\n| LLM call | error recovery | 429/529 retry、`max_tokens` escalation、prompt-too-long compact |\n| tool 実行前 | `PreToolUse` hooks + permission | 危険な command、範囲外 write、destructive MCP tool を止める |\n| tool dispatch | `assemble_tool_pool` | built-in tools と dynamic MCP tools を組み立てる |\n| tool 実行中 | background dispatch | 遅い bash work を daemon thread に逃がし、placeholder result を返す |\n| tool 実行後 | `PostToolUse` hooks | large-output warning、log、後処理 |\n| loop へ戻る | tool_result | 1 つの `tool_use` に 1 つの `tool_result`、そして次の model round |\n| tool_use がない round / stop 時 | `Stop` hooks | 統計、cleanup、audit |\n\n---\n\n## code.py に含まれるもの\n\n### Tools と Dispatch\n\nbuilt-in tool pool には 27 個の tool がある:\n\n```text\nbash, read_file, write_file, edit_file, glob\ntodo_write, task, load_skill, compact\ncreate_task, list_tasks, get_task, claim_task, complete_task\nschedule_cron, list_crons, cancel_cron\nspawn_teammate, send_message, check_inbox\nrequest_shutdown, request_plan, review_plan\ncreate_worktree, remove_worktree, keep_worktree\nconnect_mcp\n```\n\n`assemble_tool_pool()` は毎 round で次を組み立てる:\n\n```text\nBUILTIN_TOOLS + connected MCP tools\nBUILTIN_HANDLERS + mcp__server__tool handlers\n```\n\n`connect_mcp(\"docs\")` のあと、次の round では `mcp__docs__search` のような tool が出現する。\n\n### Permission と Hooks\n\npermission は tool 実行行に直接埋め込まない。`PreToolUse` hook として扱う:\n\n```python\nblocked = trigger_hooks(\"PreToolUse\", block)\nif blocked:\n results.append(tool_result(block.id, blocked))\n continue\n```\n\nこれにより permission、logging、audit が同じ hook point に接続できる。実行後には `PostToolUse` hook が走る。\n\n### Plan と Task\n\nS20 には 2 層の plan がある:\n\n- `todo_write`: current session 用の軽量 plan。メモリに保持。\n- task graph: cross-session、dependency-aware、claimable な task file。`.tasks/task_*.json` に保存。\n\n前者は単独 agent の drift を防ぐ。後者は team coordination の土台になる。\n\n目的は近いが実装は別である。`todo_write` は現在のセッションのチェックリスト全体を置き換え、task record は安定 ID と個別のライフサイクル更新を持つ。次節の独立した `task` ツールは「隔離 subagent を一度派遣する」意味であり、Task System ではない。\n\n### Subagent と Team\n\nS20 には 2 種類の delegation がある:\n\n- `task`: one-shot subagent。独立した `messages[]` を使い、中間 context を捨て、final summary だけ返す。\n- `spawn_teammate`: persistent teammate thread。`MessageBus` で通信し、idle 中に task board を polling して自律的に claim できる。\n\none-shot subagent は context isolation を解決する。persistent teammate は長期並列協作を解決する。\n\n### Memory、Skills、Prompt\n\n`assemble_system_prompt(context)` は毎 round 次を組み立てる:\n\n- identity と tool guidance\n- workspace\n- skills catalog\n- `.memory/MEMORY.md`\n- connected MCP servers\n\nskills は system prompt には catalog だけ置く。全文は `load_skill(name)` で必要な時に読む。\n\n### Compaction と Recovery\n\nLLM call の前に compaction pipeline を走らせる:\n\n```text\ntool_result_budget → snip_compact → micro_compact → compact_history\n```\n\nmodel call は recovery で包む:\n\n- 429: exponential backoff retry\n- 529: exponential backoff、連続失敗時は fallback model へ切替可能\n- `max_tokens`: max tokens を上げ、その後 continuation を要求\n- prompt too long: reactive compact 後に retry\n\n### Background と Cron\n\n遅い bash work は main loop を止めない:\n\n```text\nshould_run_background → start_background_task → placeholder tool_result\nbackground done → task_notification → next round injects messages\n```\n\ncron scheduler は daemon thread として動き、1 秒ごとに確認する。CLI は `cron_queue` を監視し、発火した job を `[Scheduled] ...` として注入して Agent を 1 turn 自動実行する。\n\n### Worktree と MCP\n\nworktree isolation は directory を担当する:\n\n- `create_worktree(name, task_id)` が isolated branch と directory を作る\n- task の `worktree` field が task と directory を紐付ける\n- teammate が worktree 付き task を claim すると、bash/read/write はその directory で実行される\n\nMCP は external capability を担当する:\n\n- `connect_mcp(name)` が mock server に接続する\n- `assemble_tool_pool()` が MCP tools を tool pool に組み立てる\n- tool name は `mcp__server__tool` 形式に統一する\n\n---\n\n## s19 からの変化\n\n| Component | s19 | s20 |\n|-----------|-----|-----|\n| tool pool | built-in + MCP | built-in + MCP、s01-s18 の tool を補完 |\n| permission | teaching body では省略 | `PreToolUse` hook で実行 |\n| hooks | 省略 | UserPromptSubmit / PreToolUse / PostToolUse / Stop |\n| todo | 省略 | `todo_write` + reminder |\n| skill | 省略 | system prompt の catalog + `load_skill` |\n| compact | 省略 | LLM 前 compaction + `compact` tool + reactive compact |\n| error recovery | simple try/except | retry / max_tokens / prompt too long |\n| background | 省略 | slow-operation thread + task notification |\n| cron | 省略 | daemon scheduler + durable jobs |\n| multi-agent | 維持 | 維持。teammate は isolated directory 上の basic tools を使う |\n| worktree | 維持 | 維持 |\n| MCP | 新規 | final tool pool の一部として維持 |\n\n---\n\n## 試す\n\n```sh\ncd learn-claude-code\npython s20_comprehensive/code.py\n```\n\n試す prompt:\n\n1. `Create a todo list for inspecting this repo, then list Python files`\n2. `Connect to the docs MCP server and search for agent loop`\n3. `Create two tasks, create worktrees for them, then spawn alice and bob. Ask them to submit plans before claiming tasks.`\n4. `remind me of the meeting in 3 minutes.`\n5. `Run npm install in the background and continue reading README.md`\n\n見るポイント:\n\n- tool call の前に hooks/permission を通るか\n- `connect_mcp` 後の次 round で MCP tool が出るか\n- 遅い operation が background placeholder を返すか\n- cron が時刻到達時に自動で reminder を返すか\n- teammate が plan を提出し、approval 前に停止するか\n- plan approval 後、teammate が task を claim できるか\n- worktree binding 後、teammate が対応 directory に切り替わるか\n\n---\n\n## 終わりは始まり\n\ns01 から s20 まで、コードの能力は増えていく。しかし中心は変わらない:\n\n```python\nwhile True:\n response = LLM(messages, tools)\n if not has_tool_use(response.content):\n return\n results = execute_tools(response.content)\n messages.append(tool_results)\n```\n\nClaude Code の複雑さは「別の agent brain」ではない。成熟した harness の複雑さだ。model は判断と action selection を担当する。harness は environment、tools、permissions、memory、teams、external capabilities を整理する。\n\nこれは本コースの統合チェックポイントだ:仕組みは多い、ループは 1 つ。\n\n次へ:[s21 Workflow Runtime](/ja/s21) — 編成の形が固定なら、多数の会話ターンではなく、決定的で再開可能なコードへ移す。\n" + "title": "s20: Workflow Runtime — モデルが単一 step を決め、script が orchestration を決める", + "content": "# s20: Workflow Runtime — モデルが単一 step を決め、script が orchestration を決める\n\ns01 → ... → s18 → s19 → `s20` → [s21](/ja/s21)\n\n> *「1 回の tool_use で、バックグラウンドに一式の orchestration を走らせる」* — `Workflow` ツールが決定的で復元可能な script runtime を起動し、多数の subagent をまとめて送り出します。\n>\n> **Harness 層**: Orchestration — single-agent loop の上に、決定的な multi-agent script runtime を追加します。\n\n`code.py` は demo を決定的に保つため、`async_launched` を出した後、同じ process で完了を待ちます。常駐 background service を用意しなくても、lifecycle と journal を確認できます。\n\n---\n\ns01 から s19 まで、loop は常にモデル駆動で 1 step ずつ進みました。各ラウンドでモデルが 1 つのツールを選び、結果を `messages[]` へ入れ、次のラウンドへ進みます。open-ended なタスクには最適です。次に何をするかを、モデルが context を見てその場で決められます。\n\nしかし、複数の Agent を決定的に指揮したい仕事もあります。大きな変更の review を考えてください。10 の観点から並行して問題を探す → 各 finding へ別 Agent を送り adversarial verification を行う → 結果を集約して重複を除く → severity 順に並べる。この流れの形は固定されており、本当に必要なのは 3 つです。\n\n- **並行性**: 1 件ずつ順番に待たないこと。\n- **決定性**: 同じ入力から同じ結果構造が得られること。\n- **復元可能性**: 途中で止まっても、完了済みの部分を最初からやり直さないこと。\n\nこの流れをモデルに main loop で 1 ラウンドずつ動かさせると、遅く、結果は不確定で、中断すれば最初からです。ここで必要なのは「もう 1 turn 話す」ことではなく、orchestration をそのままコードにすることです。\n\n## 計画は chat のラウンドを重ねず、コードに書く\n\nharness の tool pool に `Workflow` ツールを追加します。ユーザーまたはモデルが渡す script は、`agent() / parallel() / pipeline() / phase()` という少数の primitive を使い、orchestration を決定的なコードとして表します。\n\nmain loop から見えるのは 1 回の `tool_use` だけで、すぐ「バックグラウンドで起動済み」という結果を受け取ります。本当の実行は background runtime で進み、進捗をリアルタイムに報告し、全過程をディスク上の journal へ記録します。script の中間結果は変数に保存され、会話履歴の場所を取りません。`resume_from_run_id` で再開すると、変更されていない `agent()` は journal cache に当たり、以前の結果を直接使って checkpoint から続行します。\n\n![Workflow Runtime Overview](/course-assets/s20_workflow_runtime/workflow-runtime-overview.svg)\n\n```python\nSAMPLE_META = {\"name\": \"review-changes\", \"description\": \"コード変更を review\", \"phases\": [\"Review\", \"Verify\"]}\n\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n results = await ctx.pipeline(DIMENSIONS, audit, verify) # 各 dimension が独立して audit → verify を通る\n confirmed = [f for r in results if r for f in r[\"confirmed\"]]\n ctx.log(f\"{len(confirmed)} 件の実在する問題を確認\")\n return {\"confirmed\": confirmed}\n```\n\n## Workflow ツール: バックグラウンド起動、main loop には 1 回の call だけ\n\n`Workflow` は main Agent の tool pool にあります。ユーザーが保存済み workflow の実行を求めるか、タスクが既知の orchestration に一致したときにモデルがこのツールを選びます。どちらも 1 回の `Workflow(...)` tool call になります。\n\nツールは argument を parse し、meta 情報を検証し、permission check を通し、local workflow task を登録すると、すぐ「非同期で起動済み」と返します。main loop は block せず別の仕事を続け、workflow は background で実行されます。これは s13 の引換券 pattern を拡大したものです。先に引換券を渡し、結果ができたら通知します。\n\n```python\nclass WorkflowTool:\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n run_id = resume_from_run_id or create_run_id(meta)\n task = LocalWorkflowTask(create_task_id(run_id), run_id, meta)\n task.event(\"async_launched\", runId=run_id, taskId=task.task_id) # すぐ return\n ... # 残りはバックグラウンドで進む\n```\n\n## Workflow metadata: 起動前に検証する\n\n各 workflow は `name`、`description`、任意の `phases` を持つ metadata object を登録します。runtime は workflow code を実行する前に検証します。`name` と `description` は task と UI の表示に使い、`phases` は progress bar の group 名を定義します。\n\n不正な入力はすぐ `WorkflowInputError` になり、登録時に止まります。s14 の cron 式検証と同じ考えです。不正な script が実行時まで進んでから壊れないようにします。\n\nruntime は `meta.name` をローカル artifact のファイル名に使うため、英数字で始まり、英数字、`.`、`_`、`-` のみからなる 1-64 文字の安全な slug も要求する。\n\n```python\ndef validate_meta(meta):\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta は object literal でなければなりません\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta には name と description が必要です\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\"meta.name は安全な 1-64 文字の slug が必要です\")\n if \"phases\" in meta and (\n not isinstance(meta[\"phases\"], list)\n or not all(isinstance(p, str) and p for p in meta[\"phases\"])\n ):\n raise WorkflowInputError(\"meta.phases は空でない文字列だけを含む必要があります\")\n return meta\n```\n\n## Orchestration primitive: この少数だけで、すべての flow を書ける\n\nscript は独立した context で動き、global variable として使えるのは少数の orchestration primitive だけです。script 自身はファイルを直接読み書きせず、shell も実行しません。実際のコード操作は、派遣された subagent が自分の tool permission で行います。primitive はすべて `ExecutionState` の method です。\n\n| Primitive | 役割 |\n|------|------|\n| `agent(prompt, {schema, label, phase})` | 1 つの subagent を派遣 |\n| `parallel(thunks)` | **barrier**: すべての task を並行実行し、全結果が戻るまで待つ |\n| `pipeline(items, *stages)` | 各 item を **barrier なし**で stage ごとに実行し、終わった item から先へ進める |\n| `phase(title)` | 現在の progress phase を記録し、progress bar を更新 |\n| `log(message)` | progress log を 1 行出力 |\n| `workflow(name, args)` | nested sub-workflow(1 階層だけ) |\n\n既定では `pipeline` を使うべきです。各 item がすべての stage を独立して通り、item A が stage 3 にいる間、item B はまだ stage 1 かもしれません。次の stage へ進むために前 stage の全結果が本当に必要なときだけ、`parallel` barrier を使います。barrier は最も遅い task を待つため、不要なら置かないでください。\n\n```python\nasync def pipeline(self, items, *stages):\n async def run_item(item, idx):\n value = item\n for stage in stages: # 各 item がすべての stage を独立して完走\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n```\n\n## 構造化出力: Subagent に散文を返させない\n\n`agent({schema})` は、schema に一致する JSON object を subagent に要求します。内部では structured output call を 1 回使い、runtime が結果を schema で検証し、不一致なら 1 回 retry します。下流コードが受け取るのは規則的な object であり、再 parse が必要な長文ではありません。\n\ns05 では tool argument を全面的に信頼できないと説明しました。ここでは同じ教訓を逆向きに使います。subagent の出力も全面的には信頼できません。orchestration boundary で検証し、1 回 retry の機会を与え、不確実性を後続 flow の外へ止めます。\n\n```python\nresult = self.runner.run(prompt, schema, label)\nif schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # 1 回だけ注意して retry、それでも不正なら error\n result = self.runner.run(prompt + \"\\n\\n有効な JSON を返してください。\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) の出力が不正です: {err}\")\n```\n\n## Background task と progress event\n\n`LocalWorkflowTask` は status と token usage を管理し、SDK style の event stream を外へ出します。`task_started` → phase change、subagent start、log batch を含む一連の `task_progress` → 完了、失敗、停止に加え、output file、token 数、tool call 数、所要時間を含む最後の `task_notification` です。\n\nmain session は通常 event として処理し、最後の完了通知だけが main loop へ再び入ります。\n\n```python\nclass LocalWorkflowTask:\n def progress_event(self, ptype, **data): # phase/subagent/log\n self.progress.append({\"type\": ptype, **data})\n print(f\" progress {ptype} ...\")\n```\n\n## 保存: Snapshot + journal で中断から再開する\n\nruntime は各 run を `s20_workflow_runtime/.runtime/` に保存します。`.json` snapshot、`.output.json` output、`.journal.jsonl` journal です。snapshot と journal は安定した `runId` を共有し、resume 時に同じ run の状態と完了済み step を特定できるようにします。\n\njournal は checkpoint resume の中心で、各 `agent()` の結果を 1 行ずつ記録します。\n\n```python\nclass WorkflowJournal:\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n```\n\n## Resume: runId から続行し、変更のないものを再利用する\n\n`resume_from_run_id` を渡して workflow を再度呼ぶと script を再実行しますが、各 `agent()` は決定的な semantic key を計算します。journal に key があれば、再実行せず cached result を返します。変更された call と、それに依存する後続 step だけが本当に動きます。\n\nkey は concurrency の完了順に依存してはいけません。`parallel` と `pipeline` の Agent は不定の順番で完了します。「何番目に完了したか」を key にすると、次回の cache が別の call へ対応してしまいます。そのため key は競合する counter ではなく、call の内容、つまり type、label、prompt、schema の stable hash です。\n\n```python\ndef key(self, kind, label, prompt, schema):\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n# agent() の内部:\ncached = self.journal.cached(key)\nif cached is not MISS:\n self.task.progress_event(\"workflow_agent\", label=label, status=\"cached\")\n return cached\n```\n\n## 決定性: Resume に意味を持たせる再現性\n\nresume が動くには、workflow が再現可能でなければなりません。stable hash と決定的な runner は、同じ workflow + 同じ argument から同じ key を作ります。そのため workflow code は、制御されていない clock、randomness、filesystem state など、run ごとに key を変える入力を避けます。\n\n## 実際に動かす\n\nsample workflow `review-changes` は `pipeline` を使い、各 review dimension を独立して audit → verify へ通します。audit では schema 付き `agent()` が問題を探し、verify では `parallel()` が各 finding に別の adversarial verification subagent を送ります。実在すると確認された問題だけを残し、severity 順に並べます。\n\n```python\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n\n async def audit(_v, dimension, _i):\n out = await ctx.agent(f\"変更されたコードに {dimension} 関連の問題がないか確認してください\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _i):\n ctx.phase(\"Verify\")\n verdicts = await ctx.parallel([ # 各 finding を独立して verify\n (lambda f=f: ctx.agent(f\"この問題が実在するか adversarial に検証してください: {f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\"))\n for f in audited[\"findings\"]])\n return {\"dimension\": dimension,\n \"confirmed\": [f for f, v in zip(audited[\"findings\"], verdicts) if v and v[\"isReal\"]]}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n ...\n```\n\n## s19 からの変更点\n\n| | s19 Comprehensive Agent | s20 Workflow Runtime |\n|--|-----------|---------------------|\n| loop | 1 つ、モデル駆動 | main loop は不変。その上に決定的 orchestration を追加 |\n| 次の step を決めるもの | モデルが毎ラウンド判断 | script が orchestration flow を事前に定義 |\n| multi-agent | s06 subagent を一度だけ派遣 | script 化された、再現可能で復元可能な一括 orchestration |\n| 新しい仕組み | — | script DSL、background task、progress event、journal/resume、structured output、deterministic VM |\n\ns20 は main loop を置き換えません。tool layer に `Workflow` を公開し、背後で local workflow runtime を起動します。1 つの workflow が N 個の Agent loop を決定的に駆動します。s06 の subagent はモデルがその場で 1 回派遣し、s20 は orchestration を replay 可能な script にします。\n\n## 試してみる\n\n```bash\npython s20_workflow_runtime/code.py # review-changes を起動し、event stream を確認\npython s20_workflow_runtime/code.py resume # 前回の runId から resume。すべての agent() が journal cache に当たる\n```\n\n1 回の起動から `async_launched`、background の phase change と subagent progress、最後の `task_notification` までを観察してください。結果は task object に保存されます。resume 時はすべて cache hit するため `agents=0 tokens=0` と表示され、結果は前回と 1 byte も違いません。\n\n## 次へ\n\norchestration は Agent 能力の上にもう 1 層を加えます。main loop は個々の操作を管理し、script はチーム全体の flow を管理します。仕事が決定的で復元可能な script になると、モデルは「ラウンドごとの driver」から「script に schedule される実行 unit」へ変わります。同じ `agent()` を main loop でモデルがその場で呼ぶことも、workflow 内で script がまとめて編成することもできます。\n\n次へ: [s21 Goal Loop](/ja/s21) — Orchestration は仕事を fan-out し、main loop から離れます。次章は逆に、1 つの goal が control を main loop へ引き戻し、objective が達成されるまで turn の終了を認めません。\n\n\n" }, { "version": "s21", "locale": "en", - "title": "s21: Workflow Runtime — The Model Decides Each Step; a Script Decides the Orchestration", - "content": "# s21: Workflow Runtime — The Model Decides Each Step; a Script Decides the Orchestration\n\ns01 → ... → s19 → s20 → `s21` → [s22](/en/s22)\n\n> *\"One tool_use starts an entire orchestration in the background\"* — The `Workflow` tool starts a deterministic, recoverable script runtime that dispatches many subagents in bulk.\n>\n> **Harness layer**: Orchestration — a deterministic multi-agent script runtime above the single-agent loop.\n\n`code.py` keeps the demo deterministic: it emits `async_launched` and then awaits completion in one process. This demonstrates the lifecycle and journal without requiring a long-running background service.\n\n---\n\nFrom s01 through s20, our loop has always been model-driven and step-by-step: the model chooses one tool each round, its result enters `messages[]`, and another round begins. That is ideal for open-ended tasks because the model can inspect the current context and decide the next step on the spot.\n\nSome jobs, however, require deterministic command of a group of agents. Consider reviewing a large change: inspect ten dimensions in parallel → send each finding to a separate agent for adversarial verification → combine and deduplicate the results → sort by severity. The shape is fixed, and you really need three properties:\n\n- **Parallelism**, rather than waiting for one item at a time;\n- **Determinism**, so the same input produces the same result structure;\n- **Recoverability**, so an interruption does not rerun work that is already complete.\n\nMaking the model drive this process one round at a time in the main loop is slow and nondeterministic, and an interruption starts everything over. At that point, you do not need \"one more conversation turn.\" You need to encode the orchestration directly as code.\n\n## Put the Plan in Code, Not in a Sequence of Chat Turns\n\nAdd a `Workflow` tool to the harness tool pool. The user or model provides a script that expresses deterministic orchestration through a few simple primitives: `agent()`, `parallel()`, `pipeline()`, and `phase()`.\n\nThe main loop sees only one `tool_use` and immediately receives a \"started in the background\" result. Real execution continues inside the background runtime, which reports progress in real time and records every step in a journal on disk. Intermediate script results live in variables instead of taking space in conversation history. When restarted with `resume_from_run_id`, unchanged `agent()` calls hit the journal cache and reuse previous results, resuming from the checkpoint.\n\n![Workflow Runtime Overview](/course-assets/s21_workflow_runtime/workflow-runtime-overview.svg)\n\n```python\nSAMPLE_META = {\"name\": \"review-changes\", \"description\": \"Review code changes\", \"phases\": [\"Review\", \"Verify\"]}\n\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n results = await ctx.pipeline(DIMENSIONS, audit, verify) # Each dimension independently runs audit → verify\n confirmed = [f for r in results if r for f in r[\"confirmed\"]]\n ctx.log(f\"Confirmed {len(confirmed)} real issues\")\n return {\"confirmed\": confirmed}\n```\n\n## The Workflow Tool: Start in the Background; the Main Loop Sees One Call\n\n`Workflow` lives in the main agent's tool pool. The user can request a saved workflow, or the model can select the tool when a task matches a known orchestration. In either case, the model emits one `Workflow(...)` tool call.\n\nThe tool parses the arguments, validates metadata, checks permissions, registers a local workflow task, and immediately returns \"started asynchronously.\" The main loop does not block and can continue with other work while the workflow runs in the background. This is the claim-ticket pattern from s13 at a larger scale: hand over the ticket now, notify the user when the result is ready.\n\n```python\nclass WorkflowTool:\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n run_id = resume_from_run_id or create_run_id(meta)\n task = LocalWorkflowTask(create_task_id(run_id), run_id, meta)\n task.event(\"async_launched\", runId=run_id, taskId=task.task_id) # Return immediately\n ... # The rest proceeds in the background\n```\n\n## Workflow Metadata: Validate Before Launch\n\nEach workflow registers a metadata object with `name`, `description`, and optional `phases`. The runtime validates it before executing any workflow code. `name` and `description` identify the task in the UI, while `phases` names groups in the progress display.\n\nInvalid input raises `WorkflowInputError` immediately and is rejected during registration. This is the same idea as validating cron expressions in s14: do not wait until execution to discover a bad script.\n\nBecause the teaching runtime uses `meta.name` in local artifact filenames, it also requires a 1-64 character safe slug containing letters, numbers, `.`, `_`, or `-`.\n\n```python\ndef validate_meta(meta):\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta must be an object literal\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta requires name and description\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\"meta.name must be a safe 1-64 character slug\")\n if \"phases\" in meta and (\n not isinstance(meta[\"phases\"], list)\n or not all(isinstance(p, str) and p for p in meta[\"phases\"])\n ):\n raise WorkflowInputError(\"meta.phases must contain non-empty strings\")\n return meta\n```\n\n## Orchestration Primitives: A Small Set Is Enough for Every Flow\n\nA script runs in an isolated context with only a small set of orchestration primitives as globals. The script does not read files or run shell commands directly. All real code operations are performed by dispatched subagents under their own tool permissions. These primitives are methods on `ExecutionState`:\n\n| Primitive | Purpose |\n|------|------|\n| `agent(prompt, {schema, label, phase})` | Dispatch one subagent |\n| `parallel(thunks)` | **Barrier**: run every task concurrently and wait until all results return |\n| `pipeline(items, *stages)` | Run each item through stages **without a barrier**; finished items proceed immediately |\n| `phase(title)` | Mark the current progress phase and update the progress display |\n| `log(message)` | Emit a progress log line |\n| `workflow(name, args)` | Run a nested sub-workflow, one level only |\n\n`pipeline` should be the default. Each item independently crosses every stage. Item A may reach stage three while item B is still in stage one. Use the `parallel` barrier only when the next stage truly requires every result from the previous stage. A barrier waits for the slowest task, so do not add one without need.\n\n```python\nasync def pipeline(self, items, *stages):\n async def run_item(item, idx):\n value = item\n for stage in stages: # Each item independently completes every stage\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n```\n\n## Structured Output: Do Not Let Subagents Return Essays\n\n`agent({schema})` requires a subagent to return a JSON object matching the schema, internally through one structured-output call. The runtime validates the result and retries once if it does not match. Downstream code receives a regular object instead of a long essay that must be parsed again.\n\ns05 warned that tool arguments cannot be trusted completely. This is the same lesson in reverse: subagent output cannot be trusted completely either. Validate at the orchestration boundary, give one retry, and keep uncertainty out of the rest of the flow.\n\n```python\nresult = self.runner.run(prompt, schema, label)\nif schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # Retry once with a reminder, then fail\n result = self.runner.run(prompt + \"\\n\\nReturn valid JSON.\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) returned invalid output: {err}\")\n```\n\n## Background Tasks and Progress Events\n\n`LocalWorkflowTask` maintains status and token usage and emits an SDK-style event stream: `task_started` → a sequence of `task_progress` events containing phase changes, subagent starts, and log batches → one final `task_notification` reporting completion, failure, or stop, plus output files, token count, tool calls, and elapsed time.\n\nThe main session treats these as ordinary events. Only the final completion notification re-enters the main loop.\n\n```python\nclass LocalWorkflowTask:\n def progress_event(self, ptype, **data): # Phase/subagent/log\n self.progress.append({\"type\": ptype, **data})\n print(f\" progress {ptype} ...\")\n```\n\n## Storage: Snapshot + Journal for Resuming after Interruptions\n\nThe minimal runtime stores each run under `s21_workflow_runtime/.runtime/`: a `.json` snapshot, `.output.json` output, and `.journal.jsonl` journal. A production harness may also persist the workflow script and subagent transcripts, but the key requirement is that the snapshot and journal share a stable `runId`.\n\nThe journal is the core of checkpointed resume. It records every `agent()` result one line at a time:\n\n```python\nclass WorkflowJournal:\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n```\n\n## Resume: Continue by runId and Reuse Everything Unchanged\n\nCalling the workflow again with `resume_from_run_id` reruns the script, but every `agent()` computes a deterministic semantic key. If that key is present in the journal, it returns the cached result without executing again. Every unchanged call hits the cache; only a changed call and the downstream steps that depend on it actually rerun.\n\nThe key detail is that keys cannot depend on concurrency order. Agents in `parallel` and `pipeline` finish in nondeterministic order. If \"the nth completion\" became the key, cache entries would map to the wrong calls on the next run. A key therefore uses a stable hash of call content, including type, label, prompt, and schema, rather than a shared counter:\n\n```python\ndef key(self, kind, label, prompt, schema):\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n# Inside agent():\ncached = self.journal.cached(key)\nif cached is not MISS:\n self.task.progress_event(\"workflow_agent\", label=label, status=\"cached\")\n return cached\n```\n\n## Determinism: Reproducibility Makes Resume Meaningful\n\nResume works only if the workflow is reproducible. The minimal Python runtime uses stable hashes and a deterministic mock runner, so the same workflow plus the same arguments produces the same keys. A production harness should also isolate workflow code and remove uncontrolled clocks, randomness, filesystem access, and other sources of nondeterminism.\n\n## See It Run\n\nThe sample `review-changes` workflow uses `pipeline` to send each review dimension independently through audit → verify. An `agent()` with a schema finds issues during audit. During verification, `parallel()` dispatches a separate adversarial subagent for every finding. Only confirmed issues remain, sorted by severity.\n\n```python\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n\n async def audit(_v, dimension, _i):\n out = await ctx.agent(f\"Inspect the changed code for {dimension} issues\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _i):\n ctx.phase(\"Verify\")\n verdicts = await ctx.parallel([ # Verify every finding independently\n (lambda f=f: ctx.agent(f\"Adversarially verify whether this issue is real: {f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\"))\n for f in audited[\"findings\"]])\n return {\"dimension\": dimension,\n \"confirmed\": [f for f, v in zip(audited[\"findings\"], verdicts) if v and v[\"isReal\"]]}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n ...\n```\n\n## Changes from s20\n\n| | s20 Comprehensive Agent | s21 Workflow Runtime |\n|--|-----------|---------------------|\n| Loop | One model-driven loop | Main loop unchanged; deterministic orchestration added above it |\n| Who decides the next step | Model decides each round | Script declares the orchestration in advance |\n| Multiple agents | One-shot s06 subagents | Scripted, reproducible, recoverable bulk orchestration |\n| New mechanisms | — | Script DSL, background tasks, progress events, journal/resume, structured output, deterministic VM |\n\ns21 does not replace the main loop. It exposes `Workflow` at the tool layer and starts a local workflow runtime behind it: one workflow deterministically drives N agent loops. An s06 subagent is dispatched once at the model's discretion; s21 turns orchestration into a replayable script.\n\n## Try It\n\n```bash\npython s21_workflow_runtime/code.py # Start review-changes and watch the event stream\npython s21_workflow_runtime/code.py resume # Resume by the last runId; every agent() hits the journal cache\n```\n\nWatch one launch produce `async_launched`, followed by background phase changes and subagent progress, then `task_notification`; the result is stored on the task object. A resumed run reports `agents=0 tokens=0` because every call hits the cache, and its result is byte-for-byte identical.\n\n## Next\n\nOrchestration adds a layer above agent capabilities: the main loop handles individual operations, while a script manages the whole team's flow. Once work becomes a deterministic, recoverable script, the model changes from the round-by-round driver into an execution unit scheduled by that script. The same `agent()` can be invoked ad hoc by the model in the main loop or orchestrated in bulk inside a workflow.\n\nNext: [s22 Goal Loop](/en/s22) — Orchestration fans work out and leaves the main loop. The next chapter moves in the opposite direction: a goal pulls control back into the main loop and refuses to let the turn end until the objective is achieved.\n\n\n" + "title": "s21: Goal Loop — The Goal Decides When to Stop, Not the Model", + "content": "# s21: Goal Loop — The Goal Decides When to Stop, Not the Model\n\ns01 → ... → s19 → s20 → `s21`\n\n> *\"A turn ends only when the goal condition is satisfied, not merely when the model says stop\"* — `/goal` adds a gate at the end of every main-loop turn. An independent evaluator checks whether trusted evidence is sufficient; if not, it pushes the model into another round.\n>\n> **Harness layer**: Goal closure — a program-controlled completion gate at the end of each turn.\n\n---\n\nFrom s01 through s20, how does a conversation turn end? When the model stops emitting `tool_use`, the loop simply executes `return`. That is fine for one-shot work: finish and stop.\n\nSome objectives, however, must be carried through to completion: \"get the tests passing\" or \"do not stop until the deployment succeeds.\" Two problems appear often. The model does half the work, decides it is close enough, and stops. Worse, it says `tests passed` and tries to declare victory. The requirement is simple: the model cannot decide by itself whether the turn may end. An explicit condition must be evaluated against concrete evidence.\n\nThis thread was present from the first chapter. s01 explained that exiting the loop is a model decision. s04's Stop hook gave the program veto power for the first time. This chapter turns that veto into a complete loop with three indispensable parts: condition, evidence, and budget.\n\n## /goal: Add a Gate at the End of Every Turn\n\nEntering `/goal ` sets a session-scoped stopping condition. The program stores it as the active goal. After each turn, an evaluator checks whether trusted evidence in the transcript satisfies the condition. If evidence is insufficient, the gate blocks the attempted stop and queues a \"keep working\" prompt for the next round. If it is sufficient, the goal is cleared and marked complete.\n\n![Goal Loop Overview](/course-assets/s21_goal_loop/goal-loop-overview.svg)\n\nCompared with the s01 loop, there is only one additional decision: when the model wants to stop, it must first pass the goal gate.\n\n```python\n# s01: stop when the model says stop\nif not has_tool_use(response):\n return\n# s21: want to stop? Pass the goal gate first\nif not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # Not achieved -> push back for another round\n return # Achieved / over budget / no goal -> really stop\n```\n\nThe program controls this gate. It is not the model restraining itself. The model does not even know the gate exists; it simply receives another round of input and continues working.\n\n## Setting a Goal: Evidence Starts after the Command\n\n`set_goal` stores an active goal containing the objective text, a maximum-turn budget, counters, and `start_index`, the beginning of the evidence window. It uses the transcript's current length, placing the `/goal` command itself outside the window. This is the first defense: a command cannot prove its own completion.\n\n```python\ndef set_goal(self, objective, max_turns=20):\n self.active = {\n \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), # Evidence starts here; the command is outside the window\n \"max_turns\": max_turns, \"checks\": 0, \"continuation_turns\": 0,\n }\n```\n\n## The Evaluator: Trust Concrete Evidence Only\n\nThis is the core of the entire mechanism. The evaluator does not inspect the whole conversation. It sees only messages inside the evidence window that come from trusted sources. Three filters keep every form of \"I said it was done, so it must be done\" outside:\n\n```python\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\ndef evidence_text(self):\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\": # 1 Slash commands are not evidence\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"): # 2 /goal command text is not evidence\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS: # 3 Trust only approved origins\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n```\n\nThe effect is clear. The same sentence, `tests passed`, does not count when typed by you, but does count when delivered by a background task notification. The model cannot bluff its way out by saying \"I finished.\" This is the final appearance of the trust boundary repeated throughout the course. s15 said protocols rely on fields, not interpretation. s18 said annotations are claims and claims may be false. s21 says completion evidence is trusted by origin, not by content alone.\n\n`goal_satisfied()` uses deterministic keyword matching so the example stays offline and reproducible. Keeping evaluation separate from execution preserves the trusted evidence boundary.\n\n## Three Gate States: Completed, Continuing, or Over Budget\n\n`evaluate_after_turn` runs after every turn and returns one of three results. If the condition is satisfied, it clears the goal as completed. If the condition is not satisfied and budget remains, it queues a \"keep working\" prompt and permits another round as continuing. If the budget is exhausted, it stops blocking and marks the goal blocked, preventing an impossible goal from burning money forever.\n\n```python\ndef evaluate_after_turn(self):\n g = self.active\n g[\"checks\"] += 1\n if self.goal_satisfied():\n g[\"status\"] = \"completed\"; self.active = None\n return \"completed\" # Achieved -> clear the goal\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=\"Keep working. Do not treat this reminder as completion evidence.\",\n origin={\"kind\": \"active-goal\"})\n return \"continuing\" # Not achieved -> queue a prompt for the next round\n g[\"status\"] = \"blocked\"; self.active = None\n return \"blocked\" # Over budget -> release the gate\n```\n\nThe continuation prompt explicitly says not to treat itself as evidence, and the evidence filter excludes it. That completes the three layers against false positives: the command does not count, the reminder does not count, and ordinary conversation does not count. The budget follows the old rule from s11: every automatic retry mechanism needs a limit. Otherwise, a goal that can never be satisfied becomes a perpetual money-burning machine.\n\n## Keep Continuation Prompts Separate from External Asynchronous Messages\n\nContinuation prompts enter the same `CommandQueue`, but they are not consumed in the same way as external asynchronous events such as task-completion notifications and monitor lines. `dequeue` has a switch, and consumption of the external inbox skips goal continuations by default.\n\n```python\ndef dequeue(self, include_goal_continuations=True):\n ...\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n```\n\nWhy separate them? If one consumer drains continuation prompts together with external notifications, a reminder can be mistaken for new evidence before the background result arrives. With the paths separated, goal progression is an explicit step and cannot be carried along accidentally by asynchronous events.\n\n## See It Run\n\n`code.py` demonstrates `/goal until tests passed and deploy green`. With no trusted evidence after goal creation, the gate pushes it back round after round. Typing `tests passed` directly still does not count because the origin is untrusted. Only after a background task sends a `task-notification` does the evidence satisfy the goal. A second small goal with `max_turns=2` demonstrates the over-budget path.\n\n```python\ns.submit(\"/goal until tests passed and deploy green\") # Set the goal; evidence begins after this command\ns.submit(\"tests passed, trust me\") # Ordinary text -> not completion evidence\ns.deliver_host_event(\"tests passed; deploy green\",\n source=\"task-notification\") # Trusted host event -> complete\n```\n\n`submit()` accepts only ordinary user text. Trusted labels enter through the separate host-event channel, whose source is allowlisted by the harness; user or model text cannot attach its own `task-notification` label.\n\n## Changes from s20\n\n| | s20 Workflow Runtime | s21 Goal Loop |\n|--|---------------------|---------------|\n| Trigger | Script-controlled orchestration outside the main loop | Condition-controlled continuation pulled back into the main loop |\n| Attachment point | Tool layer: one `Workflow` tool | End of turn: a completion gate |\n| Who decides when to stop | The script finishes | Goal condition evaluated against trusted evidence |\n| New mechanisms | Script DSL, background tasks, journal/resume, structured output | Goal gate, evidence trust boundary, separate continuation path, budget |\n\ns20 sends script-defined orchestration away from the main loop. s21 applies an opposite force that pulls control back: if the goal is not achieved, the turn is not finished. Neither changes the `while` loop from s01; each constrains it from a different side.\n\n## Try It\n\n```bash\npython s21_goal_loop/code.py # /goal until tests pass + deploy green; watch the gate decide\n```\n\nAfter setting a goal, watch every turn produce `goal_evaluated`. Ordinary text yields `satisfied=False`; the same content from a `task-notification` origin yields `satisfied=True`; exhausted budget produces `goal_blocked`. The same `tests passed` sentence has opposite results depending on its origin. That is why an empty claim cannot fool `/goal`.\n\n## Next\n\n`/goal` is one kind of trigger that pulls control back into the main loop: condition control. It pairs naturally with s20's orchestration outside the main loop, one dispatching work outward and the other pulling control inward. Beyond them are time-controlled re-entry through `/loop` and cron, and event-controlled re-entry through `Monitor`; all share the same task and notification foundation. But the essential gate is already here: **the model's words do not decide whether to stop. The goal must judge trusted evidence.**\n\n\n" }, { "version": "s21", "locale": "zh", - "title": "s21: Workflow Runtime — 模型决定单步,脚本决定编排", - "content": "# s21: Workflow Runtime — 模型决定单步,脚本决定编排\n\ns01 → ... → s19 → s20 → `s21` → [s22](/zh/s22)\n\n> *\"一次 tool_use,后台跑完一整套编排\"* — `Workflow` 工具启动一个确定、可恢复的脚本运行时,批量派出去一堆子 agent。\n>\n> **Harness 层**: 编排 — 在单 agent 循环之上,加一层确定的多 agent 脚本运行时。\n\n`code.py` 为了让演示保持确定,会先发出 `async_launched`,随后在同一进程里等待执行完成。这样不用启动常驻后台服务,也能看清生命周期和 journal。\n\n---\n\n从 s01 到 s20,我们的循环一直是模型驱动、一步一步来的:每一轮模型挑一个工具,结果塞回 `messages[]`,再来一轮。开放式任务这么干最合适,下一步做什么,让模型看着上下文临场决定就好。\n\n但有些活,你需要的是确定地指挥一群 agent 干活。比如审一个大改动:十个维度并行找问题 → 每条发现各自派一个 agent 做对抗性验证 → 结果汇总去重 → 按严重度排序。这种流程的形状是固定的,你要的其实是三样东西:\n\n- **并行**,别一个一个串着等;\n- **确定**,同样的输入跑出来同样的结果结构;\n- **可恢复**,跑到一半断了,已经做完的部分别从头再来。\n\n让模型在主循环里一步一步驱动这套流程,又慢、结果又不确定,断了还得从头跑。这时候你要的不是\"再聊一轮\",而是把这套编排直接写成代码。\n\n## 计划写在代码里,不是靠聊天一轮轮凑\n\n在 harness 的工具池里加入一个 `Workflow` 工具。用户或模型给它一段脚本,脚本用 `agent() / parallel() / pipeline() / phase()` 这几个简单的原语,把编排写成确定的代码。\n\n主循环这边只看到一次 `tool_use`,立刻拿到\"已在后台启动\"的返回:真正的执行在后台运行时里推进,实时上报进度,所有过程都写到磁盘的 journal 文件里。脚本里的中间结果存在变量里,不会塞进对话历史占地方。下次用 `resume_from_run_id` 重启时,没改过的 `agent()` 直接命中 journal 缓存,直接用之前的结果,断点续跑。\n\n![Workflow Runtime 总览](/course-assets/s21_workflow_runtime/workflow-runtime-overview.svg)\n\n```python\nSAMPLE_META = {\"name\": \"review-changes\", \"description\": \"审查代码改动\", \"phases\": [\"Review\", \"Verify\"]}\n\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n results = await ctx.pipeline(DIMENSIONS, audit, verify) # 每个维度独立走 审计 → 验证\n confirmed = [f for r in results if r for f in r[\"confirmed\"]]\n ctx.log(f\"确认了 {len(confirmed)} 个真实问题\")\n return {\"confirmed\": confirmed}\n```\n\n## Workflow 工具:后台启动,主循环只看到一次调用\n\n`Workflow` 就在主 agent 的工具池里。用户可以要求运行一个保存好的 workflow,模型也可以在任务匹配已知编排时选择这个工具;两种情况最终都只发出一次 `Workflow(...)` 工具调用。\n\n工具收到后会解析参数、校验 meta 信息、过权限检查、注册一个本地 workflow 任务,然后立刻返回\"已异步启动\"。主循环不阻塞,该干嘛干嘛;workflow 自己在后台跑。这其实就是 s13 后台任务那套\"凭条模式\"的放大版:先给你个取件条,结果好了再通知你。\n\n```python\nclass WorkflowTool:\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n run_id = resume_from_run_id or create_run_id(meta)\n task = LocalWorkflowTask(create_task_id(run_id), run_id, meta)\n task.event(\"async_launched\", runId=run_id, taskId=task.task_id) # 立刻返回\n ... # 剩下的后台慢慢跑\n```\n\n## Workflow 元数据:启动前先校验\n\n每个 workflow 都要注册一个元数据对象,包含 `name`、`description` 和可选的 `phases`。运行时会在执行任何 workflow 代码之前校验它:`name` 和 `description` 用来标识任务,`phases` 给进度条分组命名。\n\n不对的输入直接抛 `WorkflowInputError`,注册的时候就拦住——这和 s14 校验 cron 表达式是一个思路:坏脚本别让它跑到执行的时候才炸。\n\n教学运行时会把 `meta.name` 用在本地产物文件名中,因此还要求它是 1-64 个字符的安全 slug,只能包含字母、数字、`.`、`_`、`-`。\n\n```python\ndef validate_meta(meta):\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta 必须是对象字面量\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta 必须包含 name 和 description\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\"meta.name 必须是 1-64 字符的安全 slug\")\n if \"phases\" in meta and (\n not isinstance(meta[\"phases\"], list)\n or not all(isinstance(p, str) and p for p in meta[\"phases\"])\n ):\n raise WorkflowInputError(\"meta.phases 必须包含非空字符串\")\n return meta\n```\n\n## 编排原语:就这几个,够写所有流程\n\n脚本跑在一个独立的上下文里,能用的全局变量就这几个编排原语。脚本本身不直接读写文件、不跑 shell,真正的代码操作都由派出去的子 agent 用它们自己的工具权限完成。这些原语都是 `ExecutionState` 上的方法:\n\n| 原语 | 作用 |\n|------|------|\n| `agent(prompt, {schema, label, phase})` | 派一个子 agent 干活 |\n| `parallel(thunks)` | **等齐屏障**:所有任务并行跑完,一起等结果回来 |\n| `pipeline(items, *stages)` | 每个 item 分阶段跑,**不等齐**,跑完一个往下走一个 |\n| `phase(title)` | 标记当前进度阶段(更新进度条) |\n| `log(message)` | 打一行进度日志 |\n| `workflow(name, args)` | 嵌套子工作流(只支持一层) |\n\n`pipeline` 是你默认该用的:每个 item 独立穿过所有 stage,item A 跑到第 3 阶段的时候,item B 可能还在第 1 阶段;只有真的需要\"拿到上一阶段所有结果才能往下走\"的时候,才用 `parallel` 这个屏障。屏障的代价是等最慢的那个任务,没必要就别立。\n\n```python\nasync def pipeline(self, items, *stages):\n async def run_item(item, idx):\n value = item\n for stage in stages: # 每个 item 独立跑完所有 stage\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n```\n\n## 结构化输出:别让子 agent 回来写散文\n\n`agent({schema})` 会强制子 agent 返回一个匹配 schema 的 JSON 对象(内部通过一次结构化输出调用实现),运行时会按 schema 校验结果,不对就重试一次。这样下游代码拿到的是规整的对象,不是需要再解析的一大段散文。\n\ns05 就说过,工具的参数不能全信;这里是同一个道理反过来:子 agent 的输出也不能全信。加一层校验,不对就给一次机会重试,把不确定性挡在编排层外面。\n\n```python\nresult = self.runner.run(prompt, schema, label)\nif schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # 提醒一次重试,再不对就报错\n result = self.runner.run(prompt + \"\\n\\n返回合法的 JSON。\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) 输出不合法: {err}\")\n```\n\n## 后台任务和进度事件\n\n`LocalWorkflowTask` 维护状态和 token 用量,向外发一条 SDK 风格的事件流:`task_started` → 一串 `task_progress`(包含阶段切换、子 agent 启动、日志输出这些批次)→ 最后一个 `task_notification`(完成/失败/停止,带输出文件、token 数、工具调用数、耗时)。\n\n主会话把这些当普通事件处理;只有最终的完成通知会重新进入主循环。\n\n```python\nclass LocalWorkflowTask:\n def progress_event(self, ptype, **data): # 阶段/子agent/日志\n self.progress.append({\"type\": ptype, **data})\n print(f\" 进度 {ptype} ...\")\n```\n\n## 存储:快照 + journal,断了能续\n\n这个最小运行时把每次运行的数据存在 `s21_workflow_runtime/.runtime/`:快照 `.json`、输出 `.output.json` 和 journal `.journal.jsonl`。生产级 harness 还可以保存 workflow 脚本与子 agent 对话记录,但关键约束是快照和 journal 必须共享稳定的 `runId`。\n\njournal 是断点续跑的核心,它一条一条记下来每个 `agent()` 的结果:\n\n```python\nclass WorkflowJournal:\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n```\n\n## resume:用 runId 续跑,没改的直接用缓存\n\n带着 `resume_from_run_id` 再次调用 workflow 时,脚本会重新执行,但每个 `agent()` 都会计算一个确定的语义 key:key 在 journal 里有记录,就直接返回缓存结果;只有改过的调用以及依赖它的后续步骤才会真的运行。\n\n这里有个关键点:key 不能依赖并发顺序。`parallel` 和 `pipeline` 里 agent 完成的顺序是不确定的,用\"第几个完成\"当 key,两次跑缓存就对错位了。所以 key 是根据调用内容(类型、标签、prompt、schema)算的稳定哈希,不是一个会竞争的计数器:\n\n```python\ndef key(self, kind, label, prompt, schema):\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n# agent() 内部:\ncached = self.journal.cached(key)\nif cached is not MISS:\n self.task.progress_event(\"workflow_agent\", label=label, status=\"cached\")\n return cached\n```\n\n## 确定性:能复现,续跑才有意义\n\n续跑要能工作,workflow 首先得可复现。这个最小 Python 运行时使用稳定哈希和确定性的 mock runner,让同一份 workflow + 同样的参数产生同样的 key。生产级 harness 还应该隔离 workflow 代码,并移除不受控的时钟、随机数、文件系统访问等不确定来源。\n\n## 跑起来看看\n\n示例 workflow `review-changes`:用 `pipeline` 让每个审查维度独立走\"审计 → 验证\"流程。审计用一个带 schema 的 `agent()` 找问题,验证用 `parallel()` 给每条发现各派一个对抗性验证的子 agent,最后只留确认真实的问题,按严重度排序。\n\n```python\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n\n async def audit(_v, dimension, _i):\n out = await ctx.agent(f\"检查改动的代码里有没有{dimension}相关的问题\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _i):\n ctx.phase(\"Verify\")\n verdicts = await ctx.parallel([ # 每条发现独立做对抗性验证\n (lambda f=f: ctx.agent(f\"请对抗性验证这个问题是不是真的:{f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\"))\n for f in audited[\"findings\"]])\n return {\"dimension\": dimension,\n \"confirmed\": [f for f, v in zip(audited[\"findings\"], verdicts) if v and v[\"isReal\"]]}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n ...\n```\n\n## 相对 s20 的变更\n\n| | s20 综合体 | s21 Workflow Runtime |\n|--|-----------|---------------------|\n| 循环 | 单个、模型驱动 | 主循环不变;上面加一层确定的编排 |\n| 谁决定下一步 | 模型逐轮决定 | 脚本预先写好编排流程 |\n| 多 agent | s06 子 agent,一次性派出去 | 脚本化、可复现、可恢复的批量编排 |\n| 新增机制 | — | 脚本 DSL、后台任务、进度事件、journal/续跑、结构化输出、确定性 VM |\n\ns21 不替换主循环,它只是在工具层暴露了 `Workflow`,背后启动一个本地 workflow 运行时:一个 workflow 确定地驱动 N 个 agent 循环。s06 的子 agent 是模型临场派一次;s21 是把编排写成可以重放的脚本。\n\n## 试一下\n\n```bash\npython s21_workflow_runtime/code.py # 启动 review-changes,看事件流\npython s21_workflow_runtime/code.py resume # 用上次的 runId 续跑,每个 agent() 都命中 journal 缓存\n```\n\n观察:一次启动 → `async_launched` → 后台阶段切换/子agent进度推进 → `task_notification`;结果存在任务对象上。续跑的时候会显示 `agents=0 tokens=0`(全部命中缓存),结果和上次一字不差。\n\n## 接下来\n\n编排是在 agent 能力之上又加了一层:主循环管单步操作,脚本管整支队伍的流程。把工作写成确定、可恢复的脚本,模型就从\"逐轮驱动者\"变成了\"被脚本调度的执行单元\"。同一个 `agent()`,既能在主循环里被模型临场调用,也能在 workflow 里被脚本批量编排。\n\n下一章:[s22 Goal Loop](/zh/s22) — 编排是把工作扇出去、脱离主循环;下一章反过来,一个目标把控制权重拉回主循环,没达成就不让这一轮结束。\n\n\n" + "title": "s21: Goal Loop — 什么时候停,目标说了算,不是模型说了算", + "content": "# s21: Goal Loop — 什么时候停,目标说了算,不是模型说了算\n\ns01 → ... → s19 → s20 → `s21`\n\n> *\"一轮能不能结束,看目标条件满不满足,不是模型说停就停\"* — `/goal` 在主循环每轮收尾的地方加一道闸门:每轮结束后,一个独立的判断器看可信证据够不够,不够就把模型推回去再来一轮。\n>\n> **Harness 层**: 目标闭环 — 在轮次收尾处,加一道程序控制的完成闸门。\n\n---\n\n从 s01 到 s20,一轮对话怎么结束?模型不再发 `tool_use`,循环就直接 `return` 了。一次性任务这么干没问题,做完就停。\n\n但有些目标你得盯着它做到底:\"把测试跑过\"、\"部署成功了再说\"。这时候经常出两种问题:模型做了一半觉得差不多了,自己就停了;更过分的是,它嘴上说一句 `tests passed` 就想收工。你要的其实很简单:这一轮能不能结束,不能模型自己说了算,得有个明确的条件,对着实打实的证据来判断。\n\n这条线其实从第一课就埋着了。s01 说过,退出循环本来是模型的一个决定;s04 的 Stop hook 第一次给了程序否决权。这一课把那个否决权做成完整的闭环:条件、证据、预算,三样缺一不可。\n\n## /goal:每轮收尾加一道闸门\n\n输入 `/goal <条件>` 就设了一个会话级的停止条件。程序把它存成当前活跃目标,每轮结束后,判断器检查对话记录里的可信证据够不够满足条件。不够,闸门就把这次结束拦住,塞一条\"继续干\"的提示进下一轮;够了,就清除目标,标记完成。\n\n![Goal Loop 总览](/course-assets/s21_goal_loop/goal-loop-overview.svg)\n\n和 s01 的循环比,只多了一道判断,模型想停的时候先过目标这关:\n\n```python\n# s01:模型说停就停\nif not has_tool_use(response):\n return\n# s21:想停?先过目标闸门\nif not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # 没达成 -> 推回去再来一轮\n return # 达成/超预算/没目标 -> 真停\n```\n\n这道闸门是程序自己控制的。不是模型自己约束自己,模型甚至不知道有这么一道闸门,它只是收到了下一轮的输入,接着干就是了。\n\n## 设目标:证据从命令之后开始算\n\n`set_goal` 会存一个活跃目标:目标文本、最大轮数预算、计数器,还有 `start_index`——也就是证据窗口的起点。它取当前对话记录的长度,所以 `/goal` 这行命令本身在窗口外面。这是第一道防线:命令自己不能证明自己完成了。\n\n```python\ndef set_goal(self, objective, max_turns=20):\n self.active = {\n \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), # 证据窗口从这里开始;命令本身在窗口外\n \"max_turns\": max_turns, \"checks\": 0, \"continuation_turns\": 0,\n }\n```\n\n## 判断器:只信实打实的证据\n\n这是整个机制最核心的地方。判断器不看整段对话,只看证据窗口里来自可信来源的消息。三层过滤,把\"嘴上说完成了但不算数\"的内容全挡在外面:\n\n```python\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\ndef evidence_text(self):\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\": # 1 斜杠命令本身不算\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"): # 2 /goal 命令文本不算\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS: # 3 只信可信来源\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n```\n\n效果很明显:同样一句 `tests passed`,你打字说的不算,后台任务通知带回来的才算。模型糊弄不过去,它没法靠自己说一句\"我做完了\"就把目标判成完成。这是全课程反复出现的那条信任边界的最后一次登场:s15 说协议靠字段不靠理解,s18 说注解是申报、申报可以撒谎,s21 说完成证据只看来源不看内容。\n\n`goal_satisfied()` 使用确定的关键词匹配,让示例保持离线和可复现。把判断与执行分开,才能守住可信证据边界。\n\n## 闸门三态:完成/继续/超预算\n\n`evaluate_after_turn` 每轮跑一次,三种结果:满足条件就清除目标(completed);没满足而且预算还没花完,就往队列塞一条\"继续干\"的提示,放行下一轮(continuing);预算花完就停(blocked),别让一个永远判不出来的目标无限烧钱。\n\n```python\ndef evaluate_after_turn(self):\n g = self.active\n g[\"checks\"] += 1\n if self.goal_satisfied():\n g[\"status\"] = \"completed\"; self.active = None\n return \"completed\" # 达成 -> 清除目标\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=\"继续干活,别把这条提醒当成完成证据。\",\n origin={\"kind\": \"active-goal\"})\n return \"continuing\" # 没达成 -> 塞提示,下一轮\n g[\"status\"] = \"blocked\"; self.active = None\n return \"blocked\" # 超预算 -> 放行,不再拦\n```\n\n那条\"继续干\"的提示里特意写了\"别把这条提醒当成完成证据\",连提醒本身都被排除在证据之外。三层防误判就齐了:命令文本不算、提醒文本不算、普通聊天文本不算。预算则是 s11 教过的老规矩:任何自动重试的机制都得有上限,不然一个永远判不满足的目标就是个烧钱的永动机。\n\n## 继续提示和外部异步消息分开走\n\n继续提示进的是同一个 `CommandQueue`,但它和外部异步事件(任务完成通知、监控行)不是同一种消费方式。`dequeue` 带个开关:消费外部收件箱的时候,默认跳过目标的继续提示。\n\n```python\ndef dequeue(self, include_goal_continuations=True):\n ...\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n```\n\n为什么要分开?如果同一个消费者把继续提示和外部通知一起取走,后台结果还没到,提醒文本就可能被误当成新证据。分开之后,目标的推进是显式的一步,不会被异步事件带着走。\n\n## 跑起来看看\n\n`code.py` 演示了一个 `/goal until tests passed and deploy green`:设了目标之后没有可信证据,闸门一轮轮把它推回去;你直接打 `tests passed` 也不算(来源不可信);直到后台任务发来 `task-notification`,证据到位,才标记完成。还加了一个 `max_turns=2` 的小目标演示超预算拦截。\n\n```python\ns.submit(\"/goal until tests passed and deploy green\") # 设目标,窗口在命令之后\ns.submit(\"tests passed, trust me\") # 普通文本 -> 不算完成\ns.deliver_host_event(\"tests passed; deploy green\",\n source=\"task-notification\") # 可信宿主事件 -> 完成\n```\n\n`submit()` 只接受普通用户文本。可信标签必须走独立的宿主事件通道,来源由 harness 白名单校验;用户或模型文本不能给自己贴上 `task-notification` 标签。\n\n## 相对 s20 的变更\n\n| | s20 Workflow Runtime | s21 Goal Loop |\n|--|---------------------|---------------|\n| 触发方式 | 脚本控制的编排(脱离主循环) | 条件控制的继续(拉回主循环) |\n| 加在哪 | 工具层:一个 `Workflow` 工具 | 轮次收尾:一道完成闸门 |\n| 谁决定停 | 脚本跑完就停 | 目标条件对着可信证据判 |\n| 新增机制 | 脚本 DSL、后台任务、journal/续跑、结构化输出 | 目标闸门、证据信任边界、继续提示分流、预算 |\n\ns20 是把编排写成脚本、派出去脱离主循环;s21 反过来,是一股力量把控制权重拉回主循环:目标没达成,这一轮就不算结束。两个都不改 s01 那个 `while` 循环,只是从两头给它加约束。\n\n## 试一下\n\n```bash\npython s21_goal_loop/code.py # /goal until tests pass + deploy green,看闸门怎么判\n```\n\n观察:设了目标之后,每轮结束都有一条 `goal_evaluated`;普通文本判 `satisfied=False`,`task-notification` 来源判 `satisfied=True`;预算花完的时候出 `goal_blocked`。同样一句 `tests passed`,来源不同,结果完全相反。这就是 `/goal` 不会被一句空话糊弄的地方。\n\n## 接下来\n\n`/goal` 是\"拉回主循环\"的一种触发:条件控制。它和 s20 的\"脱离主循环\"正好成对,一个把工作派出去,一个把控制权拉回来。再往外,还有时间控制(`/loop`、cron)和事件控制(`Monitor`)的重入,它们共享同一套任务/通知基底;但闸门的核心已经在这里:**停不停,不是模型一句话说了算,得目标对着可信证据来判。**\n\n\n" }, { "version": "s21", "locale": "ja", - "title": "s21: Workflow Runtime — モデルが単一 step を決め、script が orchestration を決める", - "content": "# s21: Workflow Runtime — モデルが単一 step を決め、script が orchestration を決める\n\ns01 → ... → s19 → s20 → `s21` → [s22](/ja/s22)\n\n> *「1 回の tool_use で、バックグラウンドに一式の orchestration を走らせる」* — `Workflow` ツールが決定的で復元可能な script runtime を起動し、多数の subagent をまとめて送り出します。\n>\n> **Harness 層**: Orchestration — single-agent loop の上に、決定的な multi-agent script runtime を追加します。\n\n`code.py` は demo を決定的に保つため、`async_launched` を出した後、同じ process で完了を待ちます。常駐 background service を用意しなくても、lifecycle と journal を確認できます。\n\n---\n\ns01 から s20 まで、loop は常にモデル駆動で 1 step ずつ進みました。各ラウンドでモデルが 1 つのツールを選び、結果を `messages[]` へ入れ、次のラウンドへ進みます。open-ended なタスクには最適です。次に何をするかを、モデルが context を見てその場で決められます。\n\nしかし、複数の Agent を決定的に指揮したい仕事もあります。大きな変更の review を考えてください。10 の観点から並行して問題を探す → 各 finding へ別 Agent を送り adversarial verification を行う → 結果を集約して重複を除く → severity 順に並べる。この流れの形は固定されており、本当に必要なのは 3 つです。\n\n- **並行性**: 1 件ずつ順番に待たないこと。\n- **決定性**: 同じ入力から同じ結果構造が得られること。\n- **復元可能性**: 途中で止まっても、完了済みの部分を最初からやり直さないこと。\n\nこの流れをモデルに main loop で 1 ラウンドずつ動かさせると、遅く、結果は不確定で、中断すれば最初からです。ここで必要なのは「もう 1 turn 話す」ことではなく、orchestration をそのままコードにすることです。\n\n## 計画は chat のラウンドを重ねず、コードに書く\n\nharness の tool pool に `Workflow` ツールを追加します。ユーザーまたはモデルが渡す script は、`agent() / parallel() / pipeline() / phase()` という少数の primitive を使い、orchestration を決定的なコードとして表します。\n\nmain loop から見えるのは 1 回の `tool_use` だけで、すぐ「バックグラウンドで起動済み」という結果を受け取ります。本当の実行は background runtime で進み、進捗をリアルタイムに報告し、全過程をディスク上の journal へ記録します。script の中間結果は変数に保存され、会話履歴の場所を取りません。`resume_from_run_id` で再開すると、変更されていない `agent()` は journal cache に当たり、以前の結果を直接使って checkpoint から続行します。\n\n![Workflow Runtime Overview](/course-assets/s21_workflow_runtime/workflow-runtime-overview.svg)\n\n```python\nSAMPLE_META = {\"name\": \"review-changes\", \"description\": \"コード変更を review\", \"phases\": [\"Review\", \"Verify\"]}\n\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n results = await ctx.pipeline(DIMENSIONS, audit, verify) # 各 dimension が独立して audit → verify を通る\n confirmed = [f for r in results if r for f in r[\"confirmed\"]]\n ctx.log(f\"{len(confirmed)} 件の実在する問題を確認\")\n return {\"confirmed\": confirmed}\n```\n\n## Workflow ツール: バックグラウンド起動、main loop には 1 回の call だけ\n\n`Workflow` は main Agent の tool pool にあります。ユーザーが保存済み workflow の実行を求めるか、タスクが既知の orchestration に一致したときにモデルがこのツールを選びます。どちらも 1 回の `Workflow(...)` tool call になります。\n\nツールは argument を parse し、meta 情報を検証し、permission check を通し、local workflow task を登録すると、すぐ「非同期で起動済み」と返します。main loop は block せず別の仕事を続け、workflow は background で実行されます。これは s13 の引換券 pattern を拡大したものです。先に引換券を渡し、結果ができたら通知します。\n\n```python\nclass WorkflowTool:\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n run_id = resume_from_run_id or create_run_id(meta)\n task = LocalWorkflowTask(create_task_id(run_id), run_id, meta)\n task.event(\"async_launched\", runId=run_id, taskId=task.task_id) # すぐ return\n ... # 残りはバックグラウンドで進む\n```\n\n## Workflow metadata: 起動前に検証する\n\n各 workflow は `name`、`description`、任意の `phases` を持つ metadata object を登録します。runtime は workflow code を実行する前に検証します。`name` と `description` は task と UI の表示に使い、`phases` は progress bar の group 名を定義します。\n\n不正な入力はすぐ `WorkflowInputError` になり、登録時に止まります。s14 の cron 式検証と同じ考えです。不正な script が実行時まで進んでから壊れないようにします。\n\n教材 runtime は `meta.name` をローカル artifact のファイル名に使うため、英数字で始まり、英数字、`.`、`_`、`-` のみからなる 1-64 文字の安全な slug も要求する。\n\n```python\ndef validate_meta(meta):\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta は object literal でなければなりません\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta には name と description が必要です\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\"meta.name は安全な 1-64 文字の slug が必要です\")\n if \"phases\" in meta and (\n not isinstance(meta[\"phases\"], list)\n or not all(isinstance(p, str) and p for p in meta[\"phases\"])\n ):\n raise WorkflowInputError(\"meta.phases は空でない文字列だけを含む必要があります\")\n return meta\n```\n\n## Orchestration primitive: この少数だけで、すべての flow を書ける\n\nscript は独立した context で動き、global variable として使えるのは少数の orchestration primitive だけです。script 自身はファイルを直接読み書きせず、shell も実行しません。実際のコード操作は、派遣された subagent が自分の tool permission で行います。primitive はすべて `ExecutionState` の method です。\n\n| Primitive | 役割 |\n|------|------|\n| `agent(prompt, {schema, label, phase})` | 1 つの subagent を派遣 |\n| `parallel(thunks)` | **barrier**: すべての task を並行実行し、全結果が戻るまで待つ |\n| `pipeline(items, *stages)` | 各 item を **barrier なし**で stage ごとに実行し、終わった item から先へ進める |\n| `phase(title)` | 現在の progress phase を記録し、progress bar を更新 |\n| `log(message)` | progress log を 1 行出力 |\n| `workflow(name, args)` | nested sub-workflow(1 階層だけ) |\n\n既定では `pipeline` を使うべきです。各 item がすべての stage を独立して通り、item A が stage 3 にいる間、item B はまだ stage 1 かもしれません。次の stage へ進むために前 stage の全結果が本当に必要なときだけ、`parallel` barrier を使います。barrier は最も遅い task を待つため、不要なら置かないでください。\n\n```python\nasync def pipeline(self, items, *stages):\n async def run_item(item, idx):\n value = item\n for stage in stages: # 各 item がすべての stage を独立して完走\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n```\n\n## 構造化出力: Subagent に散文を返させない\n\n`agent({schema})` は、schema に一致する JSON object を subagent に要求します。内部では structured output call を 1 回使い、runtime が結果を schema で検証し、不一致なら 1 回 retry します。下流コードが受け取るのは規則的な object であり、再 parse が必要な長文ではありません。\n\ns05 では tool argument を全面的に信頼できないと説明しました。ここでは同じ教訓を逆向きに使います。subagent の出力も全面的には信頼できません。orchestration boundary で検証し、1 回 retry の機会を与え、不確実性を後続 flow の外へ止めます。\n\n```python\nresult = self.runner.run(prompt, schema, label)\nif schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # 1 回だけ注意して retry、それでも不正なら error\n result = self.runner.run(prompt + \"\\n\\n有効な JSON を返してください。\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) の出力が不正です: {err}\")\n```\n\n## Background task と progress event\n\n`LocalWorkflowTask` は status と token usage を管理し、SDK style の event stream を外へ出します。`task_started` → phase change、subagent start、log batch を含む一連の `task_progress` → 完了、失敗、停止に加え、output file、token 数、tool call 数、所要時間を含む最後の `task_notification` です。\n\nmain session は通常 event として処理し、最後の完了通知だけが main loop へ再び入ります。\n\n```python\nclass LocalWorkflowTask:\n def progress_event(self, ptype, **data): # phase/subagent/log\n self.progress.append({\"type\": ptype, **data})\n print(f\" progress {ptype} ...\")\n```\n\n## 保存: Snapshot + journal で中断から再開する\n\nこの最小 runtime は各 run を `s21_workflow_runtime/.runtime/` に保存します。`.json` snapshot、`.output.json` output、`.journal.jsonl` journal です。production harness では workflow script や subagent transcript も保存できますが、snapshot と journal が安定した `runId` を共有することが重要です。\n\njournal は checkpoint resume の中心で、各 `agent()` の結果を 1 行ずつ記録します。\n\n```python\nclass WorkflowJournal:\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n```\n\n## Resume: runId から続行し、変更のないものを再利用する\n\n`resume_from_run_id` を渡して workflow を再度呼ぶと script を再実行しますが、各 `agent()` は決定的な semantic key を計算します。journal に key があれば、再実行せず cached result を返します。変更された call と、それに依存する後続 step だけが本当に動きます。\n\nkey は concurrency の完了順に依存してはいけません。`parallel` と `pipeline` の Agent は不定の順番で完了します。「何番目に完了したか」を key にすると、次回の cache が別の call へ対応してしまいます。そのため key は競合する counter ではなく、call の内容、つまり type、label、prompt、schema の stable hash です。\n\n```python\ndef key(self, kind, label, prompt, schema):\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n# agent() の内部:\ncached = self.journal.cached(key)\nif cached is not MISS:\n self.task.progress_event(\"workflow_agent\", label=label, status=\"cached\")\n return cached\n```\n\n## 決定性: Resume に意味を持たせる再現性\n\nresume が動くには、workflow が再現可能でなければなりません。この最小 Python runtime は stable hash と決定的な mock runner を使い、同じ workflow + 同じ argument から同じ key を作ります。production harness では workflow code も隔離し、制御されていない clock、randomness、filesystem access などの非決定的な source を除くべきです。\n\n## 実際に動かす\n\nsample workflow `review-changes` は `pipeline` を使い、各 review dimension を独立して audit → verify へ通します。audit では schema 付き `agent()` が問題を探し、verify では `parallel()` が各 finding に別の adversarial verification subagent を送ります。実在すると確認された問題だけを残し、severity 順に並べます。\n\n```python\nasync def sample_workflow(ctx, args):\n ctx.phase(\"Review\")\n\n async def audit(_v, dimension, _i):\n out = await ctx.agent(f\"変更されたコードに {dimension} 関連の問題がないか確認してください\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _i):\n ctx.phase(\"Verify\")\n verdicts = await ctx.parallel([ # 各 finding を独立して verify\n (lambda f=f: ctx.agent(f\"この問題が実在するか adversarial に検証してください: {f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\"))\n for f in audited[\"findings\"]])\n return {\"dimension\": dimension,\n \"confirmed\": [f for f, v in zip(audited[\"findings\"], verdicts) if v and v[\"isReal\"]]}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n ...\n```\n\n## s20 からの変更点\n\n| | s20 Comprehensive Agent | s21 Workflow Runtime |\n|--|-----------|---------------------|\n| loop | 1 つ、モデル駆動 | main loop は不変。その上に決定的 orchestration を追加 |\n| 次の step を決めるもの | モデルが毎ラウンド判断 | script が orchestration flow を事前に定義 |\n| multi-agent | s06 subagent を一度だけ派遣 | script 化された、再現可能で復元可能な一括 orchestration |\n| 新しい仕組み | — | script DSL、background task、progress event、journal/resume、structured output、deterministic VM |\n\ns21 は main loop を置き換えません。tool layer に `Workflow` を公開し、背後で local workflow runtime を起動します。1 つの workflow が N 個の Agent loop を決定的に駆動します。s06 の subagent はモデルがその場で 1 回派遣し、s21 は orchestration を replay 可能な script にします。\n\n## 試してみる\n\n```bash\npython s21_workflow_runtime/code.py # review-changes を起動し、event stream を確認\npython s21_workflow_runtime/code.py resume # 前回の runId から resume。すべての agent() が journal cache に当たる\n```\n\n1 回の起動から `async_launched`、background の phase change と subagent progress、最後の `task_notification` までを観察してください。結果は task object に保存されます。resume 時はすべて cache hit するため `agents=0 tokens=0` と表示され、結果は前回と 1 byte も違いません。\n\n## 次へ\n\norchestration は Agent 能力の上にもう 1 層を加えます。main loop は個々の操作を管理し、script はチーム全体の flow を管理します。仕事が決定的で復元可能な script になると、モデルは「ラウンドごとの driver」から「script に schedule される実行 unit」へ変わります。同じ `agent()` を main loop でモデルがその場で呼ぶことも、workflow 内で script がまとめて編成することもできます。\n\n次へ: [s22 Goal Loop](/ja/s22) — Orchestration は仕事を fan-out し、main loop から離れます。次章は逆に、1 つの goal が control を main loop へ引き戻し、objective が達成されるまで turn の終了を認めません。\n\n\n" - }, - { - "version": "s22", - "locale": "en", - "title": "s22: Goal Loop — The Goal Decides When to Stop, Not the Model", - "content": "# s22: Goal Loop — The Goal Decides When to Stop, Not the Model\n\ns01 → ... → s20 → s21 → `s22`\n\n> *\"A turn ends only when the goal condition is satisfied, not merely when the model says stop\"* — `/goal` adds a gate at the end of every main-loop turn. An independent evaluator checks whether trusted evidence is sufficient; if not, it pushes the model into another round.\n>\n> **Harness layer**: Goal closure — a program-controlled completion gate at the end of each turn.\n\n---\n\nFrom s01 through s21, how does a conversation turn end? When the model stops emitting `tool_use`, the loop simply executes `return`. That is fine for one-shot work: finish and stop.\n\nSome objectives, however, must be carried through to completion: \"get the tests passing\" or \"do not stop until the deployment succeeds.\" Two problems appear often. The model does half the work, decides it is close enough, and stops. Worse, it says `tests passed` and tries to declare victory. The requirement is simple: the model cannot decide by itself whether the turn may end. An explicit condition must be evaluated against concrete evidence.\n\nThis thread was present from the first chapter. s01 explained that exiting the loop is a model decision. s04's Stop hook gave the program veto power for the first time. This chapter turns that veto into a complete loop with three indispensable parts: condition, evidence, and budget.\n\n## /goal: Add a Gate at the End of Every Turn\n\nEntering `/goal ` sets a session-scoped stopping condition. The program stores it as the active goal. After each turn, an evaluator checks whether trusted evidence in the transcript satisfies the condition. If evidence is insufficient, the gate blocks the attempted stop and queues a \"keep working\" prompt for the next round. If it is sufficient, the goal is cleared and marked complete.\n\n![Goal Loop Overview](/course-assets/s22_goal_loop/goal-loop-overview.svg)\n\nCompared with the s01 loop, there is only one additional decision: when the model wants to stop, it must first pass the goal gate.\n\n```python\n# s01: stop when the model says stop\nif not has_tool_use(response):\n return\n# s22: want to stop? Pass the goal gate first\nif not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # Not achieved -> push back for another round\n return # Achieved / over budget / no goal -> really stop\n```\n\nThe program controls this gate. It is not the model restraining itself. The model does not even know the gate exists; it simply receives another round of input and continues working.\n\n## Setting a Goal: Evidence Starts after the Command\n\n`set_goal` stores an active goal containing the objective text, a maximum-turn budget, counters, and `start_index`, the beginning of the evidence window. It uses the transcript's current length, placing the `/goal` command itself outside the window. This is the first defense: a command cannot prove its own completion.\n\n```python\ndef set_goal(self, objective, max_turns=20):\n self.active = {\n \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), # Evidence starts here; the command is outside the window\n \"max_turns\": max_turns, \"checks\": 0, \"continuation_turns\": 0,\n }\n```\n\n## The Evaluator: Trust Concrete Evidence Only\n\nThis is the core of the entire mechanism. The evaluator does not inspect the whole conversation. It sees only messages inside the evidence window that come from trusted sources. Three filters keep every form of \"I said it was done, so it must be done\" outside:\n\n```python\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\ndef evidence_text(self):\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\": # 1 Slash commands are not evidence\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"): # 2 /goal command text is not evidence\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS: # 3 Trust only approved origins\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n```\n\nThe effect is clear. The same sentence, `tests passed`, does not count when typed by you, but does count when delivered by a background task notification. The model cannot bluff its way out by saying \"I finished.\" This is the final appearance of the trust boundary repeated throughout the course. s16 said protocols rely on fields, not interpretation. s19 said annotations are claims and claims may be false. s22 says completion evidence is trusted by origin, not by content alone.\n\nThe minimal `goal_satisfied()` uses deterministic keyword matching so the demo stays offline and reproducible. A production harness can replace this policy with a separate lightweight evaluator model, while keeping the same trusted evidence boundary.\n\n## Three Gate States: Completed, Continuing, or Over Budget\n\n`evaluate_after_turn` runs after every turn and returns one of three results. If the condition is satisfied, it clears the goal as completed. If the condition is not satisfied and budget remains, it queues a \"keep working\" prompt and permits another round as continuing. If the budget is exhausted, it stops blocking and marks the goal blocked, preventing an impossible goal from burning money forever.\n\n```python\ndef evaluate_after_turn(self):\n g = self.active\n g[\"checks\"] += 1\n if self.goal_satisfied():\n g[\"status\"] = \"completed\"; self.active = None\n return \"completed\" # Achieved -> clear the goal\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=\"Keep working. Do not treat this reminder as completion evidence.\",\n origin={\"kind\": \"active-goal\"})\n return \"continuing\" # Not achieved -> queue a prompt for the next round\n g[\"status\"] = \"blocked\"; self.active = None\n return \"blocked\" # Over budget -> release the gate\n```\n\nThe continuation prompt explicitly says not to treat itself as evidence, and the evidence filter excludes it. That completes the three layers against false positives: the command does not count, the reminder does not count, and ordinary conversation does not count. The budget follows the old rule from s11: every automatic retry mechanism needs a limit. Otherwise, a goal that can never be satisfied becomes a perpetual money-burning machine.\n\n## Keep Continuation Prompts Separate from External Asynchronous Messages\n\nContinuation prompts enter the same `CommandQueue`, but they are not consumed in the same way as external asynchronous events such as task-completion notifications and monitor lines. `dequeue` has a switch, and consumption of the external inbox skips goal continuations by default.\n\n```python\ndef dequeue(self, include_goal_continuations=True):\n ...\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n```\n\nWhy separate them? If one consumer drains continuation prompts together with external notifications, a reminder can be mistaken for new evidence before the background result arrives. With the paths separated, goal progression is an explicit step and cannot be carried along accidentally by asynchronous events.\n\n## See It Run\n\n`code.py` demonstrates `/goal until tests passed and deploy green`. With no trusted evidence after goal creation, the gate pushes it back round after round. Typing `tests passed` directly still does not count because the origin is untrusted. Only after a background task sends a `task-notification` does the evidence satisfy the goal. A second small goal with `max_turns=2` demonstrates the over-budget path.\n\n```python\ns.submit(\"/goal until tests passed and deploy green\") # Set the goal; evidence begins after this command\ns.submit(\"tests passed, trust me\") # Ordinary text -> not completion evidence\ns.deliver_host_event(\"tests passed; deploy green\",\n source=\"task-notification\") # Trusted host event -> complete\n```\n\n`submit()` accepts only ordinary user text. Trusted labels enter through the separate host-event channel, whose source is allowlisted by the harness; user or model text cannot attach its own `task-notification` label.\n\n## Changes from s21\n\n| | s21 Workflow Runtime | s22 Goal Loop |\n|--|---------------------|---------------|\n| Trigger | Script-controlled orchestration outside the main loop | Condition-controlled continuation pulled back into the main loop |\n| Attachment point | Tool layer: one `Workflow` tool | End of turn: a completion gate |\n| Who decides when to stop | The script finishes | Goal condition evaluated against trusted evidence |\n| New mechanisms | Script DSL, background tasks, journal/resume, structured output | Goal gate, evidence trust boundary, separate continuation path, budget |\n\ns21 sends script-defined orchestration away from the main loop. s22 applies an opposite force that pulls control back: if the goal is not achieved, the turn is not finished. Neither changes the `while` loop from s01; each constrains it from a different side.\n\n## Try It\n\n```bash\npython s22_goal_loop/code.py # /goal until tests pass + deploy green; watch the gate decide\n```\n\nAfter setting a goal, watch every turn produce `goal_evaluated`. Ordinary text yields `satisfied=False`; the same content from a `task-notification` origin yields `satisfied=True`; exhausted budget produces `goal_blocked`. The same `tests passed` sentence has opposite results depending on its origin. That is why an empty claim cannot fool `/goal`.\n\n## Next\n\n`/goal` is one kind of trigger that pulls control back into the main loop: condition control. It pairs naturally with s21's orchestration outside the main loop, one dispatching work outward and the other pulling control inward. Beyond them are time-controlled re-entry through `/loop` and cron, and event-controlled re-entry through `Monitor`; all share the same task and notification foundation. But the essential gate is already here: **the model's words do not decide whether to stop. The goal must judge trusted evidence.**\n\n\n" - }, - { - "version": "s22", - "locale": "zh", - "title": "s22: Goal Loop — 什么时候停,目标说了算,不是模型说了算", - "content": "# s22: Goal Loop — 什么时候停,目标说了算,不是模型说了算\n\ns01 → ... → s20 → s21 → `s22`\n\n> *\"一轮能不能结束,看目标条件满不满足,不是模型说停就停\"* — `/goal` 在主循环每轮收尾的地方加一道闸门:每轮结束后,一个独立的判断器看可信证据够不够,不够就把模型推回去再来一轮。\n>\n> **Harness 层**: 目标闭环 — 在轮次收尾处,加一道程序控制的完成闸门。\n\n---\n\n从 s01 到 s21,一轮对话怎么结束?模型不再发 `tool_use`,循环就直接 `return` 了。一次性任务这么干没问题,做完就停。\n\n但有些目标你得盯着它做到底:\"把测试跑过\"、\"部署成功了再说\"。这时候经常出两种问题:模型做了一半觉得差不多了,自己就停了;更过分的是,它嘴上说一句 `tests passed` 就想收工。你要的其实很简单:这一轮能不能结束,不能模型自己说了算,得有个明确的条件,对着实打实的证据来判断。\n\n这条线其实从第一课就埋着了。s01 说过,退出循环本来是模型的一个决定;s04 的 Stop hook 第一次给了程序否决权。这一课把那个否决权做成完整的闭环:条件、证据、预算,三样缺一不可。\n\n## /goal:每轮收尾加一道闸门\n\n输入 `/goal <条件>` 就设了一个会话级的停止条件。程序把它存成当前活跃目标,每轮结束后,判断器检查对话记录里的可信证据够不够满足条件。不够,闸门就把这次结束拦住,塞一条\"继续干\"的提示进下一轮;够了,就清除目标,标记完成。\n\n![Goal Loop 总览](/course-assets/s22_goal_loop/goal-loop-overview.svg)\n\n和 s01 的循环比,只多了一道判断,模型想停的时候先过目标这关:\n\n```python\n# s01:模型说停就停\nif not has_tool_use(response):\n return\n# s22:想停?先过目标闸门\nif not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # 没达成 -> 推回去再来一轮\n return # 达成/超预算/没目标 -> 真停\n```\n\n这道闸门是程序自己控制的。不是模型自己约束自己,模型甚至不知道有这么一道闸门,它只是收到了下一轮的输入,接着干就是了。\n\n## 设目标:证据从命令之后开始算\n\n`set_goal` 会存一个活跃目标:目标文本、最大轮数预算、计数器,还有 `start_index`——也就是证据窗口的起点。它取当前对话记录的长度,所以 `/goal` 这行命令本身在窗口外面。这是第一道防线:命令自己不能证明自己完成了。\n\n```python\ndef set_goal(self, objective, max_turns=20):\n self.active = {\n \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), # 证据窗口从这里开始;命令本身在窗口外\n \"max_turns\": max_turns, \"checks\": 0, \"continuation_turns\": 0,\n }\n```\n\n## 判断器:只信实打实的证据\n\n这是整个机制最核心的地方。判断器不看整段对话,只看证据窗口里来自可信来源的消息。三层过滤,把\"嘴上说完成了但不算数\"的内容全挡在外面:\n\n```python\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\ndef evidence_text(self):\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\": # 1 斜杠命令本身不算\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"): # 2 /goal 命令文本不算\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS: # 3 只信可信来源\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n```\n\n效果很明显:同样一句 `tests passed`,你打字说的不算,后台任务通知带回来的才算。模型糊弄不过去,它没法靠自己说一句\"我做完了\"就把目标判成完成。这是全课程反复出现的那条信任边界的最后一次登场:s16 说协议靠字段不靠理解,s19 说注解是申报、申报可以撒谎,s22 说完成证据只看来源不看内容。\n\n最小版的 `goal_satisfied()` 使用确定的关键词匹配,让演示保持离线和可复现。生产级 harness 可以把这条策略替换成独立的轻量判断模型,但仍然保留相同的可信证据边界。\n\n## 闸门三态:完成/继续/超预算\n\n`evaluate_after_turn` 每轮跑一次,三种结果:满足条件就清除目标(completed);没满足而且预算还没花完,就往队列塞一条\"继续干\"的提示,放行下一轮(continuing);预算花完就停(blocked),别让一个永远判不出来的目标无限烧钱。\n\n```python\ndef evaluate_after_turn(self):\n g = self.active\n g[\"checks\"] += 1\n if self.goal_satisfied():\n g[\"status\"] = \"completed\"; self.active = None\n return \"completed\" # 达成 -> 清除目标\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=\"继续干活,别把这条提醒当成完成证据。\",\n origin={\"kind\": \"active-goal\"})\n return \"continuing\" # 没达成 -> 塞提示,下一轮\n g[\"status\"] = \"blocked\"; self.active = None\n return \"blocked\" # 超预算 -> 放行,不再拦\n```\n\n那条\"继续干\"的提示里特意写了\"别把这条提醒当成完成证据\",连提醒本身都被排除在证据之外。三层防误判就齐了:命令文本不算、提醒文本不算、普通聊天文本不算。预算则是 s11 教过的老规矩:任何自动重试的机制都得有上限,不然一个永远判不满足的目标就是个烧钱的永动机。\n\n## 继续提示和外部异步消息分开走\n\n继续提示进的是同一个 `CommandQueue`,但它和外部异步事件(任务完成通知、监控行)不是同一种消费方式。`dequeue` 带个开关:消费外部收件箱的时候,默认跳过目标的继续提示。\n\n```python\ndef dequeue(self, include_goal_continuations=True):\n ...\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n```\n\n为什么要分开?如果同一个消费者把继续提示和外部通知一起取走,后台结果还没到,提醒文本就可能被误当成新证据。分开之后,目标的推进是显式的一步,不会被异步事件带着走。\n\n## 跑起来看看\n\n`code.py` 演示了一个 `/goal until tests passed and deploy green`:设了目标之后没有可信证据,闸门一轮轮把它推回去;你直接打 `tests passed` 也不算(来源不可信);直到后台任务发来 `task-notification`,证据到位,才标记完成。还加了一个 `max_turns=2` 的小目标演示超预算拦截。\n\n```python\ns.submit(\"/goal until tests passed and deploy green\") # 设目标,窗口在命令之后\ns.submit(\"tests passed, trust me\") # 普通文本 -> 不算完成\ns.deliver_host_event(\"tests passed; deploy green\",\n source=\"task-notification\") # 可信宿主事件 -> 完成\n```\n\n`submit()` 只接受普通用户文本。可信标签必须走独立的宿主事件通道,来源由 harness 白名单校验;用户或模型文本不能给自己贴上 `task-notification` 标签。\n\n## 相对 s21 的变更\n\n| | s21 Workflow Runtime | s22 Goal Loop |\n|--|---------------------|---------------|\n| 触发方式 | 脚本控制的编排(脱离主循环) | 条件控制的继续(拉回主循环) |\n| 加在哪 | 工具层:一个 `Workflow` 工具 | 轮次收尾:一道完成闸门 |\n| 谁决定停 | 脚本跑完就停 | 目标条件对着可信证据判 |\n| 新增机制 | 脚本 DSL、后台任务、journal/续跑、结构化输出 | 目标闸门、证据信任边界、继续提示分流、预算 |\n\ns21 是把编排写成脚本、派出去脱离主循环;s22 反过来,是一股力量把控制权重拉回主循环:目标没达成,这一轮就不算结束。两个都不改 s01 那个 `while` 循环,只是从两头给它加约束。\n\n## 试一下\n\n```bash\npython s22_goal_loop/code.py # /goal until tests pass + deploy green,看闸门怎么判\n```\n\n观察:设了目标之后,每轮结束都有一条 `goal_evaluated`;普通文本判 `satisfied=False`,`task-notification` 来源判 `satisfied=True`;预算花完的时候出 `goal_blocked`。同样一句 `tests passed`,来源不同,结果完全相反。这就是 `/goal` 不会被一句空话糊弄的地方。\n\n## 接下来\n\n`/goal` 是\"拉回主循环\"的一种触发:条件控制。它和 s21 的\"脱离主循环\"正好成对,一个把工作派出去,一个把控制权拉回来。再往外,还有时间控制(`/loop`、cron)和事件控制(`Monitor`)的重入,它们共享同一套任务/通知基底;但闸门的核心已经在这里:**停不停,不是模型一句话说了算,得目标对着可信证据来判。**\n\n\n" - }, - { - "version": "s22", - "locale": "ja", - "title": "s22: Goal Loop — いつ止まるかはモデルではなく goal が決める", - "content": "# s22: Goal Loop — いつ止まるかはモデルではなく goal が決める\n\ns01 → ... → s20 → s21 → `s22`\n\n> *「turn が終了できるかは goal condition を満たすかで決まり、モデルが stop と言っただけでは終わらない」* — `/goal` は main loop の各 turn の終端に gate を追加します。独立した evaluator が trusted evidence の充足を確認し、不足ならモデルを次のラウンドへ押し戻します。\n>\n> **Harness 層**: Goal closure — turn 終端に program-controlled completion gate を追加します。\n\n---\n\ns01 から s21 まで、会話の 1 turn はどう終わったでしょうか。モデルが `tool_use` を出さなくなると、loop はそのまま `return` しました。one-shot task なら問題ありません。終わったら止まります。\n\nしかし「テストを通す」「deploy が成功するまで続ける」のように、最後まで見届けるべき goal もあります。そこでは 2 つの問題がよく起きます。モデルが途中まで進めて十分だと思い、自分で止まる。さらに悪ければ、口頭で `tests passed` と言うだけで終了しようとします。必要なことは単純です。turn が終了できるかをモデル自身に決めさせず、明示的な condition を実際の evidence に照らして判断します。\n\nこの流れは最初の章からありました。s01 は loop の exit がモデルの判断だと説明し、s04 の Stop hook が初めて program に veto を与えました。この章は、その veto を condition、evidence、budget の 3 要素が欠けない完全な loop にします。\n\n## /goal: 各 turn の終端に gate を追加する\n\n`/goal ` を入力すると session-scoped stopping condition を設定します。program は active goal として保存し、各 turn の後に evaluator が transcript 内の trusted evidence を condition と照合します。不足なら gate が停止を拒み、次ラウンドへ「作業を続ける」prompt を queue します。十分なら goal を消して complete とします。\n\n![Goal Loop Overview](/course-assets/s22_goal_loop/goal-loop-overview.svg)\n\ns01 の loop と比べて、追加されるのは 1 つの判断だけです。モデルが止まりたいとき、先に goal gate を通ります。\n\n```python\n# s01: モデルが stop と言えば停止\nif not has_tool_use(response):\n return\n# s22: 止まりたい?先に goal gate を通る\nif not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # 未達成 -> 次のラウンドへ押し戻す\n return # 達成 / budget 超過 / goal なし -> 本当に停止\n```\n\nこの gate を制御するのは program です。モデルが自分を律しているのではありません。モデルは gate の存在すら知らず、次のラウンドの入力を受け取って作業を続けるだけです。\n\n## Goal の設定: Evidence は command の後から数える\n\n`set_goal` は active goal として、goal text、最大 turn budget、counter、そして evidence window の開始点 `start_index` を保存します。現在の transcript length を使うため、`/goal` command 自身は window の外です。これが最初の防御です。command が自分自身の完了を証明することはできません。\n\n```python\ndef set_goal(self, objective, max_turns=20):\n self.active = {\n \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), # evidence はここから。command 自身は window 外\n \"max_turns\": max_turns, \"checks\": 0, \"continuation_turns\": 0,\n }\n```\n\n## Evaluator: 実在する evidence だけを信頼する\n\nここが仕組み全体の core です。evaluator は会話全体を見ず、evidence window 内で trusted source から来た message だけを見ます。3 層の filter が、「完了したと言ったから完了」という内容をすべて外へ止めます。\n\n```python\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\ndef evidence_text(self):\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\": # 1 slash command 自身は evidence ではない\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"): # 2 /goal command text は evidence ではない\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS: # 3 trusted origin だけを信頼\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n```\n\n効果は明確です。同じ `tests passed` でも、あなたが入力したものは数えず、background task notification が持ち帰ったものだけを数えます。モデルは「完了した」と自分で言うだけでは goal を complete にできません。これはコース全体に繰り返し現れた trust boundary の最後の登場です。s16 は protocol が理解ではなく field に依存すると言い、s19 は annotation が申告であり、申告は嘘をつけると言い、s22 は completion evidence を content ではなく origin で信頼します。\n\n最小版の `goal_satisfied()` は決定的な keyword matching を使い、demo を offline かつ再現可能に保ちます。production harness では、この policy を独立した lightweight evaluator model に置き換えられますが、trusted evidence boundary はそのまま維持します。\n\n## Gate の 3 状態: Completed / continuing / budget 超過\n\n`evaluate_after_turn` は各 turn で 1 回動き、3 つの結果を返します。condition が満たされれば goal を completed として消します。満たされず budget が残れば「作業を続ける」prompt を queue し、continuing として次ラウンドを許可します。budget を使い切れば blocked で gate を解除し、永遠に判定できない goal が無限に費用を使わないようにします。\n\n```python\ndef evaluate_after_turn(self):\n g = self.active\n g[\"checks\"] += 1\n if self.goal_satisfied():\n g[\"status\"] = \"completed\"; self.active = None\n return \"completed\" # 達成 -> goal を消す\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=\"作業を続けてください。この reminder を completion evidence として扱わないでください。\",\n origin={\"kind\": \"active-goal\"})\n return \"continuing\" # 未達成 -> prompt を queue し、次ラウンドへ\n g[\"status\"] = \"blocked\"; self.active = None\n return \"blocked\" # budget 超過 -> gate を解除\n```\n\ncontinuation prompt には、わざわざ自身を evidence にしないよう書き、filter でも除外します。これで false positive を防ぐ 3 層がそろいます。command text、reminder text、ordinary conversation のいずれも数えません。budget は s11 の古い規則に従います。automatic retry mechanism には必ず上限が必要です。そうでなければ、永遠に satisfied にならない goal が費用を燃やし続けます。\n\n## Continuation prompt と外部 asynchronous message を分ける\n\ncontinuation prompt は同じ `CommandQueue` に入りますが、task completion notification や monitor line といった外部 asynchronous event とは別の方法で消費します。`dequeue` には switch があり、外部 inbox を消費するときは goal continuation を既定で skip します。\n\n```python\ndef dequeue(self, include_goal_continuations=True):\n ...\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n```\n\nなぜ分けるのでしょう。同じ consumer が continuation prompt と外部 notification を一緒に取り出すと、background result が届く前に reminder text を新しい evidence と誤認する可能性があります。分離後は goal の進行が明示的な 1 step になり、asynchronous event に偶然運ばれません。\n\n## 実際に動かす\n\n`code.py` は `/goal until tests passed and deploy green` を実演します。goal 設定後に trusted evidence がなければ、gate がラウンドごとに押し戻します。直接 `tests passed` と入力しても origin が信頼されないため数えません。background task が `task-notification` を送って初めて evidence がそろい、complete になります。`max_turns=2` の小さな goal で budget 超過も示します。\n\n```python\ns.submit(\"/goal until tests passed and deploy green\") # goal を設定。evidence は command 後から\ns.submit(\"tests passed, trust me\") # ordinary text -> completion evidence ではない\ns.deliver_host_event(\"tests passed; deploy green\",\n source=\"task-notification\") # trusted host event -> complete\n```\n\n`submit()` は通常のユーザーテキストだけを受け取る。trusted label は独立した host event channel から入り、source は harness の allowlist で検証される。ユーザーやモデルのテキストが自分に `task-notification` label を付けることはできない。\n\n## s21 からの変更点\n\n| | s21 Workflow Runtime | s22 Goal Loop |\n|--|---------------------|---------------|\n| trigger | script-controlled orchestration(main loop の外) | condition-controlled continuation(main loop へ引き戻す) |\n| 接続位置 | tool layer: 1 つの `Workflow` ツール | turn 終端: completion gate |\n| stop を決めるもの | script が完了 | goal condition を trusted evidence と照合 |\n| 新しい仕組み | script DSL、background task、journal/resume、structured output | goal gate、evidence trust boundary、continuation 分流、budget |\n\ns21 は script-defined orchestration を main loop の外へ送り出します。s22 は反対の力で control を引き戻します。goal が未達成なら turn は終わっていません。どちらも s01 の `while` loop を変えず、両側から制約を加えます。\n\n## 試してみる\n\n```bash\npython s22_goal_loop/code.py # /goal until tests pass + deploy green。gate の判定を見る\n```\n\ngoal 設定後、各 turn が `goal_evaluated` を出す様子を確認してください。ordinary text は `satisfied=False`、同じ内容でも `task-notification` origin は `satisfied=True`、budget を使い切ると `goal_blocked` です。同じ `tests passed` でも origin によって結果が正反対になります。空疎な主張で `/goal` を欺けない理由です。\n\n## 次へ\n\n`/goal` は control を main loop へ引き戻す trigger の 1 つ、condition control です。s21 の main loop 外 orchestration と対になり、一方は仕事を外へ送り、もう一方は control を内へ戻します。その外側には `/loop` と cron による time-controlled re-entry、`Monitor` による event-controlled re-entry もあり、同じ task/notification 基盤を共有します。しかし gate の core はすでにここにあります。**stop するかはモデルの一言では決まらず、goal が trusted evidence に照らして判断します。**\n\n\n" + "title": "s21: Goal Loop — いつ止まるかはモデルではなく goal が決める", + "content": "# s21: Goal Loop — いつ止まるかはモデルではなく goal が決める\n\ns01 → ... → s19 → s20 → `s21`\n\n> *「turn が終了できるかは goal condition を満たすかで決まり、モデルが stop と言っただけでは終わらない」* — `/goal` は main loop の各 turn の終端に gate を追加します。独立した evaluator が trusted evidence の充足を確認し、不足ならモデルを次のラウンドへ押し戻します。\n>\n> **Harness 層**: Goal closure — turn 終端に program-controlled completion gate を追加します。\n\n---\n\ns01 から s20 まで、会話の 1 turn はどう終わったでしょうか。モデルが `tool_use` を出さなくなると、loop はそのまま `return` しました。one-shot task なら問題ありません。終わったら止まります。\n\nしかし「テストを通す」「deploy が成功するまで続ける」のように、最後まで見届けるべき goal もあります。そこでは 2 つの問題がよく起きます。モデルが途中まで進めて十分だと思い、自分で止まる。さらに悪ければ、口頭で `tests passed` と言うだけで終了しようとします。必要なことは単純です。turn が終了できるかをモデル自身に決めさせず、明示的な condition を実際の evidence に照らして判断します。\n\nこの流れは最初の章からありました。s01 は loop の exit がモデルの判断だと説明し、s04 の Stop hook が初めて program に veto を与えました。この章は、その veto を condition、evidence、budget の 3 要素が欠けない完全な loop にします。\n\n## /goal: 各 turn の終端に gate を追加する\n\n`/goal ` を入力すると session-scoped stopping condition を設定します。program は active goal として保存し、各 turn の後に evaluator が transcript 内の trusted evidence を condition と照合します。不足なら gate が停止を拒み、次ラウンドへ「作業を続ける」prompt を queue します。十分なら goal を消して complete とします。\n\n![Goal Loop Overview](/course-assets/s21_goal_loop/goal-loop-overview.svg)\n\ns01 の loop と比べて、追加されるのは 1 つの判断だけです。モデルが止まりたいとき、先に goal gate を通ります。\n\n```python\n# s01: モデルが stop と言えば停止\nif not has_tool_use(response):\n return\n# s21: 止まりたい?先に goal gate を通る\nif not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # 未達成 -> 次のラウンドへ押し戻す\n return # 達成 / budget 超過 / goal なし -> 本当に停止\n```\n\nこの gate を制御するのは program です。モデルが自分を律しているのではありません。モデルは gate の存在すら知らず、次のラウンドの入力を受け取って作業を続けるだけです。\n\n## Goal の設定: Evidence は command の後から数える\n\n`set_goal` は active goal として、goal text、最大 turn budget、counter、そして evidence window の開始点 `start_index` を保存します。現在の transcript length を使うため、`/goal` command 自身は window の外です。これが最初の防御です。command が自分自身の完了を証明することはできません。\n\n```python\ndef set_goal(self, objective, max_turns=20):\n self.active = {\n \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), # evidence はここから。command 自身は window 外\n \"max_turns\": max_turns, \"checks\": 0, \"continuation_turns\": 0,\n }\n```\n\n## Evaluator: 実在する evidence だけを信頼する\n\nここが仕組み全体の core です。evaluator は会話全体を見ず、evidence window 内で trusted source から来た message だけを見ます。3 層の filter が、「完了したと言ったから完了」という内容をすべて外へ止めます。\n\n```python\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\ndef evidence_text(self):\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\": # 1 slash command 自身は evidence ではない\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"): # 2 /goal command text は evidence ではない\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS: # 3 trusted origin だけを信頼\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n```\n\n効果は明確です。同じ `tests passed` でも、あなたが入力したものは数えず、background task notification が持ち帰ったものだけを数えます。モデルは「完了した」と自分で言うだけでは goal を complete にできません。これはコース全体に繰り返し現れた trust boundary の最後の登場です。s15 は protocol が理解ではなく field に依存すると言い、s18 は annotation が申告であり、申告は嘘をつけると言い、s21 は completion evidence を content ではなく origin で信頼します。\n\n`goal_satisfied()` は決定的な keyword matching を使い、例を offline かつ再現可能に保ちます。評価と実行を分けることで、trusted evidence boundary を維持します。\n\n## Gate の 3 状態: Completed / continuing / budget 超過\n\n`evaluate_after_turn` は各 turn で 1 回動き、3 つの結果を返します。condition が満たされれば goal を completed として消します。満たされず budget が残れば「作業を続ける」prompt を queue し、continuing として次ラウンドを許可します。budget を使い切れば blocked で gate を解除し、永遠に判定できない goal が無限に費用を使わないようにします。\n\n```python\ndef evaluate_after_turn(self):\n g = self.active\n g[\"checks\"] += 1\n if self.goal_satisfied():\n g[\"status\"] = \"completed\"; self.active = None\n return \"completed\" # 達成 -> goal を消す\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=\"作業を続けてください。この reminder を completion evidence として扱わないでください。\",\n origin={\"kind\": \"active-goal\"})\n return \"continuing\" # 未達成 -> prompt を queue し、次ラウンドへ\n g[\"status\"] = \"blocked\"; self.active = None\n return \"blocked\" # budget 超過 -> gate を解除\n```\n\ncontinuation prompt には、わざわざ自身を evidence にしないよう書き、filter でも除外します。これで false positive を防ぐ 3 層がそろいます。command text、reminder text、ordinary conversation のいずれも数えません。budget は s11 の古い規則に従います。automatic retry mechanism には必ず上限が必要です。そうでなければ、永遠に satisfied にならない goal が費用を燃やし続けます。\n\n## Continuation prompt と外部 asynchronous message を分ける\n\ncontinuation prompt は同じ `CommandQueue` に入りますが、task completion notification や monitor line といった外部 asynchronous event とは別の方法で消費します。`dequeue` には switch があり、外部 inbox を消費するときは goal continuation を既定で skip します。\n\n```python\ndef dequeue(self, include_goal_continuations=True):\n ...\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n```\n\nなぜ分けるのでしょう。同じ consumer が continuation prompt と外部 notification を一緒に取り出すと、background result が届く前に reminder text を新しい evidence と誤認する可能性があります。分離後は goal の進行が明示的な 1 step になり、asynchronous event に偶然運ばれません。\n\n## 実際に動かす\n\n`code.py` は `/goal until tests passed and deploy green` を実演します。goal 設定後に trusted evidence がなければ、gate がラウンドごとに押し戻します。直接 `tests passed` と入力しても origin が信頼されないため数えません。background task が `task-notification` を送って初めて evidence がそろい、complete になります。`max_turns=2` の小さな goal で budget 超過も示します。\n\n```python\ns.submit(\"/goal until tests passed and deploy green\") # goal を設定。evidence は command 後から\ns.submit(\"tests passed, trust me\") # ordinary text -> completion evidence ではない\ns.deliver_host_event(\"tests passed; deploy green\",\n source=\"task-notification\") # trusted host event -> complete\n```\n\n`submit()` は通常のユーザーテキストだけを受け取る。trusted label は独立した host event channel から入り、source は harness の allowlist で検証される。ユーザーやモデルのテキストが自分に `task-notification` label を付けることはできない。\n\n## s20 からの変更点\n\n| | s20 Workflow Runtime | s21 Goal Loop |\n|--|---------------------|---------------|\n| trigger | script-controlled orchestration(main loop の外) | condition-controlled continuation(main loop へ引き戻す) |\n| 接続位置 | tool layer: 1 つの `Workflow` ツール | turn 終端: completion gate |\n| stop を決めるもの | script が完了 | goal condition を trusted evidence と照合 |\n| 新しい仕組み | script DSL、background task、journal/resume、structured output | goal gate、evidence trust boundary、continuation 分流、budget |\n\ns20 は script-defined orchestration を main loop の外へ送り出します。s21 は反対の力で control を引き戻します。goal が未達成なら turn は終わっていません。どちらも s01 の `while` loop を変えず、両側から制約を加えます。\n\n## 試してみる\n\n```bash\npython s21_goal_loop/code.py # /goal until tests pass + deploy green。gate の判定を見る\n```\n\ngoal 設定後、各 turn が `goal_evaluated` を出す様子を確認してください。ordinary text は `satisfied=False`、同じ内容でも `task-notification` origin は `satisfied=True`、budget を使い切ると `goal_blocked` です。同じ `tests passed` でも origin によって結果が正反対になります。空疎な主張で `/goal` を欺けない理由です。\n\n## 次へ\n\n`/goal` は control を main loop へ引き戻す trigger の 1 つ、condition control です。s20 の main loop 外 orchestration と対になり、一方は仕事を外へ送り、もう一方は control を内へ戻します。その外側には `/loop` と cron による time-controlled re-entry、`Monitor` による event-controlled re-entry もあり、同じ task/notification 基盤を共有します。しかし gate の core はすでにここにあります。**stop するかはモデルの一言では決まらず、goal が trusted evidence に照らして判断します。**\n\n\n" } ] \ No newline at end of file diff --git a/web/src/data/generated/versions.json b/web/src/data/generated/versions.json index 1e8640f3..a79cf529 100644 --- a/web/src/data/generated/versions.json +++ b/web/src/data/generated/versions.json @@ -28,7 +28,7 @@ } ], "layer": "tools", - "source": "#!/usr/bin/env python3\n\"\"\"\ns01_agent_loop.py - The Agent Loop\n\nThe entire secret of an AI coding agent in one pattern:\n\n while stop_reason == \"tool_use\":\n response = LLM(messages, tools)\n execute tools\n append results\n\n +----------+ +-------+ +---------+\n | User | ---> | LLM | ---> | Tool |\n | prompt | | | | execute |\n +----------+ +---+---+ +----+----+\n ^ |\n | tool_result |\n +---------------+\n (loop continues)\n\nThis is the core loop: feed tool results back to the model\nuntil the model decides to stop. Production agents layer\npolicy, hooks, and lifecycle controls on top.\n\nUsage:\n pip install anthropic python-dotenv\n ANTHROPIC_API_KEY=... python s01_agent_loop/code.py\n\"\"\"\n\nimport os\nimport subprocess\n\ntry:\n import readline\n # macOS 的 libedit 在处理中文输入时有退格问题,这四行修复它\n readline.parse_and_bind('set bind-tty-special-chars off')\n readline.parse_and_bind('set input-meta on')\n readline.parse_and_bind('set output-meta on')\n readline.parse_and_bind('set convert-meta off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\n\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\nSYSTEM = f\"You are a coding agent at {os.getcwd()}. Use bash to solve tasks. Act, don't explain.\"\n\n# ── Tool definition: just bash ────────────────────────────\nTOOLS = [{\n \"name\": \"bash\",\n \"description\": \"Run a shell command.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"],\n },\n}]\n\n\n# ── Tool execution ────────────────────────────────────────\ndef run_bash(command: str) -> str:\n dangerous = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"> /dev/\"]\n if any(d in command for d in dangerous):\n return \"Error: Dangerous command blocked\"\n try:\n r = subprocess.run(command, shell=True, cwd=os.getcwd(),\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n except (FileNotFoundError, OSError) as e:\n return f\"Error: {e}\"\n\n\n# ── The core pattern: a while loop that calls tools until the model stops ──\ndef agent_loop(messages: list):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n\n # Append assistant turn\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n # If the model didn't call a tool, we're done\n if response.stop_reason != \"tool_use\":\n return\n\n # Execute each tool call, collect results\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n print(f\"\\033[33m$ {block.input['command']}\\033[0m\")\n output = run_bash(block.input[\"command\"])\n print(output[:200])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n\n # Feed tool results back, loop continues\n messages.append({\"role\": \"user\", \"content\": results})\n\n\n# ── Entry point ──────────────────────────────────────────\nif __name__ == \"__main__\":\n print(\"s01: Agent Loop\")\n print(\"输入问题,回车发送。输入 q 退出。\\n\")\n\n history = []\n while True:\n try:\n query = input(\"\\033[36ms01 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history)\n # Print the model's final text response\n response_content = history[-1][\"content\"]\n if isinstance(response_content, list):\n for block in response_content:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns01_agent_loop.py - The Agent Loop\n\nThe entire secret of an AI coding agent in one pattern:\n\n while stop_reason == \"tool_use\":\n response = LLM(messages, tools)\n execute tools\n append results\n\n +----------+ +-------+ +---------+\n | User | ---> | LLM | ---> | Tool |\n | prompt | | | | execute |\n +----------+ +---+---+ +----+----+\n ^ |\n | tool_result |\n +---------------+\n (loop continues)\n\nThis is the core loop: feed tool results back to the model\nuntil the model decides to stop. Later chapters add policy,\nhooks, and lifecycle controls around it.\n\nUsage:\n pip install anthropic python-dotenv\n ANTHROPIC_API_KEY=... python s01_agent_loop/code.py\n\"\"\"\n\nimport os\nimport subprocess\n\ntry:\n import readline\n # macOS 的 libedit 在处理中文输入时有退格问题,这四行修复它\n readline.parse_and_bind('set bind-tty-special-chars off')\n readline.parse_and_bind('set input-meta on')\n readline.parse_and_bind('set output-meta on')\n readline.parse_and_bind('set convert-meta off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\n\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\nSYSTEM = f\"You are a coding agent at {os.getcwd()}. Use bash to solve tasks. Act, don't explain.\"\n\n# ── Tool definition: just bash ────────────────────────────\nTOOLS = [{\n \"name\": \"bash\",\n \"description\": \"Run a shell command.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"],\n },\n}]\n\n\n# ── Tool execution ────────────────────────────────────────\ndef run_bash(command: str) -> str:\n dangerous = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"> /dev/\"]\n if any(d in command for d in dangerous):\n return \"Error: Dangerous command blocked\"\n try:\n r = subprocess.run(command, shell=True, cwd=os.getcwd(),\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n except (FileNotFoundError, OSError) as e:\n return f\"Error: {e}\"\n\n\n# ── The core pattern: a while loop that calls tools until the model stops ──\ndef agent_loop(messages: list):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n\n # Append assistant turn\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n # If the model didn't call a tool, we're done\n if response.stop_reason != \"tool_use\":\n return\n\n # Execute each tool call, collect results\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n print(f\"\\033[33m$ {block.input['command']}\\033[0m\")\n output = run_bash(block.input[\"command\"])\n print(output[:200])\n results.append({\n \"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output,\n })\n\n # Feed tool results back, loop continues\n messages.append({\"role\": \"user\", \"content\": results})\n\n\n# ── Entry point ──────────────────────────────────────────\nif __name__ == \"__main__\":\n print(\"s01: Agent Loop\")\n print(\"输入问题,回车发送。输入 q 退出。\\n\")\n\n history = []\n while True:\n try:\n query = input(\"\\033[36ms01 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history)\n # Print the model's final text response\n response_content = history[-1][\"content\"]\n if isinstance(response_content, list):\n for block in response_content:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", "images": [ { "src": "/course-assets/s01_agent_loop/agent-loop.svg", @@ -98,10 +98,6 @@ "layer": "tools", "source": "#!/usr/bin/env python3\n\"\"\"\ns02: Tool Use — 在 s01 基础上新增 4 个工具 + 分发映射。\n\n运行: python s02_tool_use/code.py\n需要: pip install anthropic python-dotenv + .env 中配置 ANTHROPIC_API_KEY\n\n本文件 = s01 的全部代码 + 以下新增:\n + run_read / run_write / run_edit / run_glob 四个工具实现\n + TOOL_HANDLERS 分发映射(替代 s01 中硬编码的 run_bash 调用)\n + safe_path 路径安全校验\n\n循环本身(agent_loop)与 s01 完全一致。\n\"\"\"\n\nimport os, subprocess\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\n readline.parse_and_bind('set input-meta on')\n readline.parse_and_bind('set output-meta on')\n readline.parse_and_bind('set convert-meta off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks. Act, don't explain.\"\n\n\n# ═══════════════════════════════════════════════════════════\n# FROM s01 (unchanged)\n# ═══════════════════════════════════════════════════════════\n\ndef run_bash(command: str) -> str:\n dangerous = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"> /dev/\"]\n if any(d in command for d in dangerous):\n return \"Error: Dangerous command blocked\"\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True,\n encoding=\"utf-8\", errors=\"replace\", timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n except (FileNotFoundError, OSError) as e:\n return f\"Error: {e}\"\n\n\n# ═══════════════════════════════════════════════════════════\n# NEW in s02: 4 个新工具\n# ═══════════════════════════════════════════════════════════\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = safe_path(path)\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_edit(path: str, old_text: str, new_text: str) -> str:\n try:\n file_path = safe_path(path)\n text = file_path.read_text()\n if old_text not in text:\n return f\"Error: text not found in {path}\"\n file_path.write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_glob(pattern: str) -> str:\n import glob as g\n try:\n results = []\n for match in g.glob(pattern, root_dir=WORKDIR):\n if (WORKDIR / match).resolve().is_relative_to(WORKDIR):\n results.append(match)\n return \"\\n\".join(results) if results else \"(no matches)\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# ═══════════════════════════════════════════════════════════\n# NEW in s02: 工具定义(s01 只有一个 bash,现在扩展到 5 个)\n# ═══════════════════════════════════════════════════════════\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"command\": {\"type\": \"string\"}}, \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"limit\": {\"type\": \"integer\"}}, \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"content\": {\"type\": \"string\"}}, \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"old_text\": {\"type\": \"string\"}, \"new_text\": {\"type\": \"string\"}}, \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"pattern\": {\"type\": \"string\"}}, \"required\": [\"pattern\"]}},\n]\n\n# ═══════════════════════════════════════════════════════════\n# NEW in s02: 工具分发映射(s01 是硬编码 run_bash,现在改为查表)\n# ═══════════════════════════════════════════════════════════\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"edit_file\": run_edit, \"glob\": run_glob,\n}\n\n\n# ═══════════════════════════════════════════════════════════\n# agent_loop — 与 s01 结构完全一致,只改了工具执行那部分\n# s01: output = run_bash(block.input[\"command\"])\n# s02: output = TOOL_HANDLERS[block.name](**block.input)\n# ═══════════════════════════════════════════════════════════\n\ndef agent_loop(messages: list):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n print(f\"\\033[33m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:200])\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id, \"content\": output})\n\n messages.append({\"role\": \"user\", \"content\": results})\n\n\nif __name__ == \"__main__\":\n print(\"s02: Tool Use — 在 s01 基础上加了 4 个工具\")\n print(\"输入问题,回车发送。输入 q 退出。\\n\")\n\n history = []\n while True:\n try:\n query = input(\"\\033[36ms02 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", "images": [ - { - "src": "/course-assets/s02_tool_use/concurrency-comparison.svg", - "alt": "concurrency comparison" - }, { "src": "/course-assets/s02_tool_use/tool-dispatch.svg", "alt": "tool dispatch" @@ -275,7 +271,7 @@ } ], "layer": "tools", - "source": "#!/usr/bin/env python3\n\"\"\"\ns04: Hooks — move extension logic out of the loop, onto hooks.\n\n User types query\n │\n ▼\n ┌──────────────────┐\n │ UserPromptSubmit │ ── trigger_hooks() before LLM\n └────────┬─────────┘\n ▼\n ┌────────────┐ ┌─────────────────────────────┐\n │ messages │────▶│ LLM (stop_reason=tool_use?)│\n └────────────┘ │ No ──▶ Stop hooks ──▶ exit │\n │ Yes ──▶ tool_use block ──┐ │\n └────────────────────────────┘ │\n ▼\n ┌──────────────────┐\n │ trigger_hooks() │\n │ PreToolUse: │\n │ permission_hook │\n │ log_hook │\n └───────┬──────────┘\n │ (not blocked)\n ┌───────▼──────────┐\n │ TOOL_HANDLERS[x] │\n └───────┬──────────┘\n │\n ┌───────▼──────────┐\n │ trigger_hooks() │\n │ PostToolUse: │\n │ large_output │\n └───────┬──────────┘\n │\n results ──▶ back to messages\n\nChanges from s03:\n + HOOKS registry (event -> list of callbacks)\n + register_hook() / trigger_hooks()\n + context_inject_hook (UserPromptSubmit)\n + permission_hook, log_hook (PreToolUse)\n + large_output_hook (PostToolUse)\n + summary_hook (Stop)\n - check_permission() removed from loop body\n (logic moved into permission_hook, triggered via PreToolUse)\n\nRun: python s04_hooks/code.py\nNeeds: pip install anthropic python-dotenv + ANTHROPIC_API_KEY in .env\n\"\"\"\n\nimport os, subprocess\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\n readline.parse_and_bind('set input-meta on')\n readline.parse_and_bind('set output-meta on')\n readline.parse_and_bind('set convert-meta off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks. Act, don't explain.\"\n\n\n# ═══════════════════════════════════════════════════════════\n# FROM s02-s03 : Tool Implementations\n# ═══════════════════════════════════════════════════════════\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n file_path = (WORKDIR / path).resolve()\n lines = file_path.read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = (WORKDIR / path).resolve()\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\ndef run_edit(path: str, old_text: str, new_text: str) -> str:\n try:\n file_path = (WORKDIR / path).resolve()\n text = file_path.read_text()\n if old_text not in text:\n return f\"Error: text not found in {path}\"\n file_path.write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\ndef run_glob(pattern: str) -> str:\n import glob as g\n try:\n results = []\n for match in g.glob(pattern, root_dir=WORKDIR):\n if (WORKDIR / match).resolve().is_relative_to(WORKDIR):\n results.append(match)\n return \"\\n\".join(results) if results else \"(no matches)\"\n except Exception as e:\n return f\"Error: {e}\"\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"command\": {\"type\": \"string\"}}, \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"limit\": {\"type\": \"integer\"}}, \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"content\": {\"type\": \"string\"}}, \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"old_text\": {\"type\": \"string\"}, \"new_text\": {\"type\": \"string\"}}, \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"pattern\": {\"type\": \"string\"}}, \"required\": [\"pattern\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"edit_file\": run_edit, \"glob\": run_glob,\n}\n\n\n# ═══════════════════════════════════════════════════════════\n# NEW in s04: Hook System (s03 permission logic now via hooks)\n# ═══════════════════════════════════════════════════════════\n\nHOOKS = {\"UserPromptSubmit\": [], \"PreToolUse\": [], \"PostToolUse\": [], \"Stop\": []}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # teaching shortcut: block this tool call\n return result\n return None\n\n\n# s03 permission check logic, now wrapped as a hook\nDENY_LIST = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"mkfs\", \"dd if=\"]\nDESTRUCTIVE = [\"rm \", \"> /etc/\", \"chmod 777\"]\n\ndef permission_hook(block):\n \"\"\"PreToolUse: s03 check_permission() logic moved here.\"\"\"\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n print(f\"\\n\\033[31m⛔ Blocked: '{pattern}'\\033[0m\")\n return \"Permission denied by deny list\"\n for kw in DESTRUCTIVE:\n if kw in block.input.get(\"command\", \"\"):\n print(f\"\\n\\033[33m⚠ Potentially destructive command\\033[0m\")\n print(f\" Tool: {block.name}({block.input})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n print(f\"\\n\\033[33m⚠ Access outside workspace\\033[0m\")\n print(f\" Tool: {block.name}({block.input})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\ndef log_hook(block):\n \"\"\"PreToolUse: log every tool call.\"\"\"\n args_preview = str(list(block.input.values())[:2])[:60]\n print(f\"\\033[90m[HOOK] {block.name}({args_preview})\\033[0m\")\n return None\n\ndef large_output_hook(block, output):\n \"\"\"PostToolUse: warn on large output.\"\"\"\n if len(str(output)) > 100000:\n print(f\"\\033[33m[HOOK] ⚠ Large output from {block.name}: {len(str(output))} chars\\033[0m\")\n return None\n\n# UserPromptSubmit hook: log user input before it reaches the LLM\ndef context_inject_hook(query: str):\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None\n\n# Stop hook: print summary when loop is about to exit\ndef summary_hook(messages: list):\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\nregister_hook(\"Stop\", summary_hook)\n\n\n# ═══════════════════════════════════════════════════════════\n# agent_loop — same structure as s03, but no hard-coded check\n# s03: if not check_permission(block): ...\n# s04: if trigger_hooks(\"PreToolUse\", block): ...\n# ═══════════════════════════════════════════════════════════\n\ndef agent_loop(messages: list):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages)\n if force:\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s04 change: hook replaces hard-coded check_permission()\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output) # s04: post hook\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id, \"content\": output})\n\n messages.append({\"role\": \"user\", \"content\": results})\n\n\nif __name__ == \"__main__\":\n print(\"s04: Hooks — extension logic on hooks, loop stays clean\")\n print(\"Type a question, press Enter. Type q to quit.\\n\")\n\n history = []\n while True:\n try:\n query = input(\"\\033[36ms04 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n trigger_hooks(\"UserPromptSubmit\", query)\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns04: Hooks — move extension logic out of the loop, onto hooks.\n\n User types query\n │\n ▼\n ┌──────────────────┐\n │ UserPromptSubmit │ ── trigger_hooks() before LLM\n └────────┬─────────┘\n ▼\n ┌────────────┐ ┌─────────────────────────────┐\n │ messages │────▶│ LLM (stop_reason=tool_use?)│\n └────────────┘ │ No ──▶ Stop hooks ──▶ exit │\n │ Yes ──▶ tool_use block ──┐ │\n └────────────────────────────┘ │\n ▼\n ┌──────────────────┐\n │ trigger_hooks() │\n │ PreToolUse: │\n │ permission_hook │\n │ log_hook │\n └───────┬──────────┘\n │ (not blocked)\n ┌───────▼──────────┐\n │ TOOL_HANDLERS[x] │\n └───────┬──────────┘\n │\n ┌───────▼──────────┐\n │ trigger_hooks() │\n │ PostToolUse: │\n │ large_output │\n └───────┬──────────┘\n │\n results ──▶ back to messages\n\nChanges from s03:\n + HOOKS registry (event -> list of callbacks)\n + register_hook() / trigger_hooks()\n + context_inject_hook (UserPromptSubmit)\n + permission_hook, log_hook (PreToolUse)\n + large_output_hook (PostToolUse)\n + summary_hook (Stop)\n - check_permission() removed from loop body\n (logic moved into permission_hook, triggered via PreToolUse)\n\nRun: python s04_hooks/code.py\nNeeds: pip install anthropic python-dotenv + ANTHROPIC_API_KEY in .env\n\"\"\"\n\nimport os, subprocess\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\n readline.parse_and_bind('set input-meta on')\n readline.parse_and_bind('set output-meta on')\n readline.parse_and_bind('set convert-meta off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\nSYSTEM = f\"You are a coding agent at {WORKDIR}. Use tools to solve tasks. Act, don't explain.\"\n\n\n# ═══════════════════════════════════════════════════════════\n# FROM s02-s03 : Tool Implementations\n# ═══════════════════════════════════════════════════════════\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n file_path = (WORKDIR / path).resolve()\n lines = file_path.read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = (WORKDIR / path).resolve()\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\ndef run_edit(path: str, old_text: str, new_text: str) -> str:\n try:\n file_path = (WORKDIR / path).resolve()\n text = file_path.read_text()\n if old_text not in text:\n return f\"Error: text not found in {path}\"\n file_path.write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\ndef run_glob(pattern: str) -> str:\n import glob as g\n try:\n results = []\n for match in g.glob(pattern, root_dir=WORKDIR):\n if (WORKDIR / match).resolve().is_relative_to(WORKDIR):\n results.append(match)\n return \"\\n\".join(results) if results else \"(no matches)\"\n except Exception as e:\n return f\"Error: {e}\"\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"command\": {\"type\": \"string\"}}, \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"limit\": {\"type\": \"integer\"}}, \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"content\": {\"type\": \"string\"}}, \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"path\": {\"type\": \"string\"}, \"old_text\": {\"type\": \"string\"}, \"new_text\": {\"type\": \"string\"}}, \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {\"pattern\": {\"type\": \"string\"}}, \"required\": [\"pattern\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"edit_file\": run_edit, \"glob\": run_glob,\n}\n\n\n# ═══════════════════════════════════════════════════════════\n# NEW in s04: Hook System (s03 permission logic now via hooks)\n# ═══════════════════════════════════════════════════════════\n\nHOOKS = {\"UserPromptSubmit\": [], \"PreToolUse\": [], \"PostToolUse\": [], \"Stop\": []}\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None: # A hook result blocks this tool call.\n return result\n return None\n\n\n# s03 permission check logic, now wrapped as a hook\nDENY_LIST = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"mkfs\", \"dd if=\"]\nDESTRUCTIVE = [\"rm \", \"> /etc/\", \"chmod 777\"]\n\ndef permission_hook(block):\n \"\"\"PreToolUse: s03 check_permission() logic moved here.\"\"\"\n if block.name == \"bash\":\n for pattern in DENY_LIST:\n if pattern in block.input.get(\"command\", \"\"):\n print(f\"\\n\\033[31m⛔ Blocked: '{pattern}'\\033[0m\")\n return \"Permission denied by deny list\"\n for kw in DESTRUCTIVE:\n if kw in block.input.get(\"command\", \"\"):\n print(f\"\\n\\033[33m⚠ Potentially destructive command\\033[0m\")\n print(f\" Tool: {block.name}({block.input})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n print(f\"\\n\\033[33m⚠ Access outside workspace\\033[0m\")\n print(f\" Tool: {block.name}({block.input})\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\ndef log_hook(block):\n \"\"\"PreToolUse: log every tool call.\"\"\"\n args_preview = str(list(block.input.values())[:2])[:60]\n print(f\"\\033[90m[HOOK] {block.name}({args_preview})\\033[0m\")\n return None\n\ndef large_output_hook(block, output):\n \"\"\"PostToolUse: warn on large output.\"\"\"\n if len(str(output)) > 100000:\n print(f\"\\033[33m[HOOK] ⚠ Large output from {block.name}: {len(str(output))} chars\\033[0m\")\n return None\n\n# UserPromptSubmit hook: log user input before it reaches the LLM\ndef context_inject_hook(query: str):\n print(f\"\\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\\033[0m\")\n return None\n\n# Stop hook: print summary when loop is about to exit\ndef summary_hook(messages: list):\n tool_count = sum(1 for m in messages\n for b in (m.get(\"content\") if isinstance(m.get(\"content\"), list) else [])\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: session used {tool_count} tool calls\\033[0m\")\n return None\n\nregister_hook(\"UserPromptSubmit\", context_inject_hook)\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\nregister_hook(\"Stop\", summary_hook)\n\n\n# ═══════════════════════════════════════════════════════════\n# agent_loop — same structure as s03, but no hard-coded check\n# s03: if not check_permission(block): ...\n# s04: if trigger_hooks(\"PreToolUse\", block): ...\n# ═══════════════════════════════════════════════════════════\n\ndef agent_loop(messages: list):\n while True:\n response = client.messages.create(\n model=MODEL, system=SYSTEM, messages=messages,\n tools=TOOLS, max_tokens=8000,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n force = trigger_hooks(\"Stop\", messages)\n if force:\n messages.append({\"role\": \"user\", \"content\": force})\n continue\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n\n # s04 change: hook replaces hard-coded check_permission()\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n\n trigger_hooks(\"PostToolUse\", block, output) # s04: post hook\n\n results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id, \"content\": output})\n\n messages.append({\"role\": \"user\", \"content\": results})\n\n\nif __name__ == \"__main__\":\n print(\"s04: Hooks — extension logic on hooks, loop stays clean\")\n print(\"Type a question, press Enter. Type q to quit.\\n\")\n\n history = []\n while True:\n try:\n query = input(\"\\033[36ms04 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n trigger_hooks(\"UserPromptSubmit\", query)\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", "images": [ { "src": "/course-assets/s04_hooks/hooks-overview.svg", @@ -1062,7 +1058,7 @@ "filename": "s10_system_prompt/code.py", "title": "Context Assembly", "subtitle": "Build Model Input from Runtime State", - "loc": 165, + "loc": 163, "tools": [ "bash", "read_file", @@ -1086,36 +1082,36 @@ { "name": "safe_path", "signature": "def safe_path(p: str)", - "startLine": 98 + "startLine": 96 }, { "name": "run_bash", "signature": "def run_bash(command: str)", - "startLine": 105 + "startLine": 103 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None)", - "startLine": 115 + "startLine": 113 }, { "name": "run_write", "signature": "def run_write(path: str, content: str)", - "startLine": 125 + "startLine": 123 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 157 + "startLine": 155 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 173 + "startLine": 171 } ], "layer": "planning", - "source": "#!/usr/bin/env python3\n\"\"\"\ns10: Context Assembly — Runtime model-input assembly with caching.\n\nRun: python s10_system_prompt/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s09:\n - PROMPT_SECTIONS: topic-keyed dict of prompt fragments\n - assemble_system_prompt(context): select + join sections by real state\n - get_system_prompt(context): deterministic cache via json.dumps\n - agent_loop uses get_system_prompt(context) instead of hardcoded SYSTEM\n\nMemory section loads when .memory/MEMORY.md exists (real state, not keywords).\n\"\"\"\n\nimport os, subprocess, json\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n\n# ── Prompt Sections ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n \"\"\"Select and join prompt sections based on current context.\"\"\"\n sections = []\n\n # Always loaded — identity\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # Dynamic — tools and workspace from context\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # Conditional — memory loaded when MEMORY.md exists and has content\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key = None\n_last_prompt = None\n\n\ndef get_system_prompt(context: dict) -> str:\n \"\"\"Cache wrapper — reassemble only when context changes.\n\n Uses json.dumps for deterministic serialization, not Python's hash()\n which has process randomization and fails on nested dicts/lists.\n This cache only avoids redundant string assembly within a process.\n Real Claude Code additionally protects API-level prompt cache via\n stable section ordering and SYSTEM_PROMPT_DYNAMIC_BOUNDARY.\n \"\"\"\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n print(\" \\033[90m[cache hit] system prompt unchanged\\033[0m\")\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n\n loaded = [\"identity\", \"tools\", \"workspace\"]\n if context.get(\"memories\"):\n loaded.append(\"memory\")\n print(f\" \\033[32m[assembled] sections: {', '.join(loaded)}\\033[0m\")\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = safe_path(path)\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n]\n\nTOOL_HANDLERS = {\"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write}\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state: which tools exist, whether memory files exist.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n \"\"\"Main loop — uses assembled system prompt instead of hardcoded SYSTEM.\"\"\"\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:200])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # Re-evaluate context and prompt after each tool round\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s10: context assembly — runtime model input\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms10 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns10: Context Assembly — Runtime model-input assembly with caching.\n\nRun: python s10_system_prompt/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s09:\n - PROMPT_SECTIONS: topic-keyed dict of prompt fragments\n - assemble_system_prompt(context): select + join sections by real state\n - get_system_prompt(context): deterministic cache via json.dumps\n - agent_loop uses get_system_prompt(context) instead of hardcoded SYSTEM\n\nMemory section loads when .memory/MEMORY.md exists (real state, not keywords).\n\"\"\"\n\nimport os, subprocess, json\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n\n# ── Prompt Sections ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n \"\"\"Select and join prompt sections based on current context.\"\"\"\n sections = []\n\n # Always loaded — identity\n sections.append(PROMPT_SECTIONS[\"identity\"])\n\n # Dynamic — tools and workspace from context\n tools = \", \".join(context.get(\"enabled_tools\", []))\n if tools:\n sections.append(f\"Available tools: {tools}.\")\n sections.append(f\"Working directory: {context.get('workspace', WORKDIR)}\")\n\n # Conditional — memory loaded when MEMORY.md exists and has content\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key = None\n_last_prompt = None\n\n\ndef get_system_prompt(context: dict) -> str:\n \"\"\"Cache wrapper — reassemble only when context changes.\n\n Uses json.dumps for deterministic serialization, not Python's hash()\n which has process randomization and fails on nested dicts/lists.\n Stable serialization lets identical context reuse the assembled prompt.\n \"\"\"\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n print(\" \\033[90m[cache hit] system prompt unchanged\\033[0m\")\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n\n loaded = [\"identity\", \"tools\", \"workspace\"]\n if context.get(\"memories\"):\n loaded.append(\"memory\")\n print(f\" \\033[32m[assembled] sections: {', '.join(loaded)}\\033[0m\")\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = safe_path(path)\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n]\n\nTOOL_HANDLERS = {\"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write}\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state: which tools exist, whether memory files exist.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n \"\"\"Main loop — uses assembled system prompt instead of hardcoded SYSTEM.\"\"\"\n system = get_system_prompt(context)\n while True:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:200])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # Re-evaluate context and prompt after each tool round\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s10: context assembly — runtime model input\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms10 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", "images": [ { "src": "/course-assets/s10_system_prompt/system-prompt-overview.svg", @@ -1128,7 +1124,7 @@ "filename": "s11_error_recovery/code.py", "title": "Error Recovery", "subtitle": "Errors Are the Start of a Retry", - "loc": 287, + "loc": 284, "tools": [ "bash", "read_file", @@ -1198,16 +1194,16 @@ { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 249 + "startLine": 246 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 265 + "startLine": 262 } ], "layer": "planning", - "source": "#!/usr/bin/env python3\n\"\"\"\ns11: Error Recovery — three recovery paths + exponential backoff.\n\nRun: python s11_error_recovery/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s10:\n - LLM call wrapped in try/except with three recovery paths\n - Path 1: max_tokens -> escalate 8K->64K (no append on first escalation),\n then continuation prompt (max 3)\n - Path 2: prompt_too_long -> reactive compact -> retry (once)\n - Path 3: 429/529 -> exponential backoff with jitter (max 10),\n fallback model on consecutive 529\n - with_retry wrapper for transient errors\n - RecoveryState tracks escalation / compact / 529 / model\n\nASCII flow:\n messages -> prompt assembly -> compress+load -> [try] LLM [except] -> tools -> loop\n | |\n stop_reason error type\n max_tokens? prompt_too_long? -> compact\n escalate / 429/529? -> backoff\n continue other? -> log + exit\n\"\"\"\n\nimport os, subprocess, time, random, json\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nPRIMARY_MODEL = os.environ[\"MODEL_ID\"]\nFALLBACK_MODEL = os.getenv(\"FALLBACK_MODEL_ID\")\n\n# ── Constants ──\n\nESCALATED_MAX_TOKENS = 64000\nDEFAULT_MAX_TOKENS = 8000\nMAX_RECOVERY_RETRIES = 3\nMAX_RETRIES = 10\nBASE_DELAY_MS = 500\nMAX_CONSECUTIVE_529 = 3\nCONTINUATION_PROMPT = (\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"\n)\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n print(\" \\033[90m[cache hit] system prompt unchanged\\033[0m\")\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n\n loaded = [\"identity\", \"tools\", \"workspace\"]\n if context.get(\"memories\"):\n loaded.append(\"memory\")\n print(f\" \\033[32m[assembled] sections: {', '.join(loaded)}\\033[0m\")\n return _last_prompt\n\n\n# ── Tools (unchanged) ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = safe_path(path)\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n]\n\nTOOL_HANDLERS = {\"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write}\n\n\n# ── Error Recovery (s11 new) ──\n\nclass RecoveryState:\n \"\"\"Track recovery attempts across the loop.\"\"\"\n def __init__(self):\n self.has_escalated = False\n self.recovery_count = 0\n self.consecutive_529 = 0\n self.has_attempted_reactive_compact = False\n self.current_model = PRIMARY_MODEL\n\n\ndef retry_delay(attempt, retry_after=None):\n \"\"\"Exponential backoff with jitter. Retry-After takes priority.\"\"\"\n if retry_after:\n return retry_after\n base = min(BASE_DELAY_MS * (2 ** attempt), 32000) / 1000\n jitter = random.uniform(0, base * 0.25)\n return base + jitter\n\n\ndef with_retry(fn, state: RecoveryState):\n \"\"\"Exponential backoff for transient errors (429/529).\n Non-transient errors are re-raised for the outer handler.\"\"\"\n for attempt in range(MAX_RETRIES):\n try:\n result = fn()\n state.consecutive_529 = 0\n return result\n except Exception as e:\n name = type(e).__name__\n msg = str(e).lower()\n\n # 429 rate limit -> exponential backoff\n if \"ratelimit\" in name.lower() or \"429\" in msg:\n delay = retry_delay(attempt)\n print(f\" \\033[33m[429 rate limit] retry {attempt+1}/{MAX_RETRIES},\"\n f\" wait {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n\n # 529 overloaded -> exponential backoff + fallback model\n if \"overloaded\" in name.lower() or \"529\" in msg or \"overloaded\" in msg:\n state.consecutive_529 += 1\n if state.consecutive_529 >= MAX_CONSECUTIVE_529:\n if FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n state.consecutive_529 = 0\n print(f\" \\033[31m[529 x{MAX_CONSECUTIVE_529}]\"\n f\" switching to {FALLBACK_MODEL}\\033[0m\")\n else:\n state.consecutive_529 = 0\n print(f\" \\033[31m[529 x{MAX_CONSECUTIVE_529}]\"\n f\" no FALLBACK_MODEL_ID configured, continuing retry\\033[0m\")\n delay = retry_delay(attempt)\n print(f\" \\033[33m[529 overloaded] retry {attempt+1}/{MAX_RETRIES},\"\n f\" wait {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n\n # Not transient -> re-raise for outer try/except\n raise\n raise RuntimeError(f\"Max retries ({MAX_RETRIES}) exceeded\")\n\n\ndef is_prompt_too_long_error(e: Exception) -> bool:\n \"\"\"Check whether an API error indicates prompt/context too long.\"\"\"\n msg = str(e).lower()\n return ((\"prompt\" in msg and \"long\" in msg)\n or \"prompt_is_too_long\" in msg\n or \"context_length_exceeded\" in msg\n or \"max_context_window\" in msg)\n\n\ndef reactive_compact(messages: list) -> list:\n \"\"\"Emergency compact — teaching version keeps last N messages.\n Real CC generates a compact summary via LLM, then retries with\n the compacted message list. Teaching version simplifies to tail\n retention since s08/s09 already cover LLM-based compact.\"\"\"\n print(\" \\033[31m[reactive compact] trimming to last 5 messages\\033[0m\")\n tail = messages[-5:]\n return [{\"role\": \"user\",\n \"content\": \"[Reactive compact] Earlier conversation trimmed. \"\n \"Continue from where you left off.\"}, *tail]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state: which tools exist, whether memory files exist.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n \"\"\"Main loop with error recovery wrapping LLM calls.\"\"\"\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = DEFAULT_MAX_TOKENS\n\n while True:\n # ── LLM call: with_retry handles 429/529, outer handles rest ──\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n # Path 2: prompt_too_long -> reactive compact (once)\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n print(\" \\033[31m[unrecoverable] still too long after compact\\033[0m\")\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": \"[Error] Context too large, cannot continue.\"}]})\n return\n\n # Unrecoverable\n name = type(e).__name__\n print(f\" \\033[31m[unrecoverable] {name}: {str(e)[:100]}\\033[0m\")\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {name}: {str(e)[:200]}\"}]})\n return\n\n # ── Path 1: max_tokens -> escalate or continue ──\n if response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n print(f\" \\033[33m[max_tokens] escalating\"\n f\" {DEFAULT_MAX_TOKENS} -> {ESCALATED_MAX_TOKENS}\\033[0m\")\n continue\n # 64K still truncated: save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n state.recovery_count += 1\n print(f\" \\033[33m[max_tokens] continuation\"\n f\" {state.recovery_count}/{MAX_RECOVERY_RETRIES}\\033[0m\")\n continue\n print(\" \\033[31m[max_tokens] recovery limit reached\\033[0m\")\n return\n\n # Normal completion: append assistant response\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n # ── Tool execution ──\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:200])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s11: error recovery\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms11 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n turn_start = len(history)\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for msg in history[turn_start:]:\n if msg.get(\"role\") != \"assistant\":\n continue\n for block in msg[\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns11: Error Recovery — three recovery paths + exponential backoff.\n\nRun: python s11_error_recovery/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s10:\n - LLM call wrapped in try/except with three recovery paths\n - Path 1: max_tokens -> escalate 8K->64K (no append on first escalation),\n then continuation prompt (max 3)\n - Path 2: prompt_too_long -> reactive compact -> retry (once)\n - Path 3: 429/529 -> exponential backoff with jitter (max 10),\n fallback model on consecutive 529\n - with_retry wrapper for transient errors\n - RecoveryState tracks escalation / compact / 529 / model\n\nASCII flow:\n messages -> prompt assembly -> compress+load -> [try] LLM [except] -> tools -> loop\n | |\n stop_reason error type\n max_tokens? prompt_too_long? -> compact\n escalate / 429/529? -> backoff\n continue other? -> log + exit\n\"\"\"\n\nimport os, subprocess, time, random, json\nfrom pathlib import Path\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nPRIMARY_MODEL = os.environ[\"MODEL_ID\"]\nFALLBACK_MODEL = os.getenv(\"FALLBACK_MODEL_ID\")\n\n# ── Constants ──\n\nESCALATED_MAX_TOKENS = 64000\nDEFAULT_MAX_TOKENS = 8000\nMAX_RECOVERY_RETRIES = 3\nMAX_RETRIES = 10\nBASE_DELAY_MS = 500\nMAX_CONSECUTIVE_529 = 3\nCONTINUATION_PROMPT = (\n \"Output token limit hit. Resume directly — \"\n \"no apology, no recap. Pick up mid-thought.\"\n)\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n print(\" \\033[90m[cache hit] system prompt unchanged\\033[0m\")\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n\n loaded = [\"identity\", \"tools\", \"workspace\"]\n if context.get(\"memories\"):\n loaded.append(\"memory\")\n print(f\" \\033[32m[assembled] sections: {', '.join(loaded)}\\033[0m\")\n return _last_prompt\n\n\n# ── Tools (unchanged) ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n file_path = safe_path(path)\n file_path.parent.mkdir(parents=True, exist_ok=True)\n file_path.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n]\n\nTOOL_HANDLERS = {\"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write}\n\n\n# ── Error Recovery (s11 new) ──\n\nclass RecoveryState:\n \"\"\"Track recovery attempts across the loop.\"\"\"\n def __init__(self):\n self.has_escalated = False\n self.recovery_count = 0\n self.consecutive_529 = 0\n self.has_attempted_reactive_compact = False\n self.current_model = PRIMARY_MODEL\n\n\ndef retry_delay(attempt, retry_after=None):\n \"\"\"Exponential backoff with jitter. Retry-After takes priority.\"\"\"\n if retry_after:\n return retry_after\n base = min(BASE_DELAY_MS * (2 ** attempt), 32000) / 1000\n jitter = random.uniform(0, base * 0.25)\n return base + jitter\n\n\ndef with_retry(fn, state: RecoveryState):\n \"\"\"Exponential backoff for transient errors (429/529).\n Non-transient errors are re-raised for the outer handler.\"\"\"\n for attempt in range(MAX_RETRIES):\n try:\n result = fn()\n state.consecutive_529 = 0\n return result\n except Exception as e:\n name = type(e).__name__\n msg = str(e).lower()\n\n # 429 rate limit -> exponential backoff\n if \"ratelimit\" in name.lower() or \"429\" in msg:\n delay = retry_delay(attempt)\n print(f\" \\033[33m[429 rate limit] retry {attempt+1}/{MAX_RETRIES},\"\n f\" wait {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n\n # 529 overloaded -> exponential backoff + fallback model\n if \"overloaded\" in name.lower() or \"529\" in msg or \"overloaded\" in msg:\n state.consecutive_529 += 1\n if state.consecutive_529 >= MAX_CONSECUTIVE_529:\n if FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n state.consecutive_529 = 0\n print(f\" \\033[31m[529 x{MAX_CONSECUTIVE_529}]\"\n f\" switching to {FALLBACK_MODEL}\\033[0m\")\n else:\n state.consecutive_529 = 0\n print(f\" \\033[31m[529 x{MAX_CONSECUTIVE_529}]\"\n f\" no FALLBACK_MODEL_ID configured, continuing retry\\033[0m\")\n delay = retry_delay(attempt)\n print(f\" \\033[33m[529 overloaded] retry {attempt+1}/{MAX_RETRIES},\"\n f\" wait {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n\n # Not transient -> re-raise for outer try/except\n raise\n raise RuntimeError(f\"Max retries ({MAX_RETRIES}) exceeded\")\n\n\ndef is_prompt_too_long_error(e: Exception) -> bool:\n \"\"\"Check whether an API error indicates prompt/context too long.\"\"\"\n msg = str(e).lower()\n return ((\"prompt\" in msg and \"long\" in msg)\n or \"prompt_is_too_long\" in msg\n or \"context_length_exceeded\" in msg\n or \"max_context_window\" in msg)\n\n\ndef reactive_compact(messages: list) -> list:\n \"\"\"Emergency compact: keep the latest messages, then retry.\"\"\"\n print(\" \\033[31m[reactive compact] trimming to last 5 messages\\033[0m\")\n tail = messages[-5:]\n return [{\"role\": \"user\",\n \"content\": \"[Reactive compact] Earlier conversation trimmed. \"\n \"Continue from where you left off.\"}, *tail]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state: which tools exist, whether memory files exist.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n \"\"\"Main loop with error recovery wrapping LLM calls.\"\"\"\n system = get_system_prompt(context)\n state = RecoveryState()\n max_tokens = DEFAULT_MAX_TOKENS\n\n while True:\n # ── LLM call: with_retry handles 429/529, outer handles rest ──\n try:\n response = with_retry(\n lambda: client.messages.create(\n model=state.current_model, system=system,\n messages=messages, tools=TOOLS,\n max_tokens=max_tokens),\n state)\n except Exception as e:\n # Path 2: prompt_too_long -> reactive compact (once)\n if is_prompt_too_long_error(e):\n if not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n print(\" \\033[31m[unrecoverable] still too long after compact\\033[0m\")\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": \"[Error] Context too large, cannot continue.\"}]})\n return\n\n # Unrecoverable\n name = type(e).__name__\n print(f\" \\033[31m[unrecoverable] {name}: {str(e)[:100]}\\033[0m\")\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {name}: {str(e)[:200]}\"}]})\n return\n\n # ── Path 1: max_tokens -> escalate or continue ──\n if response.stop_reason == \"max_tokens\":\n # First escalation: don't append truncated output, retry same request\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n print(f\" \\033[33m[max_tokens] escalating\"\n f\" {DEFAULT_MAX_TOKENS} -> {ESCALATED_MAX_TOKENS}\\033[0m\")\n continue\n # 64K still truncated: save truncated output + continuation prompt\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n state.recovery_count += 1\n print(f\" \\033[33m[max_tokens] continuation\"\n f\" {state.recovery_count}/{MAX_RECOVERY_RETRIES}\\033[0m\")\n continue\n print(\" \\033[31m[max_tokens] recovery limit reached\\033[0m\")\n return\n\n # Normal completion: append assistant response\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n if response.stop_reason != \"tool_use\":\n return\n\n # ── Tool execution ──\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:200])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s11: error recovery\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms11 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n turn_start = len(history)\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for msg in history[turn_start:]:\n if msg.get(\"role\") != \"assistant\":\n continue\n for block in msg[\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n print()\n", "images": [ { "src": "/course-assets/s11_error_recovery/error-recovery-overview.svg", @@ -1220,7 +1216,7 @@ "filename": "s12_task_system/code.py", "title": "Task System", "subtitle": "Break Big Goals into Small Tasks", - "loc": 299, + "loc": 297, "tools": [ "bash", "read_file", @@ -1243,114 +1239,114 @@ "classes": [ { "name": "Task", - "startLine": 53, - "endLine": 61 + "startLine": 51, + "endLine": 59 } ], "functions": [ { "name": "_task_path", "signature": "def _task_path(task_id: str)", - "startLine": 62 + "startLine": 60 }, { "name": "save_task", "signature": "def save_task(task: Task)", - "startLine": 80 + "startLine": 78 }, { "name": "load_task", "signature": "def load_task(task_id: str)", - "startLine": 84 + "startLine": 82 }, { "name": "list_tasks", "signature": "def list_tasks()", - "startLine": 88 + "startLine": 86 }, { "name": "get_task", "signature": "def get_task(task_id: str)", - "startLine": 93 + "startLine": 91 }, { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 99 + "startLine": 97 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 111 + "startLine": 109 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 126 + "startLine": 124 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 153 + "startLine": 151 }, { "name": "get_system_prompt", "signature": "def get_system_prompt(context: dict)", - "startLine": 166 + "startLine": 164 }, { "name": "safe_path", "signature": "def safe_path(p: str)", - "startLine": 178 + "startLine": 176 }, { "name": "run_bash", "signature": "def run_bash(command: str)", - "startLine": 185 + "startLine": 183 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None)", - "startLine": 195 + "startLine": 193 }, { "name": "run_write", "signature": "def run_write(path: str, content: str)", - "startLine": 205 + "startLine": 203 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 225 + "startLine": 223 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 240 + "startLine": 238 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 247 + "startLine": 245 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 251 + "startLine": 249 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 310 + "startLine": 308 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 326 + "startLine": 324 } ], "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns12: Task System — file-persisted task graph with blockedBy dependencies.\n\nRun: python s12_task_system/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s11:\n - Task dataclass (id, subject, description, status, owner, blockedBy)\n - TASKS_DIR = .tasks/ for persistent JSON storage\n - create_task / save_task / load_task / list_tasks / get_task\n - can_start: checks blockedBy all completed (missing deps = blocked)\n - claim_task: set owner + pending -> in_progress\n - complete_task: set completed + report unblocked downstream\n - 5 new tools: create_task, list_tasks, get_task, claim_task, complete_task\n\nNote: Teaching code keeps a basic agent loop to stay focused on the task\nsystem. S11's full error recovery (RecoveryState, backoff, escalation,\nreactive compact, fallback model) is omitted — in real CC, tasks.ts and\nwithRetry are independent layers that compose naturally.\n\"\"\"\n\nimport os, subprocess, json, time, random\nfrom pathlib import Path\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent name (multi-agent scenarios)\n blockedBy: list[str] # Dependency task IDs\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject,\n description=description,\n status=\"pending\",\n owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n}\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop (simplified, focused on task system) ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s12: task system\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms12 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns12: Task System — file-persisted task graph with blockedBy dependencies.\n\nRun: python s12_task_system/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s11:\n - Task dataclass (id, subject, description, status, owner, blockedBy)\n - TASKS_DIR = .tasks/ for persistent JSON storage\n - create_task / save_task / load_task / list_tasks / get_task\n - can_start: checks blockedBy all completed (missing deps = blocked)\n - claim_task: set owner + pending -> in_progress\n - complete_task: set completed + report unblocked downstream\n - 5 new tools: create_task, list_tasks, get_task, claim_task, complete_task\n\nThis chapter keeps the agent loop focused on the task system. Error recovery\nremains the independent layer introduced in s11.\n\"\"\"\n\nimport os, subprocess, json, time, random\nfrom pathlib import Path\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None # Agent name (multi-agent scenarios)\n blockedBy: list[str] # Dependency task IDs\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject,\n description=description,\n status=\"pending\",\n owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n}\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop (simplified, focused on task system) ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else f\"Unknown: {block.name}\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s12: task system\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms12 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n print()\n", "images": [ { "src": "/course-assets/s12_task_system/task-dag.svg", @@ -1367,7 +1363,7 @@ "filename": "s13_background_tasks/code.py", "title": "Background Tasks", "subtitle": "Slow Operations Go to the Background", - "loc": 381, + "loc": 380, "tools": [ "bash", "read_file", @@ -1384,139 +1380,139 @@ "classes": [ { "name": "Task", - "startLine": 54, - "endLine": 62 + "startLine": 53, + "endLine": 61 } ], "functions": [ { "name": "_task_path", "signature": "def _task_path(task_id: str)", - "startLine": 63 + "startLine": 62 }, { "name": "save_task", "signature": "def save_task(task: Task)", - "startLine": 79 + "startLine": 78 }, { "name": "load_task", "signature": "def load_task(task_id: str)", - "startLine": 83 + "startLine": 82 }, { "name": "list_tasks", "signature": "def list_tasks()", - "startLine": 87 + "startLine": 86 }, { "name": "get_task", "signature": "def get_task(task_id: str)", - "startLine": 92 + "startLine": 91 }, { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 98 + "startLine": 97 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 110 + "startLine": 109 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 125 + "startLine": 124 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 152 + "startLine": 151 }, { "name": "get_system_prompt", "signature": "def get_system_prompt(context: dict)", - "startLine": 165 + "startLine": 164 }, { "name": "safe_path", "signature": "def safe_path(p: str)", - "startLine": 177 + "startLine": 176 }, { "name": "run_bash", "signature": "def run_bash(command: str, run_in_background: bool = False)", - "startLine": 184 + "startLine": 183 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None)", - "startLine": 195 + "startLine": 194 }, { "name": "run_write", "signature": "def run_write(path: str, content: str)", - "startLine": 205 + "startLine": 204 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 225 + "startLine": 224 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 240 + "startLine": 239 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 247 + "startLine": 246 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 251 + "startLine": 250 }, { "name": "is_slow_operation", "signature": "def is_slow_operation(tool_name: str, tool_input: dict)", - "startLine": 318 + "startLine": 317 }, { "name": "should_run_background", "signature": "def should_run_background(tool_name: str, tool_input: dict)", - "startLine": 329 + "startLine": 328 }, { "name": "execute_tool", "signature": "def execute_tool(block)", - "startLine": 336 + "startLine": 335 }, { "name": "start_background_task", "signature": "def start_background_task(block)", - "startLine": 344 + "startLine": 343 }, { "name": "collect_background_results", "signature": "def collect_background_results()", - "startLine": 369 + "startLine": 368 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 394 + "startLine": 393 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 410 + "startLine": 409 } ], "layer": "concurrency", - "source": "#!/usr/bin/env python3\n\"\"\"\ns13: Background Tasks — thread-based async execution + notification injection.\n\nRun: python s13_background_tasks/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s12:\n - threading.Thread for background execution\n - background_tasks dict for lifecycle tracking (bg_id, command, status)\n - background_results dict + threading.Lock for thread-safe storage\n - should_run_background: model explicit request via run_in_background param\n - is_slow_operation: fallback heuristic when model doesn't specify\n - start_background_task: dispatch to daemon thread, return bg task id\n - collect_background_results: gather completed, return as notifications\n - agent_loop: slow ops → background + placeholder, inject notifications\n - Notifications use format, not reused tool_use_id\n\nNote: Teaching code keeps a basic agent loop to stay focused on background\ntasks. S11's full error recovery (RecoveryState, backoff, escalation,\nreactive compact, fallback model) is omitted.\n\"\"\"\n\nimport os, subprocess, json, time, random, threading\nfrom pathlib import Path\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n}\n\n\n# ── Background Tasks (s13 new) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = TOOL_HANDLERS.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop (simplified, focused on background tasks) ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Command: {block.input.get('command', '')}. \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Inject tool results + background notifications in one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n print(f\" \\033[32m[inject] {len(bg_notifications)} background \"\n f\"notification(s)\\033[0m\")\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s13: background tasks\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms13 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns13: Background Tasks — thread-based async execution + notification injection.\n\nRun: python s13_background_tasks/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s12:\n - threading.Thread for background execution\n - background_tasks dict for lifecycle tracking (bg_id, command, status)\n - background_results dict + threading.Lock for thread-safe storage\n - should_run_background: model explicit request via run_in_background param\n - is_slow_operation: fallback heuristic when model doesn't specify\n - start_background_task: dispatch to daemon thread, return bg task id\n - collect_background_results: gather completed, return as notifications\n - agent_loop: slow ops → background + placeholder, inject notifications\n - Notifications use format, not reused tool_use_id\n\nThis chapter keeps the agent loop focused on background tasks. Error recovery\nremains the independent layer introduced in s11.\n\"\"\"\n\nimport os, subprocess, json, time, random, threading\nfrom pathlib import Path\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n}\n\n\n# ── Background Tasks (s13 new) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {} # bg_id → {tool_use_id, command, status}\nbackground_results: dict[str, str] = {} # bg_id → output\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = TOOL_HANDLERS.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n thread = threading.Thread(target=worker, daemon=True)\n thread.start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": list(TOOL_HANDLERS.keys()),\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop (simplified, focused on background tasks) ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Command: {block.input.get('command', '')}. \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Inject tool results + background notifications in one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n print(f\" \\033[32m[inject] {len(bg_notifications)} background \"\n f\"notification(s)\\033[0m\")\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s13: background tasks\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms13 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n print()\n", "images": [ { "src": "/course-assets/s13_background_tasks/background-tasks-overview.svg", @@ -1765,7 +1761,7 @@ } ], "layer": "concurrency", - "source": "#!/usr/bin/env python3\n\"\"\"\ns14: Cron Scheduler — independent daemon thread + queue processor.\n\nRun: python s14_cron_scheduler/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s13:\n - CronJob dataclass (id, cron, prompt, recurring, durable)\n - cron_matches: 5-field cron expression matching with DOM/DOW OR semantics\n - schedule_job / cancel_job: register/remove cron jobs (with validation)\n - cron_scheduler_loop: independent daemon thread, polls every 1s\n - cron_queue: thread-safe queue, scheduler writes, queue processor delivers\n - queue_processor_loop: auto-runs agent_loop when cron_queue has work\n - Durable storage: .scheduled_tasks.json (survives restart)\n - 3 new tools: schedule_cron, list_crons, cancel_cron\n\nFour layers:\n 1. Scheduler: daemon thread checks time → fires matching jobs\n 2. Queue: cron_queue decouples scheduler from agent loop\n 3. Queue processor: wakes the agent when queued work exists and it is idle\n 4. Consumer: agent_loop consumes queued jobs and injects them into messages\n\"\"\"\n\nimport os, subprocess, json, time, random, threading\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\n# ── Background Tasks (from s13, synced) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron, \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n }.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\n# ── Cron Scheduler (s14 new) ──\n\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"\n prompt: str # message to inject when fired\n recurring: bool # True = recurring, False = one-shot\n durable: bool # True = persist to disk\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\nagent_lock = threading.Lock()\n_last_fired: dict[str, str] = {} # job_id → \"YYYY-MM-DD HH:MM\"\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n \"\"\"Match a single cron field against a value.\"\"\"\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(f.strip(), value)\n for f in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n \"\"\"Check if a 5-field cron expression matches the given datetime.\n Standard cron semantics: DOM and DOW use OR when both are constrained.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n # Minute, hour, month must all match\n if not (m and h and month_ok):\n return False\n # DOM and DOW: if both constrained, either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n \"\"\"Validate a single cron field value is within [lo, hi].\"\"\"\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step_str = field[2:]\n if not step_str.isdigit():\n return f\"Invalid step: {field}\"\n step = int(step_str)\n if step <= 0:\n return f\"Step must be > 0: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err: return err\n return None\n if \"-\" in field:\n parts = field.split(\"-\", 1)\n if not parts[0].isdigit() or not parts[1].isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(parts[0]), int(parts[1])\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n val = int(field)\n if val < lo or val > hi:\n return f\"Value {val} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n \"\"\"Validate a cron expression. Returns error message or None.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n \"\"\"Persist durable jobs to .scheduled_tasks.json.\"\"\"\n durable = [asdict(j) for j in scheduled_jobs.values() if j.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n \"\"\"Load durable jobs from disk on startup.\"\"\"\n if not DURABLE_PATH.exists():\n return\n try:\n jobs = json.loads(DURABLE_PATH.read_text())\n for j in jobs:\n job = CronJob(**j)\n err = validate_cron(job.cron)\n if err:\n print(f\" \\033[31m[cron] skipping invalid job {job.id}: {err}\\033[0m\")\n continue\n scheduled_jobs[job.id] = job\n valid = [j for j in jobs if j[\"id\"] in scheduled_jobs]\n if valid:\n print(f\" \\033[35m[cron] loaded {len(valid)} durable job(s)\\033[0m\")\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str, recurring: bool = True,\n durable: bool = True) -> CronJob | str:\n \"\"\"Register a new cron job. Returns CronJob or error string.\"\"\"\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable,\n )\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n print(f\" \\033[35m[cron register] {job.id} '{cron}' → {prompt[:40]}\\033[0m\")\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n \"\"\"Cancel a cron job.\"\"\"\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n print(f\" \\033[31m[cron cancel] {job_id}\\033[0m\")\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n \"\"\"Independent daemon thread: poll every 1s, fire matching jobs.\n Individual job errors are caught to prevent one bad job from\n killing the entire scheduler thread.\"\"\"\n while True:\n time.sleep(1)\n now = datetime.now()\n # Date-aware marker prevents daily jobs from skipping on day 2+\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n print(f\" \\033[35m[cron fire] {job.id} → \"\n f\"{job.prompt[:40]}\\033[0m\")\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n \"\"\"Consume fired jobs from cron_queue (called by agent_loop).\"\"\"\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\ndef has_cron_queue() -> bool:\n \"\"\"Return whether fired cron jobs are waiting to be delivered.\"\"\"\n with cron_lock:\n return bool(cron_queue)\n\n\n# Load durable jobs on startup, then start scheduler thread\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\nprint(\" \\033[35m[cron] scheduler thread started\\033[0m\")\n\n\n# ── Cron Tools ──\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' → {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs. Use schedule_cron to add one.\"\n lines = []\n for j in jobs:\n tag = \"recurring\" if j.recurring else \"one-shot\"\n dur = \"durable\" if j.durable else \"session\"\n lines.append(f\" {j.id}: '{j.cron}' → {j.prompt[:40]} \"\n f\"[{tag}, {dur}]\")\n return \"\\n\".join(lines)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": \"Schedule a cron job. cron is 5-field: min hour dom month dow.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"cron\": {\"type\": \"string\",\n \"description\": \"5-field cron expression\"},\n \"prompt\": {\"type\": \"string\",\n \"description\": \"Message to inject when fired\"},\n \"recurring\": {\"type\": \"boolean\",\n \"description\": \"True=recurring, False=one-shot\"},\n \"durable\": {\"type\": \"boolean\",\n \"description\": \"True=persist to disk\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\",\n \"description\": \"List all registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"cancel_cron\",\n \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": [t[\"name\"] for t in TOOLS],\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop (simplified, focused on cron scheduler) ──\n# Teaching code keeps a basic agent loop. S11's full error recovery is omitted.\n# cron_scheduler_loop produces work; queue_processor_loop wakes this loop when\n# queued work exists and no other agent turn is running.\n\ndef agent_loop(messages: list, context: dict) -> dict:\n system = get_system_prompt(context)\n while True:\n # Layer 4: consume fired cron jobs → inject as messages\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[inject cron] {job.prompt[:50]}\\033[0m\")\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return context\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return context\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Merge background tool results + notifications into one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nsession_history: list = []\nsession_context = update_context({}, [])\n\n\ndef print_latest_assistant_text(messages: list):\n \"\"\"Print text blocks from the latest assistant message.\"\"\"\n if not messages:\n return\n msg = messages[-1]\n if not isinstance(msg, dict) or msg.get(\"role\") != \"assistant\":\n return\n content = msg.get(\"content\", \"\")\n if isinstance(content, str):\n print(content)\n return\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n\ndef run_agent_turn_locked(user_query: str | None = None):\n \"\"\"Run one agent turn. Caller must hold agent_lock.\"\"\"\n global session_context\n if user_query is not None:\n session_history.append({\"role\": \"user\", \"content\": user_query})\n session_context = agent_loop(session_history, session_context)\n session_context = update_context(session_context, session_history)\n print_latest_assistant_text(session_history)\n print()\n\n\ndef queue_processor_loop():\n \"\"\"Auto-deliver fired cron jobs when the agent is idle.\"\"\"\n global session_context\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if not has_cron_queue():\n continue\n print(\"\\n \\033[35m[queue processor] delivering scheduled work\\033[0m\")\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n\n\nif __name__ == \"__main__\":\n print(\"s14: cron scheduler\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n threading.Thread(target=queue_processor_loop, daemon=True).start()\n print(\" \\033[35m[queue processor] started\\033[0m\")\n while True:\n try:\n query = input(\"\\033[36ms14 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n with agent_lock:\n run_agent_turn_locked(query)\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns14: Cron Scheduler — independent daemon thread + queue processor.\n\nRun: python s14_cron_scheduler/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s13:\n - CronJob dataclass (id, cron, prompt, recurring, durable)\n - cron_matches: 5-field cron expression matching with DOM/DOW OR semantics\n - schedule_job / cancel_job: register/remove cron jobs (with validation)\n - cron_scheduler_loop: independent daemon thread, polls every 1s\n - cron_queue: thread-safe queue, scheduler writes, queue processor delivers\n - queue_processor_loop: auto-runs agent_loop when cron_queue has work\n - Durable storage: .scheduled_tasks.json (survives restart)\n - 3 new tools: schedule_cron, list_crons, cancel_cron\n\nFour layers:\n 1. Scheduler: daemon thread checks time → fires matching jobs\n 2. Queue: cron_queue decouples scheduler from agent loop\n 3. Queue processor: wakes the agent when queued work exists and it is idle\n 4. Consumer: agent_loop consumes queued jobs and injects them into messages\n\"\"\"\n\nimport os, subprocess, json, time, random, threading\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\n# ── Background Tasks (from s13, synced) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron, \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n }.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\n# ── Cron Scheduler (s14 new) ──\n\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"\n prompt: str # message to inject when fired\n recurring: bool # True = recurring, False = one-shot\n durable: bool # True = persist to disk\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\nagent_lock = threading.Lock()\n_last_fired: dict[str, str] = {} # job_id → \"YYYY-MM-DD HH:MM\"\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n \"\"\"Match a single cron field against a value.\"\"\"\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(f.strip(), value)\n for f in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n \"\"\"Check if a 5-field cron expression matches the given datetime.\n Standard cron semantics: DOM and DOW use OR when both are constrained.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n # Minute, hour, month must all match\n if not (m and h and month_ok):\n return False\n # DOM and DOW: if both constrained, either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n \"\"\"Validate a single cron field value is within [lo, hi].\"\"\"\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step_str = field[2:]\n if not step_str.isdigit():\n return f\"Invalid step: {field}\"\n step = int(step_str)\n if step <= 0:\n return f\"Step must be > 0: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err: return err\n return None\n if \"-\" in field:\n parts = field.split(\"-\", 1)\n if not parts[0].isdigit() or not parts[1].isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(parts[0]), int(parts[1])\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n val = int(field)\n if val < lo or val > hi:\n return f\"Value {val} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n \"\"\"Validate a cron expression. Returns error message or None.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n \"\"\"Persist durable jobs to .scheduled_tasks.json.\"\"\"\n durable = [asdict(j) for j in scheduled_jobs.values() if j.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n \"\"\"Load durable jobs from disk on startup.\"\"\"\n if not DURABLE_PATH.exists():\n return\n try:\n jobs = json.loads(DURABLE_PATH.read_text())\n for j in jobs:\n job = CronJob(**j)\n err = validate_cron(job.cron)\n if err:\n print(f\" \\033[31m[cron] skipping invalid job {job.id}: {err}\\033[0m\")\n continue\n scheduled_jobs[job.id] = job\n valid = [j for j in jobs if j[\"id\"] in scheduled_jobs]\n if valid:\n print(f\" \\033[35m[cron] loaded {len(valid)} durable job(s)\\033[0m\")\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str, recurring: bool = True,\n durable: bool = True) -> CronJob | str:\n \"\"\"Register a new cron job. Returns CronJob or error string.\"\"\"\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable,\n )\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n print(f\" \\033[35m[cron register] {job.id} '{cron}' → {prompt[:40]}\\033[0m\")\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n \"\"\"Cancel a cron job.\"\"\"\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n print(f\" \\033[31m[cron cancel] {job_id}\\033[0m\")\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n \"\"\"Independent daemon thread: poll every 1s, fire matching jobs.\n Individual job errors are caught to prevent one bad job from\n killing the entire scheduler thread.\"\"\"\n while True:\n time.sleep(1)\n now = datetime.now()\n # Date-aware marker prevents daily jobs from skipping on day 2+\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n print(f\" \\033[35m[cron fire] {job.id} → \"\n f\"{job.prompt[:40]}\\033[0m\")\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n \"\"\"Consume fired jobs from cron_queue (called by agent_loop).\"\"\"\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\ndef has_cron_queue() -> bool:\n \"\"\"Return whether fired cron jobs are waiting to be delivered.\"\"\"\n with cron_lock:\n return bool(cron_queue)\n\n\n# Load durable jobs on startup, then start scheduler thread\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\nprint(\" \\033[35m[cron] scheduler thread started\\033[0m\")\n\n\n# ── Cron Tools ──\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' → {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs. Use schedule_cron to add one.\"\n lines = []\n for j in jobs:\n tag = \"recurring\" if j.recurring else \"one-shot\"\n dur = \"durable\" if j.durable else \"session\"\n lines.append(f\" {j.id}: '{j.cron}' → {j.prompt[:40]} \"\n f\"[{tag}, {dur}]\")\n return \"\\n\".join(lines)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": \"Schedule a cron job. cron is 5-field: min hour dom month dow.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"cron\": {\"type\": \"string\",\n \"description\": \"5-field cron expression\"},\n \"prompt\": {\"type\": \"string\",\n \"description\": \"Message to inject when fired\"},\n \"recurring\": {\"type\": \"boolean\",\n \"description\": \"True=recurring, False=one-shot\"},\n \"durable\": {\"type\": \"boolean\",\n \"description\": \"True=persist to disk\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\",\n \"description\": \"List all registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"cancel_cron\",\n \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": [t[\"name\"] for t in TOOLS],\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop (focused on cron scheduling) ──\n# Error recovery remains the independent layer introduced in s11.\n# cron_scheduler_loop produces work; queue_processor_loop wakes this loop when\n# queued work exists and no other agent turn is running.\n\ndef agent_loop(messages: list, context: dict) -> dict:\n system = get_system_prompt(context)\n while True:\n # Layer 4: consume fired cron jobs → inject as messages\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[inject cron] {job.prompt[:50]}\\033[0m\")\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return context\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return context\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Merge background tool results + notifications into one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nsession_history: list = []\nsession_context = update_context({}, [])\n\n\ndef print_latest_assistant_text(messages: list):\n \"\"\"Print text blocks from the latest assistant message.\"\"\"\n if not messages:\n return\n msg = messages[-1]\n if not isinstance(msg, dict) or msg.get(\"role\") != \"assistant\":\n return\n content = msg.get(\"content\", \"\")\n if isinstance(content, str):\n print(content)\n return\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n\ndef run_agent_turn_locked(user_query: str | None = None):\n \"\"\"Run one agent turn. Caller must hold agent_lock.\"\"\"\n global session_context\n if user_query is not None:\n session_history.append({\"role\": \"user\", \"content\": user_query})\n session_context = agent_loop(session_history, session_context)\n session_context = update_context(session_context, session_history)\n print_latest_assistant_text(session_history)\n print()\n\n\ndef queue_processor_loop():\n \"\"\"Auto-deliver fired cron jobs when the agent is idle.\"\"\"\n global session_context\n while True:\n time.sleep(0.2)\n if not has_cron_queue():\n continue\n if not agent_lock.acquire(blocking=False):\n continue\n try:\n if not has_cron_queue():\n continue\n print(\"\\n \\033[35m[queue processor] delivering scheduled work\\033[0m\")\n run_agent_turn_locked()\n finally:\n agent_lock.release()\n\n\nif __name__ == \"__main__\":\n print(\"s14: cron scheduler\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n threading.Thread(target=queue_processor_loop, daemon=True).start()\n print(\" \\033[35m[queue processor] started\\033[0m\")\n while True:\n try:\n query = input(\"\\033[36ms14 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n with agent_lock:\n run_agent_turn_locked(query)\n", "images": [ { "src": "/course-assets/s14_cron_scheduler/cron-scheduler-overview.svg", @@ -1776,14 +1772,15 @@ { "id": "s15", "filename": "s15_agent_teams/code.py", - "title": "Agent Teams: Runtime Lab", - "subtitle": "Persistent Teammates and Mailboxes", - "loc": 786, + "title": "Agent Teams", + "subtitle": "Persistent Teammates and Coordination Protocols", + "loc": 1078, "tools": [ "bash", "read_file", "write_file", "send_message", + "submit_plan", "create_task", "list_tasks", "get_task", @@ -1793,246 +1790,315 @@ "list_crons", "cancel_cron", "spawn_teammate", - "check_inbox" + "request_shutdown", + "request_plan", + "review_plan" ], "newTools": [ "send_message", + "submit_plan", "spawn_teammate", - "check_inbox" + "request_shutdown", + "request_plan", + "review_plan" ], - "coreAddition": "Teammate mailboxes", - "keyInsight": "Persistent teammates let work continue in parallel without stuffing every thought into one context.", + "coreAddition": "Team runtime and typed protocols", + "keyInsight": "A Lead can coordinate persistent teammates when message delivery, approval, and shutdown belong to the runtime.", "classes": [ { "name": "Task", - "startLine": 54, - "endLine": 62 + "startLine": 52, + "endLine": 60 }, { "name": "CronJob", - "startLine": 360, - "endLine": 367 + "startLine": 370, + "endLine": 377 }, { "name": "MessageBus", - "startLine": 602, - "endLine": 634 + "startLine": 616, + "endLine": 674 + }, + { + "name": "ProtocolState", + "startLine": 685, + "endLine": 694 } ], "functions": [ { "name": "_task_path", "signature": "def _task_path(task_id: str)", - "startLine": 63 + "startLine": 61 }, { "name": "save_task", "signature": "def save_task(task: Task)", - "startLine": 79 + "startLine": 77 }, { "name": "load_task", "signature": "def load_task(task_id: str)", - "startLine": 83 + "startLine": 81 }, { "name": "list_tasks", "signature": "def list_tasks()", - "startLine": 87 + "startLine": 85 }, { "name": "get_task", "signature": "def get_task(task_id: str)", - "startLine": 92 + "startLine": 90 }, { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 98 + "startLine": 96 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 110 + "startLine": 108 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 125 + "startLine": 123 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 154 + "startLine": 160 }, { "name": "get_system_prompt", "signature": "def get_system_prompt(context: dict)", - "startLine": 167 + "startLine": 174 }, { "name": "safe_path", "signature": "def safe_path(p: str)", - "startLine": 179 + "startLine": 186 }, { "name": "run_bash", "signature": "def run_bash(command: str, run_in_background: bool = False)", - "startLine": 186 + "startLine": 193 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None)", - "startLine": 197 + "startLine": 204 }, { "name": "run_write", "signature": "def run_write(path: str, content: str)", - "startLine": 207 + "startLine": 214 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 227 + "startLine": 234 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 242 + "startLine": 249 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 249 + "startLine": 256 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 253 + "startLine": 260 }, { "name": "is_slow_operation", "signature": "def is_slow_operation(tool_name: str, tool_input: dict)", - "startLine": 265 + "startLine": 272 }, { "name": "should_run_background", "signature": "def should_run_background(tool_name: str, tool_input: dict)", - "startLine": 276 + "startLine": 283 }, { "name": "execute_tool", "signature": "def execute_tool(block)", - "startLine": 283 + "startLine": 290 }, { "name": "start_background_task", "signature": "def start_background_task(block)", - "startLine": 300 + "startLine": 310 }, { "name": "collect_background_results", "signature": "def collect_background_results()", - "startLine": 324 + "startLine": 334 }, { "name": "has_pending_background", "signature": "def has_pending_background()", - "startLine": 347 + "startLine": 357 }, { "name": "_cron_field_matches", "signature": "def _cron_field_matches(field: str, value: int)", - "startLine": 374 + "startLine": 384 }, { "name": "cron_matches", "signature": "def cron_matches(cron_expr: str, dt: datetime)", - "startLine": 390 + "startLine": 400 }, { "name": "_validate_cron_field", "signature": "def _validate_cron_field(field: str, lo: int, hi: int)", - "startLine": 420 + "startLine": 430 }, { "name": "validate_cron", "signature": "def validate_cron(cron_expr: str)", - "startLine": 455 + "startLine": 465 }, { "name": "save_durable_jobs", "signature": "def save_durable_jobs()", - "startLine": 469 + "startLine": 479 }, { "name": "load_durable_jobs", "signature": "def load_durable_jobs()", - "startLine": 475 + "startLine": 485 }, { "name": "cancel_job", "signature": "def cancel_job(job_id: str)", - "startLine": 514 + "startLine": 524 }, { "name": "cron_scheduler_loop", "signature": "def cron_scheduler_loop()", - "startLine": 526 + "startLine": 536 }, { "name": "consume_cron_queue", "signature": "def consume_cron_queue()", - "startLine": 552 + "startLine": 562 }, { "name": "run_list_crons", "signature": "def run_list_crons()", - "startLine": 576 + "startLine": 586 }, { "name": "run_cancel_cron", "signature": "def run_cancel_cron(job_id: str)", - "startLine": 590 + "startLine": 600 + }, + { + "name": "is_valid_agent_name", + "signature": "def is_valid_agent_name(name: str)", + "startLine": 612 + }, + { + "name": "new_request_id", + "signature": "def new_request_id()", + "startLine": 698 + }, + { + "name": "consume_lead_inbox", + "signature": "def consume_lead_inbox()", + "startLine": 733 + }, + { + "name": "format_team_events", + "signature": "def format_team_events(msgs: list[dict])", + "startLine": 746 + }, + { + "name": "_last_assistant_text", + "signature": "def _last_assistant_text(content)", + "startLine": 758 + }, + { + "name": "_teammate_submit_plan", + "signature": "def _teammate_submit_plan(from_name: str, plan: str)", + "startLine": 767 + }, + { + "name": "_run_teammate_tool", + "signature": "def _run_teammate_tool(name: str, block, handlers: dict)", + "startLine": 788 + }, + { + "name": "apply_plan_response", + "signature": "def apply_plan_response(name: str, msg: dict)", + "startLine": 798 + }, + { + "name": "apply_shutdown_request", + "signature": "def apply_shutdown_request(name: str, msg: dict)", + "startLine": 826 + }, + { + "name": "_teammate_send_message", + "signature": "def _teammate_send_message(from_name: str, to: str, content: str)", + "startLine": 847 }, { "name": "spawn_teammate_thread", "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", - "startLine": 643 + "startLine": 857 }, { "name": "run_spawn_teammate", "signature": "def run_spawn_teammate(name: str, role: str, prompt: str)", - "startLine": 731 + "startLine": 1000 }, { "name": "run_send_message", "signature": "def run_send_message(to: str, content: str)", - "startLine": 735 + "startLine": 1004 }, { - "name": "run_check_inbox", - "signature": "def run_check_inbox()", - "startLine": 740 + "name": "run_request_shutdown", + "signature": "def run_request_shutdown(teammate: str)", + "startLine": 1011 + }, + { + "name": "run_request_plan", + "signature": "def run_request_plan(teammate: str, task: str)", + "startLine": 1029 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 842 + "startLine": 1168 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 861 + "startLine": 1186 } ], "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns15: Agent Teams — MessageBus + spawn_teammate_thread + inbox injection.\n\nRun: python s15_agent_teams/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s14:\n - MessageBus class: file-based mailboxes (.mailboxes/*.jsonl)\n - spawn_teammate_thread: creates teammate in background thread\n - Teammate runs own simplified agent_loop (bash, read, write, send_message)\n - Lead tools: spawn_teammate, send_message, check_inbox (3 new)\n - Lead inbox: teammate messages injected into history (not just printed)\n - Teaching version: teammates limited to 10 rounds (real CC uses idle loop)\n\nASCII flow:\n Lead: cron_queue → messages → prompt → LLM → TOOLS ────→ loop\n ↑ ↓ |\n └── inbox ← MessageBus ← teammate.send_message ←┘\n Teammate: inbox → LLM → bash/read/write/send → loop (max 10 turns)\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, queue\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"get_task, create_task, list_tasks, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron, \"\n \"spawn_teammate, send_message, check_inbox.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\n# ── Background Tasks (from s13, synced) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron, \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message, \"check_inbox\": run_check_inbox,\n }.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\ndef has_pending_background() -> bool:\n \"\"\"Non-destructive: True if any background task has completed and is\n waiting to be collected. The inbox poller uses this in its wake condition.\"\"\"\n with background_lock:\n return any(t[\"status\"] == \"completed\" for t in background_tasks.values())\n\n\n# ── Cron Scheduler (from s14, synced) ──\n\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"\n prompt: str # message to inject when fired\n recurring: bool # True = recurring, False = one-shot\n durable: bool # True = persist to disk\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\n_last_fired: dict[str, str] = {} # job_id → \"YYYY-MM-DD HH:MM\"\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n \"\"\"Match a single cron field against a value.\"\"\"\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(f.strip(), value)\n for f in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n \"\"\"Check if a 5-field cron expression matches the given datetime.\n Standard cron semantics: DOM and DOW use OR when both are constrained.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n # Minute, hour, month must all match\n if not (m and h and month_ok):\n return False\n # DOM and DOW: if both constrained, either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n \"\"\"Validate a single cron field value is within [lo, hi].\"\"\"\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step_str = field[2:]\n if not step_str.isdigit():\n return f\"Invalid step: {field}\"\n step = int(step_str)\n if step <= 0:\n return f\"Step must be > 0: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err: return err\n return None\n if \"-\" in field:\n parts = field.split(\"-\", 1)\n if not parts[0].isdigit() or not parts[1].isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(parts[0]), int(parts[1])\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n val = int(field)\n if val < lo or val > hi:\n return f\"Value {val} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n \"\"\"Validate a cron expression. Returns error message or None.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n \"\"\"Persist durable jobs to .scheduled_tasks.json.\"\"\"\n durable = [asdict(j) for j in scheduled_jobs.values() if j.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n \"\"\"Load durable jobs from disk on startup.\"\"\"\n if not DURABLE_PATH.exists():\n return\n try:\n jobs = json.loads(DURABLE_PATH.read_text())\n for j in jobs:\n job = CronJob(**j)\n err = validate_cron(job.cron)\n if err:\n print(f\" \\033[31m[cron] skipping invalid job {job.id}: {err}\\033[0m\")\n continue\n scheduled_jobs[job.id] = job\n valid = [j for j in jobs if j[\"id\"] in scheduled_jobs]\n if valid:\n print(f\" \\033[35m[cron] loaded {len(valid)} durable job(s)\\033[0m\")\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str, recurring: bool = True,\n durable: bool = True) -> CronJob | str:\n \"\"\"Register a new cron job. Returns CronJob or error string.\"\"\"\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable,\n )\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n print(f\" \\033[35m[cron register] {job.id} '{cron}' → {prompt[:40]}\\033[0m\")\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n \"\"\"Cancel a cron job.\"\"\"\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n print(f\" \\033[31m[cron cancel] {job_id}\\033[0m\")\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n \"\"\"Independent daemon thread: poll every 1s, fire matching jobs.\n Individual job errors are caught to prevent one bad job from\n killing the entire scheduler thread.\"\"\"\n while True:\n time.sleep(1)\n now = datetime.now()\n # Date-aware marker prevents daily jobs from skipping on day 2+\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n print(f\" \\033[35m[cron fire] {job.id} → \"\n f\"{job.prompt[:40]}\\033[0m\")\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n \"\"\"Consume fired jobs from cron_queue (called by agent_loop).\"\"\"\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\n# Load durable jobs on startup, then start scheduler thread\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\nprint(\" \\033[35m[cron] scheduler thread started\\033[0m\")\n\n\n# Cron tool handlers\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' → {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs. Use schedule_cron to add one.\"\n lines = []\n for j in jobs:\n tag = \"recurring\" if j.recurring else \"one-shot\"\n dur = \"durable\" if j.durable else \"session\"\n lines.append(f\" {j.id}: '{j.cron}' → {j.prompt[:40]} \"\n f\"[{tag}, {dur}]\")\n return \"\\n\".join(lines)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\n# ── MessageBus (s15 new) ──\n# Teaching version uses simple file append + unlink.\n# Real CC uses proper-lockfile for concurrent write safety.\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\n\n\nclass MessageBus:\n \"\"\"File-based message bus. Each agent has a .jsonl inbox.\n Read is destructive: read_text + unlink (consumes messages).\n Teaching version: no file locking; real CC uses proper-lockfile.\"\"\"\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\"):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time()}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"{content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink() # consume: read + delete\n return msgs\n\n def peek(self, agent: str) -> bool:\n \"\"\"Non-destructive: True if the agent has unread inbox messages.\n The Lead's inbox poller uses this to decide whether to wake a turn\n without consuming the mailbox.\"\"\"\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n return inbox.exists() and inbox.stat().st_size > 0\n\n\nBUS = MessageBus()\n\n# Track spawned teammates\nactive_teammates: dict[str, bool] = {}\n\n\n# ── Teammate Thread (s15 new) ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n \"\"\"Spawn a teammate agent in a background thread.\n Teaching version: max 10 rounds per teammate.\n Real CC: teammates use idle loop (wait for inbox, work, repeat)\n until shutdown_request.\"\"\"\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n\n system = (f\"You are '{name}', a {role}. \"\n f\"Use tools to complete tasks. \"\n f\"Send results via send_message to 'lead'.\")\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send a message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n ]\n sub_handlers = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"send_message\": lambda to, content: (BUS.send(name, to, content),\n \"Sent\")[1],\n }\n\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n if inbox:\n messages.append({\"role\": \"user\",\n \"content\": f\"{json.dumps(inbox)}\"})\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n handler = sub_handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # Send final summary to Lead\n summary = \"Done.\"\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\" and isinstance(msg[\"content\"], list):\n for b in msg[\"content\"]:\n if getattr(b, \"type\", None) == \"text\":\n summary = b.text\n break\n else:\n continue\n break\n BUS.send(name, \"lead\", summary, \"result\")\n active_teammates.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n active_teammates[name] = True\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role}\"\n\n\n# ── Team Tool Handlers (s15 new) ──\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\ndef run_check_inbox() -> str:\n msgs = BUS.read_inbox(\"lead\")\n if not msgs:\n return \"(inbox empty)\"\n lines = []\n for m in msgs:\n lines.append(f\" [{m['from']}] {m['content'][:200]}\")\n return \"\\n\".join(lines)\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": \"Schedule a cron job. cron is 5-field: min hour dom month dow.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"cron\": {\"type\": \"string\",\n \"description\": \"5-field cron expression\"},\n \"prompt\": {\"type\": \"string\",\n \"description\": \"Message to inject when fired\"},\n \"recurring\": {\"type\": \"boolean\",\n \"description\": \"True=recurring, False=one-shot\"},\n \"durable\": {\"type\": \"boolean\",\n \"description\": \"True=persist to disk\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\",\n \"description\": \"List all registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"cancel_cron\",\n \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn a teammate agent in a background thread.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send a message to a teammate via MessageBus.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"check_inbox\",\n \"description\": \"Check Lead's inbox for teammate messages.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": [t[\"name\"] for t in TOOLS],\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n# Teaching code keeps a basic agent loop. S11's full error recovery is omitted.\n# Cron queue is consumed when agent_loop is called; real CC auto-wakes via\n# queue processor (useQueueProcessor.ts) when items arrive.\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n # Consume fired cron jobs → inject as messages\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[inject cron] {job.prompt[:50]}\\033[0m\")\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Merge background tool results + notifications into one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s15: agent teams\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n\n # input() and a 1s poller (teammate inbox or background results) feed one\n # event queue (issues #291, #46).\n events = queue.Queue()\n\n def input_reader():\n while True:\n try:\n line = input(\"\\033[36ms15 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n events.put((\"quit\", None))\n return\n events.put((\"user\", line))\n\n def inbox_poller():\n # Poll ~1s and wake the Lead when async results are ready: teammate\n # inbox messages or completed background tasks. Don't gate on\n # active_teammates: a teammate sends its result and then removes itself,\n # so the final message can outlive its registry entry.\n while True:\n time.sleep(1)\n if BUS.peek(\"lead\") or has_pending_background():\n events.put((\"wake\", None))\n\n threading.Thread(target=input_reader, daemon=True).start()\n threading.Thread(target=inbox_poller, daemon=True).start()\n\n had_teammates = False\n while True:\n kind, payload = events.get()\n if kind == \"quit\":\n break\n if kind == \"user\":\n if payload.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": payload})\n else: # \"wake\": teammate inbox or background results are ready\n parts = []\n inbox = BUS.read_inbox(\"lead\")\n if inbox:\n parts.append(\"[Inbox]\\n\" + \"\\n\".join(\n f\"From {m['from']}: {m['content'][:200]}\" for m in inbox))\n bg = collect_background_results()\n parts.extend(bg)\n if not parts:\n continue # already drained by an earlier wake (idempotent)\n history.append({\"role\": \"user\", \"content\": \"\\n\".join(parts)})\n print(f\"\\n\\033[33m[wake: {len(inbox)} inbox + {len(bg)} background \"\n f\"-> new turn]\\033[0m\")\n\n # One turn for whichever source woke us.\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n # Announce once when every teammate has finished and its output drained.\n if active_teammates:\n had_teammates = True\n elif had_teammates and not BUS.peek(\"lead\") and not has_pending_background():\n print(\"\\033[32m[all teammates done]\\033[0m\")\n had_teammates = False\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns15: Agent Teams — persistent teammates, mailboxes, and typed protocols.\n\nRun: python s15_agent_teams/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s14:\n - MessageBus: thread-safe, file-backed mailboxes (.mailboxes/*.jsonl)\n - Persistent teammate loops with WORK and IDLE states\n - Runtime delivery of teammate results and idle notifications to Lead\n - Typed shutdown and plan-approval protocols with request_id matching\n - Plan approval gates bash and write_file until Lead approves\n\nASCII flow:\n User → Lead → spawn_teammate → teammate WORK → result → IDLE\n ↑ ↓ |\n └──────── MessageBus + typed protocol ┘\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, queue, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"get_task, create_task, list_tasks, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron, \"\n \"spawn_teammate, send_message, request_shutdown, \"\n \"request_plan, review_plan.\",\n \"teams\": (\n \"When parallel work would help, first propose a small team with clear \"\n \"responsibilities and wait for the user's confirmation. Do not call \"\n \"spawn_teammate before the user confirms. After confirmation, delegate \"\n \"independent work, react to team events delivered by the runtime, and \"\n \"shut teammates down when coordination is complete.\"\n ),\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"teams\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\n# ── Background Tasks (from s13, synced) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron, \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan,\n \"review_plan\": run_review_plan,\n }.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\ndef has_pending_background() -> bool:\n \"\"\"Non-destructive: True if any background task has completed and is\n waiting to be collected. The inbox poller uses this in its wake condition.\"\"\"\n with background_lock:\n return any(t[\"status\"] == \"completed\" for t in background_tasks.values())\n\n\n# ── Cron Scheduler (from s14, synced) ──\n\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"\n prompt: str # message to inject when fired\n recurring: bool # True = recurring, False = one-shot\n durable: bool # True = persist to disk\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\n_last_fired: dict[str, str] = {} # job_id → \"YYYY-MM-DD HH:MM\"\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n \"\"\"Match a single cron field against a value.\"\"\"\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(f.strip(), value)\n for f in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n \"\"\"Check if a 5-field cron expression matches the given datetime.\n Standard cron semantics: DOM and DOW use OR when both are constrained.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n # Minute, hour, month must all match\n if not (m and h and month_ok):\n return False\n # DOM and DOW: if both constrained, either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n \"\"\"Validate a single cron field value is within [lo, hi].\"\"\"\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step_str = field[2:]\n if not step_str.isdigit():\n return f\"Invalid step: {field}\"\n step = int(step_str)\n if step <= 0:\n return f\"Step must be > 0: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err: return err\n return None\n if \"-\" in field:\n parts = field.split(\"-\", 1)\n if not parts[0].isdigit() or not parts[1].isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(parts[0]), int(parts[1])\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n val = int(field)\n if val < lo or val > hi:\n return f\"Value {val} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n \"\"\"Validate a cron expression. Returns error message or None.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n \"\"\"Persist durable jobs to .scheduled_tasks.json.\"\"\"\n durable = [asdict(j) for j in scheduled_jobs.values() if j.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n \"\"\"Load durable jobs from disk on startup.\"\"\"\n if not DURABLE_PATH.exists():\n return\n try:\n jobs = json.loads(DURABLE_PATH.read_text())\n for j in jobs:\n job = CronJob(**j)\n err = validate_cron(job.cron)\n if err:\n print(f\" \\033[31m[cron] skipping invalid job {job.id}: {err}\\033[0m\")\n continue\n scheduled_jobs[job.id] = job\n valid = [j for j in jobs if j[\"id\"] in scheduled_jobs]\n if valid:\n print(f\" \\033[35m[cron] loaded {len(valid)} durable job(s)\\033[0m\")\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str, recurring: bool = True,\n durable: bool = True) -> CronJob | str:\n \"\"\"Register a new cron job. Returns CronJob or error string.\"\"\"\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable,\n )\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n print(f\" \\033[35m[cron register] {job.id} '{cron}' → {prompt[:40]}\\033[0m\")\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n \"\"\"Cancel a cron job.\"\"\"\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n print(f\" \\033[31m[cron cancel] {job_id}\\033[0m\")\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n \"\"\"Independent daemon thread: poll every 1s, fire matching jobs.\n Individual job errors are caught to prevent one bad job from\n killing the entire scheduler thread.\"\"\"\n while True:\n time.sleep(1)\n now = datetime.now()\n # Date-aware marker prevents daily jobs from skipping on day 2+\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n print(f\" \\033[35m[cron fire] {job.id} → \"\n f\"{job.prompt[:40]}\\033[0m\")\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n \"\"\"Consume fired jobs from cron_queue (called by agent_loop).\"\"\"\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\n# Load durable jobs on startup, then start scheduler thread\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\nprint(\" \\033[35m[cron] scheduler thread started\\033[0m\")\n\n\n# Cron tool handlers\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' → {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs. Use schedule_cron to add one.\"\n lines = []\n for j in jobs:\n tag = \"recurring\" if j.recurring else \"one-shot\"\n dur = \"durable\" if j.durable else \"session\"\n lines.append(f\" {j.id}: '{j.cron}' → {j.prompt[:40]} \"\n f\"[{tag}, {dur}]\")\n return \"\\n\".join(lines)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\n# ── MessageBus + Team Protocols (s15 new) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\nMAILBOX_ROOT = MAILBOX_DIR.resolve()\nVALID_AGENT_NAME = re.compile(r\"^[A-Za-z0-9_-]{1,64}$\")\n\n\ndef is_valid_agent_name(name: str) -> bool:\n return bool(VALID_AGENT_NAME.fullmatch(name))\n\n\nclass MessageBus:\n \"\"\"Thread-safe file mailboxes with destructive reads.\"\"\"\n\n def __init__(self):\n self._lock = threading.RLock()\n self._changed = threading.Condition(self._lock)\n\n def _path(self, agent: str) -> Path:\n if not is_valid_agent_name(agent):\n raise ValueError(f\"Invalid mailbox recipient: {agent!r}\")\n path = (MAILBOX_DIR / f\"{agent}.jsonl\").resolve()\n if not path.is_relative_to(MAILBOX_ROOT):\n raise ValueError(f\"Mailbox path escapes directory: {agent!r}\")\n return path\n\n def _read_unlocked(self, agent: str) -> list[dict]:\n inbox = self._path(agent)\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict | None = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n with self._changed:\n with open(self._path(to_agent), \"a\") as f:\n f.write(json.dumps(msg, ensure_ascii=False) + \"\\n\")\n self._changed.notify_all()\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n with self._lock:\n return self._read_unlocked(agent)\n\n def peek(self, agent: str) -> bool:\n with self._lock:\n inbox = self._path(agent)\n return inbox.exists() and inbox.stat().st_size > 0\n\n def wait_for_messages(self, agent: str,\n timeout: float | None = None) -> list[dict]:\n \"\"\"Block until the agent has messages or timeout expires.\"\"\"\n deadline = None if timeout is None else time.monotonic() + timeout\n with self._changed:\n while not self.peek(agent):\n remaining = (None if deadline is None\n else deadline - time.monotonic())\n if remaining is not None and remaining <= 0:\n return []\n self._changed.wait(remaining)\n return self._read_unlocked(agent)\n\n\nBUS = MessageBus()\n\n# working | waiting_approval | idle | stopping\nactive_teammates: dict[str, str] = {}\nplan_gates: dict[str, str] = {}\nplan_request_ids: dict[str, str] = {}\nteam_lock = threading.RLock()\n\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n while True:\n request_id = f\"req_{random.randint(0, 999999):06d}\"\n if request_id not in pending_requests:\n return request_id\n\n\ndef match_response(response_type: str, request_id: str, approve: bool,\n from_agent: str, to_agent: str) -> bool:\n \"\"\"Match one protocol response to one pending request.\"\"\"\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return False\n expected = {\n \"shutdown\": \"shutdown_response\",\n \"plan_approval\": \"plan_approval_response\",\n }[state.type]\n if response_type != expected:\n print(f\" \\033[31m[protocol] expected {expected}, \"\n f\"got {response_type}\\033[0m\")\n return False\n if from_agent != state.target or to_agent != state.sender:\n print(f\" \\033[31m[protocol] {request_id} responder mismatch\\033[0m\")\n return False\n if state.status != \"pending\":\n print(f\" \\033[33m[protocol] {request_id} already \"\n f\"{state.status}\\033[0m\")\n return False\n state.status = \"approved\" if approve else \"rejected\"\n print(f\" \\033[35m[protocol] {request_id} → {state.status}\\033[0m\")\n return True\n\n\ndef consume_lead_inbox() -> list[dict]:\n \"\"\"Consume Lead events and update protocol state before model delivery.\"\"\"\n msgs = BUS.read_inbox(\"lead\")\n for msg in msgs:\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n if request_id and msg.get(\"type\", \"\").endswith(\"_response\"):\n match_response(msg[\"type\"], request_id,\n metadata.get(\"approve\", False),\n msg.get(\"from\", \"\"), msg.get(\"to\", \"\"))\n return msgs\n\n\ndef format_team_events(msgs: list[dict]) -> str:\n lines = []\n for msg in msgs:\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\")\n suffix = f\" request_id={request_id}\" if request_id else \"\"\n lines.append(\n f\"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}\"\n )\n return \"[Team events]\\n\" + \"\\n\".join(lines)\n\n\ndef _last_assistant_text(content) -> str:\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n return block.text.strip()\n if isinstance(block, dict) and block.get(\"type\") == \"text\":\n return str(block.get(\"text\", \"\")).strip()\n return \"\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n with team_lock:\n if plan_gates.get(from_name) == \"pending\":\n return \"A plan is already waiting for review.\"\n request_id = new_request_id()\n pending_requests[request_id] = ProtocolState(\n request_id=request_id,\n type=\"plan_approval\",\n sender=from_name,\n target=\"lead\",\n status=\"pending\",\n payload=plan,\n )\n plan_gates[from_name] = \"pending\"\n plan_request_ids[from_name] = request_id\n active_teammates[from_name] = \"waiting_approval\"\n BUS.send(from_name, \"lead\", plan, \"plan_approval_request\",\n {\"request_id\": request_id})\n return f\"Plan submitted ({request_id}). Wait for Lead's decision.\"\n\n\ndef _run_teammate_tool(name: str, block, handlers: dict) -> str:\n gate = plan_gates.get(name, \"not_required\")\n if block.name in {\"bash\", \"write_file\"} and gate != \"not_required\":\n if gate != \"approved\":\n return (f\"Blocked: plan status is {gate}. Submit or revise the \"\n \"plan and wait for approval before changing the workspace.\")\n handler = handlers.get(block.name)\n return str(handler(**block.input)) if handler else f\"Unknown tool: {block.name}\"\n\n\ndef apply_plan_response(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Apply only the Lead response for this teammate's current plan.\"\"\"\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n expected_id = plan_request_ids.get(name)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and request_id == expected_id\n and state is not None\n and state.type == \"plan_approval\"\n and state.sender == name\n and state.target == \"lead\"\n and state.status in {\"approved\", \"rejected\"}\n and metadata.get(\"approve\", False)\n == (state.status == \"approved\")\n )\n if not valid:\n return False, \"[Ignored plan response: request mismatch]\"\n plan_gates[name] = state.status\n active_teammates[name] = \"working\"\n plan_request_ids.pop(name, None)\n outcome = state.status\n return True, f\"[Plan {outcome}] {msg['content']}\"\n\n\ndef apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Accept only a pending shutdown request sent by Lead to this teammate.\"\"\"\n request_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and state is not None\n and state.type == \"shutdown\"\n and state.sender == \"lead\"\n and state.target == name\n and state.status == \"pending\"\n and active_teammates.get(name) != \"stopping\"\n )\n if not valid:\n return False, \"[Ignored shutdown request: request mismatch]\"\n active_teammates[name] = \"stopping\"\n return True, request_id\n\n\ndef _teammate_send_message(from_name: str, to: str, content: str) -> str:\n with team_lock:\n if to != \"lead\" and to not in active_teammates:\n return f\"Agent '{to}' is not active\"\n BUS.send(from_name, to, content)\n return f\"Sent to {to}\"\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n \"\"\"Spawn a persistent teammate that alternates between WORK and IDLE.\"\"\"\n if not is_valid_agent_name(name):\n return (\"Invalid teammate name: use 1-64 letters, digits, \"\n \"underscores, or dashes\")\n with team_lock:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n active_teammates[name] = \"working\"\n plan_gates[name] = \"not_required\"\n\n system = (f\"You are '{name}', a {role}. \"\n \"Use tools to complete assigned work. \"\n \"When asked for a plan, call submit_plan before bash or \"\n \"write_file and wait for approval. End each assignment with a \"\n \"concise result; the runtime delivers it to Lead.\")\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send a message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a work plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n ]\n sub_handlers = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"send_message\": lambda to, content: _teammate_send_message(\n name, to, content),\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n }\n\n def handle_messages(inbox: list[dict]) -> bool:\n \"\"\"Return True when a shutdown request ends the teammate.\"\"\"\n work_messages = []\n for msg in inbox:\n msg_type = msg.get(\"type\", \"message\")\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n if msg_type == \"shutdown_request\":\n accepted, notice = apply_shutdown_request(name, msg)\n if not accepted:\n work_messages.append(notice)\n continue\n request_id = notice\n BUS.send(name, \"lead\", \"Shutdown acknowledged.\",\n \"shutdown_response\",\n {\"request_id\": request_id, \"approve\": True})\n return True\n if msg_type == \"plan_approval_response\":\n _, notice = apply_plan_response(name, msg)\n work_messages.append(notice)\n continue\n if msg_type == \"plan_request\":\n work_messages.append(\n f\"[Plan required] {msg['content']}\"\n )\n continue\n work_messages.append(\n f\"[Message from {msg['from']}] {msg['content']}\"\n )\n if work_messages:\n messages.append({\"role\": \"user\",\n \"content\": \"\\n\".join(work_messages)})\n return False\n\n should_stop = False\n while not should_stop:\n with team_lock:\n active_teammates[name] = \"working\"\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception as exc:\n BUS.send(name, \"lead\",\n f\"{type(exc).__name__}: {exc}\", \"error\")\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason == \"tool_use\":\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n output = _run_teammate_tool(name, block, sub_handlers)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n continue\n\n summary = _last_assistant_text(response.content)\n gate = plan_gates.get(name, \"not_required\")\n if gate != \"pending\" and summary:\n BUS.send(name, \"lead\", summary, \"result\")\n if gate == \"pending\":\n with team_lock:\n active_teammates[name] = \"waiting_approval\"\n else:\n with team_lock:\n active_teammates[name] = \"idle\"\n BUS.send(name, \"lead\", \"Waiting for more work.\",\n \"idle_notification\")\n\n while True:\n inbox = BUS.wait_for_messages(name)\n should_stop = handle_messages(inbox)\n if should_stop or messages[-1][\"role\"] == \"user\":\n break\n\n with team_lock:\n active_teammates.pop(name, None)\n plan_gates.pop(name, None)\n plan_request_ids.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role}\"\n\n\n# ── Lead Team Tools ──\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n if to not in active_teammates:\n return f\"Teammate '{to}' is not active\"\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\ndef run_request_shutdown(teammate: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n request_id = new_request_id()\n pending_requests[request_id] = ProtocolState(\n request_id=request_id,\n type=\"shutdown\",\n sender=\"lead\",\n target=teammate,\n status=\"pending\",\n payload=\"\",\n )\n BUS.send(\"lead\", teammate, \"Finish the current step and shut down.\",\n \"shutdown_request\", {\"request_id\": request_id})\n return f\"Shutdown requested from {teammate} ({request_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n plan_gates[teammate] = \"required\"\n BUS.send(\"lead\", teammate, task, \"plan_request\")\n return f\"Plan requested from {teammate}\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.type != \"plan_approval\":\n return f\"Request {request_id} is not a plan\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n if plan_request_ids.get(state.sender) != request_id:\n return f\"Request {request_id} is not the current plan\"\n state.status = \"approved\" if approve else \"rejected\"\n content = feedback or (\"Plan approved.\" if approve\n else \"Revise the plan and submit it again.\")\n BUS.send(\"lead\", state.sender, content, \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n return f\"Plan {state.status} ({request_id})\"\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": \"Schedule a cron job. cron is 5-field: min hour dom month dow.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"cron\": {\"type\": \"string\",\n \"description\": \"5-field cron expression\"},\n \"prompt\": {\"type\": \"string\",\n \"description\": \"Message to inject when fired\"},\n \"recurring\": {\"type\": \"boolean\",\n \"description\": \"True=recurring, False=one-shot\"},\n \"durable\": {\"type\": \"boolean\",\n \"description\": \"True=persist to disk\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\",\n \"description\": \"List all registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"cancel_cron\",\n \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn a teammate agent in a background thread.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9_-]{1,64}$\",\n },\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send a message to a teammate via MessageBus.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Ask an active teammate to shut down gracefully.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Require a teammate to submit a plan before changing files.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan by request_id.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": [t[\"name\"] for t in TOOLS],\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n# Keep the loop focused on the mechanisms introduced in this chapter.\n# Fired cron entries are injected at the start of each model turn.\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n # Consume fired cron jobs → inject as messages\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[inject cron] {job.prompt[:50]}\\033[0m\")\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Merge background tool results + notifications into one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s15: agent teams\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n\n # input() and a 1s poller (teammate inbox or background results) feed one\n # event queue (issues #291, #46).\n events = queue.Queue()\n\n def input_reader():\n while True:\n try:\n line = input(\"\\033[36ms15 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n events.put((\"quit\", None))\n return\n events.put((\"user\", line))\n\n def inbox_poller():\n # Poll ~1s and wake the Lead when async results are ready: teammate\n # inbox messages or completed background tasks. Don't gate on\n # active_teammates: a teammate sends its result and then removes itself,\n # so the final message can outlive its registry entry.\n while True:\n time.sleep(1)\n if BUS.peek(\"lead\") or has_pending_background():\n events.put((\"wake\", None))\n\n threading.Thread(target=input_reader, daemon=True).start()\n threading.Thread(target=inbox_poller, daemon=True).start()\n\n had_teammates = False\n while True:\n kind, payload = events.get()\n if kind == \"quit\":\n break\n if kind == \"user\":\n if payload.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": payload})\n else: # \"wake\": teammate inbox or background results are ready\n parts = []\n inbox = consume_lead_inbox()\n if inbox:\n parts.append(format_team_events(inbox))\n bg = collect_background_results()\n parts.extend(bg)\n if not parts:\n continue # already drained by an earlier wake (idempotent)\n history.append({\"role\": \"user\", \"content\": \"\\n\".join(parts)})\n print(f\"\\n\\033[33m[wake: {len(inbox)} team events + \"\n f\"{len(bg)} background \"\n f\"-> new turn]\\033[0m\")\n\n # One turn for whichever source woke us.\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n # Announce once after all requested shutdowns have completed.\n if active_teammates:\n had_teammates = True\n elif had_teammates and not BUS.peek(\"lead\") and not has_pending_background():\n print(\"\\033[32m[all teammates shut down]\\033[0m\")\n had_teammates = False\n print()\n", "images": [ { "src": "/course-assets/s15_agent_teams/agent-teams-overview.svg", "alt": "agent teams overview" }, + { + "src": "/course-assets/s15_agent_teams/team-protocols-overview.svg", + "alt": "team protocols overview" + }, { "src": "/course-assets/s15_agent_teams/team-topology.svg", "alt": "team topology" @@ -2041,249 +2107,10 @@ }, { "id": "s16", - "filename": "s16_team_protocols/code.py", - "title": "Agent Teams: Protocol Lab", - "subtitle": "Typed Requests, Replies, and Handshakes", - "loc": 711, - "tools": [ - "bash", - "read_file", - "write_file", - "send_message", - "submit_plan", - "create_task", - "list_tasks", - "get_task", - "claim_task", - "complete_task", - "spawn_teammate", - "check_inbox", - "request_shutdown", - "request_plan", - "review_plan" - ], - "newTools": [ - "submit_plan", - "request_shutdown", - "request_plan", - "review_plan" - ], - "coreAddition": "Shared coordination protocols", - "keyInsight": "Multi-agent systems need explicit message contracts, not vibes.", - "classes": [ - { - "name": "Task", - "startLine": 58, - "endLine": 66 - }, - { - "name": "MessageBus", - "startLine": 340, - "endLine": 365 - }, - { - "name": "ProtocolState", - "startLine": 372, - "endLine": 381 - } - ], - "functions": [ - { - "name": "_task_path", - "signature": "def _task_path(task_id: str)", - "startLine": 67 - }, - { - "name": "save_task", - "signature": "def save_task(task: Task)", - "startLine": 83 - }, - { - "name": "load_task", - "signature": "def load_task(task_id: str)", - "startLine": 87 - }, - { - "name": "list_tasks", - "signature": "def list_tasks()", - "startLine": 91 - }, - { - "name": "get_task", - "signature": "def get_task(task_id: str)", - "startLine": 96 - }, - { - "name": "can_start", - "signature": "def can_start(task_id: str)", - "startLine": 102 - }, - { - "name": "claim_task", - "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 114 - }, - { - "name": "complete_task", - "signature": "def complete_task(task_id: str)", - "startLine": 129 - }, - { - "name": "assemble_system_prompt", - "signature": "def assemble_system_prompt(context: dict)", - "startLine": 158 - }, - { - "name": "get_system_prompt", - "signature": "def get_system_prompt(context: dict)", - "startLine": 171 - }, - { - "name": "safe_path", - "signature": "def safe_path(p: str)", - "startLine": 183 - }, - { - "name": "run_bash", - "signature": "def run_bash(command: str, run_in_background: bool = False)", - "startLine": 190 - }, - { - "name": "run_read", - "signature": "def run_read(path: str, limit: int | None = None)", - "startLine": 201 - }, - { - "name": "run_write", - "signature": "def run_write(path: str, content: str)", - "startLine": 211 - }, - { - "name": "run_list_tasks", - "signature": "def run_list_tasks()", - "startLine": 231 - }, - { - "name": "run_get_task", - "signature": "def run_get_task(task_id: str)", - "startLine": 246 - }, - { - "name": "run_claim_task", - "signature": "def run_claim_task(task_id: str)", - "startLine": 253 - }, - { - "name": "run_complete_task", - "signature": "def run_complete_task(task_id: str)", - "startLine": 257 - }, - { - "name": "is_slow_operation", - "signature": "def is_slow_operation(tool_name: str, tool_input: dict)", - "startLine": 269 - }, - { - "name": "should_run_background", - "signature": "def should_run_background(tool_name: str, tool_input: dict)", - "startLine": 280 - }, - { - "name": "start_background_task", - "signature": "def start_background_task(block)", - "startLine": 287 - }, - { - "name": "collect_background_results", - "signature": "def collect_background_results()", - "startLine": 311 - }, - { - "name": "new_request_id", - "signature": "def new_request_id()", - "startLine": 385 - }, - { - "name": "match_response", - "signature": "def match_response(response_type: str, request_id: str, approve: bool)", - "startLine": 389 - }, - { - "name": "consume_lead_inbox", - "signature": "def consume_lead_inbox(route_protocol: bool = True)", - "startLine": 420 - }, - { - "name": "spawn_teammate_thread", - "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", - "startLine": 440 - }, - { - "name": "_teammate_submit_plan", - "signature": "def _teammate_submit_plan(from_name: str, plan: str)", - "startLine": 598 - }, - { - "name": "run_request_shutdown", - "signature": "def run_request_shutdown(teammate: str)", - "startLine": 621 - }, - { - "name": "run_request_plan", - "signature": "def run_request_plan(teammate: str, task: str)", - "startLine": 635 - }, - { - "name": "run_review_plan", - "signature": "def run_review_plan(request_id: str, approve: bool, feedback: str = \"\")", - "startLine": 642 - }, - { - "name": "run_spawn_teammate", - "signature": "def run_spawn_teammate(name: str, role: str, prompt: str)", - "startLine": 659 - }, - { - "name": "run_send_message", - "signature": "def run_send_message(to: str, content: str)", - "startLine": 663 - }, - { - "name": "run_check_inbox", - "signature": "def run_check_inbox()", - "startLine": 668 - }, - { - "name": "execute_tool", - "signature": "def execute_tool(block)", - "startLine": 684 - }, - { - "name": "update_context", - "signature": "def update_context(context: dict, messages: list)", - "startLine": 790 - }, - { - "name": "agent_loop", - "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 806 - } - ], - "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns16: Team Protocols — request-response protocol + request_id + dispatch + state machine.\n\nRun: python s16_team_protocols/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s15:\n - ProtocolState dataclass (request_id, type, sender, status, created_at)\n - pending_requests dict: tracks in-flight protocol requests\n - dispatch_message: routes incoming messages by type to handlers\n - request_shutdown: Lead sends shutdown protocol request\n - request_plan: Lead asks teammate to submit plan\n - handle_shutdown_request / handle_plan_response: teammate receives & responds\n - match_response: Lead correlates response to request via request_id (with type validation)\n - Teammate idle loop: waits for inbox messages instead of exiting after 10 rounds\n - Unified consume_lead_inbox: protocol routing + injection into history\n - 3 new Lead tools: request_shutdown, request_plan, review_plan\n - 1 new teammate tool: submit_plan\n\nASCII flow:\n Lead: BUS.send(\"shutdown_request\", {request_id}) ──────→ teammate inbox\n Teammate: dispatch → handler → BUS.send(\"shutdown_response\", {request_id}) ─→ Lead inbox\n Lead: consume_lead_inbox → match_response(request_id) → pending_requests[req_id].status = approved\n\"\"\"\n\nimport os, subprocess, json, time, random, threading\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if not _task_path(d).exists() or load_task(d).status != \"completed\"]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"get_task, create_task, list_tasks, claim_task, complete_task, \"\n \"spawn_teammate, send_message, check_inbox, \"\n \"request_shutdown, request_plan, review_plan.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\n# ── Background Tasks (from s13, synced) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\n# ── MessageBus (from s15) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\n\n\nclass MessageBus:\n \"\"\"File-based message bus. Each agent has a .jsonl inbox.\n Read is destructive: read_text + unlink (consumes messages).\n Teaching version: no file locking; real CC uses proper-lockfile.\"\"\"\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink() # consume: read + delete\n return msgs\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, bool] = {}\n\n# ── Protocol State (s16 new) ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str # \"shutdown\" | \"plan_approval\"\n sender: str\n target: str\n status: str # pending | approved | rejected\n payload: str # plan text or shutdown reason\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n return f\"req_{random.randint(0, 999999):06d}\"\n\n\ndef match_response(response_type: str, request_id: str, approve: bool):\n \"\"\"Correlate a response to the original request via request_id.\n Validates that response_type matches the request type.\"\"\"\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return\n # Validate response type matches request type\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n print(f\" \\033[31m[protocol] type mismatch: expected shutdown_response, \"\n f\"got {response_type}\\033[0m\")\n return\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n print(f\" \\033[31m[protocol] type mismatch: expected plan_approval_response, \"\n f\"got {response_type}\\033[0m\")\n return\n if state.status != \"pending\":\n print(f\" \\033[33m[protocol] {request_id} already {state.status}, \"\n f\"ignoring duplicate\\033[0m\")\n return\n state.status = \"approved\" if approve else \"rejected\"\n icon = \"✓\" if approve else \"✗\"\n color = \"32\" if approve else \"31\"\n print(f\" \\033[{color}m[protocol] {state.type} {icon} \"\n f\"({request_id}: {state.status})\\033[0m\")\n\n\n# ── Unified Lead Inbox Consumer (s16 fix) ──\n# Both check_inbox tool and main loop call this function.\n# Protocol responses are routed via match_response before returning.\n\ndef consume_lead_inbox(route_protocol: bool = True) -> list[dict]:\n \"\"\"Read Lead's inbox. Route protocol responses, return all messages.\n Called by both run_check_inbox() and main loop to avoid\n messages being consumed without protocol routing.\"\"\"\n msgs = BUS.read_inbox(\"lead\")\n if not msgs:\n return []\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n approve = meta.get(\"approve\", False)\n match_response(msg_type, req_id, approve)\n return msgs\n\n\n# ── Teammate Thread (s16: idle loop + dispatch) ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n \"\"\"Spawn a teammate agent in a background thread.\n Uses idle loop: after each LLM turn, waits for inbox messages\n (shutdown_request, new task) instead of exiting.\"\"\"\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n\n system = (f\"You are '{name}', a {role}. \"\n f\"Use tools to complete tasks. \"\n f\"Check inbox for protocol messages (shutdown_request, etc).\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list) -> bool:\n \"\"\"Dispatch incoming protocol messages by type.\n Returns True if teammate should stop.\"\"\"\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"({req_id})\\033[0m\")\n return True # stop the loop\n\n if msg_type == \"plan_approval_response\":\n approve = meta.get(\"approve\", False)\n if approve:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan approved] Proceed with the task.\"})\n else:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan rejected] Feedback: {msg['content']}\"})\n\n return False # continue\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n ]\n sub_handlers = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"send_message\": lambda to, content: (BUS.send(name, to, content),\n \"Sent\")[1],\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n }\n\n shutdown_requested = False\n while not shutdown_requested:\n # Check inbox for protocol messages\n inbox = BUS.read_inbox(name)\n should_stop = False\n non_protocol = []\n for msg in inbox:\n if msg.get(\"type\") in (\"shutdown_request\", \"plan_approval_response\"):\n should_stop = handle_inbox_message(name, msg, messages)\n if should_stop:\n break\n else:\n non_protocol.append(msg)\n if should_stop:\n shutdown_requested = True\n break\n if non_protocol:\n inbox_json = json.dumps(non_protocol)\n messages.append({\"role\": \"user\",\n \"content\": \"\" + inbox_json + \"\"})\n\n # LLM turn\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n # Idle: wait for inbox messages instead of exiting\n # Real CC sends idle_notification to Lead here\n while not shutdown_requested:\n time.sleep(1)\n inbox = BUS.read_inbox(name)\n if not inbox:\n continue\n for msg in inbox:\n if msg.get(\"type\") in (\"shutdown_request\", \"plan_approval_response\"):\n should_stop = handle_inbox_message(name, msg, messages)\n if should_stop:\n shutdown_requested = True\n break\n else:\n non_protocol.append(msg)\n if shutdown_requested:\n break\n if non_protocol:\n inbox_json = json.dumps(non_protocol)\n messages.append({\"role\": \"user\",\n \"content\": \"\" + inbox_json + \"\"})\n break # back to LLM turn with new messages\n\n # Execute tool calls\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n handler = sub_handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n # Send final summary to Lead\n summary = \"Done.\"\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\" and isinstance(msg[\"content\"], list):\n for b in msg[\"content\"]:\n if getattr(b, \"type\", None) == \"text\":\n summary = b.text\n break\n else:\n continue\n break\n BUS.send(name, \"lead\", summary, \"result\")\n active_teammates.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n active_teammates[name] = True\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role}\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n \"\"\"Teammate submits a plan to Lead for approval.\n\n Note: This is a protocol-level request, not a code-level gate.\n After submitting, the teammate's thread continues running — it can\n still call bash/write/etc. Real enforcement relies on the model\n waiting for the approval response before acting. Code-level tool\n gating would require blocking the teammate's tool dispatch until\n approval arrives.\n \"\"\"\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id}). Waiting for approval...\"\n\n\n# ── Lead Protocol Tools (s16 new) ──\n\ndef run_request_shutdown(teammate: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Please shut down gracefully.\",\n \"shutdown_request\",\n {\"request_id\": req_id})\n print(f\" \\033[35m[protocol] shutdown_request → {teammate} \"\n f\"({req_id})\\033[0m\")\n return f\"Shutdown request sent to {teammate} (req: {req_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n \"\"\"Lead asks a teammate to submit a plan for a task.\"\"\"\n BUS.send(\"lead\", teammate, f\"Please submit a plan for: {task}\",\n \"message\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool, feedback: str = \"\") -> str:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender, feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n icon = \"✓\" if approve else \"✗\"\n print(f\" \\033[32m[protocol] plan {icon} ({request_id})\\033[0m\")\n return f\"Plan {'approved' if approve else 'rejected'} ({request_id})\"\n\n\n# ── Other Lead Tool Handlers ──\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\ndef run_check_inbox() -> str:\n \"\"\"Check Lead's inbox. Routes protocol responses via match_response.\"\"\"\n msgs = consume_lead_inbox(route_protocol=True)\n if not msgs:\n return \"(inbox empty)\"\n lines = []\n for m in msgs:\n meta = m.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n tag = f\" [{m['type']} req:{req_id}]\" if req_id else f\" [{m['type']}]\"\n lines.append(f\" [{m['from']}]{tag} {m['content'][:200]}\")\n return \"\\n\".join(lines)\n\n\n# ── Tool Dispatch ──\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message, \"check_inbox\": run_check_inbox,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n }.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn a teammate agent in a background thread.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"name\": {\"type\": \"string\"},\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to a teammate via MessageBus.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"check_inbox\",\n \"description\": \"Check Lead's inbox. Routes protocol responses automatically.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down gracefully.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan for review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan by request_id.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": [t[\"name\"] for t in TOOLS],\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Merge background tool results + notifications into one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s16: team protocols\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n while True:\n try:\n query = input(\"\\033[36ms16 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n # Check inbox → route protocol + inject into history\n inbox_msgs = consume_lead_inbox(route_protocol=True)\n if inbox_msgs:\n inbox_text = \"\\n\".join(\n f\"From {m['from']}: {m['content'][:200]}\" for m in inbox_msgs)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n print(f\"\\n\\033[33m[Inbox: {len(inbox_msgs)} messages injected]\\033[0m\")\n print()\n", - "images": [ - { - "src": "/course-assets/s16_team_protocols/team-protocols-overview.svg", - "alt": "team protocols overview" - } - ] - }, - { - "id": "s17", - "filename": "s17_autonomous_agents/code.py", + "filename": "s16_autonomous_agents/code.py", "title": "Autonomous Agents", "subtitle": "Check the Board, Claim the Task", - "loc": 649, + "loc": 1130, "tools": [ "bash", "read_file", @@ -2295,30 +2122,37 @@ "complete_task", "create_task", "get_task", + "schedule_cron", + "list_crons", + "cancel_cron", "spawn_teammate", - "check_inbox", "request_shutdown", "request_plan", "review_plan" ], "newTools": [], "coreAddition": "Autonomous task claiming", - "keyInsight": "Teammates become useful when they can discover and claim work themselves.", + "keyInsight": "Idle teammates can discover ready work when claiming is atomic and respects task dependencies.", "classes": [ { "name": "Task", "startLine": 51, "endLine": 59 }, + { + "name": "CronJob", + "startLine": 373, + "endLine": 380 + }, { "name": "MessageBus", - "startLine": 219, - "endLine": 240 + "startLine": 619, + "endLine": 677 }, { "name": "ProtocolState", - "startLine": 248, - "endLine": 257 + "startLine": 688, + "endLine": 697 } ], "functions": [ @@ -2350,154 +2184,264 @@ { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 94 + "startLine": 95 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 104 + "startLine": 107 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 125 + "startLine": 126 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 153 + "startLine": 163 }, { "name": "get_system_prompt", "signature": "def get_system_prompt(context: dict)", - "startLine": 165 + "startLine": 177 }, { "name": "safe_path", "signature": "def safe_path(p: str)", - "startLine": 176 + "startLine": 189 }, { "name": "run_bash", - "signature": "def run_bash(command: str)", - "startLine": 183 + "signature": "def run_bash(command: str, run_in_background: bool = False)", + "startLine": 196 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None)", - "startLine": 193 + "startLine": 207 }, { "name": "run_write", "signature": "def run_write(path: str, content: str)", - "startLine": 203 - }, - { - "name": "new_request_id", - "signature": "def new_request_id()", - "startLine": 261 - }, - { - "name": "match_response", - "signature": "def match_response(response_type: str, request_id: str, approve: bool)", - "startLine": 265 - }, - { - "name": "scan_unclaimed_tasks", - "signature": "def scan_unclaimed_tasks()", - "startLine": 292 - }, - { - "name": "idle_poll", - "signature": "def idle_poll(name: str, messages: list, role: str)", - "startLine": 304 - }, - { - "name": "spawn_teammate_thread", - "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", - "startLine": 350 - }, - { - "name": "_teammate_submit_plan", - "signature": "def _teammate_submit_plan(from_name: str, plan: str)", - "startLine": 527 - }, - { - "name": "run_request_shutdown", - "signature": "def run_request_shutdown(teammate: str)", - "startLine": 542 - }, - { - "name": "run_request_plan", - "signature": "def run_request_plan(teammate: str, task: str)", - "startLine": 556 + "startLine": 217 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 590 + "startLine": 237 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 599 + "startLine": 252 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 603 + "startLine": 259 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 607 + "startLine": 263 + }, + { + "name": "is_slow_operation", + "signature": "def is_slow_operation(tool_name: str, tool_input: dict)", + "startLine": 275 + }, + { + "name": "should_run_background", + "signature": "def should_run_background(tool_name: str, tool_input: dict)", + "startLine": 286 + }, + { + "name": "execute_tool", + "signature": "def execute_tool(block)", + "startLine": 293 + }, + { + "name": "start_background_task", + "signature": "def start_background_task(block)", + "startLine": 313 + }, + { + "name": "collect_background_results", + "signature": "def collect_background_results()", + "startLine": 337 + }, + { + "name": "has_pending_background", + "signature": "def has_pending_background()", + "startLine": 360 + }, + { + "name": "_cron_field_matches", + "signature": "def _cron_field_matches(field: str, value: int)", + "startLine": 387 + }, + { + "name": "cron_matches", + "signature": "def cron_matches(cron_expr: str, dt: datetime)", + "startLine": 403 + }, + { + "name": "_validate_cron_field", + "signature": "def _validate_cron_field(field: str, lo: int, hi: int)", + "startLine": 433 + }, + { + "name": "validate_cron", + "signature": "def validate_cron(cron_expr: str)", + "startLine": 468 + }, + { + "name": "save_durable_jobs", + "signature": "def save_durable_jobs()", + "startLine": 482 + }, + { + "name": "load_durable_jobs", + "signature": "def load_durable_jobs()", + "startLine": 488 + }, + { + "name": "cancel_job", + "signature": "def cancel_job(job_id: str)", + "startLine": 527 + }, + { + "name": "cron_scheduler_loop", + "signature": "def cron_scheduler_loop()", + "startLine": 539 + }, + { + "name": "consume_cron_queue", + "signature": "def consume_cron_queue()", + "startLine": 565 + }, + { + "name": "run_list_crons", + "signature": "def run_list_crons()", + "startLine": 589 + }, + { + "name": "run_cancel_cron", + "signature": "def run_cancel_cron(job_id: str)", + "startLine": 603 + }, + { + "name": "is_valid_agent_name", + "signature": "def is_valid_agent_name(name: str)", + "startLine": 615 + }, + { + "name": "new_request_id", + "signature": "def new_request_id()", + "startLine": 701 + }, + { + "name": "consume_lead_inbox", + "signature": "def consume_lead_inbox()", + "startLine": 736 + }, + { + "name": "format_team_events", + "signature": "def format_team_events(msgs: list[dict])", + "startLine": 749 + }, + { + "name": "_last_assistant_text", + "signature": "def _last_assistant_text(content)", + "startLine": 761 + }, + { + "name": "_teammate_submit_plan", + "signature": "def _teammate_submit_plan(from_name: str, plan: str)", + "startLine": 770 + }, + { + "name": "_run_teammate_tool", + "signature": "def _run_teammate_tool(name: str, block, handlers: dict)", + "startLine": 791 + }, + { + "name": "apply_plan_response", + "signature": "def apply_plan_response(name: str, msg: dict)", + "startLine": 801 + }, + { + "name": "apply_shutdown_request", + "signature": "def apply_shutdown_request(name: str, msg: dict)", + "startLine": 829 + }, + { + "name": "_teammate_send_message", + "signature": "def _teammate_send_message(from_name: str, to: str, content: str)", + "startLine": 850 + }, + { + "name": "scan_unclaimed_tasks", + "signature": "def scan_unclaimed_tasks()", + "startLine": 863 + }, + { + "name": "claim_next_task", + "signature": "def claim_next_task(name: str)", + "startLine": 873 + }, + { + "name": "spawn_teammate_thread", + "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", + "startLine": 884 }, { "name": "run_spawn_teammate", "signature": "def run_spawn_teammate(name: str, role: str, prompt: str)", - "startLine": 611 + "startLine": 1061 }, { "name": "run_send_message", "signature": "def run_send_message(to: str, content: str)", - "startLine": 615 + "startLine": 1065 }, { - "name": "consume_lead_inbox", - "signature": "def consume_lead_inbox(route_protocol=True)", - "startLine": 620 + "name": "run_request_shutdown", + "signature": "def run_request_shutdown(teammate: str)", + "startLine": 1072 }, { - "name": "run_check_inbox", - "signature": "def run_check_inbox()", - "startLine": 633 + "name": "run_request_plan", + "signature": "def run_request_plan(teammate: str, task: str)", + "startLine": 1090 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 744 + "startLine": 1229 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 753 + "startLine": 1247 } ], "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns17: Autonomous Agents — idle poll + auto-claim + WORK/IDLE lifecycle.\n\nRun: python s17_autonomous_agents/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s16:\n - scan_unclaimed_tasks: find pending, unowned tasks with deps completed\n - idle_poll: 60s polling loop (inbox + task board), dispatches shutdown in IDLE\n - claim_task: owner check + return value verification\n - Teammate lifecycle: WORK → IDLE → SHUTDOWN\n - Teammate tools: + list_tasks, claim_task, complete_task (5→8)\n - consume_lead_inbox: unified inbox consumer for protocol + context injection\n - Identity re-injection after context compression\n\nASCII lifecycle:\n WORK: inbox → LLM → tools → (tool_use? loop) → (done? → IDLE)\n IDLE: 5s poll → inbox? → WORK / unclaimed? → claim → WORK / 60s? → SHUTDOWN\n\"\"\"\n\nimport os, subprocess, json, time, random, threading\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if _task_path(d).exists() and load_task(d).status != \"completed\"]\n missing = [d for d in task.blockedBy if not _task_path(d).exists()]\n parts = []\n if deps: parts.append(f\"blocked by: {deps}\")\n if missing: parts.append(f\"missing deps: {missing}\")\n return \"Cannot start — \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Prompt Assembly (from s10) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"spawn_teammate, send_message, check_inbox, \"\n \"request_shutdown, request_plan, review_plan.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_hash, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_hash, _last_prompt\n h = json.dumps(context, sort_keys=True)\n if h == _last_context_hash and _last_prompt:\n return _last_prompt\n _last_context_hash, _last_prompt = h, assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools (from s15) ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# ── MessageBus (from s15) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\n\n\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, bool] = {}\n\n\n# ── Protocol State (from s16) ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n return f\"req_{random.randint(0, 999999):06d}\"\n\n\ndef match_response(response_type: str, request_id: str, approve: bool):\n \"\"\"Correlate a response to the original request via request_id.\"\"\"\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n print(f\" \\033[31m[protocol] type mismatch: expected shutdown_response, \"\n f\"got {response_type}\\033[0m\")\n return\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n print(f\" \\033[31m[protocol] type mismatch: expected plan_approval_response, \"\n f\"got {response_type}\\033[0m\")\n return\n state.status = \"approved\" if approve else \"rejected\"\n icon = \"✓\" if approve else \"✗\"\n color = \"32\" if approve else \"31\"\n print(f\" \\033[{color}m[protocol] {state.type} {icon} \"\n f\"({request_id}: {state.status})\\033[0m\")\n\n\n# ── Autonomous Agent (s17 new) ──\n\nIDLE_POLL_INTERVAL = 5 # seconds\nIDLE_TIMEOUT = 60 # seconds\n\n\ndef scan_unclaimed_tasks() -> list[dict]:\n \"\"\"Find pending, unowned tasks with all dependencies completed.\"\"\"\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n\n\ndef idle_poll(name: str, messages: list, role: str) -> str:\n \"\"\"Poll for 60s. Return 'work', 'shutdown', or 'timeout'.\"\"\"\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n\n # Check inbox — dispatch protocol messages first\n inbox = BUS.read_inbox(name)\n if inbox:\n # Check for shutdown_request\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"in idle ({req_id})\\033[0m\")\n return \"shutdown\"\n\n # Non-protocol inbox: inject and resume work\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(inbox) + \"\"})\n print(f\" \\033[36m[idle] {name} found inbox messages\\033[0m\")\n return \"work\"\n\n # Scan task board\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task = unclaimed[0]\n result = claim_task(task[\"id\"], name)\n if \"Claimed\" in result:\n messages.append({\"role\": \"user\",\n \"content\": f\"Task {task['id']}: \"\n f\"{task['subject']}\"})\n print(f\" \\033[32m[idle] {name} auto-claimed: \"\n f\"{task['subject']}\\033[0m\")\n return \"work\"\n print(f\" \\033[33m[idle] {name} claim failed: \"\n f\"{result}\\033[0m\")\n\n print(f\" \\033[31m[idle] {name} timeout ({IDLE_TIMEOUT}s)\\033[0m\")\n return \"timeout\"\n\n\n# ── Teammate Thread (from s15 + s16 + s17) ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n\n system = (f\"You are '{name}', a {role}. \"\n f\"Use tools to complete tasks. \"\n f\"You can list and claim tasks from the board. \"\n f\"Check inbox for protocol messages.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n \"\"\"Dispatch incoming protocol messages by type.\"\"\"\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"({req_id})\\033[0m\")\n return True\n\n if msg_type == \"plan_approval_response\":\n approve = meta.get(\"approve\", False)\n if approve:\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved] Proceed with the task.\"})\n else:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan rejected] Feedback: {msg['content']}\"})\n return False\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n # s17 new: teammates can list, claim, and complete tasks\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks on the board.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n return claim_task(task_id, owner=name)\n\n def _run_complete_task(task_id: str):\n return complete_task(task_id)\n\n sub_handlers = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"send_message\": lambda to, content: (BUS.send(name, to, content),\n \"Sent\")[1],\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n # Outer loop: WORK → IDLE cycle\n while True:\n # Identity re-injection (s17)\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n\n # WORK phase\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n if inbox and not should_shutdown:\n non_protocol = [m for m in inbox\n if m.get(\"type\") == \"message\"]\n if non_protocol:\n messages.append({\"role\": \"user\",\n \"content\": f\"{json.dumps(non_protocol)}\"})\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n handler = sub_handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if should_shutdown:\n break\n\n # IDLE phase (s17 new)\n idle_result = idle_poll(name, messages, role)\n if idle_result == \"shutdown\":\n break\n if idle_result == \"timeout\":\n break\n\n # Summary\n summary = \"Done.\"\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\" and isinstance(msg[\"content\"], list):\n for b in msg[\"content\"]:\n if getattr(b, \"type\", None) == \"text\":\n summary = b.text\n break\n else:\n continue\n break\n BUS.send(name, \"lead\", summary, \"result\")\n active_teammates.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n active_teammates[name] = True\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role} (autonomous)\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n \"\"\"Teammate submits a plan to Lead for approval.\"\"\"\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id}). Waiting for approval...\"\n\n\n# ── Lead Protocol Tools (from s16) ──\n\ndef run_request_shutdown(teammate: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Please shut down gracefully.\",\n \"shutdown_request\",\n {\"request_id\": req_id})\n print(f\" \\033[35m[protocol] shutdown_request → {teammate} \"\n f\"({req_id})\\033[0m\")\n return f\"Shutdown request sent to {teammate} (req: {req_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n \"\"\"Lead asks a teammate to submit a plan.\"\"\"\n BUS.send(\"lead\", teammate, f\"Please submit a plan for: {task}\",\n \"message\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n icon = \"✓\" if approve else \"✗\"\n print(f\" \\033[32m[protocol] plan {icon} ({request_id})\\033[0m\")\n return f\"Plan {'approved' if approve else 'rejected'} ({request_id})\"\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n return get_task(task_id)\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n \"\"\"Read Lead inbox: route protocol responses, return all messages.\"\"\"\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n\n\ndef run_check_inbox() -> str:\n msgs = consume_lead_inbox(route_protocol=True)\n if not msgs:\n return \"(inbox empty)\"\n lines = []\n for m in msgs:\n meta = m.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n tag = f\" [{m['type']} req:{req_id}]\" if req_id else f\" [{m['type']}]\"\n lines.append(f\" [{m['from']}]{tag} {m['content'][:200]}\")\n return \"\\n\".join(lines)\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn an autonomous teammate agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"check_inbox\",\n \"description\": \"Check inbox for messages and protocol responses.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down gracefully.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan for review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message, \"check_inbox\": run_check_inbox,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\"memories\": memories}\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s17: autonomous agents\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = {\"memories\": \"\"}\n while True:\n try:\n query = input(\"\\033[36ms17 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n # Consume lead inbox: route protocol + inject into history\n inbox = consume_lead_inbox(route_protocol=True)\n if inbox:\n inbox_text = \"\\n\".join(\n f\"From {m['from']} [{m.get('type', 'message')}]: \"\n f\"{m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns16: Autonomous Agents — idle teammates discover and claim ready tasks.\n\nRun: python s16_autonomous_agents/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s15:\n - scan_unclaimed_tasks finds pending, unowned, unblocked tasks\n - Idle teammates periodically scan the shared task board\n - claim_next_task atomically assigns one ready task to a teammate\n - Teammates can list, claim, and complete tasks\n\nASCII flow:\n WORK → result → IDLE → scan board → claim ready task → WORK\n └→ inbox or shutdown event\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, queue, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12, synced) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\ntask_lock = threading.RLock()\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str # pending | in_progress | completed\n owner: str | None\n blockedBy: list[str]\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task(task_id: str) -> str:\n \"\"\"Return full task details as JSON.\"\"\"\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n \"\"\"Check if all blockedBy dependencies are completed.\n Missing dependencies are treated as blocked.\"\"\"\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} is already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if (not _task_path(d).exists()\n or load_task(d).status != \"completed\")]\n return f\"Blocked by: {deps}\"\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress (owner: {owner})\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n print(f\" \\033[33m[unblocked] {', '.join(unblocked)}\\033[0m\")\n return msg\n\n\n# ── Prompt Assembly (from s10, synced) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"get_task, create_task, list_tasks, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron, \"\n \"spawn_teammate, send_message, request_shutdown, \"\n \"request_plan, review_plan.\",\n \"teams\": (\n \"When parallel work would help, first propose a small team with clear \"\n \"responsibilities and wait for the user's confirmation. Do not call \"\n \"spawn_teammate before the user confirms. After confirmation, delegate \"\n \"independent work, react to team events delivered by the runtime, and \"\n \"shut teammates down when coordination is complete.\"\n ),\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"teams\"],\n PROMPT_SECTIONS[\"workspace\"]]\n memories = context.get(\"memories\", \"\")\n if memories:\n sections.append(f\"Relevant memories:\\n{memories}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_key, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_key, _last_prompt\n key = json.dumps(context, sort_keys=True, ensure_ascii=False, default=str)\n if key == _last_context_key and _last_prompt:\n return _last_prompt\n _last_context_key = key\n _last_prompt = assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Tools ──\n\ndef safe_path(p: str) -> Path:\n path = (WORKDIR / p).resolve()\n if not path.is_relative_to(WORKDIR):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, run_in_background: bool = False) -> str:\n # run_in_background is handled by agent_loop dispatch, not here\n try:\n r = subprocess.run(command, shell=True, cwd=WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None) -> str:\n try:\n lines = safe_path(path).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str) -> str:\n try:\n fp = safe_path(path)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# Task tools\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks. Use create_task to add some.\"\n lines = []\n for t in tasks:\n icon = {\"pending\": \"○\", \"in_progress\": \"●\",\n \"completed\": \"✓\"}.get(t.status, \"?\")\n deps = f\" (blockedBy: {', '.join(t.blockedBy)})\" if t.blockedBy else \"\"\n owner = f\" [{t.owner}]\" if t.owner else \"\"\n lines.append(f\" {icon} {t.id}: {t.subject} \"\n f\"[{t.status}]{owner}{deps}\")\n return \"\\n\".join(lines)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task(task_id)\n except FileNotFoundError:\n return f\"Error: Task {task_id} not found\"\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\n# ── Background Tasks (from s13, synced) ──\n\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Fallback heuristic: commands likely to take > 30s.\"\"\"\n if tool_name != \"bash\":\n return False\n cmd = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(kw in cmd for kw in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n \"\"\"Model explicit request takes priority; fallback to heuristic.\"\"\"\n if tool_input.get(\"run_in_background\"):\n return True\n return is_slow_operation(tool_name, tool_input)\n\n\ndef execute_tool(block) -> str:\n \"\"\"Execute a tool call block, return output.\"\"\"\n handler = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task, \"claim_task\": run_claim_task,\n \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron, \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan,\n \"review_plan\": run_review_plan,\n }.get(block.name)\n if handler:\n return handler(**block.input)\n return f\"Unknown tool: {block.name}\"\n\n\ndef start_background_task(block) -> str:\n \"\"\"Run tool in a daemon thread. Returns background task ID.\"\"\"\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n cmd = block.input.get(\"command\", block.name)\n\n def worker():\n result = execute_tool(block)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = result\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": cmd,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] dispatched {bg_id}: {cmd[:40]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n \"\"\"Collect completed background results as task_notification messages.\"\"\"\n with background_lock:\n ready_ids = [bid for bid, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready_ids:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n print(f\" \\033[32m[background done] {bg_id}: \"\n f\"{task['command'][:40]} ({len(output)} chars)\\033[0m\")\n return notifications\n\n\ndef has_pending_background() -> bool:\n \"\"\"Non-destructive: True if any background task has completed and is\n waiting to be collected. The inbox poller uses this in its wake condition.\"\"\"\n with background_lock:\n return any(t[\"status\"] == \"completed\" for t in background_tasks.values())\n\n\n# ── Cron Scheduler (from s14, synced) ──\n\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str # \"0 9 * * *\"\n prompt: str # message to inject when fired\n recurring: bool # True = recurring, False = one-shot\n durable: bool # True = persist to disk\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\n_last_fired: dict[str, str] = {} # job_id → \"YYYY-MM-DD HH:MM\"\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n \"\"\"Match a single cron field against a value.\"\"\"\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(f.strip(), value)\n for f in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n \"\"\"Check if a 5-field cron expression matches the given datetime.\n Standard cron semantics: DOM and DOW use OR when both are constrained.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7 # Python Monday=0 → cron Sunday=0\n\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n\n # Minute, hour, month must all match\n if not (m and h and month_ok):\n return False\n # DOM and DOW: if both constrained, either matching is enough (OR)\n dom_unconstrained = dom == \"*\"\n dow_unconstrained = dow == \"*\"\n if dom_unconstrained and dow_unconstrained:\n return True\n if dom_unconstrained:\n return dow_ok\n if dow_unconstrained:\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n \"\"\"Validate a single cron field value is within [lo, hi].\"\"\"\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step_str = field[2:]\n if not step_str.isdigit():\n return f\"Invalid step: {field}\"\n step = int(step_str)\n if step <= 0:\n return f\"Step must be > 0: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err: return err\n return None\n if \"-\" in field:\n parts = field.split(\"-\", 1)\n if not parts[0].isdigit() or not parts[1].isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(parts[0]), int(parts[1])\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n val = int(field)\n if val < lo or val > hi:\n return f\"Value {val} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n \"\"\"Validate a cron expression. Returns error message or None.\"\"\"\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for i, (field, (lo, hi), name) in enumerate(zip(fields, bounds, names)):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n \"\"\"Persist durable jobs to .scheduled_tasks.json.\"\"\"\n durable = [asdict(j) for j in scheduled_jobs.values() if j.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n \"\"\"Load durable jobs from disk on startup.\"\"\"\n if not DURABLE_PATH.exists():\n return\n try:\n jobs = json.loads(DURABLE_PATH.read_text())\n for j in jobs:\n job = CronJob(**j)\n err = validate_cron(job.cron)\n if err:\n print(f\" \\033[31m[cron] skipping invalid job {job.id}: {err}\\033[0m\")\n continue\n scheduled_jobs[job.id] = job\n valid = [j for j in jobs if j[\"id\"] in scheduled_jobs]\n if valid:\n print(f\" \\033[35m[cron] loaded {len(valid)} durable job(s)\\033[0m\")\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str, recurring: bool = True,\n durable: bool = True) -> CronJob | str:\n \"\"\"Register a new cron job. Returns CronJob or error string.\"\"\"\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable,\n )\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n print(f\" \\033[35m[cron register] {job.id} '{cron}' → {prompt[:40]}\\033[0m\")\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n \"\"\"Cancel a cron job.\"\"\"\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n print(f\" \\033[31m[cron cancel] {job_id}\\033[0m\")\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n \"\"\"Independent daemon thread: poll every 1s, fire matching jobs.\n Individual job errors are caught to prevent one bad job from\n killing the entire scheduler thread.\"\"\"\n while True:\n time.sleep(1)\n now = datetime.now()\n # Date-aware marker prevents daily jobs from skipping on day 2+\n minute_marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now):\n if _last_fired.get(job.id) != minute_marker:\n cron_queue.append(job)\n _last_fired[job.id] = minute_marker\n print(f\" \\033[35m[cron fire] {job.id} → \"\n f\"{job.prompt[:40]}\\033[0m\")\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n \"\"\"Consume fired jobs from cron_queue (called by agent_loop).\"\"\"\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\n# Load durable jobs on startup, then start scheduler thread\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\nprint(\" \\033[35m[cron] scheduler thread started\\033[0m\")\n\n\n# Cron tool handlers\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' → {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs. Use schedule_cron to add one.\"\n lines = []\n for j in jobs:\n tag = \"recurring\" if j.recurring else \"one-shot\"\n dur = \"durable\" if j.durable else \"session\"\n lines.append(f\" {j.id}: '{j.cron}' → {j.prompt[:40]} \"\n f\"[{tag}, {dur}]\")\n return \"\\n\".join(lines)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\n# ── MessageBus + Team Protocols (s15 new) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\nMAILBOX_ROOT = MAILBOX_DIR.resolve()\nVALID_AGENT_NAME = re.compile(r\"^[A-Za-z0-9_-]{1,64}$\")\n\n\ndef is_valid_agent_name(name: str) -> bool:\n return bool(VALID_AGENT_NAME.fullmatch(name))\n\n\nclass MessageBus:\n \"\"\"Thread-safe file mailboxes with destructive reads.\"\"\"\n\n def __init__(self):\n self._lock = threading.RLock()\n self._changed = threading.Condition(self._lock)\n\n def _path(self, agent: str) -> Path:\n if not is_valid_agent_name(agent):\n raise ValueError(f\"Invalid mailbox recipient: {agent!r}\")\n path = (MAILBOX_DIR / f\"{agent}.jsonl\").resolve()\n if not path.is_relative_to(MAILBOX_ROOT):\n raise ValueError(f\"Mailbox path escapes directory: {agent!r}\")\n return path\n\n def _read_unlocked(self, agent: str) -> list[dict]:\n inbox = self._path(agent)\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict | None = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n with self._changed:\n with open(self._path(to_agent), \"a\") as f:\n f.write(json.dumps(msg, ensure_ascii=False) + \"\\n\")\n self._changed.notify_all()\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n with self._lock:\n return self._read_unlocked(agent)\n\n def peek(self, agent: str) -> bool:\n with self._lock:\n inbox = self._path(agent)\n return inbox.exists() and inbox.stat().st_size > 0\n\n def wait_for_messages(self, agent: str,\n timeout: float | None = None) -> list[dict]:\n \"\"\"Block until the agent has messages or timeout expires.\"\"\"\n deadline = None if timeout is None else time.monotonic() + timeout\n with self._changed:\n while not self.peek(agent):\n remaining = (None if deadline is None\n else deadline - time.monotonic())\n if remaining is not None and remaining <= 0:\n return []\n self._changed.wait(remaining)\n return self._read_unlocked(agent)\n\n\nBUS = MessageBus()\n\n# working | waiting_approval | idle | stopping\nactive_teammates: dict[str, str] = {}\nplan_gates: dict[str, str] = {}\nplan_request_ids: dict[str, str] = {}\nteam_lock = threading.RLock()\n\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n while True:\n request_id = f\"req_{random.randint(0, 999999):06d}\"\n if request_id not in pending_requests:\n return request_id\n\n\ndef match_response(response_type: str, request_id: str, approve: bool,\n from_agent: str, to_agent: str) -> bool:\n \"\"\"Match one protocol response to one pending request.\"\"\"\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return False\n expected = {\n \"shutdown\": \"shutdown_response\",\n \"plan_approval\": \"plan_approval_response\",\n }[state.type]\n if response_type != expected:\n print(f\" \\033[31m[protocol] expected {expected}, \"\n f\"got {response_type}\\033[0m\")\n return False\n if from_agent != state.target or to_agent != state.sender:\n print(f\" \\033[31m[protocol] {request_id} responder mismatch\\033[0m\")\n return False\n if state.status != \"pending\":\n print(f\" \\033[33m[protocol] {request_id} already \"\n f\"{state.status}\\033[0m\")\n return False\n state.status = \"approved\" if approve else \"rejected\"\n print(f\" \\033[35m[protocol] {request_id} → {state.status}\\033[0m\")\n return True\n\n\ndef consume_lead_inbox() -> list[dict]:\n \"\"\"Consume Lead events and update protocol state before model delivery.\"\"\"\n msgs = BUS.read_inbox(\"lead\")\n for msg in msgs:\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n if request_id and msg.get(\"type\", \"\").endswith(\"_response\"):\n match_response(msg[\"type\"], request_id,\n metadata.get(\"approve\", False),\n msg.get(\"from\", \"\"), msg.get(\"to\", \"\"))\n return msgs\n\n\ndef format_team_events(msgs: list[dict]) -> str:\n lines = []\n for msg in msgs:\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\")\n suffix = f\" request_id={request_id}\" if request_id else \"\"\n lines.append(\n f\"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}\"\n )\n return \"[Team events]\\n\" + \"\\n\".join(lines)\n\n\ndef _last_assistant_text(content) -> str:\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n return block.text.strip()\n if isinstance(block, dict) and block.get(\"type\") == \"text\":\n return str(block.get(\"text\", \"\")).strip()\n return \"\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n with team_lock:\n if plan_gates.get(from_name) == \"pending\":\n return \"A plan is already waiting for review.\"\n request_id = new_request_id()\n pending_requests[request_id] = ProtocolState(\n request_id=request_id,\n type=\"plan_approval\",\n sender=from_name,\n target=\"lead\",\n status=\"pending\",\n payload=plan,\n )\n plan_gates[from_name] = \"pending\"\n plan_request_ids[from_name] = request_id\n active_teammates[from_name] = \"waiting_approval\"\n BUS.send(from_name, \"lead\", plan, \"plan_approval_request\",\n {\"request_id\": request_id})\n return f\"Plan submitted ({request_id}). Wait for Lead's decision.\"\n\n\ndef _run_teammate_tool(name: str, block, handlers: dict) -> str:\n gate = plan_gates.get(name, \"not_required\")\n if block.name in {\"bash\", \"write_file\"} and gate != \"not_required\":\n if gate != \"approved\":\n return (f\"Blocked: plan status is {gate}. Submit or revise the \"\n \"plan and wait for approval before changing the workspace.\")\n handler = handlers.get(block.name)\n return str(handler(**block.input)) if handler else f\"Unknown tool: {block.name}\"\n\n\ndef apply_plan_response(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Apply only the Lead response for this teammate's current plan.\"\"\"\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n expected_id = plan_request_ids.get(name)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and request_id == expected_id\n and state is not None\n and state.type == \"plan_approval\"\n and state.sender == name\n and state.target == \"lead\"\n and state.status in {\"approved\", \"rejected\"}\n and metadata.get(\"approve\", False)\n == (state.status == \"approved\")\n )\n if not valid:\n return False, \"[Ignored plan response: request mismatch]\"\n plan_gates[name] = state.status\n active_teammates[name] = \"working\"\n plan_request_ids.pop(name, None)\n outcome = state.status\n return True, f\"[Plan {outcome}] {msg['content']}\"\n\n\ndef apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Accept only a pending shutdown request sent by Lead to this teammate.\"\"\"\n request_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and state is not None\n and state.type == \"shutdown\"\n and state.sender == \"lead\"\n and state.target == name\n and state.status == \"pending\"\n and active_teammates.get(name) != \"stopping\"\n )\n if not valid:\n return False, \"[Ignored shutdown request: request mismatch]\"\n active_teammates[name] = \"stopping\"\n return True, request_id\n\n\ndef _teammate_send_message(from_name: str, to: str, content: str) -> str:\n with team_lock:\n if to != \"lead\" and to not in active_teammates:\n return f\"Agent '{to}' is not active\"\n BUS.send(from_name, to, content)\n return f\"Sent to {to}\"\n\n\n# ── Autonomous Task Discovery (s16 new) ──\n\nIDLE_SCAN_INTERVAL = 2.0\n\n\ndef scan_unclaimed_tasks() -> list[Task]:\n \"\"\"Return ready tasks without changing ownership.\"\"\"\n return [\n task for task in list_tasks()\n if (task.status == \"pending\"\n and task.owner is None\n and can_start(task.id))\n ]\n\n\ndef claim_next_task(name: str) -> Task | None:\n \"\"\"Claim the first ready task that is still available.\"\"\"\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n \"\"\"Spawn a persistent teammate that alternates between WORK and IDLE.\"\"\"\n if not is_valid_agent_name(name):\n return (\"Invalid teammate name: use 1-64 letters, digits, \"\n \"underscores, or dashes\")\n with team_lock:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n active_teammates[name] = \"working\"\n plan_gates[name] = \"not_required\"\n\n system = (f\"You are '{name}', a {role}. \"\n \"Use tools to complete assigned work. \"\n \"When idle, the runtime may assign a ready task from the shared \"\n \"board. \"\n \"When asked for a plan, call submit_plan before bash or \"\n \"write_file and wait for approval. End each assignment with a \"\n \"concise result; the runtime delivers it to Lead.\")\n\n def run():\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send a message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a work plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List tasks on the shared board.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a ready task from the shared board.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an owned task completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n sub_handlers = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"send_message\": lambda to, content: _teammate_send_message(\n name, to, content),\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": run_list_tasks,\n \"claim_task\": lambda task_id: claim_task(task_id, owner=name),\n \"complete_task\": complete_task,\n }\n\n def handle_messages(inbox: list[dict]) -> bool:\n \"\"\"Return True when a shutdown request ends the teammate.\"\"\"\n work_messages = []\n for msg in inbox:\n msg_type = msg.get(\"type\", \"message\")\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n if msg_type == \"shutdown_request\":\n accepted, notice = apply_shutdown_request(name, msg)\n if not accepted:\n work_messages.append(notice)\n continue\n request_id = notice\n BUS.send(name, \"lead\", \"Shutdown acknowledged.\",\n \"shutdown_response\",\n {\"request_id\": request_id, \"approve\": True})\n return True\n if msg_type == \"plan_approval_response\":\n _, notice = apply_plan_response(name, msg)\n work_messages.append(notice)\n continue\n if msg_type == \"plan_request\":\n work_messages.append(\n f\"[Plan required] {msg['content']}\"\n )\n continue\n work_messages.append(\n f\"[Message from {msg['from']}] {msg['content']}\"\n )\n if work_messages:\n messages.append({\"role\": \"user\",\n \"content\": \"\\n\".join(work_messages)})\n return False\n\n should_stop = False\n while not should_stop:\n with team_lock:\n active_teammates[name] = \"working\"\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception as exc:\n BUS.send(name, \"lead\",\n f\"{type(exc).__name__}: {exc}\", \"error\")\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason == \"tool_use\":\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n output = _run_teammate_tool(name, block, sub_handlers)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n continue\n\n summary = _last_assistant_text(response.content)\n gate = plan_gates.get(name, \"not_required\")\n if gate != \"pending\" and summary:\n BUS.send(name, \"lead\", summary, \"result\")\n if gate == \"pending\":\n with team_lock:\n active_teammates[name] = \"waiting_approval\"\n else:\n with team_lock:\n active_teammates[name] = \"idle\"\n BUS.send(name, \"lead\", \"Waiting for more work.\",\n \"idle_notification\")\n\n while True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n should_stop = handle_messages(inbox)\n if should_stop or messages[-1][\"role\"] == \"user\":\n break\n continue\n\n task = claim_next_task(name)\n if task:\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}\"\n ),\n })\n print(f\" \\033[32m[idle] {name} claimed \"\n f\"{task.id}: {task.subject}\\033[0m\")\n break\n\n with team_lock:\n active_teammates.pop(name, None)\n plan_gates.pop(name, None)\n plan_request_ids.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role} (autonomous)\"\n\n\n# ── Lead Team Tools ──\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n if to not in active_teammates:\n return f\"Teammate '{to}' is not active\"\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\ndef run_request_shutdown(teammate: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n request_id = new_request_id()\n pending_requests[request_id] = ProtocolState(\n request_id=request_id,\n type=\"shutdown\",\n sender=\"lead\",\n target=teammate,\n status=\"pending\",\n payload=\"\",\n )\n BUS.send(\"lead\", teammate, \"Finish the current step and shut down.\",\n \"shutdown_request\", {\"request_id\": request_id})\n return f\"Shutdown requested from {teammate} ({request_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n plan_gates[teammate] = \"required\"\n BUS.send(\"lead\", teammate, task, \"plan_request\")\n return f\"Plan requested from {teammate}\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.type != \"plan_approval\":\n return f\"Request {request_id} is not a plan\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n if plan_request_ids.get(state.sender) != request_id:\n return f\"Request {request_id} is not the current plan\"\n state.status = \"approved\" if approve else \"rejected\"\n content = feedback or (\"Plan approved.\" if approve\n else \"Revise the plan and submit it again.\")\n BUS.send(\"lead\", state.sender, content, \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n return f\"Plan {state.status} ({request_id})\"\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a new task with optional blockedBy dependencies.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks with status, owner, and dependencies.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task. Sets owner, changes status to in_progress.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task. Reports unblocked downstream tasks.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": \"Schedule a cron job. cron is 5-field: min hour dom month dow.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"cron\": {\"type\": \"string\",\n \"description\": \"5-field cron expression\"},\n \"prompt\": {\"type\": \"string\",\n \"description\": \"Message to inject when fired\"},\n \"recurring\": {\"type\": \"boolean\",\n \"description\": \"True=recurring, False=one-shot\"},\n \"durable\": {\"type\": \"boolean\",\n \"description\": \"True=persist to disk\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\",\n \"description\": \"List all registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"cancel_cron\",\n \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn a teammate agent in a background thread.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9_-]{1,64}$\",\n },\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send a message to a teammate via MessageBus.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Ask an active teammate to shut down gracefully.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Require a teammate to submit a plan before changing files.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan by request_id.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n]\n\n\n# ── Context ──\n\ndef update_context(context: dict, messages: list) -> dict:\n \"\"\"Derive context from real state.\"\"\"\n memories = \"\"\n if MEMORY_INDEX.exists():\n content = MEMORY_INDEX.read_text().strip()\n if content:\n memories = content\n return {\n \"enabled_tools\": [t[\"name\"] for t in TOOLS],\n \"workspace\": str(WORKDIR),\n \"memories\": memories,\n }\n\n\n# ── Agent Loop ──\n# Keep the loop focused on the mechanisms introduced in this chapter.\n# Fired cron entries are injected at the start of each model turn.\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n # Consume fired cron jobs → inject as messages\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[inject cron] {job.prompt[:50]}\\033[0m\")\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\",\n \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": f\"[Background task {bg_id} started] \"\n f\"Result will be available when complete.\"})\n else:\n output = execute_tool(block)\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n\n # Merge background tool results + notifications into one user message\n user_content = list(results)\n bg_notifications = collect_background_results()\n if bg_notifications:\n for notif in bg_notifications:\n user_content.append({\"type\": \"text\", \"text\": notif})\n messages.append({\"role\": \"user\", \"content\": user_content})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s16: autonomous agents\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n\n # input() and a 1s poller (teammate inbox or background results) feed one\n # event queue (issues #291, #46).\n events = queue.Queue()\n\n def input_reader():\n while True:\n try:\n line = input(\"\\033[36ms16 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n events.put((\"quit\", None))\n return\n events.put((\"user\", line))\n\n def inbox_poller():\n # Poll ~1s and wake the Lead when async results are ready: teammate\n # inbox messages or completed background tasks. Don't gate on\n # active_teammates: a teammate sends its result and then removes itself,\n # so the final message can outlive its registry entry.\n while True:\n time.sleep(1)\n if BUS.peek(\"lead\") or has_pending_background():\n events.put((\"wake\", None))\n\n threading.Thread(target=input_reader, daemon=True).start()\n threading.Thread(target=inbox_poller, daemon=True).start()\n\n had_teammates = False\n while True:\n kind, payload = events.get()\n if kind == \"quit\":\n break\n if kind == \"user\":\n if payload.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": payload})\n else: # \"wake\": teammate inbox or background results are ready\n parts = []\n inbox = consume_lead_inbox()\n if inbox:\n parts.append(format_team_events(inbox))\n bg = collect_background_results()\n parts.extend(bg)\n if not parts:\n continue # already drained by an earlier wake (idempotent)\n history.append({\"role\": \"user\", \"content\": \"\\n\".join(parts)})\n print(f\"\\n\\033[33m[wake: {len(inbox)} team events + \"\n f\"{len(bg)} background \"\n f\"-> new turn]\\033[0m\")\n\n # One turn for whichever source woke us.\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n # Announce once after all requested shutdowns have completed.\n if active_teammates:\n had_teammates = True\n elif had_teammates and not BUS.peek(\"lead\") and not has_pending_background():\n print(\"\\033[32m[all teammates shut down]\\033[0m\")\n had_teammates = False\n print()\n", "images": [ { - "src": "/course-assets/s17_autonomous_agents/autonomous-agents-overview.svg", + "src": "/course-assets/s16_autonomous_agents/autonomous-agents-overview.svg", "alt": "autonomous agents overview" } ] }, { - "id": "s18", - "filename": "s18_worktree_isolation/code.py", + "id": "s17", + "filename": "s17_worktree_isolation/code.py", "title": "Worktree Isolation", "subtitle": "Separate Directories, No Conflicts", - "loc": 810, + "loc": 967, "tools": [ "bash", "read_file", @@ -2510,7 +2454,6 @@ "create_task", "get_task", "spawn_teammate", - "check_inbox", "request_shutdown", "request_plan", "review_plan", @@ -2528,247 +2471,277 @@ "classes": [ { "name": "Task", - "startLine": 58, - "endLine": 67 + "startLine": 59, + "endLine": 68 }, { "name": "MessageBus", - "startLine": 347, - "endLine": 368 + "startLine": 365, + "endLine": 420 }, { "name": "ProtocolState", - "startLine": 375, - "endLine": 384 + "startLine": 430, + "endLine": 439 } ], "functions": [ { "name": "_task_path", "signature": "def _task_path(task_id: str)", - "startLine": 68 + "startLine": 69 }, { "name": "save_task", "signature": "def save_task(task: Task)", - "startLine": 84 + "startLine": 85 }, { "name": "load_task", "signature": "def load_task(task_id: str)", - "startLine": 88 + "startLine": 89 }, { "name": "list_tasks", "signature": "def list_tasks()", - "startLine": 92 + "startLine": 93 }, { "name": "get_task_json", "signature": "def get_task_json(task_id: str)", - "startLine": 97 + "startLine": 98 }, { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 102 + "startLine": 103 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 112 + "startLine": 113 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 133 + "startLine": 139 }, { "name": "validate_worktree_name", "signature": "def validate_worktree_name(name: str)", - "startLine": 156 + "startLine": 162 }, { "name": "run_git", "signature": "def run_git(args: list[str])", - "startLine": 168 + "startLine": 174 }, { "name": "log_event", "signature": "def log_event(event_type: str, worktree_name: str, task_id: str = \"\")", - "startLine": 180 + "startLine": 186 }, { "name": "create_worktree", "signature": "def create_worktree(name: str, task_id: str = \"\")", - "startLine": 189 + "startLine": 195 }, { "name": "bind_task_to_worktree", "signature": "def bind_task_to_worktree(task_id: str, worktree_name: str)", - "startLine": 207 + "startLine": 213 }, { "name": "_count_worktree_changes", "signature": "def _count_worktree_changes(path: Path)", - "startLine": 215 + "startLine": 221 }, { "name": "remove_worktree", "signature": "def remove_worktree(name: str, discard_changes: bool = False)", - "startLine": 229 + "startLine": 235 }, { "name": "keep_worktree", "signature": "def keep_worktree(name: str)", - "startLine": 256 + "startLine": 262 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 280 + "startLine": 291 }, { "name": "get_system_prompt", "signature": "def get_system_prompt(context: dict)", - "startLine": 292 + "startLine": 304 }, { "name": "safe_path", "signature": "def safe_path(p: str, cwd: Path = None)", - "startLine": 303 + "startLine": 315 }, { "name": "run_bash", "signature": "def run_bash(command: str, cwd: Path = None)", - "startLine": 311 + "startLine": 323 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None, cwd: Path = None)", - "startLine": 321 + "startLine": 333 }, { "name": "run_write", "signature": "def run_write(path: str, content: str, cwd: Path = None)", - "startLine": 331 + "startLine": 343 + }, + { + "name": "is_valid_agent_name", + "signature": "def is_valid_agent_name(name: str)", + "startLine": 361 }, { "name": "new_request_id", "signature": "def new_request_id()", - "startLine": 388 - }, - { - "name": "match_response", - "signature": "def match_response(response_type: str, request_id: str, approve: bool)", - "startLine": 392 + "startLine": 443 }, { "name": "consume_lead_inbox", "signature": "def consume_lead_inbox(route_protocol=True)", - "startLine": 412 + "startLine": 478 + }, + { + "name": "format_team_events", + "signature": "def format_team_events(msgs: list[dict])", + "startLine": 491 }, { "name": "scan_unclaimed_tasks", "signature": "def scan_unclaimed_tasks()", - "startLine": 430 + "startLine": 507 + }, + { + "name": "claim_next_task", + "signature": "def claim_next_task(name: str)", + "startLine": 516 + }, + { + "name": "_last_assistant_text", + "signature": "def _last_assistant_text(content)", + "startLine": 524 + }, + { + "name": "_run_teammate_tool", + "signature": "def _run_teammate_tool(name: str, block, handlers: dict)", + "startLine": 533 + }, + { + "name": "apply_plan_response", + "signature": "def apply_plan_response(name: str, msg: dict)", + "startLine": 542 + }, + { + "name": "apply_shutdown_request", + "signature": "def apply_shutdown_request(name: str, msg: dict)", + "startLine": 570 + }, + { + "name": "_teammate_send_message", + "signature": "def _teammate_send_message(from_name: str, to: str, content: str)", + "startLine": 591 }, { "name": "spawn_teammate_thread", "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", - "startLine": 489 + "startLine": 601 }, { "name": "_teammate_submit_plan", "signature": "def _teammate_submit_plan(from_name: str, plan: str)", - "startLine": 697 + "startLine": 837 }, { "name": "run_request_shutdown", "signature": "def run_request_shutdown(teammate: str)", - "startLine": 711 + "startLine": 857 }, { "name": "run_request_plan", "signature": "def run_request_plan(teammate: str, task: str)", - "startLine": 725 + "startLine": 874 }, { "name": "run_create_worktree", "signature": "def run_create_worktree(name: str, task_id: str = \"\")", - "startLine": 750 + "startLine": 907 }, { "name": "run_remove_worktree", "signature": "def run_remove_worktree(name: str, discard_changes: bool = False)", - "startLine": 754 + "startLine": 911 }, { "name": "run_keep_worktree", "signature": "def run_keep_worktree(name: str)", - "startLine": 758 + "startLine": 915 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 772 + "startLine": 929 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 782 + "startLine": 939 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 786 + "startLine": 943 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 790 + "startLine": 947 }, { "name": "run_spawn_teammate", "signature": "def run_spawn_teammate(name: str, role: str, prompt: str)", - "startLine": 794 + "startLine": 951 }, { "name": "run_send_message", "signature": "def run_send_message(to: str, content: str)", - "startLine": 798 - }, - { - "name": "run_check_inbox", - "signature": "def run_check_inbox()", - "startLine": 803 + "startLine": 955 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 935 + "startLine": 1081 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 944 + "startLine": 1090 } ], "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns18: Worktree Isolation — git worktree + task-directory binding + event log.\n\nRun: python s18_worktree_isolation/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s17:\n - Task dataclass gains worktree field (str | None)\n - validate_worktree_name: reject path traversal and illegal chars\n - create_worktree: validate name, git worktree add, optional task binding\n - bind_task_to_worktree: write worktree field only, keep task pending\n - remove_worktree: safety check before force, no auto-complete\n - run_git returns (ok, output), events only on success\n - Teammate tools: + complete_task, run in worktree cwd when bound\n - scan_unclaimed_tasks: uses can_start() for dependency checking\n - idle_poll: checks claim result, dispatches shutdown in IDLE\n - consume_lead_inbox: unified inbox consumer\n - 3 new Lead tools: create_worktree, remove_worktree, keep_worktree\n\nASCII topology:\n Main repo (/)\n ├── .worktrees/auth/ (branch: wt/auth) ← Task #1\n ├── .worktrees/ui/ (branch: wt/ui) ← Task #2\n ├── .tasks/task_xxx.json (worktree: \"auth\")\n └── .worktrees/events.jsonl\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12 + s18 worktree field) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n worktree: str | None = None # s18: bound worktree name\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task_json(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if _task_path(d).exists() and load_task(d).status != \"completed\"]\n missing = [d for d in task.blockedBy if not _task_path(d).exists()]\n parts = []\n if deps: parts.append(f\"blocked by: {deps}\")\n if missing: parts.append(f\"missing deps: {missing}\")\n return \"Cannot start — \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Worktree System (s18 new) ──\n\nWORKTREES_DIR = WORKDIR / \".worktrees\"\nWORKTREES_DIR.mkdir(exist_ok=True)\n\nVALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')\n\n\ndef validate_worktree_name(name: str) -> str | None:\n \"\"\"Return error message if invalid, None if valid.\"\"\"\n if not name:\n return \"Worktree name cannot be empty\"\n if name == \".\" or name == \"..\":\n return f\"'{name}' is not a valid worktree name\"\n if not VALID_WT_NAME.match(name):\n return (f\"Invalid worktree name '{name}': \"\n \"only letters, digits, dots, underscores, dashes (1-64 chars)\")\n return None\n\n\ndef run_git(args: list[str]) -> tuple[bool, str]:\n \"\"\"Run git command. Return (ok, output).\"\"\"\n try:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR,\n capture_output=True, text=True, timeout=30)\n out = (r.stdout + r.stderr).strip()\n out = out[:5000] if out else \"(no output)\"\n return r.returncode == 0, out\n except subprocess.TimeoutExpired:\n return False, \"Error: git timeout\"\n\n\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n \"\"\"Append a lifecycle event to events.jsonl.\"\"\"\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n events_file = WORKTREES_DIR / \"events.jsonl\"\n with open(events_file, \"a\") as f:\n f.write(json.dumps(event) + \"\\n\")\n\n\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n \"\"\"Create a git worktree with a dedicated branch. Optionally bind to a task.\"\"\"\n err = validate_worktree_name(name)\n if err:\n return f\"Error: {err}\"\n path = WORKTREES_DIR / name\n if path.exists():\n return f\"Worktree '{name}' already exists at {path}\"\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n print(f\" \\033[33m[worktree] created: {name} at {path}\\033[0m\")\n return f\"Worktree '{name}' created at {path}\"\n\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n \"\"\"Write worktree field to task. Keep status as pending for auto-claim.\"\"\"\n task = load_task(task_id)\n task.worktree = worktree_name\n save_task(task)\n print(f\" \\033[33m[bind] {task.subject} → worktree:{worktree_name}\\033[0m\")\n\n\ndef _count_worktree_changes(path: Path) -> tuple[int, int]:\n \"\"\"Count uncommitted files and commits in a worktree.\"\"\"\n try:\n r1 = subprocess.run([\"git\", \"status\", \"--porcelain\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])\n r2 = subprocess.run([\"git\", \"log\", \"@{push}..HEAD\", \"--oneline\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])\n return files, commits\n except Exception:\n return -1, -1\n\n\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n \"\"\"Remove worktree. Refuses if uncommitted changes unless discard_changes.\"\"\"\n err = validate_worktree_name(name)\n if err:\n return err\n path = WORKTREES_DIR / name\n if not path.exists():\n return f\"Worktree '{name}' not found\"\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files < 0:\n return (f\"Cannot verify worktree '{name}' status. \"\n \"Use discard_changes=true to force removal.\")\n if files > 0 or commits > 0:\n return (f\"Worktree '{name}' has {files} uncommitted file(s) \"\n f\"and {commits} unpushed commit(s). \"\n \"Use discard_changes=true to force removal, \"\n \"or keep_worktree to preserve for review.\")\n ok1, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok1:\n return f\"Failed to remove worktree directory for '{name}'\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n print(f\" \\033[33m[worktree] removed: {name}\\033[0m\")\n return f\"Worktree '{name}' removed\"\n\n\ndef keep_worktree(name: str) -> str:\n \"\"\"Keep worktree for manual review. Branch preserved.\"\"\"\n err = validate_worktree_name(name)\n if err:\n return err\n log_event(\"keep\", name)\n print(f\" \\033[36m[worktree] kept: {name}\\033[0m\")\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n\n\n# ── Prompt Assembly (from s10) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"spawn_teammate, send_message, check_inbox, \"\n \"request_shutdown, request_plan, review_plan, \"\n \"create_worktree, remove_worktree, keep_worktree.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_hash, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_hash, _last_prompt\n h = json.dumps(context, sort_keys=True)\n if h == _last_context_hash and _last_prompt:\n return _last_prompt\n _last_context_hash, _last_prompt = h, assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Basic Tools ──\n\ndef safe_path(p: str, cwd: Path = None) -> Path:\n base = cwd or WORKDIR\n path = (base / p).resolve()\n if not path.is_relative_to(base):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, cwd: Path = None) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None, cwd: Path = None) -> str:\n try:\n lines = safe_path(path, cwd).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str, cwd: Path = None) -> str:\n try:\n fp = safe_path(path, cwd)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# ── MessageBus (from s15) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\n\n\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, bool] = {}\n\n# ── Protocol State (from s16) ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n return f\"req_{random.randint(0, 999999):06d}\"\n\n\ndef match_response(response_type: str, request_id: str, approve: bool):\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n print(f\" \\033[31m[protocol] type mismatch: expected shutdown_response, \"\n f\"got {response_type}\\033[0m\")\n return\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n print(f\" \\033[31m[protocol] type mismatch: expected plan_approval_response, \"\n f\"got {response_type}\\033[0m\")\n return\n state.status = \"approved\" if approve else \"rejected\"\n icon = \"✓\" if approve else \"✗\"\n color = \"32\" if approve else \"31\"\n print(f\" \\033[{color}m[protocol] {state.type} {icon} \"\n f\"({request_id}: {state.status})\\033[0m\")\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n\n\n# ── Autonomous Agent (from s17, + worktree cwd) ──\n\nIDLE_POLL_INTERVAL = 5\nIDLE_TIMEOUT = 60\n\n\ndef scan_unclaimed_tasks() -> list[dict]:\n \"\"\"Find pending, unowned tasks with all dependencies completed.\"\"\"\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n\n\ndef idle_poll(agent_name: str, messages: list,\n name: str, role: str) -> tuple[str, str | None]:\n \"\"\"Poll for 60s. Return (result, auto_claimed_task_id).\"\"\"\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n\n inbox = BUS.read_inbox(agent_name)\n if inbox:\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"in idle ({req_id})\\033[0m\")\n return \"shutdown\", None\n\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(inbox) + \"\"})\n print(f\" \\033[36m[idle] {name} found inbox messages\\033[0m\")\n return \"work\", None\n\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task_data = unclaimed[0]\n result = claim_task(task_data[\"id\"], agent_name)\n if \"Claimed\" in result:\n wt_info = \"\"\n if task_data.get(\"worktree\"):\n wt_path = WORKTREES_DIR / task_data[\"worktree\"]\n wt_info = f\"\\nWork directory: {wt_path}\"\n messages.append({\"role\": \"user\",\n \"content\": f\"Task {task_data['id']}: \"\n f\"{task_data['subject']}{wt_info}\"})\n print(f\" \\033[32m[idle] {name} auto-claimed: \"\n f\"{task_data['subject']}\\033[0m\")\n return \"work\", task_data[\"id\"]\n print(f\" \\033[33m[idle] {name} claim failed: \"\n f\"{result}\\033[0m\")\n\n print(f\" \\033[31m[idle] {name} timeout ({IDLE_TIMEOUT}s)\\033[0m\")\n return \"timeout\", None\n\n\n# ── Teammate Thread (from s15 + s16 + s17 + s18) ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n\n system = (f\"You are '{name}', a {role}. \"\n f\"Use tools to complete tasks. \"\n f\"You can list and claim tasks from the board. \"\n f\"If a task has a worktree, work in that directory.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"({req_id})\\033[0m\")\n return True\n\n if msg_type == \"plan_approval_response\":\n approve = meta.get(\"approve\", False)\n if approve:\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved] Proceed with the task.\"})\n else:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan rejected] Feedback: {msg['content']}\"})\n return False\n\n def run():\n # Track current worktree for this teammate's cwd\n wt_ctx = {\"path\": None}\n\n def _wt_cwd() -> Path | None:\n p = wt_ctx[\"path\"]\n return Path(p) if p else None\n\n def _run_bash(command: str) -> str:\n return run_bash(command, cwd=_wt_cwd())\n\n def _run_read(path: str) -> str:\n return run_read(path, cwd=_wt_cwd())\n\n def _run_write(path: str, content: str) -> str:\n return run_write(path, content, cwd=_wt_cwd())\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n # Set worktree cwd if task has one\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n else:\n wt_ctx[\"path\"] = None\n return result\n\n def _run_complete_task(task_id: str):\n result = complete_task(task_id)\n wt_ctx[\"path\"] = None\n return result\n\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks on the board.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n sub_handlers = {\n \"bash\": _run_bash, \"read_file\": _run_read,\n \"write_file\": _run_write,\n \"send_message\": lambda to, content: (BUS.send(name, to, content),\n \"Sent\")[1],\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n # Outer loop: WORK → IDLE cycle\n while True:\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n\n # WORK phase\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n if inbox and not should_shutdown:\n non_protocol = [m for m in inbox\n if m.get(\"type\") == \"message\"]\n if non_protocol:\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(non_protocol) + \"\"})\n\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n handler = sub_handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if should_shutdown:\n break\n\n # IDLE phase\n idle_result, claimed_task_id = idle_poll(name, messages, name, role)\n if idle_result == \"shutdown\":\n break\n if idle_result == \"timeout\":\n break\n if idle_result == \"work\" and claimed_task_id:\n task = load_task(claimed_task_id)\n if task.get(\"worktree\"):\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task[\"worktree\"])\n else:\n wt_ctx[\"path\"] = None\n\n # Summary\n summary = \"Done.\"\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\" and isinstance(msg[\"content\"], list):\n for b in msg[\"content\"]:\n if getattr(b, \"type\", None) == \"text\":\n summary = b.text\n break\n else:\n continue\n break\n BUS.send(name, \"lead\", summary, \"result\")\n active_teammates.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n active_teammates[name] = True\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role} (autonomous)\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id}). Waiting for approval...\"\n\n\n# ── Lead Protocol Tools (from s16) ──\n\ndef run_request_shutdown(teammate: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Please shut down gracefully.\",\n \"shutdown_request\",\n {\"request_id\": req_id})\n print(f\" \\033[35m[protocol] shutdown_request → {teammate} \"\n f\"({req_id})\\033[0m\")\n return f\"Shutdown request sent to {teammate} (req: {req_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n BUS.send(\"lead\", teammate, f\"Please submit a plan for: {task}\",\n \"message\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n icon = \"✓\" if approve else \"✗\"\n print(f\" \\033[32m[protocol] plan {icon} ({request_id})\\033[0m\")\n return f\"Plan {'approved' if approve else 'rejected'} ({request_id})\"\n\n\n# ── Lead Worktree Tools (s18 new) ──\n\ndef run_create_worktree(name: str, task_id: str = \"\") -> str:\n return create_worktree(name, task_id)\n\n\ndef run_remove_worktree(name: str, discard_changes: bool = False) -> str:\n return remove_worktree(name, discard_changes)\n\n\ndef run_keep_worktree(name: str) -> str:\n return keep_worktree(name)\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n return get_task_json(task_id)\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\ndef run_check_inbox() -> str:\n msgs = consume_lead_inbox(route_protocol=True)\n if not msgs:\n return \"(inbox empty)\"\n lines = []\n for m in msgs:\n meta = m.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n tag = f\" [{m['type']} req:{req_id}]\" if req_id else f\" [{m['type']}]\"\n lines.append(f\" [{m['from']}]{tag} {m['content'][:200]}\")\n return \"\\n\".join(lines)\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn an autonomous teammate agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"check_inbox\",\n \"description\": \"Check inbox for messages and protocol responses.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down gracefully.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan for review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n # s18 new: worktree tools\n {\"name\": \"create_worktree\",\n \"description\": \"Create an isolated git worktree with its own branch.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"task_id\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"remove_worktree\",\n \"description\": \"Remove a worktree. Refuses if uncommitted changes unless discard_changes=true.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"discard_changes\": {\"type\": \"boolean\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"keep_worktree\",\n \"description\": \"Keep a worktree for manual review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message, \"check_inbox\": run_check_inbox,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n \"create_worktree\": run_create_worktree,\n \"remove_worktree\": run_remove_worktree,\n \"keep_worktree\": run_keep_worktree,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\"memories\": memories}\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s18: worktree isolation\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = {\"memories\": \"\"}\n while True:\n try:\n query = input(\"\\033[36ms18 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n # Consume lead inbox: route protocol + inject into history\n inbox = consume_lead_inbox(route_protocol=True)\n if inbox:\n inbox_text = \"\\n\".join(\n f\"From {m['from']} [{m.get('type', 'message')}]: \"\n f\"{m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns17: Worktree Isolation — git worktree + task-directory binding + event log.\n\nRun: python s17_worktree_isolation/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s16:\n - Task dataclass gains worktree field (str | None)\n - validate_worktree_name: reject path traversal and illegal chars\n - create_worktree: validate name, git worktree add, optional task binding\n - bind_task_to_worktree: write worktree field only, keep task pending\n - remove_worktree: safety check before force, no auto-complete\n - run_git returns (ok, output), events only on success\n - Teammate tools: + complete_task, run in worktree cwd when bound\n - scan_unclaimed_tasks: uses can_start() for dependency checking\n - Idle teammates wait for messages, then scan and claim ready tasks\n - consume_lead_inbox: unified inbox consumer\n - 3 new Lead tools: create_worktree, remove_worktree, keep_worktree\n\nASCII topology:\n Main repo (/)\n ├── .worktrees/auth/ (branch: wt/auth) ← Task #1\n ├── .worktrees/ui/ (branch: wt/ui) ← Task #2\n ├── .tasks/task_xxx.json (worktree: \"auth\")\n └── .worktrees/events.jsonl\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, queue, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System (from s12 + s17 worktree field) ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\ntask_lock = threading.RLock()\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n worktree: str | None = None # s17: bound worktree name\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task_json(task_id: str) -> str:\n task = load_task(task_id)\n return json.dumps(asdict(task), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if (_task_path(d).exists()\n and load_task(d).status != \"completed\")]\n missing = [d for d in task.blockedBy\n if not _task_path(d).exists()]\n parts = []\n if deps:\n parts.append(f\"blocked by: {deps}\")\n if missing:\n parts.append(f\"missing deps: {missing}\")\n return \"Cannot start: \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Worktree System (s17 new) ──\n\nWORKTREES_DIR = WORKDIR / \".worktrees\"\nWORKTREES_DIR.mkdir(exist_ok=True)\n\nVALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')\n\n\ndef validate_worktree_name(name: str) -> str | None:\n \"\"\"Return error message if invalid, None if valid.\"\"\"\n if not name:\n return \"Worktree name cannot be empty\"\n if name == \".\" or name == \"..\":\n return f\"'{name}' is not a valid worktree name\"\n if not VALID_WT_NAME.match(name):\n return (f\"Invalid worktree name '{name}': \"\n \"only letters, digits, dots, underscores, dashes (1-64 chars)\")\n return None\n\n\ndef run_git(args: list[str]) -> tuple[bool, str]:\n \"\"\"Run git command. Return (ok, output).\"\"\"\n try:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR,\n capture_output=True, text=True, timeout=30)\n out = (r.stdout + r.stderr).strip()\n out = out[:5000] if out else \"(no output)\"\n return r.returncode == 0, out\n except subprocess.TimeoutExpired:\n return False, \"Error: git timeout\"\n\n\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n \"\"\"Append a lifecycle event to events.jsonl.\"\"\"\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n events_file = WORKTREES_DIR / \"events.jsonl\"\n with open(events_file, \"a\") as f:\n f.write(json.dumps(event) + \"\\n\")\n\n\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n \"\"\"Create a git worktree with a dedicated branch. Optionally bind to a task.\"\"\"\n err = validate_worktree_name(name)\n if err:\n return f\"Error: {err}\"\n path = WORKTREES_DIR / name\n if path.exists():\n return f\"Worktree '{name}' already exists at {path}\"\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n print(f\" \\033[33m[worktree] created: {name} at {path}\\033[0m\")\n return f\"Worktree '{name}' created at {path}\"\n\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n \"\"\"Write worktree field to task. Keep status as pending for auto-claim.\"\"\"\n task = load_task(task_id)\n task.worktree = worktree_name\n save_task(task)\n print(f\" \\033[33m[bind] {task.subject} → worktree:{worktree_name}\\033[0m\")\n\n\ndef _count_worktree_changes(path: Path) -> tuple[int, int]:\n \"\"\"Count uncommitted files and commits in a worktree.\"\"\"\n try:\n r1 = subprocess.run([\"git\", \"status\", \"--porcelain\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])\n r2 = subprocess.run([\"git\", \"log\", \"@{push}..HEAD\", \"--oneline\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])\n return files, commits\n except Exception:\n return -1, -1\n\n\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n \"\"\"Remove worktree. Refuses if uncommitted changes unless discard_changes.\"\"\"\n err = validate_worktree_name(name)\n if err:\n return err\n path = WORKTREES_DIR / name\n if not path.exists():\n return f\"Worktree '{name}' not found\"\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files < 0:\n return (f\"Cannot verify worktree '{name}' status. \"\n \"Use discard_changes=true to force removal.\")\n if files > 0 or commits > 0:\n return (f\"Worktree '{name}' has {files} uncommitted file(s) \"\n f\"and {commits} unpushed commit(s). \"\n \"Use discard_changes=true to force removal, \"\n \"or keep_worktree to preserve for review.\")\n ok1, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok1:\n return f\"Failed to remove worktree directory for '{name}'\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n print(f\" \\033[33m[worktree] removed: {name}\\033[0m\")\n return f\"Worktree '{name}' removed\"\n\n\ndef keep_worktree(name: str) -> str:\n \"\"\"Keep worktree for manual review. Branch preserved.\"\"\"\n err = validate_worktree_name(name)\n if err:\n return err\n log_event(\"keep\", name)\n print(f\" \\033[36m[worktree] kept: {name}\\033[0m\")\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n\n\n# ── Prompt Assembly (from s10) ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"spawn_teammate, send_message, \"\n \"request_shutdown, request_plan, review_plan, \"\n \"create_worktree, remove_worktree, keep_worktree.\",\n \"teams\": (\n \"When parallel work would help, first propose a small team with clear \"\n \"responsibilities and wait for the user's confirmation. Do not call \"\n \"spawn_teammate before the user confirms.\"\n ),\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"teams\"],\n PROMPT_SECTIONS[\"workspace\"]]\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n return \"\\n\\n\".join(sections)\n\n\n_last_context_hash, _last_prompt = None, None\n\n\ndef get_system_prompt(context: dict) -> str:\n global _last_context_hash, _last_prompt\n h = json.dumps(context, sort_keys=True)\n if h == _last_context_hash and _last_prompt:\n return _last_prompt\n _last_context_hash, _last_prompt = h, assemble_system_prompt(context)\n return _last_prompt\n\n\n# ── Basic Tools ──\n\ndef safe_path(p: str, cwd: Path = None) -> Path:\n base = cwd or WORKDIR\n path = (base / p).resolve()\n if not path.is_relative_to(base):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, cwd: Path = None) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None, cwd: Path = None) -> str:\n try:\n lines = safe_path(path, cwd).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str, cwd: Path = None) -> str:\n try:\n fp = safe_path(path, cwd)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# ── MessageBus (from s15) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\nMAILBOX_ROOT = MAILBOX_DIR.resolve()\nVALID_AGENT_NAME = re.compile(r\"^[A-Za-z0-9_-]{1,64}$\")\n\n\ndef is_valid_agent_name(name: str) -> bool:\n return bool(VALID_AGENT_NAME.fullmatch(name))\n\n\nclass MessageBus:\n def __init__(self):\n self._lock = threading.RLock()\n self._changed = threading.Condition(self._lock)\n\n def _path(self, agent: str) -> Path:\n if not is_valid_agent_name(agent):\n raise ValueError(f\"Invalid mailbox recipient: {agent!r}\")\n path = (MAILBOX_DIR / f\"{agent}.jsonl\").resolve()\n if not path.is_relative_to(MAILBOX_ROOT):\n raise ValueError(f\"Mailbox path escapes directory: {agent!r}\")\n return path\n\n def _read_unlocked(self, agent: str) -> list[dict]:\n inbox = self._path(agent)\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict | None = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n with self._changed:\n with open(self._path(to_agent), \"a\") as f:\n f.write(json.dumps(msg, ensure_ascii=False) + \"\\n\")\n self._changed.notify_all()\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n with self._lock:\n return self._read_unlocked(agent)\n\n def peek(self, agent: str) -> bool:\n with self._lock:\n inbox = self._path(agent)\n return inbox.exists() and inbox.stat().st_size > 0\n\n def wait_for_messages(self, agent: str,\n timeout: float | None = None) -> list[dict]:\n deadline = None if timeout is None else time.monotonic() + timeout\n with self._changed:\n while not self.peek(agent):\n remaining = (None if deadline is None\n else deadline - time.monotonic())\n if remaining is not None and remaining <= 0:\n return []\n self._changed.wait(remaining)\n return self._read_unlocked(agent)\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, str] = {}\nplan_gates: dict[str, str] = {}\nplan_request_ids: dict[str, str] = {}\nteam_lock = threading.RLock()\n\n# ── Protocol State (from s15) ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n while True:\n request_id = f\"req_{random.randint(0, 999999):06d}\"\n if request_id not in pending_requests:\n return request_id\n\n\ndef match_response(response_type: str, request_id: str, approve: bool,\n from_agent: str, to_agent: str) -> bool:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return False\n expected = {\n \"shutdown\": \"shutdown_response\",\n \"plan_approval\": \"plan_approval_response\",\n }[state.type]\n if response_type != expected:\n print(f\" \\033[31m[protocol] expected {expected}, \"\n f\"got {response_type}\\033[0m\")\n return False\n if from_agent != state.target or to_agent != state.sender:\n print(f\" \\033[31m[protocol] {request_id} responder mismatch\\033[0m\")\n return False\n if state.status != \"pending\":\n return False\n state.status = \"approved\" if approve else \"rejected\"\n icon = \"✓\" if approve else \"✗\"\n color = \"32\" if approve else \"31\"\n print(f\" \\033[{color}m[protocol] {state.type} {icon} \"\n f\"({request_id}: {state.status})\\033[0m\")\n return True\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False),\n msg.get(\"from\", \"\"), msg.get(\"to\", \"\"))\n return msgs\n\n\ndef format_team_events(msgs: list[dict]) -> str:\n lines = []\n for msg in msgs:\n request_id = msg.get(\"metadata\", {}).get(\"request_id\")\n suffix = f\" request_id={request_id}\" if request_id else \"\"\n lines.append(\n f\"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}\"\n )\n return \"[Team events]\\n\" + \"\\n\".join(lines)\n\n\n# ── Autonomous Agent (from s16, + worktree cwd) ──\n\nIDLE_SCAN_INTERVAL = 2.0\n\n\ndef scan_unclaimed_tasks() -> list[Task]:\n return [\n task for task in list_tasks()\n if (task.status == \"pending\"\n and task.owner is None\n and can_start(task.id))\n ]\n\n\ndef claim_next_task(name: str) -> Task | None:\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n\n\ndef _last_assistant_text(content) -> str:\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n return block.text.strip()\n if isinstance(block, dict) and block.get(\"type\") == \"text\":\n return str(block.get(\"text\", \"\")).strip()\n return \"\"\n\n\ndef _run_teammate_tool(name: str, block, handlers: dict) -> str:\n gate = plan_gates.get(name, \"not_required\")\n if (block.name in {\"bash\", \"write_file\"}\n and gate not in {\"not_required\", \"approved\"}):\n return f\"Blocked: plan status is {gate}.\"\n handler = handlers.get(block.name)\n return str(handler(**block.input)) if handler else f\"Unknown tool: {block.name}\"\n\n\ndef apply_plan_response(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Apply only the Lead response for this teammate's current plan.\"\"\"\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n expected_id = plan_request_ids.get(name)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and request_id == expected_id\n and state is not None\n and state.type == \"plan_approval\"\n and state.sender == name\n and state.target == \"lead\"\n and state.status in {\"approved\", \"rejected\"}\n and metadata.get(\"approve\", False)\n == (state.status == \"approved\")\n )\n if not valid:\n return False, \"[Ignored plan response: request mismatch]\"\n plan_gates[name] = state.status\n active_teammates[name] = \"working\"\n plan_request_ids.pop(name, None)\n outcome = state.status\n return True, f\"[Plan {outcome}] {msg['content']}\"\n\n\ndef apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Accept only a pending shutdown request sent by Lead to this teammate.\"\"\"\n request_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and state is not None\n and state.type == \"shutdown\"\n and state.sender == \"lead\"\n and state.target == name\n and state.status == \"pending\"\n and active_teammates.get(name) != \"stopping\"\n )\n if not valid:\n return False, \"[Ignored shutdown request: request mismatch]\"\n active_teammates[name] = \"stopping\"\n return True, request_id\n\n\ndef _teammate_send_message(from_name: str, to: str, content: str) -> str:\n with team_lock:\n if to != \"lead\" and to not in active_teammates:\n return f\"Agent '{to}' is not active\"\n BUS.send(from_name, to, content)\n return f\"Sent to {to}\"\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if not is_valid_agent_name(name):\n return (\"Invalid teammate name: use 1-64 letters, digits, \"\n \"underscores, or dashes\")\n with team_lock:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n active_teammates[name] = \"working\"\n plan_gates[name] = \"not_required\"\n\n system = (f\"You are '{name}', a {role}. \"\n \"Use tools to complete tasks. \"\n \"You can list and claim tasks from the board. \"\n \"If a task has a worktree, work in that directory. \"\n \"When asked for a plan, submit it before bash or write_file \"\n \"and wait for approval.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n accepted, notice = apply_shutdown_request(name, msg)\n if not accepted:\n messages.append({\"role\": \"user\", \"content\": notice})\n return False\n req_id = notice\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"({req_id})\\033[0m\")\n return True\n\n if msg_type == \"plan_approval_response\":\n _, notice = apply_plan_response(name, msg)\n messages.append({\"role\": \"user\",\n \"content\": notice})\n elif msg_type == \"plan_request\":\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan required] {msg['content']}\"})\n elif msg_type == \"message\":\n messages.append({\"role\": \"user\",\n \"content\": f\"[Message from {msg['from']}] {msg['content']}\"})\n return False\n\n def run():\n # Track current worktree for this teammate's cwd\n wt_ctx = {\"path\": None}\n\n def _wt_cwd() -> Path | None:\n p = wt_ctx[\"path\"]\n return Path(p) if p else None\n\n def _run_bash(command: str) -> str:\n return run_bash(command, cwd=_wt_cwd())\n\n def _run_read(path: str) -> str:\n return run_read(path, cwd=_wt_cwd())\n\n def _run_write(path: str, content: str) -> str:\n return run_write(path, content, cwd=_wt_cwd())\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n # Set worktree cwd if task has one\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n else:\n wt_ctx[\"path\"] = None\n return result\n\n def _run_complete_task(task_id: str):\n result = complete_task(task_id)\n wt_ctx[\"path\"] = None\n return result\n\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks on the board.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n sub_handlers = {\n \"bash\": _run_bash, \"read_file\": _run_read,\n \"write_file\": _run_write,\n \"send_message\": lambda to, content: _teammate_send_message(\n name, to, content),\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n # Outer loop: WORK → IDLE cycle\n while True:\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n\n # WORK phase\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n summary = _last_assistant_text(response.content)\n gate = plan_gates.get(name, \"not_required\")\n if gate != \"pending\" and summary:\n BUS.send(name, \"lead\", summary, \"result\")\n if gate == \"pending\":\n with team_lock:\n active_teammates[name] = \"waiting_approval\"\n else:\n with team_lock:\n active_teammates[name] = \"idle\"\n BUS.send(name, \"lead\", \"Waiting for more work.\",\n \"idle_notification\")\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = _run_teammate_tool(name, block, sub_handlers)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if should_shutdown:\n break\n\n # IDLE phase: messages take priority, then scan the task board.\n while True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n for msg in inbox:\n if handle_inbox_message(name, msg, messages):\n should_shutdown = True\n break\n if should_shutdown or messages[-1][\"role\"] == \"user\":\n break\n continue\n\n task = claim_next_task(name)\n if not task:\n continue\n wt_ctx[\"path\"] = (str(WORKTREES_DIR / task.worktree)\n if task.worktree else None)\n workdir = (f\"\\nWork directory: {wt_ctx['path']}\"\n if wt_ctx[\"path\"] else \"\")\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}{workdir}\"\n ),\n })\n print(f\" \\033[32m[idle] {name} claimed \"\n f\"{task.id}: {task.subject}\\033[0m\")\n break\n if should_shutdown:\n break\n\n with team_lock:\n active_teammates.pop(name, None)\n plan_gates.pop(name, None)\n plan_request_ids.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role} (autonomous)\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n with team_lock:\n if plan_gates.get(from_name) == \"pending\":\n return \"A plan is already waiting for review.\"\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n plan_gates[from_name] = \"pending\"\n plan_request_ids[from_name] = req_id\n active_teammates[from_name] = \"waiting_approval\"\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id}). Waiting for approval...\"\n\n\n# ── Lead Protocol Tools (from s15) ──\n\ndef run_request_shutdown(teammate: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Please shut down gracefully.\",\n \"shutdown_request\",\n {\"request_id\": req_id})\n print(f\" \\033[35m[protocol] shutdown_request → {teammate} \"\n f\"({req_id})\\033[0m\")\n return f\"Shutdown request sent to {teammate} (req: {req_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n plan_gates[teammate] = \"required\"\n BUS.send(\"lead\", teammate, task, \"plan_request\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.type != \"plan_approval\":\n return f\"Request {request_id} is not a plan\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n if plan_request_ids.get(state.sender) != request_id:\n return f\"Request {request_id} is not the current plan\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n icon = \"✓\" if approve else \"✗\"\n print(f\" \\033[32m[protocol] plan {icon} ({request_id})\\033[0m\")\n return f\"Plan {'approved' if approve else 'rejected'} ({request_id})\"\n\n\n# ── Lead Worktree Tools (s17 new) ──\n\ndef run_create_worktree(name: str, task_id: str = \"\") -> str:\n return create_worktree(name, task_id)\n\n\ndef run_remove_worktree(name: str, discard_changes: bool = False) -> str:\n return remove_worktree(name, discard_changes)\n\n\ndef run_keep_worktree(name: str) -> str:\n return keep_worktree(name)\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n return get_task_json(task_id)\n\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\n\ndef run_send_message(to: str, content: str) -> str:\n if to not in active_teammates:\n return f\"Teammate '{to}' is not active\"\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\n\n# ── Tool Definitions ──\n\nTOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\",\n \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\",\n \"description\": \"Get full details of a specific task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"spawn_teammate\",\n \"description\": \"Spawn an autonomous teammate agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9_-]{1,64}$\",\n },\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down gracefully.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan for review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\n \"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n # s17 new: worktree tools\n {\"name\": \"create_worktree\",\n \"description\": \"Create an isolated git worktree with its own branch.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"task_id\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"remove_worktree\",\n \"description\": \"Remove a worktree. Refuses if uncommitted changes unless discard_changes=true.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"discard_changes\": {\"type\": \"boolean\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"keep_worktree\",\n \"description\": \"Keep a worktree for manual review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n]\n\nTOOL_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n \"create_worktree\": run_create_worktree,\n \"remove_worktree\": run_remove_worktree,\n \"keep_worktree\": run_keep_worktree,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\"memories\": memories}\n\n\n# ── Agent Loop ──\n\ndef agent_loop(messages: list, context: dict):\n system = get_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=TOOLS, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = TOOL_HANDLERS.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n context = update_context(context, messages)\n system = get_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s17: worktree isolation\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = {\"memories\": \"\"}\n\n events = queue.Queue()\n\n def input_reader():\n while True:\n try:\n line = input(\"\\033[36ms17 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n events.put((\"quit\", None))\n return\n events.put((\"user\", line))\n\n def inbox_poller():\n while True:\n time.sleep(1)\n if BUS.peek(\"lead\"):\n events.put((\"wake\", None))\n\n threading.Thread(target=input_reader, daemon=True).start()\n threading.Thread(target=inbox_poller, daemon=True).start()\n\n had_teammates = False\n while True:\n kind, payload = events.get()\n if kind == \"quit\":\n break\n if kind == \"user\":\n if payload.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": payload})\n else:\n inbox = consume_lead_inbox(route_protocol=True)\n if not inbox:\n continue\n history.append({\"role\": \"user\",\n \"content\": format_team_events(inbox)})\n print(f\"\\n\\033[33m[wake: {len(inbox)} team events \"\n f\"-> new turn]\\033[0m\")\n\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n if active_teammates:\n had_teammates = True\n elif had_teammates and not BUS.peek(\"lead\"):\n print(\"\\033[32m[all teammates shut down]\\033[0m\")\n had_teammates = False\n print()\n", "images": [ { - "src": "/course-assets/s18_worktree_isolation/worktree-overview.svg", + "src": "/course-assets/s17_worktree_isolation/worktree-overview.svg", "alt": "worktree overview" } ] }, { - "id": "s19", - "filename": "s19_mcp_plugin/code.py", + "id": "s18", + "filename": "s18_mcp_plugin/code.py", "title": "MCP Tools", "subtitle": "External Tools, Standard Protocol", - "loc": 837, + "loc": 1040, "tools": [ "bash", "read_file", @@ -2785,7 +2758,6 @@ "create_task", "get_task", "spawn_teammate", - "check_inbox", "request_shutdown", "request_plan", "review_plan", @@ -2806,277 +2778,307 @@ "classes": [ { "name": "Task", - "startLine": 53, - "endLine": 62 + "startLine": 54, + "endLine": 63 }, { "name": "MessageBus", - "startLine": 319, - "endLine": 340 + "startLine": 337, + "endLine": 392 }, { "name": "ProtocolState", - "startLine": 347, - "endLine": 356 + "startLine": 402, + "endLine": 411 }, { "name": "MCPClient", - "startLine": 660, - "endLine": 682 + "startLine": 879, + "endLine": 901 } ], "functions": [ { "name": "_task_path", "signature": "def _task_path(task_id: str)", - "startLine": 63 + "startLine": 64 }, { "name": "save_task", "signature": "def save_task(task: Task)", - "startLine": 79 + "startLine": 80 }, { "name": "load_task", "signature": "def load_task(task_id: str)", - "startLine": 83 + "startLine": 84 }, { "name": "list_tasks", "signature": "def list_tasks()", - "startLine": 87 + "startLine": 88 }, { "name": "get_task_json", "signature": "def get_task_json(task_id: str)", - "startLine": 92 + "startLine": 93 }, { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 96 + "startLine": 97 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 106 + "startLine": 107 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 127 + "startLine": 133 }, { "name": "validate_worktree_name", "signature": "def validate_worktree_name(name: str)", - "startLine": 150 + "startLine": 156 }, { "name": "run_git", "signature": "def run_git(args: list[str])", - "startLine": 161 + "startLine": 167 }, { "name": "log_event", "signature": "def log_event(event_type: str, worktree_name: str, task_id: str = \"\")", - "startLine": 171 + "startLine": 177 }, { "name": "create_worktree", "signature": "def create_worktree(name: str, task_id: str = \"\")", - "startLine": 179 + "startLine": 185 }, { "name": "bind_task_to_worktree", "signature": "def bind_task_to_worktree(task_id: str, worktree_name: str)", - "startLine": 196 + "startLine": 202 }, { "name": "_count_worktree_changes", "signature": "def _count_worktree_changes(path: Path)", - "startLine": 202 + "startLine": 208 }, { "name": "remove_worktree", "signature": "def remove_worktree(name: str, discard_changes: bool = False)", - "startLine": 215 + "startLine": 221 }, { "name": "keep_worktree", "signature": "def keep_worktree(name: str)", - "startLine": 238 + "startLine": 244 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 261 + "startLine": 272 }, { "name": "safe_path", "signature": "def safe_path(p: str, cwd: Path = None)", - "startLine": 275 + "startLine": 287 }, { "name": "run_bash", "signature": "def run_bash(command: str, cwd: Path = None)", - "startLine": 283 + "startLine": 295 }, { "name": "run_read", "signature": "def run_read(path: str, limit: int | None = None, cwd: Path = None)", - "startLine": 293 + "startLine": 305 }, { "name": "run_write", "signature": "def run_write(path: str, content: str, cwd: Path = None)", - "startLine": 303 + "startLine": 315 + }, + { + "name": "is_valid_agent_name", + "signature": "def is_valid_agent_name(name: str)", + "startLine": 333 }, { "name": "new_request_id", "signature": "def new_request_id()", - "startLine": 360 - }, - { - "name": "match_response", - "signature": "def match_response(response_type: str, request_id: str, approve: bool)", - "startLine": 364 + "startLine": 415 }, { "name": "consume_lead_inbox", "signature": "def consume_lead_inbox(route_protocol=True)", - "startLine": 375 + "startLine": 450 + }, + { + "name": "format_team_events", + "signature": "def format_team_events(msgs: list[dict])", + "startLine": 463 }, { "name": "scan_unclaimed_tasks", "signature": "def scan_unclaimed_tasks()", - "startLine": 393 + "startLine": 479 + }, + { + "name": "claim_next_task", + "signature": "def claim_next_task(name: str)", + "startLine": 488 + }, + { + "name": "_last_assistant_text", + "signature": "def _last_assistant_text(content)", + "startLine": 496 + }, + { + "name": "_run_teammate_tool", + "signature": "def _run_teammate_tool(name: str, block, handlers: dict)", + "startLine": 505 + }, + { + "name": "apply_plan_response", + "signature": "def apply_plan_response(name: str, msg: dict)", + "startLine": 514 + }, + { + "name": "apply_shutdown_request", + "signature": "def apply_shutdown_request(name: str, msg: dict)", + "startLine": 542 + }, + { + "name": "_teammate_send_message", + "signature": "def _teammate_send_message(from_name: str, to: str, content: str)", + "startLine": 563 }, { "name": "spawn_teammate_thread", "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", - "startLine": 437 + "startLine": 573 }, { "name": "_teammate_submit_plan", "signature": "def _teammate_submit_plan(from_name: str, plan: str)", - "startLine": 615 + "startLine": 809 }, { "name": "run_request_shutdown", "signature": "def run_request_shutdown(teammate: str)", - "startLine": 629 + "startLine": 829 }, { "name": "run_request_plan", "signature": "def run_request_plan(teammate: str, task: str)", - "startLine": 640 + "startLine": 846 }, { "name": "normalize_mcp_name", "signature": "def normalize_mcp_name(name: str)", - "startLine": 688 + "startLine": 907 }, { "name": "_mock_server_docs", "signature": "def _mock_server_docs()", - "startLine": 693 + "startLine": 912 }, { "name": "_mock_server_deploy", "signature": "def _mock_server_deploy()", - "startLine": 712 + "startLine": 931 }, { "name": "connect_mcp", "signature": "def connect_mcp(name: str)", - "startLine": 739 + "startLine": 958 }, { "name": "assemble_tool_pool", "signature": "def assemble_tool_pool()", - "startLine": 754 + "startLine": 973 }, { "name": "run_create_worktree", "signature": "def run_create_worktree(name: str, task_id: str = \"\")", - "startLine": 775 + "startLine": 994 }, { "name": "run_remove_worktree", "signature": "def run_remove_worktree(name: str, discard_changes: bool = False)", - "startLine": 778 + "startLine": 997 }, { "name": "run_keep_worktree", "signature": "def run_keep_worktree(name: str)", - "startLine": 781 + "startLine": 1000 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 795 + "startLine": 1014 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 805 + "startLine": 1024 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 808 + "startLine": 1027 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 811 + "startLine": 1030 }, { "name": "run_spawn_teammate", "signature": "def run_spawn_teammate(name: str, role: str, prompt: str)", - "startLine": 814 + "startLine": 1033 }, { "name": "run_send_message", "signature": "def run_send_message(to: str, content: str)", - "startLine": 817 - }, - { - "name": "run_check_inbox", - "signature": "def run_check_inbox()", - "startLine": 821 + "startLine": 1036 }, { "name": "run_connect_mcp", "signature": "def run_connect_mcp(name: str)", - "startLine": 833 + "startLine": 1042 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 953 + "startLine": 1162 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 962 + "startLine": 1171 } ], "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns19: MCP Tools — MCPClient + tool discovery + assemble_tool_pool.\n\nRun: python s19_mcp_plugin/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s18:\n - MCPClient class: discovers tools, calls tools via mock handler\n - normalize_mcp_name: normalize tool/server names\n - assemble_tool_pool: assembles builtin + MCP tools into one pool\n - connect_mcp: connect to an MCP server, discover tools\n - Tool naming: mcp__{server}__{tool} with normalization\n - MCP tools have readOnly/destructive annotations\n - agent_loop uses dynamic tool pool (builtin + MCP), no prompt cache\n - Teammate tools: complete_task, worktree cwd (from s17/s18 fixes)\n\nASCII flow:\n connect_mcp(\"docs\") → MCPClient discovers tools →\n assemble_tool_pool → [builtin... , mcp__docs__search, mcp__docs__get_version]\n agent_loop uses assembled pool\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n worktree: str | None = None\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task_json(task_id: str) -> str:\n return json.dumps(asdict(load_task(task_id)), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if _task_path(d).exists() and load_task(d).status != \"completed\"]\n missing = [d for d in task.blockedBy if not _task_path(d).exists()]\n parts = []\n if deps: parts.append(f\"blocked by: {deps}\")\n if missing: parts.append(f\"missing deps: {missing}\")\n return \"Cannot start — \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Worktree System ──\n\nWORKTREES_DIR = WORKDIR / \".worktrees\"\nWORKTREES_DIR.mkdir(exist_ok=True)\n\nVALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')\n\n\ndef validate_worktree_name(name: str) -> str | None:\n if not name:\n return \"Worktree name cannot be empty\"\n if name in (\".\", \"..\"):\n return f\"'{name}' is not a valid worktree name\"\n if not VALID_WT_NAME.match(name):\n return (f\"Invalid worktree name '{name}': \"\n \"only letters, digits, dots, underscores, dashes (1-64 chars)\")\n return None\n\n\ndef run_git(args: list[str]) -> tuple[bool, str]:\n try:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR,\n capture_output=True, text=True, timeout=30)\n out = (r.stdout + r.stderr).strip()\n return r.returncode == 0, out[:5000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return False, \"Error: git timeout\"\n\n\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n events_file = WORKTREES_DIR / \"events.jsonl\"\n with open(events_file, \"a\") as f:\n f.write(json.dumps(event) + \"\\n\")\n\n\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n err = validate_worktree_name(name)\n if err:\n return f\"Error: {err}\"\n path = WORKTREES_DIR / name\n if path.exists():\n return f\"Worktree '{name}' already exists at {path}\"\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n print(f\" \\033[33m[worktree] created: {name} at {path}\\033[0m\")\n return f\"Worktree '{name}' created at {path}\"\n\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name\n save_task(task)\n\n\ndef _count_worktree_changes(path: Path) -> tuple[int, int]:\n try:\n r1 = subprocess.run([\"git\", \"status\", \"--porcelain\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])\n r2 = subprocess.run([\"git\", \"log\", \"@{push}..HEAD\", \"--oneline\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])\n return files, commits\n except Exception:\n return -1, -1\n\n\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n path = WORKTREES_DIR / name\n if not path.exists():\n return f\"Worktree '{name}' not found\"\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files < 0:\n return \"Cannot verify status. Use discard_changes=true to force.\"\n if files > 0 or commits > 0:\n return (f\"Worktree '{name}' has {files} file(s), {commits} commit(s). \"\n \"Use discard_changes=true or keep_worktree.\")\n ok1, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok1:\n return f\"Failed to remove worktree '{name}'\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n print(f\" \\033[33m[worktree] removed: {name}\\033[0m\")\n return f\"Worktree '{name}' removed\"\n\n\ndef keep_worktree(name: str) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n\n\n# ── Prompt Assembly ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"spawn_teammate, send_message, check_inbox, \"\n \"request_shutdown, request_plan, review_plan, \"\n \"create_worktree, remove_worktree, keep_worktree, \"\n \"connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n mcp_names = list(mcp_clients.keys())\n if mcp_names:\n sections.append(f\"Connected MCP servers: {', '.join(mcp_names)}\")\n return \"\\n\\n\".join(sections)\n\n\n# ── Basic Tools ──\n\ndef safe_path(p: str, cwd: Path = None) -> Path:\n base = cwd or WORKDIR\n path = (base / p).resolve()\n if not path.is_relative_to(base):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, cwd: Path = None) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None, cwd: Path = None) -> str:\n try:\n lines = safe_path(path, cwd).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str, cwd: Path = None) -> str:\n try:\n fp = safe_path(path, cwd)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# ── MessageBus ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\n\n\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, bool] = {}\n\n# ── Protocol State ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n return f\"req_{random.randint(0, 999999):06d}\"\n\n\ndef match_response(response_type: str, request_id: str, approve: bool):\n state = pending_requests.get(request_id)\n if not state:\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n return\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n return\n state.status = \"approved\" if approve else \"rejected\"\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n\n\n# ── Autonomous Agent ──\n\nIDLE_POLL_INTERVAL = 5\nIDLE_TIMEOUT = 60\n\n\ndef scan_unclaimed_tasks() -> list[dict]:\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n\n\ndef idle_poll(agent_name: str, messages: list,\n name: str, role: str) -> str:\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n inbox = BUS.read_inbox(agent_name)\n if inbox:\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n BUS.send(name, \"lead\", \"Shutting down.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return \"shutdown\"\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(inbox) + \"\"})\n return \"work\"\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task_data = unclaimed[0]\n result = claim_task(task_data[\"id\"], agent_name)\n if \"Claimed\" in result:\n wt_info = \"\"\n if task_data.get(\"worktree\"):\n wt_info = f\"\\nWork directory: {WORKTREES_DIR / task_data['worktree']}\"\n messages.append({\"role\": \"user\",\n \"content\": f\"Task {task_data['id']}: \"\n f\"{task_data['subject']}{wt_info}\"})\n return \"work\"\n return \"timeout\"\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n\n system = (f\"You are '{name}', a {role}. \"\n f\"Use tools to complete tasks. \"\n f\"If a task has a worktree, work in that directory.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return True\n if msg_type == \"plan_approval_response\":\n approve = meta.get(\"approve\", False)\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved]\" if approve\n else f\"[Plan rejected] {msg['content']}\"})\n return False\n\n def run():\n wt_ctx = {\"path\": None}\n\n def _wt_cwd():\n p = wt_ctx[\"path\"]\n return Path(p) if p else None\n\n def _run_bash(command: str) -> str:\n return run_bash(command, cwd=_wt_cwd())\n\n def _run_read(path: str) -> str:\n return run_read(path, cwd=_wt_cwd())\n\n def _run_write(path: str, content: str) -> str:\n return run_write(path, content, cwd=_wt_cwd())\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n wt_ctx[\"path\"] = (str(WORKTREES_DIR / task.worktree)\n if task.worktree else None)\n return result\n\n def _run_complete_task(task_id: str):\n result = complete_task(task_id)\n wt_ctx[\"path\"] = None\n return result\n\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n sub_handlers = {\n \"bash\": _run_bash, \"read_file\": _run_read,\n \"write_file\": _run_write,\n \"send_message\": lambda to, content: (BUS.send(name, to, content),\n \"Sent\")[1],\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n while True:\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n if inbox and not should_shutdown:\n non_protocol = [m for m in inbox\n if m.get(\"type\") == \"message\"]\n if non_protocol:\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(non_protocol) + \"\"})\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n handler = sub_handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n if should_shutdown:\n break\n idle_result = idle_poll(name, messages, name, role)\n if idle_result in (\"shutdown\", \"timeout\"):\n break\n\n summary = \"Done.\"\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\" and isinstance(msg[\"content\"], list):\n for b in msg[\"content\"]:\n if getattr(b, \"type\", None) == \"text\":\n summary = b.text\n break\n else:\n continue\n break\n BUS.send(name, \"lead\", summary, \"result\")\n active_teammates.pop(name, None)\n\n active_teammates[name] = True\n threading.Thread(target=run, daemon=True).start()\n return f\"Teammate '{name}' spawned as {role}\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id})\"\n\n\n# ── Lead Protocol Tools ──\n\ndef run_request_shutdown(teammate: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Shut down.\", \"shutdown_request\",\n {\"request_id\": req_id})\n return f\"Shutdown request sent to {teammate}\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n BUS.send(\"lead\", teammate, f\"Submit plan for: {task}\", \"message\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n return f\"Plan {'approved' if approve else 'rejected'}\"\n\n\n# ── MCP System (s19 new) ──\n\nclass MCPClient:\n \"\"\"Discovers and calls tools on an MCP server (mock for teaching).\"\"\"\n\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs: list[dict],\n handlers: dict[str, callable]):\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n try:\n return handler(**args)\n except Exception as e:\n return f\"MCP error: {e}\"\n\n\nmcp_clients: dict[str, MCPClient] = {}\n\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\n\ndef normalize_mcp_name(name: str) -> str:\n \"\"\"Replace non [a-zA-Z0-9_-] with underscore.\"\"\"\n return _DISALLOWED_CHARS.sub('_', name)\n\n\ndef _mock_server_docs():\n client = MCPClient(\"docs\")\n client.register(\n tool_defs=[\n {\"name\": \"search\", \"description\": \"Search documentation. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"query\": {\"type\": \"string\"}},\n \"required\": [\"query\"]}},\n {\"name\": \"get_version\", \"description\": \"Get API version. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n ],\n handlers={\n \"search\": lambda query: f\"[docs] Found 3 results for '{query}'\",\n \"get_version\": lambda: \"[docs] API v2.1.0\",\n })\n return client\n\n\ndef _mock_server_deploy():\n client = MCPClient(\"deploy\")\n client.register(\n tool_defs=[\n {\"name\": \"trigger\",\n \"description\": \"Trigger a deployment. (destructive — requires approval in real CC)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n {\"name\": \"status\", \"description\": \"Check deployment status. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n ],\n handlers={\n \"trigger\": lambda service: f\"[deploy] Triggered: {service}\",\n \"status\": lambda service: f\"[deploy] {service}: running (v1.4.2)\",\n })\n return client\n\n\nMOCK_SERVERS = {\n \"docs\": _mock_server_docs,\n \"deploy\": _mock_server_deploy,\n}\n\n\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n available = \", \".join(MOCK_SERVERS.keys())\n return f\"Unknown server '{name}'. Available: {available}\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n tool_names = [t[\"name\"] for t in mcp_client.tools]\n print(f\" \\033[31m[mcp] connected: {name} → {tool_names}\\033[0m\")\n return (f\"Connected to MCP server '{name}'. \"\n f\"Discovered {len(mcp_client.tools)} tools: {', '.join(tool_names)}\")\n\n\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n \"\"\"Assemble builtin tools + all MCP tools into one pool.\"\"\"\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append({\n \"name\": prefixed,\n \"description\": tool_def.get(\"description\", \"\"),\n \"input_schema\": tool_def.get(\"inputSchema\", {}),\n })\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw: c.call_tool(t, kw))\n return tools, handlers\n\n\n# ── Lead Worktree Tools ──\n\ndef run_create_worktree(name: str, task_id: str = \"\") -> str:\n return create_worktree(name, task_id)\n\ndef run_remove_worktree(name: str, discard_changes: bool = False) -> str:\n return remove_worktree(name, discard_changes)\n\ndef run_keep_worktree(name: str) -> str:\n return keep_worktree(name)\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n return get_task_json(task_id)\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\ndef run_send_message(to: str, content: str) -> str:\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\ndef run_check_inbox() -> str:\n msgs = consume_lead_inbox(route_protocol=True)\n if not msgs:\n return \"(inbox empty)\"\n lines = []\n for m in msgs:\n meta = m.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n tag = f\" [{m['type']} req:{req_id}]\" if req_id else f\" [{m['type']}]\"\n lines.append(f\" [{m['from']}]{tag} {m['content'][:200]}\")\n return \"\\n\".join(lines)\n\ndef run_connect_mcp(name: str) -> str:\n return connect_mcp(name)\n\n\n# ── Tool Definitions ──\n\nBUILTIN_TOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\", \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\", \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\", \"description\": \"Get full task details.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\", \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\", \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"spawn_teammate\", \"description\": \"Spawn an autonomous teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\", \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"check_inbox\",\n \"description\": \"Check inbox for messages and protocol responses.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n {\"name\": \"create_worktree\",\n \"description\": \"Create an isolated git worktree.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"task_id\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"remove_worktree\",\n \"description\": \"Remove a worktree. Refuses if changes exist.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"discard_changes\": {\"type\": \"boolean\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"keep_worktree\",\n \"description\": \"Keep a worktree for manual review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"connect_mcp\",\n \"description\": \"Connect to an MCP server (docs, deploy) and discover tools.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n]\n\nBUILTIN_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message, \"check_inbox\": run_check_inbox,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n \"create_worktree\": run_create_worktree,\n \"remove_worktree\": run_remove_worktree,\n \"keep_worktree\": run_keep_worktree,\n \"connect_mcp\": run_connect_mcp,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\"memories\": memories}\n\n\n# ── Agent Loop (s19: dynamic tool pool, no prompt cache) ──\n\ndef agent_loop(messages: list, context: dict):\n tools, handlers = assemble_tool_pool()\n system = assemble_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=tools, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if any(b.name == \"connect_mcp\" for b in response.content\n if b.type == \"tool_use\"):\n tools, handlers = assemble_tool_pool()\n context = update_context(context, messages)\n system = assemble_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s19: mcp tools\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = {\"memories\": \"\"}\n while True:\n try:\n query = input(\"\\033[36ms19 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": query})\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n inbox = consume_lead_inbox(route_protocol=True)\n if inbox:\n inbox_text = \"\\n\".join(\n f\"From {m['from']} [{m.get('type', 'message')}]: \"\n f\"{m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns18: MCP Tools — MCPClient + tool discovery + assemble_tool_pool.\n\nRun: python s18_mcp_plugin/code.py\nNeed: pip install anthropic python-dotenv + .env with ANTHROPIC_API_KEY\n\nChanges from s17:\n - MCPClient class: discovers tools, calls tools via mock handler\n - normalize_mcp_name: normalize tool/server names\n - assemble_tool_pool: assembles builtin + MCP tools into one pool\n - connect_mcp: connect to an MCP server, discover tools\n - Tool naming: mcp__{server}__{tool} with normalization\n - MCP tools have readOnly/destructive annotations\n - agent_loop uses dynamic tool pool (builtin + MCP), no prompt cache\n - Teammate tools: complete_task, worktree cwd (from s16/s17 fixes)\n\nASCII flow:\n connect_mcp(\"docs\") → MCPClient discovers tools →\n assemble_tool_pool → [builtin... , mcp__docs__search, mcp__docs__get_version]\n agent_loop uses assembled pool\n\"\"\"\n\nimport os, subprocess, json, time, random, threading, queue, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\nexcept ImportError:\n pass\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\n\n# ── Task System ──\n\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\ntask_lock = threading.RLock()\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n worktree: str | None = None\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task_json(task_id: str) -> str:\n return json.dumps(asdict(load_task(task_id)), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if (_task_path(d).exists()\n and load_task(d).status != \"completed\")]\n missing = [d for d in task.blockedBy\n if not _task_path(d).exists()]\n parts = []\n if deps:\n parts.append(f\"blocked by: {deps}\")\n if missing:\n parts.append(f\"missing deps: {missing}\")\n return \"Cannot start: \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Worktree System ──\n\nWORKTREES_DIR = WORKDIR / \".worktrees\"\nWORKTREES_DIR.mkdir(exist_ok=True)\n\nVALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')\n\n\ndef validate_worktree_name(name: str) -> str | None:\n if not name:\n return \"Worktree name cannot be empty\"\n if name in (\".\", \"..\"):\n return f\"'{name}' is not a valid worktree name\"\n if not VALID_WT_NAME.match(name):\n return (f\"Invalid worktree name '{name}': \"\n \"only letters, digits, dots, underscores, dashes (1-64 chars)\")\n return None\n\n\ndef run_git(args: list[str]) -> tuple[bool, str]:\n try:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR,\n capture_output=True, text=True, timeout=30)\n out = (r.stdout + r.stderr).strip()\n return r.returncode == 0, out[:5000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return False, \"Error: git timeout\"\n\n\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n events_file = WORKTREES_DIR / \"events.jsonl\"\n with open(events_file, \"a\") as f:\n f.write(json.dumps(event) + \"\\n\")\n\n\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n err = validate_worktree_name(name)\n if err:\n return f\"Error: {err}\"\n path = WORKTREES_DIR / name\n if path.exists():\n return f\"Worktree '{name}' already exists at {path}\"\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n print(f\" \\033[33m[worktree] created: {name} at {path}\\033[0m\")\n return f\"Worktree '{name}' created at {path}\"\n\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name\n save_task(task)\n\n\ndef _count_worktree_changes(path: Path) -> tuple[int, int]:\n try:\n r1 = subprocess.run([\"git\", \"status\", \"--porcelain\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])\n r2 = subprocess.run([\"git\", \"log\", \"@{push}..HEAD\", \"--oneline\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])\n return files, commits\n except Exception:\n return -1, -1\n\n\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n path = WORKTREES_DIR / name\n if not path.exists():\n return f\"Worktree '{name}' not found\"\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files < 0:\n return \"Cannot verify status. Use discard_changes=true to force.\"\n if files > 0 or commits > 0:\n return (f\"Worktree '{name}' has {files} file(s), {commits} commit(s). \"\n \"Use discard_changes=true or keep_worktree.\")\n ok1, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok1:\n return f\"Failed to remove worktree '{name}'\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n print(f\" \\033[33m[worktree] removed: {name}\\033[0m\")\n return f\"Worktree '{name}' removed\"\n\n\ndef keep_worktree(name: str) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n\n\n# ── Prompt Assembly ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"spawn_teammate, send_message, \"\n \"request_shutdown, request_plan, review_plan, \"\n \"create_worktree, remove_worktree, keep_worktree, \"\n \"connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.\",\n \"teams\": (\n \"When parallel work would help, first propose a small team with clear \"\n \"responsibilities and wait for the user's confirmation. Do not call \"\n \"spawn_teammate before the user confirms.\"\n ),\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"teams\"],\n PROMPT_SECTIONS[\"workspace\"]]\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n mcp_names = list(mcp_clients.keys())\n if mcp_names:\n sections.append(f\"Connected MCP servers: {', '.join(mcp_names)}\")\n return \"\\n\\n\".join(sections)\n\n\n# ── Basic Tools ──\n\ndef safe_path(p: str, cwd: Path = None) -> Path:\n base = cwd or WORKDIR\n path = (base / p).resolve()\n if not path.is_relative_to(base):\n raise ValueError(f\"Path escapes workspace: {p}\")\n return path\n\n\ndef run_bash(command: str, cwd: Path = None) -> str:\n try:\n r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None, cwd: Path = None) -> str:\n try:\n lines = safe_path(path, cwd).read_text().splitlines()\n if limit and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str, cwd: Path = None) -> str:\n try:\n fp = safe_path(path, cwd)\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\n# ── MessageBus (from s15) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\nMAILBOX_ROOT = MAILBOX_DIR.resolve()\nVALID_AGENT_NAME = re.compile(r\"^[A-Za-z0-9_-]{1,64}$\")\n\n\ndef is_valid_agent_name(name: str) -> bool:\n return bool(VALID_AGENT_NAME.fullmatch(name))\n\n\nclass MessageBus:\n def __init__(self):\n self._lock = threading.RLock()\n self._changed = threading.Condition(self._lock)\n\n def _path(self, agent: str) -> Path:\n if not is_valid_agent_name(agent):\n raise ValueError(f\"Invalid mailbox recipient: {agent!r}\")\n path = (MAILBOX_DIR / f\"{agent}.jsonl\").resolve()\n if not path.is_relative_to(MAILBOX_ROOT):\n raise ValueError(f\"Mailbox path escapes directory: {agent!r}\")\n return path\n\n def _read_unlocked(self, agent: str) -> list[dict]:\n inbox = self._path(agent)\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict | None = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n with self._changed:\n with open(self._path(to_agent), \"a\") as f:\n f.write(json.dumps(msg, ensure_ascii=False) + \"\\n\")\n self._changed.notify_all()\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n with self._lock:\n return self._read_unlocked(agent)\n\n def peek(self, agent: str) -> bool:\n with self._lock:\n inbox = self._path(agent)\n return inbox.exists() and inbox.stat().st_size > 0\n\n def wait_for_messages(self, agent: str,\n timeout: float | None = None) -> list[dict]:\n deadline = None if timeout is None else time.monotonic() + timeout\n with self._changed:\n while not self.peek(agent):\n remaining = (None if deadline is None\n else deadline - time.monotonic())\n if remaining is not None and remaining <= 0:\n return []\n self._changed.wait(remaining)\n return self._read_unlocked(agent)\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, str] = {}\nplan_gates: dict[str, str] = {}\nplan_request_ids: dict[str, str] = {}\nteam_lock = threading.RLock()\n\n# ── Protocol State (from s15) ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n while True:\n request_id = f\"req_{random.randint(0, 999999):06d}\"\n if request_id not in pending_requests:\n return request_id\n\n\ndef match_response(response_type: str, request_id: str, approve: bool,\n from_agent: str, to_agent: str) -> bool:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return False\n expected = {\n \"shutdown\": \"shutdown_response\",\n \"plan_approval\": \"plan_approval_response\",\n }[state.type]\n if response_type != expected:\n print(f\" \\033[31m[protocol] expected {expected}, \"\n f\"got {response_type}\\033[0m\")\n return False\n if from_agent != state.target or to_agent != state.sender:\n print(f\" \\033[31m[protocol] {request_id} responder mismatch\\033[0m\")\n return False\n if state.status != \"pending\":\n return False\n state.status = \"approved\" if approve else \"rejected\"\n icon = \"✓\" if approve else \"✗\"\n color = \"32\" if approve else \"31\"\n print(f\" \\033[{color}m[protocol] {state.type} {icon} \"\n f\"({request_id}: {state.status})\\033[0m\")\n return True\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False),\n msg.get(\"from\", \"\"), msg.get(\"to\", \"\"))\n return msgs\n\n\ndef format_team_events(msgs: list[dict]) -> str:\n lines = []\n for msg in msgs:\n request_id = msg.get(\"metadata\", {}).get(\"request_id\")\n suffix = f\" request_id={request_id}\" if request_id else \"\"\n lines.append(\n f\"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}\"\n )\n return \"[Team events]\\n\" + \"\\n\".join(lines)\n\n\n# ── Autonomous Agent (from s16, + worktree cwd) ──\n\nIDLE_SCAN_INTERVAL = 2.0\n\n\ndef scan_unclaimed_tasks() -> list[Task]:\n return [\n task for task in list_tasks()\n if (task.status == \"pending\"\n and task.owner is None\n and can_start(task.id))\n ]\n\n\ndef claim_next_task(name: str) -> Task | None:\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n\n\ndef _last_assistant_text(content) -> str:\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n return block.text.strip()\n if isinstance(block, dict) and block.get(\"type\") == \"text\":\n return str(block.get(\"text\", \"\")).strip()\n return \"\"\n\n\ndef _run_teammate_tool(name: str, block, handlers: dict) -> str:\n gate = plan_gates.get(name, \"not_required\")\n if (block.name in {\"bash\", \"write_file\"}\n and gate not in {\"not_required\", \"approved\"}):\n return f\"Blocked: plan status is {gate}.\"\n handler = handlers.get(block.name)\n return str(handler(**block.input)) if handler else f\"Unknown tool: {block.name}\"\n\n\ndef apply_plan_response(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Apply only the Lead response for this teammate's current plan.\"\"\"\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n expected_id = plan_request_ids.get(name)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and request_id == expected_id\n and state is not None\n and state.type == \"plan_approval\"\n and state.sender == name\n and state.target == \"lead\"\n and state.status in {\"approved\", \"rejected\"}\n and metadata.get(\"approve\", False)\n == (state.status == \"approved\")\n )\n if not valid:\n return False, \"[Ignored plan response: request mismatch]\"\n plan_gates[name] = state.status\n active_teammates[name] = \"working\"\n plan_request_ids.pop(name, None)\n outcome = state.status\n return True, f\"[Plan {outcome}] {msg['content']}\"\n\n\ndef apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Accept only a pending shutdown request sent by Lead to this teammate.\"\"\"\n request_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and state is not None\n and state.type == \"shutdown\"\n and state.sender == \"lead\"\n and state.target == name\n and state.status == \"pending\"\n and active_teammates.get(name) != \"stopping\"\n )\n if not valid:\n return False, \"[Ignored shutdown request: request mismatch]\"\n active_teammates[name] = \"stopping\"\n return True, request_id\n\n\ndef _teammate_send_message(from_name: str, to: str, content: str) -> str:\n with team_lock:\n if to != \"lead\" and to not in active_teammates:\n return f\"Agent '{to}' is not active\"\n BUS.send(from_name, to, content)\n return f\"Sent to {to}\"\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if not is_valid_agent_name(name):\n return (\"Invalid teammate name: use 1-64 letters, digits, \"\n \"underscores, or dashes\")\n with team_lock:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n active_teammates[name] = \"working\"\n plan_gates[name] = \"not_required\"\n\n system = (f\"You are '{name}', a {role}. \"\n \"Use tools to complete tasks. \"\n \"You can list and claim tasks from the board. \"\n \"If a task has a worktree, work in that directory. \"\n \"When asked for a plan, submit it before bash or write_file \"\n \"and wait for approval.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n accepted, notice = apply_shutdown_request(name, msg)\n if not accepted:\n messages.append({\"role\": \"user\", \"content\": notice})\n return False\n req_id = notice\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"({req_id})\\033[0m\")\n return True\n\n if msg_type == \"plan_approval_response\":\n _, notice = apply_plan_response(name, msg)\n messages.append({\"role\": \"user\",\n \"content\": notice})\n elif msg_type == \"plan_request\":\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan required] {msg['content']}\"})\n elif msg_type == \"message\":\n messages.append({\"role\": \"user\",\n \"content\": f\"[Message from {msg['from']}] {msg['content']}\"})\n return False\n\n def run():\n # Track current worktree for this teammate's cwd\n wt_ctx = {\"path\": None}\n\n def _wt_cwd() -> Path | None:\n p = wt_ctx[\"path\"]\n return Path(p) if p else None\n\n def _run_bash(command: str) -> str:\n return run_bash(command, cwd=_wt_cwd())\n\n def _run_read(path: str) -> str:\n return run_read(path, cwd=_wt_cwd())\n\n def _run_write(path: str, content: str) -> str:\n return run_write(path, content, cwd=_wt_cwd())\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n # Set worktree cwd if task has one\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n else:\n wt_ctx[\"path\"] = None\n return result\n\n def _run_complete_task(task_id: str):\n result = complete_task(task_id)\n wt_ctx[\"path\"] = None\n return result\n\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks on the board.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n sub_handlers = {\n \"bash\": _run_bash, \"read_file\": _run_read,\n \"write_file\": _run_write,\n \"send_message\": lambda to, content: _teammate_send_message(\n name, to, content),\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n # Outer loop: WORK → IDLE cycle\n while True:\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n\n # WORK phase\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n summary = _last_assistant_text(response.content)\n gate = plan_gates.get(name, \"not_required\")\n if gate != \"pending\" and summary:\n BUS.send(name, \"lead\", summary, \"result\")\n if gate == \"pending\":\n with team_lock:\n active_teammates[name] = \"waiting_approval\"\n else:\n with team_lock:\n active_teammates[name] = \"idle\"\n BUS.send(name, \"lead\", \"Waiting for more work.\",\n \"idle_notification\")\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = _run_teammate_tool(name, block, sub_handlers)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if should_shutdown:\n break\n\n # IDLE phase: messages take priority, then scan the task board.\n while True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n for msg in inbox:\n if handle_inbox_message(name, msg, messages):\n should_shutdown = True\n break\n if should_shutdown or messages[-1][\"role\"] == \"user\":\n break\n continue\n\n task = claim_next_task(name)\n if not task:\n continue\n wt_ctx[\"path\"] = (str(WORKTREES_DIR / task.worktree)\n if task.worktree else None)\n workdir = (f\"\\nWork directory: {wt_ctx['path']}\"\n if wt_ctx[\"path\"] else \"\")\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}{workdir}\"\n ),\n })\n print(f\" \\033[32m[idle] {name} claimed \"\n f\"{task.id}: {task.subject}\\033[0m\")\n break\n if should_shutdown:\n break\n\n with team_lock:\n active_teammates.pop(name, None)\n plan_gates.pop(name, None)\n plan_request_ids.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role} (autonomous)\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n with team_lock:\n if plan_gates.get(from_name) == \"pending\":\n return \"A plan is already waiting for review.\"\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n plan_gates[from_name] = \"pending\"\n plan_request_ids[from_name] = req_id\n active_teammates[from_name] = \"waiting_approval\"\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id}). Waiting for approval...\"\n\n\n# ── Lead Protocol Tools (from s15) ──\n\ndef run_request_shutdown(teammate: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Please shut down gracefully.\",\n \"shutdown_request\",\n {\"request_id\": req_id})\n print(f\" \\033[35m[protocol] shutdown_request → {teammate} \"\n f\"({req_id})\\033[0m\")\n return f\"Shutdown request sent to {teammate} (req: {req_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n plan_gates[teammate] = \"required\"\n BUS.send(\"lead\", teammate, task, \"plan_request\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.type != \"plan_approval\":\n return f\"Request {request_id} is not a plan\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n if plan_request_ids.get(state.sender) != request_id:\n return f\"Request {request_id} is not the current plan\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n icon = \"✓\" if approve else \"✗\"\n print(f\" \\033[32m[protocol] plan {icon} ({request_id})\\033[0m\")\n return f\"Plan {'approved' if approve else 'rejected'} ({request_id})\"\n\n\n# ── MCP System (s18 new) ──\n\nclass MCPClient:\n \"\"\"Discovers and calls tools on an in-process MCP server.\"\"\"\n\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs: list[dict],\n handlers: dict[str, callable]):\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n try:\n return handler(**args)\n except Exception as e:\n return f\"MCP error: {e}\"\n\n\nmcp_clients: dict[str, MCPClient] = {}\n\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\n\ndef normalize_mcp_name(name: str) -> str:\n \"\"\"Replace non [a-zA-Z0-9_-] with underscore.\"\"\"\n return _DISALLOWED_CHARS.sub('_', name)\n\n\ndef _mock_server_docs():\n client = MCPClient(\"docs\")\n client.register(\n tool_defs=[\n {\"name\": \"search\", \"description\": \"Search documentation. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"query\": {\"type\": \"string\"}},\n \"required\": [\"query\"]}},\n {\"name\": \"get_version\", \"description\": \"Get API version. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n ],\n handlers={\n \"search\": lambda query: f\"[docs] Found 3 results for '{query}'\",\n \"get_version\": lambda: \"[docs] API v2.1.0\",\n })\n return client\n\n\ndef _mock_server_deploy():\n client = MCPClient(\"deploy\")\n client.register(\n tool_defs=[\n {\"name\": \"trigger\",\n \"description\": \"Trigger a deployment. (destructive)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n {\"name\": \"status\", \"description\": \"Check deployment status. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n ],\n handlers={\n \"trigger\": lambda service: f\"[deploy] Triggered: {service}\",\n \"status\": lambda service: f\"[deploy] {service}: running (v1.4.2)\",\n })\n return client\n\n\nMOCK_SERVERS = {\n \"docs\": _mock_server_docs,\n \"deploy\": _mock_server_deploy,\n}\n\n\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n available = \", \".join(MOCK_SERVERS.keys())\n return f\"Unknown server '{name}'. Available: {available}\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n tool_names = [t[\"name\"] for t in mcp_client.tools]\n print(f\" \\033[31m[mcp] connected: {name} → {tool_names}\\033[0m\")\n return (f\"Connected to MCP server '{name}'. \"\n f\"Discovered {len(mcp_client.tools)} tools: {', '.join(tool_names)}\")\n\n\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n \"\"\"Assemble builtin tools + all MCP tools into one pool.\"\"\"\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append({\n \"name\": prefixed,\n \"description\": tool_def.get(\"description\", \"\"),\n \"input_schema\": tool_def.get(\"inputSchema\", {}),\n })\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw: c.call_tool(t, kw))\n return tools, handlers\n\n\n# ── Lead Worktree Tools ──\n\ndef run_create_worktree(name: str, task_id: str = \"\") -> str:\n return create_worktree(name, task_id)\n\ndef run_remove_worktree(name: str, discard_changes: bool = False) -> str:\n return remove_worktree(name, discard_changes)\n\ndef run_keep_worktree(name: str) -> str:\n return keep_worktree(name)\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n return get_task_json(task_id)\n\ndef run_claim_task(task_id: str) -> str:\n return claim_task(task_id, owner=\"agent\")\n\ndef run_complete_task(task_id: str) -> str:\n return complete_task(task_id)\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\ndef run_send_message(to: str, content: str) -> str:\n if to not in active_teammates:\n return f\"Teammate '{to}' is not active\"\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\ndef run_connect_mcp(name: str) -> str:\n return connect_mcp(name)\n\n\n# ── Tool Definitions ──\n\nBUILTIN_TOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"create_task\", \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\", \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\", \"description\": \"Get full task details.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\", \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\", \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"spawn_teammate\", \"description\": \"Spawn an autonomous teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9_-]{1,64}$\",\n },\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\", \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n {\"name\": \"create_worktree\",\n \"description\": \"Create an isolated git worktree.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"task_id\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"remove_worktree\",\n \"description\": \"Remove a worktree. Refuses if changes exist.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"discard_changes\": {\"type\": \"boolean\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"keep_worktree\",\n \"description\": \"Keep a worktree for manual review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"connect_mcp\",\n \"description\": \"Connect to an MCP server (docs, deploy) and discover tools.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n]\n\nBUILTIN_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n \"create_worktree\": run_create_worktree,\n \"remove_worktree\": run_remove_worktree,\n \"keep_worktree\": run_keep_worktree,\n \"connect_mcp\": run_connect_mcp,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\"memories\": memories}\n\n\n# ── Agent Loop (s18: dynamic tool pool, no prompt cache) ──\n\ndef agent_loop(messages: list, context: dict):\n tools, handlers = assemble_tool_pool()\n system = assemble_system_prompt(context)\n while True:\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages,\n tools=tools, max_tokens=8000)\n except Exception as e:\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n return\n\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n handler = handlers.get(block.name)\n output = handler(**block.input) if handler else \"Unknown\"\n print(str(output)[:300])\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if any(b.name == \"connect_mcp\" for b in response.content\n if b.type == \"tool_use\"):\n tools, handlers = assemble_tool_pool()\n context = update_context(context, messages)\n system = assemble_system_prompt(context)\n\n\nif __name__ == \"__main__\":\n print(\"s18: mcp tools\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = {\"memories\": \"\"}\n\n events = queue.Queue()\n\n def input_reader():\n while True:\n try:\n line = input(\"\\033[36ms18 >> \\033[0m\")\n except (EOFError, KeyboardInterrupt):\n events.put((\"quit\", None))\n return\n events.put((\"user\", line))\n\n def inbox_poller():\n while True:\n time.sleep(1)\n if BUS.peek(\"lead\"):\n events.put((\"wake\", None))\n\n threading.Thread(target=input_reader, daemon=True).start()\n threading.Thread(target=inbox_poller, daemon=True).start()\n\n had_teammates = False\n while True:\n kind, payload = events.get()\n if kind == \"quit\":\n break\n if kind == \"user\":\n if payload.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n history.append({\"role\": \"user\", \"content\": payload})\n else:\n inbox = consume_lead_inbox(route_protocol=True)\n if not inbox:\n continue\n history.append({\"role\": \"user\",\n \"content\": format_team_events(inbox)})\n print(f\"\\n\\033[33m[wake: {len(inbox)} team events \"\n f\"-> new turn]\\033[0m\")\n\n agent_loop(history, context)\n context = update_context(context, history)\n for block in history[-1][\"content\"]:\n if getattr(block, \"type\", None) == \"text\":\n print(block.text)\n elif isinstance(block, dict) and block.get(\"type\") == \"text\":\n print(block.get(\"text\", \"\"))\n\n if active_teammates:\n had_teammates = True\n elif had_teammates and not BUS.peek(\"lead\"):\n print(\"\\033[32m[all teammates shut down]\\033[0m\")\n had_teammates = False\n print()\n", "images": [ { - "src": "/course-assets/s19_mcp_plugin/mcp-architecture.svg", + "src": "/course-assets/s18_mcp_plugin/mcp-architecture.svg", "alt": "mcp architecture" } ] }, { - "id": "s20", - "filename": "s20_comprehensive/code.py", + "id": "s19", + "filename": "s19_comprehensive/code.py", "title": "Comprehensive Agent", "subtitle": "All Mechanisms, One Loop", - "loc": 1708, + "loc": 1858, "tools": [ "bash", "read_file", @@ -3102,7 +3104,6 @@ "list_crons", "cancel_cron", "spawn_teammate", - "check_inbox", "request_shutdown", "request_plan", "review_plan", @@ -3123,37 +3124,37 @@ "cancel_cron" ], "coreAddition": "Integrated harness", - "keyInsight": "The final harness is still one loop, now surrounded by the systems that make it production-shaped.", + "keyInsight": "The complete harness is still one loop, surrounded by the systems introduced across the course.", "classes": [ { "name": "Task", - "startLine": 81, - "endLine": 90 + "startLine": 82, + "endLine": 91 }, { "name": "MessageBus", - "startLine": 492, - "endLine": 513 + "startLine": 508, + "endLine": 563 }, { "name": "ProtocolState", - "startLine": 520, - "endLine": 529 + "startLine": 573, + "endLine": 582 }, { "name": "RecoveryState", - "startLine": 1204, - "endLine": 1212 + "startLine": 1384, + "endLine": 1392 }, { "name": "CronJob", - "startLine": 1334, - "endLine": 1341 + "startLine": 1514, + "endLine": 1521 }, { "name": "MCPClient", - "startLine": 1531, - "endLine": 1553 + "startLine": 1711, + "endLine": 1733 } ], "functions": [ @@ -3165,509 +3166,539 @@ { "name": "_task_path", "signature": "def _task_path(task_id: str)", - "startLine": 91 + "startLine": 92 }, { "name": "save_task", "signature": "def save_task(task: Task)", - "startLine": 107 + "startLine": 108 }, { "name": "load_task", "signature": "def load_task(task_id: str)", - "startLine": 111 + "startLine": 112 }, { "name": "list_tasks", "signature": "def list_tasks()", - "startLine": 115 + "startLine": 116 }, { "name": "get_task_json", "signature": "def get_task_json(task_id: str)", - "startLine": 120 + "startLine": 121 }, { "name": "can_start", "signature": "def can_start(task_id: str)", - "startLine": 124 + "startLine": 125 }, { "name": "claim_task", "signature": "def claim_task(task_id: str, owner: str = \"agent\")", - "startLine": 136 + "startLine": 137 }, { "name": "complete_task", "signature": "def complete_task(task_id: str)", - "startLine": 157 + "startLine": 163 }, { "name": "validate_worktree_name", "signature": "def validate_worktree_name(name: str)", - "startLine": 182 + "startLine": 188 }, { "name": "run_git", "signature": "def run_git(args: list[str])", - "startLine": 193 + "startLine": 199 }, { "name": "log_event", "signature": "def log_event(event_type: str, worktree_name: str, task_id: str = \"\")", - "startLine": 203 + "startLine": 209 }, { "name": "create_worktree", "signature": "def create_worktree(name: str, task_id: str = \"\")", - "startLine": 211 + "startLine": 217 }, { "name": "bind_task_to_worktree", "signature": "def bind_task_to_worktree(task_id: str, worktree_name: str)", - "startLine": 235 + "startLine": 241 }, { "name": "_count_worktree_changes", "signature": "def _count_worktree_changes(path: Path)", - "startLine": 241 + "startLine": 247 }, { "name": "remove_worktree", "signature": "def remove_worktree(name: str, discard_changes: bool = False)", - "startLine": 254 + "startLine": 260 }, { "name": "keep_worktree", "signature": "def keep_worktree(name: str)", - "startLine": 277 + "startLine": 283 }, { "name": "_parse_frontmatter", "signature": "def _parse_frontmatter(text: str)", - "startLine": 290 + "startLine": 296 }, { "name": "scan_skills", "signature": "def scan_skills()", - "startLine": 303 + "startLine": 309 }, { "name": "list_skills", "signature": "def list_skills()", - "startLine": 327 + "startLine": 333 }, { "name": "load_skill", "signature": "def load_skill(name: str)", - "startLine": 335 + "startLine": 341 }, { "name": "assemble_system_prompt", "signature": "def assemble_system_prompt(context: dict)", - "startLine": 360 + "startLine": 371 }, { "name": "run_write", "signature": "def run_write(path: str, content: str, cwd: Path = None)", - "startLine": 407 + "startLine": 419 }, { "name": "run_glob", "signature": "def run_glob(pattern: str, cwd: Path = None)", - "startLine": 432 + "startLine": 444 }, { "name": "call_tool_handler", "signature": "def call_tool_handler(handler, args: dict, name: str)", - "startLine": 445 + "startLine": 457 }, { "name": "_normalize_todos", "signature": "def _normalize_todos(todos)", - "startLine": 454 + "startLine": 466 }, { "name": "run_todo_write", "signature": "def run_todo_write(todos: list)", - "startLine": 474 + "startLine": 486 + }, + { + "name": "is_valid_agent_name", + "signature": "def is_valid_agent_name(name: str)", + "startLine": 504 }, { "name": "new_request_id", "signature": "def new_request_id()", - "startLine": 533 - }, - { - "name": "match_response", - "signature": "def match_response(response_type: str, request_id: str, approve: bool)", - "startLine": 537 + "startLine": 586 }, { "name": "consume_lead_inbox", "signature": "def consume_lead_inbox(route_protocol=True)", - "startLine": 550 + "startLine": 621 + }, + { + "name": "format_team_events", + "signature": "def format_team_events(msgs: list[dict])", + "startLine": 634 }, { "name": "scan_unclaimed_tasks", "signature": "def scan_unclaimed_tasks()", - "startLine": 568 + "startLine": 650 + }, + { + "name": "claim_next_task", + "signature": "def claim_next_task(name: str)", + "startLine": 659 + }, + { + "name": "_last_assistant_text", + "signature": "def _last_assistant_text(content)", + "startLine": 667 + }, + { + "name": "_run_teammate_tool", + "signature": "def _run_teammate_tool(name: str, block, handlers: dict)", + "startLine": 676 + }, + { + "name": "apply_plan_response", + "signature": "def apply_plan_response(name: str, msg: dict)", + "startLine": 685 + }, + { + "name": "apply_shutdown_request", + "signature": "def apply_shutdown_request(name: str, msg: dict)", + "startLine": 713 + }, + { + "name": "_teammate_send_message", + "signature": "def _teammate_send_message(from_name: str, to: str, content: str)", + "startLine": 734 }, { "name": "spawn_teammate_thread", "signature": "def spawn_teammate_thread(name: str, role: str, prompt: str)", - "startLine": 618 + "startLine": 744 }, { "name": "_teammate_submit_plan", "signature": "def _teammate_submit_plan(from_name: str, plan: str)", - "startLine": 825 + "startLine": 980 }, { "name": "run_request_shutdown", "signature": "def run_request_shutdown(teammate: str)", - "startLine": 839 + "startLine": 1000 }, { "name": "run_request_plan", "signature": "def run_request_plan(teammate: str, task: str)", - "startLine": 850 + "startLine": 1017 }, { "name": "register_hook", "signature": "def register_hook(event: str, callback)", - "startLine": 876 + "startLine": 1056 }, { "name": "trigger_hooks", "signature": "def trigger_hooks(event: str, *args)", - "startLine": 880 + "startLine": 1060 }, { "name": "permission_hook", "signature": "def permission_hook(block)", - "startLine": 892 + "startLine": 1072 }, { "name": "log_hook", "signature": "def log_hook(block)", - "startLine": 922 + "startLine": 1102 }, { "name": "large_output_hook", "signature": "def large_output_hook(block, output)", - "startLine": 927 + "startLine": 1107 }, { "name": "user_prompt_hook", "signature": "def user_prompt_hook(query: str)", - "startLine": 934 + "startLine": 1114 }, { "name": "stop_hook", "signature": "def stop_hook(messages: list)", - "startLine": 939 + "startLine": 1119 }, { "name": "extract_text", "signature": "def extract_text(content)", - "startLine": 1003 + "startLine": 1183 }, { "name": "has_tool_use", "signature": "def has_tool_use(content)", - "startLine": 1012 + "startLine": 1192 }, { "name": "spawn_subagent", "signature": "def spawn_subagent(description: str)", - "startLine": 1019 + "startLine": 1199 }, { "name": "estimate_size", "signature": "def estimate_size(messages: list)", - "startLine": 1056 + "startLine": 1236 }, { "name": "block_type", "signature": "def block_type(block)", - "startLine": 1059 + "startLine": 1239 }, { "name": "message_has_tool_use", "signature": "def message_has_tool_use(message: dict)", - "startLine": 1063 + "startLine": 1243 }, { "name": "is_tool_result_message", "signature": "def is_tool_result_message(message: dict)", - "startLine": 1072 + "startLine": 1252 }, { "name": "collect_tool_results", "signature": "def collect_tool_results(messages: list)", - "startLine": 1082 + "startLine": 1262 }, { "name": "persist_large_output", "signature": "def persist_large_output(tool_use_id: str, output: str)", - "startLine": 1094 + "startLine": 1274 }, { "name": "tool_result_budget", "signature": "def tool_result_budget(messages: list, max_bytes: int = 200_000)", - "startLine": 1105 + "startLine": 1285 }, { "name": "snip_compact", "signature": "def snip_compact(messages: list, max_messages: int = 50)", - "startLine": 1129 + "startLine": 1309 }, { "name": "micro_compact", "signature": "def micro_compact(messages: list)", - "startLine": 1148 + "startLine": 1328 }, { "name": "write_transcript", "signature": "def write_transcript(messages: list)", - "startLine": 1158 + "startLine": 1338 }, { "name": "summarize_history", "signature": "def summarize_history(messages: list)", - "startLine": 1167 + "startLine": 1347 }, { "name": "compact_history", "signature": "def compact_history(messages: list)", - "startLine": 1179 + "startLine": 1359 }, { "name": "reactive_compact", "signature": "def reactive_compact(messages: list)", - "startLine": 1186 + "startLine": 1366 }, { "name": "retry_delay", "signature": "def retry_delay(attempt: int)", - "startLine": 1213 + "startLine": 1393 }, { "name": "with_retry", "signature": "def with_retry(fn, state: RecoveryState)", - "startLine": 1218 + "startLine": 1398 }, { "name": "is_prompt_too_long_error", "signature": "def is_prompt_too_long_error(e: Exception)", - "startLine": 1248 + "startLine": 1428 }, { "name": "is_slow_operation", "signature": "def is_slow_operation(tool_name: str, tool_input: dict)", - "startLine": 1265 + "startLine": 1445 }, { "name": "should_run_background", "signature": "def should_run_background(tool_name: str, tool_input: dict)", - "startLine": 1275 + "startLine": 1455 }, { "name": "start_background_task", "signature": "def start_background_task(block, handlers: dict)", - "startLine": 1281 + "startLine": 1461 }, { "name": "collect_background_results", "signature": "def collect_background_results()", - "startLine": 1306 + "startLine": 1486 }, { "name": "_cron_field_matches", "signature": "def _cron_field_matches(field: str, value: int)", - "startLine": 1348 + "startLine": 1528 }, { "name": "cron_matches", "signature": "def cron_matches(cron_expr: str, dt: datetime)", - "startLine": 1363 + "startLine": 1543 }, { "name": "_validate_cron_field", "signature": "def _validate_cron_field(field: str, lo: int, hi: int)", - "startLine": 1385 + "startLine": 1565 }, { "name": "validate_cron", "signature": "def validate_cron(cron_expr: str)", - "startLine": 1417 + "startLine": 1597 }, { "name": "save_durable_jobs", "signature": "def save_durable_jobs()", - "startLine": 1430 + "startLine": 1610 }, { "name": "load_durable_jobs", "signature": "def load_durable_jobs()", - "startLine": 1435 + "startLine": 1615 }, { "name": "cancel_job", "signature": "def cancel_job(job_id: str)", - "startLine": 1463 + "startLine": 1643 }, { "name": "cron_scheduler_loop", "signature": "def cron_scheduler_loop()", - "startLine": 1473 + "startLine": 1653 }, { "name": "consume_cron_queue", "signature": "def consume_cron_queue()", - "startLine": 1492 + "startLine": 1672 }, { "name": "run_list_crons", "signature": "def run_list_crons()", - "startLine": 1507 + "startLine": 1687 }, { "name": "run_cancel_cron", "signature": "def run_cancel_cron(job_id: str)", - "startLine": 1519 + "startLine": 1699 }, { "name": "normalize_mcp_name", "signature": "def normalize_mcp_name(name: str)", - "startLine": 1559 + "startLine": 1739 }, { "name": "_mock_server_docs", "signature": "def _mock_server_docs()", - "startLine": 1564 + "startLine": 1744 }, { "name": "_mock_server_deploy", "signature": "def _mock_server_deploy()", - "startLine": 1583 + "startLine": 1763 }, { "name": "connect_mcp", "signature": "def connect_mcp(name: str)", - "startLine": 1610 + "startLine": 1790 }, { "name": "assemble_tool_pool", "signature": "def assemble_tool_pool()", - "startLine": 1625 + "startLine": 1805 }, { "name": "run_create_worktree", "signature": "def run_create_worktree(name: str, task_id: str = \"\")", - "startLine": 1646 + "startLine": 1826 }, { "name": "run_remove_worktree", "signature": "def run_remove_worktree(name: str, discard_changes: bool = False)", - "startLine": 1649 + "startLine": 1829 }, { "name": "run_keep_worktree", "signature": "def run_keep_worktree(name: str)", - "startLine": 1652 + "startLine": 1832 }, { "name": "run_list_tasks", "signature": "def run_list_tasks()", - "startLine": 1666 + "startLine": 1846 }, { "name": "run_get_task", "signature": "def run_get_task(task_id: str)", - "startLine": 1676 + "startLine": 1856 }, { "name": "run_claim_task", "signature": "def run_claim_task(task_id: str)", - "startLine": 1682 + "startLine": 1862 }, { "name": "run_complete_task", "signature": "def run_complete_task(task_id: str)", - "startLine": 1688 + "startLine": 1868 }, { "name": "run_spawn_teammate", "signature": "def run_spawn_teammate(name: str, role: str, prompt: str)", - "startLine": 1694 + "startLine": 1874 }, { "name": "run_send_message", "signature": "def run_send_message(to: str, content: str)", - "startLine": 1697 - }, - { - "name": "run_check_inbox", - "signature": "def run_check_inbox()", - "startLine": 1701 + "startLine": 1877 }, { "name": "run_connect_mcp", "signature": "def run_connect_mcp(name: str)", - "startLine": 1713 + "startLine": 1883 }, { "name": "update_context", "signature": "def update_context(context: dict, messages: list)", - "startLine": 1895 + "startLine": 2065 }, { "name": "prepare_context", "signature": "def prepare_context(messages: list)", - "startLine": 1912 + "startLine": 2082 }, { "name": "build_user_content", "signature": "def build_user_content(results: list[dict])", - "startLine": 1922 + "startLine": 2092 }, { "name": "inject_background_notifications", "signature": "def inject_background_notifications(messages: list)", - "startLine": 1931 + "startLine": 2101 }, { "name": "agent_loop", "signature": "def agent_loop(messages: list, context: dict)", - "startLine": 1951 + "startLine": 2121 }, { "name": "print_turn_assistants", "signature": "def print_turn_assistants(messages: list, turn_start: int)", - "startLine": 2057 + "startLine": 2227 }, { - "name": "cron_autorun_loop", - "signature": "def cron_autorun_loop(history: list, context: dict)", - "startLine": 2066 + "name": "async_event_loop", + "signature": "def async_event_loop(history: list, context: dict)", + "startLine": 2236 } ], "layer": "collaboration", - "source": "#!/usr/bin/env python3\n\"\"\"\ns20: Comprehensive Agent — all teaching components in one loop.\n\nRun: python s20_comprehensive/code.py\nNeed: pip install anthropic python-dotenv pyyaml + .env with ANTHROPIC_API_KEY\n\nThis final chapter intentionally puts the earlier teaching mechanisms back\ntogether: dispatch, permission, hooks, todo, subagent, skills, compaction,\nmemory, prompt assembly, error recovery, task graph, background tasks, cron,\nteams, protocols, autonomous agents, worktrees, and MCP.\n\"\"\"\n\nimport ast, json, os, subprocess, time, random, threading, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\nimport yaml\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\n READLINE_AVAILABLE = True\nexcept ImportError:\n READLINE_AVAILABLE = False\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\nPRIMARY_MODEL = MODEL\nFALLBACK_MODEL = os.getenv(\"FALLBACK_MODEL_ID\")\n\nSKILLS_DIR = WORKDIR / \"skills\"\nTRANSCRIPT_DIR = WORKDIR / \".transcripts\"\nTOOL_RESULTS_DIR = WORKDIR / \".task_outputs\" / \"tool-results\"\n\nDEFAULT_MAX_TOKENS = 8000\nESCALATED_MAX_TOKENS = 16000\nMAX_RETRIES = 3\nMAX_CONSECUTIVE_529 = 2\nMAX_RECOVERY_RETRIES = 2\nBASE_DELAY_MS = 500\nCONTEXT_LIMIT = 50000\nKEEP_RECENT_TOOL_RESULTS = 3\nPERSIST_THRESHOLD = 30000\nCONTINUATION_PROMPT = \"Continue from the previous response. Do not repeat completed work.\"\nPROMPT = \"\\033[36ms20 >> \\033[0m\"\nCLI_ACTIVE = False\n\n\ndef terminal_print(text: str):\n if threading.current_thread() is threading.main_thread() or not CLI_ACTIVE:\n print(text)\n return\n line = \"\"\n if READLINE_AVAILABLE:\n try:\n line = readline.get_line_buffer()\n except Exception:\n line = \"\"\n print(f\"\\r\\033[K{text}\")\n print(PROMPT + line, end=\"\", flush=True)\n\n# ── Task System ──\n\n# Tasks are tiny durable records. Later systems add ownership, dependencies,\n# worktrees, and teammates on top of this same file-backed state.\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\nCURRENT_TODOS: list[dict] = []\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n worktree: str | None = None\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task_json(task_id: str) -> str:\n return json.dumps(asdict(load_task(task_id)), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n # Dependencies are intentionally simple: every blocker must exist and be\n # completed before the task can be claimed.\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if _task_path(d).exists() and load_task(d).status != \"completed\"]\n missing = [d for d in task.blockedBy if not _task_path(d).exists()]\n parts = []\n if deps: parts.append(f\"blocked by: {deps}\")\n if missing: parts.append(f\"missing deps: {missing}\")\n return \"Cannot start — \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Worktree System ──\n\n# Worktree names become filesystem paths, so the teaching version keeps the\n# validation rules strict and reuses them for create/remove/keep.\nWORKTREES_DIR = WORKDIR / \".worktrees\"\nWORKTREES_DIR.mkdir(exist_ok=True)\n\nVALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')\n\n\ndef validate_worktree_name(name: str) -> str | None:\n if not name:\n return \"Worktree name cannot be empty\"\n if name in (\".\", \"..\"):\n return f\"'{name}' is not a valid worktree name\"\n if not VALID_WT_NAME.match(name):\n return (f\"Invalid worktree name '{name}': \"\n \"only letters, digits, dots, underscores, dashes (1-64 chars)\")\n return None\n\n\ndef run_git(args: list[str]) -> tuple[bool, str]:\n try:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR,\n capture_output=True, text=True, timeout=30)\n out = (r.stdout + r.stderr).strip()\n return r.returncode == 0, out[:5000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return False, \"Error: git timeout\"\n\n\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n events_file = WORKTREES_DIR / \"events.jsonl\"\n with open(events_file, \"a\") as f:\n f.write(json.dumps(event) + \"\\n\")\n\n\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n # Tool-layer validation is part of the safety boundary; do it before git\n # sees the name, not only after git happens to reject something.\n err = validate_worktree_name(name)\n if err:\n return f\"Error: {err}\"\n if task_id:\n try:\n load_task(task_id)\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n path = WORKTREES_DIR / name\n if path.exists():\n return f\"Worktree '{name}' already exists at {path}\"\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n print(f\" \\033[33m[worktree] created: {name} at {path}\\033[0m\")\n return f\"Worktree '{name}' created at {path}\"\n\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name\n save_task(task)\n\n\ndef _count_worktree_changes(path: Path) -> tuple[int, int]:\n try:\n r1 = subprocess.run([\"git\", \"status\", \"--porcelain\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])\n r2 = subprocess.run([\"git\", \"log\", \"@{push}..HEAD\", \"--oneline\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])\n return files, commits\n except Exception:\n return -1, -1\n\n\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n path = WORKTREES_DIR / name\n if not path.exists():\n return f\"Worktree '{name}' not found\"\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files < 0:\n return \"Cannot verify status. Use discard_changes=true to force.\"\n if files > 0 or commits > 0:\n return (f\"Worktree '{name}' has {files} file(s), {commits} commit(s). \"\n \"Use discard_changes=true or keep_worktree.\")\n ok1, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok1:\n return f\"Failed to remove worktree '{name}'\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n print(f\" \\033[33m[worktree] removed: {name}\\033[0m\")\n return f\"Worktree '{name}' removed\"\n\n\ndef keep_worktree(name: str) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n\n\n# ── Skill Loading ──\n\nSKILL_REGISTRY: dict[str, dict] = {}\n\n\ndef _parse_frontmatter(text: str) -> tuple[dict, str]:\n if not text.startswith(\"---\"):\n return {}, text\n parts = text.split(\"---\", 2)\n if len(parts) < 3:\n return {}, text\n try:\n meta = yaml.safe_load(parts[1]) or {}\n except yaml.YAMLError:\n meta = {}\n return meta, parts[2].strip()\n\n\ndef scan_skills():\n SKILL_REGISTRY.clear()\n if not SKILLS_DIR.exists():\n return\n for directory in sorted(SKILLS_DIR.iterdir()):\n if not directory.is_dir():\n continue\n manifest = directory / \"SKILL.md\"\n if not manifest.exists():\n continue\n raw = manifest.read_text()\n meta, _ = _parse_frontmatter(raw)\n name = meta.get(\"name\", directory.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\n \"name\": name,\n \"description\": desc,\n \"content\": raw,\n }\n\n\nscan_skills()\n\n\ndef list_skills() -> str:\n if not SKILL_REGISTRY:\n return \"(no skills found)\"\n return \"\\n\".join(\n f\"- {skill['name']}: {skill['description']}\"\n for skill in SKILL_REGISTRY.values())\n\n\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n available = \", \".join(SKILL_REGISTRY.keys()) or \"(none)\"\n return f\"Skill not found: {name}. Available: {available}\"\n return skill[\"content\"]\n\n\n# ── Prompt Assembly ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, edit_file, glob, \"\n \"todo_write, task, load_skill, compact, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron, \"\n \"spawn_teammate, send_message, check_inbox, \"\n \"request_shutdown, request_plan, review_plan, \"\n \"create_worktree, remove_worktree, keep_worktree, \"\n \"connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.\",\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n # The system prompt is rebuilt each turn from live context. This is where\n # memory, skill catalog, MCP state, and active teammates become visible.\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"workspace\"]]\n sections.append(f\"Current time: {datetime.now().isoformat(timespec='seconds')}\")\n sections.append(\"Skills catalog:\\n\" + list_skills() +\n \"\\nUse load_skill(name) when a skill is relevant.\")\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n mcp_names = list(mcp_clients.keys())\n if mcp_names:\n sections.append(f\"Connected MCP servers: {', '.join(mcp_names)}\")\n return \"\\n\\n\".join(sections)\n\n\n# ── Basic Tools ──\n\ndef run_bash(command: str, cwd: Path = None,\n run_in_background: bool = False) -> str:\n # run_in_background is consumed by the dispatcher; direct execution ignores it.\n try:\n r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None,\n offset: int = 0, cwd: Path = None) -> str:\n try:\n base = cwd or WORKDIR\n file_path = (base / path).resolve()\n lines = file_path.read_text().splitlines()\n offset = max(int(offset or 0), 0)\n limit = int(limit) if limit is not None else None\n lines = lines[offset:]\n if limit is not None and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str, cwd: Path = None) -> str:\n try:\n base = cwd or WORKDIR\n fp = (base / path).resolve()\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_edit(path: str, old_text: str, new_text: str,\n cwd: Path = None) -> str:\n try:\n base = cwd or WORKDIR\n fp = (base / path).resolve()\n text = fp.read_text()\n if old_text not in text:\n return f\"Error: text not found in {path}\"\n fp.write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_glob(pattern: str, cwd: Path = None) -> str:\n import glob as g\n try:\n base = cwd or WORKDIR\n results = []\n for match in g.glob(pattern, root_dir=base):\n if (base / match).resolve().is_relative_to(base):\n results.append(match)\n return \"\\n\".join(results) if results else \"(no matches)\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef call_tool_handler(handler, args: dict, name: str) -> str:\n if not handler:\n return f\"Unknown: {name}\"\n try:\n return handler(**(args or {}))\n except TypeError as e:\n return f\"Error: {e}\"\n\n\ndef _normalize_todos(todos):\n if isinstance(todos, str):\n try:\n todos = json.loads(todos)\n except json.JSONDecodeError:\n try:\n todos = ast.literal_eval(todos)\n except (SyntaxError, ValueError):\n return None, \"Error: todos must be a list or JSON array string\"\n if not isinstance(todos, list):\n return None, \"Error: todos must be a list\"\n for i, todo in enumerate(todos):\n if not isinstance(todo, dict):\n return None, f\"Error: todos[{i}] must be an object\"\n if \"content\" not in todo or \"status\" not in todo:\n return None, f\"Error: todos[{i}] missing 'content' or 'status'\"\n if todo[\"status\"] not in (\"pending\", \"in_progress\", \"completed\"):\n return None, f\"Error: todos[{i}] has invalid status '{todo['status']}'\"\n return todos, None\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n todos, error = _normalize_todos(todos)\n if error:\n return error\n CURRENT_TODOS = todos\n print(f\" \\033[33m[todo] updated {len(CURRENT_TODOS)} item(s)\\033[0m\")\n return f\"Updated {len(CURRENT_TODOS)} todos\"\n\n\n# ── MessageBus ──\n\n# Team communication is append-only JSONL mailboxes. This keeps the protocol\n# inspectable on disk and lets background teammates send messages.\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\n\n\nclass MessageBus:\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n inbox = MAILBOX_DIR / f\"{to_agent}.jsonl\"\n with open(inbox, \"a\") as f:\n f.write(json.dumps(msg) + \"\\n\")\n terminal_print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n inbox = MAILBOX_DIR / f\"{agent}.jsonl\"\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, bool] = {}\n\n# ── Protocol State ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n return f\"req_{random.randint(0, 999999):06d}\"\n\n\ndef match_response(response_type: str, request_id: str, approve: bool):\n # Responses are matched by request_id so one protocol reply cannot approve\n # a different pending request.\n state = pending_requests.get(request_id)\n if not state:\n return\n if state.type == \"shutdown\" and response_type != \"shutdown_response\":\n return\n if state.type == \"plan_approval\" and response_type != \"plan_approval_response\":\n return\n state.status = \"approved\" if approve else \"rejected\"\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False))\n return msgs\n\n\n# ── Autonomous Agent ──\n\nIDLE_POLL_INTERVAL = 5\nIDLE_TIMEOUT = 60\n\n\ndef scan_unclaimed_tasks() -> list[dict]:\n unclaimed = []\n for f in sorted(TASKS_DIR.glob(\"task_*.json\")):\n task = json.loads(f.read_text())\n if (task.get(\"status\") == \"pending\"\n and not task.get(\"owner\")\n and can_start(task[\"id\"])):\n unclaimed.append(task)\n return unclaimed\n\n\ndef idle_poll(agent_name: str, messages: list,\n name: str, role: str,\n worktree_context: dict | None = None) -> str:\n # Autonomous teammates wake up for inbox messages first, then look for\n # unclaimed tasks. This keeps direct protocol messages higher priority.\n for _ in range(IDLE_TIMEOUT // IDLE_POLL_INTERVAL):\n time.sleep(IDLE_POLL_INTERVAL)\n inbox = BUS.read_inbox(agent_name)\n if inbox:\n for msg in inbox:\n if msg.get(\"type\") == \"shutdown_request\":\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n BUS.send(name, \"lead\", \"Shutting down.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return \"shutdown\"\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(inbox) + \"\"})\n return \"work\"\n unclaimed = scan_unclaimed_tasks()\n if unclaimed:\n task_data = unclaimed[0]\n result = claim_task(task_data[\"id\"], agent_name)\n if \"Claimed\" in result:\n wt_info = \"\"\n if task_data.get(\"worktree\"):\n wt_path = WORKTREES_DIR / task_data[\"worktree\"]\n wt_info = f\"\\nWork directory: {wt_path}\"\n if worktree_context is not None:\n worktree_context[\"path\"] = str(wt_path)\n messages.append({\"role\": \"user\",\n \"content\": f\"Task {task_data['id']}: \"\n f\"{task_data['subject']}{wt_info}\"})\n return \"work\"\n return \"timeout\"\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n\n # Plan approval is a real gate: after submit_plan, the teammate stops\n # taking model/tool steps until lead sends plan_approval_response.\n protocol_ctx = {\"waiting_plan\": None}\n system = (f\"You are '{name}', a {role}. \"\n f\"Use tools to complete tasks. \"\n f\"If a task has a worktree, work in that directory.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n if msg_type == \"shutdown_request\":\n BUS.send(name, \"lead\", \"Shutting down.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n return True\n if msg_type == \"plan_approval_response\":\n approve = meta.get(\"approve\", False)\n if req_id == protocol_ctx[\"waiting_plan\"]:\n protocol_ctx[\"waiting_plan\"] = None\n messages.append({\"role\": \"user\",\n \"content\": \"[Plan approved]\" if approve\n else f\"[Plan rejected] {msg['content']}\"})\n return False\n\n def run():\n wt_ctx = {\"path\": None}\n\n def _wt_cwd():\n # Once a task with a worktree is claimed, all teammate file tools\n # transparently run inside that isolated directory.\n p = wt_ctx[\"path\"]\n return Path(p) if p else None\n\n def _run_bash(command: str) -> str:\n return run_bash(command, cwd=_wt_cwd())\n\n def _run_read(path: str) -> str:\n return run_read(path, cwd=_wt_cwd())\n\n def _run_write(path: str, content: str) -> str:\n return run_write(path, content, cwd=_wt_cwd())\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n task = load_task(task_id)\n wt_ctx[\"path\"] = (str(WORKTREES_DIR / task.worktree)\n if task.worktree else None)\n return result\n\n def _run_complete_task(task_id: str):\n result = complete_task(task_id)\n wt_ctx[\"path\"] = None\n return result\n\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"},\n \"offset\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n sub_handlers = {\n \"bash\": _run_bash, \"read_file\": _run_read,\n \"write_file\": _run_write,\n \"send_message\": lambda to, content: (BUS.send(name, to, content),\n \"Sent\")[1],\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n while True:\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n if protocol_ctx[\"waiting_plan\"]:\n # Poll only for protocol replies while the approval gate is\n # closed; do not let the model continue with the task.\n time.sleep(IDLE_POLL_INTERVAL)\n continue\n if inbox and not should_shutdown:\n non_protocol = [m for m in inbox\n if m.get(\"type\") == \"message\"]\n if non_protocol:\n messages.append({\"role\": \"user\",\n \"content\": \"\" + json.dumps(non_protocol) + \"\"})\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if not has_tool_use(response.content):\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n if block.name == \"submit_plan\":\n output = _teammate_submit_plan(\n name, block.input.get(\"plan\", \"\"))\n match = re.search(r\"\\((req_\\d+)\\)\", output)\n protocol_ctx[\"waiting_plan\"] = (\n match.group(1) if match else output)\n else:\n handler = sub_handlers.get(block.name)\n output = call_tool_handler(handler, block.input,\n block.name)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n if protocol_ctx[\"waiting_plan\"]:\n # Ignore later tool_use blocks from the same model\n # response; they belong after approval, not before.\n break\n messages.append({\"role\": \"user\", \"content\": results})\n if protocol_ctx[\"waiting_plan\"]:\n break\n if should_shutdown:\n break\n if protocol_ctx[\"waiting_plan\"]:\n continue\n idle_result = idle_poll(name, messages, name, role, wt_ctx)\n if idle_result in (\"shutdown\", \"timeout\"):\n break\n\n summary = \"Done.\"\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\" and isinstance(msg[\"content\"], list):\n for b in msg[\"content\"]:\n if getattr(b, \"type\", None) == \"text\":\n summary = b.text\n break\n else:\n continue\n break\n BUS.send(name, \"lead\", summary, \"result\")\n active_teammates.pop(name, None)\n\n active_teammates[name] = True\n threading.Thread(target=run, daemon=True).start()\n return f\"Teammate '{name}' spawned as {role}\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id})\"\n\n\n# ── Lead Protocol Tools ──\n\ndef run_request_shutdown(teammate: str) -> str:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Shut down.\", \"shutdown_request\",\n {\"request_id\": req_id})\n return f\"Shutdown request sent to {teammate}\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n BUS.send(\"lead\", teammate, f\"Submit plan for: {task}\", \"message\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n return f\"Plan {'approved' if approve else 'rejected'}\"\n\n\n# ── Hooks + Permission Pipeline ──\n\n# Hooks are intentionally outside tool handlers. The loop can add permission,\n# logging, and stop behavior without changing each individual tool.\nHOOKS = {\"UserPromptSubmit\": [], \"PreToolUse\": [],\n \"PostToolUse\": [], \"Stop\": []}\n\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None:\n return result\n return None\n\n\nDENY_LIST = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"mkfs\", \"dd if=\"]\nDESTRUCTIVE = [\"rm \", \"> /etc/\", \"chmod 777\"]\n\n\ndef permission_hook(block):\n # The permission layer sees the raw tool_use before dispatch. It can deny,\n # ask the user, or allow execution to continue.\n if block.name == \"bash\":\n command = block.input.get(\"command\", \"\")\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Permission denied: '{pattern}' is on the deny list\"\n if any(token in command for token in DESTRUCTIVE):\n print(f\"\\n\\033[33m[permission] destructive command\\033[0m\")\n print(f\" {command}\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n print(f\"\\n\\033[33m[permission] Access outside workspace\\033[0m\")\n print(f\" {block.name}: {path}\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n if block.name.startswith(\"mcp__\") and \"deploy\" in block.name:\n print(f\"\\n\\033[33m[permission] MCP destructive-looking tool: {block.name}\\033[0m\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n\ndef log_hook(block):\n print(f\"\\033[90m[HOOK] {block.name}\\033[0m\")\n return None\n\n\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"\\033[33m[HOOK] large output from {block.name}: \"\n f\"{len(str(output))} chars\\033[0m\")\n return None\n\n\ndef user_prompt_hook(query: str):\n print(f\"\\033[90m[HOOK] UserPromptSubmit: {WORKDIR}\\033[0m\")\n return None\n\n\ndef stop_hook(messages: list):\n tool_count = 0\n for msg in messages:\n content = msg.get(\"content\")\n if isinstance(content, list):\n tool_count += sum(1 for item in content\n if isinstance(item, dict)\n and item.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: {tool_count} tool result(s)\\033[0m\")\n return None\n\n\nregister_hook(\"UserPromptSubmit\", user_prompt_hook)\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\nregister_hook(\"Stop\", stop_hook)\n\n\n# ── Subagent Tool ──\n\nSUB_SYSTEM = (\n f\"You are a coding subagent at {WORKDIR}. \"\n \"Complete the task, then return a concise final summary. \"\n \"Do not spawn more agents.\"\n)\n\n\nSUB_TOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"},\n \"offset\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"old_text\": {\"type\": \"string\"},\n \"new_text\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"pattern\": {\"type\": \"string\"}},\n \"required\": [\"pattern\"]}},\n]\n\n\nSUB_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read,\n \"write_file\": run_write, \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n\ndef extract_text(content) -> str:\n if not isinstance(content, list):\n return str(content)\n return \"\\n\".join(\n getattr(block, \"text\", \"\")\n for block in content\n if getattr(block, \"type\", None) == \"text\").strip()\n\n\ndef has_tool_use(content) -> bool:\n # Do not rely on stop_reason alone; the concrete tool_use block is the\n # continuation signal used by the loop.\n return any(getattr(block, \"type\", None) == \"tool_use\"\n for block in content)\n\n\ndef spawn_subagent(description: str) -> str:\n messages = [{\"role\": \"user\", \"content\": description}]\n for _ in range(30):\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM, messages=messages,\n tools=SUB_TOOLS, max_tokens=8000)\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if not has_tool_use(response.content):\n break\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n output = str(blocked)\n else:\n handler = SUB_HANDLERS.get(block.name)\n output = call_tool_handler(handler, block.input, block.name)\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\":\n text = extract_text(msg[\"content\"])\n if text:\n return text\n return \"Subagent finished without a text summary.\"\n\n\n# ── Context Compaction ──\n\n# Compaction is layered: first shrink oversized tool results, then trim old\n# message ranges, and only call the model for a summary when the context is\n# still too large or the model explicitly asks for compact.\ndef estimate_size(messages: list) -> int:\n return len(json.dumps(messages, default=str))\n\ndef block_type(block):\n return block.get(\"type\") if isinstance(block, dict) else getattr(block, \"type\", None)\n\n\ndef message_has_tool_use(message: dict) -> bool:\n if message.get(\"role\") != \"assistant\":\n return False\n content = message.get(\"content\")\n if not isinstance(content, list):\n return False\n return any(block_type(block) == \"tool_use\" for block in content)\n\n\ndef is_tool_result_message(message: dict) -> bool:\n if message.get(\"role\") != \"user\":\n return False\n content = message.get(\"content\")\n if not isinstance(content, list):\n return False\n return any(isinstance(block, dict) and block.get(\"type\") == \"tool_result\"\n for block in content)\n\n\ndef collect_tool_results(messages: list):\n found = []\n for mi, msg in enumerate(messages):\n content = msg.get(\"content\")\n if msg.get(\"role\") != \"user\" or not isinstance(content, list):\n continue\n for bi, block in enumerate(content):\n if isinstance(block, dict) and block.get(\"type\") == \"tool_result\":\n found.append((mi, bi, block))\n return found\n\n\ndef persist_large_output(tool_use_id: str, output: str) -> str:\n if len(output) <= PERSIST_THRESHOLD:\n return output\n TOOL_RESULTS_DIR.mkdir(parents=True, exist_ok=True)\n path = TOOL_RESULTS_DIR / f\"{tool_use_id}.txt\"\n if not path.exists():\n path.write_text(output)\n return (f\"\\nFull output: {path}\\n\"\n f\"Preview:\\n{output[:2000]}\\n\")\n\n\ndef tool_result_budget(messages: list, max_bytes: int = 200_000) -> list:\n if not messages:\n return messages\n last = messages[-1]\n content = last.get(\"content\")\n if last.get(\"role\") != \"user\" or not isinstance(content, list):\n return messages\n blocks = [(i, b) for i, b in enumerate(content)\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n for _, block in sorted(blocks,\n key=lambda pair: len(str(pair[1].get(\"content\", \"\"))),\n reverse=True):\n if total <= max_bytes:\n break\n text = str(block.get(\"content\", \"\"))\n block[\"content\"] = persist_large_output(\n block.get(\"tool_use_id\", \"unknown\"), text)\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n return messages\n\n\ndef snip_compact(messages: list, max_messages: int = 50) -> list:\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and is_tool_result_message(messages[tail_start])\n and message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n if head_end >= tail_start:\n return messages\n snipped = tail_start - head_end\n return (messages[:head_end]\n + [{\"role\": \"user\", \"content\": f\"[snipped {snipped} messages]\"}]\n + messages[tail_start:])\n\n\ndef micro_compact(messages: list) -> list:\n tool_results = collect_tool_results(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(str(block.get(\"content\", \"\"))) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n\n\ndef write_transcript(messages: list) -> Path:\n TRANSCRIPT_DIR.mkdir(parents=True, exist_ok=True)\n path = TRANSCRIPT_DIR / f\"transcript_{int(time.time())}.jsonl\"\n with path.open(\"w\") as f:\n for msg in messages:\n f.write(json.dumps(msg, default=str) + \"\\n\")\n return path\n\n\ndef summarize_history(messages: list) -> str:\n conversation = json.dumps(messages, default=str)[:80000]\n prompt = (\"Summarize this coding-agent conversation so work can continue. \"\n \"Preserve current goal, key findings, changed files, remaining work, \"\n \"and user constraints.\\n\\n\" + conversation)\n response = client.messages.create(\n model=MODEL,\n messages=[{\"role\": \"user\", \"content\": prompt}],\n max_tokens=2000)\n return extract_text(response.content) or \"(empty summary)\"\n\n\ndef compact_history(messages: list) -> list:\n transcript = write_transcript(messages)\n print(f\" \\033[36m[compact] transcript saved: {transcript}\\033[0m\")\n summary = summarize_history(messages)\n return [{\"role\": \"user\", \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n\n\ndef reactive_compact(messages: list) -> list:\n transcript = write_transcript(messages)\n print(f\" \\033[31m[reactive compact] transcript saved: {transcript}\\033[0m\")\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and is_tool_result_message(messages[tail_start])\n and message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n try:\n summary = summarize_history(messages[:tail_start])\n except Exception:\n summary = \"Earlier conversation was trimmed after a prompt-too-long error.\"\n return [{\"role\": \"user\", \"content\": f\"[Reactive compact]\\n\\n{summary}\"},\n *messages[tail_start:]]\n\n\n# ── Error Recovery ──\n\nclass RecoveryState:\n def __init__(self):\n self.has_escalated = False\n self.recovery_count = 0\n self.consecutive_529 = 0\n self.has_attempted_reactive_compact = False\n self.current_model = PRIMARY_MODEL\n\n\ndef retry_delay(attempt: int) -> float:\n base = min(BASE_DELAY_MS * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\n\ndef with_retry(fn, state: RecoveryState):\n for attempt in range(MAX_RETRIES):\n try:\n result = fn()\n state.consecutive_529 = 0\n return result\n except Exception as e:\n name = type(e).__name__.lower()\n msg = str(e).lower()\n if \"ratelimit\" in name or \"429\" in msg:\n delay = retry_delay(attempt)\n print(f\" \\033[33m[429] retry {attempt + 1}/{MAX_RETRIES} \"\n f\"after {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n if \"overloaded\" in name or \"529\" in msg or \"overloaded\" in msg:\n state.consecutive_529 += 1\n if state.consecutive_529 >= MAX_CONSECUTIVE_529 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n state.consecutive_529 = 0\n print(f\" \\033[31m[529] switching to {FALLBACK_MODEL}\\033[0m\")\n delay = retry_delay(attempt)\n print(f\" \\033[33m[529] retry {attempt + 1}/{MAX_RETRIES} \"\n f\"after {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n raise\n raise RuntimeError(f\"Max retries ({MAX_RETRIES}) exceeded\")\n\n\ndef is_prompt_too_long_error(e: Exception) -> bool:\n msg = str(e).lower()\n return ((\"prompt\" in msg and \"long\" in msg)\n or \"context_length_exceeded\" in msg\n or \"max_context_window\" in msg)\n\n\n# ── Background Tasks ──\n\n# Slow tools return a placeholder tool_result immediately. Their real output is\n# later injected as a task_notification, so the main loop can keep moving.\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n if tool_name != \"bash\":\n return False\n command = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(keyword in command for keyword in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n if tool_name != \"bash\":\n return False\n return bool(tool_input.get(\"run_in_background\")) or is_slow_operation(tool_name, tool_input)\n\n\ndef start_background_task(block, handlers: dict) -> str:\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n command = block.input.get(\"command\", block.name)\n\n def worker():\n handler = handlers.get(block.name)\n result = call_tool_handler(handler, block.input, block.name)\n trigger_hooks(\"PostToolUse\", block, result)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = str(result)\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": command,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] {bg_id}: {str(command)[:60]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n with background_lock:\n ready = [bg_id for bg_id, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n return notifications\n\n\n# ── Cron Scheduler ──\n\n# Cron jobs are stored separately from conversation history. When a job fires,\n# it becomes a scheduled prompt that is injected back into the same agent loop.\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str\n prompt: str\n recurring: bool\n durable: bool\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\n_last_fired: dict[str, str] = {}\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(part.strip(), value)\n for part in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n if not (m and h and month_ok):\n return False\n if dom == \"*\" and dow == \"*\":\n return True\n if dom == \"*\":\n return dow_ok\n if dow == \"*\":\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step = field[2:]\n if not step.isdigit() or int(step) <= 0:\n return f\"Invalid step: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err:\n return err\n return None\n if \"-\" in field:\n left, right = field.split(\"-\", 1)\n if not left.isdigit() or not right.isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(left), int(right)\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n value = int(field)\n if value < lo or value > hi:\n return f\"Value {value} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for field, (lo, hi), name in zip(fields, bounds, names):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n durable = [asdict(job) for job in scheduled_jobs.values() if job.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n if not DURABLE_PATH.exists():\n return\n try:\n for item in json.loads(DURABLE_PATH.read_text()):\n job = CronJob(**item)\n if not validate_cron(job.cron):\n scheduled_jobs[job.id] = job\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> CronJob | str:\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable)\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now) and _last_fired.get(job.id) != marker:\n cron_queue.append(job)\n _last_fired[job.id] = marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' -> {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs.\"\n return \"\\n\".join(\n f\" {job.id}: '{job.cron}' -> {job.prompt[:40]} \"\n f\"[{'recurring' if job.recurring else 'one-shot'}, \"\n f\"{'durable' if job.durable else 'session'}]\"\n for job in jobs)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\n\n\n# ── MCP System ──\n\n# MCP is modeled as late-bound tools: connect first, then discovered server\n# tools are merged into the normal tool pool with mcp__server__tool names.\nclass MCPClient:\n \"\"\"Discovers and calls tools on an MCP server (mock for teaching).\"\"\"\n\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs: list[dict],\n handlers: dict[str, callable]):\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n try:\n return handler(**args)\n except Exception as e:\n return f\"MCP error: {e}\"\n\n\nmcp_clients: dict[str, MCPClient] = {}\n\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\n\ndef normalize_mcp_name(name: str) -> str:\n \"\"\"Replace non [a-zA-Z0-9_-] with underscore.\"\"\"\n return _DISALLOWED_CHARS.sub('_', name)\n\n\ndef _mock_server_docs():\n client = MCPClient(\"docs\")\n client.register(\n tool_defs=[\n {\"name\": \"search\", \"description\": \"Search documentation. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"query\": {\"type\": \"string\"}},\n \"required\": [\"query\"]}},\n {\"name\": \"get_version\", \"description\": \"Get API version. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n ],\n handlers={\n \"search\": lambda query: f\"[docs] Found 3 results for '{query}'\",\n \"get_version\": lambda: \"[docs] API v2.1.0\",\n })\n return client\n\n\ndef _mock_server_deploy():\n client = MCPClient(\"deploy\")\n client.register(\n tool_defs=[\n {\"name\": \"trigger\",\n \"description\": \"Trigger a deployment. (destructive — requires approval in real CC)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n {\"name\": \"status\", \"description\": \"Check deployment status. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n ],\n handlers={\n \"trigger\": lambda service: f\"[deploy] Triggered: {service}\",\n \"status\": lambda service: f\"[deploy] {service}: running (v1.4.2)\",\n })\n return client\n\n\nMOCK_SERVERS = {\n \"docs\": _mock_server_docs,\n \"deploy\": _mock_server_deploy,\n}\n\n\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n available = \", \".join(MOCK_SERVERS.keys())\n return f\"Unknown server '{name}'. Available: {available}\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n tool_names = [t[\"name\"] for t in mcp_client.tools]\n print(f\" \\033[31m[mcp] connected: {name} → {tool_names}\\033[0m\")\n return (f\"Connected to MCP server '{name}'. \"\n f\"Discovered {len(mcp_client.tools)} tools: {', '.join(tool_names)}\")\n\n\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n \"\"\"Merge builtin tools + all MCP tools into one pool.\"\"\"\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append({\n \"name\": prefixed,\n \"description\": tool_def.get(\"description\", \"\"),\n \"input_schema\": tool_def.get(\"inputSchema\", {}),\n })\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw: c.call_tool(t, kw))\n return tools, handlers\n\n\n# ── Lead Worktree Tools ──\n\ndef run_create_worktree(name: str, task_id: str = \"\") -> str:\n return create_worktree(name, task_id)\n\ndef run_remove_worktree(name: str, discard_changes: bool = False) -> str:\n return remove_worktree(name, discard_changes)\n\ndef run_keep_worktree(name: str) -> str:\n return keep_worktree(name)\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task_json(task_id)\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n\ndef run_claim_task(task_id: str) -> str:\n try:\n return claim_task(task_id, owner=\"agent\")\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n\ndef run_complete_task(task_id: str) -> str:\n try:\n return complete_task(task_id)\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\ndef run_send_message(to: str, content: str) -> str:\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\ndef run_check_inbox() -> str:\n msgs = consume_lead_inbox(route_protocol=True)\n if not msgs:\n return \"(inbox empty)\"\n lines = []\n for m in msgs:\n meta = m.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n tag = f\" [{m['type']} req:{req_id}]\" if req_id else f\" [{m['type']}]\"\n lines.append(f\" [{m['from']}]{tag} {m['content'][:200]}\")\n return \"\\n\".join(lines)\n\ndef run_connect_mcp(name: str) -> str:\n return connect_mcp(name)\n\n\n# ── Tool Definitions ──\n\n# The model sees tool schemas; Python executes handlers. S20 keeps both tables\n# explicit so every added capability is visible in one place.\nBUILTIN_TOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"},\n \"offset\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"old_text\": {\"type\": \"string\"},\n \"new_text\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"pattern\": {\"type\": \"string\"}},\n \"required\": [\"pattern\"]}},\n {\"name\": \"todo_write\",\n \"description\": \"Create and manage a task list for the current session.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"todos\": {\"type\": \"array\",\n \"items\": {\"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\",\n \"enum\": [\"pending\", \"in_progress\", \"completed\"]}},\n \"required\": [\"content\", \"status\"]}}},\n \"required\": [\"todos\"]}},\n {\"name\": \"task\",\n \"description\": \"Launch a focused subagent. Returns only its final summary.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"description\": {\"type\": \"string\"}},\n \"required\": [\"description\"]}},\n {\"name\": \"load_skill\",\n \"description\": \"Load the full content of a skill by name.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"compact\",\n \"description\": \"Summarize earlier conversation and continue with compacted context.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"focus\": {\"type\": \"string\"}},\n \"required\": []}},\n {\"name\": \"create_task\", \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\", \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\", \"description\": \"Get full task details.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\", \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\", \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": (\"Schedule a cron job. cron is 5-field: min hour dom \"\n \"month dow. For one-shot reminders, compute the target \"\n \"minute and set recurring=false.\"),\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"cron\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"},\n \"recurring\": {\"type\": \"boolean\"},\n \"durable\": {\"type\": \"boolean\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\", \"description\": \"List registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"cancel_cron\", \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n {\"name\": \"spawn_teammate\", \"description\": \"Spawn an autonomous teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\", \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"check_inbox\",\n \"description\": \"Check inbox for messages and protocol responses.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n {\"name\": \"create_worktree\",\n \"description\": \"Create an isolated git worktree.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"task_id\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"remove_worktree\",\n \"description\": \"Remove a worktree. Refuses if changes exist.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"discard_changes\": {\"type\": \"boolean\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"keep_worktree\",\n \"description\": \"Keep a worktree for manual review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"connect_mcp\",\n \"description\": \"Connect to an MCP server (docs, deploy) and discover tools.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n]\n\nBUILTIN_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"edit_file\": run_edit, \"glob\": run_glob,\n \"todo_write\": run_todo_write, \"task\": spawn_subagent,\n \"load_skill\": load_skill,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron,\n \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message, \"check_inbox\": run_check_inbox,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n \"create_worktree\": run_create_worktree,\n \"remove_worktree\": run_remove_worktree,\n \"keep_worktree\": run_keep_worktree,\n \"connect_mcp\": run_connect_mcp,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\n \"memories\": memories,\n \"connected_mcp\": list(mcp_clients.keys()),\n \"active_teammates\": list(active_teammates.keys()),\n }\n\n\n# ── Agent Loop ──\n\nrounds_since_todo = 0\nagent_lock = threading.Lock()\n\n\ndef prepare_context(messages: list) -> list:\n # Every LLM turn enters through the same context budget pipeline.\n messages[:] = tool_result_budget(messages)\n messages[:] = snip_compact(messages)\n messages[:] = micro_compact(messages)\n if estimate_size(messages) > CONTEXT_LIMIT:\n messages[:] = compact_history(messages)\n return messages\n\n\ndef build_user_content(results: list[dict]) -> list[dict]:\n # Tool results and completed background notifications are both returned to\n # the model as user-side content, matching the tool_result feedback loop.\n content = list(results)\n for note in collect_background_results():\n content.append({\"type\": \"text\", \"text\": note})\n return content\n\n\ndef inject_background_notifications(messages: list):\n notes = collect_background_results()\n if notes:\n messages.append({\"role\": \"user\", \"content\": [\n {\"type\": \"text\", \"text\": note} for note in notes]})\n\n\ndef call_llm(messages: list, context: dict, tools: list,\n state: RecoveryState, max_tokens: int):\n system = assemble_system_prompt(context)\n return with_retry(\n lambda: client.messages.create(\n model=state.current_model,\n system=system,\n messages=messages,\n tools=tools,\n max_tokens=max_tokens),\n state)\n\n\ndef agent_loop(messages: list, context: dict):\n global rounds_since_todo\n tools, handlers = assemble_tool_pool()\n state = RecoveryState()\n max_tokens = DEFAULT_MAX_TOKENS\n\n while True:\n # One cycle: inject scheduled/background work, prepare context, call\n # the model, execute tool_use blocks, append tool_results, repeat.\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[cron inject] {job.prompt[:60]}\\033[0m\")\n\n inject_background_notifications(messages)\n\n if rounds_since_todo >= 3:\n messages.append({\"role\": \"user\",\n \"content\": \"Update your todos.\"})\n rounds_since_todo = 0\n\n prepare_context(messages)\n context = update_context(context, messages)\n tools, handlers = assemble_tool_pool()\n\n try:\n response = call_llm(messages, context, tools, state, max_tokens)\n except Exception as e:\n if is_prompt_too_long_error(e) and not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n print(f\" \\033[33m[max_tokens] retry with {max_tokens}\\033[0m\")\n continue\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n state.recovery_count += 1\n continue\n return\n\n max_tokens = DEFAULT_MAX_TOKENS\n state.has_escalated = False\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if not has_tool_use(response.content):\n trigger_hooks(\"Stop\", messages)\n return\n\n results = []\n compacted_now = False\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n messages.append({\"role\": \"user\",\n \"content\": \"[Compacted. Continue with summarized context.]\"})\n compacted_now = True\n break\n\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block, handlers)\n output = (f\"[Background task {bg_id} started] \"\n \"Result will arrive as a task_notification.\")\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n continue\n\n handler = handlers.get(block.name)\n output = call_tool_handler(handler, block.input, block.name)\n trigger_hooks(\"PostToolUse\", block, output)\n print(str(output)[:300])\n\n if block.name == \"todo_write\":\n rounds_since_todo = 0\n else:\n rounds_since_todo += 1\n\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n if compacted_now:\n continue\n\n messages.append({\"role\": \"user\", \"content\": build_user_content(results)})\n\n\ndef print_turn_assistants(messages: list, turn_start: int):\n for msg in messages[turn_start:]:\n if msg.get(\"role\") != \"assistant\":\n continue\n for block in msg.get(\"content\", []):\n if block_type(block) == \"text\":\n terminal_print(block[\"text\"] if isinstance(block, dict) else block.text)\n\n\ndef cron_autorun_loop(history: list, context: dict):\n while True:\n time.sleep(1)\n fired = consume_cron_queue()\n if not fired:\n continue\n with agent_lock:\n turn_start = len(history)\n for job in fired:\n history.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n terminal_print(\n f\" \\033[35m[cron auto] {job.prompt[:60]}\\033[0m\")\n agent_loop(history, context)\n context.update(update_context(context, history))\n print_turn_assistants(history, turn_start)\n\n\nif __name__ == \"__main__\":\n CLI_ACTIVE = True\n print(\"s20: comprehensive agent\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n threading.Thread(target=cron_autorun_loop,\n args=(history, context), daemon=True).start()\n while True:\n try:\n query = input(PROMPT)\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n trigger_hooks(\"UserPromptSubmit\", query)\n turn_start = len(history)\n history.append({\"role\": \"user\", \"content\": query})\n with agent_lock:\n agent_loop(history, context)\n context = update_context(context, history)\n print_turn_assistants(history, turn_start)\n\n inbox = consume_lead_inbox(route_protocol=True)\n if inbox:\n def inbox_label(msg):\n req_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n suffix = f\" req:{req_id}\" if req_id else \"\"\n return f\"{msg.get('type', 'message')}{suffix}\"\n\n inbox_text = \"\\n\".join(\n f\"From {m['from']} [{inbox_label(m)}]: \"\n f\"{m['content'][:200]}\" for m in inbox)\n history.append({\"role\": \"user\",\n \"content\": f\"[Inbox]\\n{inbox_text}\"})\n print()\n", + "source": "#!/usr/bin/env python3\n\"\"\"\ns19: Comprehensive Agent — all course mechanisms in one loop.\n\nRun: python s19_comprehensive/code.py\nNeed: pip install anthropic python-dotenv pyyaml + .env with ANTHROPIC_API_KEY\n\nThis final chapter puts the earlier mechanisms back together: dispatch,\npermission, hooks, todo, subagent, skills, compaction,\nmemory, prompt assembly, error recovery, task graph, background tasks, cron,\nteams, protocols, autonomous agents, worktrees, and MCP.\n\"\"\"\n\nimport ast, json, os, subprocess, time, random, threading, re\nfrom pathlib import Path\nfrom datetime import datetime\nfrom dataclasses import dataclass, asdict, field\nimport yaml\n\ntry:\n import readline\n readline.parse_and_bind('set bind-tty-special-chars off')\n READLINE_AVAILABLE = True\nexcept ImportError:\n READLINE_AVAILABLE = False\n\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv(override=True)\nif os.getenv(\"ANTHROPIC_BASE_URL\"):\n os.environ.pop(\"ANTHROPIC_AUTH_TOKEN\", None)\n\nWORKDIR = Path.cwd()\nclient = Anthropic(base_url=os.getenv(\"ANTHROPIC_BASE_URL\"))\nMODEL = os.environ[\"MODEL_ID\"]\nPRIMARY_MODEL = MODEL\nFALLBACK_MODEL = os.getenv(\"FALLBACK_MODEL_ID\")\n\nSKILLS_DIR = WORKDIR / \"skills\"\nTRANSCRIPT_DIR = WORKDIR / \".transcripts\"\nTOOL_RESULTS_DIR = WORKDIR / \".task_outputs\" / \"tool-results\"\n\nDEFAULT_MAX_TOKENS = 8000\nESCALATED_MAX_TOKENS = 16000\nMAX_RETRIES = 3\nMAX_CONSECUTIVE_529 = 2\nMAX_RECOVERY_RETRIES = 2\nBASE_DELAY_MS = 500\nCONTEXT_LIMIT = 50000\nKEEP_RECENT_TOOL_RESULTS = 3\nPERSIST_THRESHOLD = 30000\nCONTINUATION_PROMPT = \"Continue from the previous response. Do not repeat completed work.\"\nPROMPT = \"\\033[36ms19 >> \\033[0m\"\nCLI_ACTIVE = False\n\n\ndef terminal_print(text: str):\n if threading.current_thread() is threading.main_thread() or not CLI_ACTIVE:\n print(text)\n return\n line = \"\"\n if READLINE_AVAILABLE:\n try:\n line = readline.get_line_buffer()\n except Exception:\n line = \"\"\n print(f\"\\r\\033[K{text}\")\n print(PROMPT + line, end=\"\", flush=True)\n\n# ── Task System ──\n\n# Tasks are tiny durable records. Later systems add ownership, dependencies,\n# worktrees, and teammates on top of this same file-backed state.\nTASKS_DIR = WORKDIR / \".tasks\"\nTASKS_DIR.mkdir(exist_ok=True)\ntask_lock = threading.RLock()\nCURRENT_TODOS: list[dict] = []\n\n\n@dataclass\nclass Task:\n id: str\n subject: str\n description: str\n status: str\n owner: str | None\n blockedBy: list[str]\n worktree: str | None = None\n\n\ndef _task_path(task_id: str) -> Path:\n return TASKS_DIR / f\"{task_id}.json\"\n\n\ndef create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> Task:\n task = Task(\n id=f\"task_{int(time.time())}_{random.randint(0, 9999):04d}\",\n subject=subject, description=description,\n status=\"pending\", owner=None,\n blockedBy=blockedBy or [],\n )\n save_task(task)\n return task\n\n\ndef save_task(task: Task):\n _task_path(task.id).write_text(json.dumps(asdict(task), indent=2))\n\n\ndef load_task(task_id: str) -> Task:\n return Task(**json.loads(_task_path(task_id).read_text()))\n\n\ndef list_tasks() -> list[Task]:\n return [Task(**json.loads(p.read_text()))\n for p in sorted(TASKS_DIR.glob(\"task_*.json\"))]\n\n\ndef get_task_json(task_id: str) -> str:\n return json.dumps(asdict(load_task(task_id)), indent=2)\n\n\ndef can_start(task_id: str) -> bool:\n # Dependencies are intentionally simple: every blocker must exist and be\n # completed before the task can be claimed.\n task = load_task(task_id)\n for dep_id in task.blockedBy:\n if not _task_path(dep_id).exists():\n return False\n if load_task(dep_id).status != \"completed\":\n return False\n return True\n\n\ndef claim_task(task_id: str, owner: str = \"agent\") -> str:\n with task_lock:\n task = load_task(task_id)\n if task.status != \"pending\":\n return f\"Task {task_id} is {task.status}, cannot claim\"\n if task.owner:\n return f\"Task {task_id} already owned by {task.owner}\"\n if not can_start(task_id):\n deps = [d for d in task.blockedBy\n if (_task_path(d).exists()\n and load_task(d).status != \"completed\")]\n missing = [d for d in task.blockedBy\n if not _task_path(d).exists()]\n parts = []\n if deps:\n parts.append(f\"blocked by: {deps}\")\n if missing:\n parts.append(f\"missing deps: {missing}\")\n return \"Cannot start: \" + \", \".join(parts)\n task.owner = owner\n task.status = \"in_progress\"\n save_task(task)\n print(f\" \\033[36m[claim] {task.subject} → in_progress\\033[0m\")\n return f\"Claimed {task.id} ({task.subject})\"\n\n\ndef complete_task(task_id: str) -> str:\n task = load_task(task_id)\n if task.status != \"in_progress\":\n return f\"Task {task_id} is {task.status}, cannot complete\"\n task.status = \"completed\"\n save_task(task)\n unblocked = [t.subject for t in list_tasks()\n if t.status == \"pending\" and t.blockedBy and can_start(t.id)]\n print(f\" \\033[32m[complete] {task.subject} ✓\\033[0m\")\n msg = f\"Completed {task.id} ({task.subject})\"\n if unblocked:\n msg += f\"\\nUnblocked: {', '.join(unblocked)}\"\n return msg\n\n\n# ── Worktree System ──\n\n# Worktree names become filesystem paths, so validation stays strict and is\n# reused for create/remove/keep.\nWORKTREES_DIR = WORKDIR / \".worktrees\"\nWORKTREES_DIR.mkdir(exist_ok=True)\n\nVALID_WT_NAME = re.compile(r'^[A-Za-z0-9._-]{1,64}$')\n\n\ndef validate_worktree_name(name: str) -> str | None:\n if not name:\n return \"Worktree name cannot be empty\"\n if name in (\".\", \"..\"):\n return f\"'{name}' is not a valid worktree name\"\n if not VALID_WT_NAME.match(name):\n return (f\"Invalid worktree name '{name}': \"\n \"only letters, digits, dots, underscores, dashes (1-64 chars)\")\n return None\n\n\ndef run_git(args: list[str]) -> tuple[bool, str]:\n try:\n r = subprocess.run([\"git\"] + args, cwd=WORKDIR,\n capture_output=True, text=True, timeout=30)\n out = (r.stdout + r.stderr).strip()\n return r.returncode == 0, out[:5000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return False, \"Error: git timeout\"\n\n\ndef log_event(event_type: str, worktree_name: str, task_id: str = \"\"):\n event = {\"type\": event_type, \"worktree\": worktree_name,\n \"task_id\": task_id, \"ts\": time.time()}\n events_file = WORKTREES_DIR / \"events.jsonl\"\n with open(events_file, \"a\") as f:\n f.write(json.dumps(event) + \"\\n\")\n\n\ndef create_worktree(name: str, task_id: str = \"\") -> str:\n # Tool-layer validation is part of the safety boundary; do it before git\n # sees the name, not only after git happens to reject something.\n err = validate_worktree_name(name)\n if err:\n return f\"Error: {err}\"\n if task_id:\n try:\n load_task(task_id)\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n path = WORKTREES_DIR / name\n if path.exists():\n return f\"Worktree '{name}' already exists at {path}\"\n ok, result = run_git([\"worktree\", \"add\", str(path), \"-b\", f\"wt/{name}\", \"HEAD\"])\n if not ok:\n return f\"Git error: {result}\"\n if task_id:\n bind_task_to_worktree(task_id, name)\n log_event(\"create\", name, task_id)\n print(f\" \\033[33m[worktree] created: {name} at {path}\\033[0m\")\n return f\"Worktree '{name}' created at {path}\"\n\n\ndef bind_task_to_worktree(task_id: str, worktree_name: str):\n task = load_task(task_id)\n task.worktree = worktree_name\n save_task(task)\n\n\ndef _count_worktree_changes(path: Path) -> tuple[int, int]:\n try:\n r1 = subprocess.run([\"git\", \"status\", \"--porcelain\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n files = len([l for l in r1.stdout.strip().splitlines() if l.strip()])\n r2 = subprocess.run([\"git\", \"log\", \"@{push}..HEAD\", \"--oneline\"],\n cwd=path, capture_output=True, text=True, timeout=10)\n commits = len([l for l in r2.stdout.strip().splitlines() if l.strip()])\n return files, commits\n except Exception:\n return -1, -1\n\n\ndef remove_worktree(name: str, discard_changes: bool = False) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n path = WORKTREES_DIR / name\n if not path.exists():\n return f\"Worktree '{name}' not found\"\n if not discard_changes:\n files, commits = _count_worktree_changes(path)\n if files < 0:\n return \"Cannot verify status. Use discard_changes=true to force.\"\n if files > 0 or commits > 0:\n return (f\"Worktree '{name}' has {files} file(s), {commits} commit(s). \"\n \"Use discard_changes=true or keep_worktree.\")\n ok1, _ = run_git([\"worktree\", \"remove\", str(path), \"--force\"])\n if not ok1:\n return f\"Failed to remove worktree '{name}'\"\n run_git([\"branch\", \"-D\", f\"wt/{name}\"])\n log_event(\"remove\", name)\n print(f\" \\033[33m[worktree] removed: {name}\\033[0m\")\n return f\"Worktree '{name}' removed\"\n\n\ndef keep_worktree(name: str) -> str:\n err = validate_worktree_name(name)\n if err:\n return err\n log_event(\"keep\", name)\n return f\"Worktree '{name}' kept for review (branch: wt/{name})\"\n\n\n# ── Skill Loading ──\n\nSKILL_REGISTRY: dict[str, dict] = {}\n\n\ndef _parse_frontmatter(text: str) -> tuple[dict, str]:\n if not text.startswith(\"---\"):\n return {}, text\n parts = text.split(\"---\", 2)\n if len(parts) < 3:\n return {}, text\n try:\n meta = yaml.safe_load(parts[1]) or {}\n except yaml.YAMLError:\n meta = {}\n return meta, parts[2].strip()\n\n\ndef scan_skills():\n SKILL_REGISTRY.clear()\n if not SKILLS_DIR.exists():\n return\n for directory in sorted(SKILLS_DIR.iterdir()):\n if not directory.is_dir():\n continue\n manifest = directory / \"SKILL.md\"\n if not manifest.exists():\n continue\n raw = manifest.read_text()\n meta, _ = _parse_frontmatter(raw)\n name = meta.get(\"name\", directory.name)\n desc = meta.get(\"description\", raw.split(\"\\n\")[0].lstrip(\"#\").strip())\n SKILL_REGISTRY[name] = {\n \"name\": name,\n \"description\": desc,\n \"content\": raw,\n }\n\n\nscan_skills()\n\n\ndef list_skills() -> str:\n if not SKILL_REGISTRY:\n return \"(no skills found)\"\n return \"\\n\".join(\n f\"- {skill['name']}: {skill['description']}\"\n for skill in SKILL_REGISTRY.values())\n\n\ndef load_skill(name: str) -> str:\n skill = SKILL_REGISTRY.get(name)\n if not skill:\n available = \", \".join(SKILL_REGISTRY.keys()) or \"(none)\"\n return f\"Skill not found: {name}. Available: {available}\"\n return skill[\"content\"]\n\n\n# ── Prompt Assembly ──\n\nPROMPT_SECTIONS = {\n \"identity\": \"You are a coding agent. Act, don't explain.\",\n \"tools\": \"Available tools: bash, read_file, write_file, edit_file, glob, \"\n \"todo_write, task, load_skill, compact, \"\n \"create_task, list_tasks, get_task, claim_task, complete_task, \"\n \"schedule_cron, list_crons, cancel_cron, \"\n \"spawn_teammate, send_message, \"\n \"request_shutdown, request_plan, review_plan, \"\n \"create_worktree, remove_worktree, keep_worktree, \"\n \"connect_mcp. MCP tools are prefixed mcp__{server}__{tool}.\",\n \"teams\": (\n \"When parallel work would help, first propose a small team with clear \"\n \"responsibilities and wait for the user's confirmation. Do not call \"\n \"spawn_teammate before the user confirms.\"\n ),\n \"workspace\": f\"Working directory: {WORKDIR}\",\n \"memory\": \"Relevant memories are injected below when available.\",\n}\n\n\ndef assemble_system_prompt(context: dict) -> str:\n # The system prompt is rebuilt each turn from live context. This is where\n # memory, skill catalog, MCP state, and active teammates become visible.\n sections = [PROMPT_SECTIONS[\"identity\"],\n PROMPT_SECTIONS[\"tools\"],\n PROMPT_SECTIONS[\"teams\"],\n PROMPT_SECTIONS[\"workspace\"]]\n sections.append(f\"Current time: {datetime.now().isoformat(timespec='seconds')}\")\n sections.append(\"Skills catalog:\\n\" + list_skills() +\n \"\\nUse load_skill(name) when a skill is relevant.\")\n if context.get(\"memories\"):\n sections.append(f\"Relevant memories:\\n{context['memories']}\")\n mcp_names = list(mcp_clients.keys())\n if mcp_names:\n sections.append(f\"Connected MCP servers: {', '.join(mcp_names)}\")\n return \"\\n\\n\".join(sections)\n\n\n# ── Basic Tools ──\n\ndef run_bash(command: str, cwd: Path = None,\n run_in_background: bool = False) -> str:\n # run_in_background is consumed by the dispatcher; direct execution ignores it.\n try:\n r = subprocess.run(command, shell=True, cwd=cwd or WORKDIR,\n capture_output=True, text=True, timeout=120)\n out = (r.stdout + r.stderr).strip()\n return out[:50000] if out else \"(no output)\"\n except subprocess.TimeoutExpired:\n return \"Error: Timeout (120s)\"\n\n\ndef run_read(path: str, limit: int | None = None,\n offset: int = 0, cwd: Path = None) -> str:\n try:\n base = cwd or WORKDIR\n file_path = (base / path).resolve()\n lines = file_path.read_text().splitlines()\n offset = max(int(offset or 0), 0)\n limit = int(limit) if limit is not None else None\n lines = lines[offset:]\n if limit is not None and limit < len(lines):\n lines = lines[:limit] + [f\"... ({len(lines) - limit} more lines)\"]\n return \"\\n\".join(lines)\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_write(path: str, content: str, cwd: Path = None) -> str:\n try:\n base = cwd or WORKDIR\n fp = (base / path).resolve()\n fp.parent.mkdir(parents=True, exist_ok=True)\n fp.write_text(content)\n return f\"Wrote {len(content)} bytes to {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_edit(path: str, old_text: str, new_text: str,\n cwd: Path = None) -> str:\n try:\n base = cwd or WORKDIR\n fp = (base / path).resolve()\n text = fp.read_text()\n if old_text not in text:\n return f\"Error: text not found in {path}\"\n fp.write_text(text.replace(old_text, new_text, 1))\n return f\"Edited {path}\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef run_glob(pattern: str, cwd: Path = None) -> str:\n import glob as g\n try:\n base = cwd or WORKDIR\n results = []\n for match in g.glob(pattern, root_dir=base):\n if (base / match).resolve().is_relative_to(base):\n results.append(match)\n return \"\\n\".join(results) if results else \"(no matches)\"\n except Exception as e:\n return f\"Error: {e}\"\n\n\ndef call_tool_handler(handler, args: dict, name: str) -> str:\n if not handler:\n return f\"Unknown: {name}\"\n try:\n return handler(**(args or {}))\n except TypeError as e:\n return f\"Error: {e}\"\n\n\ndef _normalize_todos(todos):\n if isinstance(todos, str):\n try:\n todos = json.loads(todos)\n except json.JSONDecodeError:\n try:\n todos = ast.literal_eval(todos)\n except (SyntaxError, ValueError):\n return None, \"Error: todos must be a list or JSON array string\"\n if not isinstance(todos, list):\n return None, \"Error: todos must be a list\"\n for i, todo in enumerate(todos):\n if not isinstance(todo, dict):\n return None, f\"Error: todos[{i}] must be an object\"\n if \"content\" not in todo or \"status\" not in todo:\n return None, f\"Error: todos[{i}] missing 'content' or 'status'\"\n if todo[\"status\"] not in (\"pending\", \"in_progress\", \"completed\"):\n return None, f\"Error: todos[{i}] has invalid status '{todo['status']}'\"\n return todos, None\n\ndef run_todo_write(todos: list) -> str:\n global CURRENT_TODOS\n todos, error = _normalize_todos(todos)\n if error:\n return error\n CURRENT_TODOS = todos\n print(f\" \\033[33m[todo] updated {len(CURRENT_TODOS)} item(s)\\033[0m\")\n return f\"Updated {len(CURRENT_TODOS)} todos\"\n\n\n# ── MessageBus (from s15) ──\n\nMAILBOX_DIR = WORKDIR / \".mailboxes\"\nMAILBOX_DIR.mkdir(exist_ok=True)\nMAILBOX_ROOT = MAILBOX_DIR.resolve()\nVALID_AGENT_NAME = re.compile(r\"^[A-Za-z0-9_-]{1,64}$\")\n\n\ndef is_valid_agent_name(name: str) -> bool:\n return bool(VALID_AGENT_NAME.fullmatch(name))\n\n\nclass MessageBus:\n def __init__(self):\n self._lock = threading.RLock()\n self._changed = threading.Condition(self._lock)\n\n def _path(self, agent: str) -> Path:\n if not is_valid_agent_name(agent):\n raise ValueError(f\"Invalid mailbox recipient: {agent!r}\")\n path = (MAILBOX_DIR / f\"{agent}.jsonl\").resolve()\n if not path.is_relative_to(MAILBOX_ROOT):\n raise ValueError(f\"Mailbox path escapes directory: {agent!r}\")\n return path\n\n def _read_unlocked(self, agent: str) -> list[dict]:\n inbox = self._path(agent)\n if not inbox.exists():\n return []\n msgs = [json.loads(line) for line in inbox.read_text().splitlines()\n if line.strip()]\n inbox.unlink()\n return msgs\n\n def send(self, from_agent: str, to_agent: str, content: str,\n msg_type: str = \"message\", metadata: dict | None = None):\n msg = {\"from\": from_agent, \"to\": to_agent,\n \"content\": content, \"type\": msg_type,\n \"ts\": time.time(), \"metadata\": metadata or {}}\n with self._changed:\n with open(self._path(to_agent), \"a\") as f:\n f.write(json.dumps(msg, ensure_ascii=False) + \"\\n\")\n self._changed.notify_all()\n print(f\" \\033[33m[bus] {from_agent} → {to_agent}: \"\n f\"({msg_type}) {content[:50]}\\033[0m\")\n\n def read_inbox(self, agent: str) -> list[dict]:\n with self._lock:\n return self._read_unlocked(agent)\n\n def peek(self, agent: str) -> bool:\n with self._lock:\n inbox = self._path(agent)\n return inbox.exists() and inbox.stat().st_size > 0\n\n def wait_for_messages(self, agent: str,\n timeout: float | None = None) -> list[dict]:\n deadline = None if timeout is None else time.monotonic() + timeout\n with self._changed:\n while not self.peek(agent):\n remaining = (None if deadline is None\n else deadline - time.monotonic())\n if remaining is not None and remaining <= 0:\n return []\n self._changed.wait(remaining)\n return self._read_unlocked(agent)\n\n\nBUS = MessageBus()\nactive_teammates: dict[str, str] = {}\nplan_gates: dict[str, str] = {}\nplan_request_ids: dict[str, str] = {}\nteam_lock = threading.RLock()\n\n# ── Protocol State (from s15) ──\n\n@dataclass\nclass ProtocolState:\n request_id: str\n type: str\n sender: str\n target: str\n status: str\n payload: str\n created_at: float = field(default_factory=time.time)\n\n\npending_requests: dict[str, ProtocolState] = {}\n\n\ndef new_request_id() -> str:\n while True:\n request_id = f\"req_{random.randint(0, 999999):06d}\"\n if request_id not in pending_requests:\n return request_id\n\n\ndef match_response(response_type: str, request_id: str, approve: bool,\n from_agent: str, to_agent: str) -> bool:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n print(f\" \\033[31m[protocol] unknown request_id: {request_id}\\033[0m\")\n return False\n expected = {\n \"shutdown\": \"shutdown_response\",\n \"plan_approval\": \"plan_approval_response\",\n }[state.type]\n if response_type != expected:\n print(f\" \\033[31m[protocol] expected {expected}, \"\n f\"got {response_type}\\033[0m\")\n return False\n if from_agent != state.target or to_agent != state.sender:\n print(f\" \\033[31m[protocol] {request_id} responder mismatch\\033[0m\")\n return False\n if state.status != \"pending\":\n return False\n state.status = \"approved\" if approve else \"rejected\"\n icon = \"✓\" if approve else \"✗\"\n color = \"32\" if approve else \"31\"\n print(f\" \\033[{color}m[protocol] {state.type} {icon} \"\n f\"({request_id}: {state.status})\\033[0m\")\n return True\n\n\ndef consume_lead_inbox(route_protocol=True) -> list[dict]:\n msgs = BUS.read_inbox(\"lead\")\n if route_protocol:\n for msg in msgs:\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n msg_type = msg.get(\"type\", \"\")\n if req_id and msg_type.endswith(\"_response\"):\n match_response(msg_type, req_id, meta.get(\"approve\", False),\n msg.get(\"from\", \"\"), msg.get(\"to\", \"\"))\n return msgs\n\n\ndef format_team_events(msgs: list[dict]) -> str:\n lines = []\n for msg in msgs:\n request_id = msg.get(\"metadata\", {}).get(\"request_id\")\n suffix = f\" request_id={request_id}\" if request_id else \"\"\n lines.append(\n f\"[{msg['type']}{suffix}] {msg['from']}: {msg['content']}\"\n )\n return \"[Team events]\\n\" + \"\\n\".join(lines)\n\n\n# ── Autonomous Agent (from s16, + worktree cwd) ──\n\nIDLE_SCAN_INTERVAL = 2.0\n\n\ndef scan_unclaimed_tasks() -> list[Task]:\n return [\n task for task in list_tasks()\n if (task.status == \"pending\"\n and task.owner is None\n and can_start(task.id))\n ]\n\n\ndef claim_next_task(name: str) -> Task | None:\n for task in scan_unclaimed_tasks():\n result = claim_task(task.id, owner=name)\n if result.startswith(\"Claimed \"):\n return load_task(task.id)\n return None\n\n\ndef _last_assistant_text(content) -> str:\n for block in content:\n if getattr(block, \"type\", None) == \"text\":\n return block.text.strip()\n if isinstance(block, dict) and block.get(\"type\") == \"text\":\n return str(block.get(\"text\", \"\")).strip()\n return \"\"\n\n\ndef _run_teammate_tool(name: str, block, handlers: dict) -> str:\n gate = plan_gates.get(name, \"not_required\")\n if (block.name in {\"bash\", \"write_file\"}\n and gate not in {\"not_required\", \"approved\"}):\n return f\"Blocked: plan status is {gate}.\"\n handler = handlers.get(block.name)\n return str(handler(**block.input)) if handler else f\"Unknown tool: {block.name}\"\n\n\ndef apply_plan_response(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Apply only the Lead response for this teammate's current plan.\"\"\"\n metadata = msg.get(\"metadata\", {})\n request_id = metadata.get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n expected_id = plan_request_ids.get(name)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and request_id == expected_id\n and state is not None\n and state.type == \"plan_approval\"\n and state.sender == name\n and state.target == \"lead\"\n and state.status in {\"approved\", \"rejected\"}\n and metadata.get(\"approve\", False)\n == (state.status == \"approved\")\n )\n if not valid:\n return False, \"[Ignored plan response: request mismatch]\"\n plan_gates[name] = state.status\n active_teammates[name] = \"working\"\n plan_request_ids.pop(name, None)\n outcome = state.status\n return True, f\"[Plan {outcome}] {msg['content']}\"\n\n\ndef apply_shutdown_request(name: str, msg: dict) -> tuple[bool, str]:\n \"\"\"Accept only a pending shutdown request sent by Lead to this teammate.\"\"\"\n request_id = msg.get(\"metadata\", {}).get(\"request_id\", \"\")\n with team_lock:\n state = pending_requests.get(request_id)\n valid = (\n msg.get(\"from\") == \"lead\"\n and msg.get(\"to\") == name\n and state is not None\n and state.type == \"shutdown\"\n and state.sender == \"lead\"\n and state.target == name\n and state.status == \"pending\"\n and active_teammates.get(name) != \"stopping\"\n )\n if not valid:\n return False, \"[Ignored shutdown request: request mismatch]\"\n active_teammates[name] = \"stopping\"\n return True, request_id\n\n\ndef _teammate_send_message(from_name: str, to: str, content: str) -> str:\n with team_lock:\n if to != \"lead\" and to not in active_teammates:\n return f\"Agent '{to}' is not active\"\n BUS.send(from_name, to, content)\n return f\"Sent to {to}\"\n\n\n# ── Teammate Thread ──\n\ndef spawn_teammate_thread(name: str, role: str, prompt: str) -> str:\n if not is_valid_agent_name(name):\n return (\"Invalid teammate name: use 1-64 letters, digits, \"\n \"underscores, or dashes\")\n with team_lock:\n if name in active_teammates:\n return f\"Teammate '{name}' already exists\"\n active_teammates[name] = \"working\"\n plan_gates[name] = \"not_required\"\n\n system = (f\"You are '{name}', a {role}. \"\n \"Use tools to complete tasks. \"\n \"You can list and claim tasks from the board. \"\n \"If a task has a worktree, work in that directory. \"\n \"When asked for a plan, submit it before bash or write_file \"\n \"and wait for approval.\")\n\n def handle_inbox_message(name: str, msg: dict, messages: list):\n msg_type = msg.get(\"type\", \"message\")\n meta = msg.get(\"metadata\", {})\n req_id = meta.get(\"request_id\", \"\")\n\n if msg_type == \"shutdown_request\":\n accepted, notice = apply_shutdown_request(name, msg)\n if not accepted:\n messages.append({\"role\": \"user\", \"content\": notice})\n return False\n req_id = notice\n BUS.send(name, \"lead\", \"Shutting down gracefully.\",\n \"shutdown_response\",\n {\"request_id\": req_id, \"approve\": True})\n print(f\" \\033[35m[protocol] {name} approved shutdown \"\n f\"({req_id})\\033[0m\")\n return True\n\n if msg_type == \"plan_approval_response\":\n _, notice = apply_plan_response(name, msg)\n messages.append({\"role\": \"user\",\n \"content\": notice})\n elif msg_type == \"plan_request\":\n messages.append({\"role\": \"user\",\n \"content\": f\"[Plan required] {msg['content']}\"})\n elif msg_type == \"message\":\n messages.append({\"role\": \"user\",\n \"content\": f\"[Message from {msg['from']}] {msg['content']}\"})\n return False\n\n def run():\n # Track current worktree for this teammate's cwd\n wt_ctx = {\"path\": None}\n\n def _wt_cwd() -> Path | None:\n p = wt_ctx[\"path\"]\n return Path(p) if p else None\n\n def _run_bash(command: str) -> str:\n return run_bash(command, cwd=_wt_cwd())\n\n def _run_read(path: str) -> str:\n return run_read(path, cwd=_wt_cwd())\n\n def _run_write(path: str, content: str) -> str:\n return run_write(path, content, cwd=_wt_cwd())\n\n def _run_list_tasks():\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n def _run_claim_task(task_id: str):\n result = claim_task(task_id, owner=name)\n if \"Claimed\" in result:\n # Set worktree cwd if task has one\n task = load_task(task_id)\n if task.worktree:\n wt_ctx[\"path\"] = str(WORKTREES_DIR / task.worktree)\n else:\n wt_ctx[\"path\"] = None\n return result\n\n def _run_complete_task(task_id: str):\n result = complete_task(task_id)\n wt_ctx[\"path\"] = None\n return result\n\n messages = [{\"role\": \"user\", \"content\": prompt}]\n sub_tools = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"send_message\",\n \"description\": \"Send message to another agent.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"submit_plan\",\n \"description\": \"Submit a plan for Lead approval.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"plan\": {\"type\": \"string\"}},\n \"required\": [\"plan\"]}},\n {\"name\": \"list_tasks\",\n \"description\": \"List all tasks on the board.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n {\"name\": \"claim_task\",\n \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\",\n \"description\": \"Mark an in-progress task as completed.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n ]\n\n sub_handlers = {\n \"bash\": _run_bash, \"read_file\": _run_read,\n \"write_file\": _run_write,\n \"send_message\": lambda to, content: _teammate_send_message(\n name, to, content),\n \"submit_plan\": lambda plan: _teammate_submit_plan(name, plan),\n \"list_tasks\": _run_list_tasks,\n \"claim_task\": _run_claim_task,\n \"complete_task\": _run_complete_task,\n }\n\n # Outer loop: WORK → IDLE cycle\n while True:\n if len(messages) <= 3:\n messages.insert(0, {\"role\": \"user\",\n \"content\": f\"You are '{name}', role: {role}. \"\n f\"Continue your work.\"})\n\n # WORK phase\n should_shutdown = False\n for _ in range(10):\n inbox = BUS.read_inbox(name)\n for msg in inbox:\n stopped = handle_inbox_message(name, msg, messages)\n if stopped:\n should_shutdown = True\n break\n if should_shutdown:\n break\n try:\n response = client.messages.create(\n model=MODEL, system=system, messages=messages[-20:],\n tools=sub_tools, max_tokens=8000)\n except Exception:\n break\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if response.stop_reason != \"tool_use\":\n summary = _last_assistant_text(response.content)\n gate = plan_gates.get(name, \"not_required\")\n if gate != \"pending\" and summary:\n BUS.send(name, \"lead\", summary, \"result\")\n if gate == \"pending\":\n with team_lock:\n active_teammates[name] = \"waiting_approval\"\n else:\n with team_lock:\n active_teammates[name] = \"idle\"\n BUS.send(name, \"lead\", \"Waiting for more work.\",\n \"idle_notification\")\n break\n results = []\n for block in response.content:\n if block.type == \"tool_use\":\n output = _run_teammate_tool(name, block, sub_handlers)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n\n if should_shutdown:\n break\n\n # IDLE phase: messages take priority, then scan the task board.\n while True:\n inbox = BUS.wait_for_messages(name, IDLE_SCAN_INTERVAL)\n if inbox:\n for msg in inbox:\n if handle_inbox_message(name, msg, messages):\n should_shutdown = True\n break\n if should_shutdown or messages[-1][\"role\"] == \"user\":\n break\n continue\n\n task = claim_next_task(name)\n if not task:\n continue\n wt_ctx[\"path\"] = (str(WORKTREES_DIR / task.worktree)\n if task.worktree else None)\n workdir = (f\"\\nWork directory: {wt_ctx['path']}\"\n if wt_ctx[\"path\"] else \"\")\n messages.append({\n \"role\": \"user\",\n \"content\": (\n f\"[Auto-claimed task {task.id}] \"\n f\"{task.subject}\\n{task.description}{workdir}\"\n ),\n })\n print(f\" \\033[32m[idle] {name} claimed \"\n f\"{task.id}: {task.subject}\\033[0m\")\n break\n if should_shutdown:\n break\n\n with team_lock:\n active_teammates.pop(name, None)\n plan_gates.pop(name, None)\n plan_request_ids.pop(name, None)\n print(f\" \\033[32m[teammate] {name} finished\\033[0m\")\n\n threading.Thread(target=run, daemon=True).start()\n print(f\" \\033[36m[teammate] {name} spawned as {role}\\033[0m\")\n return f\"Teammate '{name}' spawned as {role} (autonomous)\"\n\n\ndef _teammate_submit_plan(from_name: str, plan: str) -> str:\n with team_lock:\n if plan_gates.get(from_name) == \"pending\":\n return \"A plan is already waiting for review.\"\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"plan_approval\",\n sender=from_name, target=\"lead\",\n status=\"pending\", payload=plan)\n plan_gates[from_name] = \"pending\"\n plan_request_ids[from_name] = req_id\n active_teammates[from_name] = \"waiting_approval\"\n BUS.send(from_name, \"lead\", plan,\n \"plan_approval_request\",\n {\"request_id\": req_id})\n return f\"Plan submitted ({req_id}). Waiting for approval...\"\n\n\n# ── Lead Protocol Tools (from s15) ──\n\ndef run_request_shutdown(teammate: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n req_id = new_request_id()\n pending_requests[req_id] = ProtocolState(\n request_id=req_id, type=\"shutdown\",\n sender=\"lead\", target=teammate,\n status=\"pending\", payload=\"\")\n BUS.send(\"lead\", teammate, \"Please shut down gracefully.\",\n \"shutdown_request\",\n {\"request_id\": req_id})\n print(f\" \\033[35m[protocol] shutdown_request → {teammate} \"\n f\"({req_id})\\033[0m\")\n return f\"Shutdown request sent to {teammate} (req: {req_id})\"\n\n\ndef run_request_plan(teammate: str, task: str) -> str:\n if teammate not in active_teammates:\n return f\"Teammate '{teammate}' is not active\"\n with team_lock:\n plan_gates[teammate] = \"required\"\n BUS.send(\"lead\", teammate, task, \"plan_request\")\n return f\"Asked {teammate} to submit a plan\"\n\n\ndef run_review_plan(request_id: str, approve: bool,\n feedback: str = \"\") -> str:\n with team_lock:\n state = pending_requests.get(request_id)\n if not state:\n return f\"Request {request_id} not found\"\n if state.type != \"plan_approval\":\n return f\"Request {request_id} is not a plan\"\n if state.status != \"pending\":\n return f\"Request {request_id} already {state.status}\"\n if plan_request_ids.get(state.sender) != request_id:\n return f\"Request {request_id} is not the current plan\"\n state.status = \"approved\" if approve else \"rejected\"\n BUS.send(\"lead\", state.sender,\n feedback or (\"Approved\" if approve else \"Rejected\"),\n \"plan_approval_response\",\n {\"request_id\": request_id, \"approve\": approve})\n icon = \"✓\" if approve else \"✗\"\n print(f\" \\033[32m[protocol] plan {icon} ({request_id})\\033[0m\")\n return f\"Plan {'approved' if approve else 'rejected'} ({request_id})\"\n\n\n# ── Hooks + Permission Pipeline ──\n\n# Hooks are intentionally outside tool handlers. The loop can add permission,\n# logging, and stop behavior without changing each individual tool.\nHOOKS = {\"UserPromptSubmit\": [], \"PreToolUse\": [],\n \"PostToolUse\": [], \"Stop\": []}\n\n\ndef register_hook(event: str, callback):\n HOOKS[event].append(callback)\n\n\ndef trigger_hooks(event: str, *args):\n for callback in HOOKS[event]:\n result = callback(*args)\n if result is not None:\n return result\n return None\n\n\nDENY_LIST = [\"rm -rf /\", \"sudo\", \"shutdown\", \"reboot\", \"mkfs\", \"dd if=\"]\nDESTRUCTIVE = [\"rm \", \"> /etc/\", \"chmod 777\"]\n\n\ndef permission_hook(block):\n # The permission layer sees the raw tool_use before dispatch. It can deny,\n # ask the user, or allow execution to continue.\n if block.name == \"bash\":\n command = block.input.get(\"command\", \"\")\n for pattern in DENY_LIST:\n if pattern in command:\n return f\"Permission denied: '{pattern}' is on the deny list\"\n if any(token in command for token in DESTRUCTIVE):\n print(f\"\\n\\033[33m[permission] destructive command\\033[0m\")\n print(f\" {command}\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n if block.name in (\"read_file\", \"write_file\", \"edit_file\"):\n path = block.input.get(\"path\", \"\")\n if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):\n print(f\"\\n\\033[33m[permission] Access outside workspace\\033[0m\")\n print(f\" {block.name}: {path}\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n if block.name.startswith(\"mcp__\") and \"deploy\" in block.name:\n print(f\"\\n\\033[33m[permission] MCP destructive-looking tool: {block.name}\\033[0m\")\n choice = input(\" Allow? [y/N] \").strip().lower()\n if choice not in (\"y\", \"yes\"):\n return \"Permission denied by user\"\n return None\n\n\ndef log_hook(block):\n print(f\"\\033[90m[HOOK] {block.name}\\033[0m\")\n return None\n\n\ndef large_output_hook(block, output):\n if len(str(output)) > 100000:\n print(f\"\\033[33m[HOOK] large output from {block.name}: \"\n f\"{len(str(output))} chars\\033[0m\")\n return None\n\n\ndef user_prompt_hook(query: str):\n print(f\"\\033[90m[HOOK] UserPromptSubmit: {WORKDIR}\\033[0m\")\n return None\n\n\ndef stop_hook(messages: list):\n tool_count = 0\n for msg in messages:\n content = msg.get(\"content\")\n if isinstance(content, list):\n tool_count += sum(1 for item in content\n if isinstance(item, dict)\n and item.get(\"type\") == \"tool_result\")\n print(f\"\\033[90m[HOOK] Stop: {tool_count} tool result(s)\\033[0m\")\n return None\n\n\nregister_hook(\"UserPromptSubmit\", user_prompt_hook)\nregister_hook(\"PreToolUse\", permission_hook)\nregister_hook(\"PreToolUse\", log_hook)\nregister_hook(\"PostToolUse\", large_output_hook)\nregister_hook(\"Stop\", stop_hook)\n\n\n# ── Subagent Tool ──\n\nSUB_SYSTEM = (\n f\"You are a coding subagent at {WORKDIR}. \"\n \"Complete the task, then return a concise final summary. \"\n \"Do not spawn more agents.\"\n)\n\n\nSUB_TOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"},\n \"offset\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"old_text\": {\"type\": \"string\"},\n \"new_text\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"pattern\": {\"type\": \"string\"}},\n \"required\": [\"pattern\"]}},\n]\n\n\nSUB_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read,\n \"write_file\": run_write, \"edit_file\": run_edit,\n \"glob\": run_glob,\n}\n\n\ndef extract_text(content) -> str:\n if not isinstance(content, list):\n return str(content)\n return \"\\n\".join(\n getattr(block, \"text\", \"\")\n for block in content\n if getattr(block, \"type\", None) == \"text\").strip()\n\n\ndef has_tool_use(content) -> bool:\n # Do not rely on stop_reason alone; the concrete tool_use block is the\n # continuation signal used by the loop.\n return any(getattr(block, \"type\", None) == \"tool_use\"\n for block in content)\n\n\ndef spawn_subagent(description: str) -> str:\n messages = [{\"role\": \"user\", \"content\": description}]\n for _ in range(30):\n response = client.messages.create(\n model=MODEL, system=SUB_SYSTEM, messages=messages,\n tools=SUB_TOOLS, max_tokens=8000)\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if not has_tool_use(response.content):\n break\n results = []\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n output = str(blocked)\n else:\n handler = SUB_HANDLERS.get(block.name)\n output = call_tool_handler(handler, block.input, block.name)\n trigger_hooks(\"PostToolUse\", block, output)\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(output)})\n messages.append({\"role\": \"user\", \"content\": results})\n for msg in reversed(messages):\n if msg[\"role\"] == \"assistant\":\n text = extract_text(msg[\"content\"])\n if text:\n return text\n return \"Subagent finished without a text summary.\"\n\n\n# ── Context Compaction ──\n\n# Compaction is layered: first shrink oversized tool results, then trim old\n# message ranges, and only call the model for a summary when the context is\n# still too large or the model explicitly asks for compact.\ndef estimate_size(messages: list) -> int:\n return len(json.dumps(messages, default=str))\n\ndef block_type(block):\n return block.get(\"type\") if isinstance(block, dict) else getattr(block, \"type\", None)\n\n\ndef message_has_tool_use(message: dict) -> bool:\n if message.get(\"role\") != \"assistant\":\n return False\n content = message.get(\"content\")\n if not isinstance(content, list):\n return False\n return any(block_type(block) == \"tool_use\" for block in content)\n\n\ndef is_tool_result_message(message: dict) -> bool:\n if message.get(\"role\") != \"user\":\n return False\n content = message.get(\"content\")\n if not isinstance(content, list):\n return False\n return any(isinstance(block, dict) and block.get(\"type\") == \"tool_result\"\n for block in content)\n\n\ndef collect_tool_results(messages: list):\n found = []\n for mi, msg in enumerate(messages):\n content = msg.get(\"content\")\n if msg.get(\"role\") != \"user\" or not isinstance(content, list):\n continue\n for bi, block in enumerate(content):\n if isinstance(block, dict) and block.get(\"type\") == \"tool_result\":\n found.append((mi, bi, block))\n return found\n\n\ndef persist_large_output(tool_use_id: str, output: str) -> str:\n if len(output) <= PERSIST_THRESHOLD:\n return output\n TOOL_RESULTS_DIR.mkdir(parents=True, exist_ok=True)\n path = TOOL_RESULTS_DIR / f\"{tool_use_id}.txt\"\n if not path.exists():\n path.write_text(output)\n return (f\"\\nFull output: {path}\\n\"\n f\"Preview:\\n{output[:2000]}\\n\")\n\n\ndef tool_result_budget(messages: list, max_bytes: int = 200_000) -> list:\n if not messages:\n return messages\n last = messages[-1]\n content = last.get(\"content\")\n if last.get(\"role\") != \"user\" or not isinstance(content, list):\n return messages\n blocks = [(i, b) for i, b in enumerate(content)\n if isinstance(b, dict) and b.get(\"type\") == \"tool_result\"]\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n if total <= max_bytes:\n return messages\n for _, block in sorted(blocks,\n key=lambda pair: len(str(pair[1].get(\"content\", \"\"))),\n reverse=True):\n if total <= max_bytes:\n break\n text = str(block.get(\"content\", \"\"))\n block[\"content\"] = persist_large_output(\n block.get(\"tool_use_id\", \"unknown\"), text)\n total = sum(len(str(b.get(\"content\", \"\"))) for _, b in blocks)\n return messages\n\n\ndef snip_compact(messages: list, max_messages: int = 50) -> list:\n if len(messages) <= max_messages:\n return messages\n head_end, tail_start = 3, len(messages) - (max_messages - 3)\n if head_end > 0 and message_has_tool_use(messages[head_end - 1]):\n while head_end < len(messages) and is_tool_result_message(messages[head_end]):\n head_end += 1\n if (tail_start > 0 and tail_start < len(messages)\n and is_tool_result_message(messages[tail_start])\n and message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n if head_end >= tail_start:\n return messages\n snipped = tail_start - head_end\n return (messages[:head_end]\n + [{\"role\": \"user\", \"content\": f\"[snipped {snipped} messages]\"}]\n + messages[tail_start:])\n\n\ndef micro_compact(messages: list) -> list:\n tool_results = collect_tool_results(messages)\n if len(tool_results) <= KEEP_RECENT_TOOL_RESULTS:\n return messages\n for _, _, block in tool_results[:-KEEP_RECENT_TOOL_RESULTS]:\n if len(str(block.get(\"content\", \"\"))) > 120:\n block[\"content\"] = \"[Earlier tool result compacted. Re-run if needed.]\"\n return messages\n\n\ndef write_transcript(messages: list) -> Path:\n TRANSCRIPT_DIR.mkdir(parents=True, exist_ok=True)\n path = TRANSCRIPT_DIR / f\"transcript_{int(time.time())}.jsonl\"\n with path.open(\"w\") as f:\n for msg in messages:\n f.write(json.dumps(msg, default=str) + \"\\n\")\n return path\n\n\ndef summarize_history(messages: list) -> str:\n conversation = json.dumps(messages, default=str)[:80000]\n prompt = (\"Summarize this coding-agent conversation so work can continue. \"\n \"Preserve current goal, key findings, changed files, remaining work, \"\n \"and user constraints.\\n\\n\" + conversation)\n response = client.messages.create(\n model=MODEL,\n messages=[{\"role\": \"user\", \"content\": prompt}],\n max_tokens=2000)\n return extract_text(response.content) or \"(empty summary)\"\n\n\ndef compact_history(messages: list) -> list:\n transcript = write_transcript(messages)\n print(f\" \\033[36m[compact] transcript saved: {transcript}\\033[0m\")\n summary = summarize_history(messages)\n return [{\"role\": \"user\", \"content\": f\"[Compacted]\\n\\n{summary}\"}]\n\n\ndef reactive_compact(messages: list) -> list:\n transcript = write_transcript(messages)\n print(f\" \\033[31m[reactive compact] transcript saved: {transcript}\\033[0m\")\n tail_start = max(0, len(messages) - 5)\n if (tail_start > 0 and tail_start < len(messages)\n and is_tool_result_message(messages[tail_start])\n and message_has_tool_use(messages[tail_start - 1])):\n tail_start -= 1\n try:\n summary = summarize_history(messages[:tail_start])\n except Exception:\n summary = \"Earlier conversation was trimmed after a prompt-too-long error.\"\n return [{\"role\": \"user\", \"content\": f\"[Reactive compact]\\n\\n{summary}\"},\n *messages[tail_start:]]\n\n\n# ── Error Recovery ──\n\nclass RecoveryState:\n def __init__(self):\n self.has_escalated = False\n self.recovery_count = 0\n self.consecutive_529 = 0\n self.has_attempted_reactive_compact = False\n self.current_model = PRIMARY_MODEL\n\n\ndef retry_delay(attempt: int) -> float:\n base = min(BASE_DELAY_MS * (2 ** attempt), 32000) / 1000\n return base + random.uniform(0, base * 0.25)\n\n\ndef with_retry(fn, state: RecoveryState):\n for attempt in range(MAX_RETRIES):\n try:\n result = fn()\n state.consecutive_529 = 0\n return result\n except Exception as e:\n name = type(e).__name__.lower()\n msg = str(e).lower()\n if \"ratelimit\" in name or \"429\" in msg:\n delay = retry_delay(attempt)\n print(f\" \\033[33m[429] retry {attempt + 1}/{MAX_RETRIES} \"\n f\"after {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n if \"overloaded\" in name or \"529\" in msg or \"overloaded\" in msg:\n state.consecutive_529 += 1\n if state.consecutive_529 >= MAX_CONSECUTIVE_529 and FALLBACK_MODEL:\n state.current_model = FALLBACK_MODEL\n state.consecutive_529 = 0\n print(f\" \\033[31m[529] switching to {FALLBACK_MODEL}\\033[0m\")\n delay = retry_delay(attempt)\n print(f\" \\033[33m[529] retry {attempt + 1}/{MAX_RETRIES} \"\n f\"after {delay:.1f}s\\033[0m\")\n time.sleep(delay)\n continue\n raise\n raise RuntimeError(f\"Max retries ({MAX_RETRIES}) exceeded\")\n\n\ndef is_prompt_too_long_error(e: Exception) -> bool:\n msg = str(e).lower()\n return ((\"prompt\" in msg and \"long\" in msg)\n or \"context_length_exceeded\" in msg\n or \"max_context_window\" in msg)\n\n\n# ── Background Tasks ──\n\n# Slow tools return a placeholder tool_result immediately. Their real output is\n# later injected as a task_notification, so the main loop can keep moving.\n_bg_counter = 0\nbackground_tasks: dict[str, dict] = {}\nbackground_results: dict[str, str] = {}\nbackground_lock = threading.Lock()\n\n\ndef is_slow_operation(tool_name: str, tool_input: dict) -> bool:\n if tool_name != \"bash\":\n return False\n command = tool_input.get(\"command\", \"\").lower()\n slow_keywords = [\"install\", \"build\", \"test\", \"deploy\", \"compile\",\n \"docker build\", \"pip install\", \"npm install\",\n \"cargo build\", \"pytest\", \"make\"]\n return any(keyword in command for keyword in slow_keywords)\n\n\ndef should_run_background(tool_name: str, tool_input: dict) -> bool:\n if tool_name != \"bash\":\n return False\n return bool(tool_input.get(\"run_in_background\")) or is_slow_operation(tool_name, tool_input)\n\n\ndef start_background_task(block, handlers: dict) -> str:\n global _bg_counter\n _bg_counter += 1\n bg_id = f\"bg_{_bg_counter:04d}\"\n command = block.input.get(\"command\", block.name)\n\n def worker():\n handler = handlers.get(block.name)\n result = call_tool_handler(handler, block.input, block.name)\n trigger_hooks(\"PostToolUse\", block, result)\n with background_lock:\n background_tasks[bg_id][\"status\"] = \"completed\"\n background_results[bg_id] = str(result)\n\n with background_lock:\n background_tasks[bg_id] = {\n \"tool_use_id\": block.id,\n \"command\": command,\n \"status\": \"running\",\n }\n threading.Thread(target=worker, daemon=True).start()\n print(f\" \\033[33m[background] {bg_id}: {str(command)[:60]}\\033[0m\")\n return bg_id\n\n\ndef collect_background_results() -> list[str]:\n with background_lock:\n ready = [bg_id for bg_id, task in background_tasks.items()\n if task[\"status\"] == \"completed\"]\n notifications = []\n for bg_id in ready:\n with background_lock:\n task = background_tasks.pop(bg_id)\n output = background_results.pop(bg_id, \"\")\n summary = output[:200] if len(output) > 200 else output\n notifications.append(\n f\"\\n\"\n f\" {bg_id}\\n\"\n f\" completed\\n\"\n f\" {task['command']}\\n\"\n f\" {summary}\\n\"\n f\"\")\n return notifications\n\n\n# ── Cron Scheduler ──\n\n# Cron jobs are stored separately from conversation history. When a job fires,\n# it becomes a scheduled prompt that is injected back into the same agent loop.\nDURABLE_PATH = WORKDIR / \".scheduled_tasks.json\"\n\n\n@dataclass\nclass CronJob:\n id: str\n cron: str\n prompt: str\n recurring: bool\n durable: bool\n\n\nscheduled_jobs: dict[str, CronJob] = {}\ncron_queue: list[CronJob] = []\ncron_lock = threading.Lock()\n_last_fired: dict[str, str] = {}\n\n\ndef _cron_field_matches(field: str, value: int) -> bool:\n if field == \"*\":\n return True\n if field.startswith(\"*/\"):\n step = int(field[2:])\n return step > 0 and value % step == 0\n if \",\" in field:\n return any(_cron_field_matches(part.strip(), value)\n for part in field.split(\",\"))\n if \"-\" in field:\n lo, hi = field.split(\"-\", 1)\n return int(lo) <= value <= int(hi)\n return value == int(field)\n\n\ndef cron_matches(cron_expr: str, dt: datetime) -> bool:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return False\n minute, hour, dom, month, dow = fields\n dow_val = (dt.weekday() + 1) % 7\n m = _cron_field_matches(minute, dt.minute)\n h = _cron_field_matches(hour, dt.hour)\n dom_ok = _cron_field_matches(dom, dt.day)\n month_ok = _cron_field_matches(month, dt.month)\n dow_ok = _cron_field_matches(dow, dow_val)\n if not (m and h and month_ok):\n return False\n if dom == \"*\" and dow == \"*\":\n return True\n if dom == \"*\":\n return dow_ok\n if dow == \"*\":\n return dom_ok\n return dom_ok or dow_ok\n\n\ndef _validate_cron_field(field: str, lo: int, hi: int) -> str | None:\n if field == \"*\":\n return None\n if field.startswith(\"*/\"):\n step = field[2:]\n if not step.isdigit() or int(step) <= 0:\n return f\"Invalid step: {field}\"\n return None\n if \",\" in field:\n for part in field.split(\",\"):\n err = _validate_cron_field(part.strip(), lo, hi)\n if err:\n return err\n return None\n if \"-\" in field:\n left, right = field.split(\"-\", 1)\n if not left.isdigit() or not right.isdigit():\n return f\"Invalid range: {field}\"\n a, b = int(left), int(right)\n if a < lo or a > hi or b < lo or b > hi:\n return f\"Range {field} out of bounds [{lo}-{hi}]\"\n if a > b:\n return f\"Range start > end: {field}\"\n return None\n if not field.isdigit():\n return f\"Invalid field: {field}\"\n value = int(field)\n if value < lo or value > hi:\n return f\"Value {value} out of bounds [{lo}-{hi}]\"\n return None\n\n\ndef validate_cron(cron_expr: str) -> str | None:\n fields = cron_expr.strip().split()\n if len(fields) != 5:\n return f\"Expected 5 fields, got {len(fields)}\"\n bounds = [(0, 59), (0, 23), (1, 31), (1, 12), (0, 6)]\n names = [\"minute\", \"hour\", \"day-of-month\", \"month\", \"day-of-week\"]\n for field, (lo, hi), name in zip(fields, bounds, names):\n err = _validate_cron_field(field, lo, hi)\n if err:\n return f\"{name}: {err}\"\n return None\n\n\ndef save_durable_jobs():\n durable = [asdict(job) for job in scheduled_jobs.values() if job.durable]\n DURABLE_PATH.write_text(json.dumps(durable, indent=2))\n\n\ndef load_durable_jobs():\n if not DURABLE_PATH.exists():\n return\n try:\n for item in json.loads(DURABLE_PATH.read_text()):\n job = CronJob(**item)\n if not validate_cron(job.cron):\n scheduled_jobs[job.id] = job\n except Exception:\n pass\n\n\ndef schedule_job(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> CronJob | str:\n err = validate_cron(cron)\n if err:\n return err\n job = CronJob(\n id=f\"cron_{random.randint(0, 999999):06d}\",\n cron=cron, prompt=prompt,\n recurring=recurring, durable=durable)\n with cron_lock:\n scheduled_jobs[job.id] = job\n if durable:\n save_durable_jobs()\n return job\n\n\ndef cancel_job(job_id: str) -> str:\n with cron_lock:\n job = scheduled_jobs.pop(job_id, None)\n if not job:\n return f\"Job {job_id} not found\"\n if job.durable:\n save_durable_jobs()\n return f\"Cancelled {job_id}\"\n\n\ndef cron_scheduler_loop():\n while True:\n time.sleep(1)\n now = datetime.now()\n marker = now.strftime(\"%Y-%m-%d %H:%M\")\n with cron_lock:\n for job in list(scheduled_jobs.values()):\n try:\n if cron_matches(job.cron, now) and _last_fired.get(job.id) != marker:\n cron_queue.append(job)\n _last_fired[job.id] = marker\n if not job.recurring:\n scheduled_jobs.pop(job.id, None)\n if job.durable:\n save_durable_jobs()\n except Exception as e:\n print(f\" \\033[31m[cron error] {job.id}: {e}\\033[0m\")\n\n\ndef consume_cron_queue() -> list[CronJob]:\n with cron_lock:\n fired = list(cron_queue)\n cron_queue.clear()\n return fired\n\n\ndef run_schedule_cron(cron: str, prompt: str,\n recurring: bool = True, durable: bool = True) -> str:\n result = schedule_job(cron, prompt, recurring, durable)\n if isinstance(result, str):\n return f\"Error: {result}\"\n return f\"Scheduled {result.id}: '{cron}' -> {prompt}\"\n\n\ndef run_list_crons() -> str:\n with cron_lock:\n jobs = list(scheduled_jobs.values())\n if not jobs:\n return \"No cron jobs.\"\n return \"\\n\".join(\n f\" {job.id}: '{job.cron}' -> {job.prompt[:40]} \"\n f\"[{'recurring' if job.recurring else 'one-shot'}, \"\n f\"{'durable' if job.durable else 'session'}]\"\n for job in jobs)\n\n\ndef run_cancel_cron(job_id: str) -> str:\n return cancel_job(job_id)\n\n\nload_durable_jobs()\nthreading.Thread(target=cron_scheduler_loop, daemon=True).start()\n\n\n# ── MCP System ──\n\n# MCP is modeled as late-bound tools: connect first, then discovered server\n# tools are merged into the normal tool pool with mcp__server__tool names.\nclass MCPClient:\n \"\"\"Discovers and calls tools on an in-process MCP server.\"\"\"\n\n def __init__(self, name: str):\n self.name = name\n self.tools: list[dict] = []\n self._handlers: dict[str, callable] = {}\n\n def register(self, tool_defs: list[dict],\n handlers: dict[str, callable]):\n self.tools = tool_defs\n self._handlers = handlers\n\n def call_tool(self, tool_name: str, args: dict) -> str:\n handler = self._handlers.get(tool_name)\n if not handler:\n return f\"MCP error: unknown tool '{tool_name}'\"\n try:\n return handler(**args)\n except Exception as e:\n return f\"MCP error: {e}\"\n\n\nmcp_clients: dict[str, MCPClient] = {}\n\n_DISALLOWED_CHARS = re.compile(r'[^a-zA-Z0-9_-]')\n\n\ndef normalize_mcp_name(name: str) -> str:\n \"\"\"Replace non [a-zA-Z0-9_-] with underscore.\"\"\"\n return _DISALLOWED_CHARS.sub('_', name)\n\n\ndef _mock_server_docs():\n client = MCPClient(\"docs\")\n client.register(\n tool_defs=[\n {\"name\": \"search\", \"description\": \"Search documentation. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"query\": {\"type\": \"string\"}},\n \"required\": [\"query\"]}},\n {\"name\": \"get_version\", \"description\": \"Get API version. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\", \"properties\": {},\n \"required\": []}},\n ],\n handlers={\n \"search\": lambda query: f\"[docs] Found 3 results for '{query}'\",\n \"get_version\": lambda: \"[docs] API v2.1.0\",\n })\n return client\n\n\ndef _mock_server_deploy():\n client = MCPClient(\"deploy\")\n client.register(\n tool_defs=[\n {\"name\": \"trigger\",\n \"description\": \"Trigger a deployment. (destructive; requires approval)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n {\"name\": \"status\", \"description\": \"Check deployment status. (readOnly)\",\n \"inputSchema\": {\"type\": \"object\",\n \"properties\": {\"service\": {\"type\": \"string\"}},\n \"required\": [\"service\"]}},\n ],\n handlers={\n \"trigger\": lambda service: f\"[deploy] Triggered: {service}\",\n \"status\": lambda service: f\"[deploy] {service}: running (v1.4.2)\",\n })\n return client\n\n\nMOCK_SERVERS = {\n \"docs\": _mock_server_docs,\n \"deploy\": _mock_server_deploy,\n}\n\n\ndef connect_mcp(name: str) -> str:\n if name in mcp_clients:\n return f\"MCP server '{name}' already connected\"\n factory = MOCK_SERVERS.get(name)\n if not factory:\n available = \", \".join(MOCK_SERVERS.keys())\n return f\"Unknown server '{name}'. Available: {available}\"\n mcp_client = factory()\n mcp_clients[name] = mcp_client\n tool_names = [t[\"name\"] for t in mcp_client.tools]\n print(f\" \\033[31m[mcp] connected: {name} → {tool_names}\\033[0m\")\n return (f\"Connected to MCP server '{name}'. \"\n f\"Discovered {len(mcp_client.tools)} tools: {', '.join(tool_names)}\")\n\n\ndef assemble_tool_pool() -> tuple[list[dict], dict]:\n \"\"\"Merge builtin tools + all MCP tools into one pool.\"\"\"\n tools = list(BUILTIN_TOOLS)\n handlers = dict(BUILTIN_HANDLERS)\n for server_name, mcp_client in mcp_clients.items():\n safe_server = normalize_mcp_name(server_name)\n for tool_def in mcp_client.tools:\n safe_tool = normalize_mcp_name(tool_def[\"name\"])\n prefixed = f\"mcp__{safe_server}__{safe_tool}\"\n tools.append({\n \"name\": prefixed,\n \"description\": tool_def.get(\"description\", \"\"),\n \"input_schema\": tool_def.get(\"inputSchema\", {}),\n })\n handlers[prefixed] = (\n lambda *, c=mcp_client, t=tool_def[\"name\"], **kw: c.call_tool(t, kw))\n return tools, handlers\n\n\n# ── Lead Worktree Tools ──\n\ndef run_create_worktree(name: str, task_id: str = \"\") -> str:\n return create_worktree(name, task_id)\n\ndef run_remove_worktree(name: str, discard_changes: bool = False) -> str:\n return remove_worktree(name, discard_changes)\n\ndef run_keep_worktree(name: str) -> str:\n return keep_worktree(name)\n\n\n# ── Basic tool handlers ──\n\ndef run_create_task(subject: str, description: str = \"\",\n blockedBy: list[str] | None = None) -> str:\n task = create_task(subject, description, blockedBy)\n deps = f\" (blockedBy: {', '.join(blockedBy)})\" if blockedBy else \"\"\n print(f\" \\033[34m[create] {task.subject}{deps}\\033[0m\")\n return f\"Created {task.id}: {task.subject}{deps}\"\n\n\ndef run_list_tasks() -> str:\n tasks = list_tasks()\n if not tasks:\n return \"No tasks.\"\n return \"\\n\".join(\n f\" {t.id}: {t.subject} [{t.status}]\"\n + (f\" (wt:{t.worktree})\" if t.worktree else \"\")\n for t in tasks)\n\n\ndef run_get_task(task_id: str) -> str:\n try:\n return get_task_json(task_id)\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n\ndef run_claim_task(task_id: str) -> str:\n try:\n return claim_task(task_id, owner=\"agent\")\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n\ndef run_complete_task(task_id: str) -> str:\n try:\n return complete_task(task_id)\n except FileNotFoundError:\n return f\"Error: task {task_id} not found\"\n\ndef run_spawn_teammate(name: str, role: str, prompt: str) -> str:\n return spawn_teammate_thread(name, role, prompt)\n\ndef run_send_message(to: str, content: str) -> str:\n if to not in active_teammates:\n return f\"Teammate '{to}' is not active\"\n BUS.send(\"lead\", to, content)\n return f\"Sent to {to}\"\n\ndef run_connect_mcp(name: str) -> str:\n return connect_mcp(name)\n\n\n# ── Tool Definitions ──\n\n# The model sees tool schemas; Python executes handlers. S19 keeps both tables\n# explicit so every added capability is visible in one place.\nBUILTIN_TOOLS = [\n {\"name\": \"bash\", \"description\": \"Run a shell command.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"command\": {\"type\": \"string\"},\n \"run_in_background\": {\"type\": \"boolean\"}},\n \"required\": [\"command\"]}},\n {\"name\": \"read_file\", \"description\": \"Read file contents.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"limit\": {\"type\": \"integer\"},\n \"offset\": {\"type\": \"integer\"}},\n \"required\": [\"path\"]}},\n {\"name\": \"write_file\", \"description\": \"Write content to a file.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"content\"]}},\n {\"name\": \"edit_file\", \"description\": \"Replace exact text in a file once.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"path\": {\"type\": \"string\"},\n \"old_text\": {\"type\": \"string\"},\n \"new_text\": {\"type\": \"string\"}},\n \"required\": [\"path\", \"old_text\", \"new_text\"]}},\n {\"name\": \"glob\", \"description\": \"Find files matching a glob pattern.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"pattern\": {\"type\": \"string\"}},\n \"required\": [\"pattern\"]}},\n {\"name\": \"todo_write\",\n \"description\": \"Create and manage a task list for the current session.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"todos\": {\"type\": \"array\",\n \"items\": {\"type\": \"object\",\n \"properties\": {\n \"content\": {\"type\": \"string\"},\n \"status\": {\"type\": \"string\",\n \"enum\": [\"pending\", \"in_progress\", \"completed\"]}},\n \"required\": [\"content\", \"status\"]}}},\n \"required\": [\"todos\"]}},\n {\"name\": \"task\",\n \"description\": \"Launch a focused subagent. Returns only its final summary.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"description\": {\"type\": \"string\"}},\n \"required\": [\"description\"]}},\n {\"name\": \"load_skill\",\n \"description\": \"Load the full content of a skill by name.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"compact\",\n \"description\": \"Summarize earlier conversation and continue with compacted context.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"focus\": {\"type\": \"string\"}},\n \"required\": []}},\n {\"name\": \"create_task\", \"description\": \"Create a task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"subject\": {\"type\": \"string\"},\n \"description\": {\"type\": \"string\"},\n \"blockedBy\": {\"type\": \"array\",\n \"items\": {\"type\": \"string\"}}},\n \"required\": [\"subject\"]}},\n {\"name\": \"list_tasks\", \"description\": \"List all tasks.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"get_task\", \"description\": \"Get full task details.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"claim_task\", \"description\": \"Claim a pending task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"complete_task\", \"description\": \"Complete an in-progress task.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"task_id\": {\"type\": \"string\"}},\n \"required\": [\"task_id\"]}},\n {\"name\": \"schedule_cron\",\n \"description\": (\"Schedule a cron job. cron is 5-field: min hour dom \"\n \"month dow. For one-shot reminders, compute the target \"\n \"minute and set recurring=false.\"),\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"cron\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"},\n \"recurring\": {\"type\": \"boolean\"},\n \"durable\": {\"type\": \"boolean\"}},\n \"required\": [\"cron\", \"prompt\"]}},\n {\"name\": \"list_crons\", \"description\": \"List registered cron jobs.\",\n \"input_schema\": {\"type\": \"object\", \"properties\": {}, \"required\": []}},\n {\"name\": \"cancel_cron\", \"description\": \"Cancel a cron job by ID.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"job_id\": {\"type\": \"string\"}},\n \"required\": [\"job_id\"]}},\n {\"name\": \"spawn_teammate\", \"description\": \"Spawn an autonomous teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Za-z0-9_-]{1,64}$\",\n },\n \"role\": {\"type\": \"string\"},\n \"prompt\": {\"type\": \"string\"}},\n \"required\": [\"name\", \"role\", \"prompt\"]}},\n {\"name\": \"send_message\", \"description\": \"Send message to a teammate.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"to\": {\"type\": \"string\"},\n \"content\": {\"type\": \"string\"}},\n \"required\": [\"to\", \"content\"]}},\n {\"name\": \"request_shutdown\",\n \"description\": \"Request a teammate to shut down.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"}},\n \"required\": [\"teammate\"]}},\n {\"name\": \"request_plan\",\n \"description\": \"Ask a teammate to submit a plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"teammate\": {\"type\": \"string\"},\n \"task\": {\"type\": \"string\"}},\n \"required\": [\"teammate\", \"task\"]}},\n {\"name\": \"review_plan\",\n \"description\": \"Approve or reject a submitted plan.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"request_id\": {\"type\": \"string\"},\n \"approve\": {\"type\": \"boolean\"},\n \"feedback\": {\"type\": \"string\"}},\n \"required\": [\"request_id\", \"approve\"]}},\n {\"name\": \"create_worktree\",\n \"description\": \"Create an isolated git worktree.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"task_id\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"remove_worktree\",\n \"description\": \"Remove a worktree. Refuses if changes exist.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"},\n \"discard_changes\": {\"type\": \"boolean\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"keep_worktree\",\n \"description\": \"Keep a worktree for manual review.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n {\"name\": \"connect_mcp\",\n \"description\": \"Connect to an MCP server (docs, deploy) and discover tools.\",\n \"input_schema\": {\"type\": \"object\",\n \"properties\": {\"name\": {\"type\": \"string\"}},\n \"required\": [\"name\"]}},\n]\n\nBUILTIN_HANDLERS = {\n \"bash\": run_bash, \"read_file\": run_read, \"write_file\": run_write,\n \"edit_file\": run_edit, \"glob\": run_glob,\n \"todo_write\": run_todo_write, \"task\": spawn_subagent,\n \"load_skill\": load_skill,\n \"create_task\": run_create_task, \"list_tasks\": run_list_tasks,\n \"get_task\": run_get_task,\n \"claim_task\": run_claim_task, \"complete_task\": run_complete_task,\n \"schedule_cron\": run_schedule_cron,\n \"list_crons\": run_list_crons,\n \"cancel_cron\": run_cancel_cron,\n \"spawn_teammate\": run_spawn_teammate,\n \"send_message\": run_send_message,\n \"request_shutdown\": run_request_shutdown,\n \"request_plan\": run_request_plan, \"review_plan\": run_review_plan,\n \"create_worktree\": run_create_worktree,\n \"remove_worktree\": run_remove_worktree,\n \"keep_worktree\": run_keep_worktree,\n \"connect_mcp\": run_connect_mcp,\n}\n\n\n# ── Context ──\n\nMEMORY_DIR = WORKDIR / \".memory\"\nMEMORY_INDEX = MEMORY_DIR / \"MEMORY.md\"\n\n\ndef update_context(context: dict, messages: list) -> dict:\n memories = \"\"\n if MEMORY_INDEX.exists():\n memories = MEMORY_INDEX.read_text()[:2000]\n return {\n \"memories\": memories,\n \"connected_mcp\": list(mcp_clients.keys()),\n \"active_teammates\": list(active_teammates.keys()),\n }\n\n\n# ── Agent Loop ──\n\nrounds_since_todo = 0\nagent_lock = threading.Lock()\n\n\ndef prepare_context(messages: list) -> list:\n # Every LLM turn enters through the same context budget pipeline.\n messages[:] = tool_result_budget(messages)\n messages[:] = snip_compact(messages)\n messages[:] = micro_compact(messages)\n if estimate_size(messages) > CONTEXT_LIMIT:\n messages[:] = compact_history(messages)\n return messages\n\n\ndef build_user_content(results: list[dict]) -> list[dict]:\n # Tool results and completed background notifications are both returned to\n # the model as user-side content, matching the tool_result feedback loop.\n content = list(results)\n for note in collect_background_results():\n content.append({\"type\": \"text\", \"text\": note})\n return content\n\n\ndef inject_background_notifications(messages: list):\n notes = collect_background_results()\n if notes:\n messages.append({\"role\": \"user\", \"content\": [\n {\"type\": \"text\", \"text\": note} for note in notes]})\n\n\ndef call_llm(messages: list, context: dict, tools: list,\n state: RecoveryState, max_tokens: int):\n system = assemble_system_prompt(context)\n return with_retry(\n lambda: client.messages.create(\n model=state.current_model,\n system=system,\n messages=messages,\n tools=tools,\n max_tokens=max_tokens),\n state)\n\n\ndef agent_loop(messages: list, context: dict):\n global rounds_since_todo\n tools, handlers = assemble_tool_pool()\n state = RecoveryState()\n max_tokens = DEFAULT_MAX_TOKENS\n\n while True:\n # One cycle: inject scheduled/background work, prepare context, call\n # the model, execute tool_use blocks, append tool_results, repeat.\n fired = consume_cron_queue()\n for job in fired:\n messages.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n print(f\" \\033[35m[cron inject] {job.prompt[:60]}\\033[0m\")\n\n inject_background_notifications(messages)\n\n if rounds_since_todo >= 3:\n messages.append({\"role\": \"user\",\n \"content\": \"Update your todos.\"})\n rounds_since_todo = 0\n\n prepare_context(messages)\n context = update_context(context, messages)\n tools, handlers = assemble_tool_pool()\n\n try:\n response = call_llm(messages, context, tools, state, max_tokens)\n except Exception as e:\n if is_prompt_too_long_error(e) and not state.has_attempted_reactive_compact:\n messages[:] = reactive_compact(messages)\n state.has_attempted_reactive_compact = True\n continue\n messages.append({\"role\": \"assistant\", \"content\": [\n {\"type\": \"text\", \"text\": f\"[Error] {type(e).__name__}: {e}\"}]})\n return\n\n if response.stop_reason == \"max_tokens\":\n if not state.has_escalated:\n max_tokens = ESCALATED_MAX_TOKENS\n state.has_escalated = True\n print(f\" \\033[33m[max_tokens] retry with {max_tokens}\\033[0m\")\n continue\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if state.recovery_count < MAX_RECOVERY_RETRIES:\n messages.append({\"role\": \"user\", \"content\": CONTINUATION_PROMPT})\n state.recovery_count += 1\n continue\n return\n\n max_tokens = DEFAULT_MAX_TOKENS\n state.has_escalated = False\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n if not has_tool_use(response.content):\n trigger_hooks(\"Stop\", messages)\n return\n\n results = []\n compacted_now = False\n for block in response.content:\n if block.type != \"tool_use\":\n continue\n print(f\"\\033[36m> {block.name}\\033[0m\")\n\n if block.name == \"compact\":\n messages[:] = compact_history(messages)\n messages.append({\"role\": \"user\",\n \"content\": \"[Compacted. Continue with summarized context.]\"})\n compacted_now = True\n break\n\n blocked = trigger_hooks(\"PreToolUse\", block)\n if blocked:\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": str(blocked)})\n continue\n\n if should_run_background(block.name, block.input):\n bg_id = start_background_task(block, handlers)\n output = (f\"[Background task {bg_id} started] \"\n \"Result will arrive as a task_notification.\")\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id,\n \"content\": output})\n continue\n\n handler = handlers.get(block.name)\n output = call_tool_handler(handler, block.input, block.name)\n trigger_hooks(\"PostToolUse\", block, output)\n print(str(output)[:300])\n\n if block.name == \"todo_write\":\n rounds_since_todo = 0\n else:\n rounds_since_todo += 1\n\n results.append({\"type\": \"tool_result\",\n \"tool_use_id\": block.id, \"content\": output})\n\n if compacted_now:\n continue\n\n messages.append({\"role\": \"user\", \"content\": build_user_content(results)})\n\n\ndef print_turn_assistants(messages: list, turn_start: int):\n for msg in messages[turn_start:]:\n if msg.get(\"role\") != \"assistant\":\n continue\n for block in msg.get(\"content\", []):\n if block_type(block) == \"text\":\n terminal_print(block[\"text\"] if isinstance(block, dict) else block.text)\n\n\ndef async_event_loop(history: list, context: dict):\n while True:\n time.sleep(1)\n with agent_lock:\n fired = consume_cron_queue()\n inbox = consume_lead_inbox(route_protocol=True)\n if not fired and not inbox:\n continue\n turn_start = len(history)\n for job in fired:\n history.append({\"role\": \"user\",\n \"content\": f\"[Scheduled] {job.prompt}\"})\n terminal_print(\n f\" \\033[35m[cron auto] {job.prompt[:60]}\\033[0m\")\n if inbox:\n history.append({\"role\": \"user\",\n \"content\": format_team_events(inbox)})\n terminal_print(\n f\" \\033[33m[team auto] {len(inbox)} events\\033[0m\")\n agent_loop(history, context)\n context.update(update_context(context, history))\n print_turn_assistants(history, turn_start)\n\n\nif __name__ == \"__main__\":\n CLI_ACTIVE = True\n print(\"s19: comprehensive agent\")\n print(\"Enter a question, press Enter to send. Type q to quit.\\n\")\n history = []\n context = update_context({}, [])\n threading.Thread(target=async_event_loop,\n args=(history, context), daemon=True).start()\n while True:\n try:\n query = input(PROMPT)\n except (EOFError, KeyboardInterrupt):\n break\n if query.strip().lower() in (\"q\", \"exit\", \"\"):\n break\n trigger_hooks(\"UserPromptSubmit\", query)\n turn_start = len(history)\n history.append({\"role\": \"user\", \"content\": query})\n with agent_lock:\n agent_loop(history, context)\n context = update_context(context, history)\n print_turn_assistants(history, turn_start)\n print()\n", "images": [ { - "src": "/course-assets/s20_comprehensive/system-architecture.svg", + "src": "/course-assets/s19_comprehensive/system-architecture.svg", "alt": "system architecture" } ] }, { - "id": "s21", - "filename": "s21_workflow_runtime/code.py", + "id": "s20", + "filename": "s20_workflow_runtime/code.py", "title": "Workflow Runtime", "subtitle": "Scripts Own Fixed Orchestration", - "loc": 423, + "loc": 419, "tools": [ "review-changes" ], @@ -3679,114 +3710,114 @@ "classes": [ { "name": "WorkflowInputError", - "startLine": 65, - "endLine": 71 + "startLine": 63, + "endLine": 69 }, { "name": "SimpleJsonSchema", - "startLine": 104, - "endLine": 145 + "startLine": 101, + "endLine": 142 }, { "name": "MockAgentRunner", - "startLine": 164, - "endLine": 194 + "startLine": 161, + "endLine": 189 }, { "name": "WorkflowJournal", - "startLine": 195, - "endLine": 245 + "startLine": 190, + "endLine": 240 }, { "name": "Budget", - "startLine": 246, - "endLine": 270 + "startLine": 241, + "endLine": 265 }, { "name": "LocalWorkflowTask", - "startLine": 271, - "endLine": 295 + "startLine": 266, + "endLine": 290 }, { "name": "ExecutionLimits", - "startLine": 296, - "endLine": 308 + "startLine": 291, + "endLine": 303 }, { "name": "ExecutionState", - "startLine": 309, - "endLine": 408 + "startLine": 304, + "endLine": 403 }, { "name": "WorkflowTool", - "startLine": 409, - "endLine": 457 + "startLine": 404, + "endLine": 452 } ], "functions": [ { "name": "_stable_hash", "signature": "def _stable_hash(s: str)", - "startLine": 40 + "startLine": 39 }, { "name": "create_run_id", "signature": "def create_run_id(meta)", - "startLine": 46 + "startLine": 45 }, { "name": "create_task_id", "signature": "def create_task_id(run_id)", - "startLine": 52 + "startLine": 50 }, { "name": "validate_run_id", "signature": "def validate_run_id(run_id)", - "startLine": 56 + "startLine": 54 }, { "name": "validate_meta", "signature": "def validate_meta(meta)", - "startLine": 72 + "startLine": 70 }, { "name": "check_permission", "signature": "def check_permission(meta, settings=None)", - "startLine": 92 + "startLine": 90 }, { "name": "_fill_schema", "signature": "def _fill_schema(schema, seed)", - "startLine": 146 + "startLine": 143 }, { "name": "_write_json", "signature": "def _write_json(path, value)", - "startLine": 458 + "startLine": 453 }, { "name": "_save_last_run", "signature": "def _save_last_run(run_id)", - "startLine": 463 + "startLine": 458 }, { "name": "_read_last_run", "signature": "def _read_last_run()", - "startLine": 467 + "startLine": 462 } ], "layer": "concurrency", - "source": "\"\"\"\ns21_workflow_runtime — minimal dynamic Workflow runtime for a teaching harness\n\nIdea:\n s01-s20 build a single, model-driven agent loop. s21 adds a deterministic\n orchestration LAYER on top: the main loop exposes a `Workflow` tool that\n launches a background runtime; a script written with agent()/parallel()/\n pipeline()/phase() drives many subagents deterministically, reports progress,\n persists a journal, and can resume from a runId.\n\nRun:\n python code.py # run the sample workflow, print the event stream\n python code.py resume # resume the last run; unchanged agent() calls hit cache\n\nImplementation choices:\n - The \"subagent\" is a deterministic MockAgentRunner, not a real LLM.\n - A workflow is a plain async Python function. A production harness may use a\n declarative format or run user-authored scripts in an isolated VM.\n - The CLI emits `async_launched` and then awaits completion so the demo stays\n deterministic. A long-running host can return while execution continues.\n - Storage is a local .runtime/ directory beside this file.\n\"\"\"\n\nimport asyncio\nimport hashlib\nimport json\nimport re\nimport sys\nfrom pathlib import Path\n\n# ---- runtime guards ----\nAGENT_CAP = 1000 # hard cap on agent() calls per run\nCONCURRENCY = 8 # parallelism cap (semaphore)\nSTORE = Path(__file__).parent / \".runtime\" # snapshots + journals live here\nMISS = object() # journal cache miss sentinel\nWORKFLOW_NAME_RE = re.compile(r\"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\")\nRUN_ID_RE = re.compile(r\"^wf_[A-Za-z0-9][A-Za-z0-9._-]{0,63}_[0-9]{4}$\")\n\n\ndef _stable_hash(s: str) -> int:\n \"\"\"Process-stable hash (Python's hash() is salted per process, which would\n break resume keys across `run` and `resume`).\"\"\"\n return int(hashlib.sha256(s.encode()).hexdigest(), 16)\n\n\ndef create_run_id(meta) -> str:\n # Deterministic in the teaching version so the journal path is predictable\n # and `resume` lands on the same file.\n return f\"wf_{meta['name']}_{_stable_hash(meta['name']) % 10000:04d}\"\n\n\ndef create_task_id(run_id) -> str:\n return f\"local_workflow_{run_id}\"\n\n\ndef validate_run_id(run_id):\n if not isinstance(run_id, str) or not RUN_ID_RE.fullmatch(run_id):\n raise WorkflowInputError(\"invalid workflow runId\")\n return run_id\n\n\n# ============================================================\n# Errors\n# ============================================================\nclass WorkflowInputError(Exception):\n \"\"\"Bad workflow, metadata, or schema input.\"\"\"\n\n\n# ============================================================\n# meta validation\n# ============================================================\ndef validate_meta(meta):\n \"\"\"Validate name, description, and optional phases before launch.\"\"\"\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta must be an object literal\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta requires `name` and `description`\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\n \"meta.name must be a 1-64 character slug using letters, numbers, '.', '_', or '-'\"\n )\n if not isinstance(meta[\"description\"], str):\n raise WorkflowInputError(\"meta.description must be a string\")\n if \"phases\" in meta:\n if not isinstance(meta[\"phases\"], list) or not all(\n isinstance(phase, str) and phase for phase in meta[\"phases\"]\n ):\n raise WorkflowInputError(\"meta.phases must be a list of non-empty strings\")\n return meta\n\n\ndef check_permission(meta, settings=None):\n \"\"\"allow / deny / ask gate before launch (s03 permission system, applied to\n Workflow). Teaching version allows by default; a deny rule blocks.\"\"\"\n settings = settings or {}\n if meta[\"name\"] in settings.get(\"deny\", []):\n raise WorkflowInputError(f\"workflow '{meta['name']}' denied by settings\")\n return \"allow\"\n\n\n# ============================================================\n# Minimal JSON-schema for structured output (SimpleJsonSchema)\n# ============================================================\nclass SimpleJsonSchema:\n \"\"\"Tiny validator backing agent({schema}). Just enough for teaching:\n object/array/string/boolean/number + required keys.\"\"\"\n\n def __init__(self, schema):\n self.schema = schema\n\n def validate(self, value, schema=None):\n schema = self.schema if schema is None else schema\n t = schema.get(\"type\")\n if t == \"object\":\n if not isinstance(value, dict):\n return False, \"expected object\"\n for key in schema.get(\"required\", []):\n if key not in value:\n return False, f\"missing required key '{key}'\"\n for key, sub in schema.get(\"properties\", {}).items():\n if key in value:\n ok, err = self.validate(value[key], sub)\n if not ok:\n return False, f\"{key}: {err}\"\n return True, None\n if t == \"array\":\n if not isinstance(value, list):\n return False, \"expected array\"\n items = schema.get(\"items\")\n if items:\n for i, el in enumerate(value):\n ok, err = self.validate(el, items)\n if not ok:\n return False, f\"[{i}]: {err}\"\n return True, None\n if t == \"string\":\n return (isinstance(value, str), None if isinstance(value, str) else \"expected string\")\n if t == \"boolean\":\n return (isinstance(value, bool), None if isinstance(value, bool) else \"expected boolean\")\n if t in (\"number\", \"integer\"):\n ok = isinstance(value, (int, float)) and not isinstance(value, bool)\n return (ok, None if ok else \"expected number\")\n return True, None\n\n\ndef _fill_schema(schema, seed):\n \"\"\"Deterministic generic filler used for schemas the mock doesn't special-case.\"\"\"\n t = schema.get(\"type\")\n if t == \"object\":\n keys = schema.get(\"required\") or list(schema.get(\"properties\", {}))\n return {k: _fill_schema(schema[\"properties\"][k], f\"{seed}/{k}\") for k in keys}\n if t == \"array\":\n return [_fill_schema(schema[\"items\"], f\"{seed}/0\")]\n if t == \"boolean\":\n return _stable_hash(seed) % 4 != 0\n if t in (\"number\", \"integer\"):\n return _stable_hash(seed) % 5\n return seed.rsplit(\"/\", 1)[-1]\n\n\n# ============================================================\n# Subagent runner (mock for teaching; real path = an LLM tool loop)\n# ============================================================\nclass MockAgentRunner:\n \"\"\"Stands in for a spawned subagent. Deterministic so resume is reproducible.\n A real runner would run an isolated agent loop that calls repo tools and is\n forced to emit StructuredOutput when a schema is present.\"\"\"\n\n def run(self, prompt, schema=None, label=None):\n if schema is None:\n return f\"[mock] {(label or prompt)[:60]}\"\n props = schema.get(\"properties\", {})\n if \"findings\" in props: # an audit agent\n n = 1 + (_stable_hash(prompt) % 2) # 1-2 findings\n sev = [\"high\", \"medium\", \"low\"]\n return {\"findings\": [\n {\"title\": f\"{label or 'audit'} #{i + 1}\",\n \"severity\": sev[_stable_hash(prompt + str(i)) % 3]}\n for i in range(n)\n ]}\n if \"isReal\" in props: # a verifier agent\n real = _stable_hash(prompt) % 4 != 0 # ~75% confirmed\n return {\"isReal\": real,\n \"reason\": \"reproduced\" if real else \"could not reproduce\"}\n return _fill_schema(schema, prompt)\n\n @staticmethod\n def tokens(prompt, result):\n return len(prompt) // 4 + len(json.dumps(result, default=str)) // 4\n\n\n# ============================================================\n# Journal (resume cache): started/result per agent under a semantic key\n# ============================================================\nclass WorkflowJournal:\n \"\"\"Append-only .journal.jsonl. On resume, agent() calls whose\n semantic key is already present are replayed from cache instead of re-run.\"\"\"\n\n def __init__(self, run_id, resume, store=STORE):\n store.mkdir(parents=True, exist_ok=True)\n self.path = store / f\"{run_id}.journal.jsonl\"\n self.resume = resume\n self.cache = {}\n if resume:\n if not self.path.exists():\n raise WorkflowInputError(f\"resume journal not found for {run_id}\")\n for line_number, line in enumerate(self.path.read_text().splitlines(), start=1):\n try:\n rec = json.loads(line)\n if (\n not isinstance(rec, dict)\n or not isinstance(rec.get(\"key\"), str)\n or \"value\" not in rec\n ):\n raise ValueError(\"expected key/value record\")\n except (json.JSONDecodeError, ValueError) as exc:\n raise WorkflowInputError(\n f\"invalid resume journal record at line {line_number}\"\n ) from exc\n self.cache[rec[\"key\"]] = rec[\"value\"]\n self._f = self.path.open(\"a\")\n else:\n self._f = self.path.open(\"w\") # fresh run truncates\n\n def key(self, kind, label, prompt, schema):\n # Deterministic semantic key — independent of concurrency order, so a\n # parallel/pipeline call gets the same key on resume.\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n def cached(self, key):\n return self.cache.get(key, MISS)\n\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n\n def close(self):\n self._f.close()\n\n\n# ============================================================\n# Token budget\n# ============================================================\nclass Budget:\n \"\"\"budget.total / spent() / remaining(). Once spent reaches total, agent()\n calls raise instead of silently overspending.\"\"\"\n\n def __init__(self, total=None):\n self.total = total\n self._spent = 0\n\n def add(self, n):\n if self.total is not None and self._spent + n > self.total:\n raise WorkflowInputError(\n f\"token budget exceeded ({self._spent + n} > {self.total})\"\n )\n self._spent += n\n\n def spent(self):\n return self._spent\n\n def remaining(self):\n return float(\"inf\") if self.total is None else max(0, self.total - self._spent)\n\n\n# ============================================================\n# Background task state + progress events (the outer event stream)\n# ============================================================\nclass LocalWorkflowTask:\n \"\"\"type local_workflow. Holds status/usage and emits the SDK-like event\n stream: task_started, task_progress (workflow_phase/agent/log), task_notification.\"\"\"\n\n def __init__(self, task_id, run_id, meta):\n self.task_id = task_id\n self.run_id = run_id\n self.meta = meta\n self.status = \"running\"\n self.usage = {\"agents\": 0, \"tokens\": 0}\n self.progress = []\n\n def event(self, name, **data):\n line = \" \".join(f\"{k}={v}\" for k, v in data.items())\n print(f\" event {name:<18} {line}\")\n\n def progress_event(self, ptype, **data):\n self.progress.append({\"type\": ptype, **data})\n line = \" \".join(f\"{k}={v}\" for k, v in data.items())\n print(f\" progress {ptype:<16} {line}\")\n\n\n# ============================================================\n# ExecutionState: the DSL the workflow script sees as `ctx`\n# ============================================================\nclass ExecutionLimits:\n \"\"\"Shared run-wide limits, including nested workflows.\"\"\"\n\n def __init__(self):\n self.agents = 0\n self.semaphore = asyncio.Semaphore(CONCURRENCY)\n\n def claim_agent(self):\n self.agents += 1\n if self.agents > AGENT_CAP:\n raise WorkflowInputError(f\"agent() cap reached ({AGENT_CAP})\")\n\n\nclass ExecutionState:\n \"\"\"Injected into the workflow script with the orchestration primitives.\"\"\"\n\n def __init__(self, task, journal, runner, budget, args, depth=0, limits=None):\n self.task = task\n self.journal = journal\n self.runner = runner\n self.budget = budget\n self.args = args\n self._depth = depth\n self._phase = None\n self._phases_seen = set()\n self._limits = limits or ExecutionLimits()\n\n def phase(self, title):\n \"\"\"Start a phase; subsequent agent()s group under it. Upsert: emitting the\n same phase again (e.g. from each pipeline item) does not re-announce it.\"\"\"\n self._phase = title\n if title not in self._phases_seen:\n self._phases_seen.add(title)\n self.task.progress_event(\"workflow_phase\", title=title)\n\n def log(self, message):\n \"\"\"Emit a workflow_log progress line.\"\"\"\n self.task.progress_event(\"workflow_log\", message=message)\n\n async def agent(self, prompt, schema=None, label=None, phase=None):\n \"\"\"Spawn one subagent. With a schema, force StructuredOutput + validate\n (retry once). On resume, a cached key short-circuits the run.\"\"\"\n label = label or (prompt[:24] + \"…\")\n self._limits.claim_agent()\n if self.budget.remaining() <= 0:\n raise WorkflowInputError(\"token budget exceeded\")\n\n key = self.journal.key(\"agent\", label, prompt, schema)\n cached = self.journal.cached(key)\n if cached is not MISS:\n if schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(cached)\n if not ok:\n raise WorkflowInputError(\n f\"cached agent output failed schema validation: {err}\"\n )\n self.task.progress_event(\"workflow_agent\", label=label,\n phase=phase or self._phase, status=\"cached\")\n return cached\n\n async with self._limits.semaphore:\n await asyncio.sleep(0) # yield: real subagents are async\n result = self.runner.run(prompt, schema, label)\n\n if schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # one nudge/retry, then fail\n result = self.runner.run(prompt + \"\\n\\nReturn valid JSON.\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) invalid output: {err}\")\n\n toks = self.runner.tokens(prompt, result)\n self.budget.add(toks)\n self.task.usage[\"agents\"] += 1\n self.task.usage[\"tokens\"] += toks\n self.journal.record(key, result)\n self.task.progress_event(\"workflow_agent\", label=label,\n phase=phase or self._phase, status=\"done\")\n return result\n\n async def parallel(self, thunks):\n \"\"\"BARRIER: run all thunks concurrently and fail if any thunk fails.\"\"\"\n return await asyncio.gather(*[thunk() for thunk in thunks])\n\n async def pipeline(self, items, *stages):\n \"\"\"Per-item staged flow, NO barrier between stages: item A can be in\n stage 3 while item B is still in stage 1. Each stage gets\n (prev_result, original_item, index). A throwing stage fails the workflow.\"\"\"\n async def run_item(item, idx):\n value = item\n for stage in stages:\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n\n async def workflow(self, name, args=None):\n \"\"\"Run a saved workflow inline as a child (one level), sharing this run's\n journal + budget + agent counter.\"\"\"\n if self._depth >= 1:\n raise WorkflowInputError(\"workflow() nesting is one level only\")\n if name not in WORKFLOWS:\n raise WorkflowInputError(f\"unknown workflow '{name}'\")\n meta, fn = WORKFLOWS[name]\n child = ExecutionState(self.task, self.journal, self.runner, self.budget,\n args or {}, depth=self._depth + 1,\n limits=self._limits)\n return await fn(child, args or {})\n\n\n# ============================================================\n# WorkflowTool: the tool entry (WorkflowTool.call)\n# ============================================================\nclass WorkflowTool:\n \"\"\"The Workflow tool. .call() validates meta, runs the permission check,\n creates runId/taskId, registers a LocalWorkflowTask, and emits lifecycle\n events while this teaching CLI awaits the final result. Supports resume.\"\"\"\n\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n args = args or {}\n run_id = resume_from_run_id or create_run_id(meta)\n validate_run_id(run_id)\n if resume_from_run_id is not None and run_id != create_run_id(meta):\n raise WorkflowInputError(\"resume runId does not match workflow meta\")\n task_id = create_task_id(run_id)\n resuming = resume_from_run_id is not None\n\n task = LocalWorkflowTask(task_id, run_id, meta)\n # The real tool returns this immediately and runs the rest in background.\n launched = {\"status\": \"async_launched\", \"taskId\": task_id,\n \"taskType\": \"local_workflow\", \"runId\": run_id,\n \"workflowName\": meta[\"name\"]}\n task.event(\"async_launched\", runId=run_id, taskId=task_id)\n task.event(\"task_started\", workflow=meta[\"name\"],\n phases=\",\".join(meta.get(\"phases\", [])) or \"-\",\n resume=resuming)\n\n journal = None\n try:\n journal = WorkflowJournal(run_id, resume=resuming)\n ctx = ExecutionState(\n task, journal, MockAgentRunner(), Budget(args.get(\"budget\")), args\n )\n result = await script_fn(ctx, args)\n task.status = \"completed\"\n except Exception as e: # failed / stopped close the loop too\n task.status = \"failed\"\n result = {\"error\": str(e)}\n finally:\n if journal is not None:\n journal.close()\n\n _write_json(STORE / f\"{run_id}.output.json\", result)\n _save_last_run(run_id)\n task.event(\"task_notification\", status=task.status,\n agents=task.usage[\"agents\"], tokens=task.usage[\"tokens\"],\n outputFile=f\".runtime/{run_id}.output.json\")\n return {\"launched\": launched, \"result\": result, \"task\": task}\n\n\ndef _write_json(path, value):\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(json.dumps(value, indent=2, default=str))\n\n\ndef _save_last_run(run_id):\n (STORE / \"last_run.txt\").write_text(run_id)\n\n\ndef _read_last_run():\n p = STORE / \"last_run.txt\"\n return p.read_text().strip() if p.exists() else None\n\n\n# ============================================================\n# Sample workflow: review changed code across dimensions, verify each finding.\n# ============================================================\nFINDINGS_SCHEMA = {\n \"type\": \"object\", \"required\": [\"findings\"],\n \"properties\": {\"findings\": {\"type\": \"array\", \"items\": {\n \"type\": \"object\", \"required\": [\"title\", \"severity\"],\n \"properties\": {\"title\": {\"type\": \"string\"}, \"severity\": {\"type\": \"string\"}}}}},\n}\nVERDICT_SCHEMA = {\n \"type\": \"object\", \"required\": [\"isReal\", \"reason\"],\n \"properties\": {\"isReal\": {\"type\": \"boolean\"}, \"reason\": {\"type\": \"string\"}},\n}\n\nSAMPLE_META = {\n \"name\": \"review-changes\",\n \"description\": \"Review changed files across dimensions, verify each finding\",\n \"phases\": [\"Review\", \"Verify\"],\n}\n\nDIMENSIONS = [\"correctness\", \"security\", \"performance\", \"style\"]\n\n\nasync def sample_workflow(ctx, args):\n \"\"\"pipeline over review dimensions (audit -> verify-each), then keep only the\n findings a verifier confirms. The plan is code, not a chat turn.\"\"\"\n ctx.phase(\"Review\")\n\n async def audit(_value, dimension, _idx):\n out = await ctx.agent(\n f\"Review the changed files for {dimension} issues.\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _idx):\n ctx.phase(\"Verify\")\n # Each finding is verified by its own adversarial subagent, concurrently.\n verdicts = await ctx.parallel([\n (lambda f=f: ctx.agent(\n f\"Adversarially verify this {dimension} finding — is it real? {f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\", phase=\"Verify\"))\n for f in audited[\"findings\"]])\n confirmed = [f for f, v in zip(audited[\"findings\"], verdicts)\n if v and v.get(\"isReal\")]\n return {\"dimension\": dimension, \"confirmed\": confirmed}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n confirmed = [{\"dimension\": r[\"dimension\"], **f}\n for r in results if r for f in r[\"confirmed\"]]\n confirmed.sort(key=lambda f: {\"high\": 0, \"medium\": 1, \"low\": 2}.get(f[\"severity\"], 3))\n ctx.log(f\"confirmed {len(confirmed)} real finding(s)\")\n return {\"confirmed\": confirmed}\n\n\n# Saved workflow registry\nWORKFLOWS = {SAMPLE_META[\"name\"]: (SAMPLE_META, sample_workflow)}\n\n\n# ============================================================\n# Demo\n# ============================================================\nasync def main(argv):\n resume_id = None\n if argv and argv[0] == \"resume\":\n resume_id = _read_last_run()\n if not resume_id:\n print(\"nothing to resume — run `python code.py` first.\")\n return\n print(f\"resuming {resume_id} — unchanged agent() calls hit the journal cache\\n\")\n else:\n print(\"launching workflow `review-changes`\\n\")\n\n tool = WorkflowTool()\n out = await tool.call(SAMPLE_META, sample_workflow,\n args={\"budget\": None}, resume_from_run_id=resume_id)\n\n print(\"\\nresult:\")\n for f in out[\"result\"].get(\"confirmed\", []):\n print(f\" [{f['severity']:<6}] {f['dimension']}: {f['title']}\")\n t = out[\"task\"]\n print(f\"\\nstatus={t.status} agents={t.usage['agents']} tokens={t.usage['tokens']}\"\n f\" journal=.runtime/{t.run_id}.journal.jsonl\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main(sys.argv[1:]))\n", + "source": "\"\"\"\ns20_workflow_runtime — minimal dynamic Workflow runtime\n\nIdea:\n s01-s19 build a single, model-driven agent loop. s20 adds a deterministic\n orchestration LAYER on top: the main loop exposes a `Workflow` tool that\n launches a background runtime; a script written with agent()/parallel()/\n pipeline()/phase() drives many subagents deterministically, reports progress,\n persists a journal, and can resume from a runId.\n\nRun:\n python code.py # run the sample workflow, print the event stream\n python code.py resume # resume the last run; unchanged agent() calls hit cache\n\nImplementation choices:\n - MockAgentRunner is deterministic so resume behavior is reproducible.\n - A workflow is a plain async Python function.\n - The CLI emits `async_launched` and then awaits completion so event order is\n deterministic.\n - Storage is a local .runtime/ directory beside this file.\n\"\"\"\n\nimport asyncio\nimport hashlib\nimport json\nimport re\nimport sys\nfrom pathlib import Path\n\n# ---- runtime guards ----\nAGENT_CAP = 1000 # hard cap on agent() calls per run\nCONCURRENCY = 8 # parallelism cap (semaphore)\nSTORE = Path(__file__).parent / \".runtime\" # snapshots + journals live here\nMISS = object() # journal cache miss sentinel\nWORKFLOW_NAME_RE = re.compile(r\"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$\")\nRUN_ID_RE = re.compile(r\"^wf_[A-Za-z0-9][A-Za-z0-9._-]{0,63}_[0-9]{4}$\")\n\n\ndef _stable_hash(s: str) -> int:\n \"\"\"Process-stable hash (Python's hash() is salted per process, which would\n break resume keys across `run` and `resume`).\"\"\"\n return int(hashlib.sha256(s.encode()).hexdigest(), 16)\n\n\ndef create_run_id(meta) -> str:\n # Keep the ID deterministic so `resume` lands on the same journal file.\n return f\"wf_{meta['name']}_{_stable_hash(meta['name']) % 10000:04d}\"\n\n\ndef create_task_id(run_id) -> str:\n return f\"local_workflow_{run_id}\"\n\n\ndef validate_run_id(run_id):\n if not isinstance(run_id, str) or not RUN_ID_RE.fullmatch(run_id):\n raise WorkflowInputError(\"invalid workflow runId\")\n return run_id\n\n\n# ============================================================\n# Errors\n# ============================================================\nclass WorkflowInputError(Exception):\n \"\"\"Bad workflow, metadata, or schema input.\"\"\"\n\n\n# ============================================================\n# meta validation\n# ============================================================\ndef validate_meta(meta):\n \"\"\"Validate name, description, and optional phases before launch.\"\"\"\n if not isinstance(meta, dict):\n raise WorkflowInputError(\"meta must be an object literal\")\n if not meta.get(\"name\") or not meta.get(\"description\"):\n raise WorkflowInputError(\"meta requires `name` and `description`\")\n if not isinstance(meta[\"name\"], str) or not WORKFLOW_NAME_RE.fullmatch(meta[\"name\"]):\n raise WorkflowInputError(\n \"meta.name must be a 1-64 character slug using letters, numbers, '.', '_', or '-'\"\n )\n if not isinstance(meta[\"description\"], str):\n raise WorkflowInputError(\"meta.description must be a string\")\n if \"phases\" in meta:\n if not isinstance(meta[\"phases\"], list) or not all(\n isinstance(phase, str) and phase for phase in meta[\"phases\"]\n ):\n raise WorkflowInputError(\"meta.phases must be a list of non-empty strings\")\n return meta\n\n\ndef check_permission(meta, settings=None):\n \"\"\"Apply the s03 allow/deny gate before launching a workflow.\"\"\"\n settings = settings or {}\n if meta[\"name\"] in settings.get(\"deny\", []):\n raise WorkflowInputError(f\"workflow '{meta['name']}' denied by settings\")\n return \"allow\"\n\n\n# ============================================================\n# Minimal JSON-schema for structured output (SimpleJsonSchema)\n# ============================================================\nclass SimpleJsonSchema:\n \"\"\"Tiny validator backing agent({schema}):\n object/array/string/boolean/number + required keys.\"\"\"\n\n def __init__(self, schema):\n self.schema = schema\n\n def validate(self, value, schema=None):\n schema = self.schema if schema is None else schema\n t = schema.get(\"type\")\n if t == \"object\":\n if not isinstance(value, dict):\n return False, \"expected object\"\n for key in schema.get(\"required\", []):\n if key not in value:\n return False, f\"missing required key '{key}'\"\n for key, sub in schema.get(\"properties\", {}).items():\n if key in value:\n ok, err = self.validate(value[key], sub)\n if not ok:\n return False, f\"{key}: {err}\"\n return True, None\n if t == \"array\":\n if not isinstance(value, list):\n return False, \"expected array\"\n items = schema.get(\"items\")\n if items:\n for i, el in enumerate(value):\n ok, err = self.validate(el, items)\n if not ok:\n return False, f\"[{i}]: {err}\"\n return True, None\n if t == \"string\":\n return (isinstance(value, str), None if isinstance(value, str) else \"expected string\")\n if t == \"boolean\":\n return (isinstance(value, bool), None if isinstance(value, bool) else \"expected boolean\")\n if t in (\"number\", \"integer\"):\n ok = isinstance(value, (int, float)) and not isinstance(value, bool)\n return (ok, None if ok else \"expected number\")\n return True, None\n\n\ndef _fill_schema(schema, seed):\n \"\"\"Deterministic generic filler used for schemas the mock doesn't special-case.\"\"\"\n t = schema.get(\"type\")\n if t == \"object\":\n keys = schema.get(\"required\") or list(schema.get(\"properties\", {}))\n return {k: _fill_schema(schema[\"properties\"][k], f\"{seed}/{k}\") for k in keys}\n if t == \"array\":\n return [_fill_schema(schema[\"items\"], f\"{seed}/0\")]\n if t == \"boolean\":\n return _stable_hash(seed) % 4 != 0\n if t in (\"number\", \"integer\"):\n return _stable_hash(seed) % 5\n return seed.rsplit(\"/\", 1)[-1]\n\n\n# ============================================================\n# Deterministic subagent runner\n# ============================================================\nclass MockAgentRunner:\n \"\"\"Runs deterministic subagent outputs so resume is reproducible.\"\"\"\n\n def run(self, prompt, schema=None, label=None):\n if schema is None:\n return f\"[mock] {(label or prompt)[:60]}\"\n props = schema.get(\"properties\", {})\n if \"findings\" in props: # an audit agent\n n = 1 + (_stable_hash(prompt) % 2) # 1-2 findings\n sev = [\"high\", \"medium\", \"low\"]\n return {\"findings\": [\n {\"title\": f\"{label or 'audit'} #{i + 1}\",\n \"severity\": sev[_stable_hash(prompt + str(i)) % 3]}\n for i in range(n)\n ]}\n if \"isReal\" in props: # a verifier agent\n real = _stable_hash(prompt) % 4 != 0 # ~75% confirmed\n return {\"isReal\": real,\n \"reason\": \"reproduced\" if real else \"could not reproduce\"}\n return _fill_schema(schema, prompt)\n\n @staticmethod\n def tokens(prompt, result):\n return len(prompt) // 4 + len(json.dumps(result, default=str)) // 4\n\n\n# ============================================================\n# Journal (resume cache): started/result per agent under a semantic key\n# ============================================================\nclass WorkflowJournal:\n \"\"\"Append-only .journal.jsonl. On resume, agent() calls whose\n semantic key is already present are replayed from cache instead of re-run.\"\"\"\n\n def __init__(self, run_id, resume, store=STORE):\n store.mkdir(parents=True, exist_ok=True)\n self.path = store / f\"{run_id}.journal.jsonl\"\n self.resume = resume\n self.cache = {}\n if resume:\n if not self.path.exists():\n raise WorkflowInputError(f\"resume journal not found for {run_id}\")\n for line_number, line in enumerate(self.path.read_text().splitlines(), start=1):\n try:\n rec = json.loads(line)\n if (\n not isinstance(rec, dict)\n or not isinstance(rec.get(\"key\"), str)\n or \"value\" not in rec\n ):\n raise ValueError(\"expected key/value record\")\n except (json.JSONDecodeError, ValueError) as exc:\n raise WorkflowInputError(\n f\"invalid resume journal record at line {line_number}\"\n ) from exc\n self.cache[rec[\"key\"]] = rec[\"value\"]\n self._f = self.path.open(\"a\")\n else:\n self._f = self.path.open(\"w\") # fresh run truncates\n\n def key(self, kind, label, prompt, schema):\n # Deterministic semantic key — independent of concurrency order, so a\n # parallel/pipeline call gets the same key on resume.\n basis = f\"{kind}|{label}|{prompt}|{json.dumps(schema, sort_keys=True)}\"\n return f\"{kind}-{_stable_hash(basis) % 10**10:010d}\"\n\n def cached(self, key):\n return self.cache.get(key, MISS)\n\n def record(self, key, value):\n self._f.write(json.dumps({\"key\": key, \"value\": value}) + \"\\n\")\n self._f.flush()\n self.cache[key] = value\n\n def close(self):\n self._f.close()\n\n\n# ============================================================\n# Token budget\n# ============================================================\nclass Budget:\n \"\"\"budget.total / spent() / remaining(). Once spent reaches total, agent()\n calls raise instead of silently overspending.\"\"\"\n\n def __init__(self, total=None):\n self.total = total\n self._spent = 0\n\n def add(self, n):\n if self.total is not None and self._spent + n > self.total:\n raise WorkflowInputError(\n f\"token budget exceeded ({self._spent + n} > {self.total})\"\n )\n self._spent += n\n\n def spent(self):\n return self._spent\n\n def remaining(self):\n return float(\"inf\") if self.total is None else max(0, self.total - self._spent)\n\n\n# ============================================================\n# Background task state + progress events (the outer event stream)\n# ============================================================\nclass LocalWorkflowTask:\n \"\"\"type local_workflow. Holds status/usage and emits the SDK-like event\n stream: task_started, task_progress (workflow_phase/agent/log), task_notification.\"\"\"\n\n def __init__(self, task_id, run_id, meta):\n self.task_id = task_id\n self.run_id = run_id\n self.meta = meta\n self.status = \"running\"\n self.usage = {\"agents\": 0, \"tokens\": 0}\n self.progress = []\n\n def event(self, name, **data):\n line = \" \".join(f\"{k}={v}\" for k, v in data.items())\n print(f\" event {name:<18} {line}\")\n\n def progress_event(self, ptype, **data):\n self.progress.append({\"type\": ptype, **data})\n line = \" \".join(f\"{k}={v}\" for k, v in data.items())\n print(f\" progress {ptype:<16} {line}\")\n\n\n# ============================================================\n# ExecutionState: the DSL the workflow script sees as `ctx`\n# ============================================================\nclass ExecutionLimits:\n \"\"\"Shared run-wide limits, including nested workflows.\"\"\"\n\n def __init__(self):\n self.agents = 0\n self.semaphore = asyncio.Semaphore(CONCURRENCY)\n\n def claim_agent(self):\n self.agents += 1\n if self.agents > AGENT_CAP:\n raise WorkflowInputError(f\"agent() cap reached ({AGENT_CAP})\")\n\n\nclass ExecutionState:\n \"\"\"Injected into the workflow script with the orchestration primitives.\"\"\"\n\n def __init__(self, task, journal, runner, budget, args, depth=0, limits=None):\n self.task = task\n self.journal = journal\n self.runner = runner\n self.budget = budget\n self.args = args\n self._depth = depth\n self._phase = None\n self._phases_seen = set()\n self._limits = limits or ExecutionLimits()\n\n def phase(self, title):\n \"\"\"Start a phase; subsequent agent()s group under it. Upsert: emitting the\n same phase again (e.g. from each pipeline item) does not re-announce it.\"\"\"\n self._phase = title\n if title not in self._phases_seen:\n self._phases_seen.add(title)\n self.task.progress_event(\"workflow_phase\", title=title)\n\n def log(self, message):\n \"\"\"Emit a workflow_log progress line.\"\"\"\n self.task.progress_event(\"workflow_log\", message=message)\n\n async def agent(self, prompt, schema=None, label=None, phase=None):\n \"\"\"Spawn one subagent. With a schema, force StructuredOutput + validate\n (retry once). On resume, a cached key short-circuits the run.\"\"\"\n label = label or (prompt[:24] + \"…\")\n self._limits.claim_agent()\n if self.budget.remaining() <= 0:\n raise WorkflowInputError(\"token budget exceeded\")\n\n key = self.journal.key(\"agent\", label, prompt, schema)\n cached = self.journal.cached(key)\n if cached is not MISS:\n if schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(cached)\n if not ok:\n raise WorkflowInputError(\n f\"cached agent output failed schema validation: {err}\"\n )\n self.task.progress_event(\"workflow_agent\", label=label,\n phase=phase or self._phase, status=\"cached\")\n return cached\n\n async with self._limits.semaphore:\n await asyncio.sleep(0) # yield: real subagents are async\n result = self.runner.run(prompt, schema, label)\n\n if schema is not None:\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok: # one nudge/retry, then fail\n result = self.runner.run(prompt + \"\\n\\nReturn valid JSON.\", schema, label)\n ok, err = SimpleJsonSchema(schema).validate(result)\n if not ok:\n raise WorkflowInputError(f\"agent({{schema}}) invalid output: {err}\")\n\n toks = self.runner.tokens(prompt, result)\n self.budget.add(toks)\n self.task.usage[\"agents\"] += 1\n self.task.usage[\"tokens\"] += toks\n self.journal.record(key, result)\n self.task.progress_event(\"workflow_agent\", label=label,\n phase=phase or self._phase, status=\"done\")\n return result\n\n async def parallel(self, thunks):\n \"\"\"BARRIER: run all thunks concurrently and fail if any thunk fails.\"\"\"\n return await asyncio.gather(*[thunk() for thunk in thunks])\n\n async def pipeline(self, items, *stages):\n \"\"\"Per-item staged flow, NO barrier between stages: item A can be in\n stage 3 while item B is still in stage 1. Each stage gets\n (prev_result, original_item, index). A throwing stage fails the workflow.\"\"\"\n async def run_item(item, idx):\n value = item\n for stage in stages:\n value = await stage(value, item, idx)\n return value\n return await asyncio.gather(*[run_item(it, i) for i, it in enumerate(items)])\n\n async def workflow(self, name, args=None):\n \"\"\"Run a saved workflow inline as a child (one level), sharing this run's\n journal + budget + agent counter.\"\"\"\n if self._depth >= 1:\n raise WorkflowInputError(\"workflow() nesting is one level only\")\n if name not in WORKFLOWS:\n raise WorkflowInputError(f\"unknown workflow '{name}'\")\n meta, fn = WORKFLOWS[name]\n child = ExecutionState(self.task, self.journal, self.runner, self.budget,\n args or {}, depth=self._depth + 1,\n limits=self._limits)\n return await fn(child, args or {})\n\n\n# ============================================================\n# WorkflowTool: the tool entry (WorkflowTool.call)\n# ============================================================\nclass WorkflowTool:\n \"\"\"The Workflow tool. .call() validates meta, runs the permission check,\n creates runId/taskId, registers a LocalWorkflowTask, and emits lifecycle\n events while the CLI awaits the final result. Supports resume.\"\"\"\n\n async def call(self, meta, script_fn, args=None, resume_from_run_id=None):\n validate_meta(meta)\n check_permission(meta)\n args = args or {}\n run_id = resume_from_run_id or create_run_id(meta)\n validate_run_id(run_id)\n if resume_from_run_id is not None and run_id != create_run_id(meta):\n raise WorkflowInputError(\"resume runId does not match workflow meta\")\n task_id = create_task_id(run_id)\n resuming = resume_from_run_id is not None\n\n task = LocalWorkflowTask(task_id, run_id, meta)\n # Record the launch envelope before workflow execution starts.\n launched = {\"status\": \"async_launched\", \"taskId\": task_id,\n \"taskType\": \"local_workflow\", \"runId\": run_id,\n \"workflowName\": meta[\"name\"]}\n task.event(\"async_launched\", runId=run_id, taskId=task_id)\n task.event(\"task_started\", workflow=meta[\"name\"],\n phases=\",\".join(meta.get(\"phases\", [])) or \"-\",\n resume=resuming)\n\n journal = None\n try:\n journal = WorkflowJournal(run_id, resume=resuming)\n ctx = ExecutionState(\n task, journal, MockAgentRunner(), Budget(args.get(\"budget\")), args\n )\n result = await script_fn(ctx, args)\n task.status = \"completed\"\n except Exception as e: # failed / stopped close the loop too\n task.status = \"failed\"\n result = {\"error\": str(e)}\n finally:\n if journal is not None:\n journal.close()\n\n _write_json(STORE / f\"{run_id}.output.json\", result)\n _save_last_run(run_id)\n task.event(\"task_notification\", status=task.status,\n agents=task.usage[\"agents\"], tokens=task.usage[\"tokens\"],\n outputFile=f\".runtime/{run_id}.output.json\")\n return {\"launched\": launched, \"result\": result, \"task\": task}\n\n\ndef _write_json(path, value):\n path.parent.mkdir(parents=True, exist_ok=True)\n path.write_text(json.dumps(value, indent=2, default=str))\n\n\ndef _save_last_run(run_id):\n (STORE / \"last_run.txt\").write_text(run_id)\n\n\ndef _read_last_run():\n p = STORE / \"last_run.txt\"\n return p.read_text().strip() if p.exists() else None\n\n\n# ============================================================\n# Sample workflow: review changed code across dimensions, verify each finding.\n# ============================================================\nFINDINGS_SCHEMA = {\n \"type\": \"object\", \"required\": [\"findings\"],\n \"properties\": {\"findings\": {\"type\": \"array\", \"items\": {\n \"type\": \"object\", \"required\": [\"title\", \"severity\"],\n \"properties\": {\"title\": {\"type\": \"string\"}, \"severity\": {\"type\": \"string\"}}}}},\n}\nVERDICT_SCHEMA = {\n \"type\": \"object\", \"required\": [\"isReal\", \"reason\"],\n \"properties\": {\"isReal\": {\"type\": \"boolean\"}, \"reason\": {\"type\": \"string\"}},\n}\n\nSAMPLE_META = {\n \"name\": \"review-changes\",\n \"description\": \"Review changed files across dimensions, verify each finding\",\n \"phases\": [\"Review\", \"Verify\"],\n}\n\nDIMENSIONS = [\"correctness\", \"security\", \"performance\", \"style\"]\n\n\nasync def sample_workflow(ctx, args):\n \"\"\"pipeline over review dimensions (audit -> verify-each), then keep only the\n findings a verifier confirms. The plan is code, not a chat turn.\"\"\"\n ctx.phase(\"Review\")\n\n async def audit(_value, dimension, _idx):\n out = await ctx.agent(\n f\"Review the changed files for {dimension} issues.\",\n schema=FINDINGS_SCHEMA, label=f\"audit:{dimension}\", phase=\"Review\")\n return {\"dimension\": dimension, \"findings\": out[\"findings\"]}\n\n async def verify(audited, dimension, _idx):\n ctx.phase(\"Verify\")\n # Each finding is verified by its own adversarial subagent, concurrently.\n verdicts = await ctx.parallel([\n (lambda f=f: ctx.agent(\n f\"Adversarially verify this {dimension} finding — is it real? {f['title']}\",\n schema=VERDICT_SCHEMA, label=f\"verify:{dimension}:{f['title']}\", phase=\"Verify\"))\n for f in audited[\"findings\"]])\n confirmed = [f for f, v in zip(audited[\"findings\"], verdicts)\n if v and v.get(\"isReal\")]\n return {\"dimension\": dimension, \"confirmed\": confirmed}\n\n results = await ctx.pipeline(DIMENSIONS, audit, verify)\n confirmed = [{\"dimension\": r[\"dimension\"], **f}\n for r in results if r for f in r[\"confirmed\"]]\n confirmed.sort(key=lambda f: {\"high\": 0, \"medium\": 1, \"low\": 2}.get(f[\"severity\"], 3))\n ctx.log(f\"confirmed {len(confirmed)} real finding(s)\")\n return {\"confirmed\": confirmed}\n\n\n# Saved workflow registry\nWORKFLOWS = {SAMPLE_META[\"name\"]: (SAMPLE_META, sample_workflow)}\n\n\n# ============================================================\n# Demo\n# ============================================================\nasync def main(argv):\n resume_id = None\n if argv and argv[0] == \"resume\":\n resume_id = _read_last_run()\n if not resume_id:\n print(\"nothing to resume — run `python code.py` first.\")\n return\n print(f\"resuming {resume_id} — unchanged agent() calls hit the journal cache\\n\")\n else:\n print(\"launching workflow `review-changes`\\n\")\n\n tool = WorkflowTool()\n out = await tool.call(SAMPLE_META, sample_workflow,\n args={\"budget\": None}, resume_from_run_id=resume_id)\n\n print(\"\\nresult:\")\n for f in out[\"result\"].get(\"confirmed\", []):\n print(f\" [{f['severity']:<6}] {f['dimension']}: {f['title']}\")\n t = out[\"task\"]\n print(f\"\\nstatus={t.status} agents={t.usage['agents']} tokens={t.usage['tokens']}\"\n f\" journal=.runtime/{t.run_id}.journal.jsonl\")\n\n\nif __name__ == \"__main__\":\n asyncio.run(main(sys.argv[1:]))\n", "images": [ { - "src": "/course-assets/s21_workflow_runtime/workflow-runtime-overview.svg", + "src": "/course-assets/s20_workflow_runtime/workflow-runtime-overview.svg", "alt": "workflow runtime overview" } ] }, { - "id": "s22", - "filename": "s22_goal_loop/code.py", + "id": "s21", + "filename": "s21_goal_loop/code.py", "title": "Goal Loop", "subtitle": "Trusted Evidence Decides When to Stop", "loc": 209, @@ -3808,12 +3839,12 @@ { "name": "GoalRuntime", "startLine": 103, - "endLine": 192 + "endLine": 191 }, { "name": "Session", - "startLine": 193, - "endLine": 249 + "startLine": 192, + "endLine": 248 } ], "functions": [ @@ -3830,19 +3861,19 @@ { "name": "banner", "signature": "def banner(text)", - "startLine": 250 + "startLine": 249 }, { "name": "main", "signature": "def main(argv)", - "startLine": 254 + "startLine": 253 } ], "layer": "planning", - "source": "\"\"\"\ns22_goal_loop — minimal /goal session loop for a teaching harness\n\nIdea:\n s01-s21 end a turn when the model emits no tool_use. `/goal` adds a\n host-owned turn-completion GATE: the user sets a stopping CONDITION, and after\n every turn a separate evaluator judges whether trusted transcript evidence\n satisfies it. Not satisfied -> the gate blocks the stop and feeds a\n continuation into the next turn. Satisfied -> the active goal is cleared.\n\n So the core contrast with s01 is one extra check before \"return\":\n\n # s01: the model says stop -> stop\n if not has_tool_use(response):\n return\n # s22: when it wants to stop, pass the goal gate first\n if not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # not met -> push it back\n return # met / over budget / no goal -> really stop\n\nRun:\n python code.py # /goal until tests pass + deploy green; watch the gate\n\nImplementation choices:\n - The evaluator is a deterministic keyword check, not a small/fast model.\n - One mock task-notification produces the trusted evidence; the loop / monitor\n / background-task plane (s13/s14) is out of scope — this chapter is just the\n goal gate.\n - The evidence trust boundary is the important part: only task-notification /\n monitor-line origins count as evidence, so the `/goal` command text, the\n continuation reminder, and plain assistant prose can NOT satisfy the goal.\n Ordinary `submit()` calls cannot set those labels; only the host-event\n ingress can deliver an allowlisted source.\n\"\"\"\n\nimport itertools\nimport sys\n\n# ---- ids + a one-line event stream so the gate is visible ----\n_ids = itertools.count(1)\n\n\ndef make_id(prefix):\n return f\"{prefix}-{next(_ids):03d}\"\n\n\ndef event(lane, etype, detail=\"\"):\n print(f\" · {lane:<6} {etype:<26} {detail}\")\n\n\n# A message's origin.kind is the TRUST LABEL that decides whether it can count\n# as goal evidence. Trusted async origins land real tool/task evidence; user /\n# slash-command / active-goal (the continuation reminder) / assistant do not.\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\n\nclass Message:\n def __init__(self, role, content, origin):\n self.role = role\n self.content = content\n self.origin = origin or {\"kind\": \"user\"}\n\n\n# ============================================================\n# CommandQueue — continuation prompts live here\n# ============================================================\nclass CommandQueue:\n PRIORITY = {\"now\": 0, \"next\": 1, \"later\": 2}\n\n def __init__(self):\n self.items = []\n\n def enqueue(self, value, priority=\"next\", origin=None):\n item = {\"id\": make_id(\"cmd\"), \"priority\": priority,\n \"origin\": origin or {}, \"value\": value}\n self.items.append(item)\n return item\n\n def dequeue(self, include_goal_continuations=True):\n # Goal continuations and the external async inbox are NOT the same drain.\n # With include_goal_continuations=False an inbox drain skips them, so a\n # goal can't be advanced (or blocked) before real evidence arrives.\n self.items.sort(key=lambda i: self.PRIORITY.get(i[\"priority\"], 1))\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n\n def remove_by_origin(self, kind):\n before = len(self.items)\n self.items = [i for i in self.items if i[\"origin\"].get(\"kind\") != kind]\n return before - len(self.items)\n\n def __len__(self):\n return len(self.items)\n\n\n# ============================================================\n# GoalRuntime — the turn-completion gate\n# ============================================================\nclass GoalRuntime:\n def __init__(self, transcript, queue):\n self.transcript = transcript # shared session transcript\n self.queue = queue\n self.active = None\n\n def set_goal(self, objective, max_turns=20):\n # start_index marks the evidence window. The /goal command line is\n # already recorded, so it sits OUTSIDE the window and can't satisfy\n # itself.\n self.active = {\n \"id\": make_id(\"goal\"), \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), \"max_turns\": max_turns,\n \"checks\": 0, \"continuation_turns\": 0,\n }\n event(\"goal\", \"goal_started\", f\"{self.active['id']} :: {objective}\")\n return self.active\n\n def clear(self, reason=\"cleared\"):\n if not self.active:\n return\n self.active[\"status\"] = reason\n self.queue.remove_by_origin(\"active-goal\")\n event(\"goal\", \"goal_cleared\", reason)\n self.active = None\n\n def evidence_text(self):\n \"\"\"The trust boundary. Three filters keep self-satisfying text out:\n drop slash-command origins, drop /goal command lines, and keep ONLY\n trusted external async origins (task-notification / monitor-line).\"\"\"\n if not self.active:\n return \"\"\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\":\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"):\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS:\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n\n def goal_satisfied(self):\n # A production harness can route this evidence window to a separate\n # evaluator model. The demo uses a deterministic keyword policy.\n objective = self.active[\"objective\"].lower()\n evidence = self.evidence_text().lower()\n wants_tests = \"test\" in objective\n wants_deploy = \"deploy\" in objective or \"green\" in objective\n tests_ok = not wants_tests or \"tests passed\" in evidence or \"test passed\" in evidence\n deploy_ok = not wants_deploy or \"deploy green\" in evidence or \"deployment green\" in evidence\n if any(k in objective for k in (\"until\", \"pass\", \"green\")):\n return tests_ok and deploy_ok\n return objective in evidence\n\n def evaluate_after_turn(self):\n \"\"\"The gate, run after every turn. Returns completed / continuing /\n blocked / none.\"\"\"\n g = self.active\n if not g or g[\"status\"] != \"active\":\n return \"none\"\n g[\"checks\"] += 1\n satisfied = self.goal_satisfied()\n event(\"goal\", \"goal_evaluated\", f\"check #{g['checks']} satisfied={satisfied}\")\n if satisfied:\n g[\"status\"] = \"completed\"\n self.queue.remove_by_origin(\"active-goal\")\n event(\"goal\", \"goal_completed\", g[\"id\"])\n self.active = None\n return \"completed\"\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=(f\"Continue working toward active goal {g['id']}. Use tool/task \"\n \"evidence; do not treat this reminder as completion evidence.\"),\n priority=\"next\", origin={\"kind\": \"active-goal\", \"goal_id\": g[\"id\"]})\n event(\"goal\", \"goal_continuation_enqueued\",\n f\"turn {g['continuation_turns']}/{g['max_turns']}\")\n return \"continuing\"\n g[\"status\"] = \"blocked\"\n self.queue.remove_by_origin(\"active-goal\")\n event(\"goal\", \"goal_blocked\", f\"exceeded {g['max_turns']} turns\")\n self.active = None\n return \"blocked\"\n\n\n# ============================================================\n# Session — the main loop host with a Stop gate\n# ============================================================\nclass Session:\n def __init__(self):\n self.transcript = []\n self.queue = CommandQueue()\n self.goal = GoalRuntime(self.transcript, self.queue)\n\n def _add(self, role, content, origin):\n self.transcript.append(Message(role, content, origin))\n\n def submit(self, text):\n \"\"\"Submit ordinary user text. Callers cannot attach a trusted origin.\"\"\"\n return self._submit(text, {\"kind\": \"user\"})\n\n def deliver_host_event(self, text, source):\n \"\"\"Host-only ingress for validated task/monitor events.\"\"\"\n if source not in TRUSTED_EVIDENCE_ORIGINS:\n raise ValueError(f\"untrusted host event source: {source}\")\n return self._submit(text, {\"kind\": source})\n\n def _submit(self, text, origin):\n \"\"\"Run one turn with an origin already assigned by the host.\"\"\"\n self._add(\"user\", text, origin) # input recorded with its origin\n kind = origin[\"kind\"]\n\n if kind == \"user\" and text.strip().startswith(\"/goal\"):\n arg = text.strip()[5:].strip()\n self._add(\"assistant\", f\"(slash) /goal {arg}\", {\"kind\": \"slash-command\"})\n if arg in (\"\", \"clear\", \"stop\", \"off\"):\n self.goal.clear()\n else:\n self.goal.set_goal(arg)\n elif kind in TRUSTED_EVIDENCE_ORIGINS:\n # The input itself (recorded above with a trusted origin) is the\n # evidence; the assistant just observes it.\n event(\"turn\", f\"observe {kind}\", text[:48])\n self._add(\"assistant\", f\"Observed {kind}: {text}\", origin)\n elif kind == \"active-goal\":\n event(\"turn\", \"continue-goal\", \"(reminder is not evidence)\")\n self._add(\"assistant\", \"Continuing the goal; checking task/monitor evidence.\", origin)\n else:\n event(\"turn\", \"assistant-turn\", text[:48])\n self._add(\"assistant\", f\"assistant handled: {text}\", {\"kind\": \"assistant\"})\n\n return self.goal.evaluate_after_turn() # <-- the Stop gate\n\n def drain_goal_continuation(self):\n \"\"\"Pull one goal continuation back into the loop — explicit, separate\n from any external async-inbox drain.\"\"\"\n item = self.queue.dequeue(include_goal_continuations=True)\n if item and item[\"origin\"].get(\"kind\") == \"active-goal\":\n return self._submit(item[\"value\"], item[\"origin\"])\n return None\n\n\n# ============================================================\n# Demo\n# ============================================================\ndef banner(text):\n print(f\"\\n— {text} —\")\n\n\ndef main(argv):\n s = Session()\n\n banner(\"1. set a goal (the gate is now armed; window starts after the command)\")\n print(\"user> /goal until tests passed and deploy green\")\n s.submit(\"/goal until tests passed and deploy green\")\n\n banner(\"2. model works, no TRUSTED evidence yet -> the gate keeps it going\")\n s.drain_goal_continuation()\n s.submit(\"Inspecting the failing tests and the deploy config.\")\n\n banner(\"3. plain user text 'tests passed' is NOT trusted -> still not satisfied\")\n s.submit(\"tests passed, trust me\")\n s.drain_goal_continuation()\n print(f\" active goal still open: {s.goal.active is not None}\")\n\n banner(\"4. a background task lands a task-notification (trusted) -> satisfied\")\n verdict = s.deliver_host_event(\n \"tests passed; deploy green\", source=\"task-notification\"\n )\n print(f\" final verdict: goal {verdict}\")\n\n banner(\"5. budget: a goal that never gets evidence blocks after max_turns\")\n s2 = Session()\n s2.goal.set_goal(\"until tests passed\", max_turns=2)\n verdict = \"continuing\"\n while verdict == \"continuing\":\n verdict = s2.submit(\"still working, no task evidence yet\")\n print(f\" final verdict: goal {verdict}\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", + "source": "\"\"\"\ns21_goal_loop — minimal /goal session loop\n\nIdea:\n s01-s20 end a turn when the model emits no tool_use. `/goal` adds a\n host-owned turn-completion GATE: the user sets a stopping CONDITION, and after\n every turn a separate evaluator judges whether trusted transcript evidence\n satisfies it. Not satisfied -> the gate blocks the stop and feeds a\n continuation into the next turn. Satisfied -> the active goal is cleared.\n\n So the core contrast with s01 is one extra check before \"return\":\n\n # s01: the model says stop -> stop\n if not has_tool_use(response):\n return\n # s21: when it wants to stop, pass the goal gate first\n if not has_tool_use(response):\n verdict = goal.evaluate_after_turn()\n if verdict == \"continuing\":\n continue # not met -> push it back\n return # met / over budget / no goal -> really stop\n\nRun:\n python code.py # /goal until tests pass + deploy green; watch the gate\n\nImplementation choices:\n - The evaluator is a deterministic keyword check, not a small/fast model.\n - One mock task-notification produces the trusted evidence; the loop / monitor\n / background-task plane (s13/s14) is out of scope — this chapter is just the\n goal gate.\n - The evidence trust boundary is the important part: only task-notification /\n monitor-line origins count as evidence, so the `/goal` command text, the\n continuation reminder, and plain assistant prose can NOT satisfy the goal.\n Ordinary `submit()` calls cannot set those labels; only the host-event\n ingress can deliver an allowlisted source.\n\"\"\"\n\nimport itertools\nimport sys\n\n# ---- ids + a one-line event stream so the gate is visible ----\n_ids = itertools.count(1)\n\n\ndef make_id(prefix):\n return f\"{prefix}-{next(_ids):03d}\"\n\n\ndef event(lane, etype, detail=\"\"):\n print(f\" · {lane:<6} {etype:<26} {detail}\")\n\n\n# A message's origin.kind is the TRUST LABEL that decides whether it can count\n# as goal evidence. Trusted async origins carry host-validated evidence; user /\n# slash-command / active-goal (the continuation reminder) / assistant do not.\nTRUSTED_EVIDENCE_ORIGINS = {\"task-notification\", \"monitor-line\"}\n\n\nclass Message:\n def __init__(self, role, content, origin):\n self.role = role\n self.content = content\n self.origin = origin or {\"kind\": \"user\"}\n\n\n# ============================================================\n# CommandQueue — continuation prompts live here\n# ============================================================\nclass CommandQueue:\n PRIORITY = {\"now\": 0, \"next\": 1, \"later\": 2}\n\n def __init__(self):\n self.items = []\n\n def enqueue(self, value, priority=\"next\", origin=None):\n item = {\"id\": make_id(\"cmd\"), \"priority\": priority,\n \"origin\": origin or {}, \"value\": value}\n self.items.append(item)\n return item\n\n def dequeue(self, include_goal_continuations=True):\n # Goal continuations and the external async inbox are NOT the same drain.\n # With include_goal_continuations=False an inbox drain skips them, so a\n # goal can't be advanced (or blocked) before real evidence arrives.\n self.items.sort(key=lambda i: self.PRIORITY.get(i[\"priority\"], 1))\n for idx, item in enumerate(self.items):\n if include_goal_continuations or item[\"origin\"].get(\"kind\") != \"active-goal\":\n return self.items.pop(idx)\n return None\n\n def remove_by_origin(self, kind):\n before = len(self.items)\n self.items = [i for i in self.items if i[\"origin\"].get(\"kind\") != kind]\n return before - len(self.items)\n\n def __len__(self):\n return len(self.items)\n\n\n# ============================================================\n# GoalRuntime — the turn-completion gate\n# ============================================================\nclass GoalRuntime:\n def __init__(self, transcript, queue):\n self.transcript = transcript # shared session transcript\n self.queue = queue\n self.active = None\n\n def set_goal(self, objective, max_turns=20):\n # start_index marks the evidence window. The /goal command line is\n # already recorded, so it sits OUTSIDE the window and can't satisfy\n # itself.\n self.active = {\n \"id\": make_id(\"goal\"), \"objective\": objective, \"status\": \"active\",\n \"start_index\": len(self.transcript), \"max_turns\": max_turns,\n \"checks\": 0, \"continuation_turns\": 0,\n }\n event(\"goal\", \"goal_started\", f\"{self.active['id']} :: {objective}\")\n return self.active\n\n def clear(self, reason=\"cleared\"):\n if not self.active:\n return\n self.active[\"status\"] = reason\n self.queue.remove_by_origin(\"active-goal\")\n event(\"goal\", \"goal_cleared\", reason)\n self.active = None\n\n def evidence_text(self):\n \"\"\"The trust boundary. Three filters keep self-satisfying text out:\n drop slash-command origins, drop /goal command lines, and keep ONLY\n trusted external async origins (task-notification / monitor-line).\"\"\"\n if not self.active:\n return \"\"\n out = []\n for m in self.transcript[self.active[\"start_index\"]:]:\n if m.origin.get(\"kind\") == \"slash-command\":\n continue\n if m.role == \"user\" and m.content.strip().startswith(\"/goal\"):\n continue\n if m.origin.get(\"kind\") not in TRUSTED_EVIDENCE_ORIGINS:\n continue\n out.append(f\"{m.role}: {m.content}\")\n return \"\\n\".join(out)\n\n def goal_satisfied(self):\n # Evaluate only the trusted evidence window with a deterministic policy.\n objective = self.active[\"objective\"].lower()\n evidence = self.evidence_text().lower()\n wants_tests = \"test\" in objective\n wants_deploy = \"deploy\" in objective or \"green\" in objective\n tests_ok = not wants_tests or \"tests passed\" in evidence or \"test passed\" in evidence\n deploy_ok = not wants_deploy or \"deploy green\" in evidence or \"deployment green\" in evidence\n if any(k in objective for k in (\"until\", \"pass\", \"green\")):\n return tests_ok and deploy_ok\n return objective in evidence\n\n def evaluate_after_turn(self):\n \"\"\"The gate, run after every turn. Returns completed / continuing /\n blocked / none.\"\"\"\n g = self.active\n if not g or g[\"status\"] != \"active\":\n return \"none\"\n g[\"checks\"] += 1\n satisfied = self.goal_satisfied()\n event(\"goal\", \"goal_evaluated\", f\"check #{g['checks']} satisfied={satisfied}\")\n if satisfied:\n g[\"status\"] = \"completed\"\n self.queue.remove_by_origin(\"active-goal\")\n event(\"goal\", \"goal_completed\", g[\"id\"])\n self.active = None\n return \"completed\"\n if g[\"continuation_turns\"] < g[\"max_turns\"]:\n g[\"continuation_turns\"] += 1\n self.queue.enqueue(\n value=(f\"Continue working toward active goal {g['id']}. Use tool/task \"\n \"evidence; do not treat this reminder as completion evidence.\"),\n priority=\"next\", origin={\"kind\": \"active-goal\", \"goal_id\": g[\"id\"]})\n event(\"goal\", \"goal_continuation_enqueued\",\n f\"turn {g['continuation_turns']}/{g['max_turns']}\")\n return \"continuing\"\n g[\"status\"] = \"blocked\"\n self.queue.remove_by_origin(\"active-goal\")\n event(\"goal\", \"goal_blocked\", f\"exceeded {g['max_turns']} turns\")\n self.active = None\n return \"blocked\"\n\n\n# ============================================================\n# Session — the main loop host with a Stop gate\n# ============================================================\nclass Session:\n def __init__(self):\n self.transcript = []\n self.queue = CommandQueue()\n self.goal = GoalRuntime(self.transcript, self.queue)\n\n def _add(self, role, content, origin):\n self.transcript.append(Message(role, content, origin))\n\n def submit(self, text):\n \"\"\"Submit ordinary user text. Callers cannot attach a trusted origin.\"\"\"\n return self._submit(text, {\"kind\": \"user\"})\n\n def deliver_host_event(self, text, source):\n \"\"\"Host-only ingress for validated task/monitor events.\"\"\"\n if source not in TRUSTED_EVIDENCE_ORIGINS:\n raise ValueError(f\"untrusted host event source: {source}\")\n return self._submit(text, {\"kind\": source})\n\n def _submit(self, text, origin):\n \"\"\"Run one turn with an origin already assigned by the host.\"\"\"\n self._add(\"user\", text, origin) # input recorded with its origin\n kind = origin[\"kind\"]\n\n if kind == \"user\" and text.strip().startswith(\"/goal\"):\n arg = text.strip()[5:].strip()\n self._add(\"assistant\", f\"(slash) /goal {arg}\", {\"kind\": \"slash-command\"})\n if arg in (\"\", \"clear\", \"stop\", \"off\"):\n self.goal.clear()\n else:\n self.goal.set_goal(arg)\n elif kind in TRUSTED_EVIDENCE_ORIGINS:\n # The input itself (recorded above with a trusted origin) is the\n # evidence; the assistant just observes it.\n event(\"turn\", f\"observe {kind}\", text[:48])\n self._add(\"assistant\", f\"Observed {kind}: {text}\", origin)\n elif kind == \"active-goal\":\n event(\"turn\", \"continue-goal\", \"(reminder is not evidence)\")\n self._add(\"assistant\", \"Continuing the goal; checking task/monitor evidence.\", origin)\n else:\n event(\"turn\", \"assistant-turn\", text[:48])\n self._add(\"assistant\", f\"assistant handled: {text}\", {\"kind\": \"assistant\"})\n\n return self.goal.evaluate_after_turn() # <-- the Stop gate\n\n def drain_goal_continuation(self):\n \"\"\"Pull one goal continuation back into the loop — explicit, separate\n from any external async-inbox drain.\"\"\"\n item = self.queue.dequeue(include_goal_continuations=True)\n if item and item[\"origin\"].get(\"kind\") == \"active-goal\":\n return self._submit(item[\"value\"], item[\"origin\"])\n return None\n\n\n# ============================================================\n# Demo\n# ============================================================\ndef banner(text):\n print(f\"\\n— {text} —\")\n\n\ndef main(argv):\n s = Session()\n\n banner(\"1. set a goal (the gate is now armed; window starts after the command)\")\n print(\"user> /goal until tests passed and deploy green\")\n s.submit(\"/goal until tests passed and deploy green\")\n\n banner(\"2. model works, no TRUSTED evidence yet -> the gate keeps it going\")\n s.drain_goal_continuation()\n s.submit(\"Inspecting the failing tests and the deploy config.\")\n\n banner(\"3. plain user text 'tests passed' is NOT trusted -> still not satisfied\")\n s.submit(\"tests passed, trust me\")\n s.drain_goal_continuation()\n print(f\" active goal still open: {s.goal.active is not None}\")\n\n banner(\"4. a background task lands a task-notification (trusted) -> satisfied\")\n verdict = s.deliver_host_event(\n \"tests passed; deploy green\", source=\"task-notification\"\n )\n print(f\" final verdict: goal {verdict}\")\n\n banner(\"5. budget: a goal that never gets evidence blocks after max_turns\")\n s2 = Session()\n s2.goal.set_goal(\"until tests passed\", max_turns=2)\n verdict = \"continuing\"\n while verdict == \"continuing\":\n verdict = s2.submit(\"still working, no task evidence yet\")\n print(f\" final verdict: goal {verdict}\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", "images": [ { - "src": "/course-assets/s22_goal_loop/goal-loop-overview.svg", + "src": "/course-assets/s21_goal_loop/goal-loop-overview.svg", "alt": "goal loop overview" } ] @@ -3993,7 +4024,7 @@ "update_context" ], "newTools": [], - "locDelta": -363 + "locDelta": -365 }, { "from": "s10", @@ -4008,7 +4039,7 @@ "reactive_compact" ], "newTools": [], - "locDelta": 122 + "locDelta": 121 }, { "from": "s11", @@ -4037,7 +4068,7 @@ "claim_task", "complete_task" ], - "locDelta": 12 + "locDelta": 13 }, { "from": "s12", @@ -4051,7 +4082,7 @@ "collect_background_results" ], "newTools": [], - "locDelta": 82 + "locDelta": 83 }, { "from": "s13", @@ -4081,66 +4112,58 @@ "list_crons", "cancel_cron" ], - "locDelta": 264 + "locDelta": 265 }, { "from": "s14", "to": "s15", "newClasses": [ - "MessageBus" - ], - "newFunctions": [ - "has_pending_background", - "spawn_teammate_thread", - "run_spawn_teammate", - "run_send_message", - "run_check_inbox" - ], - "newTools": [ - "send_message", - "spawn_teammate", - "check_inbox" - ], - "locDelta": 141 - }, - { - "from": "s15", - "to": "s16", - "newClasses": [ + "MessageBus", "ProtocolState" ], "newFunctions": [ + "has_pending_background", + "is_valid_agent_name", "new_request_id", - "match_response", "consume_lead_inbox", + "format_team_events", + "_last_assistant_text", "_teammate_submit_plan", + "_run_teammate_tool", + "apply_plan_response", + "apply_shutdown_request", + "_teammate_send_message", + "spawn_teammate_thread", + "run_spawn_teammate", + "run_send_message", "run_request_shutdown", - "run_request_plan", - "run_review_plan" + "run_request_plan" ], "newTools": [ + "send_message", "submit_plan", + "spawn_teammate", "request_shutdown", "request_plan", "review_plan" ], - "locDelta": -75 + "locDelta": 433 + }, + { + "from": "s15", + "to": "s16", + "newClasses": [], + "newFunctions": [ + "scan_unclaimed_tasks", + "claim_next_task" + ], + "newTools": [], + "locDelta": 52 }, { "from": "s16", "to": "s17", "newClasses": [], - "newFunctions": [ - "scan_unclaimed_tasks", - "idle_poll" - ], - "newTools": [], - "locDelta": -62 - }, - { - "from": "s17", - "to": "s18", - "newClasses": [], "newFunctions": [ "get_task_json", "validate_worktree_name", @@ -4160,11 +4183,11 @@ "remove_worktree", "keep_worktree" ], - "locDelta": 161 + "locDelta": -163 }, { - "from": "s18", - "to": "s19", + "from": "s17", + "to": "s18", "newClasses": [ "MCPClient" ], @@ -4183,11 +4206,11 @@ "status", "connect_mcp" ], - "locDelta": 27 + "locDelta": 73 }, { - "from": "s19", - "to": "s20", + "from": "s18", + "to": "s19", "newClasses": [ "RecoveryState", "CronJob" @@ -4247,7 +4270,7 @@ "build_user_content", "inject_background_notifications", "print_turn_assistants", - "cron_autorun_loop" + "async_event_loop" ], "newTools": [ "edit_file", @@ -4260,11 +4283,11 @@ "list_crons", "cancel_cron" ], - "locDelta": 871 + "locDelta": 818 }, { - "from": "s20", - "to": "s21", + "from": "s19", + "to": "s20", "newClasses": [ "WorkflowInputError", "SimpleJsonSchema", @@ -4291,11 +4314,11 @@ "newTools": [ "review-changes" ], - "locDelta": -1285 + "locDelta": -1439 }, { - "from": "s21", - "to": "s22", + "from": "s20", + "to": "s21", "newClasses": [ "Message", "CommandQueue", @@ -4309,7 +4332,7 @@ "main" ], "newTools": [], - "locDelta": -214 + "locDelta": -210 } ] } \ No newline at end of file diff --git a/web/src/data/scenarios/s15.json b/web/src/data/scenarios/s15.json index 0b7e2983..231298a8 100644 --- a/web/src/data/scenarios/s15.json +++ b/web/src/data/scenarios/s15.json @@ -1,51 +1,60 @@ { "version": "s15", - "title": "Agent Teams: Runtime Lab", - "description": "The first Agent Teams lab builds persistent teammate loops and file-backed mailboxes.", + "title": "Agent Teams", + "description": "The Lead proposes a team for a normal user request, waits for confirmation, then coordinates persistent teammates through runtime-delivered events.", "steps": [ { "type": "user_message", - "content": "Split this task: one agent checks tests, another reviews docs.", - "annotation": "The request needs parallel work with separate responsibilities." + "content": "Refactor the configuration loader and authentication flow, then update the tests.", + "annotation": "The user describes the goal without designing a team." }, { "type": "assistant_text", - "content": "I'll spawn teammates with narrow roles and coordinate their updates through the message bus.", - "annotation": "The lead keeps orchestration authority while delegating execution." + "content": "These areas can be handled in parallel. I propose one teammate for configuration and authentication, and another for tests. Shall I start that team?", + "annotation": "The Lead chooses a small team and makes the extra-agent decision visible." + }, + { + "type": "user_message", + "content": "Yes, go ahead.", + "annotation": "Teammates start only after explicit confirmation." }, { "type": "tool_call", "toolName": "spawn_teammate", - "content": "{\"name\":\"test-runner\",\"role\":\"Run test commands and report failures.\"}", - "annotation": "A teammate thread starts with its own simplified loop." + "content": "{\"name\":\"backend\",\"role\":\"backend engineer\",\"prompt\":\"Refactor configuration and authentication while preserving interfaces.\"}", + "annotation": "The first persistent teammate enters WORK with a focused assignment." }, { "type": "tool_call", - "toolName": "send_message", - "content": "{\"to\":\"test-runner\",\"message\":\"Run the focused test suite and summarize failures.\"}", - "annotation": "The lead sends work through the file-backed mailbox." + "toolName": "spawn_teammate", + "content": "{\"name\":\"tests\",\"role\":\"test engineer\",\"prompt\":\"Update and run tests for the refactor.\"}", + "annotation": "The second teammate gets an independent slice." }, { "type": "system_event", - "content": ".mailboxes/test-runner.jsonl <- {from:\"lead\", message:\"Run the focused test suite\"}", - "annotation": "MessageBus persists the handoff as JSONL." + "content": "backend -> Lead: result(refactor complete) -> idle_notification", + "annotation": "Result and idle state are separate events; the teammate remains available." }, { "type": "system_event", - "content": ".mailboxes/lead.jsonl <- {from:\"test-runner\", message:\"Tests passed.\"}", - "annotation": "The teammate replies without sharing the lead's whole conversation." + "content": "tests -> Lead: result(test suite passed) -> idle_notification", + "annotation": "The runtime observes mailbox writes and wakes the Lead without a polling tool." + }, + { + "type": "assistant_text", + "content": "Both parts are complete. The interfaces were preserved and the updated tests pass.", + "annotation": "The Lead combines teammate results into one user-facing answer." }, { "type": "tool_call", - "toolName": "check_inbox", - "content": "{\"agent\":\"lead\"}", - "annotation": "The lead polls its own inbox for teammate updates." + "toolName": "request_shutdown", + "content": "{\"teammate\":\"backend\"}", + "annotation": "A typed request with a request id closes the persistent teammate cleanly." }, { - "type": "tool_result", - "toolName": "check_inbox", - "content": "test-runner: Tests passed.", - "annotation": "Mailbox messages re-enter the lead loop as tool results." + "type": "system_event", + "content": "shutdown_response(request_id=req_42, approve=true)", + "annotation": "The matching response resolves the pending protocol request." } ] } diff --git a/web/src/data/scenarios/s16.json b/web/src/data/scenarios/s16.json index 3b2b13d0..9a8ff8b7 100644 --- a/web/src/data/scenarios/s16.json +++ b/web/src/data/scenarios/s16.json @@ -1,45 +1,50 @@ { "version": "s16", - "title": "Agent Teams: Protocol Lab", - "description": "The second Agent Teams lab adds typed requests, request ids, and response matching to the s15 runtime.", + "title": "Autonomous Agents", + "description": "Idle teammates discover ready tasks on a shared board and use an atomic claim before starting work.", "steps": [ { "type": "user_message", - "content": "Ask the reviewer agent for a plan before it edits anything.", - "annotation": "The lead needs a structured plan request, not free-form chat." + "content": "Update the API examples, then add tests that use the final examples.", + "annotation": "The request contains two tasks with a clear dependency." }, { "type": "tool_call", - "toolName": "request_plan", - "content": "{\"to\":\"reviewer\",\"task\":\"Review the parser change before editing.\"}", - "annotation": "The protocol records a pending request with a request_id." - }, - { - "type": "system_event", - "content": "pending_requests[req_18] = {kind:\"plan\", to:\"reviewer\", status:\"pending\"}", - "annotation": "ProtocolState keeps the request open until a matching response arrives." - }, - { - "type": "system_event", - "content": "dispatch_message -> reviewer inbox: {type:\"plan_request\", request_id:\"req_18\"}", - "annotation": "The message is typed so the teammate knows how to handle it." + "toolName": "create_task", + "content": "{\"subject\":\"Update API examples\"}", + "annotation": "The Lead creates the first task in the shared graph." }, { "type": "tool_call", - "toolName": "submit_plan", - "content": "{\"request_id\":\"req_18\",\"plan\":[\"inspect parser\",\"run fixtures\",\"report risks\"]}", - "annotation": "The teammate responds with the same request_id." + "toolName": "create_task", + "content": "{\"subject\":\"Add example tests\",\"blockedBy\":[\"task_examples\"]}", + "annotation": "The second task cannot start until the examples are complete." }, { "type": "system_event", - "content": "match_response(req_18) -> status: ready_for_review", - "annotation": "The lead can correlate the reply with the exact request." + "content": "alice, bob: state=IDLE -> scan_unclaimed_tasks()", + "annotation": "Existing IDLE teammates scan the board after waiting for messages." + }, + { + "type": "system_event", + "content": "claim_next_task(alice) -> task_examples; task_lock commits owner=alice", + "annotation": "The ownership check and pending-to-in_progress update are atomic." + }, + { + "type": "system_event", + "content": "claim_next_task(bob) -> no ready task; remain IDLE", + "annotation": "The test task is still blocked, so Bob does not start it early." }, { "type": "tool_call", - "toolName": "review_plan", - "content": "{\"request_id\":\"req_18\",\"approved\":true}", - "annotation": "The lead explicitly approves the plan before work proceeds." + "toolName": "complete_task", + "content": "{\"task_id\":\"task_examples\"}", + "annotation": "Completing the examples unblocks the dependent test task." + }, + { + "type": "system_event", + "content": "claim_next_task(bob) -> task_tests; task_lock commits owner=bob", + "annotation": "Bob claims the newly ready work without another direct assignment." } ] } diff --git a/web/src/data/scenarios/s17.json b/web/src/data/scenarios/s17.json index 9bb25f5f..e2f870d2 100644 --- a/web/src/data/scenarios/s17.json +++ b/web/src/data/scenarios/s17.json @@ -1,46 +1,45 @@ { "version": "s17", - "title": "Autonomous Agents", - "description": "Idle teammates can scan the task board, claim eligible work, and return to idle after completion.", + "title": "Worktree Isolation", + "description": "A task can be bound to an isolated git worktree so concurrent agents avoid stepping on each other.", "steps": [ { - "type": "system_event", - "content": "teammate(worker-a): state=IDLE -> idle_poll()", - "annotation": "Autonomy starts from an idle lifecycle tick, not a direct user command." + "type": "user_message", + "content": "Update the docs and parser in parallel without letting the changes interfere.", + "annotation": "Concurrent edits need isolated working directories." }, { "type": "tool_call", - "toolName": "list_tasks", - "content": "{\"status\":\"open\"}", - "annotation": "The idle agent scans the shared task board." + "toolName": "create_worktree", + "content": "{\"task_id\":\"task_docs\",\"name\":\"docs-fix\"}", + "annotation": "The tool validates a safe worktree name before touching git." + }, + { + "type": "system_event", + "content": "git worktree add .worktrees/docs-fix -b agent/docs-fix", + "annotation": "A separate branch and checkout are created for that task." }, { "type": "tool_result", - "toolName": "list_tasks", - "content": "[{\"id\":\"task_5\",\"status\":\"open\",\"owner\":null,\"title\":\"Update README\"}]", - "annotation": "Only unclaimed work is eligible for autonomous pickup." - }, - { - "type": "tool_call", - "toolName": "claim_task", - "content": "{\"id\":\"task_5\",\"owner\":\"worker-a\"}", - "annotation": "The task manager enforces ownership before work begins." + "toolName": "create_worktree", + "content": "task_docs bound to .worktrees/docs-fix", + "annotation": "The task record stores the assigned worktree path." }, { "type": "system_event", - "content": "worker-a: state=WORK task=task_5", - "annotation": "The lifecycle moves from IDLE to WORK." + "content": ".worktrees/events.jsonl <- {event:\"created\", task:\"task_docs\", worktree:\"docs-fix\"}", + "annotation": "Lifecycle events are emitted as a side channel." }, { "type": "tool_call", - "toolName": "complete_task", - "content": "{\"id\":\"task_5\",\"result\":\"README updated with setup notes.\"}", - "annotation": "Completion writes the result back to the shared board." + "toolName": "keep_worktree", + "content": "{\"task_id\":\"task_docs\",\"reason\":\"needs human review\"}", + "annotation": "Closeout can preserve a worktree instead of deleting it immediately." }, { - "type": "system_event", - "content": "worker-a: state=IDLE next_poll_in=5s", - "annotation": "After finishing, the agent becomes available for more work." + "type": "assistant_text", + "content": "The docs task now has an isolated worktree and can be reviewed independently from parser changes.", + "annotation": "The user sees the isolation boundary, not just a raw git command." } ] } diff --git a/web/src/data/scenarios/s18.json b/web/src/data/scenarios/s18.json index edbc04ff..1d20d4b1 100644 --- a/web/src/data/scenarios/s18.json +++ b/web/src/data/scenarios/s18.json @@ -1,45 +1,46 @@ { "version": "s18", - "title": "Worktree Isolation", - "description": "A task can be bound to an isolated git worktree so concurrent agents avoid stepping on each other.", + "title": "MCP Tools", + "description": "The agent discovers external MCP tools and exposes them through a normalized tool namespace.", "steps": [ { "type": "user_message", - "content": "Let one teammate fix the docs while another changes the parser.", - "annotation": "Concurrent edits need isolated working directories." + "content": "Search the documentation for deployment guidance.", + "annotation": "The user asks for a tool source outside the built-in set." }, { "type": "tool_call", - "toolName": "create_worktree", - "content": "{\"task_id\":\"task_docs\",\"name\":\"docs-fix\"}", - "annotation": "The tool validates a safe worktree name before touching git." + "toolName": "connect_mcp", + "content": "{\"server\":\"docs\",\"command\":\"mock-docs-server\"}", + "annotation": "The runtime creates an MCP client for the named server." }, { "type": "system_event", - "content": "git worktree add .worktrees/docs-fix -b agent/docs-fix", - "annotation": "A separate branch and checkout are created for that task." + "content": "normalize_mcp_name(\"docs\", \"search\") -> mcp__docs__search", + "annotation": "External tools are namespaced to avoid collisions." }, { "type": "tool_result", - "toolName": "create_worktree", - "content": "task_docs bound to .worktrees/docs-fix", - "annotation": "The task record stores the assigned worktree path." - }, - { - "type": "system_event", - "content": ".worktrees/events.jsonl <- {event:\"created\", task:\"task_docs\", worktree:\"docs-fix\"}", - "annotation": "Lifecycle events are emitted as a side channel." + "toolName": "connect_mcp", + "content": "Connected docs with tools: mcp__docs__search, mcp__docs__read", + "annotation": "Tool discovery expands the active tool pool." }, { "type": "tool_call", - "toolName": "keep_worktree", - "content": "{\"task_id\":\"task_docs\",\"reason\":\"needs human review\"}", - "annotation": "Closeout can preserve a worktree instead of deleting it immediately." + "toolName": "mcp__docs__search", + "content": "{\"query\":\"deployment\"}", + "annotation": "The LLM can now call the discovered tool by its normalized name." + }, + { + "type": "tool_result", + "toolName": "mcp__docs__search", + "content": "[\"Deploy with npm run build\", \"Use environment variables for tokens\"]", + "annotation": "The external result is appended like any other tool result." }, { "type": "assistant_text", - "content": "The docs task now has an isolated worktree and can be reviewed independently from parser changes.", - "annotation": "The user sees the isolation boundary, not just a raw git command." + "content": "The docs server says to build first and keep tokens in environment variables.", + "annotation": "The agent summarizes external tool output for the user." } ] } diff --git a/web/src/data/scenarios/s19.json b/web/src/data/scenarios/s19.json index 193877de..f944758a 100644 --- a/web/src/data/scenarios/s19.json +++ b/web/src/data/scenarios/s19.json @@ -1,46 +1,57 @@ { "version": "s19", - "title": "MCP Tools", - "description": "The agent discovers external MCP tools and exposes them through a normalized tool namespace.", + "title": "Comprehensive Agent", + "description": "The final agent composes context assembly, tools, memory, teams, background work, cron, worktrees, and MCP.", "steps": [ { "type": "user_message", - "content": "Connect the docs server and search for deployment guidance.", - "annotation": "The user asks for a tool source outside the built-in set." - }, - { - "type": "tool_call", - "toolName": "connect_mcp", - "content": "{\"server\":\"docs\",\"command\":\"mock-docs-server\"}", - "annotation": "The runtime creates an MCP client for the named server." + "content": "Prepare this project for release. Check the code, update the docs, and report deployment readiness.", + "annotation": "One ordinary request needs several earlier capabilities to work together." }, { "type": "system_event", - "content": "normalize_mcp_name(\"docs\", \"search\") -> mcp__docs__search", - "annotation": "External tools are namespaced to avoid collisions." - }, - { - "type": "tool_result", - "toolName": "connect_mcp", - "content": "Connected docs with tools: mcp__docs__search, mcp__docs__read", - "annotation": "Tool discovery expands the active tool pool." - }, - { - "type": "tool_call", - "toolName": "mcp__docs__search", - "content": "{\"query\":\"deployment\"}", - "annotation": "The LLM can now call the discovered tool by its normalized name." - }, - { - "type": "tool_result", - "toolName": "mcp__docs__search", - "content": "[\"Deploy with npm run build\", \"Use environment variables for tokens\"]", - "annotation": "The external result is appended like any other tool result." + "content": "assemble_prompt: memory + task graph + skills + available tools + policy", + "annotation": "The runtime builds the prompt from layered sources of context." }, { "type": "assistant_text", - "content": "The docs server says to build first and keep tokens in environment variables.", - "annotation": "The agent summarizes external tool output for the user." + "content": "I'll inspect the task graph, delegate docs, start the slow scan in the background, and use the release checklist skill.", + "annotation": "The model chooses multiple mechanisms while keeping one coherent plan." + }, + { + "type": "tool_call", + "toolName": "load_skill", + "content": "{\"name\":\"release-check\"}", + "annotation": "Skills contribute procedural context before execution." + }, + { + "type": "tool_call", + "toolName": "spawn_teammate", + "content": "{\"name\":\"docs\",\"role\":\"Update release notes in its worktree.\"}", + "annotation": "Team delegation handles a parallel slice of the release." + }, + { + "type": "tool_call", + "toolName": "bash", + "content": "npm run lint && npm run test", + "toolInput": "{\"background\":true}", + "annotation": "Long-running validation goes through the background task path." + }, + { + "type": "tool_call", + "toolName": "connect_mcp", + "content": "{\"server\":\"deploy\",\"command\":\"mock-deploy-server\"}", + "annotation": "External capabilities are added only when needed." + }, + { + "type": "system_event", + "content": "recover: background task done, teammate replied, MCP deploy status ready", + "annotation": "The integrated runtime folds asynchronous results back into the loop." + }, + { + "type": "assistant_text", + "content": "Release preparation is ready: checks passed, docs are updated in the teammate worktree, and deployment status is available.", + "annotation": "The comprehensive agent returns a single user-facing outcome." } ] } diff --git a/web/src/data/scenarios/s20.json b/web/src/data/scenarios/s20.json index 5211bcf5..bc0f2479 100644 --- a/web/src/data/scenarios/s20.json +++ b/web/src/data/scenarios/s20.json @@ -1,57 +1,43 @@ { "version": "s20", - "title": "Comprehensive Agent", - "description": "The final agent composes context assembly, tools, memory, teams, background work, cron, worktrees, and MCP.", + "title": "Workflow Runtime", + "description": "A fixed review pipeline runs in parallel, records a journal, and resumes completed agent calls from cache.", "steps": [ { "type": "user_message", - "content": "Plan a release: inspect tasks, run checks, delegate docs, and keep long scans in the background.", - "annotation": "The final lesson combines many earlier capabilities in one request." + "content": "Review this change across correctness, security, performance, and style.", + "annotation": "The goal is open-ended, but the review procedure has a fixed shape." + }, + { + "type": "tool_call", + "toolName": "Workflow", + "content": "{\"name\":\"review-changes\",\"phases\":[\"Review\",\"Verify\"]}", + "annotation": "One tool call hands deterministic orchestration to the workflow runtime." + }, + { + "type": "tool_result", + "content": "{\"status\":\"async_launched\",\"runId\":\"wf_review-changes_6779\"}", + "annotation": "The product runtime returns a claim ticket while work continues in the background." }, { "type": "system_event", - "content": "assemble_prompt: memory + task graph + skills + available tools + policy", - "annotation": "The runtime builds the prompt from layered sources of context." - }, - { - "type": "assistant_text", - "content": "I'll inspect the task graph, delegate docs, start the slow scan in the background, and use the release checklist skill.", - "annotation": "The model chooses multiple mechanisms while keeping one coherent plan." - }, - { - "type": "tool_call", - "toolName": "load_skill", - "content": "{\"name\":\"release-check\"}", - "annotation": "Skills contribute procedural context before execution." - }, - { - "type": "tool_call", - "toolName": "spawn_teammate", - "content": "{\"name\":\"docs\",\"role\":\"Update release notes in its worktree.\"}", - "annotation": "Team delegation handles a parallel slice of the release." - }, - { - "type": "tool_call", - "toolName": "bash", - "content": "npm run lint && npm run test", - "toolInput": "{\"background\":true}", - "annotation": "Long-running validation goes through the background task path." - }, - { - "type": "tool_call", - "toolName": "connect_mcp", - "content": "{\"server\":\"deploy\",\"command\":\"mock-deploy-server\"}", - "annotation": "External capabilities are added only when needed." + "content": "phase=Review -> pipeline([correctness, security, performance, style])", + "annotation": "Each item advances independently through the scripted stages." }, { "type": "system_event", - "content": "recover: background task done, teammate replied, MCP deploy status ready", - "annotation": "The integrated runtime folds asynchronous results back into the loop." + "content": "phase=Verify -> adversarial checks run in parallel", + "annotation": "Structured results cross a validation boundary before aggregation." }, { - "type": "assistant_text", - "content": "Release preparation is ready: checks passed, docs are updated in the teammate worktree, and deployment status is available.", - "annotation": "The comprehensive agent returns a single user-facing outcome." + "type": "system_event", + "content": "journal append -> task_notification(status=completed)", + "annotation": "Every completed agent call is checkpointed before the final notification." + }, + { + "type": "system_event", + "content": "resumeFromRunId -> unchanged calls status=cached", + "annotation": "Semantic keys reuse completed work without depending on concurrency order." } ] } diff --git a/web/src/data/scenarios/s21.json b/web/src/data/scenarios/s21.json index e068aa84..6c7f414b 100644 --- a/web/src/data/scenarios/s21.json +++ b/web/src/data/scenarios/s21.json @@ -1,43 +1,37 @@ { "version": "s21", - "title": "Workflow Runtime", - "description": "A fixed review pipeline runs in parallel, records a journal, and resumes completed agent calls from cache.", + "title": "Goal Loop", + "description": "A host-owned completion gate keeps the turn alive until trusted evidence satisfies the active goal.", "steps": [ { "type": "user_message", - "content": "Review this change across correctness, security, performance, and style.", - "annotation": "The goal is open-ended, but the review procedure has a fixed shape." + "content": "/goal until tests passed and deploy green", + "annotation": "The command defines the condition but sits outside the evidence window." }, { - "type": "tool_call", - "toolName": "Workflow", - "content": "{\"name\":\"review-changes\",\"phases\":[\"Review\",\"Verify\"]}", - "annotation": "One tool call hands deterministic orchestration to the workflow runtime." + "type": "system_event", + "content": "goal_started -> evidence window reset", + "annotation": "The harness, not the working model, owns the completion gate." + }, + { + "type": "assistant_text", + "content": "Tests passed and deployment is green.", + "annotation": "Assistant prose is not trusted completion evidence." + }, + { + "type": "system_event", + "content": "goal_evaluated satisfied=false -> continuation queued", + "annotation": "An unmet condition pushes the loop into another bounded turn." }, { "type": "tool_result", - "content": "{\"status\":\"async_launched\",\"runId\":\"wf_review-changes_6779\"}", - "annotation": "The product runtime returns a claim ticket while work continues in the background." + "content": "tests passed; deploy green", + "annotation": "Only an allowlisted host event can attach a trusted evidence origin." }, { "type": "system_event", - "content": "phase=Review -> pipeline([correctness, security, performance, style])", - "annotation": "Each item advances independently through the scripted stages." - }, - { - "type": "system_event", - "content": "phase=Verify -> adversarial checks run in parallel", - "annotation": "Structured results cross a validation boundary before aggregation." - }, - { - "type": "system_event", - "content": "journal append -> task_notification(status=completed)", - "annotation": "Every completed agent call is checkpointed before the final notification." - }, - { - "type": "system_event", - "content": "resumeFromRunId -> unchanged calls status=cached", - "annotation": "Semantic keys reuse completed work without depending on concurrency order." + "content": "goal_evaluated satisfied=true -> goal_completed", + "annotation": "Trusted evidence closes the goal and releases the stop gate." } ] } diff --git a/web/src/data/scenarios/s22.json b/web/src/data/scenarios/s22.json deleted file mode 100644 index b46309d4..00000000 --- a/web/src/data/scenarios/s22.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "version": "s22", - "title": "Goal Loop", - "description": "A host-owned completion gate keeps the turn alive until trusted evidence satisfies the active goal.", - "steps": [ - { - "type": "user_message", - "content": "/goal until tests passed and deploy green", - "annotation": "The command defines the condition but sits outside the evidence window." - }, - { - "type": "system_event", - "content": "goal_started -> evidence window reset", - "annotation": "The harness, not the working model, owns the completion gate." - }, - { - "type": "assistant_text", - "content": "Tests passed and deployment is green.", - "annotation": "Assistant prose is not trusted completion evidence." - }, - { - "type": "system_event", - "content": "goal_evaluated satisfied=false -> continuation queued", - "annotation": "An unmet condition pushes the loop into another bounded turn." - }, - { - "type": "tool_result", - "content": "tests passed; deploy green", - "annotation": "Only an allowlisted host event can attach a trusted evidence origin." - }, - { - "type": "system_event", - "content": "goal_evaluated satisfied=true -> goal_completed", - "annotation": "Trusted evidence closes the goal and releases the stop gate." - } - ] -} diff --git a/web/src/i18n/messages/en.json b/web/src/i18n/messages/en.json index a1f1a39f..7343aa0a 100644 --- a/web/src/i18n/messages/en.json +++ b/web/src/i18n/messages/en.json @@ -1,10 +1,10 @@ { "meta": { "title": "Learn Claude Code", "description": "Build a nano Claude Code-like agent from 0 to 1, one mechanism at a time" }, "nav": { "home": "Home", "timeline": "Timeline", "compare": "Compare", "layers": "Layers", "github": "GitHub" }, - "home": { "hero_title": "Learn Claude Code", "hero_subtitle": "Build a nano Claude Code-like agent from 0 to 1, one mechanism at a time", "start": "Start Learning", "core_pattern": "The Core Pattern", "core_pattern_desc": "Every AI coding agent shares the same loop: call the model, execute tools, feed results back. Production systems add policy, permissions, and lifecycle layers on top.", "learning_path": "Learning Path", "learning_path_desc": "22 progressive sessions, from a simple loop to deterministic orchestration and goal closure", "layers_title": "Architectural Layers", "layers_desc": "Five orthogonal concerns that compose into a complete agent", "loc": "LOC", "learn_more": "Learn More", "versions_in_layer": "versions", "message_flow": "Message Growth", "message_flow_desc": "Watch the messages array grow as the agent loop executes" }, + "home": { "hero_title": "Learn Claude Code", "hero_subtitle": "Build a nano Claude Code-like agent from 0 to 1, one mechanism at a time", "start": "Start Learning", "core_pattern": "The Core Pattern", "core_pattern_desc": "Every AI coding agent shares the same loop: call the model, execute tools, feed results back. The harness adds policy, permissions, memory, coordination, and lifecycle control around it.", "learning_path": "Learning Path", "learning_path_desc": "21 progressive sessions, from a simple loop to deterministic orchestration and goal closure", "layers_title": "Architectural Layers", "layers_desc": "Five orthogonal concerns that compose into a complete agent", "loc": "LOC", "learn_more": "Learn More", "versions_in_layer": "versions", "message_flow": "Message Growth", "message_flow_desc": "Watch the messages array grow as the agent loop executes" }, "version": { "loc": "lines of code", "tools": "tools", "new": "New", "prev": "Previous", "next": "Next", "view_source": "View Source", "view_diff": "View Diff", "design_decisions": "Design Decisions", "whats_new": "What's New", "tutorial": "Tutorial", "simulator": "Agent Loop Simulator", "execution_flow": "Execution Flow", "architecture": "Architecture", "concept_viz": "Concept Visualization", "alternatives": "Alternatives Considered", "tab_learn": "Learn", "tab_simulate": "Simulate", "tab_code": "Code", "tab_deep_dive": "Deep Dive" }, "sim": { "play": "Play", "pause": "Pause", "step": "Step", "reset": "Reset", "speed": "Speed", "step_of": "of" }, - "timeline": { "title": "Learning Path", "subtitle": "s01 to s22: Progressive Agent Harness Design", "layer_legend": "Layer Legend", "loc_growth": "LOC Growth", "learn_more": "Learn More" }, + "timeline": { "title": "Learning Path", "subtitle": "s01 to s21: Progressive Agent Harness Design", "layer_legend": "Layer Legend", "loc_growth": "LOC Growth", "learn_more": "Learn More" }, "layers": { "title": "Architectural Layers", "subtitle": "Five orthogonal concerns that compose into a complete agent", @@ -53,14 +53,13 @@ "s12": "Task System", "s13": "Background Tasks", "s14": "Cron Scheduler", - "s15": "Agent Teams: Runtime Lab", - "s16": "Agent Teams: Protocol Lab", - "s17": "Autonomous Agents", - "s18": "Worktree Isolation", - "s19": "MCP Tools", - "s20": "Comprehensive Agent Turn", - "s21": "Workflow Runtime", - "s22": "Goal Loop" + "s15": "Agent Teams", + "s16": "Autonomous Agents", + "s17": "Worktree Isolation", + "s18": "MCP Tools", + "s19": "Comprehensive Agent", + "s20": "Workflow Runtime", + "s21": "Goal Loop" }, "layer_labels": { "tools": "Tools & Execution", @@ -84,13 +83,12 @@ "s12": "Task Board Dependencies", "s13": "Background Task Lanes", "s14": "Cron Scheduler", - "s15": "Agent Teams Runtime Lab", - "s16": "Agent Teams Protocol Lab", - "s17": "Autonomous Agent Cycle", - "s18": "Worktree Task Isolation", - "s19": "MCP Tool Bridge", - "s20": "Comprehensive Agent Turn", - "s21": "Workflow Runtime", - "s22": "Goal Completion Gate" + "s15": "Agent Teams and Protocols", + "s16": "Autonomous Agent Cycle", + "s17": "Worktree Task Isolation", + "s18": "MCP Tool Bridge", + "s19": "Comprehensive Agent Turn", + "s20": "Workflow Runtime", + "s21": "Goal Completion Gate" } } diff --git a/web/src/i18n/messages/ja.json b/web/src/i18n/messages/ja.json index 71c18d1f..1fd906e3 100644 --- a/web/src/i18n/messages/ja.json +++ b/web/src/i18n/messages/ja.json @@ -1,10 +1,10 @@ { "meta": { "title": "Learn Claude Code", "description": "0 から 1 へ nano Claude Code-like agent を構築し、毎回 1 つの仕組みを追加" }, "nav": { "home": "ホーム", "timeline": "学習パス", "compare": "バージョン比較", "layers": "アーキテクチャ層", "github": "GitHub" }, - "home": { "hero_title": "Learn Claude Code", "hero_subtitle": "0 から 1 へ nano Claude Code-like agent を構築し、毎回 1 つの仕組みを追加", "start": "学習を始める", "core_pattern": "コアパターン", "core_pattern_desc": "すべての AI コーディングエージェントは同じループを共有する:モデルを呼び出し、ツールを実行し、結果を返す。実運用ではこの上にポリシー、権限、ライフサイクル層が重なる。", "learning_path": "学習パス", "learning_path_desc": "22の段階的セッション、シンプルなループから決定的な編成と目標完了まで", "layers_title": "アーキテクチャ層", "layers_desc": "5つの直交する関心事が完全なエージェントを構成", "loc": "行", "learn_more": "詳細を見る", "versions_in_layer": "バージョン", "message_flow": "メッセージの増加", "message_flow_desc": "エージェントループ実行時のメッセージ配列の成長を観察" }, + "home": { "hero_title": "Learn Claude Code", "hero_subtitle": "0 から 1 へ nano Claude Code-like agent を構築し、毎回 1 つの仕組みを追加", "start": "学習を始める", "core_pattern": "コアパターン", "core_pattern_desc": "すべての AI コーディングエージェントは同じループを共有する:モデルを呼び出し、ツールを実行し、結果を返す。Harness はその周囲にポリシー、権限、記憶、協調、ライフサイクル制御を加える。", "learning_path": "学習パス", "learning_path_desc": "21の段階的セッション、シンプルなループから決定的な編成と目標完了まで", "layers_title": "アーキテクチャ層", "layers_desc": "5つの直交する関心事が完全なエージェントを構成", "loc": "行", "learn_more": "詳細を見る", "versions_in_layer": "バージョン", "message_flow": "メッセージの増加", "message_flow_desc": "エージェントループ実行時のメッセージ配列の成長を観察" }, "version": { "loc": "行のコード", "tools": "ツール", "new": "新規", "prev": "前のバージョン", "next": "次のバージョン", "view_source": "ソースを見る", "view_diff": "差分を見る", "design_decisions": "設計判断", "whats_new": "新機能", "tutorial": "チュートリアル", "simulator": "エージェントループシミュレーター", "execution_flow": "実行フロー", "architecture": "アーキテクチャ", "concept_viz": "コンセプト可視化", "alternatives": "検討された代替案", "tab_learn": "学習", "tab_simulate": "シミュレーション", "tab_code": "ソースコード", "tab_deep_dive": "詳細分析" }, "sim": { "play": "再生", "pause": "一時停止", "step": "ステップ", "reset": "リセット", "speed": "速度", "step_of": "/" }, - "timeline": { "title": "学習パス", "subtitle": "s01からs22へ:段階的エージェント Harness 設計", "layer_legend": "レイヤー凡例", "loc_growth": "コード量の推移", "learn_more": "詳細を見る" }, + "timeline": { "title": "学習パス", "subtitle": "s01からs21へ:段階的エージェント Harness 設計", "layer_legend": "レイヤー凡例", "loc_growth": "コード量の推移", "learn_more": "詳細を見る" }, "layers": { "title": "アーキテクチャ層", "subtitle": "5つの直交する関心事が完全なエージェントを構成", @@ -53,14 +53,13 @@ "s12": "タスクシステム", "s13": "バックグラウンドタスク", "s14": "Cron スケジューラー", - "s15": "Agent Teams:ランタイム実験", - "s16": "Agent Teams:プロトコル実験", - "s17": "自律エージェント", - "s18": "Worktree 分離", - "s19": "MCP ツール", - "s20": "Comprehensive Agent Turn", - "s21": "Workflow Runtime", - "s22": "Goal Loop" + "s15": "Agent Teams", + "s16": "自律エージェント", + "s17": "Worktree 分離", + "s18": "MCP ツール", + "s19": "Comprehensive Agent", + "s20": "Workflow Runtime", + "s21": "Goal Loop" }, "layer_labels": { "tools": "ツールと実行", @@ -84,13 +83,12 @@ "s12": "タスクボード依存関係", "s13": "バックグラウンドタスクレーン", "s14": "Cron スケジューラー", - "s15": "Agent Teams ランタイム実験", - "s16": "Agent Teams プロトコル実験", - "s17": "自律エージェントサイクル", - "s18": "Worktree タスク分離", - "s19": "MCP ツールブリッジ", - "s20": "Comprehensive Agent Turn", - "s21": "Workflow Runtime", - "s22": "目標完了ゲート" + "s15": "Agent Teams と協調プロトコル", + "s16": "自律エージェントサイクル", + "s17": "Worktree タスク分離", + "s18": "MCP ツールブリッジ", + "s19": "Comprehensive Agent Turn", + "s20": "Workflow Runtime", + "s21": "目標完了ゲート" } } diff --git a/web/src/i18n/messages/zh.json b/web/src/i18n/messages/zh.json index 364cb720..58aec7f1 100644 --- a/web/src/i18n/messages/zh.json +++ b/web/src/i18n/messages/zh.json @@ -1,10 +1,10 @@ { "meta": { "title": "Learn Claude Code", "description": "从 0 到 1 构建 nano Claude Code-like agent,每次只加一个机制" }, "nav": { "home": "首页", "timeline": "学习路径", "compare": "版本对比", "layers": "架构层", "github": "GitHub" }, - "home": { "hero_title": "Learn Claude Code", "hero_subtitle": "从 0 到 1 构建 nano Claude Code-like agent,每次只加一个机制", "start": "开始学习", "core_pattern": "核心模式", "core_pattern_desc": "所有 AI 编程 Agent 共享同一个循环:调用模型、执行工具、回传结果。生产级系统会在其上叠加策略、权限和生命周期层。", "learning_path": "学习路径", "learning_path_desc": "22 个渐进式课程,从简单循环到确定性编排与目标闭环", "layers_title": "架构层次", "layers_desc": "五个正交关注点组合成完整的 Agent", "loc": "行", "learn_more": "了解更多", "versions_in_layer": "个版本", "message_flow": "消息增长", "message_flow_desc": "观察 Agent 循环执行时消息数组的增长" }, + "home": { "hero_title": "Learn Claude Code", "hero_subtitle": "从 0 到 1 构建 nano Claude Code-like agent,每次只加一个机制", "start": "开始学习", "core_pattern": "核心模式", "core_pattern_desc": "所有 AI 编程 Agent 共享同一个循环:调用模型、执行工具、回传结果。Harness 在循环周围加入策略、权限、记忆、协作与生命周期控制。", "learning_path": "学习路径", "learning_path_desc": "21 个渐进式课程,从简单循环到确定性编排与目标闭环", "layers_title": "架构层次", "layers_desc": "五个正交关注点组合成完整的 Agent", "loc": "行", "learn_more": "了解更多", "versions_in_layer": "个版本", "message_flow": "消息增长", "message_flow_desc": "观察 Agent 循环执行时消息数组的增长" }, "version": { "loc": "行代码", "tools": "个工具", "new": "新增", "prev": "上一版", "next": "下一版", "view_source": "查看源码", "view_diff": "查看变更", "design_decisions": "设计决策", "whats_new": "新增内容", "tutorial": "教程", "simulator": "Agent 循环模拟器", "execution_flow": "执行流程", "architecture": "架构", "concept_viz": "概念可视化", "alternatives": "替代方案", "tab_learn": "学习", "tab_simulate": "模拟", "tab_code": "源码", "tab_deep_dive": "深入探索" }, "sim": { "play": "播放", "pause": "暂停", "step": "单步", "reset": "重置", "speed": "速度", "step_of": "/" }, - "timeline": { "title": "学习路径", "subtitle": "s01 到 s22:渐进式 Agent Harness 设计", "layer_legend": "层次图例", "loc_growth": "代码量增长", "learn_more": "了解更多" }, + "timeline": { "title": "学习路径", "subtitle": "s01 到 s21:渐进式 Agent Harness 设计", "layer_legend": "层次图例", "loc_growth": "代码量增长", "learn_more": "了解更多" }, "layers": { "title": "架构层次", "subtitle": "五个正交关注点组合成完整的 Agent", @@ -53,14 +53,13 @@ "s12": "Task System", "s13": "Background Tasks", "s14": "Cron Scheduler", - "s15": "Agent Teams:运行时实验", - "s16": "Agent Teams:协议实验", - "s17": "Autonomous Agents", - "s18": "Worktree Isolation", - "s19": "MCP Tools", - "s20": "Comprehensive Agent Turn", - "s21": "Workflow Runtime", - "s22": "Goal Loop" + "s15": "Agent Teams", + "s16": "Autonomous Agents", + "s17": "Worktree Isolation", + "s18": "MCP Tools", + "s19": "Comprehensive Agent", + "s20": "Workflow Runtime", + "s21": "Goal Loop" }, "layer_labels": { "tools": "工具与执行", @@ -84,13 +83,12 @@ "s12": "任务看板依赖", "s13": "Background Task Lanes", "s14": "Cron Scheduler", - "s15": "Agent Teams 运行时实验", - "s16": "Agent Teams 协议实验", - "s17": "Autonomous Agent Cycle", - "s18": "Worktree Task Isolation", - "s19": "MCP Tool Bridge", - "s20": "Comprehensive Agent Turn", - "s21": "Workflow Runtime", - "s22": "目标完成闸门" + "s15": "Agent Teams 与协作协议", + "s16": "Autonomous Agent Cycle", + "s17": "Worktree Task Isolation", + "s18": "MCP Tool Bridge", + "s19": "Comprehensive Agent Turn", + "s20": "Workflow Runtime", + "s21": "目标完成闸门" } } diff --git a/web/src/lib/constants.ts b/web/src/lib/constants.ts index 082002ee..7fb5a563 100644 --- a/web/src/lib/constants.ts +++ b/web/src/lib/constants.ts @@ -22,7 +22,6 @@ export const VERSION_ORDER = [ "s19", "s20", "s21", - "s22", ] as const; export const LEARNING_PATH = VERSION_ORDER; @@ -150,68 +149,60 @@ export const VERSION_META: Record