> For the complete documentation index, see [llms.txt](https://groktown.gitbook.io/groktown-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://groktown.gitbook.io/groktown-docs/groktown.md).

# GrokTown

Gastown-Style Multi-Agent Coding System powered by xAI Grok

A multi-agent orchestration system for software development, inspired by [Steve Yegge's Gastown](https://github.com/steveyegge/gastown), but powered by **xAI's Grok** instead of Claude Code.

Twitter Account: <https://x.com/GrokTownX>

***

### What Is This?

GrokTown is a **pure coding agent orchestration system** that implements Gastown's architecture:

#### Core Concepts from Gastown

1. **The Town** - Your HQ where all projects live
2. **Rigs** - Individual projects (git repos) under management
3. **Agents** - AI workers with persistent identities
4. **Beads** - Git-backed persistent state for everything
5. **GUPP Protocol** - "If there's work on your hook, you run it"
6. **Molecules** - Multi-step workflows that survive crashes
7. **Crews** - Workspaces for teams/users

#### GrokTown vs Gastown

| Feature       | Gastown            | GrokTown                 |
| ------------- | ------------------ | ------------------------ |
| AI Backend    | Claude Code        | xAI Grok                 |
| Language      | Go                 | Python                   |
| Primary Use   | Code orchestration | Code orchestration       |
| X Integration | No                 | Yes (Grok's superpower!) |
| Open Source   | Yes                | Yes                      |

***

### Architecture

```
┌─────────────────────────────────────────────────────┐
│                    The Town (HQ)                     │
│                                                      │
│  ┌────────────┐  ┌────────────┐  ┌────────────┐   │
│  │   Rig 1    │  │   Rig 2    │  │   Rig 3    │   │
│  │  (Project) │  │  (Project) │  │  (Project) │   │
│  └────────────┘  └────────────┘  └────────────┘   │
│                                                      │
│  Each Rig has:                                      │
│  • 1 Mayor (orchestrator)                           │
│  • N Coding Agents (workers)                        │
│  • 1 Witness (audit trail)                          │
│                                                      │
└─────────────────────────────────────────────────────┘

Persistent State (Beads):
• Agent identities
• Issues (GitHub-style)
• Work logs
• Task hooks
• Workflows (molecules)
```

#### Agent Roles

**Mayor** 🎩

* Main orchestrator for the project
* Breaks down high-level goals into issues
* Reviews completed work
* Plans architecture

**Coding Agent** 👨‍💻

* Implements features
* Fixes bugs
* Writes tests
* Refactors code

**Witness** 👁️

* Maintains audit trail
* Tracks all work done
* Generates reports
* Ensures compliance

***

### Quick Start

#### Prerequisites

* Python 3.11+
* xAI Grok API key ([get one here](https://x.ai/api))
* Git

#### Installation

```bash
# 1. Install dependencies
pip install pyyaml requests

# 2. Set your Grok API key
export XAI_API_KEY=xai-your-key-here

# 3. Initialize GrokTown
python groktown.py
```

#### Run Demo

```bash
python groktown.py demo
```

This will:

1. Create a convoy of issues for building a web server
2. Assign the first issue to a coding agent
3. Watch the agent implement it
4. Generate a project report

***

### Usage

#### Basic Commands

```bash
# Start the system
python groktown.py

# Run demo workflow
python groktown.py demo

# Create new project
python groktown.py create my-awesome-app "Description of the app"
```

#### Working with GrokTown

**1. Create a Project (Rig)**

```bash
python groktown.py create weather-api "RESTful API for weather data"
```

This creates:

* Project directory structure
* Agent beads
* README and scaffolding

**2. Configure the Rig**

Edit `groktown_config.yaml`:

```yaml
rigs:
  weather-api:
    enabled: true
    description: "RESTful API for weather data"
    language: "python"
```

**3. Start the System**

```bash
python groktown.py
```

Agents will:

* Check their hooks for pending work
* Execute tasks autonomously
* Store all work in git (Beads)
* Continue until stopped

**4. Create Issues**

GrokTown uses GitHub-style issues. You can:

**Via Mayor (AI-generated):**

```python
# Mayor breaks down high-level goal into issues
mayor.create_convoy({
    "goal": "Build a REST API with authentication"
})
```

**Manually:**

```python
from groktown_framework import IssueBead, IssueStatus

issue = IssueBead(
    id="issue_001",
    title="Implement user authentication",
    description="Add JWT-based authentication to the API",
    status=IssueStatus.OPEN.value,
    rig="weather-api",
    priority="high",
    created_at=datetime.now().isoformat(),
    updated_at=datetime.now().isoformat()
)

storage.save_bead(issue, "issue")
```

**5. Assign to Agent**

```python
from groktown_framework import Task, TaskStatus

task = Task(
    id="task_001",
    type="work_on_issue",
    priority="high",
    status=TaskStatus.PENDING,
    agent_id="coder-1-weather-api",
    data={"issue_id": "issue_001"},
    created_at=datetime.now().isoformat()
)

coder.add_task(task)
```

**6. Monitor Progress**

```bash
# Check beads directory
ls groktown/beads/issues/
ls groktown/beads/hooks/

# View agent statistics
cat groktown/beads/agents/coder-1-weather-api.yaml

# Check work logs
cat groktown/beads/issues/issue_001.yaml
```

***

### GUPP Protocol

**G**rok **U**nified **P**erpetual **P**rotocol

The core principle: **If there is work on your hook, YOU MUST RUN IT.**

#### How It Works

1. **Hooks** - Each agent has a task queue (hook)
2. **Check** - Agents continuously check their hooks
3. **Execute** - If work exists, agent must process it
4. **Persist** - All state stored in git
5. **Resume** - Crashed agents restart and continue

#### Example Flow

```
Agent Loop:
  while running:
    1. Load hook from storage
    2. Get pending tasks
    3. If no tasks: sleep
    4. If tasks exist:
       - Pick highest priority
       - Mark as ACTIVE
       - Execute task
       - Mark as COMPLETED
       - Save results
    5. Repeat
```

This ensures:

* No forgotten tasks
* Crash resilience
* Full audit trail
* Predictable behavior

***

### File Structure

```
groktown/
├── beads/                    # Git-backed persistent state
│   ├── roles/               # Agent role definitions
│   ├── agents/              # Agent identities
│   ├── issues/              # GitHub-style issues
│   ├── molecules/           # Workflow chains
│   └── hooks/               # Agent task queues
│
├── rigs/                     # Projects under management
│   ├── example-webapp/
│   │   ├── crew/            # User workspaces
│   │   │   └── default/
│   │   ├── src/
│   │   └── tests/
│   └── weather-api/
│       └── ...
│
├── groktown.py              # Main runner
├── groktown_framework.py    # Core agent classes
└── groktown_config.yaml     # Configuration
```

***

### Configuration

#### groktown\_config.yaml

```yaml
# Enable/disable projects
rigs:
  my-project:
    enabled: true
    description: "My awesome project"
    language: "python"

# Agents per project
agents_per_rig:
  mayor: 1
  coders: 3
  witness: 1

# Grok settings
grok:
  model: "grok-beta"
  temperature: 0.7
  max_tokens: 8000
```

***

### Grok Features

#### Real-Time X Context

Grok's unique advantage: access to real-time X (Twitter) data!

```python
# Search X for project-related discussions
sentiment = await agent.search_x_sentiment("Python async programming")

# Get trending topics
trends = await agent.search_x_sentiment("trending programming languages")
```

Use cases:

* Research best practices
* Find solutions to problems
* Stay updated on tech trends
* Monitor sentiment about technologies

#### Code Generation

Grok excels at code generation:

```python
code = await agent.think(
    "Write a Flask API endpoint for user authentication with JWT"
)
```

***

### Advanced Usage

#### Custom Workflows (Molecules)

Create multi-step workflows:

```python
from groktown_framework import MoleculeBead

molecule = MoleculeBead(
    id="mol_feature_001",
    name="feature-development",
    description="Complete feature development workflow",
    steps=[
        "issue_design",
        "issue_implement", 
        "issue_test",
        "issue_review"
    ],
    created_at=datetime.now().isoformat(),
    updated_at=datetime.now().isoformat()
)

storage.save_bead(molecule, "molecule")
```

#### Custom Agent Types

Extend the base agent class:

```python
from groktown_framework import GrokAgent, AgentRole

class ReviewerAgent(GrokAgent):
    def __init__(self, agent_id, storage, grok_api_key, rig):
        super().__init__(agent_id, AgentRole.AGENT, storage, 
                        grok_api_key, rig)
    
    async def execute_task(self, task):
        if task.type == "review_code":
            return await self.review_code(task.data)
        return {"error": "Unknown task"}
    
    async def review_code(self, data):
        code = data["code"]
        prompt = f"Review this code:\n\n{code}\n\nProvide detailed feedback."
        review = await self.think(prompt)
        return {"review": review}
```

***

### Comparison with Original Gastown

#### Similarities ✅

* Multi-agent orchestration
* Persistent state (Beads)
* GUPP protocol
* Git-backed storage
* Workflow molecules
* Rig/Crew structure

#### Differences 🔄

| Feature     | Gastown                 | GrokTown           |
| ----------- | ----------------------- | ------------------ |
| AI          | Claude Code             | xAI Grok           |
| Language    | Go                      | Python             |
| CLI Tool    | `gt` command            | Python scripts     |
| Integration | Deep Claude integration | Generic LLM calls  |
| X Context   | No                      | Yes (Grok feature) |
| Maturity    | Production-ready        | Proof of concept   |

***

### Roadmap

#### Phase 1: Foundation ✅

* \[x] Core agent framework
* \[x] GUPP protocol
* \[x] Bead storage system
* \[x] Mayor, Coder, Witness agents
* \[x] Issue management

#### Phase 2: Enhancement

* \[ ] Polecat agents (testing)
* \[ ] Refinery agent (data processing)
* \[ ] Deacon agent (system health)
* \[ ] Advanced molecule workflows
* \[ ] Better git integration

#### Phase 3: Integration

* \[ ] GitHub integration
* \[ ] VS Code extension
* \[ ] Web dashboard
* \[ ] Slack/Discord notifications
* \[ ] CI/CD integration

#### Phase 4: Intelligence

* \[ ] Learning from past work
* \[ ] Code quality metrics
* \[ ] Performance optimization
* \[ ] Team collaboration features

***

### Why GrokTown?

#### Advantages of Grok

1. **X Integration** - Real-time access to developer discussions
2. **Cost** - Competitive pricing vs other LLMs
3. **Speed** - Fast inference for quick iterations
4. **Flexibility** - Not tied to specific CLI tools

#### When to Use GrokTown

✅ **Good for:**

* Multi-project management
* Team collaboration
* Long-running development tasks
* Projects needing social context (X data)

❌ **Not ideal for:**

* Single-file quick edits (use Claude Code directly)
* Projects requiring deep IDE integration
* Real-time pair programming

***

### Inspiration & Credits

* **Gastown** by [Steve Yegge](https://github.com/steveyegge/gastown) - The original inspiration
* **Beads** by [Steve Yegge](https://github.com/steveyegge/beads) - Memory system for agents
* **xAI Grok** - The AI powering the system

Special thanks to the Gastown architecture for showing how multi-agent systems should work!

***

### Contributing

GrokTown is experimental. Improvements welcome:

1. Fork the repo
2. Add features
3. Test thoroughly
4. Submit PR

Areas that need work:

* Better error handling
* More agent types
* Improved git integration
* Web UI
* Performance optimization

***

### License

MIT License - Use at your own risk

***

### FAQ

**Q: Why not just use Gastown?**\
A: Gastown is tied to Claude Code and requires the `gt` CLI. GrokTown is more flexible and uses Grok's unique features like X integration.

**Q: Can I use Claude instead of Grok?**\
A: Yes! Just modify the `GrokClient` class to use Anthropic's API instead.

**Q: How much does this cost?**\
A: Depends on usage. Grok pricing is \~$0.20 per million input tokens. For typical projects, expect $5-50/month.

**Q: Is this production-ready?**\
A: No, this is a proof of concept. Use for experimentation and learning.

**Q: How does it compare to cursor/copilot?**\
A: Different use case. Cursor/Copilot are IDE assistants. GrokTown is for multi-agent project orchestration.

***

***

**Happy coding with your AI crew!** 🚀🤖

*May your agents be productive and your git history clean.*
