Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
docs: add living specification in specify/ directory
JerrettDavis31a05dc26025
diff --git a/.gitignore b/.gitignoreindex be1d70694..6a5cef7aa 100644--- a/.gitignore+++ b/.gitignore@@ -198,7 +198,8 @@ CLAUDE.md.vitals/# Superpowers working files (plans, specs, brainstorming)-docs/superpowers/+# docs/superpowers/ (moved to specify/ for versioning)+# specify/ (NOTE: not ignored - tracked in git)# Managed platform (separate private repo)headroom-managed/diff --git a/specify/001-vision.md b/specify/001-vision.mdnew file mode 100644index 000000000..46860cb04--- /dev/null+++ b/specify/001-vision.md@@ -0,0 +1,109 @@+# 001. Vision++**Status:** done++## What Headroom Is++Headroom is a **context compression proxy** for AI provider APIs. It sits between AI coding tools (Claude Code, Copilot, Codex, etc.) and provider APIs (OpenAI, Anthropic, Google, Cohere), compressing context before it reaches the provider to reduce token usage and costs.++### Core Value Proposition++1. **Token Savings** — 30-90% reduction in tokens sent to providers through semantic compression+2. **Cost Reduction** — Lower API costs via compression before provider transmission+3. **Context Window Extension** — Effective 2-10x larger context windows via compression+4. **Privacy** — Prompts never logged by default; all processing stays local+5. **Compatibility** — Works with existing AI coding tools via proxy or SDK++### What Headroom Is Not++- A model provider — Headroom does not host or run AI models+- A data store — No prompt storage by default (local SQLite is optional)+- A logging service — No prompt logging by default+- A billing service — Usage tracking is internal only++---++## Design Principles++### 1. Local-First Privacy++**Principle:** Prompt data never leaves the proxy unless explicitly exported.++**Implications:**+- All compression happens locally or through the proxy+- No third-party data sharing+- Optional SQLite storage with user control+- Export must be explicitly configured++### 2. Transparent Compression++**Principle:** Users see exactly what is being compressed and why.++**Implications:**+- Full observability into compression decisions+- Metrics and logs show savings+- Transform audit trail available+- Dashboard visualizes all compression activity++### 3. Composable Integration++**Principle:** Headroom works alongside existing tools without requiring workflow changes.++**Implications:**+- Proxy mode: route traffic through Headroom+- SDK mode: integrate into custom applications+- CLI mode: wrap existing AI commands+- Agent mode: MCP/LiteLLM/ASGI integrations++### 4. Production-Ready Defaults++**Principle:** Safe defaults that work out of the box.++**Implications:**+- Compression enabled by default+- No logging by default+- Cache enabled by default+- Learning disabled by default++---++## Core Guarantees++| Guarantee | Description |+|-----------|-------------|+| **Never logs prompts** | No prompt data in logs unless exporter configured |+| **Never leaves proxy** | All data stays local unless explicitly exported |+| **Composable** | Works alongside Claude Code, Copilot, Codex, etc. |+| **Transparent** | Full observability into compression decisions |+| **Type-safe** | Full type annotations, mypy compliance |+| **Test-covered** | Unit, integration, and E2E test coverage |++---++## Target Users++| User | Use Case |+|------|----------|+| **Individual Developers** | Reduce API costs for personal AI coding |+| **Development Teams** | Shared compression with learn plugins |+| **Enterprises** | Self-hosted deployment with security guarantees |+| **Plugin Authors** | Extend Headroom via plugin ABI |++---++## Success Metrics++| Metric | Target | Measurement |+|--------|--------|-------------|+| Token savings | >30% | (tokens_before - tokens_after) / tokens_before |+| Compression latency | <50ms | Per-request proxy overhead |+| Cache hit rate | >60% | cache_hits / total_requests |+| Zero data exfiltration | 100% | No prompts in logs by default |++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial vision document |diff --git a/specify/002-architecture.md b/specify/002-architecture.mdnew file mode 100644index 000000000..742558d1f--- /dev/null+++ b/specify/002-architecture.md@@ -0,0 +1,339 @@+# 002. Architecture++**Status:** done++## System Overview++Headroom is a context compression proxy for LLM applications, featuring intelligent transforms, semantic caching, and CCR (Compress-Cache-Retrieve) architecture.++```+┌─────────────────────────────────────────────────────────────────┐+│ Headroom │+├─────────────────────────────────────────────────────────────────┤+│ │+│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────┐ │+│ │ Proxy │ │ SDK │ │ Wrap │ │ CCR MCP │ │+│ │ Server │ │ (Python) │ │ CLI │ │ Server │ │+│ │ (8787) │ │ │ │ │ │ │ │+│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬──────┘ │+│ │ │ │ │ │+│ ┌────┴──────────────┴──────────────┴─────────────────┴──────┐ │+│ │ Compression Layer │ │+│ │ ┌────────────┐ ┌────────────┐ ┌────────────────────┐ │ │+│ │ │SmartCrusher│ │CacheAligner│ │ RollingWindow │ │ │+│ │ │(JSON array │ │(Prefix │ │ (Token cap) │ │ │+│ │ │ crush) │ │ stabilization)│ │ │ │ │+│ │ └────────────┘ └────────────┘ └────────────────────┘ │ │+│ └───────────────────────────────────────────────────────────┘ │+│ │+│ ┌───────────────────────────────────────────────────────────┐ │+│ │ Learn System │ │+│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────────────┐ │ │+│ │ │Claude │ │Codex │ │Gemini │ │ Generic │ │ │+│ │ │Scanner │ │Scanner │ │Scanner │ │ Writer │ │ │+│ │ └────────┘ └────────┘ └────────┘ └────────────────┘ │ │+│ └───────────────────────────────────────────────────────────┘ │+│ │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │+│ │ Dashboard │ │ CCR │ │ TOIN │ │+│ │ (HTML) │ │ (Compress- │ │ (Telemetry-based │ │+│ │ │ │ Cache- │ │ Intelligence) │ │+│ │ │ │ Retrieve) │ │ │ │+│ └──────────────┘ └──────────────┘ └──────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────┘+```++---++## Component Specifications++### Proxy Server (`headroom/proxy/server.py`)++**`HeadroomProxy` class** — Main proxy server (default port 8787):++```python+class HeadroomProxy:+ def __init__(self, config: ProxyConfig) -> None:+ self.config = config+ self.compression_cache = CompressionCache(...)+ self.transform_pipeline = [...]+ self.ccr_store = CompressionStore(...)+ self.prefix_freeze = PrefixFreeze(...)++ async def startup(self) -> None: ...+ async def shutdown(self) -> None: ...+ async def handle_request(request: Request) -> Response: ...+```++**`ProxyConfig` dataclass** (from `headroom/models/config.py`):+```python+@dataclass+class ProxyConfig:+ store_url: str = "sqlite:///headroom.db"+ default_mode: HeadroomMode = HeadroomMode.AUDIT+ tool_crusher: ToolCrusherConfig = field(default_factory=ToolCrusherConfig)+ smart_crusher: SmartCrusherConfig = field(default_factory=SmartCrusherConfig)+ cache_aligner: CacheAlignerConfig = field(default_factory=CacheAlignerConfig)+ rolling_window: RollingWindowConfig = field(default_factory=RollingWindowConfig)+ cache_optimizer: CacheOptimizerConfig = field(default_factory=CacheOptimizerConfig)+ ccr: CCRConfig = field(default_factory=CCRConfig)+ prefix_freeze: PrefixFreezeConfig = field(default_factory=PrefixFreezeConfig)+```++**`HeadroomMode` enum** (actual modes):+```python+class HeadroomMode(str, Enum):+ AUDIT = "audit" # Observe only, no modifications+ OPTIMIZE = "optimize" # Apply deterministic transforms+ SIMULATE = "simulate" # Return transform plan without API call+```++**HTTP Endpoints (actual):**+| Endpoint | Method | Description |+|----------|--------|-------------|+| `/v1/messages` | POST | Proxy chat completions |+| `/v1/embeddings` | POST | Proxy embeddings |+| `/health` | GET | Basic health check |+| `/livez` | GET | Liveness check |+| `/readyz` | GET | Readiness check |+| `/metrics` | GET | Prometheus metrics |+| `/v1/compress` | POST | Direct compression |+| `/v1/retrieve` | POST | CCR retrieval |+| `/stats` | GET | Compression statistics |++**Default Port:** 8787 (not 8765)++---++### Python SDK (`headroom/client.py`)++**`HeadroomClient` class:**+```python+class HeadroomClient:+ def __init__(+ self,+ api_key: str | None = None,+ base_url: str = "http://localhost:8787",+ timeout: float = 60.0,+ fallback: bool = True,+ retries: int = 3,+ ) -> None:+ pass++ async def compress(+ self,+ messages: list[dict],+ options: CompressOptions | None = None,+ ) -> CompressResult: ...++ async def get_stats(self) -> Stats: ...++ async def close(self) -> None: ...+```++---++### Wrap CLI (`headroom/cli/wrap.py`)++**Commands (all use default port 8787):**+- `claude` — Wrap Claude Code+- `copilot` — Wrap GitHub Copilot+- `codex` — Wrap OpenAI Codex+- `aider` — Wrap Aider+- `cursor` — Wrap Cursor+- `openclaw` — Wrap OpenClaw++```python[email protected]("--port", "-p", default=8787, help="Proxy port")[email protected]("command", nargs=-1, required=True)+def wrap(command: tuple, port: int) -> None:+ """Wrap a command with Headroom proxy."""+ ...+```++---++### CCR MCP Server (`headroom/ccr/mcp_server.py`)++Model Context Protocol server for Claude Desktop integration.++```python+class CCRMcpServer:+ async def compress(messages: list[dict]) -> CompressResult: ...+ async def retrieve(hash: str, query: str) -> RetrieveResult: ...+ async def get_stats() -> Stats: ...+```++**MCP Tools:**+- `headroom_compress` — Compress messages+- `headroom_retrieve` — Retrieve cached content+- `headroom_stats` — Get statistics++---++### ASGI Middleware (`headroom/integrations/asgi.py`)++ASGI-compatible middleware for Python web frameworks.++```python+class HeadroomMiddleware:+ def __init__(+ self,+ app: ASGIApplication,+ headroom_url: str = "http://localhost:8787",+ ) -> None: ...+```++---++### LiteLLM Callback (`headroom/integrations/litellm_callback.py`)++Callback for LiteLLM proxy integration.++```python+class LiteLLMCallback:+ def on_completion(self, completion_response: dict) -> dict: ...+ def on_error(self, error: Exception) -> None: ...+```++---++## Compression Layer (`headroom/transforms/`)++### SmartCrusher (`headroom/transforms/smart_crusher.py`)++Statistical JSON array compression preserving schema.++```python+class SmartCrusher:+ def __init__(self, config: SmartCrusherConfig) -> None: ...+ def crush(self, content: str, context: TransformContext) -> TransformResult: ...+```++### CacheAligner (`headroom/transforms/cache_aligner.py`)++Prefix stabilization for provider cache optimization.++```python+class CacheAligner:+ def __init__(self, config: CacheAlignerConfig) -> None: ...+ def align(self, messages: list[dict]) -> TransformResult: ...+```++### RollingWindow (`headroom/transforms/rolling_window.py`)++Rolling window token cap.++```python+class RollingWindow:+ def __init__(self, config: RollingWindowConfig) -> None: ...+ def apply(self, messages: list[dict]) -> TransformResult: ...+```++### ContentRouter (`headroom/transforms/content_router.py`)++Routes content to appropriate compressor based on type.++```python+class ContentRouter:+ def route(self, messages: list[dict]) -> list[dict]: ...+```++---++## Learn System (`headroom/learn/`)++**`LearnPlugin` interface** (actual):++```python+class LearnPlugin(ConversationScanner):+ @property+ def name(self) -> str: ...+ @property+ def display_name(self) -> str: ...+ @abstractmethod+ def detect(self) -> bool: ...+ @abstractmethod+ def discover_projects(self) -> list[ProjectInfo]: ...+ @abstractmethod+ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]: ...+ @abstractmethod+ def create_writer(self) -> ContextWriter: ...+```++**Scanner implementations:**+- `ClaudeScanner` — Claude Code session parsing+- `CodexScanner` — Codex session parsing+- `CursorScanner` — Cursor session parsing++---++## CCR System (`headroom/ccr/`)++CCR (Compress-Cache-Retrieve) makes compression reversible.++```python+class CompressionStore:+ def store(self, hash: str, original: str, metadata: dict) -> None: ...+ def retrieve(self, hash: str) -> str | None: ...++class ContextTracker:+ def track(self, session_id: str, messages: list[dict]) -> CCRContext: ...+ def get_context(self, session_id: str) -> CCRContext | None: ...+```++**CCRConfig fields:**+- `enabled: bool = True`+- `store_max_entries: int = 1000`+- `store_ttl_seconds: int = 300`+- `inject_retrieval_marker: bool = True`+- `feedback_enabled: bool = True`++---++## TOIN (`headroom/telemetry/toin.py`)++Tool Output Intelligence Network — telemetry-based compression hints.++```python+class TOINCollector:+ def record_retrieval(self, tool_name: str, field: str, query: str) -> None: ...+ def get_hints(self, tool_name: str) -> dict[str, float]: ...+```++---++## Dashboard (`headroom/dashboard/`)++Simple HTML dashboard served by the proxy.++```python+def get_dashboard_html() -> str:+ """Load the dashboard HTML template."""+ return (TEMPLATES_DIR / "dashboard.html").read_text()+```++---++## Data Flow++```+Client → Headroom Proxy → [ContentRouter] → [SmartCrusher/CacheAligner/RollingWindow]+ │ │ │+ │ [CCR Store] ←───────────────────────┘+ │+ │ [Telemetry/Metrics]+ │+ ▼+ Provider API+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial architecture document |diff --git a/specify/003-adrs.md b/specify/003-adrs.mdnew file mode 100644index 000000000..d18b0a30c--- /dev/null+++ b/specify/003-adrs.md@@ -0,0 +1,164 @@+# 003. Architecture Decision Records++**Status:** done++## ADR-001: Why a Proxy Instead of SDK Injection++**Context:** Headroom could be implemented as an SDK that users import, or as a network proxy.++**Decision:** Network proxy with SDK for complex use cases.++**Rationale:**+- Works with any HTTP client without code changes+- No need to modify existing applications+- Centralized configuration+- Can intercept all traffic, not just explicit SDK calls++**Consequences:**+- Requires running a separate service (or using wrap mode)+- Network latency added (~5-10ms)+- Need to handle connection pooling++---++## ADR-002: Why SQLite for Local Storage++**Context:** Headroom needs to store compression cache, savings history, memory graphs.++**Decision:** SQLite with optional external stores (Redis, PostgreSQL, etc.).++**Rationale:**+- Zero configuration — works out of the box+- Single file, easy backup+- ACID compliant transactions+- Good performance for single-node deployments+- sqlite-vec for vector similarity search+- FTS5 for full-text search++**Consequences:**+- Not distributed by default+- Must configure external stores for multi-node deployments+- Cloud-hosted databases require additional setup++---++## ADR-003: Why CCR (Compress-Cache-Retrieve) Pattern++**Context:** Compression alone doesn't leverage repeated context patterns.++**Decision:** CCR pattern for semantic caching and retrieval.++**Rationale:**+- Semantic similarity enables cache hits across different phrasings+- Retrieves relevant compressed context for new requests+- Reduces provider API calls for similar patterns+- Enables cross-session learning++**Consequences:**+- Requires storing compressed content+- Semantic hashing adds latency+- Cache invalidation is complex++---++## ADR-004: Why Per-Agent Plugins for Learn System++**Context:** Different AI agents (Claude, Codex, Gemini) have different context patterns.++**Decision:** Plugin architecture with agent-specific analyzers.++**Rationale:**+- Tailored compression per agent type+- Extensible for new agents+- Clear interface contract+- Independent versioning++**Consequences:**+- Plugin API must be stable+- Multiple plugins may conflict+- Testing complexity increases++---++## ADR-005: Why ONNX for TOIN++**Context:** TOIN (Tenant-specific ONNX) requires ML inference.++**Decision:** Use ONNX Runtime for portable ML inference.++**Rationale:**+- Hardware acceleration (CPU/GPU)+- Cross-platform (Windows, Linux, macOS)+- Model interchange format+- Single model file deployment++**Consequences:**+- ONNX model files must be hosted+- Version compatibility issues+- Larger package size++---++## ADR-006: Why Python for Core Implementation++**Context:** Language choice for the main implementation.++**Decision:** Python as the primary language.++**Rationale:**+- Primary language for AI/ML ecosystem+- Easy integration with provider APIs+- Rich async ecosystem (asyncio, httpx)+- Strong type annotation support (mypy)+- Good testing infrastructure++**Consequences:**+- GIL limitations for threading+- Slower than compiled languages+- Type checking adds build time++---++## ADR-007: Why TypeScript SDK for npm++**Context:** JavaScript/TypeScript ecosystem for frontend integrations.++**Decision:** Official TypeScript SDK published to npm.++**Rationale:**+- Node.js compatibility+- TypeScript type safety+- Wide adoption in AI tooling+- ESM and CommonJS support++**Consequences:**+- Dual language maintenance+- Must keep SDK in sync with Python core+- Additional CI/CD pipeline needed++---++## ADR-008: Why HierarchicalMemory with SQLite + vec + FTS5++**Context:** Memory system needs to store, search, and reason over context.++**Decision:** Hierarchical memory using SQLite + sqlite-vec + FTS5.++**Rationale:**+- SQLite: ACID transactions, single file+- sqlite-vec: Vector similarity for semantic search+- FTS5: Full-text search for keyword matching+- Hierarchical: Session < Conversation < Message structure++**Consequences:**+- Memory hierarchy adds complexity+- SQLite limitations for concurrent writes+- Vector search accuracy depends on embedding quality++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial ADRs |diff --git a/specify/004-domain-model.md b/specify/004-domain-model.mdnew file mode 100644index 000000000..450ba15cb--- /dev/null+++ b/specify/004-domain-model.md@@ -0,0 +1,363 @@+# 004. Domain Model++**Status:** done++## Core Entities++### Session++A session represents a conversation context between a user and an AI agent.++**Fields:**+- `session_id: UUID` — Unique identifier+- `created_at: datetime` — Creation time+- `updated_at: datetime` — Last modification+- `agent_type: str` — "claude", "codex", "gemini", etc.+- `messages: list[Message]` — Conversation history+- `metadata: dict` — Agent-specific metadata++```python+@dataclass+class Session:+ session_id: UUID+ created_at: datetime+ updated_at: datetime+ agent_type: str+ messages: list[Message] = field(default_factory=list)+ metadata: dict = field(default_factory=dict)+```++---++### Message++A single message in a conversation.++**Fields:**+- `message_id: UUID` — Unique identifier+- `session_id: UUID` — Associated session+- `role: str` — "user", "assistant", "system", "tool"+- `content: str` — Message content+- `tokens: int | None` — Token count (if known)+- `created_at: datetime` — Creation time+- `attachments: list[Attachment] | None` — Optional attachments++```python+@dataclass+class Message:+ message_id: UUID+ session_id: UUID+ role: str+ content: str+ tokens: int | None = None+ created_at: datetime = field(default_factory=datetime.utcnow)+ attachments: list[Attachment] | None = None+```++---++### Request++A single API request to an AI provider.++**Fields:**+- `request_id: UUID` — Unique identifier+- `session_id: UUID` — Associated session+- `provider: str` — "anthropic", "openai", "google", etc.+- `model: str` — Model identifier+- `input_tokens: int` — Tokens in request+- `output_tokens: int` — Tokens in response+- `compressed: bool` — Whether compression was applied+- `savings_percentage: float` — Savings as decimal+- `timestamp: datetime` — Request time+- `duration_ms: int` — Request duration+- `error: str | None` — Error message if failed++```python+@dataclass+class Request:+ request_id: UUID+ session_id: UUID+ provider: str+ model: str+ input_tokens: int+ output_tokens: int+ compressed: bool = False+ savings_percentage: float = 0.0+ timestamp: datetime = field(default_factory=datetime.utcnow)+ duration_ms: int = 0+ error: str | None = None+```++---++### Savings++A record of token savings from a compressed request.++**Fields:**+- `savings_id: UUID` — Unique identifier+- `request_id: UUID` — Associated request+- `original_tokens: int` — Tokens before compression+- `compressed_tokens: int` — Tokens after compression+- `savings_percentage: float` — Savings as decimal+- `savings_amount: float` — Absolute token savings+- `provider: str` — Provider name+- `model: str` — Model used+- `window_start: datetime | None` — Billing window start++```python+@dataclass+class Savings:+ savings_id: UUID+ request_id: UUID+ original_tokens: int+ compressed_tokens: int+ savings_percentage: float+ savings_amount: float+ provider: str+ model: str+ window_start: datetime | None = None+```++---++### CacheEntry++A cached compression result.++**Fields:**+- `cache_key: str` — Hash of input+- `input_hash: str` — Hash of original content+- `output: str` — Compressed output+- `compression_type: str` — "semantic", "summary", "ccr"+- `tokens_before: int` — Tokens before compression+- `tokens_after: int` — Tokens after compression+- `created_at: datetime` — Creation time+- `ttl: int` — Time to live in seconds+- `hit_count: int` — Number of cache hits+- `last_accessed: datetime` — Last access time++```python+@dataclass+class CacheEntry:+ cache_key: str+ input_hash: str+ output: str+ compression_type: str+ tokens_before: int+ tokens_after: int+ created_at: datetime = field(default_factory=datetime.utcnow)+ ttl: int = 3600+ hit_count: int = 0+ last_accessed: datetime = field(default_factory=datetime.utcnow)+```++---++### ToolDefinition++A tool/function definition available to an AI agent.++**Fields:**+- `tool_id: UUID` — Unique identifier+- `name: str` — Tool name+- `description: str` — Tool description+- `parameters: dict` — JSON Schema for parameters+- `provider: str` — Provider that defined this tool+- `created_at: datetime` — Creation time++```python+@dataclass+class ToolDefinition:+ tool_id: UUID+ name: str+ description: str+ parameters: dict+ provider: str+ created_at: datetime = field(default_factory=datetime.utcnow)+```++---++### PluginInterface++A learn plugin for agent-specific compression.++**Fields:**+- `plugin_id: UUID` — Unique identifier+- `name: str` — Plugin name+- `agent_type: str` — Supported agent type+- `version: str` — Plugin version+- `entry_point: str` — Import path or file path+- `config: dict` — Plugin configuration+- `enabled: bool` — Whether plugin is active++```python+@dataclass+class PluginInterface:+ plugin_id: UUID+ name: str+ agent_type: str+ version: str+ entry_point: str+ config: dict = field(default_factory=dict)+ enabled: bool = True+```++---++### TOINTenant++A tenant configuration for TOIN (Tenant-specific ONNX).++**Fields:**+- `tenant_id: UUID` — Unique identifier+- `name: str` — Tenant name+- `model_path: str | Path` — Path to ONNX model+- `model_version: str` — Model version+- `config: dict` — Tenant-specific configuration+- `created_at: datetime` — Creation time+- `updated_at: datetime` — Last modification++```python+@dataclass+class TOINTenant:+ tenant_id: UUID+ name: str+ model_path: str | Path+ model_version: str+ config: dict = field(default_factory=dict)+ created_at: datetime = field(default_factory=datetime.utcnow)+ updated_at: datetime = field(default_factory=datetime.utcnow)+```++---++### CCRContext++Claude Code Relay context tracking.++**Fields:**+- `context_id: UUID` — Unique identifier+- `session_id: UUID` — Associated session+- `agent_type: str` — "claude", "claude-desktop", etc.+- `window_start: datetime` — Context window start+- `window_end: datetime` — Context window end+- `messages_tracked: int` — Number of messages+- `compressed_content: str | None` — Compressed context++```python+@dataclass+class CCRContext:+ context_id: UUID+ session_id: UUID+ agent_type: str+ window_start: datetime+ window_end: datetime+ messages_tracked: int = 0+ compressed_content: str | None = None+```++---++### SubscriptionState++Subscription/quota tracking state.++**Fields:**+- `subscription_id: UUID` — Unique identifier+- `provider: str` — Provider name+- `plan_name: str` — Plan name+- `window_start: datetime` — Billing window start+- `window_end: datetime` — Billing window end+- `max_tokens: int | None` — Maximum tokens in window+- `tokens_used: int` — Tokens used in window+- `tokens_remaining: int | None` — Tokens remaining+- `is_active: bool` — Whether subscription is active+- `last_updated: datetime` — Last update time++```python+@dataclass+class SubscriptionState:+ subscription_id: UUID+ provider: str+ plan_name: str+ window_start: datetime+ window_end: datetime+ max_tokens: int | None = None+ tokens_used: int = 0+ tokens_remaining: int | None = None+ is_active: bool = True+ last_updated: datetime = field(default_factory=datetime.utcnow)+```++---++## Relationships++```+Session 1───N Message+Session 1───N Request+Request 1───1 Savings+Request 1───1 CacheEntry+Session 1───N CCRContext+TOINTenant 1───N Request+ToolDefinition N───N Session (via tool_use)+```++---++## Value Objects++### CompressResult++```python+@dataclass+class CompressResult:+ messages: list[dict]+ tokens_before: int+ tokens_after: int+ tokens_saved: int+ compression_ratio: float+ transforms_applied: list[str]+ content_type: ContentType+ model: str | None+ ccr_hash: str | None+ cached: bool+```++### ContentType (Enum)++```python+class ContentType(Enum):+ PLAINTEXT = "text/plain"+ MARKDOWN = "text/markdown"+ JSON = "application/json"+ HTML = "text/html"+ XML = "text/xml"+ PYTHON = "text/x-python"+ JAVASCRIPT = "text/javascript"+ TYPESCRIPT = "text/typescript"+ YAML = "text/yaml"+ MARKDOWN_SNAPSHOT = "text/markdown-snapshot"+ UNKNOWN = "application/octet-stream"+```++### ProxyMode (Enum)++```python+class ProxyMode(Enum):+ PASSTHROUGH = "passthrough"+ COMPRESS = "compress"+ LEARN = "learn"+ DETACHED = "detached"+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial domain model |diff --git a/specify/005-integrations.md b/specify/005-integrations.mdnew file mode 100644index 000000000..7fe9e2bb2--- /dev/null+++ b/specify/005-integrations.md@@ -0,0 +1,359 @@+# 005. Integrations++**Status:** done++## Supported Agents++### Claude (`headroom/learn/plugins/claude/`)++**Plugin:** `ClaudeLearnPlugin`++**Capabilities:**+- Session branch comparison+- Token headroom mode detection+- Tool use tracking+- Multi-modal support (images)++**Interface:**+```python+class ClaudeLearnPlugin(LearnPlugin, ConversationScanner):+ @property+ def name(self) -> str:+ return "claude"++ @property+ def display_name(self) -> str:+ return "Claude Code"++ def detect(self) -> bool:+ """Check if Claude Code has data on the current machine."""+ pass++ def discover_projects(self) -> list[ProjectInfo]:+ """Discover all projects with Claude sessions."""+ pass++ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]:+ """Scan all sessions for a project."""+ pass++ def create_writer(self) -> ContextWriter:+ """Return Claude-specific ContextWriter."""+ pass+```++**Configuration:**+```bash+HEADROOM_LEARN_CLAUDE_ENABLED=true+HEADROOM_LEARN_CLAUDE_SESSION_MODES=auto,learn,disabled+```++---++### Codex (OpenAI) (`headroom/learn/plugins/codex/`)++**Plugin:** `CodexLearnPlugin`++**Capabilities:**+- Rate limit handling+- Code completion optimization+- Batch request support++**Interface:**+```python+class CodexLearnPlugin(LearnPlugin, ConversationScanner):+ @property+ def name(self) -> str:+ return "codex"++ @property+ def display_name(self) -> str:+ return "OpenAI Codex"++ def detect(self) -> bool:+ pass++ def discover_projects(self) -> list[ProjectInfo]:+ pass++ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]:+ pass++ def create_writer(self) -> ContextWriter:+ pass+```++**Configuration:**+```bash+HEADROOM_LEARN_CODEX_ENABLED=true+```++---++### Gemini (Google) (`headroom/learn/plugins/gemini/`)++**Plugin:** `GeminiLearnPlugin`++**Capabilities:**+- Multimodal inputs+- Function calling support+- Context caching API++**Interface:**+```python+class GeminiLearnPlugin(LearnPlugin, ConversationScanner):+ @property+ def name(self) -> str:+ return "gemini"++ @property+ def display_name(self) -> str:+ return "Google Gemini"++ def detect(self) -> bool:+ pass++ def discover_projects(self) -> list[ProjectInfo]:+ pass++ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]:+ pass++ def create_writer(self) -> ContextWriter:+ pass+```++**Configuration:**+```bash+HEADROOM_LEARN_GEMINI_ENABLED=true+```++---++## Integration Points++### LiteLLM Callback (`headroom/integrations/litellm_callback.py`)++LiteLLM proxy callback for integrating with LiteLLM-based setups.++**`LiteLLMCallback` class:**+```python+class LiteLLMCallback:+ def __init__(+ self,+ headroom_url: str = "http://localhost:8787",+ api_key: str | None = None,+ ) -> None:+ self.headroom_url = headroom_url+ self.api_key = api_key++ def on_completion(self, completion_response: dict) -> dict:+ """Called after completion. Can modify response."""+ pass++ def on_error(self, error: Exception) -> None:+ """Called on error."""+ pass+```++**Usage:**+```python+from headroom.integrations import LiteLLMCallback++callback = LiteLLMCallback(headroom_url="http://localhost:8787")+# Register with LiteLLM proxy+```++---++### ASGI Middleware (`headroom/integrations/asgi.py`)++ASGI-compatible middleware for Python web frameworks (FastAPI, Starlette, etc.).++**`HeadroomMiddleware` class:**+```python+class HeadroomMiddleware:+ def __init__(+ self,+ app: ASGIApplication,+ headroom_url: str = "http://localhost:8787",+ mode: ProxyMode = ProxyMode.COMPRESS,+ ) -> None:+ self.app = app+ self.headroom_url = headroom_url+ self.mode = mode++ async def __call__(+ self,+ scope: Scope,+ receive: Receive,+ send: Send,+ ) -> None:+ """ASGI application interface."""+ pass+```++**Usage:**+```python+from headroom.integrations import HeadroomMiddleware+from fastapi import FastAPI++app = FastAPI()+app.add_middleware(+ HeadroomMiddleware,+ headroom_url="http://localhost:8787",+ mode=ProxyMode.COMPRESS,+)+```++---++### MCP Server (`headroom/integrations/mcp/server.py`)++Model Context Protocol server for Claude Desktop integration.++**`HeadroomMCPCompressor` class:**+```python+class HeadroomMCPCompressor:+ def __init__(+ self,+ headroom_url: str = "http://localhost:8787",+ api_key: str | None = None,+ ) -> None:+ self.headroom_url = headroom_url+ self.api_key = api_key++ async def compress(self, messages: list[dict]) -> CompressResult:+ """MCP tool: compress"""+ pass++ async def get_savings(self) -> SavingsStats:+ """MCP tool: get_savings"""+ pass++ async def get_stats(self) -> Stats:+ """MCP tool: get_stats"""+ pass+```++**MCP Tools:**+- `compress` — Compress messages+- `get_savings` — Get savings statistics+- `get_stats` — Get compression statistics++**MCP Resources:**+- `session://headroom/sessions` — List of sessions+- `savings://headroom/history` — Savings history++**Configuration:**+```bash+headroom mcp --port 8766+```++---++### Strands (`headroom/integrations/strands/`)++Strands framework integration.++**Usage:**+```python+from headroom.integrations.strands import HeadroomStrandsPlugin++plugin = HeadroomStrandsPlugin()+```++---++### LangChain (`headroom/integrations/langchain/`)++LangChain callback handler integration.++**`HeadroomLangChainCallback` class:**+```python+class HeadroomLangChainCallback(BaseCallbackHandler):+ def __init__(+ self,+ headroom_url: str = "http://localhost:8787",+ api_key: str | None = None,+ ) -> None:+ self.headroom_url = headroom_url+ self.api_key = api_key++ async def on_llm_start(self, serialized, prompts, **kwargs) -> None:+ pass++ async def on_llm_end(self, response, **kwargs) -> None:+ pass+```++**Usage:**+```python+from langchain.callbacks import HeadroomLangChainCallback++callback = HeadroomLangChainCallback()+# Pass to LangChain chain+```++---++## Agent Contract++All learn plugins must implement the `LearnPlugin` interface:++```python+from abc import ABC, abstractmethod+from headroom.learn.base import ConversationScanner, ContextWriter+from headroom.learn.models import ProjectInfo, SessionData++class LearnPlugin(ConversationScanner):+ """A self-contained learn plugin for a single coding agent."""++ @property+ @abstractmethod+ def name(self) -> str:+ """Short lowercase identifier (e.g., 'claude', 'cursor')."""+ ...++ @property+ @abstractmethod+ def display_name(self) -> str:+ """Human-readable name (e.g., 'Claude Code', 'Cursor')."""+ ...++ @abstractmethod+ def detect(self) -> bool:+ """Return True if this agent has data on the current machine."""+ ...++ @abstractmethod+ def discover_projects(self) -> list[ProjectInfo]:+ """Discover all projects with conversation data."""+ ...++ @abstractmethod+ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]:+ """Scan all sessions for a project."""+ ...++ @abstractmethod+ def create_writer(self) -> ContextWriter:+ """Return the appropriate ContextWriter for this agent."""+ ...+```++**Plugin Registration:**+```python+# Module-level instance for auto-discovery+plugin = MyAgentPlugin()+```++Plugins are auto-discovered from `headroom.learn.plugins.*` or via `headroom.learn_plugin` entry points.++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial integrations document |diff --git a/specify/006-actors.md b/specify/006-actors.mdnew file mode 100644index 000000000..1b0d6c421--- /dev/null+++ b/specify/006-actors.md@@ -0,0 +1,232 @@+# 006. Actors++**Status:** done++## Actor Types++### End User++The developer using an AI coding agent with Headroom.++**Interactions:**+- Configures Headroom via environment variables or config file+- Uses wrapped CLI commands or SDK+- Views savings in dashboard+- Optionally enables learn mode++**Needs:**+- Transparent compression (doesn't break workflows)+- Clear savings metrics+- Easy opt-out of specific features++**Configuration:**+```bash+# Minimal setup+export ANTHROPIC_API_KEY=sk-...++# Optional overrides+export HEADROOM_MODE=compress+export HEADROOM_CACHE_ENABLED=true+```++---++### Operator++The person deploying and managing Headroom in production.++**Interactions:**+- Deploys Headroom (Docker, native, or embedded)+- Configures profiles and presets+- Monitors health endpoints+- Reviews metrics and logs+- Manages upgrades++**Needs:**+- Clear deployment documentation+- Health and readiness checks+- Metrics for capacity planning+- Upgrade and rollback procedures++**Configuration:**+```yaml+# ~/.headroom/config.yaml+proxy:+ host: 0.0.0.0+ port: 8787++compression:+ enabled: true+ cache:+ enabled: true+ ttl: 3600++telemetry:+ metrics:+ enabled: true+```++**Health Endpoints:**+```bash+curl http://localhost:8787/health+curl http://localhost:8787/livez+curl http://localhost:8787/readyz+curl http://localhost:8787/metrics+```++---++### Plugin Author++The developer creating a custom learn plugin for a specific agent.++**Interactions:**+- Implements `LearnPlugin` interface+- Plugins auto-discovered from `headroom/learn/plugins/` directory+- Contributes to Headroom++**Needs:**+- Clear plugin interface documentation+- Example plugins to reference+- Test utilities++**Plugin Template:**+```python+from headroom.learn.base import LearnPlugin, ConversationScanner++class MyAgentPlugin(LearnPlugin):+ @property+ def name(self) -> str:+ return "my_agent"++ @property+ def display_name(self) -> str:+ return "My Agent"++ def detect(self) -> bool:+ # Check if this agent has data on the current machine+ pass++ def discover_projects(self) -> list[ProjectInfo]:+ # Discover all projects with conversation data+ pass++ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]:+ # Scan all sessions for a project+ pass++ def create_writer(self) -> ContextWriter:+ # Return the appropriate ContextWriter for this agent+ pass+```++---++### Enterprise Evaluator++The person assessing Headroom for organizational adoption.++**Interactions:**+- Reviews security documentation+- Assesses compliance guarantees+- Evaluates operational characteristics++**Needs:**+- Clear data handling guarantees+- Security and privacy documentation+- Compliance certifications (if any)+- SOC2/GDPR considerations++**Security Configuration:**+```bash+# Maximum privacy settings+HEADROOM_CACHE_ENABLED=false+HEADROOM_TELEMETRY_ENABLED=false+HEADROOM_LEARN_ENABLED=false+HEADROOM_DASHBOARD_ENABLED=false+```++---++## Interaction Patterns++### User → Headroom++```+┌──────────────┐ ┌────────────────┐ ┌─────────────┐+│ User's AI │──────▶│ Headroom │──────▶│ Provider │+│ Agent │ │ Proxy │ │ API │+└──────────────┘ └───────┬────────┘ └─────────────┘+ │+ ▼+ ┌──────────────┐+ │ Dashboard │+ │ (optional) │+ └──────────────┘+```++**Flow:**+1. User's AI agent sends request to Headroom proxy+2. Headroom compresses context+3. Compressed request sent to provider API+4. Response returned to agent+5. Optional: savings logged to dashboard++---++### Operator → Headroom++```+┌──────────┐ ┌────────────────┐ ┌─────────────┐+│ Operator │──────▶│ Health │──────▶│ Metrics │+│ │ │ Endpoints │ │ Server │+└──────────┘ └────────────────┘ └─────────────┘+ │+ ▼+┌────────────────┐+│ Logs │+│ (stdout/file) │+└────────────────┘+```++**Flow:**+1. Operator checks health endpoints+2. Reviews Prometheus metrics+3. Monitors logs for errors+4. Manages configuration++---++### Plugin Author → Headroom++```+┌──────────────┐ ┌────────────────┐ ┌─────────────┐+│ Plugin │──────▶│ Plugin │──────▶│ Registry │+│ Author │ │ Interface │ │ + Tests │+└──────────────┘ └────────────────┘ └─────────────┘+```++**Flow:**+1. Plugin author implements LearnPlugin+2. Plugins are auto-discovered from `headroom/learn/plugins/` directory+3. Writes unit tests+4. Submits contribution++---++## Permissions Model++| Actor | Config | Read Metrics | Admin | Plugin |+|-------|--------|--------------|-------|--------|+| End User | ✓ (own) | ✓ (own) | - | - |+| Operator | ✓ (full) | ✓ (all) | ✓ | - |+| Plugin Author | - | - | - | ✓ (write) |+| Enterprise Evaluator | - | ✓ (security) | - | - |++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial actors document |diff --git a/specify/007-behavior.md b/specify/007-behavior.mdnew file mode 100644index 000000000..f6df2ee6e--- /dev/null+++ b/specify/007-behavior.md@@ -0,0 +1,179 @@+# 007. Behavior++**Status:** done++## Proxy Modes++### Passthrough Mode++Headroom forwards requests without modification.++**Behavior:**+- All requests pass through unchanged+- Response headers may be modified for telemetry+- No compression applied+- Useful for testing or debugging++**Configuration:** `HEADROOM_MODE=audit`++**Request Flow:**+```+Client → Proxy → Provider API → Response+```++---++### Optimize Mode++Headroom applies deterministic transforms to requests.++**Behavior:**+- SmartCrusher compresses JSON tool outputs+- CacheAligner stabilizes prefixes+- RollingWindow caps context tokens+- CCR caching enabled+- Token budget enforced++**Configuration:** `HEADROOM_MODE=optimize`++**Request Flow:**+```+Client → Proxy → [SmartCrusher] → [CacheAligner]+ → [RollingWindow] → [CCR Cache]+ → Provider API → Response+```++---++### Simulate Mode++Headroom returns transform plan without API call.++**Behavior:**+- Analyzes content for compression opportunity+- Returns TransformResult with planned transforms+- No actual compression or provider call+- Useful for debugging/optimization++**Configuration:** `HEADROOM_MODE=simulate`++---++## Session Modes++Session modes control how Headroom handles context windows.++| Mode | Description | Use Case |+|------|-------------|----------|+| `audit` | Observe only, no modifications | Monitoring |+| `optimize` | Apply deterministic transforms | Production |+| `simulate` | Return plan without API call | Debugging |++---++## Request Lifecycle++```+1. Request received at proxy endpoint+ │+ ▼+2. Session lookup/creation+ │ - Extract session ID from headers+ │ - Create new session if not found+ │+ ▼+3. Mode determination+ │ - Check HEADROOM_MODE+ │ - Check runtime headers+ │ - Determine active plugins+ │+ ▼+4. Compression pipeline execution+ │ a. Token counting+ │ b. Semantic cache check+ │ c. Content type detection+ │ d. Transform selection+ │ e. Summary compression (if eligible)+ │ f. Token budget enforcement+ │+ ▼+5. Forward to provider API+ │ - Route to correct provider+ │ - Apply API key from config+ │ - Handle timeouts+ │+ ▼+6. Response capture+ │ - Log request/response metadata+ │ - Calculate savings+ │+ ▼+7. Savings calculation+ │ - tokens_before - tokens_after+ │ - percentage = savings / tokens_before+ │+ ▼+8. Telemetry emission+ │ - Prometheus metrics+ │ - Optional tracing+ │+ ▼+9. Response returned to client+ - X-Headroom-Savings header+ - X-Headroom-Original-Tokens header+ - X-Headroom-Compressed-Tokens header+```++---++## Error Handling++| Error Type | HTTP Code | Behavior |+|------------|----------|----------|+| Provider timeout | 504 | Retry up to 3 times with exponential backoff |+| Invalid request | 400 | Return error details in body |+| Compression failure | 500 | Fall back to passthrough mode |+| Provider error | Provider code | Return provider error to client |+| Internal error | 500 | Return 500, log details |+| Rate limited | 429 | Return retry-after header |++**Retry Configuration:**+```python+@dataclass+class RetryConfig:+ max_retries: int = 3+ base_delay: float = 1.0+ max_delay: float = 60.0+ exponential_base: float = 2.0+```++---++## Response Headers++Headroom adds headers to all compressed responses:++```+X-Headroom-Savings: 0.35+X-Headroom-Original-Tokens: 8192+X-Headroom-Compressed-Tokens: 5325+X-Headroom-Compression-Type: semantic,summary+X-Headroom-Request-Id: abc123+X-Headroom-Cache-Hit: false+```++**Header Descriptions:**+- `X-Headroom-Savings` — Token savings percentage (0.35 = 35%)+- `X-Headroom-Original-Tokens` — Token count before compression+- `X-Headroom-Compressed-Tokens` — Token count after compression+- `X-Headroom-Compression-Type` — Types of compression applied+- `X-Headroom-Request-Id` — Unique request identifier+- `X-Headroom-Cache-Hit` — Whether result was from cache++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial behavior document |diff --git a/specify/008-capabilities.md b/specify/008-capabilities.mdnew file mode 100644index 000000000..a5fa25f35--- /dev/null+++ b/specify/008-capabilities.md@@ -0,0 +1,256 @@+# 008. Capabilities++**Status:** done++## Feature Matrix++| Capability | Proxy | SDK | Wrap | MCP | ASGI | LiteLLM |+|------------|:-----:|:---:|:----:|:---:|:----:|:-------:|+| Semantic compression | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| Summary compression | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| Token budget management | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| Learn mode | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| Session tracking | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| CCR feedback | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| TOIN tagging | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| Savings tracking | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |+| Dashboard | ✓ | - | ✓ | - | - | - |+| Health endpoints | ✓ | - | - | - | - | - |+| Metrics (Prometheus) | ✓ | - | - | - | - | - |++---++## Compression Capabilities++### Semantic Cache++**Description:** Caches semantically similar requests using CCR pattern.++**Configuration:**+```bash+HEADROOM_CACHE_ENABLED=true+HEADROOM_CACHE_TTL=3600+HEADROOM_CACHE_MAX_SIZE=10000+```++**Behavior:**+1. Hash input content+2. Check cache for similar entries (configurable threshold)+3. Return cached response if match found (CCR retrieval)+4. Update cache on miss+5. Store compressed content for future retrieval++**CCR Configuration:**+```python+@dataclass+class CCRConfig:+ enabled: bool = True+ storage: ContentStorage | None = None+ cache_ttl: int = 3600+ similarity_threshold: float = 0.85+ max_results: int = 10+```++---++### Summary Compression++**Description:** Compresses long context using summarization.++**Configuration:**+```bash+HEADROOM_SUMMARY_ENABLED=true+HEADROOM_SUMMARY_THRESHOLD=5000 # tokens+HEADROOM_SUMMARY_RATIO=0.3 # compress to 30%+```++**Behavior:**+1. Count input tokens+2. If over threshold, apply summary compression+3. Preserve key information (configurable priority)+4. Track summary statistics++**Summary Pipeline:**+```python+class SummaryCompressor:+ def __init__(+ self,+ threshold: int = 5000,+ target_ratio: float = 0.3,+ priority_preservation: bool = True,+ ) -> None:+ pass++ def compress(+ self,+ content: str,+ context: TransformContext,+ ) -> TransformResult:+ pass+```++---++### Token Budget Manager++**Description:** Enforces token budget limits per session via RollingWindow.++**Configuration:**+```python+@dataclass+class RollingWindowConfig:+ enabled: bool = True+ keep_system: bool = True # Never drop system prompt+ keep_last_turns: int = 2 # Never drop last N turns+ output_buffer_tokens: int = 4000 # Reserve for output+```++**Behavior:**+1. Track token usage per session+2. Enforce budget limits via rolling window+3. Preserve system prompt and last N turns+4. Reserve output buffer tokens++---++## Intelligent Context Management++**Description:** Semantic-aware context management with TOIN integration.++```python+@dataclass+class IntelligentContextConfig:+ enabled: bool = True+ use_importance_scoring: bool = True+ scoring_weights: ScoringWeights = field(default_factory=ScoringWeights)+ toin_integration: bool = True+ toin_confidence_threshold: float = 0.3+```++**Scoring Weights:**+```python+@dataclass+class ScoringWeights:+ recency: float = 0.20+ semantic_similarity: float = 0.20+ toin_importance: float = 0.25+ error_indicator: float = 0.15+ forward_reference: float = 0.15+ token_density: float = 0.05+```++---++## CCR Configuration++**Description:** Compress-Cache-Retrieve makes compression reversible.++```python+@dataclass+class CCRConfig:+ enabled: bool = True+ store_max_entries: int = 1000+ store_ttl_seconds: int = 300+ inject_retrieval_marker: bool = True+ feedback_enabled: bool = True+ min_items_to_cache: int = 20+ inject_tool: bool = True+ inject_system_instructions: bool = False+```++---++## SmartCrusher (Statistical JSON Compression)++**Description:** Preserves JSON schema while reducing array size via statistical analysis.++```python+@dataclass+class SmartCrusherConfig:+ enabled: bool = True+ min_items_to_analyze: int = 5+ min_tokens_to_crush: int = 200+ variance_threshold: float = 2.0+ uniqueness_threshold: float = 0.1+ similarity_threshold: float = 0.8+ max_items_after_crush: int = 15+ preserve_change_points: bool = True+ use_feedback_hints: bool = True+ toin_confidence_threshold: float = 0.3+ relevance: RelevanceScorerConfig = field(default_factory=RelevanceScorerConfig)+ anchor: AnchorConfig = field(default_factory=AnchorConfig)+ dedup_identical_items: bool = True+ first_fraction: float = 0.3+ last_fraction: float = 0.15+```++**Relevance Scoring:**+```python+@dataclass+class RelevanceScorerConfig:+ tier: Literal["bm25", "embedding", "hybrid"] = "hybrid"+ bm25_k1: float = 1.5+ bm25_b: float = 0.75+ embedding_model: str = field(default_factory=lambda: ML_MODEL_DEFAULTS.sentence_transformer)+ hybrid_alpha: float = 0.5+ adaptive_alpha: bool = True+ relevance_threshold: float = 0.25+```++**Anchor Allocation:**+```python+@dataclass+class AnchorConfig:+ anchor_budget_pct: float = 0.25+ min_anchor_slots: int = 3+ max_anchor_slots: int = 12+ default_front_weight: float = 0.5+ default_back_weight: float = 0.4+ default_middle_weight: float = 0.1+ search_front_weight: float = 0.75+ logs_back_weight: float = 0.75+```++---++## Agent-Specific Capabilities++### Claude++- Session branch comparison+- Token headroom mode+- Tool use tracking+- Multi-modal support (images)++### Codex++- Rate limit handling+- Code completion optimization+- Batch request support++### Gemini++- Multi-modal inputs+- Function calling support+- Context caching API++---++## Deployment Capabilities++| Feature | Docker | Native | Embedded |+|---------|:------:|:------:|:--------:|+| Standalone proxy | ✓ | ✓ | - |+| Health endpoints | ✓ | ✓ | - |+| Prometheus metrics | ✓ | ✓ | - |+| Dashboard | ✓ | ✓ | - |+| Volume mounts | ✓ | - | - |+| Environment overrides | ✓ | ✓ | ✓ |++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial capabilities document |diff --git a/specify/009-compliance.md b/specify/009-compliance.mdnew file mode 100644index 000000000..4db500a6b--- /dev/null+++ b/specify/009-compliance.md@@ -0,0 +1,83 @@+# 009. Compliance++**Status:** done++## Data Handling Guarantees++### Default Behavior (No Export)++| Data Type | Stored | Exported | Logged |+|-----------|:------:|:--------:|:------:|+| Prompts | Optional (cache) | Never | Never |+| Responses | Optional (cache) | Never | Never |+| Savings metrics | Yes | Never | Never |+| Session metadata | Yes | Never | Never |+| Telemetry | Aggregated | Never | Never |++---++### With Exporters Configured++**Warning:** Enabling exporters may send data outside your infrastructure.++| Exporter | Data Sent | Destination |+|----------|-----------|-------------|+| Prometheus | Metrics only | Prometheus server |+| OpenTelemetry | Traces/spans | OTLP endpoint |+| Custom webhook | Configurable | HTTP endpoint |++---++## Privacy Commitments++1. **No prompt logging by default** — Headroom never logs prompt content unless explicitly configured+2. **No data leaves proxy by default** — All processing happens locally+3. **User control** — All data handling is configurable via environment variables+4. **Transparency** — Response headers indicate compression was applied+5. **No telemetry to Headroom project** — No data sent to external servers without explicit opt-in++---++## Compliance Considerations++### SOC 2++*To be documented if applicable.*++### GDPR++| Requirement | Headroom Support |+|-------------|:----------------:|+| Data minimization | ✓ Default no-logging |+| Right to deletion | ✓ Cache can be cleared |+| Data portability | Export available via API |+| Breach notification | N/A (no external data) |++### HIPAA++*To be documented if applicable.*++---++## Configuration for Maximum Privacy++```bash+HEADROOM_CACHE_ENABLED=false+HEADROOM_TELEMETRY_ENABLED=false+HEADROOM_LEARN_ENABLED=false+HEADROOM_DASHBOARD_ENABLED=false+```++This configuration results in:+- No prompt data stored+- No data exported+- No analytics collected+- Headroom acts as pure compression proxy++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial compliance document |diff --git a/specify/010-data.md b/specify/010-data.mdnew file mode 100644index 000000000..7b58c571a--- /dev/null+++ b/specify/010-data.md@@ -0,0 +1,175 @@+# 010. Data++**Status:** done++## Storage Overview++| Store | Location | Type | Purpose |+|-------|----------|------|---------|+| SQLite | `headroom.db` (cwd or `~/.headroom/`) | Local file | Metrics, sessions, compression store |+| Memory DB | `~/.headroom/headroom_memory.db` | Local file | Memory system (optional) |+| Vector Index | `~/.headroom/headroom_memory_vectors.db` | Local file | Semantic search (optional, requires sqlite-vec) |+| Graph Store | `~/.headroom/headroom_memory_graph.db` | Local file | Memory relationships |+| Compression cache | `~/.headroom/cache/` | Directory | Semantic + summary cache |++**Note:** Default store URL is `sqlite:///headroom.db` (relative to working directory).++---++## SQLite Schema++### Core Tables++**sessions:**+```sql+CREATE TABLE sessions (+ session_id TEXT PRIMARY KEY,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ metadata TEXT -- JSON+);+```++**requests:**+```sql+CREATE TABLE requests (+ id TEXT PRIMARY KEY,+ timestamp TEXT NOT NULL,+ model TEXT NOT NULL,+ stream INTEGER NOT NULL,+ mode TEXT NOT NULL,+ tokens_input_before INTEGER NOT NULL,+ tokens_input_after INTEGER NOT NULL,+ tokens_output INTEGER,+ block_breakdown TEXT NOT NULL, -- JSON+ waste_signals TEXT NOT NULL, -- JSON+ stable_prefix_hash TEXT,+ cache_alignment_score REAL,+ cached_tokens INTEGER,+ transforms_applied TEXT NOT NULL, -- JSON+ tool_units_dropped INTEGER DEFAULT 0,+ turns_dropped INTEGER DEFAULT 0,+ messages_hash TEXT,+ error TEXT+);++CREATE INDEX idx_timestamp ON requests(timestamp);+CREATE INDEX idx_model ON requests(model);+CREATE INDEX idx_mode ON requests(mode);+```++**cache_entries:**+```sql+CREATE TABLE cache_entries (+ cache_key TEXT PRIMARY KEY,+ input_hash TEXT NOT NULL,+ output TEXT NOT NULL,+ compression_type TEXT NOT NULL,+ tokens_before INTEGER NOT NULL,+ tokens_after INTEGER NOT NULL,+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ ttl INTEGER DEFAULT 3600,+ hit_count INTEGER DEFAULT 0,+ last_accessed TIMESTAMP DEFAULT CURRENT_TIMESTAMP+);+```++**compression_store (CCR):**+```sql+CREATE TABLE compression_store (+ hash TEXT PRIMARY KEY,+ original TEXT NOT NULL,+ metadata TEXT, -- JSON+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ expires_at TIMESTAMP NOT NULL+);+```++---++## Environment Variables++### Database++| Variable | Default | Description |+|----------|---------|-------------|+| `HEADROOM_DB_PATH` | `~/.headroom/` | Base path for databases |+| `HEADROOM_DB_URL` | - | External database URL (overrides default) |+| `HEADROOM_CACHE_PATH` | `~/.headroom/cache/` | Compression cache location |++### Cache++| Variable | Default | Description |+|----------|---------|-------------|+| `HEADROOM_CACHE_ENABLED` | `true` | Enable compression cache |+| `HEADROOM_CACHE_TTL` | `3600` | Cache TTL in seconds |+| `HEADROOM_CACHE_MAX_SIZE` | `10000` | Max cache entries |++---++## Data Retention++| Data Type | Retention | Auto-cleanup |+|-----------|-----------|:------------:|+| Savings history | Forever | No |+| Session history | 30 days | Yes (configurable) |+| Compression cache | 7 days | Yes |+| Telemetry | 90 days | Yes |+| Dashboard state | 30 days | Yes |++---++## Data Export++### Savings Export++```bash+curl http://localhost:8787/stats+```++Response:+```json+{+ "savings": [+ {+ "date": "2026-04-16",+ "original_tokens": 8192,+ "compressed_tokens": 5325,+ "savings_percentage": 0.35+ }+ ],+ "total_savings": 1234567+}+```++### Session Export++```bash+curl http://localhost:8787/stats+```++---++## Backup++### Manual Backup++```bash+tar -czf headroom-backup.tar.gz ~/.headroom/+```++### External Database++Set `HEADROOM_DB_URL` for external storage:++```bash+export HEADROOM_DB_URL=postgresql://user:pass@host:5432/headroom+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial data document |diff --git a/specify/011-deployment.md b/specify/011-deployment.mdnew file mode 100644index 000000000..6eb697dad--- /dev/null+++ b/specify/011-deployment.md@@ -0,0 +1,180 @@+# 011. Deployment++**Status:** done++## Deployment Profiles++### Docker Profile++**Image:** `headroom-ai/headroom:latest`++**Dockerfile:**+```dockerfile+FROM python:3.12-slim++RUN pip install headroom-ai++EXPOSE 8787++ENTRYPOINT ["headroom", "proxy"]+CMD ["--host", "0.0.0.0", "--port", "8787"]+```++**docker-compose.yml:**+```yaml+version: '3.8'+services:+ headroom:+ image: headroom-ai/headroom:latest+ ports:+ - "8787:8787"+ environment:+ - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}+ - HEADROOM_MODE=compress+ - HEADROOM_CACHE_ENABLED=true+ volumes:+ - headroom-data:/root/.headroom++volumes:+ headroom-data:+```++**Run:**+```bash+docker-compose up -d+```++---++### Native Profile++**Installation:**+```bash+pip install headroom-ai+```++**Run:**+```bash+headroom proxy --host 0.0.0.0 --port 8787+```++---++### Embedded Profile++**Usage:**+```python+from headroom import HeadroomClient++client = HeadroomClient(+ api_key="your-api-key",+ base_url="http://localhost:8787"+)++result = await client.compress(messages)+```++---++## Cloud Presets++### AWS (EC2/ECS)++```yaml+# ~/.headroom/config.yaml+deployment:+ profile: aws+ instance_type: t3.medium++compression:+ enabled: true+ max_tokens: 8192++cache:+ backend: redis+ redis_url: redis://localhost:6379+```++### Google Cloud (Cloud Run)++```yaml+deployment:+ profile: gcp+ region: us-central1+ memory: 512Mi+ cpu: 1+```++### Azure (Container Apps)++```yaml+deployment:+ profile: azure+ resource_group: headroom-rg+```++---++## Runtime Configuration++### Environment Variables++| Variable | Default | Description |+|----------|---------|-------------|+| `HEADROOM_MODE` | `audit` | Proxy mode (audit/optimize/simulate) |+| `HEADROOM_PORT` | `8787` | Proxy port |+| `HEADROOM_HOST` | `0.0.0.0` | Proxy host |+| `ANTHROPIC_API_KEY` | - | Anthropic API key |+| `OPENAI_API_KEY` | - | OpenAI API key |+| `HEADROOM_CACHE_ENABLED` | `true` | Enable cache |+| `HEADROOM_CACHE_TTL` | `3600` | Cache TTL |+| `HEADROOM_TELEMETRY_ENABLED` | `true` | Enable telemetry |++### Config File++```yaml+# ~/.headroom/config.yaml+proxy:+ host: 0.0.0.0+ port: 8787++compression:+ enabled: true+ max_tokens: 4096+ overlap_tokens: 512+ content_sensitivity: 0.5+ preserve_system_messages: true+ priority_tokens: 1024++cache:+ enabled: true+ ttl: 3600+ max_size: 10000++telemetry:+ metrics:+ enabled: true+ tracing:+ enabled: false++learn:+ enabled: false+```++---++## Resource Requirements++| Deployment | CPU | Memory | Storage |+|------------|-----|--------|---------|+| Minimal | 0.5 core | 512MB | 1GB |+| Default | 1 core | 1GB | 5GB |+| Enterprise | 2 cores | 2GB | 20GB |++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial deployment document |diff --git a/specify/012-diagrams.md b/specify/012-diagrams.mdnew file mode 100644index 000000000..d471b5021--- /dev/null+++ b/specify/012-diagrams.md@@ -0,0 +1,140 @@+# 012. Diagrams++**Status:** done++## Component Diagram++```+┌─────────────────────────────────────────────────────────────────┐+│ Headroom │+├─────────────────────────────────────────────────────────────────┤+│ │+│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────┐ │+│ │ Proxy │ │ SDK │ │ Wrap │ │ MCP │ │+│ │ Server │ │ (Python) │ │ CLI │ │ Server │ │+│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬──────┘ │+│ │ │ │ │ │+│ ┌────┴──────────────┴──────────────┴─────────────────┴──────┐ │+│ │ Compression Layer │ │+│ │ ┌────────────┐ ┌────────────┐ ┌────────────────────┐ │ │+│ │ │ Semantic │ │ Summary │ │ Token Budget │ │ │+│ │ │ Cache │ │ Compress │ │ Manager │ │ │+│ │ └────────────┘ └────────────┘ └────────────────────┘ │ │+│ └───────────────────────────────────────────────────────────┘ │+│ │+│ ┌───────────────────────────────────────────────────────────┐ │+│ │ Learn System │ │+│ │ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────────────┐ │ │+│ │ │Claude │ │ Codex │ │ Gemini │ │ ...more │ │ │+│ │ │Plugin │ │ Plugin │ │ Plugin │ │ plugins │ │ │+│ │ └────────┘ └────────┘ └────────┘ └────────────────┘ │ │+│ └───────────────────────────────────────────────────────────┘ │+│ │+│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │+│ │ Dashboard │ │ CCR │ │ TOIN │ │+│ │ (Next.js) │ │ (Claude │ │ (Tenant-specific │ │+│ │ │ │ Code Relay)│ │ ONNX) │ │+│ └──────────────┘ └──────────────┘ └──────────────────────┘ │+│ │+└─────────────────────────────────────────────────────────────────┘+```++---++## Request Flow Sequence Diagram++```+Client Headroom Compression CCR Provider+ Proxy Layer Cache API+ │ │ │ │ │+ │──POST /v1/msg──▶│ │ │ │+ │ │ │ │ │+ │ │──Count tokens──▶│ │ │+ │ │ │ │ │+ │ │────Cache check────▶│ │ │+ │ │ │◀───hit──────│ │+ │ │ │◀───CCR retrieval───────│+ │ │ │ │ │+ │ │───Summary compression───▶│ │+ │ │ │◀──budget enforcement─────│+ │ │ │ │ │+ │ │─────Forward compressed─────▶│ │+ │ │ │ │◀──Response──│+ │ │◀──────────────────────────────────────│+ │◀──Response──│ │ │ │+```++---++## CCR Cache Flow++```+Request Headroom CCR Storage+ │ Proxy Cache+ │ │ │+ │──compress──▶│ │+ │ │──hash────▶│+ │ │ │──store──▶│+ │ │◀──stored──│ │+ │ │──CCR hash │+ │◀──Response──│ │+ │ │ │+```++---++## Learn System Flow++```+Session Headroom Learn Plugin+ Data Proxy System Registry+ │ │ │ │+ │──session──▶│ │ │+ │ │──analyze──▶│ │+ │ │ │──load────▶│+ │ │ │◀─Result───│+ │ │◀──Feedback──│ │+ │ │──Improve compression │+ │◀───────────│ │ │+```++---++## Data Flow++```+┌──────────────┐+│ User's │+│ AI Agent │+└──────┬───────┘+ │ HTTP+ ▼+┌──────────────┐ ┌─────────────────────────────────────┐+│ Headroom │────▶│ Compression Layer │+│ Proxy │ │ │+└──────┬───────┘ │ ┌─────────┐ ┌──────────────┐ │+ │ │ │ Semantic│ │ Summary │ │+ │ │ │ Cache │ │ Compression │ │+ │ │ └────┬───┘ └──────┬───────┘ │+ │ │ │ │ │+ │ │ ┌────┴─────────────┴──────┐ │+ │ │ │ Token Budget │ │+ │ │ │ Manager │ │+ │ │ └────────────┬───────────┘ │+ │ └───────────────┼─────────────────┘+ │ │+ │ │ Compressed request+ ▼ ▼+┌──────────────┐ ┌──────────────┐+│ Dashboard │ │ Provider │+│ (optional) │ │ API │+└──────────────┘ └──────────────┘+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial diagrams document |diff --git a/specify/013-disaster-recovery.md b/specify/013-disaster-recovery.mdnew file mode 100644index 000000000..335482bf7--- /dev/null+++ b/specify/013-disaster-recovery.md@@ -0,0 +1,162 @@+# 013. Disaster Recovery++**Status:** done++## Failure Modes++### Proxy Failures++| Failure | Impact | Recovery |+|---------|--------|----------|+| Proxy crash | Service unavailable | Restart or failover |+| OOM | Service unavailable | Restart with more memory |+| Network partition | Cannot reach providers | Retry with backoff |++### Compression Failures++| Failure | Impact | Recovery |+|---------|--------|----------|+| Compression timeout | Request delayed | Retry with passthrough |+| Transform error | Compression skipped | Log error, passthrough |+| Budget exceeded | Truncation | Notify via headers |++### Storage Failures++| Failure | Impact | Recovery |+|---------|--------|----------|+| SQLite corruption | Data loss | Restore from backup |+| Cache full | CCR disabled | Clear old entries |+| Disk full | Write failures | Expand storage |++---++## Backup Strategies++### Manual Backup++```bash+# Full backup+tar -czf headroom-backup-$(date +%Y%m%d).tar.gz ~/.headroom/++# Incremental (last 24h)+sqlite3 ~/.headroom/headroom_memory.db ".backup /tmp/headroom_incremental.db"+```++### Automated Backup++```bash+# Cron job (daily at 2am)+0 2 * * * tar -czf /backup/headroom-$(date +\%Y\%m\%d).tar.gz ~/.headroom/+```++### External Storage++```bash+export HEADROOM_DB_URL=postgresql://user:pass@host:5432/headroom+export HEADROOM_CACHE_BACKEND=redis+```++---++## Recovery Procedures++### Proxy Recovery++1. **Restart proxy:**+```bash+# Docker+docker-compose restart headroom++# Native+pkill headroom && headroom proxy &+```++2. **Check health:**+```bash+curl http://localhost:8787/health+curl http://localhost:8787/readyz+```++### Database Recovery++1. **Restore from backup:**+```bash+# Stop headroom+pkill headroom++# Restore SQLite+rm ~/.headroom/headroom_memory.db+tar -xzf headroom-backup-20260416.tar.gz -C ~/++# Restart headroom+headroom proxy &+```++2. **Verify data:**+```bash+curl http://localhost:8787/stats+```++---++## Data Migration++### Schema Migration++```python+async def migrate_v1_to_v2():+ async with aiosqlite.connect(DB_PATH) as db:+ await db.execute("""+ ALTER TABLE sessions+ ADD COLUMN agent_version TEXT+ """)+ await db.commit()+```++### Data Export/Import++```bash+# Export+curl http://localhost:8787/api/v1/export > backup.json++# Import+curl -X POST http://localhost:8787/api/v1/import \+ -H "Content-Type: application/json" \+ -d @backup.json+```++---++## High Availability++### Active-Active++```yaml+services:+ headroom-1:+ image: headroom-ai/headroom:latest+ ports:+ - "8787:8787"++ headroom-2:+ image: headroom-ai/headroom:latest+ ports:+ - "8788:8787"++ redis:+ image: redis:latest+```++### Health Check Failover++```bash+curl http://primary:8787/health || curl http://backup:8787/health+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial disaster recovery document |diff --git a/specify/014-governance.md b/specify/014-governance.mdnew file mode 100644index 000000000..03640193a--- /dev/null+++ b/specify/014-governance.md@@ -0,0 +1,129 @@+# 014. Governance++**Status:** done++## Project Structure++- **Repository:** `github.com/JerrettDavis/headroom`+- **License:** Apache 2.0+- **Main Languages:** Python (core), TypeScript (SDK/dashboard)++---++## Release Cadence++| Channel | Frequency | Stability |+|---------|-----------|-----------|+| Stable | Monthly | Production-ready |+| Beta | As needed | May have issues |+| Nightly | Daily | Unstable |++---++## Semantic Versioning++Headroom follows semver:++- **MAJOR:** Breaking changes to API, CLI, or core behavior+- **MINOR:** New features, backwards-compatible+- **PATCH:** Bug fixes, backwards-compatible++---++## Decision Making++### RFC Process++1. Open GitHub issue with `[RFC]` prefix+2. Gather community feedback (2 weeks minimum)+3. Core team reviews+4. Decision documented in ADRs+5. Implementation proceeds++### Criteria for Core Team Approval++- Consistent with project vision+- Does not break existing guarantees+- Implementation is feasible+- Tests can be written++---++## Spec-Driven Development++This specification is the **canonical source of truth** for Headroom behavior:++| Rule | Description |+|------|-------------|+| **Canonical** | When code and spec diverge, the spec is the target |+| **Living** | Spec updates required for behavior-changing changes |+| **Comprehensive** | Spec covers every user-visible surface |+| **Language-agnostic** | Enables complete rewrite in any language |++### Spec Change Process++1. Propose change in GitHub issue+2. Discuss in RFC format+3. Update relevant spec section+4. Update SPEC.md version and change log+5. Implement code change+6. Verify implementation matches spec++---++## Supply Chain Posture++| Component | Policy |+|-----------|--------|+| Dependencies | Pin versions, audit regularly |+| Build artifacts | Reproducible builds |+| Signing | Code signed for releases |+| Vulnerability reporting | See SECURITY.md |++---++## Contributing++### Development Setup++```bash+# Clone repository+git clone https://github.com/JerrettDavis/headroom.git+cd headroom++# Create virtual environment+python -m venv venv+source venv/bin/activate++# Install dependencies+pip install -e ".[dev]"++# Run tests+pytest+```++### Code Style++- Format: `ruff format`+- Lint: `ruff check`+- Type check: `mypy`++---++## Code of Conduct++See `CODE_OF_CONDUCT.md`.++---++## Security++See `SECURITY.md` for vulnerability reporting and response timeline.++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial governance document |diff --git a/specify/015-interfaces.md b/specify/015-interfaces.mdnew file mode 100644index 000000000..daf297688--- /dev/null+++ b/specify/015-interfaces.md@@ -0,0 +1,334 @@+# 015. Interfaces++**Status:** done++## CLI Surface++### `headroom proxy`++Start the Headroom proxy server.++```bash+headroom proxy [OPTIONS]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--host` | `0.0.0.0` | Bind host |+| `--port` | `8787` | Bind port |+| `--llmlingua-device` | `cpu` | LLMLingua device (cpu/cuda) |+| `--config` | - | Config file path |++---++### `headroom evals`++Run evaluation suite.++```bash+headroom evals [OPTIONS]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--suite` | `all` | Evaluation suite to run |+| `--output` | - | Output file for results |++---++### `headroom install`++Install agent integrations.++```bash+headroom install [OPTIONS]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--agent` | - | Agent type (claude/copilot/codex/aider/cursor/openclaw) |++---++### `headroom mcp`++Start MCP server.++```bash+headroom mcp [OPTIONS]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--port` | `8766` | MCP server port |++---++### `headroom perf`++Run performance tests.++```bash+headroom perf [OPTIONS]+```++---++### `headroom wrap`++Wrap a command with Headroom proxy.++```bash+headroom wrap [OPTIONS] -- <command> [args...]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--port` | `8787` | Proxy port |+| `--no-rtk` | `false` | Skip RTK hooks |++**Supported Commands:**+- `claude` — Wrap Claude Code+- `copilot` — Wrap GitHub Copilot+- `codex` — Wrap OpenAI Codex+- `aider` — Wrap Aider+- `cursor` — Wrap Cursor+- `openclaw` — Wrap OpenClaw++---++### `headroom memory`++Memory system management (requires numpy/hnswlib).++```bash+headroom memory [OPTIONS]+```++**Commands:**+- `list` — List stored memories+- `stats` — Show memory statistics+- `search QUERY` — Search memories++---++### `headroom learn`++Run learn mode analysis.++```bash+headroom learn [OPTIONS]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--agent` | `auto` | Agent type |+| `--mode` | `auto` | Learn mode |+| `--session` | - | Session ID |++---++### `headroom stats`++Show savings statistics.++```bash+headroom stats [OPTIONS]+```++**Options:**+| Flag | Default | Description |+|------|---------|-------------|+| `--period` | `24h` | Time period |+| `--format` | `table` | Output format (table, json, csv) |++---++### `headroom config`++Manage configuration.++```bash+headroom config [COMMAND] [OPTIONS]+```++**Commands:**+- `get KEY` — Get config value+- `set KEY VALUE` — Set config value+- `list` — List all config+- `export` — Export config to file++---++## HTTP API++### Endpoints++| Method | Path | Description |+|--------|------|-------------|+| `GET` | `/health` | Health check |+| `GET` | `/livez` | Liveness check |+| `GET` | `/readyz` | Readiness check |+| `POST` | `/v1/messages` | Proxy chat completions |+| `POST` | `/v1/embeddings` | Proxy embeddings |+| `POST` | `/v1/compress` | Direct compression |+| `POST` | `/v1/retrieve` | CCR retrieval |+| `GET` | `/stats` | Compression statistics |+| `GET` | `/metrics` | Prometheus metrics |++### Request/Response Examples++**POST /v1/messages:**+```bash+curl -X POST http://localhost:8787/v1/messages \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer sk-..." \+ -d '{+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "Hello"}]+ }'+```++**Response headers:**+```+X-Headroom-Savings: 0.35+X-Headroom-Original-Tokens: 8192+X-Headroom-Compressed-Tokens: 5325+```++---++## Environment Variables++### Core++| Variable | Default | Description |+|----------|---------|-------------|+| `HEADROOM_MODE` | `audit` | Operation mode (audit/optimize/simulate) |+| `HEADROOM_PORT` | `8787` | Proxy port |+| `HEADROOM_HOST` | `0.0.0.0` | Proxy host |+| `HEADROOM_STORE_URL` | `sqlite:///headroom.db` | Storage URL |+| `HEADROOM_PROXY_URL` | `http://localhost:8787` | Proxy URL |+| `HEADROOM_LOG_LEVEL` | `INFO` | Log level |++### Provider++| Variable | Default | Description |+|----------|---------|-------------|+| `ANTHROPIC_API_KEY` | - | Anthropic API key |+| `OPENAI_API_KEY` | - | OpenAI API key |+| `GOOGLE_API_KEY` | - | Google AI API key |+| `COHERE_API_KEY` | - | Cohere API key |++### Features++| Variable | Default | Description |+|----------|---------|-------------|+| `HEADROOM_CACHE_ENABLED` | `true` | Enable cache |+| `HEADROOM_CACHE_TTL` | `3600` | Cache TTL in seconds |+| `HEADROOM_CACHE_MAX_SIZE` | `10000` | Max cache entries |+| `HEADROOM_LEARN_ENABLED` | `false` | Enable learn |+| `HEADROOM_DASHBOARD_ENABLED` | `false` | Enable dashboard |+| `HEADROOM_TELEMETRY_ENABLED` | `true` | Enable telemetry |++### Compression++| Variable | Default | Description |+|----------|---------|-------------|+| `HEADROOM_MAX_TOKENS` | `4096` | Max tokens per request |+| `HEADROOM_TARGET_TOKENS` | - | Target tokens after compression |+| `HEADROOM_OVERLAP_TOKENS` | `512` | Overlap tokens for chunking |+| `HEADROOM_CONTENT_SENSITIVITY` | `0.5` | Content sensitivity (0-1) |+| `HEADROOM_PRESERVE_SYSTEM` | `true` | Preserve system messages |++---++## Plugin ABI++### Plugin Interface++```python+from abc import ABC, abstractmethod+from headroom.learn.base import ConversationScanner, ContextWriter+from headroom.learn.models import ProjectInfo, SessionData++class LearnPlugin(ConversationScanner):+ """A self-contained learn plugin for a single coding agent."""++ @property+ @abstractmethod+ def name(self) -> str:+ """Short lowercase identifier (e.g., 'claude', 'cursor')."""+ ...++ @property+ @abstractmethod+ def display_name(self) -> str:+ """Human-readable name (e.g., 'Claude Code', 'Cursor')."""+ ...++ @abstractmethod+ def detect(self) -> bool:+ """Return True if this agent has data on the current machine."""+ ...++ @abstractmethod+ def discover_projects(self) -> list[ProjectInfo]:+ """Discover all projects with conversation data."""+ ...++ @abstractmethod+ def scan_project(self, project: ProjectInfo, max_workers: int = 1) -> list[SessionData]:+ """Scan all sessions for a project."""+ ...++ @abstractmethod+ def create_writer(self) -> ContextWriter:+ """Return the appropriate ContextWriter for this agent."""+ ...+```++### Plugin Registration++Plugins are auto-discovered from `headroom/learn/plugins/` directory.++**Manual registration:**+```python+from headroom.learn import plugin_registry++plugin_registry.register(MyPlugin())+```++### Plugin Config++```yaml+# ~/.headroom/config.yaml+learn:+ enabled: true+ plugins:+ - name: claude+ enabled: true+ config:+ session_modes:+ - auto+ - learn+ - disabled+ - name: my_plugin+ enabled: true+ config:+ custom_option: value+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial interfaces document |diff --git a/specify/016-observability.md b/specify/016-observability.mdnew file mode 100644index 000000000..0070f6d67--- /dev/null+++ b/specify/016-observability.md@@ -0,0 +1,170 @@+# 016. Observability++**Status:** done++## Telemetry++### Metrics++Headroom exposes Prometheus metrics at `/metrics`.++**Key Metrics:**++| Metric | Type | Description |+|--------|------|-------------|+| `headroom_requests_total` | Counter | Total requests |+| `headroom_tokens_original` | Counter | Original token count |+| `headroom_tokens_compressed` | Counter | Compressed token count |+| `headroom_savings_percent` | Histogram | Savings distribution |+| `headroom_cache_hits_total` | Counter | Cache hits |+| `headroom_cache_misses_total` | Counter | Cache misses |+| `headroom_compression_duration_seconds` | Histogram | Compression latency |+| `headroom_request_duration_seconds` | Histogram | Total request latency |++**Prometheus scrape config:**+```yaml+scrape_configs:+ - job_name: 'headroom'+ static_configs:+ - targets: ['localhost:8787']+ metrics_path: '/metrics'+```++---++### Tracing++OpenTelemetry tracing support.++**Configuration:**+```bash+OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317+OTEL_SERVICE_NAME=headroom+HEADROOM_TRACING_ENABLED=true+```++**Spans:**+| Span | Description |+|------|-------------|+| `headroom.proxy.request` | Full request lifecycle |+| `headroom.compression` | Compression operation |+| `headroom.cache.lookup` | Cache check |+| `headroom.provider.call` | Provider API call |++---++### Logging++**Log Levels:**++| Level | Use Case |+|-------|----------|+| `DEBUG` | Detailed debugging |+| `INFO` | General operation |+| `WARNING` | Degraded operation |+| `ERROR` | Failures |++**Log Format (JSON):**+```json+{+ "timestamp": "2026-04-16T12:00:00Z",+ "level": "INFO",+ "message": "Request completed",+ "request_id": "abc123",+ "savings": 0.45,+ "duration_ms": 120+}+```++**Configuration:**+```bash+HEADROOM_LOG_LEVEL=INFO+HEADROOM_LOG_FORMAT=json+```++Or in config:+```yaml+logging:+ level: INFO+ format: json+```++---++## Dashboard++**URL:** `http://localhost:8787/dashboard`++**Metrics Shown:**+- Total savings over time+- Requests per day+- Cache hit rate+- Top compressed endpoints+- Session overview++**Requires:** `HEADROOM_DASHBOARD_ENABLED=true`++---++## Alerting++### Recommended Alerts++| Alert | Condition | Severity |+|-------|-----------|----------|+| HighErrorRate | error_rate > 5% | warning |+| LowSavings | savings < 20% | warning |+| CacheDown | cache_hits < 10% for 1h | critical |+| ProxyDown | health check fails | critical |++**Alert rule example (Prometheus):**+```yaml+groups:+ - name: headroom+ rules:+ - alert: HighErrorRate+ expr: rate(headroom_errors_total[5m]) / rate(headroom_requests_total[5m]) > 0.05+ for: 5m+ labels:+ severity: warning+ annotations:+ summary: "High error rate in Headroom"+```++---++## Health Endpoints++| Endpoint | Method | Description |+|----------|--------|-------------|+| `/health` | GET | Basic health check |+| `/livez` | GET | Liveness check (process alive) |+| `/readyz` | GET | Readiness check (can serve traffic) |++**Health response:**+```json+{+ "status": "healthy",+ "version": "1.0.0"+}+```++**Readiness response:**+```json+{+ "ready": true,+ "checks": {+ "database": true,+ "cache": true,+ "provider": true+ }+}+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial observability document |diff --git a/specify/017-operations.md b/specify/017-operations.mdnew file mode 100644index 000000000..e30299c04--- /dev/null+++ b/specify/017-operations.md@@ -0,0 +1,179 @@+# 017. Operations++**Status:** done++## Health Endpoints++### `GET /health`++Basic health check. Returns 200 if process is running.++```bash+curl http://localhost:8787/health+```++**Response:**+```json+{+ "status": "healthy",+ "version": "1.0.0"+}+```++---++### `GET /livez`++Liveness check. Returns 200 if process is alive.++```bash+curl http://localhost:8787/livez+```++---++### `GET /readyz`++Readiness check. Returns 200 if ready to serve traffic.++```bash+curl http://localhost:8787/readyz+```++**Response:**+```json+{+ "ready": true,+ "checks": {+ "database": true,+ "cache": true,+ "provider": true+ }+}+```++---++## Logs++### Log Locations++| Installation | Location |+|-------------|----------|+| Docker | `docker logs headroom` |+| Native | `~/.headroom/logs/` |+| Systemd | `journalctl -u headroom` |++### Log Levels++Set via environment:+```bash+HEADROOM_LOG_LEVEL=INFO+```++Or in config:+```yaml+logging:+ level: INFO+ format: json+```++---++## Metrics++### Prometheus++**Scrape Config:**+```yaml+scrape_configs:+ - job_name: 'headroom'+ static_configs:+ - targets: ['localhost:8787']+ metrics_path: '/metrics'+```++---++## Upgrade Procedure++### Docker++```bash+docker pull headroom-ai/headroom:latest+docker-compose down+docker-compose up -d+```++### Native++```bash+pip install --upgrade headroom-ai+# Restart headroom service+```++### Embedded++```bash+pip install --upgrade headroom-ai+# Restart application+```++---++## Rollback++### Docker++```bash+docker-compose down+docker tag headroom-ai/headroom:latest headroom-ai/headroom:rollback+# Edit docker-compose.yml to use rollback tag+docker-compose up -d+```++---++## Monitoring++### Key Metrics to Watch++1. **Request rate** — requests per second+2. **Error rate** — 4xx + 5xx / total+3. **Savings rate** — average savings percentage+4. **Latency** — p50, p95, p99+5. **Cache hit rate** — hits / total++**Prometheus queries:**+```promql+# Request rate+rate(headroom_requests_total[5m])++# Error rate+rate(headroom_errors_total[5m]) / rate(headroom_requests_total[5m])++# Average savings+rate(headroom_tokens_original[5m] - headroom_tokens_compressed[5m]) / rate(headroom_tokens_original[5m])++# Cache hit rate+rate(headroom_cache_hits_total[5m]) / (rate(headroom_cache_hits_total[5m]) + rate(headroom_cache_misses_total[5m]))+```++---++## Runbook++| Symptom | Cause | Solution |+|---------|-------|----------|+| "Connection refused" | Proxy not running | `headroom proxy start` |+| "Cache miss on every request" | Cache disabled | Set `HEADROOM_CACHE_ENABLED=true` |+| "No savings shown" | Database locked | Check file permissions |+| "Provider timeout" | Network issue | Check firewall/proxy |++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial operations document |diff --git a/specify/018-policies.md b/specify/018-policies.mdnew file mode 100644index 000000000..2851c5fa4--- /dev/null+++ b/specify/018-policies.md@@ -0,0 +1,119 @@+# 018. Policies++**Status:** done++## Default Behaviors++### Compression++| Setting | Default | Description |+|---------|---------|-------------|+| Compression enabled | `true` | Apply compression by default |+| Cache enabled | `true` | Use semantic cache |+| Summary enabled | `true` | Use summary compression |+| Token budget enforced | `false` | No budget limit by default |++### Telemetry++| Setting | Default | Description |+|---------|---------|-------------|+| Metrics enabled | `true` | Emit Prometheus metrics |+| Tracing enabled | `false` | No OTEL tracing |+| Dashboard enabled | `false` | No built-in dashboard |++### Learn++| Setting | Default | Description |+|---------|---------|-------------|+| Learn enabled | `false` | Learning disabled |+| Plugin auto-detect | `true` | Auto-load plugins |+| Feedback collection | `false` | No CCR feedback |++---++## Override Mechanisms++### Environment Variables++All settings can be overridden via environment variables:+```bash+HEADROOM_CACHE_ENABLED=false+HEADROOM_MODE=passthrough+HEADROOM_MAX_TOKENS=8192+```++### Config File++```yaml+# ~/.headroom/config.yaml+proxy:+ host: 0.0.0.0+ port: 8787++compression:+ enabled: true+ cache:+ enabled: true+ ttl: 3600++telemetry:+ metrics:+ enabled: true+ tracing:+ enabled: false++learn:+ enabled: false+```++### Runtime API++```bash+# Disable compression for single request+curl -X POST http://localhost:8787/v1/messages \+ -H "X-Headroom-Compress: false"+```++### Runtime Headers++| Header | Description |+|--------|-------------|+| `X-Headroom-Compress` | Override compression (true/false) |+| `X-Headroom-Mode` | Override mode (passthrough/compress/learn) |+| `X-Headroom-Cache` | Override cache (true/false) |++---++## Policy Hierarchy++Settings are evaluated in this order (highest wins):++1. **Runtime headers** — Per-request overrides+2. **Environment variables** — Process-level+3. **Config file** — Persistent settings+4. **Defaults** — Built-in defaults++---++## Per-Tenant Policies (TOIN)++TOIN tenants can have custom policies:++```yaml+tenant:+ id: "acme-corp"+ policies:+ compression:+ enabled: true+ threshold: 3000+ budget:+ daily_limit: 1000000+```++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial policies document |diff --git a/specify/019-quality.md b/specify/019-quality.mdnew file mode 100644index 000000000..0cd0af1bd--- /dev/null+++ b/specify/019-quality.md@@ -0,0 +1,111 @@+# 019. Quality++**Status:** done++## Test Pyramid++```+ ┌─────────────┐+ │ E2E │ ← Few, slow, comprehensive+ │ Tests │+ └──────┬──────┘+ │+ ┌──────┴──────┐+ │ Integration │ ← Medium, moderate+ │ Tests │+ └──────┬──────┘+ │+ ┌────────────┴────────────┐+ │ │+┌────┴────┐ ┌────┴────┐+│ Unit │ │ Unit │+│ Tests │ │ Tests │+└─────────┘ └─────────┘+Many, fast, isolated+```++---++## Test Coverage++| Surface | Unit | Integration | E2E |+|---------|:----:|:------------:|:---:|+| Proxy Server | ✓ | ✓ | ✓ |+| SDK | ✓ | ✓ | - |+| Compression | ✓ | ✓ | ✓ |+| Cache | ✓ | ✓ | - |+| Learn | ✓ | ✓ | - |+| CCR | ✓ | ✓ | ✓ |+| TOIN | ✓ | ✓ | - |+| Dashboard | ✓ | - | ✓ |++---++## Coverage Targets++| Metric | Target | Threshold |+|--------|--------|-----------|+| Line coverage | 80% | 70% |+| Branch coverage | 70% | 60% |+| Critical path | 100% | 100% |++---++## Critical Paths++These must always pass:++1. **Compression pipeline** — Input → Compress → Output+2. **Cache hit path** — Input → Cache check → Return+3. **Provider proxy** — Request → Proxy → Provider → Response+4. **Learn feedback** — Session → Analyze → Compress → Store++---++## Performance Benchmarks++| Operation | Target | Threshold |+|-----------|--------|-----------|+| Compression | < 50ms | < 200ms |+| Cache lookup | < 5ms | < 20ms |+| Proxy latency | +10ms | +50ms |++---++## CI/CD++### Required Checks++| Check | Command | Timeout |+|-------|---------|---------|+| Lint | `ruff check` | 2m |+| Type check | `mypy` | 5m |+| Unit tests | `pytest tests/unit/` | 10m |+| Integration | `pytest tests/ -k integration` | 15m |+| E2E | `pytest e2e/` | 30m |++### Workflow (`.github/workflows/`)++1. **Lint** — `ruff check` + `ruff format --check`+2. **Type check** — `mypy src/`+3. **Unit tests** — `pytest tests/unit/ --cov`+4. **Integration** — `pytest tests/ -k integration`+5. **E2E** — `pytest e2e/ --api-key=$ANTHROPIC_API_KEY`++---++## Quality Gates++PRs must pass:+- All tests green+- Type checking passes (`mypy`)+- Lint passes (`ruff`)+- Coverage maintained or improved++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial quality document |diff --git a/specify/020-security.md b/specify/020-security.mdnew file mode 100644index 000000000..8c5477c61--- /dev/null+++ b/specify/020-security.md@@ -0,0 +1,120 @@+# 020. Security++**Status:** done++## Threat Model++### Threats++| Threat | Impact | Mitigation |+|--------|--------|------------|+| Prompt data exfiltration | High | No logging, local-only |+| API key theft | High | Key rotation, secrets management |+| Cache poisoning | Medium | Input validation |+| DoS via large prompts | Medium | Token limits |+| SSRF via redirects | Medium | URL validation |++---++### Trust Boundaries++```+┌──────────────────┐ ┌──────────────────┐+│ User's App │────▶│ Headroom Proxy │+└──────────────────┘ └────────┬─────────┘+ │+ ┌────────┴─────────┐+ │ │+ ┌─────▼─────┐ ┌──────▼──────┐+ │ Provider │ │ Database │+ │ APIs │ │ (SQLite) │+ └───────────┘ └─────────────┘+```++---++## Security Controls++### Authentication++| Surface | Auth Method |+|---------|-------------|+| Proxy | API key (optional) |+| Dashboard | None by default |+| Health endpoints | None |+| Metrics | None |++### Authorization++- **No multi-user support** — Single-tenant by design+- **API keys** — For proxy authentication+- **CORS** — Configurable origins++---++## Data Protection++| Data | At Rest | In Transit |+|------|---------|------------|+| Prompts | Encrypted (if DB encrypted) | TLS |+| Responses | Encrypted (if DB encrypted) | TLS |+| API keys | Encrypted | TLS |+| Metrics | Plain text | TLS |++---++## Input Validation++- **Prompt length** — Enforced via token budget+- **URL validation** — For provider redirects+- **Schema validation** — For all API inputs++---++## Secrets Management++### Environment Variables++```bash+ANTHROPIC_API_KEY=sk-...+OPENAI_API_KEY=sk-...+```++### Secrets Management Systems++Headroom supports:+- AWS Secrets Manager+- HashiCorp Vault+- Azure Key Vault++---++## Supply Chain Security++### Dependencies++- **Pinned versions** — All dependencies pinned+- **Audit** — Regular `pip audit`+- **SBOM** — Software Bill of Materials generated++### Build++- **Reproducible** — Docker builds are reproducible+- **Signed releases** — Code signed++---++## Vulnerability Reporting++See `SECURITY.md` for:+- Reporting process+- Response timeline+- Disclosure policy++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial security document |diff --git a/specify/021-testing.md b/specify/021-testing.mdnew file mode 100644index 000000000..47e9e8a31--- /dev/null+++ b/specify/021-testing.md@@ -0,0 +1,162 @@+# 021. Testing++**Status:** done++## Test Strategy by Surface++### Proxy Server++**Unit Tests:**+- Request routing+- Response header injection+- Mode switching+- Error handling++**Integration Tests:**+- Full request/response cycle+- Provider mocking+- Cache integration++**E2E Tests:**+- Against real provider APIs (with API keys)++---++### Compression++**Unit Tests:**+- Token counting+- Semantic hashing+- Summary compression+- Budget enforcement++**Integration Tests:**+- Cache round-trip+- Multi-stage compression++**Benchmarks:**+- Latency at scale+- Memory usage++---++### Learn System++**Unit Tests:**+- Plugin interface compliance+- Error classification+- Session analysis++**Integration Tests:**+- Plugin discovery+- Cross-plugin interaction++**E2E Tests:**+- Real session analysis++---++### CCR (Claude Code Relay)++**Unit Tests:**+- Context tracking+- Feedback collection+- Batch processing++**Integration Tests:**+- Tool injection+- Response handling++**E2E Tests:**+- Full CCR workflow++---++## Test Utilities++### Fixtures++Located in `tests/conftest.py`:+- `mock_provider` — Mock AI provider+- `sample_session` — Sample conversation+- `temp_db` — Temporary database++### Mock Libraries++- `responses` — HTTP mocking+- `pytest-mock` — Function mocking+- `aioresponses` — Async HTTP mocking++---++## Running Tests++### All Tests++```bash+pytest+```++### By Surface++```bash+pytest tests/test_proxy/+pytest tests/test_compression/+pytest tests/test_learn/+```++### With Coverage++```bash+pytest --cov=headroom --cov-report=html+```++### E2E Tests++```bash+# Requires API keys+pytest e2e/ --api-key=$ANTHROPIC_API_KEY+```++---++## Test Data++### Sample Sessions++Stored in `tests/fixtures/sessions/`:+- `claude_code_short.json` — Short Claude Code session+- `claude_code_long.json` — Long session with tool use+- `codex_completion.json` — Codex completion+- `gemini_multimodal.json` — Gemini with images++---++## Continuous Integration++### Required Checks++| Check | Command | Timeout |+|-------|---------|---------|+| Lint | `ruff check` | 2m |+| Type check | `mypy` | 5m |+| Unit tests | `pytest tests/` | 10m |+| Integration | `pytest tests/ -k integration` | 15m |+| E2E | `pytest e2e/` | 30m |++---++## Test Maintenance++- **Fixtures** — Keep realistic but small+- **Mocks** — Don't over-mock providers+- **Flaky tests** — Mark with `@pytest.mark.flaky`+- **Coverage drops** — PR blocked if coverage drops++---++## Version History++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial testing document |diff --git a/specify/SPEC.md b/specify/SPEC.mdnew file mode 100644index 000000000..4005d99d3--- /dev/null+++ b/specify/SPEC.md@@ -0,0 +1,88 @@+# Headroom Living Specification++**Version:** 1.0.0-draft+**Date:** 2026-04-16+**Status:** Draft — In Progress+**Related Issue:** GitHub #183++---++## Constitution++This specification is the **canonical source of truth** for how Headroom is designed to behave. It serves:++1. **New contributors** — One place to understand how Headroom works+2. **Enterprises evaluating adoption** — Clear guarantees about behavior, privacy, security+3. **Operators running managed deployments** — Operational guidance for all surfaces+4. **Plugin authors** — Clear contracts for extension points+5. **PR review** — A checklist target: "does the code match the spec?"++### Spec Governance++| Rule | Description |+|------|-------------|+| **Canonical** | When code and spec diverge, the spec is the target; the code needs updating |+| **Living** | Spec updates are required for behavior-changing changes (PR checklist) |+| **Comprehensive** | Spec covers every user-visible surface, behavior, and guarantee |+| **Language-agnostic** | Spec enables complete rewrite in any language with parity |+| **Versioned** | Changes increment version; breaking changes require major version bump |++### Spec Sections++| # | Section | Status | Description |+|---|---------|:------:|-------------|+| 001 | [Vision](001-vision.md) | done | What Headroom is, what it is not |+| 002 | [Architecture](002-architecture.md) | done | Component diagram + descriptions |+| 003 | [ADRs](003-adrs.md) | done | Architecture Decision Records |+| 004 | [Domain Model](004-domain-model.md) | done | Core entities |+| 005 | [Integrations](005-integrations.md) | done | Agent contracts |+| 006 | [Actors](006-actors.md) | done | User types + interactions |+| 007 | [Behavior](007-behavior.md) | done | Mode-by-mode specification |+| 008 | [Capabilities](008-capabilities.md) | done | Feature matrix |+| 009 | [Compliance](009-compliance.md) | done | Data guarantees, privacy |+| 010 | [Data](010-data.md) | done | Storage, retention, env vars |+| 011 | [Deployment](011-deployment.md) | done | Profiles, presets, runtimes |+| 012 | [Diagrams](012-diagrams.md) | done | Component, sequence, data-flow |+| 013 | [Disaster Recovery](013-disaster-recovery.md) | done | Failure modes + recovery |+| 014 | [Governance](014-governance.md) | done | Decision-making, releases |+| 015 | [Interfaces](015-interfaces.md) | done | CLI, HTTP, env var, plugin ABI |+| 016 | [Observability](016-observability.md) | done | Telemetry, metrics, logs |+| 017 | [Operations](017-operations.md) | done | Health, logs, upgrades |+| 018 | [Policies](018-policies.md) | done | Defaults + overrides |+| 019 | [Quality](019-quality.md) | done | Test pyramid coverage |+| 020 | [Security](020-security.md) | done | Threat model, supply-chain |+| 021 | [Testing](021-testing.md) | done | Test strategy per surface |++---++## Quick Reference++### What Headroom Is++- A **context compression proxy** for AI provider APIs+- A **Python package** (`headroom-ai`) with proxy, SDK, and CLI+- A **TypeScript SDK** (`@headroom/sdk`) for Node.js+- A **dashboard** for visualizing savings+- A **learn system** with per-agent plugins++### What Headroom Is Not++- A model provider+- A data store for prompts (by default)+- A logging service (by default)+- A billing service++### Core Guarantees++1. **Never logs prompts by default** — No prompt data leaves the proxy unless an exporter is configured+2. **Never leaves the proxy by default** — All data stays local unless explicitly exported+3. **Composable** — Works alongside existing tools (Claude Code, Copilot, etc.)+4. **Transparent** — Full observability into what's being compressed and why++---++## Change Log++| Version | Date | Changes |+|---------|------|---------|+| 1.0.0-draft | 2026-04-16 | Initial draft — 21 sections outlined |