Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

234 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Moat — AI Moat: The Brake for AI Engineering 🛡️

Version: v1.7.1 · PyPI: pip install moat-ai==1.7.1 · GitHub: wang-jie-git/moat

PyPI version License Python Moats CI

🌐 中文版本 🇨🇳

"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.


🛡️ Security Manifesto: Your Code, Your Domain

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.

📺 Demos

Moat: Bug Interception + AI Audit
Bug Interception → AI Tool Config Audit → Three Lines of Defense

Moat: Leak Detection
Symlink leaks, sensitive file exposure, AI tool trace detection

Moat: AI Tool System Audit
Scan Claude Code / Codex / Grok configs for sensitive info leaks


🌟 North Star — 北极星架构导航 (v1.7.0+)

"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.

Dashboard

Start the web dashboard to view real-time architecture health:

moat dashboard
# Visit http://127.0.0.1:9876

The 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

Initialization

# Auto-scan codebase and generate blueprint (AI-enhanced)
moat north_star init

# Confirm and activate the blueprint
moat north_star confirm

Drift Detection

# Compare current codebase against activated blueprint
moat north_star drift

# Output:
# ✅ 架构合规率: 100.0% (目标 ≥ 95%)
# 🔗 依赖枢纽: 4 高危 / 9 中危 (阈值 5 / 10)
# 💸 技术债务: 16 (TODO: 11, FIXME: 5, 圈复杂度: 149)

Weekly Health Report

# Generate weekly architecture health report
moat north_star weekly

# Store report in One Memory for cross-session persistence
moat north_star weekly --store-memory

Other Commands

moat north_star status           # Show current blueprint summary
moat north_star edit --diff      # Interactive blueprint editing
moat north_star history          # Blueprint version history

4 Architecture Rules

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

Key Features

  • 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.py serves North Star context (blueprint + rules + debt) to Claude Code via MCP protocol
  • One Memory: Architecture snapshots stored as type: architecture insights (optional)

🚨 Leak Detection

moat check --leak — Detect AI tool cross-directory reads and sensitive file exposure:

moat check --leak

Scans for:

  • AI tool traces: .grok/, .claude/, .codex/ configs referenced by the project
  • Sensitive file exposure: .env, credentials.json not 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

👁️ AI Tool System Audit

moat check --scan-ai — Scan local AI tool configurations for security risks:

moat check --scan-ai

Detects:

  • 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

🔐 Permission Audit

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-memory — Self-Learning Memory (v1.2.0+)

Moat remembers every check failure and every fix. The more you use it, the smarter it gets.

Memory Types

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

🏛️ Core File Protection (v1.4.2+)

Protects your core architecture files from unauthorized AI modifications:

moat check  # Core files are automatically protected

Default 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"
        }
      ]
    }
  }
}

🎭 AI Red-Team Adversarial Review (v1.5.0+)

"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 --json

Three 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 check workflow
  • Non-blocking — Failures don't affect the main moat check flow
  • 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

CLI Commands

# 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.md

AI Tool Integration

After moat adapter install, AI tools automatically read moat-memory before modifying code:

  • Claude Code: .claude/skills/moat/SKILL.md loaded at startup
  • Codex CLI: .codex/skills/moat/SKILL.md loaded at startup
  • OpenCode: .opencode/skills/moat/SKILL.md loaded at startup

Zero External Dependencies

All memory is stored in .moat/memory.db (SQLite, WAL mode). No external services, no API calls, no data leaves your machine.


⚔️ Moat vs Traditional Tools

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 ⚠️ Code smells only
Layer Enforcement ✅ Built-in 5 layers + custom
North Star Navigation ✅ Blueprint + compliance + drift + weekly reports
Incremental Audit --diff 2s results ⚠️ File-level only ❌ Full scan
Gate Mode --fail-on-score ⚠️ Partial
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

✨ Three Key Differentiators

🔍 Diff-Aware Audit (Incremental Acceptance)

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.md

🧱 Layer-Enforcer

Built-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 --diff

Customize any layer rules via architect.yml.

🛡️ Environment Isolation Guard (v1.6.2+)

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

📋 Evidence-Based

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

🚀 Quick Start

# 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/Discord

📍 Installation

Moat 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 version

Integration with Claude/Cursor

Method 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 status

Method 2: Sidecar Daemon

moat sidecar start             # Start daemon
curl http://localhost:7777/api/health  # REST API

Method 3: Static Rule Injection

moat adapter claude            # Generate CLAUDE.md
moat adapter all               # Generate rules for all AI tools

📋 Full Command Reference

# 🏗️ 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

📚 Documentation


🔑 Core Philosophy

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.


🏷️ Tags

ai-agent architecture-guard security-tool code-review static-analysis python gatekeeper devtools lint architecture mcp north-star blueprint


License

Apache 2.0

About

AI Coding Gatekeeper — Zero-config, real-time guardrails for AI-generated code. 零配置AI编码守门员,实时拦截架构/安全/回归问题。

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages