Version: v1.7.1 · PyPI:
pip install moat-ai==1.7.1· GitHub: wang-jie-git/moat
🌐 中文版本 🇨🇳
"The Chief Architect for the AI Era" — Not a linter, not a SAST tool. It's the collision avoidance system for your codebase.
AI writes code fast. AI breaks things fast too. Moat runs before and after every code change, telling you in seconds whether your system is still intact.
v1.7.1: 🌟 北极星架构导航 (North Star Navigation) — Architecture blueprint generation, compliance tracking, dependency hub analysis, drift detection, and health weekly reports. Full 28/28 feature completion.
In the wake of the July 2026 Grok CLI incident (auto-packaging codebases + reading ~/.claude/ API keys across directories), Moat upholds the Local-First principle — no compromise on security.
| Commitment | Description |
|---|---|
| Zero-Telemetry | Moat never uploads code snapshots, configs, or API keys. All checks run locally. |
| Transparent Audit | Every file read is under your local audit. No silent side channels. |
| Self-Sovereignty | Your architecture rules, baselines, and memory indices stay under your control. |
Bug Interception → AI Tool Config Audit → Three Lines of Defense
Symlink leaks, sensitive file exposure, AI tool trace detection
Scan Claude Code / Codex / Grok configs for sensitive info leaks
"If Moat is the brake, North Star is the GPS."
Moat's flagship capability: generate an architecture blueprint from your codebase, continuously track compliance, dependency health, and technical debt — then alert you when architecture drifts.
Start the web dashboard to view real-time architecture health:
moat dashboard
# Visit http://127.0.0.1:9876The dashboard shows:
- 🏗️ Architecture Compliance Rate — Layer rule conformance (target: ≥95%)
- 🔗 Dependency Hub Risk — Module centrality analysis (high/medium/low)
- 💸 Technical Debt — TODO/FIXME count + cyclomatic complexity
- 🚫 ARCH-003: Unregistered dependencies not in blueprint
⚠️ ARCH-004: Hub growth exceeding threshold
# Auto-scan codebase and generate blueprint (AI-enhanced)
moat north_star init
# Confirm and activate the blueprint
moat north_star confirm# Compare current codebase against activated blueprint
moat north_star drift
# Output:
# ✅ 架构合规率: 100.0% (目标 ≥ 95%)
# 🔗 依赖枢纽: 4 高危 / 9 中危 (阈值 5 / 10)
# 💸 技术债务: 16 (TODO: 11, FIXME: 5, 圈复杂度: 149)# Generate weekly architecture health report
moat north_star weekly
# Store report in One Memory for cross-session persistence
moat north_star weekly --store-memorymoat north_star status # Show current blueprint summary
moat north_star edit --diff # Interactive blueprint editing
moat north_star history # Blueprint version history| Rule | Description | Enforcement |
|---|---|---|
| ARCH-001 | Directory purpose drift | Blueprint says utils/, code stores auth tokens ❌ |
| ARCH-002 | Cross-layer calls | routes/ directly calls db/ ❌ |
| ARCH-003 | Unregistered imports | Module X imports Y not in blueprint allowed_dependencies |
| ARCH-004 | Hub growth alert | Import hub grows beyond configurable threshold |
- Smart layer rules: 9,506 raw directory pairs → 34 intelligible rules via LLM distillation + keyword mapping fallback
- LLM integration: Auto-initializes LLMClient; falls back to hardcoded rules when no API key is set
- MCP integration:
moat/mcp.pyserves North Star context (blueprint + rules + debt) to Claude Code via MCP protocol - One Memory: Architecture snapshots stored as
type: architectureinsights (optional)
moat check --leak — Detect AI tool cross-directory reads and sensitive file exposure:
moat check --leakScans for:
- AI tool traces:
.grok/,.claude/,.codex/configs referenced by the project - Sensitive file exposure:
.env,credentials.jsonnot excluded by.gitignore - Symlink leaks: Symlinks pointing outside the project (
.ssh/,.aws/) - Hardcoded paths:
~/or/home/sensitive paths in code
🔒 Scanning for code leak risks...
🔍 Scanning for leaks...
🔴 [CRITICAL] AI tool traces found: .grok (Grok CLI session dir)
📍 /project/.grok/
💡 Check if .grok introduces sensitive configs. Remove from project if not needed.
🟡 [WARNING] Symlink pointing outside project: secret.key → ~/.ssh/id_rsa
📍 secret.key
💡 Use relative paths or copy the file into the project.
✅ No code leak risks detected
moat check --scan-ai — Scan local AI tool configurations for security risks:
moat check --scan-aiDetects:
- Claude Code / Codex / Grok config directories
- Telemetry data accumulation
- Authorized sensitive commands (sshpass, scp, tar+curl combinations)
- Session history containing sensitive conversation data
🕵️ AI tool system config security audit...
📋 Found Claude Code config: /Users/mac/.claude
🟡 [WARNING] Claude Code telemetry data: 24 files, 302.3 KB
📍 /Users/mac/.claude/telemetry
ℹ️ [INFO] Claude Code session history: 421.9 KB
📍 /Users/mac/.claude/history.jsonl
🟡 [WARNING] Claude Code has 19 sensitive commands authorized
📍 /Users/mac/.claude/settings.local.json
moat audit --permissions — Audit AI tool permissions and get a "slimming" recommendation:
moat audit --permissions🔍 AI Tool Permission Audit...
📋 Analyzing 156 authorized commands...
🔴 [CRITICAL] 4 plaintext passwords found in command args
🟡 [HIGH] 4 high-risk commands never used
🟢 [INFO] 59 safe commands actively used
📊 Idle rate: 62% (96 unused permissions)
💡 Recommended: remove 4 plaintext passwords, remove 4 unused commands
Moat remembers every check failure and every fix. The more you use it, the smarter it gets.
| Type | Description | Auto-generated |
|---|---|---|
| Redlines | Architecture rules & coding boundaries | ✅ moat init presets 5 defaults |
| Lessons | Check failure records | ✅ On every moat check failure |
| Templates | Experience patterns from git diffs | ✅ On successful moat check if last commit is a fix |
| Skills | AI tool instructions | ✅ moat adapter install |
Protects your core architecture files from unauthorized AI modifications:
moat check # Core files are automatically protectedDefault protected files:
- Application entry points:
App.tsx,App.jsx,App.vue - Critical pages:
ChatPage.tsx - Server entry points:
server.py,main.py,app.py - WebSocket logic:
*websocket*,*ws*handler*,*bridge* - Auth configs:
*auth*,*permission*
Customize in .moat/moat.json:
{
"rules": {
"core_file_modification": {
"enabled": true,
"core_files": [
{
"name": "my_core",
"patterns": ["SecretFile.tsx"],
"description": "My confidential files"
}
]
}
}
}"Use AI to review AI" — Moat reviews your code with three ruthless AI personas to find bugs before they bite:
# Auto-trigger (when Pain Score ≥ 75)
moat check --full
# Explicit trigger
moat review
# Target specific files
moat review --files payment.py auth.py
# JSON output (for CI/CD)
moat review --jsonThree Ruthless Personas:
| Role | Focus | Expertise |
|---|---|---|
| 🔴 Security Auditor | SQL injection, XSS, hardcoded secrets, auth bypass | OWASP Top 10 |
| 🏗️ Architect | Layer violations, circular deps, God objects | Clean Architecture |
| ⚡ Concurrency Devil | Race conditions, deadlocks, missing await | Async safety |
Key Features:
- ✅ Independent context — The reviewing LLM only sees evidence chains (git diff + AST + One Memory), no bias
- ✅ Tiered triggering — Only triggers when needed (Pain Score ≥ 75 / critical files / explicit command)
- ✅ Multiple LLM support — Anthropic Claude + OpenAI-compatible APIs
- ✅ Zero intrusion — Seamlessly integrated into
moat checkworkflow - ✅ Non-blocking — Failures don't affect the main
moat checkflow - ✅ Robust — v1.5.2 fixed ThinkingBlock handling + version comparison (100% test coverage)
Configure in .moat/moat.json:
{
"adversarial_review": {
"enabled": true,
"always_review": false,
"pain_threshold": 75.0,
"review_depth": "standard",
"enable_security_auditor": true,
"enable_architect": true,
"enable_concurrency_devil": true,
"model": "claude-sonnet-4",
"max_tokens": 4000,
"timeout": 30
}
}📚 Documentation: docs/adversarial_review.md
# Overview
moat memory # Memory stats (default)
moat memory --ai # AI-readable format (all memories)
# Redlines (architecture rules)
moat redline list # List all redlines
moat redline add "禁止跨层调用" --description "routes/ 不应直接调用 db/" --severity critical
moat redline remove <id>
# Templates (experience patterns)
moat template list # List all templates
moat template extract # Extract from latest git commit (keyword)
moat template extract --llm # Extract with LLM semantic analysis (optional)
# Adapters (AI tool integration)
moat adapter claude # Inject memory reading instructions into CLAUDE.mdAfter moat adapter install, AI tools automatically read moat-memory before modifying code:
- Claude Code:
.claude/skills/moat/SKILL.mdloaded at startup - Codex CLI:
.codex/skills/moat/SKILL.mdloaded at startup - OpenCode:
.opencode/skills/moat/SKILL.mdloaded at startup
All memory is stored in .moat/memory.db (SQLite, WAL mode). No external services, no API calls, no data leaves your machine.
Moat is not a linter replacement. It's a new category: AI Engineering OS Linters check syntax, SAST scans vulnerabilities, Moat governs architecture.
| Dimension | 🛡️ Moat | 🔧 Traditional Linter | 📊 SonarQube |
|---|---|---|---|
| Core Positioning | AI Engineering OS | Code style check | Code quality platform |
| Architecture Governance | ✅ 8-step acceptance loop | ❌ Syntax/style only | |
| Layer Enforcement | ✅ Built-in 5 layers + custom | ❌ | ❌ |
| North Star Navigation | ✅ Blueprint + compliance + drift + weekly reports | ❌ | ❌ |
| Incremental Audit | ✅ --diff 2s results |
❌ Full scan | |
| Gate Mode | ✅ --fail-on-score |
✅ | |
| Evidence Chain | ✅ Reason → File → Line | ❌ Line only | ✅ |
| Security Injection | ✅ Zero false positives | ❌ High noise | ✅ |
| AI Context Integration | ✅ MCP / Claude Code Hook | ❌ | ❌ |
| Performance | < 0.2s/run | Medium | Slow (full scan) |
| Test Coverage | 99.8%+ (1054 tests) | ❌ | ❌ |
| Configuration | Zero config | Requires config | Requires config |
Full scan of 4160 files? Too slow. moat accept --diff scans only the 5 files you changed, completing architecture-level audit in 2 seconds.
# Incremental acceptance after changing a few files
moat accept --diff --fail-on-score 60
# Full acceptance
moat accept --output ACCEPTANCE_REPORT.mdBuilt-in standard MVC/DDD layer rules, auto-detects cross-layer violations like routes/ directly calling db/.
# Default 5-layer rule: routes → services → db / models / utils
moat accept --diffCustomize any layer rules via architect.yml.
Prevents AI from polluting your Python environment. Three new rules for zero-configuration environment protection:
# Standard moat check now includes environment isolation
moat check --quick
# Output example:
❌ [CRITICAL] [ENV-001] 环境污染警告:当前 Python 解释器 (/usr/bin/python3)
不在项目虚拟环境中!
修复建议: 使用 'uv run python' 或激活 .venv
⚠️ [WARN] [ENV-002] 依赖漂移:代码中引用了 'pandas',但未在 pyproject.toml 中声明。
修复建议: 将 pandas 添加到 dependencies 列表中
ℹ️ [INFO] [ENV-003] 发现危险命令(pip install 裸奔命令)
文件: setup.sh:3
建议: 使用 'uv pip install' 或 '.venv/bin/pip install'Three Rules:
| Rule | Severity | Description |
|---|---|---|
| ENV-001 | CRITICAL | Detects if current Python interpreter is from global env (not .venv) |
| ENV-002 | WARNING | Detects undeclared dependencies (code imports vs config files) |
| ENV-003 | INFO | Scans for bare pip install commands in scripts/Makefiles |
Zero Configuration: Works out of the box with .venv, venv, requirements.txt, and pyproject.toml.
Performance: +1s overhead (quick mode), no impact on full mode.
📚 Documentation: docs/env_isolation_plan.md
All blocks come with a complete evidence chain, not black-box errors:
❌ LAYER_VIOLATION: routes/ should not directly import db/
→ Reason: Layer violation (routes → services → db)
→ File: app/routes/user.py:15
→ Detail: Direct import db.session
# Install
pip install moat-ai
# Zero-config init
moat init
# 🌟 North Star Architecture Navigation (v1.7.0+)
moat dashboard # Open web dashboard
moat north_star init # Generate architecture blueprint
moat north_star confirm # Activate blueprint
moat north_star drift # Check architecture drift
moat north_star weekly # Generate health report
moat north_star status # View blueprint summary
# Basic checks
moat check --quick # Second-level check
moat check --full # Full check (includes architecture audit)
moat check # Core file protection (v1.5.0+)
moat check --leak # 🔒 Leak detection (2s)
moat check --scan-ai # 👁️ AI tool config audit
# Architecture acceptance (v1.1.4+)
moat accept # 8-step architecture acceptance
moat accept --diff # Incremental acceptance (2s)
moat accept --output report.md # Generate report
# Gate mode
moat accept --diff --fail-on-score 60 # Block if score < 60
# Permission audit (v1.1.9+)
moat audit --permissions # 🔐 Permission audit + slimming
# AI Red-Team Review (v1.5.0+)
moat review # Review all changes
moat review --files payment.py # Review specific files
moat review --json # JSON output for CI/CD
# AI Review Config (v1.5.1+)
moat config # View review config
moat config set --key model --value claude-3-5-sonnet # Configure
moat config test # Test LLM connection
# CI/CD integration
moat ci # Auto-generate GitHub Actions workflow
moat notify --webhook <url> # Send results to Slack/Feishu/DiscordMoat is a standard Python package, runs on your local machine. Code never leaves your machine.
pip install moat-ai # Latest stable (v1.7.1)
pip install moat-ai==1.7.1 # Specific versionMethod 1: Direct CLI (Recommended)
Claude executes Moat commands directly in the terminal, just like a human developer:
moat check --full # Full check
moat accept # Architecture acceptance
moat gatekeeper check --file app.py # Single file check
moat north_star status # Check blueprint statusMethod 2: Sidecar Daemon
moat sidecar start # Start daemon
curl http://localhost:7777/api/health # REST APIMethod 3: Static Rule Injection
moat adapter claude # Generate CLAUDE.md
moat adapter all # Generate rules for all AI tools# 🏗️ North Star Navigation (v1.7.0+)
moat dashboard # Web dashboard (http://127.0.0.1:9876)
moat north_star init # Generate architecture blueprint
moat north_star confirm # Activate blueprint
moat north_star drift # Check architecture drift vs blueprint
moat north_star status # Show blueprint summary
moat north_star edit --diff # Interactive blueprint editing
moat north_star history # Blueprint version history
moat north_star weekly # Weekly architecture health report
moat north_star weekly --store-memory # + persist to One Memory
# Core checks
moat check [--quick|--full|--diff] # 4 check modes
moat check --leak # 🔒 Leak detection
moat check --scan-ai # 👁️ AI tool config audit
moat init # Zero-config init
moat watch # Real-time log monitoring
moat report [--format pdf|md|json] # Generate report (PDF supported)
moat baseline [save|show|diff] # Baseline management
# Architecture acceptance (v1.1.4+)
moat accept # 8-step architecture acceptance
moat accept --diff # Incremental acceptance
moat accept --output report.md # Generate report
moat accept --fail-on-score 60 # Gate mode
# Permission audit (v1.1.9+)
moat audit --permissions # 🔐 Permission audit + slimming
# CI/CD integration (v1.1.6+)
moat ci # ⚡ Generate GitHub Actions / GitLab CI
moat notify --webhook <url> # 🔔 Send results to Slack / Feishu / Discord
# Optimization checks
moat check --quick --optimize # Quick + optimization rules
moat check --full --optimize # Full + optimization rules
# Evolution metrics
moat evolution report # View evolution report
moat evolution adjust # Auto-adjust configuration
# Sidecar daemon
moat sidecar start # Start daemon
moat sidecar status # View status
moat sidecar stop # Stop daemon
# AI adapters
moat adapter claude # Install Claude Code adapter
moat adapter all # Install all AI tool adapters
moat adapter precommit # Install pre-commit hook
# moat-memory (v1.2.0+)
moat memory # 📊 Memory stats
moat memory --ai # 🤖 AI-readable format (all memories)
moat redline list # 📏 List redlines
moat template extract # 📋 Extract template from git commit
moat template extract --llm # 🤖 Extract with LLM semantic analysis- Quick Start — Get started in 5 minutes
- North Star Architecture Guide — 🌟 Architecture navigation
- Security Detection Guide — 🛡️ AI tool security audit
- FAQ — Frequently Asked Questions
- Project Map — Feature overview
- CHANGELOG — Version history
- ROADMAP — Future roadmap
- Contributing — How to contribute
AI lies, cuts corners, and hallucinates.
Moat's real value: it's the brake for AI.
No matter how AI evolves, physics doesn't change — high speed needs brakes, complex systems need checkpoints, continuous output needs validation pauses.
Why this positioning matters:
- ❌ Toy vs. Tool: If defined as "AI Engineering OS", it's a toy. If defined as "the brake", it's a tool.
- ❌ AI will get stronger, not more honest: Future AI will be more capable, but still have "lazy tendencies" and "memory blind spots".
- ✅ The eternal value of a "brake": High-speed motion needs brakes. Complex systems need checkpoints.
You own the code, you own the guard.
ai-agent architecture-guard security-tool code-review static-analysis
python gatekeeper devtools lint architecture mcp north-star blueprint
Apache 2.0