Skip to content

Commit 0449368

Browse files
committed
Initial release: parallel multi-agent swarm with G-Memory
Full implementation of the Blitz-Swarm architecture: - Parallel agent invocation via asyncio + subprocess (Claude CLI) - 5 agent roles: Researcher, Critic, Fact-Checker, Quality Judge, Synthesizer - LLM-powered dynamic agent planning (count + subtopics per topic) - Iterative consensus loop with holdout override and dissent preservation - Redis blackboard for live agent coordination (optional, --no-redis mode) - G-Memory three-tier hierarchical memory (NeurIPS 2025): - Tier 1: Interaction graphs (raw agent traces) - Tier 2: Query graph (task-level semantic links) - Tier 3: Insight graph (LLM-distilled cross-task wisdom) - SQLite+WAL persistence with single-writer serialization - LanceDB vector search for query similarity (MiniLM 384-dim) - Memory eviction (query archival, interaction purging) - TOML configuration (blitz.toml)
0 parents  commit 0449368

17 files changed

Lines changed: 3244 additions & 0 deletions

.gitignore

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
__pycache__/
2+
*.pyc
3+
*.pyo
4+
.DS_Store
5+
output/
6+
*.db
7+
memory_vectors/
8+
.venv/
9+
*.egg-info/
10+
dist/
11+
build/
12+
compass_artifact_*.md

BLITZ-SWARM.md

Lines changed: 271 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,271 @@
1+
# BLITZ-SWARM
2+
3+
> A parallel multi-agent swarm architecture for collective AI intelligence.
4+
> All agents live. All agents share memory. All agents iterate together until consensus.
5+
6+
---
7+
8+
## What This Is
9+
10+
Blitz-Swarm is an open-source, parallel multi-agent system built on three principles:
11+
12+
**No waves.** Traditional agent pipelines run in sequential waves — one tier finishes before the next starts. Blitz-Swarm fires all agents simultaneously. Every agent reads from and writes to a shared live blackboard. The swarm thinks as a unit, not a pipeline.
13+
14+
**Shared hierarchical memory.** Agents don't just coordinate — they accumulate. Every task the swarm completes makes it smarter on future tasks. Memory is organized across three tiers (interaction traces, query patterns, distilled insights) using the G-Memory architecture (NeurIPS 2025).
15+
16+
**Consensus-driven convergence.** The swarm doesn't stop on a timer or after a fixed number of rounds. It stops when all agents agree the output meets quality bar. Dissent is preserved, not suppressed.
17+
18+
This is infrastructure for the AI field. Not a wrapper. Not a product. A reference architecture for how parallel agent swarms should work.
19+
20+
---
21+
22+
## First Target Task: Research + Summarize a Technical Topic
23+
24+
Given a topic string, Blitz-Swarm deploys a parallel agent swarm that collectively researches, cross-validates, critiques, and synthesizes a high-quality technical summary.
25+
26+
No single agent produces the output. The output *emerges* from the swarm's collective iteration over shared memory.
27+
28+
**Output format:** Structured markdown — core concepts, key findings, implementation implications, open questions, source confidence ratings, and a dissent section preserving minority views.
29+
30+
---
31+
32+
## How Agents Are Defined
33+
34+
Agent count is **dynamic — decided by the orchestrator at runtime based on task complexity.** The orchestrator analyzes the topic, estimates domain breadth, and spawns the minimum number of agents needed to achieve coverage without redundancy.
35+
36+
### Agent Roles
37+
38+
| Role | Count | Responsibility |
39+
|------|-------|----------------|
40+
| **Researcher** | 2–4 | Deep-dives into an assigned subtopic. Writes findings to blackboard. |
41+
| **Critic** | 1–2 | Reads all researcher outputs. Flags gaps, contradictions, low-confidence claims. |
42+
| **Synthesizer** | 1 | Integrates all findings into a coherent structured summary. |
43+
| **Fact-Checker** | 1 | Cross-validates specific claims across researcher outputs. |
44+
| **Quality Judge** | 1 | Scores synthesized output on coverage, accuracy, clarity, depth. Casts consensus vote. |
45+
46+
**Typical spawn count:** 6–8 agents for a standard technical topic.
47+
For a narrow topic (e.g. "SQLite WAL mode internals"): 4 agents.
48+
For a broad topic (e.g. "multi-agent memory architectures"): up to 12 agents.
49+
50+
### Agent Definition Schema
51+
52+
```python
53+
@dataclass
54+
class BlitzAgent:
55+
id: str # e.g. "researcher_01"
56+
role: str # "researcher" | "critic" | "synthesizer" | "fact_checker" | "quality_judge"
57+
subtopic: str # Assigned scope (e.g. "embedding strategies for memory retrieval")
58+
system_prompt: str # Full role instruction injected at invocation
59+
max_iterations: int = 3 # Max rounds this agent participates in
60+
```
61+
62+
---
63+
64+
## Subprocess Architecture
65+
66+
Blitz-Swarm agents are **stateless CLI invocations.** The orchestrator is the only persistent process — it owns all state, all memory, all coordination. Agents receive context in their prompt and return structured output. They never touch storage directly.
67+
68+
This design is model-agnostic. Any CLI-invocable model works as an agent backend.
69+
70+
### Invocation Pattern
71+
72+
```python
73+
import subprocess
74+
75+
def invoke_agent(agent: BlitzAgent, context: str, task: str) -> str:
76+
prompt = f"""
77+
{agent.system_prompt}
78+
79+
## Your Assigned Subtopic
80+
{agent.subtopic}
81+
82+
## Shared Memory Context (current blackboard state)
83+
{context}
84+
85+
## Task
86+
{task}
87+
88+
## Output Format
89+
Provide your findings, then close with a memory block:
90+
```memory
91+
{{
92+
"key_findings": ["finding 1", "finding 2"],
93+
"confidence": 0.0-1.0,
94+
"gaps_identified": ["gap 1"],
95+
"quality_vote": "ready" | "needs_work",
96+
"quality_notes": "reason for vote"
97+
}}
98+
```
99+
"""
100+
result = subprocess.run(
101+
["claude", "-p", prompt],
102+
capture_output=True, text=True, timeout=120
103+
)
104+
return result.stdout
105+
```
106+
107+
### Orchestrator Lifecycle
108+
109+
```
110+
1. SPAWN — Analyze topic, define agents, initialize blackboard
111+
2. BLAST — All agents invoked simultaneously via asyncio.gather()
112+
3. WRITE — Agent outputs parsed, memory blocks queued to Redis Stream
113+
4. CONSOLIDATE — MemoryWriter commits to SQLite + LanceDB, updates G-Memory tiers
114+
5. CHECK — Evaluate consensus across all quality votes
115+
6. ITERATE — If no consensus: re-invoke agents with updated blackboard context
116+
7. FINALIZE — Synthesizer produces final document, output saved to disk
117+
```
118+
119+
### Parallel Invocation
120+
121+
```python
122+
import asyncio
123+
124+
async def blast_all_agents(agents: list[BlitzAgent], context: str, task: str):
125+
tasks = [
126+
asyncio.to_thread(invoke_agent, agent, context, task)
127+
for agent in agents
128+
]
129+
return await asyncio.gather(*tasks)
130+
```
131+
132+
All agents receive the **same blackboard snapshot** at the start of each round. No agent waits for another. Between rounds, the orchestrator consolidates all outputs before the next blast.
133+
134+
---
135+
136+
## Convergence Condition
137+
138+
**Blitz-Swarm stops when all voting agents reach unanimous "ready" consensus.**
139+
140+
### Consensus Algorithm
141+
142+
```python
143+
def check_consensus(agent_outputs: list[dict]) -> bool:
144+
voters = [o for o in agent_outputs if o.get("quality_vote") is not None]
145+
if not voters:
146+
return False
147+
return all(v["quality_vote"] == "ready" for v in voters)
148+
```
149+
150+
### Convergence Rules
151+
152+
| Condition | Action |
153+
|-----------|--------|
154+
| All voters say `"ready"` | ✅ Converged — finalize output |
155+
| Any voter says `"needs_work"` | 🔄 Re-iterate with updated blackboard |
156+
| Max iterations reached (default: 5) | ⚠️ Force-finalize with quality warning |
157+
| One holdout after 3 rounds, all others ready | 🔍 Override + log dissent |
158+
159+
### What Triggers "needs_work"
160+
161+
- Factual contradiction between researcher outputs not yet resolved
162+
- Critical subtopic with zero coverage
163+
- Synthesizer output that misrepresents a finding
164+
- Confidence below 0.6 on a core claim
165+
166+
### Dissent Preservation
167+
168+
Every `"needs_work"` vote and `quality_notes` entry is preserved in the final output under `## Dissent & Open Questions`. The swarm surfaces disagreement rather than hiding it. Minority views are first-class output.
169+
170+
---
171+
172+
## Memory Architecture
173+
174+
Blitz-Swarm implements G-Memory's three-tier hierarchical memory (NeurIPS 2025, arXiv 2506.07398), adapted for a subprocess-based parallel swarm.
175+
176+
### Storage Stack
177+
178+
| Layer | Technology | Purpose |
179+
|-------|------------|---------|
180+
| Working memory | Redis (Hash + Streams + Pub/Sub) | Live blackboard, write queue, event bus |
181+
| Persistent graphs | SQLite + WAL | G-Memory three tiers (Interaction, Query, Insight graphs) |
182+
| Semantic retrieval | LanceDB (embedded) | Vector similarity search for query recall |
183+
| Embedding model | all-MiniLM-L6-v2 (384-dim) | Loaded once in orchestrator, never in agents |
184+
185+
### The Three Memory Tiers
186+
187+
**Tier 1 — Interaction Graph:** Raw agent communication traces per task. Every utterance, every causal link between outputs. The finest-grained record of how the swarm solved a problem.
188+
189+
**Tier 2 — Query Graph:** Task-level nodes connected by semantic similarity. 1-hop expansion at retrieval time surfaces related past tasks without noise (2+ hops degrade performance).
190+
191+
**Tier 3 — Insight Graph:** LLM-distilled generalizations extracted from interaction traces. Hyper-edges connect insights through the queries that validated them. This is the swarm's long-term learned knowledge — it compounds across tasks.
192+
193+
### Write Serialization
194+
195+
All memory writes funnel through a single `MemoryWriter` process consuming a Redis Stream. Agents never write to storage directly. This eliminates SQLite write contention at any agent count.
196+
197+
### Retrieval Pipeline (per task)
198+
199+
```
200+
1. Embed new query → cosine similarity search → top-2 historical queries
201+
2. 1-hop graph expansion → expand candidate set
202+
3. Upward traversal → collect insights whose Ω set overlaps candidates
203+
4. LLM relevance scoring → select top-3 most relevant historical interactions
204+
5. LLM sparsification → extract essential subgraph, discard noise
205+
6. Inject context → build agent prompt with insights + interaction fragments
206+
```
207+
208+
Full implementation details in the companion research documents.
209+
210+
---
211+
212+
## Design Principles
213+
214+
**Model-agnostic.** Any CLI-invocable model can be an agent backend. The architecture doesn't assume Claude, GPT, or any specific provider.
215+
216+
**No frameworks.** Vanilla Python + asyncio + subprocess. No LangGraph, no CrewAI, no AutoGen. Every component is explicit and inspectable.
217+
218+
**Infrastructure, not product.** Blitz-Swarm is a reference implementation and research platform. It is meant to be studied, forked, adapted, and improved — not wrapped in a UI and sold.
219+
220+
**Privacy-first.** All memory is local. No telemetry. No external APIs required beyond the model backend.
221+
222+
**Compounding intelligence.** Each task makes the swarm smarter. The insight tier distills accumulated experience into generalizable knowledge that improves future task performance without retraining any model weights.
223+
224+
---
225+
226+
## Repository Structure
227+
228+
```
229+
blitz-swarm/
230+
├── BLITZ-SWARM.md # This file
231+
├── README.md # Project overview + quickstart
232+
├── orchestrator.py # Main entrypoint + agent spawning + consensus loop
233+
├── agents.py # BlitzAgent dataclass + role prompt definitions
234+
├── memory/
235+
│ ├── writer.py # MemoryWriter (single-writer daemon)
236+
│ ├── reader.py # MemoryReader (retrieval pipeline)
237+
│ ├── schema.sql # SQLite schema — G-Memory three tiers
238+
│ └── models.py # Dataclasses: Utterance, QueryNode, InsightNode, InsightEdge
239+
├── blackboard.py # Redis interface (read / write / subscribe)
240+
├── embedder.py # Embedding model wrapper (MiniLM, loaded once at startup)
241+
├── consensus.py # Convergence logic + dissent logging
242+
└── output/
243+
└── {topic}_{timestamp}.md # Final research summaries
244+
```
245+
246+
---
247+
248+
## Implementation Constraints
249+
250+
- Python only — no other languages in core
251+
- No agent frameworks — vanilla asyncio + subprocess throughout
252+
- External services: Redis (single instance, `docker run redis`), SQLite (file), LanceDB (embedded, zero config)
253+
- Single machine target — no distributed infrastructure required
254+
- Model backend: any CLI-invocable model; reference implementation uses Claude Code CLI
255+
- Code style: explicit over clever, constants at file tops, no unnecessary abstractions
256+
257+
---
258+
259+
## Status
260+
261+
🔨 **In development.** Research phase complete. Implementation in progress.
262+
263+
Reference research:
264+
- Blackboard architecture + storage layer: `docs/memory-architecture-research.md`
265+
- G-Memory hierarchical memory: `docs/g-memory-implementation-guide.md`
266+
267+
---
268+
269+
## License
270+
271+
MIT. Build on it. Break it. Make it better.

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Joona Tyrninoksa
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

0 commit comments

Comments
 (0)