claude_swarm 1.0.4 → 1.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +24 -0
  3. data/Rakefile +4 -4
  4. data/docs/v2/CHANGELOG.swarm_cli.md +19 -0
  5. data/docs/v2/CHANGELOG.swarm_memory.md +19 -0
  6. data/docs/v2/CHANGELOG.swarm_sdk.md +92 -0
  7. data/docs/v2/README.md +56 -22
  8. data/docs/v2/guides/MEMORY_DEFRAG_GUIDE.md +811 -0
  9. data/docs/v2/guides/complete-tutorial.md +115 -3
  10. data/docs/v2/guides/getting-started.md +6 -6
  11. data/docs/v2/guides/rails-integration.md +6 -6
  12. data/docs/v2/reference/architecture-flow.md +407 -0
  13. data/docs/v2/reference/event_payload_structures.md +471 -0
  14. data/docs/v2/reference/execution-flow.md +600 -0
  15. data/docs/v2/reference/ruby-dsl.md +138 -5
  16. data/docs/v2/reference/swarm_memory_technical_details.md +2090 -0
  17. data/examples/v2/swarm_with_hooks.yml +1 -1
  18. data/lib/claude_swarm/cli.rb +9 -11
  19. data/lib/claude_swarm/commands/ps.rb +1 -2
  20. data/lib/claude_swarm/configuration.rb +2 -3
  21. data/lib/claude_swarm/mcp_generator.rb +4 -10
  22. data/lib/claude_swarm/orchestrator.rb +43 -44
  23. data/lib/claude_swarm/system_utils.rb +4 -4
  24. data/lib/claude_swarm/version.rb +1 -1
  25. data/lib/claude_swarm.rb +4 -9
  26. data/lib/swarm_cli/commands/mcp_serve.rb +2 -2
  27. data/lib/swarm_cli/commands/mcp_tools.rb +3 -3
  28. data/lib/swarm_cli/config_loader.rb +14 -13
  29. data/lib/swarm_cli/version.rb +1 -1
  30. data/lib/swarm_cli.rb +2 -0
  31. data/lib/swarm_memory/adapters/base.rb +4 -4
  32. data/lib/swarm_memory/adapters/filesystem_adapter.rb +0 -12
  33. data/lib/swarm_memory/core/storage.rb +66 -6
  34. data/lib/swarm_memory/integration/sdk_plugin.rb +14 -0
  35. data/lib/swarm_memory/optimization/defragmenter.rb +4 -0
  36. data/lib/swarm_memory/tools/memory_edit.rb +1 -0
  37. data/lib/swarm_memory/tools/memory_glob.rb +24 -1
  38. data/lib/swarm_memory/tools/memory_write.rb +2 -2
  39. data/lib/swarm_memory/version.rb +1 -1
  40. data/lib/swarm_memory.rb +2 -0
  41. data/lib/swarm_sdk/agent/chat.rb +1 -1
  42. data/lib/swarm_sdk/agent/definition.rb +18 -21
  43. data/lib/swarm_sdk/configuration.rb +34 -10
  44. data/lib/swarm_sdk/mcp.rb +16 -0
  45. data/lib/swarm_sdk/node/agent_config.rb +7 -2
  46. data/lib/swarm_sdk/node/builder.rb +130 -35
  47. data/lib/swarm_sdk/node_context.rb +75 -0
  48. data/lib/swarm_sdk/node_orchestrator.rb +219 -12
  49. data/lib/swarm_sdk/plugin.rb +73 -1
  50. data/lib/swarm_sdk/prompts/base_system_prompt.md.erb +0 -126
  51. data/lib/swarm_sdk/result.rb +32 -6
  52. data/lib/swarm_sdk/swarm/builder.rb +1 -0
  53. data/lib/swarm_sdk/swarm.rb +32 -50
  54. data/lib/swarm_sdk/tools/delegate.rb +2 -2
  55. data/lib/swarm_sdk/tools/scratchpad/scratchpad_list.rb +23 -2
  56. data/lib/swarm_sdk/tools/scratchpad/scratchpad_read.rb +23 -2
  57. data/lib/swarm_sdk/tools/scratchpad/scratchpad_write.rb +21 -4
  58. data/lib/swarm_sdk/tools/stores/storage.rb +4 -4
  59. data/lib/swarm_sdk/tools/think.rb +4 -1
  60. data/lib/swarm_sdk/tools/todo_write.rb +20 -8
  61. data/lib/swarm_sdk/version.rb +1 -1
  62. data/lib/swarm_sdk.rb +332 -27
  63. data/swarm_sdk.gemspec +1 -1
  64. metadata +9 -3
@@ -1889,7 +1889,119 @@ input do |ctx|
1889
1889
  end
1890
1890
  ```
1891
1891
 
1892
- ### 5.8 Complex Workflow Example
1892
+ **Control Flow Methods**:
1893
+
1894
+ NodeContext provides three methods for dynamic workflow control:
1895
+
1896
+ **1. goto_node - Jump to any node**:
1897
+ ```ruby
1898
+ output do |ctx|
1899
+ if needs_revision?(ctx.content)
1900
+ # Jump back to revision node instead of continuing forward
1901
+ ctx.goto_node(:revision, content: ctx.content)
1902
+ else
1903
+ ctx.content # Continue to next node normally
1904
+ end
1905
+ end
1906
+ ```
1907
+
1908
+ **2. halt_workflow - Stop entire workflow**:
1909
+ ```ruby
1910
+ output do |ctx|
1911
+ if converged?(ctx.content)
1912
+ # Stop workflow early with final result
1913
+ ctx.halt_workflow(content: ctx.content)
1914
+ else
1915
+ ctx.content # Continue to next node
1916
+ end
1917
+ end
1918
+ ```
1919
+
1920
+ **3. skip_execution - Skip node's LLM call** (input transformers only):
1921
+ ```ruby
1922
+ input do |ctx|
1923
+ cached = check_cache(ctx.content)
1924
+ if cached
1925
+ # Skip expensive LLM call and use cached result
1926
+ ctx.skip_execution(content: cached)
1927
+ else
1928
+ ctx.content # Execute node normally
1929
+ end
1930
+ end
1931
+ ```
1932
+
1933
+ **Creating loops with goto_node**:
1934
+ ```ruby
1935
+ node :reasoning do
1936
+ agent(:thinker, reset_context: false) # Preserve context across iterations
1937
+
1938
+ output do |ctx|
1939
+ # Loop until convergence
1940
+ if ctx.all_results.size > 10
1941
+ ctx.halt_workflow(content: "Max iterations reached")
1942
+ else
1943
+ ctx.goto_node(:reflection, content: ctx.content)
1944
+ end
1945
+ end
1946
+ end
1947
+
1948
+ node :reflection do
1949
+ agent(:critic, reset_context: false)
1950
+
1951
+ output do |ctx|
1952
+ # Loop back to reasoning
1953
+ ctx.goto_node(:reasoning, content: ctx.content)
1954
+ end
1955
+ end
1956
+
1957
+ start_node :reasoning
1958
+ ```
1959
+
1960
+ **Note:** All control flow methods validate that `content` is not nil. If a node fails with an error, check for errors before calling goto_node:
1961
+
1962
+ ```ruby
1963
+ output do |ctx|
1964
+ if ctx.error
1965
+ ctx.halt_workflow(content: "Error: #{ctx.error.message}")
1966
+ else
1967
+ ctx.goto_node(:next_node, content: ctx.content)
1968
+ end
1969
+ end
1970
+ ```
1971
+
1972
+ ### 5.8 Context Preservation Across Nodes
1973
+
1974
+ By default, agents get fresh conversation context in each node (`reset_context: true`). To preserve an agent's conversation history across nodes, use `reset_context: false`:
1975
+
1976
+ ```ruby
1977
+ agent :architect do
1978
+ model "gpt-4"
1979
+ system_prompt "You design systems"
1980
+ end
1981
+
1982
+ node :planning do
1983
+ agent(:architect, reset_context: false) # Preserve context
1984
+ end
1985
+
1986
+ node :revision do
1987
+ agent(:architect, reset_context: false) # Same instance - remembers planning!
1988
+ depends_on :planning
1989
+ end
1990
+ ```
1991
+
1992
+ **When to preserve context:**
1993
+ - Iterative refinement workflows
1994
+ - Agent builds on its previous decisions
1995
+ - Chain of thought reasoning across stages
1996
+ - Self-reflection loops
1997
+
1998
+ **When to reset context (default):**
1999
+ - Independent validation/review
2000
+ - Fresh perspective needed
2001
+ - Memory management in long workflows
2002
+ - Different roles for same agent in different stages
2003
+
2004
+ ### 5.9 Complex Workflow Example
1893
2005
 
1894
2006
  **Multi-stage development pipeline**:
1895
2007
 
@@ -2523,7 +2635,7 @@ end
2523
2635
  SwarmSDK validates configurations and emits warnings:
2524
2636
 
2525
2637
  ```ruby
2526
- swarm = SwarmSDK::Swarm.load("config.yml")
2638
+ swarm = SwarmSDK.load_file("config.yml")
2527
2639
 
2528
2640
  # Check for warnings
2529
2641
  warnings = swarm.validate
@@ -2723,7 +2835,7 @@ end
2723
2835
  **Integration test workflows**:
2724
2836
  ```ruby
2725
2837
  RSpec.describe "Development Pipeline" do
2726
- let(:swarm) { SwarmSDK::Swarm.load("swarm.yml") }
2838
+ let(:swarm) { SwarmSDK.load_file("swarm.yml") }
2727
2839
 
2728
2840
  it "completes full workflow" do
2729
2841
  result = swarm.execute("Build auth system")
@@ -303,7 +303,7 @@ agents:
303
303
  require 'swarm_sdk'
304
304
 
305
305
  # Load swarm from YAML (which references the Markdown file)
306
- swarm = SwarmSDK::Swarm.load('swarm.yml')
306
+ swarm = SwarmSDK.load_file('swarm.yml')
307
307
  result = swarm.execute("Your task here")
308
308
  ```
309
309
 
@@ -359,7 +359,7 @@ Create a file called `run.rb`:
359
359
  require 'swarm_sdk'
360
360
 
361
361
  # Load swarm from YAML
362
- swarm = SwarmSDK::Swarm.load('swarm.yml')
362
+ swarm = SwarmSDK.load_file('swarm.yml')
363
363
 
364
364
  # Execute a task
365
365
  result = swarm.execute("What is 2 + 2?")
@@ -433,7 +433,7 @@ Create `run.rb`:
433
433
  require 'swarm_sdk'
434
434
 
435
435
  # Load swarm from YAML (which references the Markdown file)
436
- swarm = SwarmSDK::Swarm.load('swarm.yml')
436
+ swarm = SwarmSDK.load_file('swarm.yml')
437
437
 
438
438
  # Execute a task
439
439
  result = swarm.execute("What is 2 + 2?")
@@ -705,7 +705,7 @@ swarm:
705
705
 
706
706
  Then load and use:
707
707
  ```ruby
708
- swarm = SwarmSDK::Swarm.load('swarm.yml')
708
+ swarm = SwarmSDK.load_file('swarm.yml')
709
709
  result = swarm.execute("Write a function to validate email addresses and get it reviewed")
710
710
  ```
711
711
 
@@ -1292,7 +1292,7 @@ swarm:
1292
1292
  ```ruby
1293
1293
  # run.rb
1294
1294
  require 'swarm_sdk'
1295
- swarm = SwarmSDK::Swarm.load('swarm.yml')
1295
+ swarm = SwarmSDK.load_file('swarm.yml')
1296
1296
  result = swarm.execute("Your task here")
1297
1297
  puts result.content if result.success?
1298
1298
  ```
@@ -1327,7 +1327,7 @@ swarm:
1327
1327
  ```ruby
1328
1328
  # run.rb
1329
1329
  require 'swarm_sdk'
1330
- swarm = SwarmSDK::Swarm.load('swarm.yml')
1330
+ swarm = SwarmSDK.load_file('swarm.yml')
1331
1331
  result = swarm.execute("Your task here")
1332
1332
  ```
1333
1333
 
@@ -125,7 +125,7 @@ swarm:
125
125
  class SwarmLoader
126
126
  def self.load(name)
127
127
  config_path = Rails.root.join('config', 'swarms', "#{name}.yml")
128
- SwarmSDK::Swarm.load(config_path)
128
+ SwarmSDK.load_file(config_path)
129
129
  end
130
130
  end
131
131
 
@@ -161,7 +161,7 @@ class CodeReviewJob < ApplicationJob
161
161
  pr = PullRequest.find(pull_request_id)
162
162
 
163
163
  # Load swarm configuration
164
- swarm = SwarmSDK::Swarm.load(
164
+ swarm = SwarmSDK.load_file(
165
165
  Rails.root.join('config', 'swarms', 'code_reviewer.yml')
166
166
  )
167
167
 
@@ -489,7 +489,7 @@ end
489
489
  namespace :content do
490
490
  desc "Batch update product descriptions"
491
491
  task update_descriptions: :environment do
492
- swarm = SwarmSDK::Swarm.load(
492
+ swarm = SwarmSDK.load_file(
493
493
  Rails.root.join('config', 'swarms', 'product_writer.yml')
494
494
  )
495
495
 
@@ -710,7 +710,7 @@ class SwarmLoader
710
710
  # Fallback to base config if env-specific doesn't exist
711
711
  config_path = Rails.root.join('config', 'swarms', "#{name}.yml") unless File.exist?(config_path)
712
712
 
713
- SwarmSDK::Swarm.load(config_path)
713
+ SwarmSDK.load_file(config_path)
714
714
  end
715
715
  end
716
716
  ```
@@ -1077,7 +1077,7 @@ RSpec.configure do |config|
1077
1077
  config.before(:each, type: :swarm) do
1078
1078
  # Use test swarm configs
1079
1079
  allow(SwarmLoader).to receive(:load) do |name|
1080
- SwarmSDK::Swarm.load(
1080
+ SwarmSDK.load_file(
1081
1081
  Rails.root.join('spec', 'fixtures', 'swarms', "#{name}.yml")
1082
1082
  )
1083
1083
  end
@@ -1637,7 +1637,7 @@ class CodeReviewJob < ApplicationJob
1637
1637
  pr = PullRequest.find(pr_id)
1638
1638
  pr.update!(status: :reviewing)
1639
1639
 
1640
- swarm = SwarmSDK::Swarm.load(
1640
+ swarm = SwarmSDK.load_file(
1641
1641
  Rails.root.join('config', 'swarms', 'code_reviewer.yml')
1642
1642
  )
1643
1643
 
@@ -0,0 +1,407 @@
1
+ # SwarmSDK Architecture Flow
2
+
3
+ This document provides a comprehensive flowchart showing how SwarmSDK, SwarmCLI, and SwarmMemory work together.
4
+
5
+ ## Complete System Flow
6
+
7
+ ```mermaid
8
+ flowchart TB
9
+ subgraph "Entry Points"
10
+ CLI["CLI: swarm run config.yml -p 'task'"]
11
+ SDK_DSL["SDK: SwarmSDK.build { }"]
12
+ SDK_YAML["SDK: SwarmSDK.load_file(path)"]
13
+ SDK_YAML_STR["SDK: SwarmSDK.load(yaml, base_dir:)"]
14
+ SDK_VALIDATE["SDK: SwarmSDK.validate(yaml)"]
15
+ end
16
+
17
+ subgraph "SwarmCLI Layer"
18
+ CLI_START["CLI.start (Thor)"]
19
+ CLI_CMDS["Commands::Run"]
20
+ CONFIG_LOADER["ConfigLoader"]
21
+ REPL["InteractiveREPL"]
22
+ FORMATTER["HumanFormatter/JsonFormatter"]
23
+ end
24
+
25
+ subgraph "Configuration Layer"
26
+ BUILDER["Swarm::Builder<br/>(DSL parser)"]
27
+ CONFIGURATION["Configuration<br/>(YAML parser)"]
28
+ MARKDOWN["MarkdownParser<br/>(agent files)"]
29
+ VALIDATE_FLOW["Validation<br/>(error parsing)"]
30
+ end
31
+
32
+ subgraph "Core SwarmSDK Layer"
33
+ SWARM["Swarm Instance"]
34
+ AGENT_DEF["Agent::Definition<br/>(validation, system prompts)"]
35
+ SWARM_EXEC["Swarm.execute(prompt)"]
36
+ HOOKS_ADAPTER["Hooks::Adapter<br/>(YAML → Ruby hooks)"]
37
+ end
38
+
39
+ subgraph "Agent Initialization (5-Pass)"
40
+ INIT["AgentInitializer"]
41
+ PASS1["Pass 1: Create Agent::Chat<br/>+ ToolConfigurator<br/>+ McpConfigurator"]
42
+ PASS2["Pass 2: Register<br/>delegation tools"]
43
+ PASS3["Pass 3: Setup<br/>Agent::Context"]
44
+ PASS4["Pass 4: Configure<br/>hook system"]
45
+ PASS5["Pass 5: Apply<br/>YAML hooks"]
46
+ end
47
+
48
+ subgraph "Agent Execution Layer"
49
+ LEAD_AGENT["Lead Agent::Chat"]
50
+ AGENT_ASK["Agent::Chat.ask(prompt)"]
51
+ HOOK_INTEGRATION["HookIntegration<br/>(user_prompt hooks)"]
52
+ RUBY_LLM["RubyLLM::Chat<br/>(LLM API calls)"]
53
+ RATE_LIMIT["Rate Limiting<br/>(Global + Local Semaphores)"]
54
+ end
55
+
56
+ subgraph "Tool Execution Layer"
57
+ TOOL_EXEC["Parallel Tool Execution<br/>(Async fibers)"]
58
+ TOOL_HOOKS["Pre/Post Tool Hooks"]
59
+ TOOL_PERMS["Permissions Wrapper<br/>(path/command validation)"]
60
+ TOOL_INSTANCES["Tool Instances"]
61
+ end
62
+
63
+ subgraph "Tool Types"
64
+ FILE_TOOLS["File Tools<br/>(Read, Write, Edit, Glob, Grep)"]
65
+ BASH_TOOL["Bash Tool"]
66
+ DELEGATE_TOOL["Delegation Tools<br/>(call other agents)"]
67
+ PLUGIN_TOOLS["Plugin Tools<br/>(from PluginRegistry)"]
68
+ DEFAULT_TOOLS["Default Tools<br/>(Think, TodoWrite, Clock)"]
69
+ SCRATCHPAD["Scratchpad Tools<br/>(volatile storage)"]
70
+ end
71
+
72
+ subgraph "SwarmMemory Plugin"
73
+ MEMORY_PLUGIN["SwarmMemory::Integration::SDKPlugin"]
74
+ MEMORY_STORAGE["Storage<br/>(orchestrates operations)"]
75
+ ADAPTER["FilesystemAdapter<br/>(persistence)"]
76
+ EMBEDDER["InformersEmbedder<br/>(ONNX models)"]
77
+ SEMANTIC_INDEX["SemanticIndex<br/>(FAISS vector search)"]
78
+ MEMORY_TOOLS["Memory Tools<br/>(MemoryWrite, MemoryRead,<br/>MemoryEdit, MemoryGrep, etc.)"]
79
+ LOAD_SKILL["LoadSkill Tool<br/>(dynamic tool swapping)"]
80
+ end
81
+
82
+ subgraph "Logging & Events"
83
+ LOG_STREAM["LogStream<br/>(event emitter)"]
84
+ LOG_COLLECTOR["LogCollector<br/>(aggregates events)"]
85
+ LOG_EVENTS["Events: swarm_start, user_prompt,<br/>tool_call, tool_result,<br/>agent_step, agent_stop, swarm_stop"]
86
+ end
87
+
88
+ subgraph "Hooks System"
89
+ HOOK_REGISTRY["Hooks::Registry<br/>(named hooks + defaults)"]
90
+ HOOK_EXECUTOR["Hooks::Executor<br/>(chains hooks)"]
91
+ HOOK_SHELL["Hooks::ShellExecutor<br/>(runs shell commands)"]
92
+ HOOK_EVENTS["Events: swarm_start, swarm_stop,<br/>pre_tool_use, post_tool_use,<br/>user_prompt, pre_delegation, etc."]
93
+ end
94
+
95
+ subgraph "Node Workflows"
96
+ NODE_ORCH["NodeOrchestrator<br/>(multi-stage execution)"]
97
+ NODE_CTX["NodeContext<br/>(goto_node, halt_workflow, skip_execution)"]
98
+ TRANSFORMERS["Bash/Ruby Transformers<br/>(input/output transformation)"]
99
+ MINI_SWARMS["Mini-Swarms<br/>(one per node)"]
100
+ end
101
+
102
+ subgraph "Result Flow"
103
+ RESULT["Result Object<br/>(content, logs, cost, tokens)"]
104
+ RETURN["Return to User"]
105
+ end
106
+
107
+ %% Entry point connections
108
+ CLI --> CLI_START
109
+ CLI_START --> CLI_CMDS
110
+ CLI_CMDS --> CONFIG_LOADER
111
+ CONFIG_LOADER --> SDK_YAML
112
+ CONFIG_LOADER --> SDK_DSL
113
+ SDK_DSL --> BUILDER
114
+ SDK_YAML --> CONFIGURATION
115
+ SDK_YAML_STR --> CONFIGURATION
116
+ SDK_VALIDATE --> VALIDATE_FLOW
117
+ VALIDATE_FLOW --> CONFIGURATION
118
+ VALIDATE_FLOW --> RETURN
119
+
120
+ %% Configuration flow
121
+ BUILDER --> AGENT_DEF
122
+ CONFIGURATION --> AGENT_DEF
123
+ CONFIGURATION --> MARKDOWN
124
+ MARKDOWN --> AGENT_DEF
125
+ AGENT_DEF --> SWARM
126
+
127
+ %% Hooks adapter
128
+ CONFIGURATION --> HOOKS_ADAPTER
129
+ HOOKS_ADAPTER --> HOOK_REGISTRY
130
+
131
+ %% Swarm creation
132
+ SWARM --> AGENT_DEF
133
+ SWARM --> HOOK_REGISTRY
134
+
135
+ %% Execution flow
136
+ CLI_CMDS --> REPL
137
+ CLI_CMDS --> SWARM_EXEC
138
+ REPL --> SWARM_EXEC
139
+ SWARM_EXEC --> INIT
140
+
141
+ %% Agent initialization
142
+ INIT --> PASS1
143
+ PASS1 --> LEAD_AGENT
144
+ PASS1 --> TOOL_CONFIGURATOR["ToolConfigurator"]
145
+ PASS1 --> MCP_CONFIGURATOR["McpConfigurator"]
146
+ TOOL_CONFIGURATOR --> TOOL_INSTANCES
147
+ TOOL_CONFIGURATOR --> MEMORY_PLUGIN
148
+ MCP_CONFIGURATOR --> MCP_SERVERS["MCP Servers"]
149
+ PASS1 --> PASS2
150
+ PASS2 --> PASS3
151
+ PASS3 --> PASS4
152
+ PASS4 --> PASS5
153
+
154
+ %% Lead agent execution
155
+ SWARM_EXEC --> LEAD_AGENT
156
+ LEAD_AGENT --> AGENT_ASK
157
+ AGENT_ASK --> HOOK_INTEGRATION
158
+ HOOK_INTEGRATION --> HOOK_EXECUTOR
159
+ HOOK_INTEGRATION --> RATE_LIMIT
160
+ RATE_LIMIT --> RUBY_LLM
161
+
162
+ %% LLM response and tool calling
163
+ RUBY_LLM --> TOOL_EXEC
164
+ TOOL_EXEC --> TOOL_HOOKS
165
+ TOOL_HOOKS --> HOOK_EXECUTOR
166
+ TOOL_HOOKS --> TOOL_PERMS
167
+ TOOL_PERMS --> TOOL_INSTANCES
168
+
169
+ %% Tool types
170
+ TOOL_INSTANCES --> FILE_TOOLS
171
+ TOOL_INSTANCES --> BASH_TOOL
172
+ TOOL_INSTANCES --> DELEGATE_TOOL
173
+ TOOL_INSTANCES --> PLUGIN_TOOLS
174
+ TOOL_INSTANCES --> DEFAULT_TOOLS
175
+ TOOL_INSTANCES --> SCRATCHPAD
176
+
177
+ %% Delegation
178
+ DELEGATE_TOOL --> AGENT_ASK
179
+
180
+ %% Plugin tools
181
+ PLUGIN_TOOLS --> MEMORY_TOOLS
182
+ MEMORY_TOOLS --> MEMORY_STORAGE
183
+ MEMORY_STORAGE --> ADAPTER
184
+ MEMORY_STORAGE --> SEMANTIC_INDEX
185
+ SEMANTIC_INDEX --> EMBEDDER
186
+ MEMORY_PLUGIN --> LOAD_SKILL
187
+ LOAD_SKILL --> LEAD_AGENT
188
+
189
+ %% Tool results flow back
190
+ TOOL_INSTANCES --> TOOL_HOOKS
191
+ TOOL_HOOKS --> HOOK_EXECUTOR
192
+ TOOL_HOOKS --> RUBY_LLM
193
+
194
+ %% Logging throughout
195
+ SWARM_EXEC --> LOG_STREAM
196
+ AGENT_ASK --> LOG_STREAM
197
+ TOOL_EXEC --> LOG_STREAM
198
+ LOG_STREAM --> LOG_COLLECTOR
199
+ LOG_COLLECTOR --> FORMATTER
200
+ LOG_COLLECTOR --> RESULT
201
+
202
+ %% Hook execution
203
+ HOOK_EXECUTOR --> HOOK_REGISTRY
204
+ HOOK_EXECUTOR --> HOOK_SHELL
205
+ HOOK_EXECUTOR --> HOOK_RESULT["Hooks::Result"]
206
+ HOOK_RESULT --> SWARM_EXEC
207
+
208
+ %% Node workflows
209
+ SWARM --> NODE_ORCH
210
+ NODE_ORCH --> MINI_SWARMS
211
+ MINI_SWARMS --> TRANSFORMERS
212
+ TRANSFORMERS --> NODE_CTX
213
+ NODE_CTX --> NODE_ORCH
214
+ MINI_SWARMS --> NODE_ORCH
215
+ NODE_ORCH --> RESULT
216
+
217
+ %% Final result
218
+ SWARM_EXEC --> HOOK_EXECUTOR
219
+ SWARM_EXEC --> RESULT
220
+ RESULT --> FORMATTER
221
+ FORMATTER --> RETURN
222
+
223
+ %% Styling
224
+ classDef entryPoint fill:#e1f5ff,stroke:#0366d6,stroke-width:2px
225
+ classDef cli fill:#fff5e1,stroke:#f9a825,stroke-width:2px
226
+ classDef config fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
227
+ classDef core fill:#fce4ec,stroke:#e91e63,stroke-width:2px
228
+ classDef agent fill:#f3e5f5,stroke:#9c27b0,stroke-width:2px
229
+ classDef tool fill:#e0f2f1,stroke:#009688,stroke-width:2px
230
+ classDef memory fill:#fff3e0,stroke:#ff9800,stroke-width:2px
231
+ classDef logging fill:#e3f2fd,stroke:#2196f3,stroke-width:2px
232
+ classDef hooks fill:#fce4ec,stroke:#e91e63,stroke-width:2px
233
+
234
+ class CLI,SDK_DSL,SDK_YAML,SDK_YAML_STR,SDK_VALIDATE entryPoint
235
+ class CLI_START,CLI_CMDS,CONFIG_LOADER,REPL,FORMATTER cli
236
+ class BUILDER,CONFIGURATION,MARKDOWN,VALIDATE_FLOW config
237
+ class SWARM,AGENT_DEF,SWARM_EXEC,HOOKS_ADAPTER,NODE_ORCH,NODE_CTX,TRANSFORMERS,MINI_SWARMS core
238
+ class INIT,PASS1,PASS2,PASS3,PASS4,PASS5,LEAD_AGENT,AGENT_ASK,HOOK_INTEGRATION,RUBY_LLM,RATE_LIMIT agent
239
+ class TOOL_EXEC,TOOL_HOOKS,TOOL_PERMS,TOOL_INSTANCES,FILE_TOOLS,BASH_TOOL,DELEGATE_TOOL,PLUGIN_TOOLS,DEFAULT_TOOLS,SCRATCHPAD,TOOL_CONFIGURATOR,MCP_CONFIGURATOR,MCP_SERVERS tool
240
+ class MEMORY_PLUGIN,MEMORY_STORAGE,ADAPTER,EMBEDDER,SEMANTIC_INDEX,MEMORY_TOOLS,LOAD_SKILL memory
241
+ class LOG_STREAM,LOG_COLLECTOR,LOG_EVENTS logging
242
+ class HOOK_REGISTRY,HOOK_EXECUTOR,HOOK_SHELL,HOOK_EVENTS,HOOK_RESULT hooks
243
+ class RESULT,RETURN core
244
+ ```
245
+
246
+ ## Key Flow Sequences
247
+
248
+ ### 1. CLI Execution Flow
249
+ ```
250
+ User → CLI → ConfigLoader → SwarmSDK.load_file → Configuration → Swarm → Execute → Formatter → User
251
+ ```
252
+
253
+ ### 2. SDK Direct Usage Flow
254
+ ```
255
+ Code → SwarmSDK.build/load → Swarm → execute(prompt) → Result → Code
256
+ ```
257
+
258
+ ### 3. Agent Initialization (Lazy, 5-Pass)
259
+ ```
260
+ Swarm.execute → AgentInitializer →
261
+ Pass 1: Create chats + tools + MCP →
262
+ Pass 2: Delegation tools →
263
+ Pass 3: Contexts →
264
+ Pass 4: Hooks →
265
+ Pass 5: YAML hooks
266
+ ```
267
+
268
+ ### 4. Agent Execution Flow
269
+ ```
270
+ Agent.ask(prompt) →
271
+ user_prompt hooks →
272
+ RubyLLM (rate limited) →
273
+ Tool calls →
274
+ pre_tool_use hooks →
275
+ Tool execution (with permissions) →
276
+ post_tool_use hooks →
277
+ Results to LLM →
278
+ agent_step/agent_stop events
279
+ ```
280
+
281
+ ### 5. Tool Execution Types
282
+ - **File Tools**: Read/Write/Edit/Glob/Grep → PathResolver → Permissions → File I/O
283
+ - **Bash Tool**: Execute shell commands
284
+ - **Delegation Tools**: Recursively call other Agent::Chat instances
285
+ - **Plugin Tools**: PluginRegistry → create_tool → (e.g., MemoryWrite → Storage)
286
+ - **Default Tools**: Think (reasoning), TodoWrite (task mgmt), Clock (time)
287
+ - **Scratchpad Tools**: Volatile shared storage across agents
288
+
289
+ ### 6. Memory Integration Flow
290
+ ```
291
+ MemoryWrite tool →
292
+ Storage.write →
293
+ MetadataExtractor (frontmatter) →
294
+ InformersEmbedder (ONNX) →
295
+ SemanticIndex (FAISS) →
296
+ FilesystemAdapter (JSON persistence)
297
+ ```
298
+
299
+ ### 7. Logging Flow
300
+ ```
301
+ All components → LogStream.emit → LogCollector →
302
+ [swarm.execute block callback] →
303
+ Formatter → User output
304
+ ```
305
+
306
+ ### 8. Hooks Flow
307
+ ```
308
+ Event occurs →
309
+ Hooks::Executor →
310
+ Registry (get hooks) →
311
+ Execute (chain hooks) →
312
+ ShellExecutor (for YAML) →
313
+ Hooks::Result (halt/replace/continue) →
314
+ Control flow decision
315
+ ```
316
+
317
+ ### 9. Node Workflow Flow
318
+ ```
319
+ NodeOrchestrator.execute →
320
+ Build execution order (topological sort) →
321
+ For each node:
322
+ Input transformer (Bash/Ruby) →
323
+ Create mini-swarm →
324
+ Execute →
325
+ NodeContext (goto_node/halt/skip) →
326
+ Output to next node →
327
+ Final result
328
+ ```
329
+
330
+ ## Component Responsibilities
331
+
332
+ ### SwarmSDK Core
333
+ - **Swarm**: Main orchestrator, agent management, execution lifecycle
334
+ - **Configuration**: YAML parsing, validation, agent file loading
335
+ - **Agent::Definition**: Configuration validation, system prompt building
336
+ - **Agent::Chat**: LLM interaction, tool calling, rate limiting, hooks
337
+ - **AgentInitializer**: Complex 5-pass initialization (tools, MCP, delegation, hooks)
338
+ - **ToolConfigurator**: Tool registration, creation, permissions wrapping
339
+ - **McpConfigurator**: MCP client management, external tool integration
340
+ - **NodeOrchestrator**: Multi-stage workflows with transformers
341
+ - **Plugin System**: Extensibility framework (SwarmMemory uses this)
342
+
343
+ ### SwarmCLI
344
+ - **CLI**: Thor-based command parser
345
+ - **Commands::Run**: Execute swarms (interactive or non-interactive)
346
+ - **InteractiveREPL**: Reline-based conversational interface
347
+ - **ConfigLoader**: Detects and loads YAML/Ruby DSL files
348
+ - **HumanFormatter**: TTY toolkit rendering (Markdown, Box, Spinner, Pastel)
349
+ - **JsonFormatter**: Structured JSON output for automation
350
+
351
+ ### SwarmMemory
352
+ - **SDKPlugin**: SwarmSDK plugin implementation
353
+ - **Storage**: Orchestrates adapter, embedder, semantic index
354
+ - **FilesystemAdapter**: JSON-based persistence
355
+ - **InformersEmbedder**: Fast local ONNX embeddings
356
+ - **SemanticIndex**: FAISS-based vector similarity search
357
+ - **Memory Tools**: MemoryWrite, MemoryRead, MemoryEdit, MemoryGrep, MemoryGlob, MemoryDelete, MemoryDefrag
358
+ - **LoadSkill**: Dynamic tool loading with semantic discovery
359
+
360
+ ### Supporting Systems
361
+ - **Hooks**: Registry → Executor → ShellExecutor (YAML) or Ruby blocks (DSL)
362
+ - **Logging**: LogStream → LogCollector → Formatters
363
+ - **Permissions**: Path-based (Read/Write) and command-based (Bash) validation
364
+ - **Rate Limiting**: Two-level semaphores (global + per-agent)
365
+ - **MCP Integration**: RubyLLM::MCP client for external tools
366
+
367
+ ## Data Flow
368
+
369
+ ### Configuration → Swarm
370
+ ```
371
+ YAML/DSL → Configuration/Builder → Agent::Definition[] → Swarm → (lazy) AgentInitializer → Agent::Chat[]
372
+ ```
373
+
374
+ ### Execution → Result
375
+ ```
376
+ User prompt → Swarm.execute → Hooks → Lead Agent → LLM → Tools → Hooks → Result → User
377
+ ```
378
+
379
+ ### Memory Operations
380
+ ```
381
+ MemoryWrite → Storage → Embedder → SemanticIndex → Adapter → File system
382
+ MemoryGrep → Storage → SemanticIndex.search → Results
383
+ ```
384
+
385
+ ## Concurrency Model
386
+
387
+ - **Async Reactor**: All execution within `Async { }` blocks (Fiber scheduler)
388
+ - **Global Semaphore**: Limits total concurrent LLM calls across all agents
389
+ - **Local Semaphore**: Limits concurrent tool calls per agent
390
+ - **Parallel Tool Execution**: Tools execute concurrently within semaphore limits
391
+ - **Fiber-Safe Logging**: LogStream designed for concurrent access
392
+
393
+ ## Plugin Architecture
394
+
395
+ ```
396
+ Plugin Registration → PluginRegistry
397
+
398
+ Plugin Lifecycle Hooks:
399
+ - on_agent_initialized (create storage, register tools)
400
+ - on_user_message (semantic skill discovery)
401
+ - system_prompt_contribution (add memory guidance)
402
+ - serialize_config (preserve config when cloning)
403
+
404
+ Tool Creation: plugin.create_tool(tool_name, context)
405
+
406
+ Tool execution within Agent::Chat
407
+ ```