SwarmAI
AGENTS.md66 starsChanged 40 days 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 code style.
Of the AGENTS.md files we read, the 35,337 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
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
17 rules. About 0 are common, 5 are distinctive, and 12 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
12
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 31
A recurring error class gets a structural fix: When the same mistake shows up 3+ times, the fix is not another prose rule — it's a …
- Very specific: line 149
All agent context lives in ~/.swarm-ai/SwarmWS/.context/ — filesystem-only, no DB, git-tracked, human-readable.
- Very specific: line 321
Every PreToolUse deny / ask is recorded by HookRegistry.register (not by the gate) in ~/.swarm-ai/logs/gate_decisions.jsonl, with the full …
- Very specific: line 373
Colors: Always use bg-[var(--color-*)], never hardcoded dark theme colors
- Very specific: line 407
Local main only: never a pipeline run's worktree.
- Distinctive: line 470
Design before code: Write a one-page design and get it agreed first: where each fact lives (exactly one source), who writes and who reads …
- Very specific: line 474
Find the existing source of truth first: Search for the store / endpoint / hook that already owns the fact (e.g.
- Distinctive: line 489
All commits in this repo MUST end with:
- Distinctive: line 493
Never use Claude/Anthropic identity in commit trailers.
- Very specific: line 502
Never edit files in the main checkout (swarmai/).
- Very specific: line 525
Every agent (SwarmAI app sessions, Claude Code, Kiro, Kiro Crew, Cursor, Codex) does it the same way:
- Very specific: line 554
If it happens to you, re-attach it in place, files untouched (the index is rebuilt from HEAD, so staged edits come back unstaged): python3 …
- Very specific: line 573
Write it yourself: Only the pipeline's landing (backend/core/run_protocol/landing.py) builds the trailer into its own message.
- Very specific: line 607
Do NOT change core.hooksPath: it is machine/corporate policy, and the project rules forbid modifying git config.
- Very specific: line 660
Never raise a per-test timeout (--testTimeout, --timeout) to get a run through: a test slow because the host is loaded means fewer files or …
- Very specific: line 662
Write logs inside your worktree or your own scratch directory, not a shared /tmp.
- Distinctive: line 690
Commit directly to
main: Never auto-branch; branch only when asked (worktree branches as in "Git Commits" above).
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 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 (ingestion, 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 gets a structural fix. When the same mistake shows up
3+ times, the fix is not another prose rule — it's a mechanism that makes the wrong move
unlikely or impossible. It becomes a gate in
security_hooks.pyonly when every user benefits (dangerous or off-machine actions, questions only a human can answer, a pipeline run's integrity, the session itself) and normal work keeps a way through; a gate never blocks native coding, testing or committing. A repo's own discipline lives in its AGENTS.md, pre-commit and CI (designdocs/design/2026-10-24-swarmai-usable-by-anyone.mdP3/P7). - 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.)
Who owns what (each fact lives in exactly one place):
- This file — architecture, the push gate, test/build commands, commit rules.
.kiro/steering/swarmai-dev-rules.md— platform rules, coding anti-patterns, session lifecycle invariants (Kiro auto-loads it)..kiro/steering/*(fileMatch) — deep invariants for regression-prone areas, loaded only when the matching files are in context. Plus the always-on security baseline and debugging methodology.CLAUDE.md— a short pointer to this file for tools that don't read AGENTS.md.
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 # 24h idle TTL, orphan reaper, hook enqueue chokepoint
│ ├── 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, ingestion kick, 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 (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, in priority order (the source of truth is
CONTEXT_FILES in backend/core/context_directory_loader.py):
- P0–P2 (SWARMAI, IDENTITY, SOUL): system identity + personality. System-owned, always overwritten from the template, read-only (0o444).
- P2 (SELF): the runtime self-portrait. Non-truncatable but runtime-owned:
copy-only-if-missing (0o644), so the live
.context/SELF.mdis authoritative. - 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).
- P10 (TIMELINE): private append-only episodic memory, copy-only-if-missing (0o644); whole-unit selection within a 1.5K-token budget.
Key behaviors:
ContextDirectoryLoader.ensure_directory()runs at session start — two-mode copy (system files overwrite; user/agent files preserve).- Dynamic token budget: 150K for ≥500K models, 50K for ≥200K, 30K for ≥64K, instance default for <64K (L0 compact path). Generic assembly never slices text. MEMORY and EVOLUTION are injected whole through the CDF selector (no budget, no score); over budget the loader warns, it never cuts.
- Selection is independent of the user query. It is recomputed only when the file hash changes
or at a UTC day boundary, persisted in
ingestion.db, and included in the L1 cache header. Within a day, identical source bytes produce identical fixed-layer prompt bytes. - L1 cache with budget-tier and rendering-layout validation (
<!-- budget:NNNNN;… -->header) and git-first freshness check. - In USER / STEERING / TOOLS, user-written text keeps its normal priority; CDF-extracted
rules render from
## 系统追加(自动提取)with priority below SWARMAI / IDENTITY / SOUL / AGENT. - The
truncatable/directionfields onContextFileSpecare legacy metadata and inert. They never slice content; MEMORY, EVOLUTION, and TIMELINE use explicit whole-unit selectors. - DailyActivity: today/yesterday inject complete session rows; days 3–7 inject complete day-summary blocks. Whole units are admitted into a 4K-token budget, resolved Next IDs are excluded, and omitted sessions are counted.
- Writes: CDF's ingestion writer is the only autonomous writer of MEMORY / EVOLUTION / the
user context files / DDD docs; skills submit units with
ingest submit. - 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:
WorkspaceAutoCommitHookcommits the workspace at session close (post-session hook, serialized by a shared lock), with a generated conventional message.
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 [2,4] based on available RAM (floor 2 = 1 chat + 1 channel) - 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 family of PreToolUse hooks registered per session in
backend/core/hook_builder.py (build_hooks, the source of truth for the list and order;
implementations in security_hooks.py). By category:
- Observability —
pre_tool_logger: logs every tool invocation; never blocks.cdf_usage_observerasynchronously records exact governed units reached by Read/Grep; it injects and denies nothing. - Hang prevention (Bash) —
background_command_guard(default-deny backgrounding),bash_syntax_guard(bash -nparse check). No gate touches test commands:pytest_command_guardand thetest_command_gategroup (pipeline_test_gate) were removed with the pipeline's own test runner (designdocs/design/2026-10-24-swarmai-usable-by-anyone.md§3.3.3, §3.4). A pipeline run's tests are the agent's own, run natively and reported in a validation report. - Command safety + human-in-the-loop —
dangerous_command_gate(Bash) andexternal_approval_gate(non-Bash off-machine side effects) route risky calls throughPermissionManager(permission_manager.py): an SSE approval dialog, approvals tracked per session by command hash, pending requests persisted to~/.swarm-ai/pending_approvals.json, 4h answer timeout. Besides its pattern list,dangerous_command_gateasks before a git command that discards uncommitted changes (reset --hard,checkout --,restore,clean -f,worktree remove --force) only when another live session wrote files there that are still uncommitted (shared_checkout.sibling_uncommitted; a repo that no longer exists holds nothing); ref moves (rebase, amend,branch -f,checkout --detach) are never asked — the reflog keeps the commits (design §3.8 r17). A path the command itself pins in a variable (W=/abs; git -C $W …,S=/tmp/x; rm -rf "$S") is judged as written out (designdocs/design/2026-11-25-approval-prompt-false-positives-r2.md).ask_question_gateblocks for AskUserQuestion answers; a person's pick (not the channel gateway's unattended one) on a Pipeline v1 decision card is recorded there as the run'shuman_answer— the agent's CLI has no answer command (docs/design/pipeline-v1-human-loop.md). - Scope + commit discipline —
skill_access_checker(Skill),governance_file_gate(advisory; Write|Edit, and Bash writes — sed -i, redirects, interpreter heredoc patches — to governed context files), thecommit_gategroup (Bash, registered beforedangerous_command_gate, members in order):run_amend_gate(in this session's active run, deniesgit commit --amendand points at the run's own landing (pipeline-v1 land --message) instead of lettingdangerous_command_gatepark the run on an approval prompt),active_run_commit_gate(the run's own logged owner session (RunEngine.owner_session) may not hand-commit files that run changed (RunEngine.owned_paths) or its REPORT: they land only through the run's landing; any other session, an unreadable run, or agit -C/--git-dirretarget gets an allow with a note naming the run); the others fail open. Native commits are never blocked:direct_commit_gateandadversarial_commit_gatewere removed (same design, §3.4); in native mode the agent decides which review experts a change needs (AGENT.md R2). Pipeline v1 review round limits and parallel waves are enforced by loggedhandout/answerevents incore/run_protocol/, not a marker-counting PreToolUse gate.session_link_gate(Bash, always on, registered right beforecommit_gate: denies removing or overridingSWARM_APP_SESSION_ID, the run↔session link both run gates key on; cannot be forced). A v1 run's owner is the logged one (its contract's session, then eachowner_transfer), never run.json; a prewarmed subprocess that has noSWARM_APP_SESSION_IDgets this session's id fromrun_owner_gate, which puts it before the onepipeline_v1call it binds.audit_marker_write_gate(Bash and Write|Edit|MultiEdit|NotebookEdit, always on, right afterbackground_command_guard, ahead of every HITL gate): denies writes, moves or deletes instate/pipeline_agent_audit, which holds the review markers and every run's event log. Since S6-3 that log is append-only with a checksum per record, not signed (designdocs/design/2026-10-24-swarmai-usable-by-anyone.md§3.3.5): a torn last line is dropped, a damaged record stops the run for a person. The gate guards against mistakes and can be forced. It denies only what writes: acdinto the directory, and interpreter code that only reads it, pass. Per-run worktrees (docs/design/pipeline-run-worktree.md; every run gets them and nothing turns them off: S6-5 removed the shared mode, where a run edited the main checkout, and$SWARM_WORKTREE_MODE):run_owner_gate(Bash, right aftercommit_gate; for a mutatingpipeline-v1call it reads the owner from the run's logged events, never run.json, takes a crashed owner's run over only when the old owner is confirmed not live (writing anowner_transferevent first, so human authorizations follow the new owner) and denies while the owner is live or its liveness is unknown; it puts this session'sSWARM_APP_SESSION_IDbefore a pipeline call that is the first command of the line (an adopted prewarm subprocess has none) viaupdatedInput— no other Bash hook may setupdatedInput; it denies a Bash call to the human-only/api/pipelines/<id>/decision). Pipeline commands are recognised in one place,core/pipeline_command.py. The agent runs"$SWARM_BACKEND_BIN" pipeline-v1 <sub>(packaged and dev alike:SWARM_BACKEND_BINis the daemon's own program, in dev thebackend/bin/python-backendshim;desktop_main.pyalso haspy <script>for Python without a system interpreter). That is the only form (S6-5 removed thepython …/pipeline_v1.pyscript andutils/source_repo.py; the CLI iscore/run_protocol/cli_main.py). Pipeline commands run in the agent's own process, daemon up or not (S6-3: the daemon execution socket, the hook token and the signing key were removed); a command acts only for the run's owner session.run-land/accept-finding/discard-snapshotwith--requestneed the person's approval: after it, the gate writes theauthevent from the run'sland_requestevent (the approval card shows the trees from that event; execution reads only it) andworktree_write_gate(Write|Edit|MultiEdit|NotebookEdit|Bash|Read|Grep, its own group; keeps an isolated run's writes in its own worktrees, denies a write into any other isolatable git repo with thepipeline-v1 create --repocommand for a run that includes it (v1 repos are fixed at create), denies a write under a v1 run's.aidlc/deliverables/(its landing writes it), denies stash / shared-ref changes from a run worktree). Run liveness everywhere (run_index.LIVE_STATUSES, the worktree sweeper, these gates) counts every non-terminal v1 status. Only runs with a protected v1 contract exist: the old pipeline (artifact_cli run commands,stage-start, run.json-only runs) is retired. - Review-expert scope (
core/pipeline_expert_agent.py) — every session defines thepipeline-expertsub-agent type (Read/Grep/Glob/Bash only, effort medium, maxTurns backstop).expert_type_gate(Agent|Task, app sessions, main thread) denies anEXPERT-ID:spawn of any other type;expert_budget_gate(Read|Grep|Glob|Bash, inside a pipeline-expert) denies every call past 24 and tells the expert to report now with what it did not reach marked UNCHECKED. Both fail open. - Session protection —
image_read_dedup_guard(a re-read of an unchanged image). This repo's own wording and frontend-style rules are not product hooks: runpython scripts/lint_terms.py --stagedbefore committing here (CI runs it on each push's added lines). - Repository guidance (inject-only) —
repo_guidance(PostToolUse, Read|Grep|Glob|Bash) andrepo_guidance_pre(PreToolUse, Write|Edit|MultiEdit|NotebookEdit): the first time a session touches a git repo, itsAGENTS.md,CLAUDE.mdand.swarmai/review.mdgo into context (core/repo_guidance.py); bound repos as norms, others as unconfirmed; never a deny. Two hooks'hookSpecificOutput.additionalContexton one matcher are joined, not overwritten (hook_builder._merge_specific).shared_checkout/shared_checkout_pre(same matchers): the first time a session works in a repo where another live session has files it wrote that git still reports as uncommitted, a note names them and the session-worktree command (scripts/session_worktree.pycreate / land / remove, under<app data>/session-worktrees); inject-only, once per session per repo (core/shared_checkout.py, design §3.8).
Every PreToolUse deny / ask is recorded by HookRegistry.register (not by the gate) in
~/.swarm-ai/logs/gate_decisions.jsonl, with the full tool input; dangerous_command_gate, which
waits for the person itself, writes its own row per prompt with the person's answer and the
rule it matched (rule, match); python
backend/scripts/gate_audit.py --samples 3 counts them per gate per day. A gate is kept,
merged or removed on that evidence.
One operator switch replaces the ten per-gate SWARM_*_FORCE=1 variables (2026-10-20,
core/gate_force.py): SWARM_GATE_FORCE=<gate or group>,... in the backend/daemon env
(groups commit_gate, expert_gate). Each use is logged as force_bypass. session_link_gate
cannot be forced: every run gate keys on the link it protects.
Plus can_use_tool file-access control, workspace isolation, and error sanitization. These
gates are the product-level ones SOUL P7 allows (every user benefits, normal work keeps a way
through). When adding one, register
it in hook_builder.py and update this list — don't restate it in other docs.
Debugging
Startup Failures ("Backend service failed to start")
- Open DevTools Console (Cmd+Option+I) → look for
[Platform]and[Health Check]logs. A release App has the inspector only when launched withSWARMAI_DEBUG=1(macOS: quit it, thenopen --env SWARMAI_DEBUG=1 -a SwarmAI);tauri devalways has it. [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: system stack — SF Pro + PingFang SC on macOS (
--font-family-sans); SF Mono, JetBrains Mono as fallback, for code only (--font-family-mono). One definition, indesktop/src/index.css - 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
Nav visual system (Left Nav, overlays, Workspace)
One type scale, one palette, one button scale for the Left Nav, OverlayHost and every
overlay (design docs/design/left-nav-backend-and-visual-system.md V1–V6):
- Type: six steps only,
text-meta/small/body/heading/title/display= 11/12/13/14/16/20px (each with its line height). Notext-[Npx], no inlinefontSize, no Tailwindtext-xs…2xl. Weights 400 and 600 only (nofont-medium/font-bold). - Colour: theme variables only —
--color-status-*,--color-primary,--color-text*, zone accents--color-zone-cognitive/work/system. A colour with no role gets ONE token inindex.css(--color-on-accent,--color-scrim[-medium|-strong],--shadow-overlay, …); a tinted surface iscolor-mix(<status colour> N%, transparent), never a dark-only hex. - Icons: Material Symbols, never colour emoji (comments included).
- Buttons: labelled →
btn-sm/md/lg+ one look class; icon-only →icon-btn(icon-sm) oricon-btn-lg(icon-md). Tabs, segments and switches carryrole="tab"/"radio"/"switch". - Shared parts:
components/overlay/index.tsx(Stat,SectionLabel,Tabs,Segmented,StatusBadge,Hint,tableHeadClass,ROW_1/ROW_2) andcomponents/layout/OverlayState.tsx(loading / error / empty). Use them, don't restyle. - Guard:
desktop/src/__tests__/navVisualSystem.test.tscounts bypasses per file and must equalKNOWN, which is{}. A new nav / overlay file is added to itsFILES.
Workspace overlay — what it is
The Workspace nav item is where the user browses their working directories by hand
(design docs/design/workspace-working-location.md v5). It is not a view of what the agent
is doing.
- Locations: SwarmWS (always first, default) plus each repo a DDD declares in
bindings.yaml(worktree) that is a main checkout (.gitis a directory) with.git/logs/HEADinside 30 days. No other source (not runs, not the chat's repo). - Local main only: never a pipeline run's worktree; bound to no session and no run (N
runs may be in flight). Repo locations are read-only — write endpoints refuse
location. - Standalone: each location has its own tab, stats, tree, filter and error; only the
shown location is fetched (
/workspace/locationsstats only,/workspace/summary?location=is one location). - Light stats only:
N changed, per-folderchanged_count, last commit time. Never "in progress". - No polling: fetched on open, on refresh (
fresh=true) and after a write.ExplorerProviderlives inside the overlay, not in the app shell. - Chat-safe: its endpoints run on the
navpool (executors.run_nav) and every git read setsGIT_OPTIONAL_LOCKS=0— the rule for every Left Nav backend (tests/test_nav_pool_and_git_locks.py).
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 DDD maintenance — queued events (git commit, 30-minute timer) run the orchestrator's DDD staleness channel; DDD knowledge itself is written by CDF (core/ingestion/) |
| Autonomous Pipeline (staged runs) | backend/skills/s_autonomous-pipeline/INSTRUCTIONS.md | Profile-driven runs (full: EVALUATE→THINK→PLAN→BUILD→REVIEW→TEST→DELIVER→REFLECT) with expert review gates |
| Pollinate Content Engine | backend/skills/s_pollinate/INSTRUCTIONS.md | Content creator for work that gets revised: HTML decks (PDF/PPTX export), posters, long images, reports, platform copy |
| 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 | Five-layer resume context (checkpoint, git state, conclusions, key tool results, recent conversation) within a model-aware token budget |
| Slack Channel Adapter | backend/channels/adapters/slack.py | Socket Mode bot with HTTP polling fallback — responds on the owner's behalf to allowlisted users |
| Background Job System | backend/jobs/scheduler.py | In-process scheduler of the background service — headless agent tasks, deterministic scripts, the weekly commit reader and other system jobs |
| AI Docs Auto-Refresh | backend/scripts/refresh_ai_docs.py | Regenerates the METRICS block (docs/CODEBASE_METRICS.md) and CAPABILITIES block (AGENTS.md + AI_CONTEXT.md) — run by hand, by prod.sh preflight, and by the post-session context health check at most once a day |
<!-- 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.
Change Discipline — design first, no patching
A fix that lands one day and needs a follow-up fix the next is a design miss, not iteration. For a change that spans backend + frontend, several files, or adds a store, endpoint or hot-path hook:
- Design before code. Write a one-page design and get it agreed first: where each fact lives (exactly one source), who writes and who reads it and when, the invariants, and the MEASURED cost it adds on the hot paths (send, each streamed token, each file write).
- Find the existing source of truth first. Search for the store / endpoint / hook
that already owns the fact (e.g.
product_registryfor what a file is) before adding one. A second source for the same fact is a bug unless the design says why. - Never guess. What cannot be computed exactly is left off or marked unknown, never filled by a heuristic ("newest 4", "last 24h"). A resource cap is fine, but what falls past it is left off too, not guessed.
- Measure hot paths before merging. Anything on send or the stream comes with
measured timings and proof it runs off the event loop and off the pools the chat path
waits on (
core/executors). - Self-review before merging. List every heuristic, second source and temporary workaround in the commit message. Resolve each one first; if one cannot be resolved, say so to the user.
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. Every commit lands on main (project convention); never push a branch. Branches
exist only as short-lived, local worktree branches, deleted once their commit is on main:
an isolated pipeline run works on run/<run_id> in ~/.swarm-ai/worktrees/<run_id>/<repo>
and lands by merge --ff-only (docs/design/pipeline-run-worktree.md §11); any other agent
follows "Code changes outside a pipeline run" below.
Code changes outside a pipeline run — always in your own worktree
Never edit files in the main checkout (swarmai/). Several sessions edit this repo at once and
share that checkout and its git index: an edit there gets swept into another session's
commit, a commit made there picks up another session's staged files, and an uncommitted edit
there blocks a run's merge --ff-only landing. All three happened on 2026-10-19.
- Nothing enforces this for any agent (the worktree gate's rule that sent SwarmAI app
sessions' main-checkout writes to a run was removed: design
docs/design/2026-10-24-swarmai-usable-by-anyone.md§3.4). It is this repo's own rule, so follow the steps below yourself. Before committing here, have review experts check the change (correctness, plus security / concurrency / integration as it touches them) and fix what they find; that is this repo's convention, not a product gate. A direct pipeline run (create --profile direct --requirement "<the user's words>") goes build -> review -> test -> deliver -> reflect: no PLAN, no requirements/design documents, no exit criteria; BUILD and TEST end with the agent's own validation report on the current tree (BX-3, TS-1); for this repo,backend/scripts/swarm_select_tests.pyprints which backend tests andvalidations.jsonchecks a change needs. An ambiguous request is abandoned and re-run as trivial. Which review experts a run dispatches is decided bycore/run_protocol/review.pyreviewers(), called fromengine.pyat REVIEW:correctnesswhen the change has at least 50 non-test source lines (.md/.txt/.rstdo not count) or a row of the repo's.swarmai/review.mdtriggers (and whenever those rows cannot be read);securitywhen a risk is declared (review.md'ssecurity:line, the BUILD report'srisk, or a design with security boundaries). A change with none of these dispatches no expert; its report and landing checks still run. - Every agent (SwarmAI app sessions, Claude Code, Kiro, Kiro Crew, Cursor, Codex) does it the same way:
git worktree add --lock --reason "<agent> session scratch" -b <agent>/<topic> <scratch>/wt-<topic> main
# NOT under ~/.swarm-ai/worktrees; --lock: see "Never prune" below
# edit + test inside the worktree; run tests with the main checkout's venv python
# (backend/.venv/bin/python, or a .venv symlink to it in the worktree);
# start pytest from the worktree's backend/: the venv's editable-install .pth puts the MAIN
# checkout's backend on sys.path, so a script run elsewhere imports main's core, not yours;
# frontend: symlink desktop/node_modules from the main checkout
git commit -- <paths> # explicit pathspec, never a bare `git commit -a`
git rebase main # main moves every few minutes
python3 backend/scripts/check_no_revert.py <agent>/<topic> # exit 1 = it undoes main
git -C <main checkout> merge --ff-only <agent>/<topic>
git worktree unlock <scratch>/wt-<topic>
git worktree remove <scratch>/wt-<topic> && git branch -d <agent>/<topic>- Never run
git worktree prunein this repo, and lock your worktree. Agents run in sandboxes that cannot see each other's scratch directories (a Kiro Crew session's~/.kiro/crew/scratch/runtime-<id>/isOperation not permittedfrom any other session). From your sandbox another session's live worktree therefore looks deleted:git worktree listmarks itprunable, andgit worktree prunedeletes its.git/worktrees/<name>entry. Its files survive, but every git command there then fails with "not a git repository" (2026-10-25: three sessions' worktrees lost this way, mid-work; one by this very rule's author). A locked worktree is never pruned, so--lockataddprotects yours from everyone else;prunableon someone else's worktree is not yours to fix. Only remove your own worktree, by its path, aftergit worktree unlock. - If it happens to you, re-attach it in place, files untouched (the index is rebuilt from
HEAD, so staged edits come back unstaged):
python3 backend/scripts/worktree_reattach.py <scratch>/wt-<topic> --branch <agent>/<topic>. It comes back locked. - Squash only from the merge base:
git reset --soft $(git merge-base HEAD main), nevergit reset --soft main. The second keeps your worktree's old tree and commits it on top of the current main, so every file another session landed since you branched goes back to the old version;rebaseandmerge --ff-onlyboth pass it (2026-10-24,a23fc2a00undid 8 commits in 30 files).check_no_revert.pyrefuses that branch: a file it changes back to the version it branched from while main changed it since (session_worktree landruns it). ~/.swarm-ai/worktrees/belongs to the pipeline: its hourly sweeper moves anything there that is not a run's worktree into.quarantine/. Put yours in your agent's scratch dir.merge --ff-onlyrefused with "would be overwritten" means another session has an uncommitted edit to a file you changed. Never stash, restore or overwrite it. Wait for that session to commit, or, when the edits do not overlap, back up its file, ff-merge onto the committed version, put its file back (git merge-file3-way) and check its hunks survived.- Not-fast-forward:
git rebase mainagain, re-run the affected tests, retry.
Write it yourself. Only the pipeline's landing (backend/core/run_protocol/landing.py)
builds the trailer into its own message. For any commit you make by hand, add the Swarm line
yourself, and never a Co-Authored-By: Claude … <noreply@anthropic.com> line.
core.hooksPath on this machine points at the corporate git-defender hook set, and
git-defender then runs the repo-local .git/hooks too. So the repo-local hooks are LIVE
(observed 2026-10-22: in a scratch repo all four of pre-commit, prepare-commit-msg,
commit-msg, post-commit fired; in this repo prepare-commit-msg rewrote a commit's
Claude trailer to Swarm). An earlier version of this file called them dead; that was wrong.
| repo-local hook | what it guards | status |
prepare-commit-msg | sed-rewrites Co-Authored-By: Claude…<noreply@anthropic.com> → Co-Authored-By: Swarm <swarm@swarmai.dev> | live |
pre-commit | CMHK SDK-drift check | live |
pre-commit | scripts/lint_doc_frontmatter.py --staged (when docs/*.md is staged); CI runs the same check as --diff BASE on the docs a push / PR adds or modifies | live |
pre-commit | scripts/sync_discussions.py --check mirror drift (when docs/discussions/ is staged) | live |
pre-commit | scripts/precommit_bvt_manifest.sh: when backend/tests/ is staged, backend/tests/bvt_manifest.txt must name only files that exist (deleting a test without its manifest line stops the BVT); CI's BVT step fails the same way | live |
pre-commit | scripts/precommit_uv_lock.sh: when backend/pyproject.toml is staged, backend/uv.lock must match it (uv lock --check); CI, release builds and Hives install exactly the locked versions with uv sync --locked, which refuses a stale lock | live |
pre-commit | scripts/precommit_breaks.sh: a staged change that breaks a caller (a removed function still called, a removed keyword still passed, a new required parameter not passed), from the code graph (core.code_intel.changed --staged --breaks); only such a definite break blocks, anything it cannot check lets the commit through with a line | live |
What these hooks do NOT cover:
prepare-commit-msgonly rewrites a Claude trailer that is already there, spelled exactlyCo-Authored-By:(the sed is case-sensitive). It never adds a missing Swarm line.- It also runs on
--amendand is not skipped by--no-verify. A Claude trailer cannot be put back with an amend, and that is intended. .git/hooksis not versioned. A fresh clone or another machine has none of these hooks.--no-verifyskipspre-commitandcommit-msg(git-defender logs a bypass warning).
There is no CI or PreToolUse trailer check. The PreToolUse commit_trailer_gate was removed
2026-08-16 (73378945: a project's private convention must not be a product-wide runtime
hook), and the CI trailer check was removed the same day (b493577a).
scripts/check_commit_trailers.py remains for optional local use:
python3 scripts/check_commit_trailers.py.
Do NOT change core.hooksPath: it is machine/corporate policy, and the project rules forbid
modifying git config. Any check that must run on every machine belongs in CI.
(git-defender runs its hooks synchronously on every commit. Measured 2026-10-18 in this repo:
0.4–0.8 s for commits of 4–162 files, 2.3 s for an amend, 1.4 s for a rebase, 0.3 s for an
ff-only merge. The old "allow ~600 s" no longer holds; a commit that takes minutes is a symptom
to investigate, not a budget to plan around.)
Development Commands
./dev.sh # Full dev: backend (port 8000) + Vite + Tauri window
./dev.sh backend # Backend only
./prod.sh build # PyInstaller + verify + deploy to daemon
./prod.sh release # Full release cycle
./prod.sh status # Daemon health + versions
cd desktop && npm run build:all # Frontend production build (embedded in the .app)backend/pyproject.tomlis the dependency source of truth: runuv lockafter changing it.- In the PyInstaller build
sys.executableis the app, not Python: import modules directly, never spawnsys.executable -m ….
The step-by-step ops skills for this repo (s_swarm-build, s_swarm-daemon,
s_swarm-release, s_swarm-ci, s_health-check, s_chat-brain-check) are not built-in
product skills: they belong to the SwarmAI DDD (Projects/SwarmAI/4-capabilities/) and find
this checkout from the worktree: in its bindings.yaml. A contributor gets them by importing
that DDD package.
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. What an agent runs itself (dev build):cd desktop && npm run build(tsc + Vite + bundle-size check, no backend packaging, no install, no deploy) as ONE foreground Bash call with an explicittimeout: 600000; the 120s default is too short for it. Never background it../prod.sh build,npm run build:all(it runsbuild-backend.shPyInstaller,npm installandtauri build) andbuild-backend.shstay the user's manual step (see the SwarmAI DDD'ss_swarm-buildskill): autonomous work never packages, deploys or restarts the daemon. - Tests — at least the affected suites, wrapped with a wall-clock cap:
cd backend && perl -e 'alarm 90; exec @ARGV' python -m pytest tests/test_<module>.py -v --timeout=60(theexec @ARGVis required — without it perl exits 0 and pytest never runs;gtimeoutis not installed here; a per-test--timeoutalone is not a cap, and a pytest still running at the Bash timeout is moved to the background and returns nothing). Frontend:cd desktop && npm test -- --run. Last-failed: add--lf. Time budget per call: one heavy step (tsc, a group of vitest files, a group of pytest files) per shell call, each with its own wall-clock cap. If you chain steps in one call, their caps added together must stay under the call's own timeout; otherwise the call is moved to the background and returns nothing. Frontend test cap:cd desktop && perl -e 'alarm 300; exec @ARGV' npx vitest run <files> --maxWorkers=2. Never raise a per-test timeout (--testTimeout,--timeout) to get a run through: a test slow because the host is loaded means fewer files or wait; a test slow on its own is a bug. Write logs inside your worktree or your own scratch directory, not a shared/tmp. A red run is truncated:backend/pyproject.tomladdoptscarries--maxfail=3, so after the 3rd failure pytest stops and every later test never runs — the "N passed, 3 failed" summary is not the scope's real count, and the 3 failures may be one cause hiding 30 more. Before you judge a red result or report numbers, re-run that scope with--maxfail=1000(2026-10-22: a findings file showed 3 failures; all 33 of its tests were red, and a 40-file "233 passed" was really 597). Full suite (SWARMAI_SUITE=1, cap ≥120s per test) only on explicit request or when the blast radius clearly warrants it — never as a reflex. Scope comes from the change: the test files of the changed functions and of their direct callers;python scripts/swarm_select_tests.py --base main(frombackend/) lists candidates by import, to pick from.tests/conftest.pyrefuses a dev-box run wider than one change's tests (over 25 files or 800 tests, counted after-k/-m) before any test runs, so a list built from a glob, a directory orlsstops there; CI andSWARMAI_SUITE=1(a wide run asked for on purpose,scripts/run_bvt.sh) pass. - 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."
SwarmAI development conventions
These hold for work on this repo. The shipped context files (backend/context/) state only
the generic rule, because they are injected into every user's prompt; the SwarmAI-specific
form lives here.
- Commit directly to
main. Never auto-branch; branch only when asked (worktree branches as in "Git Commits" above). - A change is live only after rebuild + restart.
./prod.sh buildmakes the binary; the daemon runs the old code until it is rebuilt and restarted (commit ≠ qualified ≠ deployed). - Daemon lifecycle (macOS, launchd).
SIGTERM= restart (KeepAlive brings it back);launchctl bootout= permanent deregister; deploy = SIGKILL + bootout + rsync of the new build + bootstrap. Never from a child process of the daemon. Restart, stop and deploy are destructive: the user's explicit approval first, never "just to verify". - Ports. Daemon (and subprocess, Hive) health:
GET /healthon :18321. The dev backend (./dev.sh) listens on :8000. - Environment. A macOS GUI app does not get the login shell's PATH: run a command that
needs it as
zsh -lic '<command>'. Never assume the daemon has your shell's environment. With the Claude Code sandbox turned on,pgrep/ps/topcan be blocked (it is off by default). CJK keyword matching uses a substring fallback (CJK text has no word boundaries). - Chat smoke check (the end-to-end smoke of AGENT R16 for this repo): send 1 message → it streams → it persists on tab switch.
- Eval only on the deployed binary. The system eval scores the deployed daemon; run on un-deployed code it tests the old binary and can hang the judge. CI runs only the eval machinery's own unit tests, never an eval.
Release checklist
Releases run through the SwarmAI DDD's s_swarm-release skill (./prod.sh release). Before
tagging:
- The local quality gate above is green (Build, Tests, Eval check).
- Context strip-test review. A zero-context reviewer (a sub-agent given no session
history) reads
git diff <last-tag>..HEAD -- backend/context(<last-tag>=git describe --tags --abbrev=0) and applies the strip test to every added or changed sentence: remove this user, this machine and this repo — is it still true and useful on a stranger's fresh install (any OS, any repo, any user with an AWS account)? It reports its findings (file, sentence, why it fails, where it belongs: this AGENTS.md, a user's own file or a DDD). It does not block the release: fix the findings in a follow-up commit or record them as known issues.
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.
- Proportionate delivery — code changes are native by default, with review experts the
agent picks for the change; the autonomous pipeline is the optional advanced mode (one
requirement → documented, expert-reviewed, isolated, landed code) that runs when the user
chooses it. Design:
docs/design/2026-10-24-swarmai-usable-by-anyone.md. Until its S4 step lands, the gates described under "Security Architecture" still fire as written.
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.

