SwarmAI
AGENTS.md50 starsChanged 7 months agoMITView on GitHub
Guidance for AI coding assistants (Claude Code, Kiro, Cursor, Codex, and others) working in this repository. Auto-refresh: the <!-- CAPABILITIES --> block below is regenerated by backend/scripts/refresh_ai_docs.py; everything else is hand-authored. Edit prose freely — just keep the marked block and the section headings intact. SwarmAI is a self-evolving Agent OS, not a chatbot and not a Claude wrapper. The distinction is load-bearing for anyone editing this repo: - Cognition is separated from knowledge. The OS (how the system judges…
- Deletes or force-pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
We split this AGENTS.md into the rules it gives an agent
7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 31
A recurring error class becomes a structural gate: When the same mistake shows up 3+ times, the fix is not another prose rule — it's a gate …
- Very specific: line 140
All agent context lives in ~/.swarm-ai/SwarmWS/.context/ — filesystem-only, no DB, git-tracked, human-readable.
- Distinctive: line 171
NEVER Claude/Anthropic identity.
- Very specific: line 247
Colors: Always use bg-[var(--color-*)], never hardcoded dark theme colors
- Distinctive: line 298
All commits in this repo MUST end with:
- Distinctive: line 302
Never use Claude/Anthropic identity in commit trailers.
- Very specific: line 331
Do NOT "fix" this by changing core.hooksPath — it is machine/corporate policy, and the project rules forbid modifying git config.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
Guidance for AI coding assistants (Claude Code, Kiro, Cursor, Codex, and others) working in this repository.
Auto-refresh: the <!-- CAPABILITIES --> block below is regenerated by
backend/scripts/refresh_ai_docs.py; everything else is hand-authored. Edit prose
freely — just keep the marked block and the section headings intact.
What SwarmAI Is (read this first — it changes how you should judge the code)
SwarmAI is a self-evolving Agent OS, not a chatbot and not a Claude wrapper. The distinction is load-bearing for anyone editing this repo:
- Cognition is separated from knowledge. The OS (how the system judges — its principles, rules, and gates) is deliberately kept apart from the disk (what it knows — memory rows, domain docs). One edited line in a governed context file shifts judgment more than a thousand knowledge entries. When you touch this codebase, ask which layer you're in: a behavior change is an OS change; a fact change is a disk change. They have different review bars.
- The model proposes, the OS disposes. Model output is never trusted on its own.
A layer of gates, a staged pipeline, and a validator sit above it and hold authority.
This is why so much of
backend/core/looks like "guardrails around an LLM" — that is the product. - Value compounds across sessions. Sessions are discontinuous; intelligence shouldn't be. Post-session hooks fire between runs (distillation, evolution, context-health, cultivation), so the next session starts warmer than the last. Code that runs after a session ends is not an afterthought here — it's the mechanism.
- A recurring error class becomes a structural gate. When the same mistake shows up
3+ times, the fix is not another prose rule — it's a gate in
security_hooks.pywhere the wrong move physically cannot happen. If you're tempted to "add a warning comment," consider whether a gate is the real fix. - Every project is a domain brain (a DDD). A project is not a folder of files — it's
a brain with one universal six-section structure (Identity · Knowledge · Gates ·
Capabilities · Delivery · Refresher), identical for every domain, governing
0..Nassets (a code repo, a data source, a corpus — or nothing). SeeProjects/*/.
The codebase is both the product AND the evidence for a thesis: one builder + AI +
self-evolving systems = team-scale output. Judge it by reading the harness
(session_unit.py, context_directory_loader.py, the pipeline spec), not by star
count or the README. (AI_CONTEXT.md expands on this for evaluators.)
Project Overview
SwarmAI is a desktop AI command center — Tauri 2.0 (Rust) + React 19 + Python FastAPI
backend, driving the Claude Agent SDK on Bedrock. It is a large codebase: many
backend core modules, a broad skill library, a React component tree, and an extensive
pytest + Hypothesis suite. (Measure any count live — e.g. git ls-files | grep … — never
trust a frozen number in docs; volatile metrics live in docs/CODEBASE_METRICS.md.)
For development rules, anti-patterns, and invariants → see .kiro/steering/swarmai-dev-rules.md
(loaded automatically by Kiro on every interaction; the .kiro/steering/ directory also
holds the security baseline, multi-tab isolation principles, and debugging methodology).
Architecture
Data Flow
User → React Frontend → FastAPI Backend → SessionRouter → SessionUnit → ClaudeSDKClient → SSE → UIProcess Topology
┌─────────────────────────────────┐ ┌──────────────────────────────┐
│ Tauri Desktop App │ │ Backend (port 18321) │
│ ├─ React Frontend (webview) │ │ ├─ FastAPI + Claude SDK │
│ ├─ Rust Core (lib.rs) │ │ ├─ Slack Socket Mode * │
│ └─ Connects to backend:18321 │ │ ├─ Channel Gateway * │
│ │ │ └─ Background Jobs * │
└─────────────────────────────────┘ └──────────────────────────────┘
macOS: daemon (launchd, 24/7) * Only in daemon/hive modes
Win/Linux: subprocess (dies with app)Four platform modes, mutually exclusive, selected by SWARMAI_MODE (default daemon):
daemon (macOS, launchd, 24/7) · subprocess (Windows/Linux desktop, dies with app) ·
hive (EC2 Linux, systemd) · dev (./dev.sh, port 8000, no channels). Channels and
background jobs run only in daemon/hive. Fixed port 18321 on all platforms.
Backend Structure
backend/
├── main.py # FastAPI entry, startup lifespan, health endpoint
├── config.py # Settings from ~/.swarm-ai/config.json
├── core/ # session management, prompt building, lifecycle, DDD, evolution
│ ├── session_router.py # Multi-session routing, dynamic slot management (1-4 tabs via RAM)
│ ├── session_unit.py # 5 states: COLD, IDLE, STREAMING, WAITING_INPUT, DEAD (flow: COLD→STREAMING→IDLE, STREAMING↔WAITING_INPUT)
│ ├── streaming_orchestrator.py # SDK response streaming, SSE event formatting, liveness
│ ├── prompt_builder.py # System prompt assembly from 11 context files + MCP tier loading
│ ├── context_directory_loader.py # Loads/orders/budgets the governed context files
│ ├── lifecycle_manager.py # 12hr TTL kill, orphan reaper, hook serialization
│ ├── session_healing.py # HealthSensor + HealingLoop — invisible auto-respawn
│ ├── security_hooks.py # The PreToolUse gate family (the "OS disposes" layer)
│ ├── resource_monitor.py # RAM-adaptive compute_max_tabs() [1,4], spawn_budget()
│ └── ... # code_intel, embedding, knowledge, memory, cultivation, evolution
├── database/sqlite.py # SQLite + WAL + FTS5 + migrations
├── utils/file_lock.py # Cross-platform flock (fcntl/msvcrt) — USE THIS, not raw fcntl
├── hooks/ # Post-session hooks (context health, evolution, distillation, etc.)
├── routers/ # API endpoints
├── channels/ # Slack adapter, channel gateway
├── skills/ # built-in skills (SKILL.md + INSTRUCTIONS.md each)
├── jobs/ # Background job scheduler + handlers
└── scripts/ # CLI tools (locked_write.py, verify_build.py, ci_eval_gate.py, etc.)Frontend Structure
desktop/src/
├── services/tauri.ts # isDesktop(), getApiBaseUrl() — START HERE for startup bugs
├── components/common/BackendStartupOverlay.tsx # Startup health polling + error display
├── pages/ChatPage.tsx # Main chat UI, tab orchestration
├── stores/MessageStore.ts # Per-tab single-writer message store (SSE-streamed, isolated)
├── hooks/
│ ├── useChatStreamingLifecycle.ts # SSE streaming, stream handlers
│ └── useUnifiedTabState.ts # Tab CRUD, tabMapRef, persistence
└── services/ # API layer (snake_case ↔ camelCase conversion)SSE Streaming Events
Emitted by streaming_orchestrator.py, consumed by the frontend streaming lifecycle:
{"type": "session_start", "sessionId": "..."}
{"type": "assistant", "content": [...], "model": "..."}
{"type": "tool_use", "content": [...]}
{"type": "tool_result", "content": [...]}
{"type": "ask_user_question", "toolUseId": "...", "questions": [...]}
{"type": "cmd_permission_request", "requestId": "...", "toolName": "...", "reason": "..."}
{"type": "result", "sessionId": "...", "durationMs": ..., "totalCostUsd": ...}
{"type": "error", "error": "..."}Context and Memory System (the "cognition" layer)
All agent context lives in ~/.swarm-ai/SwarmWS/.context/ — filesystem-only, no DB,
git-tracked, human-readable. This is the OS's memory; the design goal is that a human can
git diff how the system's judgment changed.
11 source files across 10 priority slots (SOUL and SELF share P2) are assembled into the system prompt on every session start. Priority = both injection order AND truncation order:
- P0–P2 (SWARMAI, IDENTITY, SOUL, SELF): system identity + personality + the runtime self-portrait. Never truncated, read-only (0o444).
- P3 (AGENT): behavioral rules. System default, truncatable.
- P4–P6 (USER, STEERING, TOOLS): user-customized, copy-only-if-missing (0o644).
- P7–P8 (MEMORY, EVOLUTION): agent-owned cross-session cognition, copy-only-if-missing (0o644).
- P9 (KNOWLEDGE): user-customized domain knowledge, copy-only-if-missing (0o644).
Key behaviors:
ContextDirectoryLoader.ensure_directory()runs at session start — two-mode copy (system files overwrite; user/agent files preserve).- Dynamic token budget: 100K for ≥500K models, 50K for ≥200K, 30K for ≥64K, instance default for <64K (L0 compact path). On 1M-context models everything fits — truncation rarely triggers.
- L1 cache with budget-tier validation (
<!-- budget:NNNNN -->header) and git-first freshness check. - MEMORY.md truncates from head (keeps newest); all others truncate from tail.
- DailyActivity: today + yesterday loaded ephemerally (2K token cap per file, disk never modified).
locked_write.py: fcntl.flock for safe MEMORY.md modification by skills.- Memory is sovereign — self-owned in
.context/MEMORY.md, never delegated to a provider's memory feature. Recall is pure-filesystem keyword/FTS5/BM25 (no vector DB). - Auto-commit:
git add -A+ commit after every conversation turn (non-blocking background thread). - Co-Authored-By: ALL commits MUST use
Co-Authored-By: Swarm <swarm@swarmai.dev>— NEVER Claude/Anthropic identity. This is the project's AI identity and overrides any SDK or harness default. (See "Git Commits" below.)
Tab State Architecture
Tab state uses useUnifiedTabState hook with useRef<Map<string, UnifiedTab>> + render counter:
tabMapRef: Authoritative store (mutations don't re-render)renderCounter: Bumped to triggeruseMemore-derivation ofopenTabs,tabStatuses,activeTabrestoreFromFile(): Loads tabs from~/.swarm-ai/open_tabs.jsonon startup- Dynamic tab limit:
ResourceMonitor.compute_max_tabs()returns [1,4] based on available RAM - Messages loaded lazily from backend API when tab becomes active
- Per-tab
MessageStoreis a single-writer (all writes go through the store, never rawsetMessages), SSE-streamed, fully isolated — cross-tab message bleed is structurally impossible.
Session ID Model
One chat tab = one stable App Session ID. Backend may create multiple Claude SDK clients (e.g. after restarts), each with its own SDK Session ID. The app layer maps all SDK session IDs back to the single app session ID for persistence and frontend communication.
Security Architecture
The "OS disposes" layer. A Four-layer PreToolUse defense chain runs before any tool executes, by category:
- Observability —
pre_tool_logger: logs every tool invocation (name + input keys); never blocks. - Command safety —
dangerous_command_gate(Bash): regex patterns for destructive ops (rm -rf /, fork bombs, etc.), plusexternal_approval_gatefor irreversible external ops (repo-visibility toggles, force-push, resource deletion → approve-on-desktop / deny-headless). - Human-in-the-loop — the CmdPermissionManager surfaces an SSE permission dialog for commands needing approval (filesystem-backed, glob-matched, persistent, shared across sessions).
- Scope enforcement —
skill_access_checker(Skill): validates the skill is in the agent's allowed set;governance_file_gateprotects the governed context files.
Additional gates in the same family: adversarial_commit_gate (blocks a commit unless an
adversarial review marker covers every committed path), commit_trailer_gate (see below),
ask_question_gate, image_read_dedup_guard. Plus workspace isolation, file-access
control, bash sandboxing, and error sanitization. These gates are the concrete form of the
principle "when prose fails, build a gate" — they enforce what a comment cannot.
Debugging
Startup Failures ("Backend service failed to start")
- Open DevTools Console (Cmd+Option+I) → look for
[Platform]and[Health Check]logs [Platform] isDesktop=false→ Tauri detection broken (check__TAURI_INTERNALS__)[Health Check] FATAL: got HTML instead of JSON→ API URL is wrong[Health Check] Response: {status: "healthy"}→ Backend OK, problem is elsewhere- Backend logs:
~/.swarm-ai/logs/backend-daemon.log(daemon/hive) or stdout (subprocess/dev)
Backend
curl -s http://127.0.0.1:18321/health | python3 -m json.tool # Daemon health
./prod.sh daemon status # Daemon status
./prod.sh daemon logs # Tail daemon logs
tail -f ~/.swarm-ai/logs/backend-dev.log # Dev logsDiagnosis discipline
Answer "is X built / deployed / running? why did it hang?" ONLY by same-turn observation
(ps, the /health endpoint, launchctl, binary mtime, grep+run) — never from a comment
or a recalled session. For a hang/crash dive: observe the live process first, falsify the
obvious story, read logs LAST. A stale comment is legibility decay, not evidence.
Design System
- Font: Inter (UI), JetBrains Mono (code)
- Icons: Material Symbols Outlined
- Themes: light, dark, system (CSS custom properties in index.css)
- Colors: Always use
bg-[var(--color-*)], never hardcoded dark theme colors - i18n:
i18nextwith locales indesktop/src/i18n/locales/{en,zh}.json
Output Format Protocol
Two consumers, two formats. Never cross the streams.
| Consumer | Format | Examples |
| Agent (self) | Markdown ALWAYS | .context/*.md, DDD docs, DailyActivity, CHANGELOG, INSTRUCTIONS.md |
| Human (user) | Markdown (chat) OR HTML (reports/reviews/dashboards) | Reports, scorecards, pipeline REPORT, code review findings |
When to generate HTML for human consumption:
- Output > 100 lines structured content
- Multi-dimensional comparison (3+ columns × 5+ rows)
- Data requires spatial layout or visual hierarchy (traffic lights, RAG)
- Reader will manipulate (filter, sort, tab-switch)
HTML constraints: Single file, inline CSS/JS, zero external deps, system fonts, warm professional palette, responsive. No gradients, no glassmorphism, no icon libraries, no dark-theme-default. L3+ interactive HTML must have an Export button (Copy as Markdown/JSON/CSV) — otherwise it's a dead end.
See Projects/SwarmAI/2-understanding/TECH.md → "Output Format Protocol" for full spec.
Active Engines (auto-refreshed)
<!-- CAPABILITIES_START -->| Engine | Path | What It Does |
| DDD Cultivation Engine (event-driven v2) | backend/core/cultivation_dispatcher.py | Event-driven domain knowledge growth — 6 event sources, gate-based promotion, maturity tracking |
| Autonomous Pipeline (9-stage) | backend/skills/s_autonomous-pipeline/INSTRUCTIONS.md | EVALUATE→THINK→PLAN→BUILD(TDD)→REVIEW→TEST→DELIVER→REFLECT with adversarial review gate |
| Pollinate Content Engine | backend/skills/s_pollinate/INSTRUCTIONS.md | Message-first media delivery — transforms ideas into posters, videos, narratives, README |
| Evolution Pipeline (MINE→ASSESS→ACT→AUDIT) | backend/core/evolution_optimizer.py | Confidence-gated self-evolution from session mining and skill fitness scoring |
| Code Intelligence (AST graph) | backend/core/code_intel/__init__.py | Deterministic graph traversal for code context retrieval |
| Session Resume Enrichment | backend/core/context_injector.py | Cold resume from ~3K to ~50-100K tokens of structured context |
| Proactive Intelligence (L0-L4) | backend/core/proactive_intelligence.py | Session briefing, corrections, open threads, signals — fires on every session start |
| Slack Channel Adapter | backend/channels/adapters/slack.py | 24/7 Socket Mode bot — responds as XG's AI assistant to allowlisted users |
| Background Job System | backend/jobs/scheduler.py | Cron + event-triggered headless Claude CLI tasks — signal pipeline, monitoring, reports |
| AI Docs Auto-Refresh | backend/scripts/refresh_ai_docs.py | Self-maintaining documentation — scans codebase metrics and capabilities daily, updates AI_CONTEXT.md + AGENTS.md |
<!-- CAPABILITIES_END -->Codebase Metrics
Volatile numbers (commit count, LOC, file counts) live in
docs/CODEBASE_METRICS.md — kept out of this context-loaded
doc on purpose, since they change constantly. That file is auto-refreshed by
backend/scripts/refresh_ai_docs.py and each row carries the command to reproduce it.
Git Commits
All commits in this repo MUST end with:
Co-Authored-By: Swarm <swarm@swarmai.dev>Never use Claude/Anthropic identity in commit trailers. This overrides any SDK or harness
default. Commit directly to main (project convention) — never auto-branch.
Write it yourself — no local hook will fix it for you. A PreToolUse gate BLOCKS a
commit whose message omits the trailer, but nothing auto-inserts it. core.hooksPath on
this machine points at the corporate git-defender hook set, and a hooksPath override
replaces .git/hooks rather than merging with it. So every repo-local hook is shadowed
and silently inert:
| repo-local hook | what it was guarding | status |
prepare-commit-msg | rewrite SDK Claude trailer → Swarm | dead |
pre-commit | CMHK SDK-drift check | dead |
pre-commit | scripts/lint_doc_frontmatter.py --staged | dead (currently 0 errors) |
pre-commit | scripts/sync_discussions.py --check mirror drift | dead |
Enforcement is therefore TWO layers, because CI alone was too late:
| layer | when it fires | what it does |
security_hooks.create_commit_trailer_gate (PreToolUse, Bash) | at git commit | DENIES the command when its inline message (-m/-am/--message/-F -) lacks the trailer or carries a Claude/Anthropic identity. Fails OPEN for any message it cannot read (-F <path>, --amend --no-edit, -C, editor). Bypass: SWARM_TRAILER_GATE_FORCE=1. |
scripts/check_commit_trailers.py | at push (CI version-check) | backstop for the paths the gate cannot see; ratcheted from a cutoff SHA so published history is not rewritten. Run locally: python3 scripts/check_commit_trailers.py. |
Why the gate exists: CI catches this at PUSH, which under this repo's commit-on-main-for-days
workflow is hours-to-days late — and by then the only repair is a history rewrite. The gate
moves the catch to the one moment the fix is free (re-run the command with the line appended).
Bump ENFORCED_FROM ONLY to record a deliberate, explained amnesty — never to paper over a
fresh violation.
Do NOT "fix" this by changing core.hooksPath — it is machine/corporate policy, and the
project rules forbid modifying git config. Any check that must actually run belongs in CI.
(git-defender is also why git commit is slow: a 22 MB commit-msg binary plus a scanning
daemon. Allow ~600s for a commit in automation.)
Before You Push — the local quality gate
main is the only branch. Push is normal flow (no per-push sign-off), but ONLY when the
change is fully green on THREE checks — any one unrun or red blocks the push:
- Build —
./prod.sh build(backend) and/orcd desktop && npm run build:all(frontend), per what the change touches. - Tests — at least the affected suites, wrapped with a wall-clock timeout
(
perl -e 'alarm 90' python -m pytest tests/test_<module>.py --timeout=60); full suite (SWARMAI_SUITE=1) only when the blast radius warrants. Never pipe pytest through| tail. - Eval —
cd backend && python scripts/ci_eval_gate.py. This is a pure check (zero Bedrock cost): it verifies the latest committed eval report is FRESH (its code_digest matches current eval-relevant code) and GREEN. Never run the eval judge inside a coding change — it scores the deployed system, not un-built code.
commit ≠ qualified ≠ deployed: a build produces a binary; code isn't live until
rebuild+restart. "Tests green" alone is not "qualified."
Key Design Decisions
- Single agent with role-switching > multi-agent orchestration (zero context-transfer cost; sub-agents are used for adversarial verification, which is not division of labor).
- Memory sovereignty — all memory self-owned (
.context/MEMORY.md), never a provider's memory feature. - Platform-native lifecycle — macOS: launchd daemon (24/7); Windows/Linux: Tauri subprocess; Hive: systemd.
- Filesystem-first for skills and context — no DB, git-tracked, human-readable.
- Prevention over recovery — if a system can hang, make it structurally impossible; don't bolt on a watchdog. A timeout is a hang-guard, never a way to bury a slow root cause.
- One-shot qualified delivery — code changes go through the autonomous pipeline as a black box: one requirement → push-ready code, quality guaranteed by adversarial gates, not by iterating cheap drafts.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

