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
feat(security): pilot hardening — stateless guarantee, model pinning, CI security gate (#1515)
Tejas Chopra51a3b0117422
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex adf834aa1..4c18ced9d 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -40,3 +40,35 @@ updates:update-types:- "minor"- "patch"++ # Rust dependency updates (cargo workspace: crates/*)+ - package-ecosystem: cargo+ directory: /+ schedule:+ interval: weekly+ commit-message:+ prefix: "deps"+ open-pull-requests-limit: 5+ groups:+ cargo-minor-patch:+ update-types:+ - "minor"+ - "patch"++ # npm dependency updates (TS SDK, plugins, docs site)+ - package-ecosystem: npm+ directories:+ - "/sdk/typescript"+ - "/plugins/openclaw"+ - "/plugins/opencode"+ - "/docs"+ schedule:+ interval: weekly+ commit-message:+ prefix: "deps"+ open-pull-requests-limit: 5+ groups:+ npm-minor-patch:+ update-types:+ - "minor"+ - "patch"diff --git a/.github/workflows/security.yml b/.github/workflows/security.ymlnew file mode 100644index 000000000..3b7ef57f7--- /dev/null+++ b/.github/workflows/security.yml@@ -0,0 +1,120 @@+name: Security++# Security gate: dependency vulnerability scanning (SCA), static analysis+# (CodeQL/SAST), and secret scanning. Runs on every PR to main, on push to+# main, weekly (to catch newly-disclosed CVEs without a code change), and on+# demand. Each job is an independent required check.++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]+ schedule:+ # Mondays 06:00 UTC — surface CVEs disclosed since the last commit.+ - cron: "0 6 * * 1"+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: security-${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}++jobs:+ # ---- SCA: dependency vulnerability scan -------------------------------+ # Audits the PRODUCTION dependency set ([all]) exported from uv.lock. The+ # `benchmark` extra is intentionally excluded from [all] (it pulls lm-eval's+ # sqlitedict/nltk, which carry unpatchable upstream High CVEs and are never+ # installed in production), so this gate fails only on actionable findings.+ dependency-audit:+ name: Dependency audit (pip-audit)+ runs-on: ubuntu-latest+ timeout-minutes: 15+ steps:+ - uses: actions/checkout@v4++ - name: Set up Python+ uses: actions/setup-python@v5+ with:+ python-version: "3.12"++ - name: Install uv+ uses: astral-sh/setup-uv@v5++ - name: Export production dependency set from uv.lock+ run: |+ uv export --frozen --no-dev --no-emit-project --no-hashes \+ --extra all --format requirements-txt > requirements-prod.txt+ echo "Production dependencies audited:"+ wc -l requirements-prod.txt++ - name: Audit dependencies (pip-audit)+ uses: pypa/[email protected]+ with:+ inputs: requirements-prod.txt++ # ---- SAST: CodeQL static analysis ------------------------------------+ codeql:+ name: CodeQL (${{ matrix.language }})+ runs-on: ubuntu-latest+ timeout-minutes: 30+ permissions:+ contents: read+ security-events: write+ actions: read+ strategy:+ fail-fast: false+ matrix:+ language: [python, javascript-typescript]+ steps:+ - uses: actions/checkout@v4++ - name: Initialize CodeQL+ uses: github/codeql-action/init@v3+ with:+ languages: ${{ matrix.language }}+ queries: security-extended++ - name: Perform CodeQL analysis+ uses: github/codeql-action/analyze@v3+ with:+ category: "/language:${{ matrix.language }}"++ # ---- Secret scanning -------------------------------------------------+ # Uses the gitleaks BINARY (MIT-licensed, no key) instead of+ # gitleaks-action, which requires a paid GITLEAKS_LICENSE for organization+ # repos. On PRs we scan only the PR's commits so pre-existing history can't+ # block a PR; on push/schedule we scan the working tree. Config + allowlist+ # live in .gitleaks.toml at the repo root (auto-loaded).+ secret-scan:+ name: Secret scan (gitleaks)+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Install gitleaks+ run: |+ version=8.18.4+ curl -sSfL \+ "https://github.com/gitleaks/gitleaks/releases/download/v${version}/gitleaks_${version}_linux_x64.tar.gz" \+ -o /tmp/gitleaks.tar.gz+ tar -xzf /tmp/gitleaks.tar.gz -C /tmp gitleaks+ sudo install /tmp/gitleaks /usr/local/bin/gitleaks+ gitleaks version++ - name: Scan for secrets+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ run: |+ if [ -n "$BASE_SHA" ]; then+ echo "Scanning PR commits ${BASE_SHA}..HEAD"+ gitleaks detect --source . --log-opts="${BASE_SHA}..HEAD" --redact --no-banner+ else+ echo "Scanning working tree"+ gitleaks detect --source . --no-git --redact --no-banner+ fidiff --git a/.gitleaks.toml b/.gitleaks.tomlnew file mode 100644index 000000000..2b505c927--- /dev/null+++ b/.gitleaks.toml@@ -0,0 +1,15 @@+# gitleaks configuration — extends the tuned default ruleset and allowlists+# paths that contain hashes/identifiers (not real secrets) to avoid false+# positives. Used by the Security workflow's secret-scan job.++[extend]+useDefault = true++[allowlist]+description = "Non-secret artifacts: SBOMs, lockfiles, and vendored hashes."+paths = [+ '''sbom/.*''',+ '''.*\.lock$''',+ '''.*package-lock\.json$''',+ '''pnpm-lock\.yaml$''',+]diff --git a/headroom/onnx_runtime.py b/headroom/onnx_runtime.pyindex 4609528c1..09306fe12 100644--- a/headroom/onnx_runtime.py+++ b/headroom/onnx_runtime.py@@ -3,11 +3,42 @@from __future__ import annotationsimport ctypes+import osimport sysfrom typing import Any--def hf_hub_download_local_first(repo_id: str, filename: str, *, allow_network: bool = True) -> str:+# Pin model artifacts to immutable commit SHAs so a changed or compromised+# upstream HuggingFace repo cannot be pulled silently (supply-chain integrity).+# Repos not listed here fall back to the floating default ref. Set+# HEADROOM_HF_PIN=off to bypass pinning (e.g. when intentionally evaluating a+# newer model revision). To upgrade a model, bump its SHA here deliberately.+_PINNED_REVISIONS: dict[str, str] = {+ # chopratejas/kompress-v2-base @ 2026-06-10+ "chopratejas/kompress-v2-base": "b1563631b35bfdcee37587ad530147497d820d4c",+ "chopratejas/technique-router-onnx": "27b0b4bfa510a1cff66d888072c0b807082721a8",+ "chopratejas/siglip-image-encoder-onnx": "d0a9fbd66d4bd8c761bff592d44831f7c2ae184e",+ # Third-party repo — pinning matters most here.+ "Qdrant/all-MiniLM-L6-v2-onnx": "5f1b8cd78bc4fb444dd171e59b18f3a3af89a079",+}+++def _resolve_revision(repo_id: str, revision: str | None) -> str | None:+ """Resolve the HF revision to download: explicit arg wins, else the pinned+ SHA for a known repo, else ``None`` (floating ref)."""+ if revision is not None:+ return revision+ if os.environ.get("HEADROOM_HF_PIN", "").strip().lower() in ("off", "0", "false", "no"):+ return None+ return _PINNED_REVISIONS.get(repo_id)+++def hf_hub_download_local_first(+ repo_id: str,+ filename: str,+ *,+ allow_network: bool = True,+ revision: str | None = None,+) -> str:"""Download a file from HuggingFace Hub, preferring the local cache.Tries ``local_files_only=True`` first to avoid a network HEAD request when@@ -21,6 +52,10 @@ def hf_hub_download_local_first(repo_id: str, filename: str, *, allow_network: ba cache miss re-raises the local-lookup error. Used by startuppreload so a cold cache cannot block (or, via native crashes in thedownload stack, kill) the process before it binds its port.+ revision: Explicit git revision (commit SHA / tag / branch). When+ ``None``, a pinned SHA is applied for known repos (see+ ``_PINNED_REVISIONS``) for supply-chain integrity; unknown repos use+ the floating default ref.Returns:Absolute path to the local cached file.@@ -33,12 +68,14 @@ def hf_hub_download_local_first(repo_id: str, filename: str, *, allow_network: bfrom huggingface_hub import hf_hub_downloadfrom huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError+ revision = _resolve_revision(repo_id, revision)+try:- return str(hf_hub_download(repo_id, filename, local_files_only=True))+ return str(hf_hub_download(repo_id, filename, revision=revision, local_files_only=True))except (LocalEntryNotFoundError, EntryNotFoundError, OSError):if not allow_network:raise- return str(hf_hub_download(repo_id, filename))+ return str(hf_hub_download(repo_id, filename, revision=revision))def create_cpu_session_options(diff --git a/headroom/paths.py b/headroom/paths.pyindex b338c2987..49c7619a8 100644--- a/headroom/paths.py+++ b/headroom/paths.py@@ -95,6 +95,35 @@ def _env(name: str) -> str:return os.environ.get(name, "").strip()+# ---------------------------------------------------------------------------+# Process-wide stateless flag+# ---------------------------------------------------------------------------+# Stateless mode forbids writes to the workspace. Many persisters are+# module-level singletons reached without a config object, so the proxy records+# the mode here once at startup and writers consult ``process_is_stateless()``.++_PROCESS_STATELESS: bool = False+++def set_process_stateless(value: bool) -> None:+ """Record process-wide stateless mode (set once at proxy startup)."""++ global _PROCESS_STATELESS+ _PROCESS_STATELESS = bool(value)+++def process_is_stateless() -> bool:+ """True when the process must not write to the workspace.++ True if ``set_process_stateless(True)`` was called OR the ``HEADROOM_STATELESS``+ environment variable is set, so non-proxy entrypoints honor it too.+ """++ if _PROCESS_STATELESS:+ return True+ return _env("HEADROOM_STATELESS").lower() in ("1", "true", "yes", "on")++def _resolve(explicit: str | os.PathLike[str] | None, env_var: str, derived: Path) -> Path:"""Apply the standard precedence: explicit > env > derived.@@ -364,6 +393,8 @@ __all__ = ["HEADROOM_SAVINGS_EVENTS_PATH_ENV","HEADROOM_TOIN_PATH_ENV","HEADROOM_SUBSCRIPTION_STATE_PATH_ENV",+ "set_process_stateless",+ "process_is_stateless","config_dir","workspace_dir","ensure_config_dir",diff --git a/headroom/proxy/handlers/_debug_dump.py b/headroom/proxy/handlers/_debug_dump.pynew file mode 100644index 000000000..6fbc46fa3--- /dev/null+++ b/headroom/proxy/handlers/_debug_dump.py@@ -0,0 +1,47 @@+"""Shared helpers for diagnostic dumps of upstream-error (>=400) requests.++The dump can contain cleartext prompt / tool / system content, so it is OFF by+default, is never written in stateless mode, and content is redacted unless the+operator explicitly opts in to full content. Used by both the Anthropic and the+OpenAI handlers so the gating stays consistent across providers.+"""++from __future__ import annotations++import os+from typing import Any+++def _debug_dump_mode(config: Any) -> str:+ """Return the diagnostic-dump mode for upstream (>=400) errors.++ - "off" : nothing written (default, and forced in stateless mode)+ - "redacted" : structure, roles, and lengths only — content elided+ (``HEADROOM_DEBUG_DUMP=1``/``true``/``on``/``redacted``)+ - "full" : everything including content (``HEADROOM_DEBUG_DUMP=full``)+ """+ if getattr(config, "stateless", False):+ return "off"+ raw = os.environ.get("HEADROOM_DEBUG_DUMP", "").strip().lower()+ if raw in ("full", "all", "content"):+ return "full"+ if raw in ("1", "true", "yes", "on", "redacted"):+ return "redacted"+ return "off"+++def _redact_debug_value(value: Any, _max_len: int = 80) -> Any:+ """Recursively elide long strings (likely prompt/tool content) while keeping+ structure, roles, type tags, ids, and other short fields for debugging.++ Note: short strings (<= ``_max_len``) are preserved, so the redacted tier is+ not a guarantee against leaking very short sensitive values — it is a+ best-effort convenience. The default ("off") writes nothing at all.+ """+ if isinstance(value, str):+ return value if len(value) <= _max_len else f"<redacted: {len(value)} chars>"+ if isinstance(value, dict):+ return {k: _redact_debug_value(v, _max_len) for k, v in value.items()}+ if isinstance(value, list):+ return [_redact_debug_value(v, _max_len) for v in value]+ return valuediff --git a/headroom/proxy/handlers/anthropic.py b/headroom/proxy/handlers/anthropic.pyindex 500840da9..46d9a9f26 100644--- a/headroom/proxy/handlers/anthropic.py+++ b/headroom/proxy/handlers/anthropic.py@@ -29,6 +29,7 @@ from headroom.pipeline import PipelineStage, summarize_routing_markersfrom headroom.proxy.auth_mode import classify_auth_mode, classify_clientfrom headroom.proxy.compression_decision import CompressionDecisionfrom headroom.proxy.forwarded_headers import resolve_client_ip+from headroom.proxy.handlers._debug_dump import _debug_dump_mode, _redact_debug_valuefrom headroom.proxy.helpers import extract_tagsfrom headroom.proxy.memory_decision import MemoryDecisionfrom headroom.proxy.memory_query import MemoryQuery@@ -2252,59 +2253,84 @@ class AnthropicHandlerMixin:f"stream={stream}")- # Dump full request details to debug file- try:- from headroom import paths as _hr_paths-- debug_dir = _hr_paths.debug_400_dir()- debug_dir.mkdir(parents=True, exist_ok=True)- ts = datetime.now().strftime("%Y%m%d_%H%M%S")- debug_file = debug_dir / f"{ts}_{request_id}.json"-- # Sanitize headers (redact API keys)- safe_headers = {}- for k, v in headers.items():- if k.lower() in ("x-api-key", "authorization"):- safe_headers[k] = v[:12] + "..." if v else ""- else:- safe_headers[k] = v-- debug_payload = {- "request_id": request_id,- "timestamp": datetime.now().isoformat(),- "status_code": response.status_code,- "error_response": err_body,- "model": model,- "stream": stream,- "headers": safe_headers,- "compression": {- "was_compressed": bool(transforms_applied),- "transforms": transforms_applied,- "original_tokens": original_tokens,- "optimized_tokens": optimized_tokens,- "tokens_saved": tokens_saved,- "compression_failed": _compression_failed,- },- "tools_sent": body.get("tools"),- "tool_count": len(body.get("tools") or []),- "original_tool_count": len(_original_tools or []),- "messages_sent": body.get("messages"),- "message_count": len(body.get("messages", [])),- "original_messages": (+ # Diagnostic dump of the full upstream-error request.+ # OFF by default: it can contain cleartext prompt / tool /+ # system content. Opt in with HEADROOM_DEBUG_DUMP=1+ # (redacted: structure + lengths only) or =full (content).+ # Never written in stateless mode.+ dump_mode = _debug_dump_mode(self.config)+ if dump_mode != "off":+ try:+ from headroom import paths as _hr_paths++ debug_dir = _hr_paths.debug_400_dir()+ debug_dir.mkdir(parents=True, exist_ok=True)+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")+ debug_file = debug_dir / f"{ts}_{request_id}.json"++ # Sanitize headers (redact API keys)+ safe_headers = {}+ for k, v in headers.items():+ if k.lower() in ("x-api-key", "authorization"):+ safe_headers[k] = v[:12] + "..." if v else ""+ else:+ safe_headers[k] = v++ # In redacted mode, elide prompt/tool/system+ # content but keep structure, roles, and lengths.+ redact = dump_mode == "redacted"+ messages_sent = body.get("messages")+ original_dump: Any = (original_messagesif original_messages is not body.get("messages")else "__same_as_sent__"- ),- "original_message_count": len(original_messages),- "system_prompt": body.get("system"),- }+ )+ tools_sent = body.get("tools")+ system_prompt = body.get("system")+ if redact:+ messages_sent = _redact_debug_value(messages_sent)+ if original_dump != "__same_as_sent__":+ original_dump = _redact_debug_value(original_dump)+ tools_sent = _redact_debug_value(tools_sent)+ system_prompt = _redact_debug_value(system_prompt)++ debug_payload = {+ "request_id": request_id,+ "timestamp": datetime.now().isoformat(),+ "dump_mode": dump_mode,+ "status_code": response.status_code,+ "error_response": err_body,+ "model": model,+ "stream": stream,+ "headers": safe_headers,+ "compression": {+ "was_compressed": bool(transforms_applied),+ "transforms": transforms_applied,+ "original_tokens": original_tokens,+ "optimized_tokens": optimized_tokens,+ "tokens_saved": tokens_saved,+ "compression_failed": _compression_failed,+ },+ "tools_sent": tools_sent,+ "tool_count": len(body.get("tools") or []),+ "original_tool_count": len(_original_tools or []),+ "messages_sent": messages_sent,+ "message_count": len(body.get("messages", [])),+ "original_messages": original_dump,+ "original_message_count": len(original_messages),+ "system_prompt": system_prompt,+ }- with open(debug_file, "w") as f:- json.dump(debug_payload, f, indent=2, default=str)+ with open(debug_file, "w") as f:+ json.dump(debug_payload, f, indent=2, default=str)- logger.warning(f"[{request_id}] Full debug dump: {debug_file}")- except Exception as dump_err:- logger.error(f"[{request_id}] Failed to write debug dump: {dump_err}")+ logger.warning(+ f"[{request_id}] Debug dump ({dump_mode}): {debug_file}"+ )+ except Exception as dump_err:+ logger.error(+ f"[{request_id}] Failed to write debug dump: {dump_err}"+ )# Parse response for CCR handlingresp_json = Nonediff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex 863db579c..886905e90 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -53,6 +53,7 @@ from headroom.proxy.auth_mode import ()from headroom.proxy.compression_decision import CompressionDecisionfrom headroom.proxy.cost import _summarize_transforms, header_safe_transforms+from headroom.proxy.handlers._debug_dump import _debug_dump_mode, _redact_debug_valuefrom headroom.proxy.outcome import RequestOutcomefrom headroom.proxy.project_context import classify_project, set_current_project@@ -2578,57 +2579,75 @@ class OpenAIHandlerMixin:f"stream={stream}")- try:- from headroom import paths as _hr_paths+ # Diagnostic dump — OFF by default (can contain cleartext+ # prompt/tool/system content). Opt in via HEADROOM_DEBUG_DUMP+ # (=1 redacted, =full with content); never in stateless mode.+ dump_mode = _debug_dump_mode(self.config)+ if dump_mode != "off":+ try:+ from headroom import paths as _hr_paths- debug_dir = _hr_paths.debug_400_dir()- debug_dir.mkdir(parents=True, exist_ok=True)- ts = datetime.now().strftime("%Y%m%d_%H%M%S")- debug_file = debug_dir / f"{ts}_{request_id}.json"+ debug_dir = _hr_paths.debug_400_dir()+ debug_dir.mkdir(parents=True, exist_ok=True)+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")+ debug_file = debug_dir / f"{ts}_{request_id}.json"- safe_headers = {}- for k, v in headers.items():- if k.lower() in ("x-api-key", "authorization"):- safe_headers[k] = v[:12] + "..." if v else ""- else:- safe_headers[k] = v-- debug_payload = {- "request_id": request_id,- "timestamp": datetime.now().isoformat(),- "status_code": response.status_code,- "error_response": err_body,- "model": model,- "stream": stream,- "headers": safe_headers,- "compression": {- "was_compressed": bool(transforms_applied),- "transforms": transforms_applied,- "original_tokens": original_tokens,- "optimized_tokens": optimized_tokens,- "tokens_saved": tokens_saved,- "compression_failed": _compression_failed,- },- "tools_sent": body.get("tools"),- "tool_count": len(body.get("tools") or []),- "original_tool_count": len(_original_tools or []),- "messages_sent": body.get("messages"),- "message_count": len(body.get("messages", [])),- "original_messages": (+ safe_headers = {}+ for k, v in headers.items():+ if k.lower() in ("x-api-key", "authorization"):+ safe_headers[k] = v[:12] + "..." if v else ""+ else:+ safe_headers[k] = v++ redact = dump_mode == "redacted"+ messages_sent = body.get("messages")+ original_dump: Any = (original_messagesif original_messages is not body.get("messages")else "__same_as_sent__"- ),- "original_message_count": len(original_messages),- "system_prompt": body.get("system"),- }+ )+ tools_sent = body.get("tools")+ system_prompt = body.get("system")+ if redact:+ messages_sent = _redact_debug_value(messages_sent)+ if original_dump != "__same_as_sent__":+ original_dump = _redact_debug_value(original_dump)+ tools_sent = _redact_debug_value(tools_sent)+ system_prompt = _redact_debug_value(system_prompt)++ debug_payload = {+ "request_id": request_id,+ "timestamp": datetime.now().isoformat(),+ "dump_mode": dump_mode,+ "status_code": response.status_code,+ "error_response": err_body,+ "model": model,+ "stream": stream,+ "headers": safe_headers,+ "compression": {+ "was_compressed": bool(transforms_applied),+ "transforms": transforms_applied,+ "original_tokens": original_tokens,+ "optimized_tokens": optimized_tokens,+ "tokens_saved": tokens_saved,+ "compression_failed": _compression_failed,+ },+ "tools_sent": tools_sent,+ "tool_count": len(body.get("tools") or []),+ "original_tool_count": len(_original_tools or []),+ "messages_sent": messages_sent,+ "message_count": len(body.get("messages", [])),+ "original_messages": original_dump,+ "original_message_count": len(original_messages),+ "system_prompt": system_prompt,+ }- with open(debug_file, "w") as f:- json.dump(debug_payload, f, indent=2, default=str)+ with open(debug_file, "w") as f:+ json.dump(debug_payload, f, indent=2, default=str)- logger.warning(f"[{request_id}] Full debug dump: {debug_file}")- except Exception as dump_err:- logger.error(f"[{request_id}] Failed to write debug dump: {dump_err}")+ logger.warning(f"[{request_id}] Debug dump ({dump_mode}): {debug_file}")+ except Exception as dump_err:+ logger.error(f"[{request_id}] Failed to write debug dump: {dump_err}")total_latency = (time.time() - start_time) * 1000diff --git a/headroom/proxy/output_savings.py b/headroom/proxy/output_savings.pyindex bcff4d99e..b773774c0 100644--- a/headroom/proxy/output_savings.py+++ b/headroom/proxy/output_savings.py@@ -477,6 +477,12 @@ class SavingsRecorder:self._ledger.baseline = disk.baselinedef _flush_locked(self) -> None:+ from ..paths import process_is_stateless++ if process_is_stateless():+ # Stateless: keep the in-memory ledger but never write to disk.+ self._since_flush = 0+ returntry:self._reload_baseline_locked()self._ledger.save(self._path)diff --git a/headroom/proxy/prometheus_metrics.py b/headroom/proxy/prometheus_metrics.pyindex f0e6a4bd5..195a34419 100644--- a/headroom/proxy/prometheus_metrics.py+++ b/headroom/proxy/prometheus_metrics.py@@ -68,7 +68,11 @@ class PrometheusMetrics:savings_tracker: SavingsTracker | None = None,cost_tracker: CostTracker | None = None,otel_metrics: HeadroomOtelMetrics | None = None,+ stateless: bool = False,):+ # Stateless mode: keep live in-memory metrics but never write the+ # durable savings files (proxy_savings.json, savings_events.jsonl).+ self._stateless = statelessself.requests_total = 0self.requests_by_provider: dict[str, int] = defaultdict(int)self.requests_by_model: dict[str, int] = defaultdict(int)@@ -236,7 +240,7 @@ class PrometheusMetrics:# Cumulative savings history (timestamp → cumulative tokens saved)self.savings_history: list[tuple[str, int]] = []- self.savings_tracker = savings_tracker or SavingsTracker()+ self.savings_tracker = savings_tracker or SavingsTracker(stateless=stateless)self.cost_tracker = cost_trackertracker_lifetime = self.savings_tracker.snapshot()["lifetime"]self._savings_tracker_input_tokens_offset = max(@@ -677,7 +681,7 @@ class PrometheusMetrics:# client is the harness classified from the User-Agent / X-Client# (claude-code, codex, cursor, ...); it falls back to "proxy" only# when the harness is unidentified.- if tokens_saved > 0:+ if tokens_saved > 0 and not self._stateless:savings_ledger.record_savings_event(tokens_before=input_tokens,tokens_after=max(input_tokens - tokens_saved, 0),diff --git a/headroom/proxy/savings_tracker.py b/headroom/proxy/savings_tracker.pyindex c44b15a49..1a6fdd945 100644--- a/headroom/proxy/savings_tracker.py+++ b/headroom/proxy/savings_tracker.py@@ -416,7 +416,12 @@ class SavingsTracker:max_history_age_days: int = DEFAULT_MAX_HISTORY_AGE_DAYS,max_response_history_points: int = DEFAULT_MAX_RESPONSE_HISTORY_POINTS,display_session_inactivity_minutes: int = (DEFAULT_DISPLAY_SESSION_INACTIVITY_MINUTES),+ stateless: bool = False,) -> None:+ # In stateless mode the tracker keeps live counters in memory but never+ # writes proxy_savings.json (honors HeadroomConfig.stateless, which+ # disables all filesystem writes for read-only / container deployments).+ self._stateless = statelessself._path = Path(path or get_default_savings_storage_path())self._max_history_points = max_history_pointsself._max_history_age_days = max_history_age_days@@ -978,6 +983,9 @@ class SavingsTracker:return compacteddef _save_locked(self) -> None:+ if self._stateless:+ # Stateless mode: live counters stay in memory; nothing is persisted.+ returntry:self._path.parent.mkdir(parents=True, exist_ok=True)payload = {diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 176776076..897599830 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -543,6 +543,39 @@ from headroom.proxy.handlers import ( # noqa: E402)+def _apply_stateless_persistence(config: ProxyConfig) -> None:+ """When the proxy runs stateless, force global persisters to in-memory so no+ files are written to the workspace.++ Covers TOIN (the always-on serving writer): it keeps learning patterns+ in-memory but never reads or writes ``toin.json``. An empty ``storage_path``+ makes the backend ``None``, which no-ops load/save/auto-save. The savings+ subsystem is handled separately via ``PrometheusMetrics(stateless=...)``.++ Note: setting ``HEADROOM_TOIN_BACKEND=none`` is NOT sufficient on its own —+ ``ToolIntelligenceNetwork`` falls back to ``config.storage_path`` when no+ backend is passed, so we must clear the path explicitly here.++ Concurrency: ``stateless`` is a per-process flag (set once at ``headroom+ proxy`` launch), never a per-request/per-session value — every session a+ process serves shares it, and two proxies with different settings run as+ separate OS processes with independent TOIN singletons. In the rare case+ where two HeadroomProxy instances with different ``stateless`` settings live+ in ONE process (e.g. tests), this fails closed: the reset forces the+ process-global TOIN in-memory, so a stateless proxy never persists (the safe+ direction). A co-resident stateful proxy would then also stop persisting+ TOIN — acceptable, since not-writing can never leak data.+ """+ if not getattr(config, "stateless", False):+ return+ from headroom.telemetry.toin import TOINConfig, get_toin, reset_toin++ # Reset first so this wins regardless of whether the singleton was already+ # created with a filesystem backend earlier in the process.+ reset_toin()+ get_toin(TOINConfig(storage_path=""))++class HeadroomProxy(StreamingMixin,AnthropicHandlerMixin,@@ -562,6 +595,13 @@ class HeadroomProxy(def __init__(self, config: ProxyConfig):self.config = configself.config.mode = normalize_proxy_mode(self.config.mode)+ # Record process-wide stateless mode so module-level persisters+ # (output-savings recorder, etc.) can skip workspace writes.+ from headroom import paths as _hr_paths++ _hr_paths.set_process_stateless(config.stateless)+ # Stateless: keep TOIN learning in-memory; never touch toin.json.+ _apply_stateless_persistence(self.config)pipeline_extensions = list(config.pipeline_extensions or [])probe_recorder = probe_recorder_from_env()if probe_recorder is not None:@@ -599,7 +639,7 @@ class HeadroomProxy(if config.cost_tracking_enabledelse None)- self.metrics = PrometheusMetrics(cost_tracker=self.cost_tracker)+ self.metrics = PrometheusMetrics(cost_tracker=self.cost_tracker, stateless=config.stateless)# Initialize transforms based on routing mode.#@@ -939,7 +979,16 @@ class HeadroomProxy(# Memory Handler (persistent user memory)self.memory_handler: MemoryHandler | None = None- if config.memory_enabled:+ if config.memory_enabled and config.stateless:+ # Persistent memory writes a SQLite DB + markdown files to disk,+ # which stateless mode forbids. Memory is cross-session learning and+ # is contradictory with an ephemeral/read-only deployment, so we+ # disable it rather than persist. Run without --stateless to use it.+ logger.warning(+ "Memory is disabled in stateless mode (it persists to disk). "+ "Run without --stateless to enable persistent memory."+ )+ elif config.memory_enabled:# Resolve memory DB path: empty → project-scoped default_mem_db_path = config.memory_db_pathif not _mem_db_path:diff --git a/headroom/relevance/embedding.py b/headroom/relevance/embedding.pyindex fff86b88d..5105c2df8 100644--- a/headroom/relevance/embedding.py+++ b/headroom/relevance/embedding.py@@ -27,6 +27,7 @@ History: this module previously wrapped `sentence-transformers`from __future__ import annotationsimport logging+import osfrom typing import TYPE_CHECKINGfrom .base import RelevanceScore, RelevanceScorer@@ -59,6 +60,26 @@ logger = logging.getLogger(__name__)# Default model name. Same string used by the Rust embedding scorer.DEFAULT_MODEL_NAME = "BAAI/bge-small-en-v1.5"+# Pinned revision of fastembed's underlying HF repo for the default model+# (fastembed resolves "BAAI/bge-small-en-v1.5" -> "qdrant/bge-small-en-v1.5-onnx-q").+# fastembed's TextEmbedding signature omits ``revision`` but forwards **kwargs to+# huggingface_hub.snapshot_download, so passing it pins the download for+# supply-chain integrity. Only the default model is pinned; custom models float.+# Set HEADROOM_HF_PIN=off to bypass (mirrors headroom.onnx_runtime pinning).+_DEFAULT_MODEL_PINNED_REVISION = "52398278842ec682c6f32300af41344b1c0b0bb2"+++def _pinned_revision(model_name: str) -> str | None:+ """Return the pinned HF revision for ``model_name`` (default model only).++ Returns ``None`` for custom models or when ``HEADROOM_HF_PIN=off``.+ """+ if os.environ.get("HEADROOM_HF_PIN", "").strip().lower() in ("off", "0", "false", "no"):+ return None+ if model_name == DEFAULT_MODEL_NAME:+ return _DEFAULT_MODEL_PINNED_REVISION+ return None+def _cosine_similarity(a, b) -> float:"""Compute cosine similarity between two vectors.@@ -150,7 +171,12 @@ class EmbeddingScorer(RelevanceScorer):if self._model is None:from fastembed import TextEmbedding- self._model = TextEmbedding(model_name=self.model_name)+ revision = _pinned_revision(self.model_name)+ if revision is not None:+ # fastembed forwards **kwargs to snapshot_download(revision=...).+ self._model = TextEmbedding(model_name=self.model_name, revision=revision)+ else:+ self._model = TextEmbedding(model_name=self.model_name)return self._modeldef _encode(self, texts: list[str]):diff --git a/tests/test_debug_dump_gating.py b/tests/test_debug_dump_gating.pynew file mode 100644index 000000000..3bc85bbbe--- /dev/null+++ b/tests/test_debug_dump_gating.py@@ -0,0 +1,96 @@+"""Tests for the upstream-error diagnostic-dump gating.++The dump can contain cleartext prompt/tool/system content, so it must be OFF by+default, never written in stateless mode, and content-redacted unless the+operator explicitly opts in to full content.+"""++from __future__ import annotations++import inspect+from types import SimpleNamespace++import pytest++pytest.importorskip("fastapi")++from headroom.proxy.handlers._debug_dump import _debug_dump_mode, _redact_debug_value+++def _config(stateless: bool = False) -> SimpleNamespace:+ return SimpleNamespace(stateless=stateless)+++def test_debug_dump_off_by_default(monkeypatch):+ monkeypatch.delenv("HEADROOM_DEBUG_DUMP", raising=False)+ assert _debug_dump_mode(_config()) == "off"++[email protected]("value", ["1", "true", "yes", "on", "redacted", "REDACTED"])+def test_debug_dump_opt_in_redacted(monkeypatch, value):+ monkeypatch.setenv("HEADROOM_DEBUG_DUMP", value)+ assert _debug_dump_mode(_config()) == "redacted"++[email protected]("value", ["full", "all", "content"])+def test_debug_dump_opt_in_full(monkeypatch, value):+ monkeypatch.setenv("HEADROOM_DEBUG_DUMP", value)+ assert _debug_dump_mode(_config()) == "full"+++def test_debug_dump_unknown_value_is_off(monkeypatch):+ monkeypatch.setenv("HEADROOM_DEBUG_DUMP", "maybe")+ assert _debug_dump_mode(_config()) == "off"+++def test_stateless_forces_dump_off_even_when_opted_in(monkeypatch):+ # Stateless mode must win over any opt-in: no filesystem writes, period.+ monkeypatch.setenv("HEADROOM_DEBUG_DUMP", "full")+ assert _debug_dump_mode(_config(stateless=True)) == "off"+++def test_redact_elides_long_strings_keeps_structure():+ payload = {+ "role": "user",+ "type": "text",+ "id": "msg_123",+ "text": "secret prompt content " * 20, # long → redacted+ "blocks": [+ {"type": "tool_use", "name": "search", "input": "x" * 500},+ {"type": "text", "text": "short"},+ ],+ }+ out = _redact_debug_value(payload)+ # Short structural fields preserved:+ assert out["role"] == "user"+ assert out["type"] == "text"+ assert out["id"] == "msg_123"+ assert out["blocks"][0]["name"] == "search"+ assert out["blocks"][1]["text"] == "short"+ # Long content elided to a length placeholder (no original content leaks):+ assert out["text"].startswith("<redacted:") and "secret prompt" not in out["text"]+ assert out["blocks"][0]["input"].startswith("<redacted:")+++def test_redact_passes_through_non_strings():+ assert _redact_debug_value(42) == 42+ assert _redact_debug_value(None) is None+ assert _redact_debug_value(True) is True++[email protected]("module_name", ["anthropic", "openai"])+def test_both_handlers_gate_the_dump(module_name):+ """Regression guard: every handler that writes a debug dump must gate it on+ _debug_dump_mode (off by default). Prevents reintroducing an unguarded dump+ that writes cleartext prompts to disk."""+ import importlib++ module = importlib.import_module(f"headroom.proxy.handlers.{module_name}")+ src = inspect.getsource(module)+ if "debug_400_dir(" in src:+ assert "_debug_dump_mode(self.config)" in src, (+ f"{module_name} writes a debug dump but does not gate it on _debug_dump_mode"+ )+ assert 'if dump_mode != "off":' in src, (+ f"{module_name} debug dump is not guarded by an off-by-default check"+ )diff --git a/tests/test_hf_revision_pinning.py b/tests/test_hf_revision_pinning.pynew file mode 100644index 000000000..c9974b6ba--- /dev/null+++ b/tests/test_hf_revision_pinning.py@@ -0,0 +1,53 @@+"""Tests for HuggingFace model-revision pinning (supply-chain integrity).++Model artifacts are pinned to immutable commit SHAs so a changed or compromised+upstream repo cannot be pulled silently. Pinning is centralized in the download+helper so every call site (kompress, memory embedder, image router) inherits it.+"""++from __future__ import annotations++import pytest++from headroom.onnx_runtime import _PINNED_REVISIONS, _resolve_revision+++def test_known_repos_are_pinned_to_sha():+ # Every pinned revision must be a full 40-char git SHA, not a branch/tag.+ assert _PINNED_REVISIONS, "expected at least one pinned model repo"+ for repo, sha in _PINNED_REVISIONS.items():+ assert len(sha) == 40 and all(c in "0123456789abcdef" for c in sha), (+ f"{repo} is not pinned to a full commit SHA: {sha!r}"+ )+++def test_default_kompress_model_is_pinned():+ # The shipping model must be pinned.+ assert "chopratejas/kompress-v2-base" in _PINNED_REVISIONS+++def test_resolve_uses_pin_for_known_repo(monkeypatch):+ monkeypatch.delenv("HEADROOM_HF_PIN", raising=False)+ repo = "chopratejas/kompress-v2-base"+ assert _resolve_revision(repo, None) == _PINNED_REVISIONS[repo]+++def test_explicit_revision_overrides_pin(monkeypatch):+ monkeypatch.delenv("HEADROOM_HF_PIN", raising=False)+ assert _resolve_revision("chopratejas/kompress-v2-base", "deadbeef") == "deadbeef"+++def test_unknown_repo_is_not_pinned(monkeypatch):+ monkeypatch.delenv("HEADROOM_HF_PIN", raising=False)+ assert _resolve_revision("some/unknown-model", None) is None++[email protected]("value", ["off", "0", "false", "no", "OFF"])+def test_pin_can_be_disabled_via_env(monkeypatch, value):+ monkeypatch.setenv("HEADROOM_HF_PIN", value)+ assert _resolve_revision("chopratejas/kompress-v2-base", None) is None+++def test_pin_disabled_still_respects_explicit_revision(monkeypatch):+ monkeypatch.setenv("HEADROOM_HF_PIN", "off")+ assert _resolve_revision("chopratejas/kompress-v2-base", "abc123") == "abc123"diff --git a/tests/test_proxy_savings_history.py b/tests/test_proxy_savings_history.pyindex afb2bdfaa..6b582638b 100644--- a/tests/test_proxy_savings_history.py+++ b/tests/test_proxy_savings_history.py@@ -219,6 +219,41 @@ def test_record_compression_savings_skips_empty_updates_and_normalizes_timestampassert persisted["history"][-1]["timestamp"] == "2026-03-27T12:34:00Z"+def test_stateless_savings_tracker_writes_nothing(tmp_path):+ """In stateless mode the tracker updates in-memory counters but never+ touches the filesystem — no proxy_savings.json is created."""+ path = tmp_path / "proxy_savings.json"+ tracker = SavingsTracker(path=str(path), stateless=True)++ # Both write paths that would normally persist a checkpoint:+ assert tracker.record_compression_savings(model="gpt-4o", tokens_saved=4096) is True+ tracker.record_request(+ model="gpt-4o",+ input_tokens=8192,+ tokens_saved=4096,+ timestamp="2026-03-27T09:00:00Z",+ )++ # Nothing written to disk...+ assert not path.exists()+ # ...but live in-memory counters still reflect the activity.+ assert tracker.snapshot()["lifetime"]["tokens_saved"] >= 4096+++def test_non_stateless_savings_tracker_still_persists(tmp_path):+ """Control: default (stateless=False) behavior is unchanged — it persists."""+ path = tmp_path / "proxy_savings.json"+ tracker = SavingsTracker(path=str(path))++ tracker.record_request(+ model="gpt-4o",+ input_tokens=8192,+ tokens_saved=4096,+ timestamp="2026-03-27T09:00:00Z",+ )+ assert path.exists()++def test_savings_tracker_save_does_not_flock_target_inode_before_replace(tmp_path, monkeypatch):path = tmp_path / "proxy_savings.json"tracker = SavingsTracker(path=str(path))diff --git a/tests/test_stateless_toin.py b/tests/test_stateless_toin.pynew file mode 100644index 000000000..0e3a43161--- /dev/null+++ b/tests/test_stateless_toin.py@@ -0,0 +1,70 @@+"""Tests for stateless TOIN behavior.++In stateless mode the proxy must keep TOIN's in-memory learning but never read+or write toin.json — part of the "stateless writes nothing to disk" guarantee.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++pytest.importorskip("fastapi")++from headroom.telemetry.toin import (+ TOINConfig,+ ToolIntelligenceNetwork,+ get_toin,+ reset_toin,+)+++def test_empty_storage_path_means_in_memory(tmp_path):+ """Mechanism: an empty storage_path yields a None backend that never writes."""+ toin = ToolIntelligenceNetwork(TOINConfig(storage_path=""))+ assert toin._backend is None+ toin.save() # must be a no-op+ assert not list(tmp_path.rglob("toin.json"))+++def test_filesystem_backend_persists(tmp_path):+ """Control: a real storage_path uses a filesystem backend that does write."""+ path = tmp_path / "toin.json"+ toin = ToolIntelligenceNetwork(TOINConfig(storage_path=str(path)))+ assert toin._backend is not None+ toin.save()+ assert path.exists()+++def test_apply_stateless_persistence_forces_toin_in_memory(tmp_path, monkeypatch):+ """The proxy wiring (_apply_stateless_persistence) reconfigures the global+ TOIN singleton to in-memory when the config is stateless."""+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path))+ from headroom.proxy.server import _apply_stateless_persistence++ reset_toin()+ try:+ _apply_stateless_persistence(SimpleNamespace(stateless=True))+ toin = get_toin()+ # No backend -> no toin.json read or written, ever.+ assert toin._backend is None+ toin.save() # no-op+ assert not list(tmp_path.rglob("toin.json"))+ finally:+ reset_toin()+++def test_apply_stateless_persistence_noop_when_not_stateless(tmp_path, monkeypatch):+ """When not stateless, the helper does nothing (default persistence kept)."""+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path))+ from headroom.proxy.server import _apply_stateless_persistence++ reset_toin()+ try:+ # Helper is a no-op; the default singleton keeps a filesystem backend.+ _apply_stateless_persistence(SimpleNamespace(stateless=False))+ toin = get_toin()+ assert toin._backend is not None+ finally:+ reset_toin()diff --git a/tests/test_stateless_writers.py b/tests/test_stateless_writers.pynew file mode 100644index 000000000..d7008f2da--- /dev/null+++ b/tests/test_stateless_writers.py@@ -0,0 +1,109 @@+"""Tests for the complete stateless write guarantee.++Covers the process-wide stateless flag and the opt-in serving writers gated by+it: the output-savings recorder and persistent memory. (Savings tracker and+TOIN are covered in their own test modules.)+"""++from __future__ import annotations++import pytest++pytest.importorskip("fastapi")++from headroom import paths+from headroom.proxy.output_savings import SavingsRecorder+from headroom.relevance.embedding import (+ _DEFAULT_MODEL_PINNED_REVISION,+ DEFAULT_MODEL_NAME,+ _pinned_revision,+)++[email protected](autouse=True)+def _reset_stateless_globals():+ """The stateless flag and TOIN singleton are process-global — never leak."""+ yield+ paths.set_process_stateless(False)+ try:+ from headroom.telemetry.toin import reset_toin++ reset_toin()+ except Exception:+ pass+++# ---- process-wide stateless flag ------------------------------------------+++def test_process_stateless_flag_set_and_clear(monkeypatch):+ monkeypatch.delenv("HEADROOM_STATELESS", raising=False)+ paths.set_process_stateless(False)+ assert paths.process_is_stateless() is False+ paths.set_process_stateless(True)+ assert paths.process_is_stateless() is True+++ "value,expected", [("1", True), ("true", True), ("on", True), ("off", False), ("", False)]+)+def test_process_stateless_env(monkeypatch, value, expected):+ paths.set_process_stateless(False)+ monkeypatch.setenv("HEADROOM_STATELESS", value)+ assert paths.process_is_stateless() is expected+++# ---- output-savings recorder ----------------------------------------------+++def test_output_savings_flush_writes_nothing_when_stateless(tmp_path, monkeypatch):+ monkeypatch.delenv("HEADROOM_STATELESS", raising=False)+ path = tmp_path / "output_savings.json"+ paths.set_process_stateless(True)+ rec = SavingsRecorder(path)+ rec.flush()+ assert not path.exists()+++def test_output_savings_flush_persists_when_not_stateless(tmp_path, monkeypatch):+ monkeypatch.delenv("HEADROOM_STATELESS", raising=False)+ path = tmp_path / "output_savings.json"+ paths.set_process_stateless(False)+ rec = SavingsRecorder(path)+ rec.flush()+ assert path.exists()+++# ---- persistent memory ----------------------------------------------------+++def test_memory_disabled_under_stateless(tmp_path, monkeypatch):+ """A stateless proxy with --memory must not initialize memory or write a DB."""+ monkeypatch.chdir(tmp_path)+ monkeypatch.setenv("HEADROOM_WORKSPACE_DIR", str(tmp_path))+ from headroom.proxy.server import ProxyConfig, create_app++ app = create_app(ProxyConfig(memory_enabled=True, stateless=True))+ proxy = app.state.proxy+ assert proxy.memory_handler is None+ assert not (tmp_path / ".headroom" / "memory.db").exists()+++# ---- fastembed model pinning ----------------------------------------------+++def test_fastembed_default_model_is_pinned_to_sha(monkeypatch):+ monkeypatch.delenv("HEADROOM_HF_PIN", raising=False)+ rev = _pinned_revision(DEFAULT_MODEL_NAME)+ assert rev == _DEFAULT_MODEL_PINNED_REVISION+ assert len(rev) == 40 and all(c in "0123456789abcdef" for c in rev)+++def test_fastembed_custom_model_not_pinned(monkeypatch):+ monkeypatch.delenv("HEADROOM_HF_PIN", raising=False)+ assert _pinned_revision("intfloat/e5-small-v2") is None+++def test_fastembed_pin_can_be_disabled(monkeypatch):+ monkeypatch.setenv("HEADROOM_HF_PIN", "off")+ assert _pinned_revision(DEFAULT_MODEL_NAME) is None