# Warden Core - The AI Code Guardian

> "AI writes the code. Warden guards the production."

![Status](https://img.shields.io/badge/Status-Beta-yellow)
![Python](https://img.shields.io/badge/Python-3.10%2B-blue)
![License](https://img.shields.io/badge/License-Apache_2.0-green)
![AI Ready](https://img.shields.io/badge/AI-Native-purple)

<p align="center">
  <img src="https://raw.githubusercontent.com/alperduzgun/warden-core/main/warden_badge.svg" alt="Warden Quality" />
</p>

**Warden** is an AI-native security and quality gate designed to validate code generated by LLMs (Claude, GPT-4, etc.) before it enters your codebase. It acts as a strict, impartial judge enforcing architectural rules, preventing security vulnerabilities, and maintaining code hygiene.

---

## 🤖 Why Warden?

### The AI Paradox: The "Wild Horse" Analogy 🐎
In a world where coding is automated, developers face a new crisis: **Loss of Context.**
> "An AI-generated project is like a **Wild Horse (Yılkı Atı)**. It is incredibly fast and powerful, capable of building weeks of work in minutes. But without a skilled handler (**Seyis**), it becomes unmanageable. It may bolt in the wrong direction, refuse to scale, or become untrained over time."

Warden is that handler. It ensures you never lose the reins of your codebase, no matter how fast the AI runs.

### The Problem
AI coding assistants are powerful but prone to:
*   **Hallucinations:** Inventing non-existent APIs or libraries.
*   **Subtle Bugs:** Introducing edge cases that human reviewers miss.
*   **Security Flaws:** Hardcoding secrets or using unsafe patterns.
*   **Drift:** Deviating from established project architecture.

Warden provides the **"Verify-Loop"** mechanism to ensure every AI-generated change is validated against a rigorous set of rules.

---

## 🌍 Universal Language Support
Warden's **Engine** runs on Python/Rust, but it validates code in **any language**.

| Category | Supported Languages (Native) | Taint Analysis |
| :--- | :--- | :--- |
| **Mobile** | **Flutter (Dart)**, Swift, Kotlin, React Native | - |
| **Backend** | Python, **Go**, **Rust**, Node.js (TS/JS), **Java** | Python, Go, Java, JS/TS |
| **Frontend** | React, Vue, Angular, HTML/CSS | JS/TS (DOM XSS) |
| **Scripting** | Shell (Bash), Lua, Perl | - |

> **Pro Tip:** Warden can orchestrate *existing* tools. Already using `very_good_analysis` for Flutter? Warden wraps it, giving it a unified interface and fixing capabilities.

## 🚀 Core Features

### 1. 🧠 AI-Native Integration (MCP & Hooks)
Warden is built to integrate directly with your AI Agent:
*   **Context Loading:** Automatically injects `.warden/AI_RULES.md` into every session via Claude `SessionStart` hooks.
*   **Protocol Enforcement:** Instructs AI agents to follow the **Plan -> Execute -> Verify** loop.
*   **Feedback Loop:** Provides JSON/SARIF reports that AI agents can read to self-correct.

### 2. ⚡ Offline-First Intelligence (New!)
Warden is built for resilience. Unlike SaaS tools that go dark without internet:
*   **Local Models:** Multiple options - Claude Code CLI (uses desktop app), Codex CLI (OpenAI local agent), Ollama (Qwen), or any local LLM server.
*   **Network Resilience:** Automatically detects connection timeouts and switches to local cache instantly.
*   **Zero Latency:** No API round-trips for standard scans.
*   **Zero API Costs:** Claude Code leverages your existing subscription without consuming API credits.

### 3. 🧠 Hybrid AI Engine (Dual-Tier)
Warden balances cost, privacy, and intelligence using a smart routing system:
*   **Local Tier (Privacy-First):**
    - **Claude Code CLI** (uses your existing subscription, zero API costs)
    - **Codex CLI** (OpenAI local agent, read-only sandbox mode)
    - **Qwen 2.5-Coder** (via Ollama) for high-frequency tasks
    - **Free & Private** - Code never leaves your machine
*   **Cloud Tier (Advanced Analysis):** Routes only complex logic (security fixes, architecture audits) to **GPT-4o/Claude API/Gemini**.
*   **Result:** 90% cost reduction compared to pure cloud agents.

**Supported Providers:**
- 🏠 **Local:** Claude Code, Codex CLI, Ollama (Qwen), Any OpenAI-compatible local server
- ☁️ **Cloud:** Anthropic (Claude), OpenAI (GPT-4), Google (Gemini), Groq, DeepSeek

#### ⚡ Performance & Optimization

Warden implements global performance optimizations that benefit ALL providers:

**1. Parallel Fast Tier Execution** (New!)
- Multiple fast providers race simultaneously - fastest wins
- Example: Claude Code (10s) + Ollama (0.7s) run in parallel → Result in ~0.7s
- **Impact:** Up to 93% faster than sequential execution

**2. Smart Caching**
- File-level hash-based caching skips unchanged files
- Result-level caching stores analysis outcomes
- **Impact:** 95% reduction in redundant LLM calls

**3. Intelligent Routing**
- Fast tier (local models) for syntax/lint checks
- Smart tier (cloud models) for complex security analysis
- Automatic fallback if fast providers unavailable
- **Single-provider mode:** CLI tools (Claude Code, Codex) route all requests through themselves — no tier split needed

**Provider Performance Profiles:**

| Provider | Avg Response | Overhead | Best Use Case |
|----------|-------------|----------|---------------|
| **Ollama (Qwen)** | ~0.7s | 50ms | Quick checks, lint validation |
| **Codex CLI** | ~5-15s | 100ms | Deep analysis, read-only sandbox |
| **Claude Code** | ~10s | 200ms | Deep analysis, security audits |
| **Azure (GPT-4)** | ~2.2s | 100ms | Complex logic, architecture review |
| **Anthropic API** | ~1.5s | 80ms | Security fixes, context-aware analysis |

**Configuration Example:**
```yaml
llm:
  # Parallel execution of fast providers
  fast_tier_providers:
    - ollama       # Fastest (0.7s avg)
    - claude_code  # Quality fallback if Ollama unavailable
    - groq         # Cloud fallback

  # Smart tier for complex analysis
  provider: claude_code  # or anthropic, openai
  smart_model: claude-sonnet-4-20250514
```

**💡 Optimization Tips:**
- **Use --diff mode** for incremental scans (analyze only changed files)
- **Enable smart caching** (default: enabled) for 95% faster repeat scans
- **Hybrid routing** leverages fast local models for 90% of checks
- **Parallel execution** automatically races all fast providers

### 4. 🛡️ Core Validation Frames (Built-in)
Warden ships with 6 powerful core frames:
1.  **SecurityFrame:** Detects vulnerabilities (SQLi, Secrets, XSS) with **multi-language taint analysis**.
2.  **ResilienceFrame:** Validates error handling, retry, and circuit-breaker patterns.
3.  **ArchitecturalFrame:** Enforces project structure and clean code references.
4.  **SpecFrame (API Contract):** Extracts and compares API contracts (Consumer vs Provider).
    - **Why SpecFrame?** Unit tests only prove that components work *internally*. SpecFrame is the only mechanism that audits both sides simultaneously to detect "Invisible Drift" (e.g., when the Frontend and Backend start speaking different languages). It automatically identifies what is missing or incorrect in the Consumer/Provider pair.
5.  **AntiPatternFrame:** Detects code smells, god classes, and bad practices.
6.  **OrphanFrame:** Detects dead code and unreferenced assets.

#### 🔍 Source-to-Sink Taint Analysis (Shared Service)

Warden includes a multi-language **taint tracking engine** that traces untrusted user input from its source to dangerous sinks (SQL queries, shell commands, HTML rendering, etc.).

Taint analysis runs as a **shared service** during the Pre-Analysis phase — computed once per pipeline run, consumed by multiple frames:

| Frame | How It Uses Taint Data |
| :--- | :--- |
| **SecurityFrame** | Direct vulnerability detection — unsanitized source-to-sink paths become findings |
| **FuzzFrame** | Taint sources become **high-priority fuzz targets** — focused edge-case testing on real input paths |
| **ResilienceFrame** | Findings on tainted paths get **severity boost** (medium → high) — missing resilience on user-controlled data is riskier |

```
Pipeline Phase 0 (PRE-ANALYSIS)
  └── TaintAnalysisService           ← catalog loaded once, all files scanned
        └── context.taint_paths = {file → [TaintPath, ...]}
                │
    ┌───────────┼───────────┐
    ▼           ▼           ▼
SecurityFrame  FuzzFrame  ResilienceFrame
 (shared-first, inline fallback)
```

**Supported Languages:**

| Language | Analysis Method | Frameworks |
| :--- | :--- | :--- |
| **Python** | AST-based (single-function scope) | Flask, FastAPI, Django, stdlib |
| **JavaScript/TypeScript** | Regex-based (3-pass propagation) | Express.js, Koa.js, Browser DOM, Node.js |
| **Go** | Regex-based (3-pass propagation) | net/http, database/sql |
| **Java** | Regex-based (3-pass propagation) | Servlet, Spring (JdbcTemplate) |

**Three-Layer Catalog Architecture:**

```
Layer 1  Built-in YAML model packs   (models/{lang}/*.yaml)
Layer 2  Hardcoded constants          (baseline guarantee, always active)
Layer 3  User overrides               (.warden/taint_catalog.yaml)
```

All layers are **unioned** — user entries never replace built-in defaults.

**Heuristic Signal Inference:**
For unknown frameworks, a signal-based inference engine (`signals.yaml`) detects potential sources and sinks by analyzing method names, parameter hints, and module patterns. Confidence scores are lower (0.60-0.70) compared to explicit model packs (0.99).

**Extending the Catalog:**

Add custom sources, sinks, or sanitizers via `.warden/taint_catalog.yaml`:

```yaml
sources:
  python:
    - fastapi.Request.query_params
  go:
    - gin.Context.Query
  javascript:
    - ctx.request.body

sinks:
  SQL-value:
    - prisma.raw
    - mongoose.exec

sanitizers:
  HTML-content:
    - myCustomSanitizer
```

**Adding Taint Awareness to Custom Frames:**

Any frame can consume taint data by implementing the `TaintAware` mixin:

```python
from warden.validation.domain.mixins import TaintAware

class MyCustomFrame(ValidationFrame, TaintAware):
    def set_taint_paths(self, taint_paths):
        self._taint_paths = taint_paths

    async def execute_async(self, code_file):
        paths = self._taint_paths.get(code_file.path, [])
        # Use taint paths in your analysis logic
```

### 5. 🧩 Warden Hub (Marketplace)
Need more power? Install specialized frames from the community:
*   **Fuzz Testing:** `warden install fuzz`
*   **Property Testing:** `warden install property`
*   **Load Testing:** `warden install stress`

### 6. 💅 Integrated Linter & Style
Warden acts as a central hub for code quality, integrating tools like `ruff` directly into its pipeline.

### 🧩 Frames Concept: Intelligence Adapters
Frames in Warden are not just plugins; they are **Intelligence Adapters** that drive dumb tools.
*   **The Problem:** Tools like `ruff`, `mypy`, or `dart analyze` are just execution engines. They don't know your business context.
*   **The Warden Frame:** Acts as a "Driver" that:
    1.  **Standardizes:** Unifies CLI arguments and JSON outputs across all tools.
    2.  **Contextualizes:** Decides if a finding matters based on Project Purpose.
    3.  **Elevates:** Turns a "Lint Error" into a "Security Finding" if relevant.

> **Philosophy:** `warden install python_lint` doesn't just install Ruff; it teaches Warden *how to use* Ruff intelligently.

### 🛡️ Defense-in-Depth Hierarchy
Warden sits at the top of the quality pyramid:

1.  **Linter Layer (Fastest):** `Ruff`, `Biome`, `Dart Analyze` (Syntax & Style)
2.  **Static Analysis (Deep):** `SonarQube`, `Snyk` (Vulnerabilities)
3.  **Warden Core (Guardian):** Context-Aware, Architectural, AI-Powered Protection.

**Pre-Analysis Strategy:** Warden detects your stack (e.g., "This is a Flutter Project") *before* defining the pipeline, ensuring zero wasted resources on irrelevant checks.

### 7. ✨ Warden Craftsman (New!)
Warden doesn't just find bugs; it acts as a **Senior Software Craftsman**. The Cleaning Phase (`code-simplifier`) analyzes your code for:
*   **Elegance:** Simplifying nested logic and removing redundant variables.
*   **Clarity:** Reducing cognitive load and improving readability.
*   **Modernization:** Suggesting modern language features (e.g., Python `f-strings`, `list comprehensions`).

*Try it yourself:*
```bash
warden scan examples/messy_code.py
```

### 8. 🚦 False Positive Management
Warden gives you granular control over what to check:
*   **Inline Suppression:** Use `# warden-ignore: rule-id` to suppress specific issues.
*   **Global Config:** Define suppressions in `.warden/suppressions.yaml`.
*   **File Exclusion:** Respects `.gitignore` and supports `.warden/ignore.yaml`.

### 9. 🧠 Structural Intelligence & Hygiene (New!)
Warden goes beyond code syntax; it understands your **Project Architecture**:
*   **Anomaly Detection:** Uses AI to identify structural flaws (e.g., redundant configuration files, orphaned directories) that static analysis misses.
*   **Smart Hygiene:** Automatically filters noise (`__pycache__`, `node_modules`) globally, ensuring AI focuses only on relevant code.
*   **One-Config Standard:** Enforces a single source of truth (`.warden/config.yaml`), preventing "Config Drift".

### 10. 🧠 Dynamic AI-Powered Rules (New!)
Warden reaches beyond static analysis patterns:
*   **Pure AI Rules:** Define rules using human language directives (e.g., "Check for race conditions in async loops"). No regex required.
*   **Context-Aware Loading:** Rules automatically activate based on your project's framework (FastAPI, React, etc.) and project type (Microservice, Library).
*   **Deep Logic Auditing:** Detects complex flaws like synchronization issues, circular dependencies, and resilience pattern violations.

### 11. 🧠 Hallucination Prevention (Suppression System)
AI analysis can sometimes produce "hallucinations" – findings that look like issues but are actually valid code patterns (false positives). Warden provides a dedicated **Suppression Phase** to filter these out.

**How it works:**
1.  **Generation:** Frames analyze code and may generate false positives (e.g., `stress-unclosed_file` on a managed stream).
2.  **Filtration:** Before reporting, Warden checks `.warden/rules/suppressions.yaml`.
3.  **Suppression:** If a finding matches a suppression rule, it is silently removed from the report.

**Configuration (`.warden/rules/suppressions.yaml`):**
```yaml
enabled: true
entries:
  - id: "suppress-stress-fp"        # Unique ID for the rule
    rules:
      - "stress-unclosed_file"      # The Finding ID to suppress (e.g. hallucination)
    file: "src/utils/stream.py"     # Specific file path
    reason: "Standard streams are managed by system"
```
> **Note:** Unlike `CustomRule`s which are *active* checks, Suppressions are *passive* filters that run at the very end of the pipeline.

### 12. 🛡️ Hybrid Analysis (Verification Phase)
Warden reduces false positives by implementing a "Trust but Verify" approach:
1.  **Fast Scan:** Static analysis (Regex/LSP) quickly identifies potential issues.
2.  **LLM Judge:** A specialized prompt acts as a "Senior Security Engineer", reviewing the finding against the code context.
3.  **Result:**
    -   **True Positives:** Passed to Fortification for fixing.
    -   **False Positives:** (e.g., Type Hints mistaken for arrays) are silently filtered out BEFORE consuming tokens on auto-fix generation.

### 13. 🎯 Intent-Driven Validation
Warden doesn't just check *correctness*; it checks *appropriateness*.
*   **The Concept:** A "hardcoded password" might be a critical vulnerability in a **Banking API**, but completely valid in a **Test Seeder**.
*   **How it Works:** Warden analyzes your project structure (`package.json`, `requirements.txt`) to detect intent (e.g., "This is a Crypto Wallet" vs "This is a CLI Tool").
*   **The Result:** Rules adjust dynamically:
    *   *Crypto Wallet:* 🛡️ Paranoid Mode (No http, strict types)
    *   *CLI Tool:* ⚡ Relaxed Mode (Allow print statements, rapid I/O)

### 14. 🧠 LLM Audit Context & Code Intelligence (New!)
Traditional LLM bots run "blind" reading text streams without structure. Warden acts differently: it maps your codebase deterministically to provide **Zero-Hallucination Audit Context** for LLMs.
*   **Layer 1 (Dependencies):** Automatically builds a file-to-file structural `DependencyGraph`.
*   **Layer 2 (Symbol Graph):** Uses AST traversal to extract relationships (`CodeGraph`) meaning Class inheritance, Method calls, and Mixin implementations without LLM token cost.
*   **Layer 3 (Runtime Validation):** Validates the AST connections using the Language Server Protocol (LSP) to ensure the map matches actual runtime execution perfectly.
*   **Self-Auditing (`--check`):** Warden computes a `GapReport` identifying broken imports, orphaned files, circular dependencies, and unreachable code.
*   **LLM Integration:** Run `warden audit-context --format markdown` to generate an optimized summary of your project's DNA. Feed this to Grok, ChatGPT, or Claude before starting code audits so they instantly understand your architecture. MCP (Claude Code/Cursor) uses `warden_get_audit_context` and `warden_query_symbol` under the hood.

---

## 🏁 Quick Start

### Installation

```bash
pip install warden-core
```

### Initialization (The Critical Step)

To setup Warden for your project and **configure your AI Agent**:

```bash
warden init --agent
```

Tips:
– On CI or headless environments, prefer: `warden init --no-agent --skip-mcp --no-grammars`
– Flags: `--baseline/--no-baseline`, `--intel/--no-intel`, `--grammars/--no-grammars`, `--agent/--no-agent`

This command:
1.  Analyzes your project structure.
2.  Creates `.warden/AI_RULES.md`.
3.  Configures Claude Code hooks (`.claude/settings.json`) to auto-load rules.
4.  Sets up MCP configuration.
5.  Creates `.env` and `.env.example` for your API keys.

### Configure Your LLM Provider

Warden auto-detects available providers and uses the best local option by default:

**Option 1: Claude Code (Recommended for Claude Users)**
```bash
# No setup needed! If you have Claude Code CLI installed:
warden config llm use claude_code

# Verify it's working:
warden config llm test
```

**Option 2: Codex CLI (Recommended for Codex Users)**
```bash
# No setup needed! If you have the Codex CLI installed:
warden init --provider codex

# Register Warden as an MCP tool in Codex (optional):
warden codex mcp-setup

# Or use it directly:
warden config llm use codex
warden config llm test
```

**Option 3: Ollama (Free & Offline)**
```bash
# Install Ollama and pull Qwen model:
ollama pull qwen2.5-coder:7b

# Warden will auto-detect and use it
warden scan
```

**Option 4: Cloud Providers (API Key Required)**
```bash
# Select a provider:
warden config llm use anthropic   # or: openai, groq, gemini, deepseek, azure

# Set environment variables for the chosen provider:
export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...
export GROQ_API_KEY=gsk_...
export GEMINI_API_KEY=...
export AZURE_OPENAI_API_KEY=...
export AZURE_OPENAI_ENDPOINT=...
export AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o
```

**Check Current Configuration:**
```bash
warden config llm status
```

### The "Verify-Loop" Protocol

AI Agents working in a Warden project follow this strict protocol:

1.  **PLAN:** Design the change (Task or Phase).
2.  **EXECUTE:** Implement the code.
3.  **VERIFY:** Run `warden scan` at the end of the task/phase.
    *   **IF PASS:** Display **Quality Score (X/10)** 🚀
    *   **IF FAIL:** Fix issues and Repeat.

---

## 🛠️ Command Reference

| Command | Description |
| :--- | :--- |
| `warden scan` | Runs the full validation pipeline on the project. |
| `warden scan --diff` | **(New!)** Incremental scan. Checks only files changed relative to main branch. |
| `warden scan --diff --baseline` | **(New!)** Smart Autopilot. Uses baseline to hide legacy issues. |
| `warden config llm` | **(New!)** Manage LLM provider (status/use/test). |
| `warden config llm status` | Shows current LLM configuration and available providers. |
| `warden config llm test` | Tests the active LLM provider connection. |
| `warden serve` | Starts the MCP Server for AI integration. |
| `warden doctor` | Checks project health and configuration status. |
| `warden install` | Installs/Updates validation frames. |
| `warden search <query>` | Searches Warden Hub or local codebase. |

### ⚡ Incremental Scanning (The Speed Force)
Don't wait hours for a full scan. Use **Diff Mode** to check only your recent changes:

```bash
# Checks changes relative to 'main' (staged + unstaged)
warden scan --diff

# Checks changes relative to a specific branch
warden scan --diff --base origin/develop
```

> **Result:** Scans finish in seconds, providing "Deep Scan" quality for just the code you touched.

### 🤖 Smart Baseline Autopilot (Delta Analysis)
Stop fighting legacy code. The **Smart Baseline Autopilot** ensures you only see *new* issues introduced in your current task, automatically suppressing existing "Legacy Debt".

#### How it Works:
1.  **Baseline Generation:** CI/CD generates a `baseline.json` (the "Known Good" state) on every merge to `main`.
2.  **Auto-Fetch:** When you run a scan, Warden automatically fetches the latest baseline from your repository or cloud storage.
3.  **Delta Filtering:** Warden compares findings against the baseline using **Semantic Hashing**. If a finding already exists in the baseline, it is hidden from the report.

#### Configuration (`.warden/config.yaml`):
```yaml
baseline:
  enabled: true
  path: .warden/baseline.json
  auto_fetch: true
  # Vendor-agnostic fetch command (GitHub, GitLab, S3, etc.)
  fetch_command: "gh run download -n warden-baseline" 
```

#### CLI Usage:
```bash
# Automatically applies baseline filtering
warden scan --diff
```

---

## 🛡️ Badge Integration

Show off your project's security and quality score with a dynamic badge.

### 1. Generate the Badge Data
In your CI/CD pipeline, run Warden with the `badge` format (Generates SVG):
```bash
warden scan --format badge --output ./warden_badge.svg
```

### 2. Add to README
Add the following Markdown to your `README.md`. Replace `USER/REPO` with your GitHub details:

```markdown
![Warden Quality](https://raw.githubusercontent.com/USER/REPO/main/warden_badge.svg)
```

**Quality Tiers:**
*   🟢 **9.0+**: Excellent (Bright Green)
*   🟢 **7.5+**: Good (Green)
*   🟡 **5.0+**: Warning (Yellow)
*   🟠 **2.5+**: Risk (Orange)
*   🔴 **< 2.5**: Critical (Red)

---


## ⚙️ Configuration

### LLM Provider Configuration (`.warden/config.yaml`)

Warden supports multiple LLM providers with automatic fallback and intelligent routing:

```yaml
llm:
  # Provider auto-detection (enabled by default)
  auto_detect: true

  # Active provider
  active_provider: claude_code  # or: ollama, anthropic, openai, gemini

  providers:
    claude_code:
      enabled: true
      model: claude-sonnet-4-20250514
      timeout_seconds: 120
      # No API key needed - uses your Claude Code CLI subscription

    codex:
      enabled: true
      timeout_seconds: 120
      # No API key needed - uses your Codex CLI (OpenAI local agent)
      # Model is managed via ~/.codex/config.toml

    ollama:
      enabled: true
      endpoint: http://localhost:11434
      model: qwen2.5-coder:7b
      timeout_seconds: 60

    anthropic:
      enabled: false
      api_key: ${ANTHROPIC_API_KEY}  # From environment
      model: claude-sonnet-4-20250514
      timeout_seconds: 120

    openai:
      enabled: false
      api_key: ${OPENAI_API_KEY}
      model: gpt-4o
      timeout_seconds: 90

  # Intelligent routing (optional)
  routing:
    fast_tier: ollama        # For quick checks (linting, parsing)
    smart_tier: claude_code  # For complex analysis (security, architecture)
```

**Priority Order (Auto-Detection):**
1. Claude Code (if CLI installed)
2. Codex CLI (if installed)
3. Ollama (if running with Qwen model)
4. Anthropic (if API key set)
5. OpenAI (if API key set)
6. Gemini (if API key set)

> **Note:** Claude Code and Codex are **single-provider** tools — they manage their own model selection internally. When either is selected as the primary provider, all Warden requests (triage, analysis, classification) route through that one tool. There is no fast/smart tier split.

---

## 📂 Project Structure

```
.
├── .warden/
│   ├── AI_RULES.md          # Protocol for AI Agents
│   ├── config.yaml          # Pipeline configuration
│   ├── ignore.yaml          # File exclusions
│   └── rules/               # Custom rules & Suppressions
│       ├── suppressions.yaml # False positive rules
│       ├── ai_rules.yaml    # AI-powered logic rules
│       └── ...
│   └── reports/             # Scan results (JSON, SARIF)
├── .claude/
│   └── settings.json        # Hooks for auto-loading context
└── src/                     # Your source code
```

---

## 🧩 Architecture

Warden is designed with modular "Frames" and extends easily:

*   **Pipes & Filters:** Sequential execution pipeline.
*   **Priority Groups:** Critical security checks run first (Fail-Fast).
*   **LSP Synergy:** Uses Language Server Protocol for deep code understanding.
*   **Vector Search & Memory:** Semantic search for context-aware fixes and specialized "Project Purpose" memory.

### 🏆 The Hybrid Guardian Identity

Warden stands out by being a **Hybrid Architecture Guardian**. Unlike cloud-only review bots that rely heavily on PR context and SaaS infrastructure, Warden is designed as a **Privacy-First, Local-First** sentinel.

| Feature | ☁️ Traditional Cloud Bot | 🛡️ Warden Core (The Guardian) |
| :--- | :--- | :--- |
| **Execution** | Cloud SaaS Only | **Local + CI/CD + Cloud** |
| **Privacy** | Code leaves your machine | **100% Local Processing** (LLM is optional/configurable) |
| **Context** | Pull Request & Tickets | **Project Purpose & Architecture Graph** |
| **Deep Scan** | Full Sandbox Build | **Dependency Graph & Impact Analysis** |
| **Memory** | Vector DB (SaaS) | **Local Vector DB + Knowledge Graph** |
| **Cost** | Per-Token / User | **Optimized (Qwen Fast Tier + Deterministic Rules First)** |

#### 🔑 Key Differentiators

1.  **Project Purpose Detector (Intent Analysis):**
    Typical cloud bots deduce intent from Jira/Linear tickets. Warden deduces it **directly from your code**. It analyzes your codebase to understand if it's a "Crypto Wallet" or "E-Commerce API" and adjusts its rules accordingly.
## 🔮 Roadmap & Vision

We are transforming Warden from a local tool into a global **Standard of Trust**.

*   Phase 1: Local Trust (MVP) ✅
*   Phase 2: Signed Badges & Verification 🏗️
*   Phase 3: Warden Cloud Registry ☁️
*   Phase 4: Enterprise Compliance 🏢

[See full usage plan in ROADMAP.md](./ROADMAP.md)

2.  **Architectural Frames:**
    We don't just look for bugs. We look for **Architectural Crimes**.
    *   *Did the Domain layer import Infrastructure?*
    *   *Is the code strictly following Clean Architecture?*
    *   *Are we drifting from the established design patterns?*

3.  **Active Memory (The "Brain"):**
    Warden doesn't just scan; it **remembers**.
    *   **Semantic Hashing:** Ignores whitespace/comment changes to avoid re-scanning.
    *   **Knowledge Graph:** Stores "Facts" about your project (e.g., "This project uses `pydantic` v2").
    *   **Vector Search:** (Roadmap) Retrieving similar historical code blocks to guide valid fixes.

#### 🧬 Anatomy of the Guardian

*   **🧠 The Brain (Project Context):** Does not just lint; it *understands* (e.g., "This is a Crypto Wallet, so security is paramount").
*   **👀 The Eyes (DependencyGraph):** Sees the "Butterfly Effect" — how a change in `utils.py` breaks `api.py`.
*   **📚 The Memory (Vector DB):** Recalls historical context and similar code patterns (Active Retrieval capabilities).
*   **⚡ The Reflexes (Semantic Hashing):** Ignores noise (whitespace, comments) to focus purely on meaningful logic.

> **The Philosophy:** Warden is not a "Reviewer" that you wait for; it is a **Guardian** that stands at the gate of your repo, ensuring quality *before* commitment.

---

## 🧭 Core vs Cloud (Open‑Core Model)

We maintain a clear separation of responsibilities between Warden Core (OSS) and Warden Cloud (Commercial).

Feature Matrix (Summary)
- Core (OSS, Apache‑2.0): CLI & pipeline engine, Frames SDK, AST/LSP integration, diff scanning, baseline autopilot,
  local LLM providers (Ollama, Claude Code, Codex), JSON/SARIF reporting, suppression/verification phases.
- Cloud (Commercial): Multi‑repo/org management, SSO/SAML, RBAC, centralized policy and approval workflows, advanced dashboards,
  team‑level suppression rules, audit logs, enterprise integrations, hosted LLM routing/telemetry.

Note: Core will always remain under an OSI‑approved license. Cloud ships as a separate product/repository.

---

## 📄 License

**Warden Core** is open source and licensed under **Apache License 2.0**.

- Full text: see [LICENSE](./LICENSE)
- Summary: Permissive use, modification, and distribution; no warranty.

Note: **Warden Cloud** (enterprise features like SSO/RBAC, centralized policy, multi‑repo management, etc.) is a separate
commercial product and is licensed independently of this repository. Warden Core will remain open source.

---

## 🤝 Contributing & Policies

- Contribution guide: [.github/CONTRIBUTING.md](.github/CONTRIBUTING.md)
- Code of Conduct: [.github/CODE_OF_CONDUCT.md](.github/CODE_OF_CONDUCT.md)
- Security policy: [.github/SECURITY.md](.github/SECURITY.md)
- Governance: [docs/governance/GOVERNANCE.md](docs/governance/GOVERNANCE.md)
- DCO: [docs/contributing/DCO](docs/contributing/DCO)
- Trademark policy: [docs/legal/TRADEMARKS.md](docs/legal/TRADEMARKS.md)
- NOTICE: [docs/legal/NOTICE](docs/legal/NOTICE)
