# Architecture

## Overview

factq is a local-first knowledge base and verification engine. It intercepts LLM queries, resolves them against proven local knowledge, and falls back to executable verification when the knowledge base cannot answer.

## Resolution Pipeline

```
User Query
  │
  ▼
┌─────────────────┐
│  Phase 0: KB    │  Check docs/ folder and indexed knowledge base
│  Lookup         │  Returns in milliseconds if found
└────────┬────────┘
         │ miss
         ▼
┌─────────────────┐
│  Phase 1:       │  LLM generates Python code to retrieve
│  Generate       │  and verify the fact from external sources
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│  Phase 2:       │  Code runs in sandbox. Errors trigger
│  Validate       │  self-correction. Up to 5 iterations.
└────────┬────────┘
         │ verified
         ▼
┌─────────────────┐
│  Phase 3:       │  Verified result offered for commit
│  Commit         │  to docs/. KB grows with every query.
└─────────────────┘
```

## Component Architecture

```
factq/
├── cli.py              # Click CLI entry point
├── core/
│   ├── engine.py       # Query orchestrator (KB → Deepthink → Commit)
│   ├── kb.py           # Knowledge base: indexing, search, persistence
│   └── result.py       # Query result model (answer, source, confidence)
├── deepthink/
│   ├── generator.py    # Code generation for fact verification
│   ├── sandbox.py      # Secure execution environment
│   └── validator.py    # Output validation and retry logic
├── indexer/
│   ├── markdown.py     # Markdown file parser and indexer
│   └── store.py        # Index storage (local SQLite or flat files)
├── mcp/
│   └── server.py       # MCP server for Claude Code, Cursor, Windsurf
└── adapters/
    └── llm.py          # LLM backend abstraction (local, API)
```

## Key Design Decisions

### RLM Over RAG

factq uses the Recursive Language Model paradigm instead of traditional RAG. The LLM writes code to navigate and verify knowledge rather than relying on embedding-based similarity search. This eliminates 3-6 GB of VRAM overhead from embedding models and vector databases.

### Local-First

All data stays on the user's machine. The knowledge base is plain markdown files in `docs/`, version-controlled in git. No cloud dependency, no API keys required for core functionality.

### Sandbox Security

Five-layer defense-in-depth for Deepthink code execution:
1. Safe builtins (restricted Python runtime)
2. AST validation (block dangerous constructs)
3. Function whitelisting (approved stdlib only)
4. Execution timeouts (hard kill after N seconds)
5. Output truncation (prevent memory exhaustion)

### MCP Integration

factq runs as a local MCP server so AI coding tools can call `factq.query()` as a tool. The MCP interface is a thin wrapper around the core engine.

## Data Flow

```
docs/ folder (markdown) ──┐
                          ├──► KB Index ──► Query Engine ──► Result
External sources ─────────┘        ▲                │
                                   │                ▼
                              Deepthink ◄──── Sandbox
                              (generate)      (execute)
```

## Dependencies

| Layer | Dependencies | Rationale |
|-------|-------------|-----------|
| Core | pydantic, pyyaml | Data models, config |
| CLI | click, rich | Terminal interface |
| Deepthink | (stdlib only) | Sandbox uses restricted Python |
| MCP | mcp (optional) | Protocol server |
| LLM | (pluggable) | Adapter pattern for backends |
