Autonomous Claude Code Orchestration

Build. Learn. Evolve.
Without stopping.

Monomind wraps Claude Code with persistent memory, multi-agent swarms, a code knowledge graph, and keyword routing with outcome measurement β€” all wired into one CLI.

GitHub
0Agent Types
0CLI Commands
0Hook Events
0Packages
Why Monomind?
🧠
Persistent Memory
Four-tier memory palace (L0–L3) with BM25 search, plus a JSON pattern store with episodic recall injected at prompt time. Context survives across sessions.
🐝
Swarm Topologies
Experimental in-process multi-agent coordination β€” hierarchical, mesh, adaptive, and hybrid topologies with vote-count consensus thresholds (bft, raft, quorum).
πŸ”—
Knowledge Graph
Monograph builds a full dependency graph of your codebase β€” 19 MCP tools by default (27 more via MONOGRAPH_MCP_ADVANCED=1) for impact analysis, dead code detection, path finding, and multi-repo queries.
⚑
Outcome-Measured Routing
Deterministic keyword routing with route-outcome correlation. Every hook event is logged so routing accuracy and adherence can be measured by doctor.
πŸ”
Autonomous Loops
--tillend runs a command until nothing is left to do. /mastermind:autodev --tillend researches, builds, reviews, and loops while you sleep.
🎣
Hook System
20 typed hook events (PreEdit, PostEdit, SessionStart...) in the registry/executor, plus 29 separate hooks CLI subcommands and 15 background workers. Zero-overhead dispatch across editing, tasks, sessions, and agent teams.
Quick Install
# Install globally npm install -g monomind # Wire into Claude Code claude mcp add monomind npx monomind@latest mcp start # Initialize a project npx monomind init npx monomind doctor --fix
1. Installation
# Option A: global install npm install -g monomind # Option B: npx (always latest) npx monomind@latest --version
2. MCP Setup

The MCP server requires the explicit mcp start subcommand. Auto-detect is disabled by default (set MONOMIND_MCP_AUTODETECT=1 to restore legacy behavior).

claude mcp add monomind npx monomind@latest mcp start # Verify tools are registered claude mcp list
3. Project Initialization
cd your-project npx monomind init # Interactive wizard: topology, memory backend, hooks npx monomind hooks worker list # Background workers (security, health, learning...) run at session start npx monomind doctor --fix # Checks: Node 20+, git, config, worker metrics, DB, MCP, disk
4. First Session
claude β€” live session
5. Autonomous Loop
# Research β†’ Build β†’ Review until nothing left /mastermind:autodev --tillend # 9 improvements, then stop /mastermind:autodev 9 --tillend # Review loop until clean /mastermind:review --tillend --auto
Core Commands Quick Reference
CommandWhat it does
npx monomind initInitialize project with wizard
npx monomind doctorHealth diagnostics; auto-fix with --fix
npx monomind hooks worker run <name>Run a background worker on demand
npx monomind memory storeStore a memory with optional namespace
npx monomind memory searchKeyword/BM25 search over stored memories
npx monomind org run <name>Start a persistent SDK-backed agent org
npx monomind hooks listShow all registered hooks
/mastermind:autodevAutonomous build loop inside Claude Code
System Diagram
@monomind/cli 32 commands Entry point @monoes/hooks 20 hook events Β· 15 workers Intelligence pipeline @monoes/mcp HTTP/WebSocket transports stdio uses CLI's own loop @monoes/memory SQLite + local embeddings Default engine, LanceDB removed @monoes/monograph 19 + 27 MCP tools Code knowledge graph @monoes/routing semantic routing (opt-in) route-outcome measurement monofence-ai Prompt-injection defense Input validation @monoes/monobrowse Browser automation via CDP No Playwright/Puppeteer @monoes/monodesign Design tokens Β· 51 antipattern rules Independent design intelligence
Package Inventory
PackagePathPurpose
@monomind/clipackages/@monomind/cli/CLI entry point β€” 32 commands, including org (org runtime v2, see src/orgrt/) and swarm (in-session coordination bookkeeping)
@monoes/hookspackages/@monomind/hooks/20 typed hook events (registry/executor) + 15 background workers; exposed via 29 hooks CLI subcommands
@monoes/memorypackages/@monomind/memory/Memory backends β€” local SQLite with embedded vectors (default engine, local HF embeddings); a dormant pure-JS HNSW index is the scale-up path. LanceDB was removed 2026-07
@monoes/mcppackages/@monomind/mcp/MCP server framework for explicit HTTP/WebSocket transports (mcp start -t http|websocket). The default stdio path (claude mcp add ... mcp start) uses a separate hand-rolled JSON-RPC loop in the CLI itself, not this package.
@monoes/routingpackages/@monomind/routing/Real embedding-based semantic router (keyword pre-filter β†’ local embedding β†’ cosine similarity β†’ LLM fallback) β€” opt-in via route semantic, agent --task, or hooks_route_semantic. The bare monomind route <task> default is a separate, simpler keyword-only stub that doesn't call this package. Both feed route-outcome measurement.
monofence-aipackages/monofence-ai/AI manipulation defense β€” prompt injection, jailbreak, evasion detection
monographpackages/@monomind/monograph/Code knowledge graph β€” 19 default MCP tools, 27 advanced via MONOGRAPH_MCP_ADVANCED=1 β€” published standalone as @monoes/monograph
@monoes/monobrowsepackages/@monoes/monobrowse/Browser automation via CDP
@monoes/monodesignpackages/@monoes/monodesign/Frontend design intelligence v1.2.0 β€” design tokens + 51-rule antipattern detector (slop/quality/performance/accessibility). Sole design agent β€” 8 retired agents consolidated into it. Produces image prompts, not images (image generation is the separate monoagent-image skill).
monomind/ (root)Umbrella package published to npm
Model Routing (hooks model-route)

Routes a task to Haiku, Sonnet, or Opus by a complexity score (0–1) β€” a real, working feature. There is no separate zero-LLM "booster" tier; that was a dangling reference to an MCP tool (agent_booster_edit_file) that was never implemented.

TierModelComplexityPrice (in/out per M tokens)Use Cases
1Claude Haiku≀ 40%$1 / $5Simple, low-complexity tasks
2Claude Sonnet40–70%$3 / $15Default β€” balanced reasoning
3Claude Opus> 70%$5 / $25Architecture, security, complex reasoning
Memory Palace β€” Four Tiers
Memory Palace visualization Memory Palace tier diagram
L0
In-flight
Current session context. Stored in drawers.jsonl. Each drawer has a key, value, tags array, timestamp, and score. Ephemeral β€” not persisted across sessions unless promoted.
L1
Working
Cross-session working memory. Closets store aggregated entries from multiple drawers. Closet boost adds +0.5 per matching search term. BM25 parameters: K1=1.5, B=0.75.
L2
Long-term
Pattern store + episodic recall. Patterns live in plain JSON (patterns.json, auto-memory-store.json) loaded by intelligence.init() at session start; episodic memories (episodic/episodes.jsonl) are keyword-matched and injected at prompt time. No vector database in the hot path.
L3
Deep search
BM25 over all drawers. Full-corpus search across drawers.jsonl with closet-term boosting β€” the most comprehensive retrieval layer, used on explicit search calls.
Storage
StoreUse CaseNotes
patterns.json / auto-memory-store.jsonLearned patterns, prompt-time recallDefault hot path. Plain JSON, keyword matching.
episodic/episodes.jsonlEpisodic recallKeyword-matched against the prompt; injected as context.
palace/drawers.jsonlVerbatim BM25 search800-char chunks, scored on retrieval.
SQLite + local embeddings (default)Semantic + keyword search, local vectorsbetter-sqlite3 with sql.js WASM fallback; local HF embeddings; no data leaves the machine. LanceDB was removed 2026-07; a dormant pure-JS HNSW index is the scale-up path if needed.
Monograph β€” Code Knowledge Graph

Monograph builds a SQLite-backed graph of your codebase via tree-sitter β€” nodes are files/classes/functions, edges are imports/calls/dependencies. 46 MCP tools total: 19 exposed by default (navigation, impact analysis, dead code, index lifecycle) plus 27 advanced tools (Cypher queries, snapshots, export, wiki, multi-repo groups) enabled with MONOGRAPH_MCP_ADVANCED=1. PPR graph reranking (HippoRAG-style) is on by default for query/suggest results. 13 language grammars supported: C, C#, C++, Dart, Go, Java, Kotlin, PHP, Python, Ruby, Rust, Swift, TypeScript/JS, and Vue. Use it before touching 3+ files. Also available standalone as @monoes/monograph.

ToolWhen to use
monograph_suggestStart every task β€” returns relevant files ranked by task description
monograph_queryBM25 keyword search; returns file + line number
monograph_impactBefore changing anything β€” full blast radius analysis
monograph_context360Β° view of a file: importers, imports, siblings
monograph_god_nodesHigh-centrality files (external/test auto-filtered)
monograph_shortest_pathHow two modules connect
monograph_renameDry-run multi-file rename with graph + text occurrences
monograph_dead_codeFind dead exports, orphan files, stale dist artifacts
monograph_detect_changesMap git diff to affected graph nodes
monograph_communityFiles forming a cohesive module cluster
monograph_cypherAd-hoc graph queries (Cypher syntax)
Second Brain β€” Document Knowledge Base

Second Brain indexes your project's documents (PDF, DOCX, Markdown, TXT, RTF, and more) into a searchable knowledge base. During monomind init, the directory scanner detects document files and auto-ingests them β€” chunked, hashed for dedup, and stored in the knowledge base for retrieval. Agents can then query business docs, compliance policies, or design specs without leaving Claude Code. A separate global cross-project brain (~/.monomind/global-brain) persists knowledge across every project on the machine and is deliberately kept outside any single project's data dir, so it survives monomind cleanup --data.

Step 1
SCAN
Directory scanner classifies files by extension (.pdf, .docx, .md, .txt, .rtf, .pages, .odt, .rst, .tex, .epub). If enough match, the "documents" capability activates.
Step 2
EXTRACT
Text extraction via pdf-parse (PDF), mammoth (DOCX), or direct read (plain text). Each document is chunked into 3200-char segments with 400-char overlap, respecting paragraph boundaries.
Step 3
INDEX
SHA-256 content hashing for deduplication. Chunks are stored under the knowledge:<scope> namespace. Metadata logged to .monomind/knowledge/doc-metadata.jsonl.
Step 4
QUERY
Search via knowledge_search MCP tool or monomind doc search CLI. Returns ranked excerpts with relevance scores.
CLI β€” monomind doc
CommandDescription
doc ingest <path>Index documents from a file or directory into the knowledge base
doc search -q "query"Search over indexed documents (supports --limit, --scope, --min-score)
doc listList all indexed documents with chunk counts and sizes
doc exportExport knowledge base as OKF bundle (Markdown + YAML frontmatter)
OKF β€” Open Knowledge Format

OKF is a portable interchange format for knowledge bases. Each document becomes a Markdown file with YAML frontmatter (type, title, resource path, tags, content hash, chunk count) plus an index.md linking them all. Use it to move knowledge between projects, share with teammates, or back up your Second Brain.

OperationCLISlash Command
Exportmonomind doc export -o ./bundle/mastermind:okf-export
Importmonomind doc ingest ./bundle/mastermind:okf-import
# Export your knowledge base monomind doc export -o ./my-knowledge -s shared # Import an OKF bundle from another project monomind doc ingest ./their-knowledge -s shared # Or use slash commands inside Claude Code /mastermind:okf-export -o ./bundle /mastermind:okf-import ./bundle
Learning Pipeline
Step 1
RETRIEVE
Keyword/Jaccard scoring of stored patterns and episodes against the prompt. Top matches are injected as context.
Step 2
LOG
Trajectories, steps, and command/route outcomes are recorded (intelligence.ts, command-outcomes.ts, route-outcomes.ts).
Step 3
MEASURE
Recommended routes are correlated with actual outcomes; doctor reports routing accuracy and adherence.
Step 4
CONSOLIDATE
Dedup, detect contradictions, and prune old patterns from patterns.json.
Hook Commands

These are hooks CLI subcommands (invoke as npx monomind hooks <name>) β€” a curated subset of the full 29. They aren't a 1:1 list of the 20 typed HookEvent registry/executor events (e.g. PreEdit/PostEdit); some rows below, like the intelligence and teams commands, are separate CLI/Claude-Code mechanisms rather than registry events.

CommandCategoryDescription
pre-editcoreContext and agent suggestions before editing a file
post-editcoreRecord edit outcome for pattern logging
pre-commandcoreIntercept command before execution
post-commandcoreRecord command result
pre-taskcoreRegister task start; get AGENT_BOOSTER_AVAILABLE or TASK_MODEL_RECOMMENDATION
post-taskcoreRecord completion; train patterns
session-startsessionRestore cross-session context
session-endsessionPersist state; flush working memory
session-restoresessionReplay session state into context
notifysessionPush notification to user or external system
routeintelligence3-tier model routing decision
explainintelligenceExplain decision rationale
pretrainintelligencePre-training signal ingestion
build-agentsintelligenceAuto-spawn agents for a task
transferintelligenceTransfer learning across tasks
teammate-idleteamsAuto-assign task to idle teammate
task-completedteamsTrain patterns; notify team lead
Background Workers
WorkerPriorityFunction
healthhighMonitor disk, memory, CPU, processes
securityhighScan for secrets, vulnerabilities, CVEs
audithighSecurity audit β†’ metrics/security-audit.json
swarmhighMonitor swarm activity and agent coordination
performancenormalBenchmark search, memory, startup performance
patternsnormalConsolidate, dedupe, optimize learned patterns
learningnormalOutcome/trajectory logging and pattern consolidation
gitnormalTrack uncommitted changes and branch status
progressnormalTrack implementation progress
mapnormalCodebase mapping β†’ metrics/codebase-map.json
optimizenormalPerformance snapshot β†’ metrics/performance.json
dddlowTrack DDD progress β†’ metrics/ddd-progress.json
adrlowCheck ADR compliance across codebase
consolidatelowMemory dedup, contradiction detection, pruning
cachebgClean temp files, old logs, stale cache

Workers live in @monoes/hooks and start with the session. Metrics-producing workers (map, audit, optimize, consolidate, ddd) refresh when their .monomind/metrics/*.json output is missing or older than 6 hours; doctor reports metrics freshness. Run any worker on demand with monomind hooks worker run <name>.

Hook Configuration
// .claude/settings.json { "hooks": { "pre-task": [{ "matcher": ".*", "hooks": [{ "type": "command", "command": "npx monomind hooks pre-task --description \"$TASK\"" }]}], "post-edit": [{ "matcher": ".*", "hooks": [{ "type": "command", "command": "npx monomind hooks post-edit --file \"$FILE\"" }]}] } }
Swarm topology diagram
Topologies
Hierarchical
Queen β†’ domain leads β†’ workers. Best for complex feature development. Default.
Mesh
Peer-to-peer, all agents equal. Best for distributed analysis with no single authority.
Hierarchical-Mesh
Queen manages peer clusters. Recommended for large swarms.
Adaptive
Reconfigures topology dynamically. High overhead β€” use for long-running sessions.
Ring
Circular communication pattern β€” each agent talks to its neighbors in a loop.
Star
Hub-and-spoke. Testing swarms β€” one orchestrator, N independent runners.
Hybrid
Hierarchical mesh for maximum flexibility β€” combines hierarchy with peer links.
Consensus Strategies (Vote-Count Thresholds)
StrategyThresholdBest For
raftSimple majorityDefault. Majority vote counting β€” no leader election or log replication.
bft2f+1 votesByzantine-style threshold for an adversarial fault model.
quorumPreset: majority / supermajority / unanimousCustom agreement thresholds.

These are vote-count thresholds applied inside a single process β€” not distributed consensus protocols. Gossip and CRDT strategies are not implemented.

15-Agent Domain Hierarchy
DomainAgents
Queen / OrchestrationQueenCoordinator, AttentionCoordinator
ArchitectureArchitect, SystemDesigner
EngineeringCoder, BackendDev, FrontendDev
QualityTester, Reviewer, SecurityAuditor
Memory / IntelligenceMemorySpecialist, MemoryCoordinator
OperationsPerfEngineer, MonitorAgent
ResearchResearchAgent
Quick Launch
# Hierarchical swarm, 8 agents, specialized strategy npx monomind swarm init \ --topology hierarchical \ --max-agents 8 \ --strategy specialized # Hive-mind (MCP tools only β€” no CLI command) # mcp__monomind__hive-mind_init with topology + consensus strategy # Interactive topology picker in Claude Code /mastermind
Intelligence subsystem visualization
How it works
Keyword Routing
createKeywordRouter maps a task description to an agent type by keyword scoring β€” no LLM call and no learned weights. Deterministic and sub-millisecond. This is the default for bare monomind route <task>. A separate, real embedding-based semantic router (@monoes/routing: keyword pre-filter β†’ local embedding β†’ cosine similarity β†’ LLM fallback) is available opt-in via route semantic, agent --task, or the hooks_route_semantic MCP tool.
Route-Outcome Measurement
Recommended routes are auto-correlated with actual outcomes. doctor surfaces routing accuracy and recommended-vs-actual adherence over a rolling window.
Trajectory + Outcome Logging
Steps and trajectories (intelligence.ts) plus command and route outcomes (command-outcomes.ts, route-outcomes.ts) are recorded as plain JSON for later analysis.
Pattern Consolidation
The learning worker dedups, detects contradictions, and prunes old entries from patterns.json on a 30-minute interval.
CLI
# Inspect logged patterns npx monomind hooks intelligence patterns --action list # Predict routing for a task from logged patterns npx monomind hooks intelligence predict --input "implement auth" # Optimize the pattern store npx monomind hooks intelligence optimize --method quantize npx monomind hooks intelligence optimize --method compact # Routing accuracy / adherence npx monomind doctor
init
Project init wizard β€” topology, memory, hooks
init --preset minimal
Initialize with a named preset configuration
agent spawn
Spawn a named agent by type
agent list
List active agents and their status
agent status <id>
Detailed agent info and metrics
agent stop <id>
Gracefully terminate an agent
agent metrics
Performance metrics by agent type
org run <name>
Start an org as a real SDK-backed daemon β€” the primary multi-agent runtime
org status [name]
Runtime state for one or all orgs
org stop <name>
Request a graceful stop
org list
List every org + status
org serve
Host-only mode β€” runs orgs with a schedule field
org delete <name>
Remove an org
org memory [stats|search|rules|rollback]
Cross-run org memory: knowledge-graph stats/search, stored "when X do Y" rules, or rollback a run's writes
org questions <name> [--all]
List pending (or all) human-in-the-loop questions an agent asked via ask_human
org answer <name> <id> "<text>"
Answer a pending question β€” delivered live if the org is running, queued for next start otherwise
org create
Define and save a new org config
swarm init
Write in-session swarm coordination state (bookkeeping only β€” real work happens via Claude Code's Task tool)
swarm status
Read back swarm state: registered agents, tasks, topology
swarm scale
Register/deregister agents in swarm state
swarm stop
Mark swarm state terminated
memory store
Store a memory entry with optional namespace
memory search
Keyword/BM25 search over stored memories
memory list
List memories by namespace or tag
memory delete <key>
Remove a memory entry
memory export
Export memories to JSON
memory import
Import memories from JSON
memory stats
Entry counts, backend info, index health
mcp start
Start MCP server (required for claude mcp add)
mcp list
List all registered MCP tools
mcp status
Server health and connection info
task create
Create a task with title, description, priority
task list
Show tasks filtered by status or board
task update <id>
Update task status, priority, assignee
task delete <id>
Remove a task permanently
hooks pre-task
Register task start; get routing recommendation
hooks post-task
Record completion; trigger learning
hooks pre-edit
Context suggestions before file edit
hooks post-edit
Record edit outcome for patterns
hooks session-start
Restore cross-session context
hooks session-end
Persist state; flush working memory
hooks route
3-tier model routing decision
hooks worker list
List active background workers
hooks worker run <name>
Run a background worker on demand
hooks intelligence patterns
List logged patterns
hooks intelligence predict
Predict routing for a task from logged patterns
hooks intelligence stats
Pattern store status
security scan
npm audit + secret-pattern scan + code-smell scan (eval, innerHTML, SQL/command injection); --fix shells to npm audit fix
security cve --check <id>
Look up a CVE against the live NVD/OSV.dev APIs (24h cache)
security secrets
Standalone secret-pattern scan (same engine as scan's secrets pass)
security defend -i "<text>"
Run monofence-ai's real threat detection against arbitrary input
security audit
Lists recent .swarm/*.json activity as inferred events β€” a lightweight preview, not a persistent audit log (declared log/export/clear actions aren't implemented yet)
security redteam --dry-run
Preview a 20-prompt adversarial test library (injection/jailbreak/adversarial/PII) β€” live --target execution against a running agent isn't implemented yet
performance profile
Record latency and token cost profiles
performance report
Time-series performance metrics
doctor
System diagnostics β€” all components
doctor --fix
Auto-fix: Node version, DB init, stale worker metrics
doc ingest <path>
Index documents into the Second Brain knowledge base
doc search -q "query"
Search over indexed documents
doc list
List all indexed documents with chunk counts
doc export
Export knowledge base as OKF bundle
monograph build
Build the code knowledge graph
monograph search
BM25, semantic, hybrid search across graph
monograph stats
Node/edge counts, top concepts by importance
monograph watch
Watch mode: incremental rebuild on file changes
browse open <url>
Open URL in CDP browser client (Chrome DevTools Protocol)
browse snapshot -i
Get interactive elements (93% less context)
browse click @e1
Click element by snapshot ref
browse workflow run <file>
Execute a DAG workflow (Kahn topological sort, parallel steps, AbortSignal cancellation)
browse workflow validate <file>
Validate workflow DAG file β€” checks for cycles and missing steps
browse session list
List persisted browser sessions (~/.monomind/sessions.json)
browse session resume <id>
Restore a previous browser session by ID
browse platform connect <name>
Connect a platform adapter (gmail, sheets, drive, msgraph, gemini-image)
browse platform list
List available built-in action handlers (http, file, gmail, sheets, drive, msgraph, gemini-image)
route <task>
Default: deterministic keyword-only routing to an agent type (no embeddings, fixed confidence)
route semantic -t "<task>"
Real semantic routing: keyword pre-filter β†’ local embedding β†’ cosine similarity β†’ LLM fallback (@monoes/routing)
route list-agents
List routable agent types
route stats
Routing accuracy / adherence over a rolling window
route feedback
Record actual outcome for a routing decision
/mastermind
Swarm topology picker β€” all 11 modes, one recommendation
/monobrowse
UI testing via monomind browse CDP client
/tokens
Token usage dashboard: today/week/30days/month
/ts
Toggle statusline between full and compact mode
/mastermind:autodev
Autonomous research→build→review loop
/mastermind:build
Build a specific feature from a brief
/mastermind:review
Iterative code review and security audit
/mastermind:code-review
Multi-agent iterative review with auto-fix
/mastermind:architect
Architecture review and file structure design
/mastermind:debug
Systematic root-cause debugging
/mastermind:tdd
Test-Driven Development: Red-Green-Refactor
/mastermind:plan
Write a comprehensive implementation plan
/mastermind:execute
Execute a written implementation plan step by step
/mastermind:taskdev
Execute plan task-by-task with fresh subagents
/mastermind:improve
Deep component improvement pipeline
/mastermind:verify
Verification gate before claiming work complete
/mastermind:finish
Decide how to integrate completed implementation
/mastermind:worktree
Start feature work in isolated git worktree
/mastermind:receive-review
Evaluate and implement code review feedback
/mastermind:research
Deep research with structured output
/mastermind:idea
Idea generation and evaluation
/mastermind:ideate
Research ideas, evaluate with PM lens
/mastermind:design
Collaborative design session β€” explore intent and requirements
/mastermind:do
Execute tasks from task file (docs/tasks/)
/mastermind:createtask
Decompose prompt into tasks (saved to docs/tasks/ by default; add --monotask for board)
/mastermind:master
Top-level orchestrator β€” routes any business prompt
/mastermind:release
Release management: versioning, changelog, deployment
/mastermind:adr
Draft Architecture Decision Record
monomind org run <name>
Start an org as a real SDK-backed daemon (the current, recommended path)
/mastermind:createorg
Define and save a v2 org config (roles, hierarchy, schedule) β€” run it with /mastermind:runorg or monomind org run
/mastermind:runorg
Org Runtime v2 delegator: validates org configs, auto-migrates v1 definitions, starts via monomind org run/serve; deprecated prompt path is /mastermind:runorgv1
/mastermind:stoporg
Legacy β€” use monomind org stop for v2 orgs
/mastermind:orgs
Legacy β€” use monomind org list for v2 orgs
/mastermind:orgstatus
Legacy β€” use monomind org status for v2 orgs
/mastermind:approvev1
Legacy approval for v1 prompt-orchestrated orgs; v2 approvals arrive in the dashboard's Human Input tab
/mastermind:okf-export
Export Second Brain as OKF bundle
/mastermind:okf-import
Import an OKF bundle into Second Brain
/mastermind:brain
Inspect and manage mastermind brain context
/mastermind:memory
Memory store: store, search, retrieve, list, delete
/mastermind:budget
Budget status: today, month, limits, autotune
/mastermind:graph-status
Single-line graph stats: nodes, edges, freshness
/mastermind:loops
List active --tillend/--repeat loops
/mastermind:repeat
Repeat any prompt or slash command on a schedule
/mastermind:understand
Semantic enrichment for monograph
/mastermind:swarm
Multi-agent swarm coordination
/mastermind:help
Quick-reference: all skills, commands, and CLI
/mastermind:skill-builder
Create, edit, or verify mastermind skills
/mastermind:specialagents
Activate a specialist agent persona
/mastermind:techport
Technical portfolio β€” assess foreign project state
/mastermind:ops
Operations planning and workflow automation
/mastermind:finance
Financial modeling, invoicing, and budget tracking
/mastermind:marketing
Marketing strategy: campaigns, copy, SEO, social
/mastermind:content
Blog posts, threads, docs, newsletters
/mastermind:sales
Sales strategy, outreach, and pipeline management
/swarm:development
Hierarchical: architect→coder→tester flow
/swarm:analysis
Mesh + adaptive for codebase analysis
/swarm:testing
Star + parallel for all test types
/swarm:optimization
Profiling, bottleneck detection, optimization
/swarm:research
Mesh swarm for research and exploration
/swarm:maintenance
Dependency updates and security audits
/github:pr-manager
Full PR lifecycle with swarm coordination
/github:issue-tracker
Issue creation and progress tracking
/github:release-manager
Release coordination and CI/CD
/monodesign craft
Shape + build a UI feature end-to-end
/monodesign shape
Plan UX/UI before writing code
/monodesign audit
Technical quality: a11y, perf, responsive
/monodesign critique
UX design review with heuristic scoring
/monodesign polish
Final quality pass before shipping
/monomotion
GSAP animation skill β€” all motion work
/monograph:monograph-build
Build knowledge graph from codebase
/monograph:monograph-search
BM25, semantic, hybrid graph search
/monograph:monograph-watch
Incremental rebuild on file changes
/hooks:setup
Configure hooks in settings.json
/hooks:overview
How hooks wire into Claude Code
/memory:README
Full memory CLI reference
autodev β€” The Autonomous Build Loop
Phase 1
Research
Parallel: git log, file scan, package.json, README, TODO/FIXME grep, monograph god nodes, memory search for already-built items. Returns ranked list of 3–5 improvement candidates.
Phase 2
Selection
Picks best candidate by feasibility Γ— blast-radius Γ— focus alignment. Stores selection to the memory store. Focus flags: --focus security, --focus dx, --focus performance.
Phase 3
Build
Invokes mastermind:build with concrete spec, acceptance criteria, and blast radius guard. Spawns architect β†’ coder β†’ tester β†’ reviewer agent chain.
Phase 4
Review Loop
Invokes mastermind:review inline. Runs Code Reviewer + Security Engineer + Reality Checker in parallel. Repeats up to 5 iterations until zero findings.
Phase 5
Log
Records completion to memory. If count > 1, continues to next improvement. If --tillend, schedules next session via ScheduleWakeup.
--tillend Loop Mechanics
Session 1: /mastermind:autodev --tillend β†’ runs β†’ schedules ScheduleWakeup(delay=60s) Session 2: wakeup fires β†’ checks staleness guard β†’ if --rep N < state.currentRep: SKIP (stale wakeup) β†’ else: run β†’ schedules next wakeup Session N: empty round (zero findings AND zero actions) β†’ emits loop:complete β†’ removes .monomind/loops/{id}.json β†’ STOP # Stop a loop manually touch .monomind/loops/{loop-id}.stop
Universal Flags
FlagDefaultPurpose
--tillendoffRepeat until empty round (zero findings, zero actions)
--repeat <N>offRepeat exactly N times
--wait <seconds>60Minimum seconds between repeat runs
--maxruns <N>50Safety cap for --tillend
--autooffNo confirmation prompts
--confirmoffAsk before each action
--focus <area>β€”Bias toward: security, dx, performance
All Mastermind Commands
CommandPurpose
β€” Development β€”
/mastermind:autodevAutonomous research β†’ build β†’ review loop
/mastermind:buildBuild a specific feature from a brief
/mastermind:reviewIterative code review and security audit
/mastermind:code-reviewMulti-agent iterative review with auto-fix
/mastermind:architectArchitecture review and file structure design
/mastermind:debugSystematic root-cause debugging
/mastermind:tddTest-Driven Development: Red-Green-Refactor
/mastermind:planWrite a comprehensive implementation plan
/mastermind:executeExecute a written implementation plan step by step
/mastermind:taskdevExecute plan task-by-task with fresh subagents
/mastermind:improveDeep component improvement pipeline
/mastermind:verifyVerification gate before claiming work complete
/mastermind:finishDecide how to integrate completed implementation
/mastermind:worktreeStart feature work in isolated git worktree
/mastermind:receive-reviewEvaluate and implement code review feedback
/mastermind:releaseRelease management: versioning, changelog, deployment
/mastermind:adrDraft Architecture Decision Record
β€” Research & Ideas β€”
/mastermind:researchDeep research with structured output
/mastermind:ideaIdea generation and evaluation
/mastermind:ideateResearch ideas, evaluate with PM lens
/mastermind:designCollaborative design session β€” explore intent and requirements
/mastermind:techportTechnical portfolio β€” assess foreign project state
β€” Task & Org Management β€”
/mastermind:doExecute tasks from task file (docs/tasks/)
/mastermind:createtaskDecompose prompt into tasks (saved to docs/tasks/ by default; add --monotask for board)
/mastermind:masterTop-level orchestrator β€” routes any business prompt
monomind org run <name>Start an org as a real SDK-backed daemon β€” the current, recommended path
monomind org status / list / stopRuntime state, listing, and graceful stop for v2 orgs
β€” Mastermind org commands (v2 default; legacy v1 names carry the v1 suffix) β€”
/mastermind:createorgDefine and save a v2 org config (roles, hierarchy, schedule)
/mastermind:runorgOrg v2 delegator: validates configs, auto-migrates v1 β†’ v2, starts via monomind org run/serve
/mastermind:stoporgLegacy β€” use monomind org stop for v2 orgs
/mastermind:orgsLegacy β€” use monomind org list for v2 orgs
/mastermind:orgstatusLegacy β€” use monomind org status for v2 orgs
/mastermind:approvev1Legacy approvals for v1 orgs; v2 approvals appear in dashboard Human Input tab
β€” Utilities β€”
/mastermind:brainInspect and manage mastermind brain context
/mastermind:memoryMemory store: store, search, retrieve, list, delete
/mastermind:budgetBudget status: today, month, limits, autotune
/mastermind:graph-statusSingle-line graph stats: nodes, edges, freshness
/mastermind:loopsList active --tillend/--repeat loops
/mastermind:repeatRepeat any prompt or slash command on a schedule
/mastermind:understandSemantic enrichment for monograph
/mastermind:swarmMulti-agent swarm coordination
/mastermind:helpQuick-reference: all skills, commands, and CLI
/mastermind:skill-builderCreate, edit, or verify mastermind skills
/mastermind:specialagentsActivate a specialist agent persona
β€” Business Domains β€”
/mastermind:opsOperations planning and workflow automation
/mastermind:financeFinancial modeling, invoicing, and budget tracking
/mastermind:marketingMarketing strategy: campaigns, copy, SEO, social
/mastermind:contentBlog posts, threads, docs, newsletters
/mastermind:salesSales strategy, outreach, and pipeline management
Brain Protocol
// Brain Load (session start) 1. Search memory-store namespace "mastermind:{domain}" 2. Three tiers: raw records (last 7 days) β†’ weekly summaries β†’ long-term principles 3. Inject combined BRAIN CONTEXT block into skill // Brain Write (session end) 1. Store key decisions + findings to the memory store 2. Update weekly summaries and principles
Overview

The dashboard is a single-page application with a 196px fixed sidebar and a scrollable main area. URL parameters support deep-linking: ?proj=<path> switches project context and &sess=<id> opens a specific session.

Topbar ElementDescription
Live dotPulses green when an active Claude Code session is detected
Today cost badgeCumulative USD spend for the current calendar day
Session cost tickerRunning cost of the currently focused session, updates in real time
Activity chipCurrent agent type and task description from the most recent hook event
⬑ MastermindOpens the Mastermind overlay (violet hexagon button)
βš‘ BudgetOpens a modal for setting daily and monthly spend limits (USD). Fields: Daily limit, Monthly limit. Once saved, the alerts rail shows a warning when actual spend approaches the limit.
⌘K SearchOpens the command palette for cross-view navigation
? HelpShows keyboard shortcuts reference
β†Ί RefreshForce-reloads current view data

Status strip (shown below topbar when data is present):

ChipMeaning
PATTERNS NNumber of learned routing patterns in the pattern store
CHUNKS NNumber of indexed text chunks available for search
SWARM topologyActive swarm topology name (hierarchical, mesh, adaptive…)
LAST ROUTEAgent name that the routing hook most recently selected

The sidebar footer shows your GitHub username and the absolute path of the current working directory.

Now β€” Live Feed

The Now view is a three-column layout: feed pane (left), optional detail panel (slides in from the right edge of the feed), and metrics pane (252px, fixed right).

Feed ControlKeyBehavior
Play / PauseSpaceToggle live-tail; pausing freezes the list without disconnecting
Clearβ€”Removes all entries from the visible feed buffer
Filter/Opens inline search β€” filters entries by text or tool name
Jump to liveGScrolls to the newest entry and resumes live-tail
Ambient modeAHides all chrome; only the feed remains
Replayβ€”Re-plays the current session from the beginning at configurable speed
FocusFExpands the feed to full width, hiding metrics pane
Exportβ€”Downloads visible feed entries as JSONL

Feed entry types:

TypeAppearance
Tool eventsColored category icon (file, bash, web, memory, agent…), tool name, condensed args
User messagesItalic text with a person icon and timestamp
Error entriesRed left border, error message, optional stack trace expand

Additional feed UI elements:

  • Session context bar β€” pinned at top of feed: session ID, model, start time, current cost
  • Recap card β€” collapsible summary of the previous session's key decisions
  • Replay bar β€” scrubber, speed selector (0.5Γ—, 1Γ—, 2Γ—, 4Γ—), play/pause when in replay mode
  • Timeline bar β€” horizontal ruler showing tool-call density over session time
  • Time-range filter β€” drag handles on the timeline to zoom into a time window
  • Weekly card β€” dismissible summary card (stored in localStorage) showing 7-day stats
  • Daily digest card β€” dismissible AI-generated digest of today's activity
  • Feed minimap β€” 8px-wide column of colored pips on the right scroll edge for quick navigation

Group rows β€” when 3 or more consecutive events share the same category, they are collapsed into a single row showing the count and a β–Έ expand affordance. Clicking the group row expands all entries in place.

Detail panel: slides in 280px when an entry is clicked. Shows full event metadata, raw JSON payload, and a Copy button.

Metrics pane groups (252px, right):

GroupWhat it shows
TodayToday API cost, call count, and a 7-day activity sparkline
Active LoopsRunning loop names with live countdown timers
Recent SessionsLast 5 sessions with cost and duration chips
Tool UsageBar chart of most-called tools in the current session
Burn RateThree rolling gauge rows β€” 5 min, 15 min, 60 min β€” each showing tool-call rate in calls/minute. Color: green < 4 calls/min, amber 4–10, red β‰₯ 10
Session LanesParallel swimlanes showing concurrent agent activity
Cache EfficiencyPer-session cache hit rate rows (cached tokens / total input tokens), with the rolling average shown in the group header.
Token VelocityTokens/minute sparkline for the current session
30-Day Cost TrendBar chart of daily spend over the last 30 days
Activity HeatmapHour-of-day Γ— day-of-week grid colored by event density
Projects

Projects are discovered from Monomind's config registry. The view renders an auto-fill card grid (min 240px) with a filter input at the top.

Card ElementDescription
Active badgeGreen "ACTIVE" pill β€” shown when the project's directory is the current working directory
Health score circle0–100 score: green β‰₯ 70, amber 40–69, red < 40
Name & pathProject display name and filesystem path
Sessions countTotal recorded sessions for this project
Memories countNumber of memory files scoped to this project
Last activeRelative time since the last session event

Clicking a card switches the global project context (updates the ?proj= URL param) and navigates to the Sessions view filtered to that project.

Sessions

Sessions are created automatically when you use Claude Code in any project. Start a session by opening Claude Code in your project directory:

# Sessions appear automatically β€” just use Claude Code # The dashboard discovers sessions from ~/.claude/projects/<project>/

Sessions are grouped by recency: Today, Yesterday, This week, Older β€” each group header is collapsible. A 12-week clickable calendar heatmap appears above the session list. Each cell represents one day; opacity scales with session count. Clicking a cell filters the session list to that day. The heatmap header shows a week-over-week delta indicator (e.g. ↑12%, ↓5%, β†’ flat).

Each session row includes:

  • Prompt text (truncated) with expand on hover
  • Timestamp (relative) and compacted badge (when the session was auto-compacted)
  • Summary excerpt β€” 2-line clamp of the AI-generated session summary
  • Meta line: duration Β· N messages Β· $cost
  • Anomaly badges: costly (cost > 2Γ— average) and errors (tool errors detected)
  • Auto-tags: topic tags inferred from session content (e.g. refactor, bug-fix)
  • File chips: up to 5 file paths touched in the session
  • Context saturation bar: horizontal progress showing % of context window consumed (message count vs. limit)
  • Notes β€” each row has a ✎ notes toggle (shown in blue when a note exists). Click to expand an inline textarea for free-form notes stored in localStorage, keyed by session ID.
  • Error drawer β€” the error anomaly badge (N err) is clickable. Clicking it toggles an inline drawer below the row listing all tool error messages from that session.
  • Custom tags β€” a '+ tag' affordance on each row adds manually typed labels (stored in localStorage). Custom tags appear as blue-toned pills alongside auto-tags and are included in the sessions filter.
  • Context window pressure gauge β€” a separate 3px bar based on actual input token count vs the 200k context ceiling. Color: green (normal), amber (warn), red (critical). Shows a 'N% ctx' label. Distinct from the message-count saturation bar.

Toolbar toggle buttons:

ButtonEffect
StarredFilter to bookmarked sessions only
LeaderboardSort by cost descending β€” shows most expensive sessions first
ModelsShow model name chip on each row
ErrorsFilter to sessions that contain tool errors
ToolsShow tool-call summary chips on each row
ProjectsShow project path chip on each row
CSVExport current filtered session list as CSV
PatternsShow learned routing pattern badges
CompareEnable multi-select mode for session diff (select exactly 2)
TimelineSwitch to a Gantt-style timeline visualization
DonutShow a cost-by-model donut chart above the list
ReportOpens the Report Card modal with a structured plain-text summary of session activity for the current period. Includes a ⎘ Copy button β€” content is copied to clipboard, not downloaded.

Period filter: Day / Week / Month / All β€” scopes the session list and heatmap to the selected window. Bulk actions become available when multiple rows are checked: Export, Bookmark, Clear.

Session diff: selecting exactly 2 sessions with Compare mode opens a side-by-side panel showing cost delta, duration delta, tool overlap, and unique tool calls per session.

Loops

Loops are created manually from the dashboard (+New Loop button) or via slash commands:

# Create a loop from Claude Code /mastermind:autodev --tillend # autonomous loop until nothing left /mastermind:review --tillend --auto # review loop until clean /monomind:repeat --every 1h /mastermind:autodev # custom repeat schedule

A loop is a scheduled automation: a prompt that re-runs at a fixed interval until a max-rep limit is reached or it is manually stopped.

Loop Card ElementDescription
NameHuman-readable loop label
Interval chipRepeat cadence (e.g. 1h, 30m, daily)
Countdown timerLive seconds-ticking countdown to the next run
Progress barcurrentRep / maxReps fill bar
Status badgerunning, paused, or completed
Stop buttonImmediately cancels the loop and records final state

Expand a loop card to see: full prompt text, interval, started-at timestamp, last-run timestamp, run count, and a sparkline of per-run duration history.

Create Loop form fields:

FieldRequiredDefault
PromptYesβ€”
NameNoAuto-generated from prompt
IntervalNo1h
Max RepsNoUnlimited
Tokens

Token data is collected automatically from every Claude Code session. No setup required β€” costs appear as soon as API calls are made.

The Tokens view provides cost and usage analytics with period-based filtering.

πŸ’΅
Today Cost
Cumulative USD spend for the current calendar day across all sessions
πŸ“ž
Today Calls
Total API calls made today
πŸ“…
Month Cost
Spend for the current calendar month
πŸ”’
Total Tokens
Cumulative input + output tokens across all recorded sessions

Period tabs β€” Today / Week / 30 Days / Month β€” each fetches /api/token-usage?period=X and re-renders the chart and table.

Animated bar chart: 400ms ease-out-cubic entrance animation. Bar colors follow threshold logic:

  • Green β€” cost < average Γ— 0.5 (low spend day)
  • Amber β€” cost in normal range
  • Red β€” cost β‰₯ average Γ— 1.5 (high spend day)

The current day's bar is full opacity; all other bars render at 50% opacity. Below the chart, a session breakdown table shows: Session, Calls, Tokens, Cost per row.

Memory

The Memory view has two distinct data sources: Memories are explicit .md files with YAML frontmatter stored in the .monomind/memories/ directory. Chunks are indexed text segments extracted from project source files and documentation for semantic search.

Memory TypeColorPurpose
userIndigoPersonal preferences, identity, working style
feedbackAmberAgent routing decisions and confidence scores
projectTealProject-scoped facts, patterns, decisions
referenceVioletReference documentation, API facts
handoffPinkCross-session state for next session pickup

Memories are created in three ways:

# 1. Auto-memory hook (runs during Claude Code sessions) # Files written to: ~/.claude/projects/<project>/memory/ # 2. From the dashboard # Click "+ New Memory" β†’ choose type β†’ fill frontmatter # 3. Via Claude Code memory commands monomind memory store --key "preference" --value "..." --namespace user

The Memory view has 7 sub-tabs:

TabDescription
MemoriesSplit-pane list + detail editor. Full CRUD: create, edit (modal with type/title/content fields), delete. New Memory button offers 4 type templates: user (personal preferences/identity), feedback (routing decisions), project (project-scoped facts), reference (documentation/API facts). Each pre-populates a minimal YAML front matter stub.
RoutingRouting feedback log β€” each entry shows agent chosen, confidence %, task description, and timestamp. YAML front matter stub format for new memories:
---
name: my preference
description: Short description of this memory
type: user
---

Content body here...
UsagePeriod tabs + stat grid (cost, calls, tokens, cache efficiency) + 5 bar charts: Models, Activity by hour, Tools, MCP Servers, Projects
ADRsArchitecture Decision Records as filterable cards. Status badges: Accepted, Proposed, Deprecated. Category filters: implementation, guidance
SwarmSwarm run list + canvas topology visualization β€” static snapshot drawing, drawn once when a run is selected. Hierarchical: queen node (labeled Q, teal, larger) at top, worker nodes spread below, straight edges connecting them. Mesh/other: nodes in a circle with all-to-all edges. Event log for selected run. Clean Data button purges stale run data
ChunksStats bar (chunk count, skill namespaces, total namespaces). Filter by namespace or keyword. Chunk cards show source file, excerpt, and namespace. Edit/Delete per card. Build Docs button triggers indexing with progress polling
Agent GraphSummary stat cards, session list, agent spawn bar chart (agents per session), tool usage bar chart (calls per tool across all sessions)

Routing tab: Routing data is collected automatically whenever Claude Code routes a task to an agent. No setup required. Use /hooks:overview to understand the routing hook.

ADRs tab: ADRs are created via the slash command or discovered automatically from existing ADR files:

/mastermind:adr # draft an ADR from accumulated decision markers in the codebase

Swarm tab: reflects in-session swarm coordination state (bookkeeping written by Task-tool-driven work, not org-runtime-v2 activity). For a running monomind org run org, watch its own live dashboard instead:

monomind org run <name> # live view at http://localhost:4243

Chunks tab: Chunks are built by indexing your project's documentation and skill files:

# From the dashboard: click "βŠ• Build Docs" in the Chunks tab # From Claude Code: /mastermind:understand # semantic enrichment β€” indexes all .md/.txt files

Agent Graph tab: The Agent Graph is populated automatically by sessions that spawn sub-agents. Spawn agents by running complex tasks via /mastermind:build, /mastermind:autodev, or any orchestration command.

Orgs

Run agent organizations via the real org-runtime-v2 daemon (live dashboard on :4243, separate from this :4242 dashboard):

monomind org run <name> # start an org β€” real Claude Agent SDK sessions per role monomind org status / list / stop # check, list, or stop # Legacy v1 prompt-orchestrated runner (deprecated 2026-07 β€” config creation itself is v2): /mastermind:createorg # define a new v2 org config /mastermind:runorgv1 # (v1 legacy) start a saved org via prompt-orchestrated flow

Organizations are multi-agent structures with roles, goals, routines, and approval workflows. Each org card shows: a running dot (live indicator), name, goal description, topology/role chips, and an avatar stack of active agents.

Each org has 29 tabs:

TabWhat it shows
ChartOrg hierarchy as an animated SVG β€” nodes for each role, animated edges for reporting lines
RolesRole cards listing responsibilities, required skills, and reporting structure
ActivityChronological event log of all agent actions within the org
HealthMetrics grid: task completion rate, error rate, average response time, agent uptime
HeartbeatsPer-agent heartbeat list showing last ping time and status (alive/stale/dead)
TasksFull task list with status, assignee, priority, and due date
CostsCost breakdown by agent, role, and time period with totals
MembersHuman and agent member list with role assignments
GoalsHierarchical goal tree with progress bars for each objective and sub-objective
BoardKanban board with columns: Open, In Progress, Blocked, Done, Cancelled
LiveReal-time agent activity feed; auto-refreshes every 5 seconds. Shows currently running agents and their current task
ApprovalsApprove/reject queue for actions that require human sign-off
SecretsSecret names and scopes β€” values are always masked (never shown in plaintext)
SettingsOrg configuration form that generates the equivalent CLI command for reproducibility
RoutinesCron table of scheduled automations: name, schedule expression, last run, next run, status
My IssuesIssues assigned to the current user or agent
BudgetsFill bars showing spend vs. budget limit per agent and in aggregate
PluginsInstalled plugin status cards: name, version, enabled toggle, health indicator
Charts14-day activity heatmap + per-agent bar charts for calls and cost
ProjectsCard grid of projects associated with this org
SkillsRole Γ— skill matrix β€” cells show proficiency level (none/basic/expert)
WorkspacesPer-agent workspace rows: branch, working directory path, running services
InvitesPending invitations with invite token, role, and expiry timestamp
AgentsFull agent table: name, type, status, model, last active, total calls, total cost
EnvironmentsAgent environment configs: driver (node/python/docker), host, status
AccessMembers grouped by role tier with their granted permissions listed
IssuesFull issue table (up to 100 rows): title, status, priority, assignee, labels, created date
Join QueuePending join requests showing requester (human πŸ‘€ or agent πŸ€– emoji) and approval status
ThreadsDiscussion threads: subject, author, message count, linked issue
Monograph

The knowledge graph must be built before Monograph tabs show data:

# Build the graph (analyzes imports, calls, dependencies) /monograph:monograph-build # full build monomind monograph build --code-only # code only, skip docs # From the dashboard: Graph tab β†’ click "β†Ί REBUILD" # Enable watch mode to auto-rebuild on file changes: WATCH toggle in Graph tab

The Monograph view provides a full knowledge-graph interface for your codebase. It has 7 tabs:

TabDescription
OverviewStat cards (total nodes, total edges, average degree, type counts), top 6 nodes by degree, and a type-distribution breakdown
GraphInteractive force-directed graph in an iframe. WATCH toggle enables file-system watching so the graph auto-rebuilds on file changes. REBUILD button forces a full rebuild immediately
AnalyzeTwo groups of analyses: 9 client-side (Stats, PageRank, Dead Code, Components, Topological Sort, Hubs, Cycles, Surprises, Communities) and 20 server-side MCP analyses (Health Score, Risk Profile, Hotspots, Maintainability, Complexity, CRAP Score, Instability, Coupling Balance, Circular Dependencies, Unlinked References, Dead Exports, Reachability, Boundary Check, Bridges, Cohesion, Largest Files, Languages, Churn Hotspots, Detect Changes, Authors)
Query6 query forms: Search nodes (BM25 keyword), Impact analysis (upstream/downstream dependents), Context (360Β° view of a file), Shortest path (between two nodes), Cypher query (raw graph query), Ask the graph (natural language)
ExportDownload the graph in: JSON, SVG, GraphML, or Cypher format
ReportRendered GRAPH_REPORT with summary stats, top nodes by degree, and type distribution
WikiSearchable node browser β€” type filter pills, mode toggle (All / Docs / Code), full-text search. Clicking a node opens a detail panel with Impact, Context, and Explain actions

The Wiki tab shows code nodes immediately after a graph build. To also see documentation nodes (from .md/.mdx/.txt files), click BUILD DOCS inside the Wiki tab or run /mastermind:understand.

Global Feed

A unified activity stream across all registered projects, accessible from the sidebar "βŠ• Global Feed" item.

The Global Feed populates automatically as you use Claude Code across multiple projects. No setup required β€” add more projects via monomind init in each project directory.

Each event entry displays a project tag chip alongside the event data, so you can see which project generated each activity. The feed is assembled by fetching /api/projects and then merging session events from all project paths.

Unlike the Now view (which is scoped to one project), the Global Feed gives a workspace-wide perspective β€” useful for multi-project workflows and general activity monitoring.

Mastermind Overlay

The Mastermind overlay opens by clicking the violet ⬑ Mastermind button in the topbar. It has 6 tabs:

TabDescription
OrgsList of all orgs β€” click to switch the dashboard's active org context
SkillsSearchable catalog of all 35+ slash-command skills. Click any skill to copy the /skill-name command to clipboard
LoopsRunning loops with live countdown timers and Stop buttons β€” mirrors the Loops view in a compact panel. Create loops with /mastermind:autodev --tillend or the +New Loop button in the Loops view.
Create OrgForm that generates and copies the equivalent /mastermind:createorg CLI command (legacy path β€” see the Organizations page for the current monomind org run flow)
MetricsSummary cards for current cost, API calls, routing confidence distribution, and active swarm topology
GraphNode and edge counts for the Monograph index, list of top god nodes, and an Open Monograph button
Command Palette ⌘K

Open with ⌘K or the Search button in the topbar. Results are grouped:

GroupContents
SessionsRecent sessions β€” select to open that session in the Now view
MemoryMemory entries β€” select to open the memory detail editor
ProjectsRegistered projects β€” select to switch project context
OrgsOrganizations β€” select to switch to that org's view
SkillsSlash-command skills β€” select to copy the command
ActionsQuick actions: Open Monograph, Refresh, Toggle Compact, Open Loops
TabsAppears when an org is selected β€” lists all 29 org tabs for direct navigation

Type a > prefix in the palette input to switch to cross-session full-text search mode β€” queries all session content, not just titles.

Keyboard Shortcuts
KeyActionContext
⌘KOpen command paletteGlobal
?Show keyboard shortcuts helpGlobal
RRefresh current viewGlobal
EscClose open panels or modalsGlobal
JNavigate down in listNow, Sessions
KNavigate up in listNow, Sessions
↡Open detail panel / jump to sessionNow, Sessions
/Open feed searchNow
GJump to live session (newest entry)Now
AToggle ambient modeNow
FToggle focus mode (full-width feed)Now
SpacePlay / pause live tailNow
API Reference

All endpoints are served by the local dashboard server at localhost:4242. SSE endpoints stream newline-delimited JSON.

Navigation / Init

MethodEndpointDescription
GET/api/git-userGit username and email
GET/api/projectsAll registered projects
GET/api/statusSystem health: memory, patterns

Sessions

MethodEndpointDescription
GET/api/session-journalSession metadata list
GET/api/sessionEvents for one session file
GET (SSE)/api/events-streamLive tool event stream
GET/api/search-sessionsFull-text session search
GET/api/session-errorsSession error list
GET/api/tool-errorsTool error list per session
GET/api/tool-rankingTool call frequency
GET/api/project-costsPer-project cost breakdown

Memory

MethodEndpointDescription
GET/api/sectionNamed data sections (e.g. tokens)
GET/api/memory/statsMemory store stats
GET/api/memory-files.md file list
PUT / DELETE/api/memory-fileCreate or delete memory file
GET/api/token-usageToken usage, accepts period param
GET/api/routing-feedbackRouting feedback log
GET/api/adrsArchitecture Decision Records

Loops

MethodEndpointDescription
GET/api/loopsActive loops
POST/api/loops/createCreate loop
GET/api/loops/stopStop a loop

Swarm

MethodEndpointDescription
GET/api/swarm-historySwarm run list
GET/api/swarm-eventsEvents for a run
DELETE/api/swarm-cleanPurge swarm data

Knowledge (Chunks)

MethodEndpointDescription
GET/api/section?name=knowledgeIndexed chunks
POST / DELETE/api/knowledge-chunkChunk CRUD
POST/api/monograph-build-docsTrigger docs indexing
GET/api/monograph-build-docs-statusIndexing progress

Graph (Monograph)

MethodEndpointDescription
POST/api/monograph-buildRebuild graph
POST/api/monograph-watch-toggleToggle file watch
GET/api/monograph-watch-statusWatch state
GET/api/monograph-graphGraph nodes/edges
GET/api/monograph-reportGRAPH_REPORT
GET/api/monograph-queryBM25 node search
GET/api/monograph-pathShortest path between two nodes
GET/api/monograph-explainNode explanation
GET/api/monograph-wiki-searchWiki full-text search
GET/api/graphAgent graph data
POST/api/mcp/callMCP tool proxy

Orgs

MethodEndpointDescription
GET/api/orgsOrg list
GET/api/org/:nameOrg detail
POST/api/orgs/:name/stopStop org
DELETE/api/orgs/:nameDelete org and clean up persisted config
POST/api/orgs/:name/copyDuplicate org under a new name
GET/api/orgs/:name/exportExport org config as JSON
POST/api/orgs/importImport org from a JSON config file
GET/api/org/:name/activityOrg activity log
GET/api/org/:name/healthOrg health metrics
GET/api/org/:name/agentsOrg agents
GET/api/org/:name/budgetsOrg budgets
GET/api/org/:name/membersOrg members
GET/api/org/:name/issuesOrg issues
GET / POST/api/org/:name/approvalsApproval queue
GET/api/org/:name/secretsSecret names and scopes
GET/api/org/:name/routinesScheduled routines
GET/api/org/:name/my-issuesIssues assigned to current user
GET/api/org/:name/pluginsInstalled plugins
GET/api/org/:name/projectsAssociated projects
GET/api/org/:name/workspacesAgent workspaces
GET/api/org/:name/invitesPending invitations
GET/api/org/:name/environmentsAgent environment configs
GET/api/org/:name/join-requestsPending join requests
GET/api/org/:name/threadsDiscussion threads
Autonomous Organizations

Assemble an AI team.
Let it run itself.

Define an org as a JSON file β€” roles, hierarchy, per-role policy β€” then start it as a real SDK-backed daemon. Live WebSocket dashboard, cross-process discovery, persistent memory, and policy-gated tool access, all real and running today.

$ monomind org run content-team --task "..." # start it
$ monomind org status content-team # check it
Real SDK sessions Live dashboard :4243 Memory-backed Policy-gated Cross-process Full lifecycle

The walkthrough below documents v1 prompt-orchestrated orgs via /mastermind:createorg + /mastermind:runorgv1. /mastermind:runorg is the v2 delegator (validates, auto-migrates configs, starts via monomind org run shown above). New orgs use v2; legacy v1 orgs still run via runorgv1.

Full lifecycle

From org.json to running organization

Author the org once as JSON β€” goal, roles, who reports to whom, per-role policy. `org run` loads it and starts a real Claude Agent SDK session per role. Stop, list, or delete orgs from the CLI at any time.

01
.monomind/orgs/<name>.json
Define the org

Hand-author (or copy sample-team.json from a fresh monomind init) β€” goal, roles, reports_to, and a per-role policy block gating tools/files/web/budget.

02
monomind org run <name>
Start the daemon

OrgDaemon loads the definition, starts a real Agent SDK session per role, and serves a live WebSocket dashboard. Every tool call is checked against that role's PolicyEngine gates.

03
http://localhost:4243
Watch it run

Live feed of agent chat, inter-agent messages, tool calls with allow/deny decisions, and files written β€” streamed over WebSocket, no polling.

.monomind/orgs/<name>.json

Define your organization

A plain JSON file: goal, roles, hierarchy via reports_to, and a policy block per role. No wizard step β€” you author it directly, or start from the shipped sample.

.monomind/orgs/content-team.json
{   "name": "content-team",   "goal": "Build and publish 3 blog posts per week",   "roles": [     { "id": "boss", "type": "boss", "reports_to": null },     { "id": "writer", "reports_to": "boss",       "policy": { "denyTools": ["bash"] } },     { "id": "seo", "reports_to": "boss" }   ] }   # then: $ monomind org run content-team  
🌳
Hierarchy via reports_to
No separate topology field β€” the boss role has reports_to: null, everyone else points at who they report to. Flat or deep, your call.
πŸ›‘οΈ
Per-role policy, enforced
Each role's policy block gates tool access, file read/write scope, web access, and token budget β€” checked on every tool call, with a full audit trail.
πŸ€–
Real SDK sessions
Each role is a real Claude Agent SDK session β€” not a simulated Task-tool subagent inside your current conversation. It runs independently, in the background.
πŸ”Œ
Cross-process discovery
--cross-process (default on) lets orgs running in different monomind processes β€” even different projects β€” discover and message each other.
Live dashboard β€” :4243

Watch the org run, live

A real WebSocket feed, not a polling API: agent status, chat and inter-agent messages, and every tool call's policy decision, streamed as they happen.

Agents
boss
reports_to: none Β· 4.2k tok
🟒 running
writer
reports_to: boss Β· 2.8k tok
🟒 running
seo
reports_to: boss Β· closed
⚫ closed
Stop running org:
monomind org stop content-team
Chats & Tool Activity
boss/boss: assigning "Draft: Claude Code vs Cursor" to writer writer write_file allow writer πŸ“„ drafts/claude-vs-cursor.md seo bash deny β€” denyTools: bash ⇄ content-team/boss β†’ growth-org/lead [handoff] draft ready for review
Use cases

Sample teams you can launch. The sky is the limit.

Every org is just a JSON definition and one command. Here are five starting points β€” copy the shape, edit the goal and roles, run.

✍️
Content Marketing
Weekly blog posts, SEO-optimized, reviewed and distributed autonomously
βš™οΈ
Software Dev
Architect, coders, tester building features end-to-end
πŸ”¬
Research Lab
Researchers gather, analysts synthesize, writers produce reports
πŸ“£
Sales Outreach
Research prospects, write sequences, track pipeline and follow up
πŸ›‘οΈ
DevOps and Security
SRE lead, security auditor, perf engineer monitoring and remediating
Team composition
Run it
Install
# Standalone package β€” works with any LLM stack npm install monofence-ai
Quick Usage
import { createMonoDefence } from 'monofence-ai'; const fence = createMonoDefence(); // Fast check β€” sub-millisecond, >12,000 req/s const result = await fence.detect(userInput); if (!result.safe) { console.log(result.threats); // threat types detected console.log(result.overallRisk); // 0.0 – 1.0 } // Scan LLM output for PII leakage or echo attacks const scan = await fence.scanOutput(llmResponse, originalPrompt); // Multi-turn context tracking console.log(fence.getContextState()); // 'clean' | 'probing' | 'escalating' | 'attack' fence.resetContext(); // start a new conversation
Key Features
πŸ”
EvasionDetector
Normalizes obfuscated inputs before pattern matching. Defeats homoglyph substitution (Cyrillic/Greek lookalikes), spaced characters (i g n o r e), leet substitution (ign0re), and base64 encoding. Applied automatically in every detect() call.
πŸ“ˆ
ContextTracker
Sliding-window escalation state machine for multi-turn conversations. States progress clean β†’ probing β†’ escalating β†’ attack. In attack state, overallRisk is raised to at least 0.5 even on individually benign inputs. Enabled by default.
πŸ”Ž
OutputScanner
Scans LLM output for PII leakage, echo attacks (output that mirrors injected instructions), policy violations, and contradictions with the original prompt. Call fence.scanOutput(llmOutput, prompt).
βœ…
Allowlist
5 built-in bypass rules plus user-defined runtime rules with TTL decay. Full-bypass rules short-circuit detection entirely; typed rules allow detection to run for other threat types. Narrows false positives for trusted inputs.
πŸ”’
SecurityHook
Registers a pre-task and pre-command scanner with priority 1000. Aborts execution when escalation state reaches attack. Off by default β€” opt in via SecurityHook.register() or the CLI flag.
🀝
SecurityConsensus
Aggregates threat assessments from multiple parallel agents with attention-based weighting. A single critical threat short-circuits scoring (fail-secure). Returns consensus, confidence, and criticalThreats.
CLI Integration
# Wire MonoFence AI into the pre-task hook (blocks on 'attack' state) npx monomind hooks pre-task --monofence-ai-check # Enable in mastermind:review β€” adds security pass to each review iteration /mastermind:review --monofence-ai-check # Deep security scan (includes SecurityConsensus across parallel agents) /mastermind:review --monofence-ai-check --monofence-ai-security-deep
API Reference
MethodReturnsDescription
fence.detect(input)ThreatDetectionResultPrimary scan β€” returns safe, threats, overallRisk. ~0.04ms per call.
fence.scanOutput(output, prompt)OutputScanResultScan LLM output for PII leakage, echo attacks, and policy violations.
fence.getContextState()ContextStateCurrent escalation state: clean | probing | escalating | attack.
fence.resetContext()voidReset conversation context. Call at the start of each new conversation.
fence.addAllowlistRule(rule)voidAdd a runtime bypass rule with optional TTL decay.
fence.isAllowed(input)booleanCheck if input matches an allowlist rule before running detection.
calculateSecurityConsensus(results)ConsensusResultAggregate threat assessments from multiple agents. Import from monofence-ai.
Threat Types Detected
CategoryExamples
Prompt InjectionInstruction overrides, system prompt leakage attempts
JailbreakDAN, developer mode, role-play bypass patterns
Role Switching"Pretend you are…", "Act as…", persona hijacking
Context ManipulationMemory poisoning, prior context overrides
Encoding AttacksBase64, homoglyph, leet, spaced-character evasion
PII ExposureOutput-scanning for SSN, credit cards, email leakage
Advanced: Multi-Agent Consensus
import { createMonoDefence, calculateSecurityConsensus } from 'monofence-ai'; // Run detection on two independent agents in parallel const [resultA, resultB] = await Promise.all([ agentA.detect(input), agentB.detect(input), ]); const consensus = calculateSecurityConsensus([ { result: resultA, weight: 0.6 }, { result: resultB, weight: 0.4 }, ]); // consensus.consensus β†’ 'safe' | 'threat' | 'uncertain' // consensus.confidence β†’ 0.0 – 1.0 // consensus.criticalThreats β†’ string[]
Migration from @monomind/monodefence
Old (deprecated)New
@monomind/monodefencemonofence-ai
createAIDefence()createMonoDefence()
getAIDefence()getMonoDefence()
AIDefenceConfigMonoDefenceConfig
AIDefenceMonoDefence
--security-check--monofence-ai-check
--security-deep--monofence-ai-security-deep

Deprecated aliases (createAIDefence, @monomind/monodefence import) remain available until v2. Migrate before the next major release.