npm package: @klotomat/klotomat-bootstrap
Description: One-command bootstrap for Klotomat with Claude Code and Codex CLIs
Latest version: 0.2.25

# Klotomat

Discord-first orchestration for autonomous collaboration between **Codex** and **Claude Code**, with optional independent AI review.

This is a local-first MVP designed to preserve each agent's native capabilities by invoking their local CLI runtimes directly.

Important: users install Klotomat as an orchestration layer, then run tasks against their own
project repo/folder workspaces. The goal is not to do product work inside the Klotomat codebase.

---

## Quick Start

```bash
# 1. Bootstrap (installs Python venv + agent CLIs)
node scripts/setup_all.mjs

# 2. Interactive guided setup (creates bot, invites it, provisions server)
source .venv/bin/activate && python scripts/setup.py

# 3. Start the bot
klotomat
```

The guided setup walks you through every step with clear explanations:

1. **Create a Discord bot** — opens the Developer Portal for you
2. **Invite it** — auto-generates the invite URL with correct permissions
3. **Provision your server** — auto-creates channels, roles, and a pinned welcome guide
4. **GitHub token** — optional, for automatic PR creation
5. **Done.** Open Discord and type `!run <your task>`

Expected time: **5 minutes**.

---

## What You Get

- Discord command interface (`!run`, `!status`, `!approve`, `!pause`, `!resume`, `!review`, `!project`, `!budget`)
- Native CLI adapters for Codex and Claude
- Autonomous duo loop with structured handoffs, checklist tracking, and bounded recovery
- SQLite task/memory store + per-task runtime logs
- Optional PostgreSQL store for production runtime (`DATABASE_URL`)
- Independent reviewer pass (opposite provider) on final outputs
- Guardrails: max turns, max runtime, human approval checkpoints, scoped cost budgets
- Executive-agent operating model (one file per agent) with a big-tech quality rubric
- Optional AWS control-plane mode (SQS-backed task queue)
- Workspace registry + per-task isolated git worktrees

---

## What You Need

Klotomat requires **two tokens** you paste once during setup, plus paid accounts with
OpenAI and Anthropic so the agent CLIs can run. The installer handles everything else.

| Requirement | Type | Purpose |
|---|---|---|
| **Discord Bot Token** | Required | Connects Klotomat to your Discord server |
| **GitHub Token** | Recommended | Enables automatic PR creation from completed tasks |
| **OpenAI account** | Required | Powers the Codex CLI agent (any plan with CLI access) |
| **Anthropic account** | Required | Powers the Claude CLI agent (any plan with CLI access) |

That's it. Everything else (Python, Node.js, git, agent CLIs) is installed automatically.

---

### Discord Server Setup

The guided setup (`python scripts/setup.py`) handles everything automatically.
If you prefer to do it manually:

1. **Create a server** — [create one free](https://support.discord.com/hc/en-us/articles/204849977-How-do-I-create-a-server)
2. **Create a bot** — at https://discord.com/developers/applications → New Application → Bot → Reset Token → Copy
3. **Enable Message Content Intent** — Bot → Privileged Gateway Intents → Message Content Intent → ON
4. **Invite the bot** — the setup script auto-generates the invite URL
5. **Provision channels & roles** — `python scripts/provision_discord.py`

> **Tip:** `python scripts/setup.py` does steps 2–5 interactively.

---

### How to Get Your GitHub Token

You have two options:

#### Option A: GitHub CLI (recommended — handles 2FA and SSO automatically)

If you have `gh` installed (the installer installs it for you), just run:

```bash
gh auth login -h github.com -p https -w
```

The installer offers this option automatically and retrieves the token for you.

#### Option B: Manual Personal Access Token

1. Go to **GitHub Token Settings**: https://github.com/settings/tokens
2. Click **"Generate new token"** → **"Generate new token (classic)"**.
3. Give it a name (e.g. "Klotomat").
4. Set an expiration (90 days recommended).
5. Under **Scopes**, check:
   - ✅ **repo** (full control of private repositories)
   - This gives Klotomat permission to create branches, push commits, and open PRs.
6. Click **"Generate token"** at the bottom.
7. **Copy the token immediately** — you won't be able to see it again.
   - It starts with `ghp_...`
   - This is your `GITHUB_TOKEN`.

> **Note:** If your organization uses SSO, you must also click **"Configure SSO"**
> next to the token and authorize it for your org. Without this, Klotomat can't
> access your org's repositories.

---

### What About Codex and Claude?

You need active **OpenAI** and **Anthropic** accounts with CLI access (any paid plan that includes CLI usage works—Pro, Team, or API-only plans are all fine).

The installer handles CLI authentication automatically:

- **Codex:** The installer runs `codex login` → opens a browser window → you sign in with your OpenAI account.
- **Claude:** The installer runs `claude auth login` → opens a browser window → you sign in with your Anthropic account.

No API keys to copy-paste. The browser login flow handles everything, including 2FA.

> **Note:** Klotomat can still run tasks if only one agent is authenticated — it falls back
> to single-agent mode. But the full duo loop (handoffs + independent review) requires both.

---

## What to Expect After Setup

Here's what a typical first session looks like:

### 1. Link your project (if not done during setup)

```
!project add https://github.com/you/my-repo
```

The bot confirms: `✓ Workspace my-repo linked to this channel.`

### 2. Run your first task

```
!run Add a health check endpoint to the API
```

Klotomat creates a task, checks out a branch, and starts the duo loop:
- Codex drafts the implementation
- Claude reviews and refines
- Each turn posts a progress update in your Discord channel

### 3. Review and approve

When the agents finish, Klotomat posts a summary with the diff and test results.
**By default, the AI never pushes to your repo.** You must approve first:

```
!approve <task_id>
```

After approval, Klotomat pushes the branch and opens a PR.

### 4. See the results

- A **git branch** with all changes is pushed to your repo (only after you approve)
- A **pull request** is opened automatically (if GitHub token is configured)
- Full execution logs are available via `!timeline <task_id>`

### Push policy (autonomy profiles)

Klotomat has three autonomy profiles that control when it auto-pushes:

| Profile | Push behavior | Use when |
|---|---|---|
| **`safe`** (default) | Never auto-pushes — always asks for `!approve` | You want full control |
| **`balanced`** | Auto-pushes low/medium-risk changes, asks for high-risk | You trust the AI on routine work |
| **`aggressive`** | Always auto-pushes | Fully autonomous mode |

Override per-task: `!run --autonomy balanced Add a README improvement`
Change the default: set `AUTONOMY_DEFAULT_PROFILE=balanced` in `.env`

> Type `!guide` in Discord to see this and more — no need to leave Discord.

### Other useful commands

```
!help                — see all commands
!guide               — full tutorial inside Discord
!status              — check active task progress
!tasks               — list all tasks
!budget              — check usage against daily limits
!project list        — show linked projects
```

---

## Discord Commands

### Getting Started

| Command | Description |
|---|---|
| `!project add <repo_url> [branch]` | Link a repo to the current channel |
| `!project topic <description>` | Set channel focus area (agents always see this) |
| `!project list` | Show all linked projects |
| `!project remove <name>` | Unlink a project |
| `!run <prompt>` | Start a task — Claude first by default |
| `!run codex <prompt>` | Force Codex as primary agent |

### Task Management

| Command | Description |
|---|---|
| `!tasks` | List all tasks |
| `!status [task_id]` | Check task progress |
| `!approve <task_id> [note]` | Approve a pending task |
| `!pause <task_id>` | Pause a running task |
| `!resume <task_id> [note]` | Resume a paused task |
| `!review <task_id>` | Trigger a review pass |
| `!timeline <task_id>` | View full task timeline |
| `!budget [channel\|workspace]` | Check usage and budgets |

### Flows & Templates

| Command | Description |
|---|---|
| `!run implement <prompt>` | Run a multi-step flow |
| `!flow list` | Show available flows |
| `!flow show <name>` | Show flow steps |
| `!queue <prompt>` | Add task to sequential queue |
| `!queue list` | Show queue |
| `!queue clear` | Clear pending tasks |
| `!template save <name> [prompt]` | Save a reusable prompt template |
| `!template run <name>` | Run a saved template |
| `!template list` | Show saved templates |

### Context, Memory & Config

| Command | Description |
|---|---|
| `!context add <rule>` | Add a persistent rule agents always see |
| `!context list` | Show rules for this workspace |
| `!context remove <id>` | Remove a rule |
| `!config show` | Show all current settings |
| `!config set <key> <value>` | Change a setting (e.g. `!config set default_agent codex`) |
| `!memory` | Show memory channel info |
| `!memory set <channel_id>` | Set memory channel for task summaries |

### Team

| Command | Description |
|---|---|
| `!dashboard` | Team activity summary (embed) |
| `!assign @user <prompt>` | Create a task for a team member |
| `!leaderboard` | Tasks completed per user |

### Admin

| Command | Description |
|---|---|
| `!agents` | Show agent status |
| `!ops` | Operational diagnostics |
| `!recover` | Re-launch stuck tasks |
| `!guide` | Full feature walkthrough inside Discord |
| `!workspace add <name> <repo_url> [branch]` | Power-user workspace setup (explicit name) |
| `!workspace list` | List all workspaces |

> **Tip:** `!project` commands are friendly aliases for `!workspace` — they auto-derive the
> project name from the repo URL. Use `!workspace` if you need explicit naming control.

---

## Alternative Install Methods

The [Quick Start](#quick-start) command above is the recommended path. These alternatives exist for specific scenarios:

### One-command npm bootstrap (if you already cloned the repo)

```bash
npm run setup:all
```

This installs agent CLIs (`@openai/codex`, `@anthropic-ai/claude-code`), creates a Python venv, and wires up `.env`.

To skip agent CLI installs (Python-only setup):

```bash
npm run setup:all:skip-agents
```

### Direct shell installer

```bash
bash MACOS_ONEFILE_SETUP.sh
```

Or with the quick 3-step flow:

```bash
bash MACOS_ONEFILE_SETUP.sh --quick
```

### Non-interactive mode (for CI/automation)

```bash
bash MACOS_ONEFILE_SETUP.sh \
  --no-interactive \
  --discord-token "<token>" \
  --github-token "<token>" \
  --channel-id "<discord_channel_id>"
```

> **Security note:** prefer interactive auth or `--secrets-file` over `--discord-token` / `--github-token`
> to reduce secret exposure in shell history.

### File-based secrets

```bash
cp templates/secrets.env.template ~/klotomat-secrets.env
$EDITOR ~/klotomat-secrets.env
npm exec --yes --package @klotomat/klotomat-bootstrap klotomat-setup -- --secrets-file ~/klotomat-secrets.env
```

### Manual developer setup

```bash
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
cp .env.example .env
# Edit .env with at minimum: DISCORD_TOKEN
klotomat
```

---

## Advanced Configuration

All configuration is via `.env`. See [`.env.example`](./.env.example) for the full list with defaults.

### Essential settings

```bash
DISCORD_TOKEN=...
CODEX_COMMAND=codex
CLAUDE_COMMAND=claude
CONTROL_PLANE_MODE=local
REQUIRE_WORKSPACE=true
AUTONOMY_DEFAULT_PROFILE=safe
```

### Usage guardrails

Tune these to stay within your subscription tiers:

```bash
DAILY_TASK_BUDGET=30
DAILY_TURN_BUDGET=300
MAX_CONCURRENT_TASKS=2
AUTO_IMPROVEMENT_ENABLED=false
AUTO_IMPROVEMENT_DAILY_BUDGET=3
```

Check runtime usage with `!budget`.

### Security hardening

```bash
STRICT_PATH_ENFORCEMENT=true
ALLOWED_RUNTIME_ROOTS=./runs
ALLOWED_WORKSPACE_ROOTS=./workspaces
PROVIDER_SANDBOX_MODE=host
SECRETS_BACKEND=env
STRUCTURED_LOGGING=true
```

### Docker sandbox

Run providers inside isolated Docker containers:

```bash
PROVIDER_SANDBOX_MODE=docker
PROVIDER_DOCKER_IMAGE=<image-with-codex-and-claude-clis>
PROVIDER_DOCKER_NETWORK_DISABLED=true
```

### macOS Keychain secrets

```bash
SECRETS_BACKEND=keychain
KEYCHAIN_SERVICE=com.klotomat
```

### Provider wrappers

If your CLIs require custom flags, point to wrapper scripts:

```bash
CODEX_COMMAND=./scripts/run_codex.sh
CLAUDE_COMMAND=./scripts/run_claude.sh
```

Each provider receives:

- prompt via `stdin`
- prompt file path via `KLOTOMAT_PROMPT_FILE`
- metadata env vars (`KLOTOMAT_TASK_ID`, `KLOTOMAT_TURN`, `KLOTOMAT_AGENT`)

### Workspace and GitHub settings

```bash
WORKSPACE_ROOT=./workspaces
GITHUB_TOKEN=...
RUN_TEST_COMMAND=pytest -q
```

### Role-based Discord ACLs

```bash
DISCORD_RUN_ALLOWED_ROLES=role-id-1,role-id-2
DISCORD_CONTROL_ALLOWED_ROLES=...
DISCORD_REVIEW_ALLOWED_ROLES=...
DISCORD_ADMIN_ALLOWED_ROLES=...
```

---

## AWS Production Blueprint

> This section is for when you're ready to scale beyond local mode. Start with local subscription mode first.

Use local subscription mode first, then evolve to AWS API/worker mode:

1. **Ingress**: Discord webhook/bot on ECS Fargate (or Lambda + API Gateway).
2. **Queue**: SQS queue per task priority (`standard`, `review`, `high-risk`).
3. **Orchestrator API**: FastAPI service on ECS/EKS.
4. **Task State**: PostgreSQL (RDS) instead of SQLite.
5. **Worker Isolation**: ECS tasks with ephemeral storage or Firecracker microVMs.
6. **Artifacts/Logs**: S3 + CloudWatch Logs.
7. **Secrets**: AWS Secrets Manager for API keys/tokens.
8. **AuthN/AuthZ**: Discord role mapping + IAM boundaries.
9. **Observability**: OpenTelemetry + CloudWatch/X-Ray + alerting.
10. **Cost/Safety Gates**: per-channel spend limits, turn limits, deny-list operations.

### AWS control-plane mode (SQS-backed queueing)

This keeps Codex/Claude running from your logged-in native CLIs while using SQS for task dispatch:

```bash
CONTROL_PLANE_MODE=aws
AWS_REGION=us-east-1
AWS_TASK_QUEUE_URL=https://sqs.us-east-1.amazonaws.com/<acct>/<queue>
```

Start the same bot process (`klotomat`). `!run` enqueues to SQS and the internal consumer executes tasks.

### Terraform provisioning

```bash
cd infra/terraform
cp terraform.tfvars.example terraform.tfvars
terraform init && terraform plan && terraform apply
terraform output env_snippet
```

Paste `env_snippet` into your app `.env`.

Detailed docs:

- [AWS reference architecture](./docs/aws-reference-architecture.md)
- [Company executive-agent charter](./docs/company-executive-agents.md)

---

## Architecture

1. Discord bot receives task requests.
2. Orchestrator creates a task record and checklist.
3. Agent providers run native CLIs in per-task runtime folders.
4. Each turn returns structured JSON (`summary`, `handoff_to`, `final_answer`, etc).
5. Orchestrator applies updates, handles handoff/approval, and posts progress to Discord.
6. Completed tasks collect git artifacts (changed files, diff, test command output), then run independent review.
7. Workspace-aware policies decide auto-push/PR (`safe`, `balanced`, `aggressive` autonomy profiles).

## Company Executive-Agent Model

Implemented roles:

1. VP Product Strategy
2. VP Solution Architecture
3. VP Platform Engineering
4. VP Quality Assurance
5. VP Security and Risk
6. VP SRE and Reliability
7. VP Data and Analytics
8. VP Developer Experience
9. VP Program Management
10. VP Compliance and Governance
11. VP Release Governance

Each role lives in its own file under `src/klotomat/company_agents/agents/`.

The runtime rotates these roles by turn (for the active executor) and enforces a release-quality structure in final answers:
- `Executive Summary`
- `Product Impact`
- `Architecture`
- `Implementation`
- `Verification`
- `Security`
- `Reliability`
- `Observability`
- `Rollback Plan`
- `Open Risks`

## Design Notes

- "All capabilities preserved" is best achieved by running each agent in its native runtime.
- Keep a single active "owner agent" per turn to avoid dual-write conflicts.
- Handoffs are explicit and machine-readable; no unbounded agent-to-agent loops.
- Reviewer is configured as a quality gate by default (`QUALITY_STANDARD=bigtech`).
- Usage guardrails protect subscription tiers via daily caps and concurrency controls.
- Optional role-based command ACLs are supported via `DISCORD_*_ALLOWED_ROLES`.
- Startup recovery automatically re-launches queued/running tasks (`RECOVER_INCOMPLETE_TASKS_ON_STARTUP=true`).
- Provider usage telemetry supports structured usage files/markers (`KLOTOMAT_USAGE_FILE` / `KLOTOMAT_USAGE:` JSON).

## Current Limitations

- Agent CLIs still require account auth and acceptance of provider terms on each machine.
- CLI command contracts vary by local install; wrappers may be needed.
- Local mode is single-process; AWS queue mode is available via SQS.
- GitHub App JWT flow is not yet wired; `GITHUB_TOKEN` is currently used for PR automation.
- Auto-merge is intentionally disabled; human merge gate remains required.

## Next Up

1. Add GitHub App token minting and installation-scoped auth.
2. Add slash commands and richer Discord thread UX.
3. Add deterministic reviewer scorecards + policy-driven auto-escalation thresholds.
4. Add long-running dashboards and alert integrations (CloudWatch/Grafana).