# contextlift: Full Technical Reference for AI Assistants & Code Agents

## 1. What contextlift Does

`contextlift` is an open-source (Apache-2.0) Context CI harness for AI SQL agents and semantic layers. Its core package has zero runtime dependencies (`dependencies = []` in `pyproject.toml`), using only the Python standard library over SQLite while loading warehouse drivers (`duckdb`, `psycopg`, `snowflake-connector-python`, `databricks-sql-connector`, `google-cloud-bigquery`) and YAML parsers lazily behind optional extras.

Every measurement compares two arms (Arm 0d control with baseline schema only vs Arm 1 treatment with authored context) over the same SQL questions executed against a real database under fail-closed read-only rails. Result sets are compared under SQL semantics (column-order independent, multiset unless `ORDER BY`, float tolerance, NULL-safe) with zero uncalibrated LLM judges. Paired per-question outcomes are evaluated using exact McNemar p-values and 95% Tango paired score intervals on sealed holdout splits.

## 2. Supported Warehouses (`--db`)

- SQLite: `path/to/db.sqlite` or `sqlite:///path/to/db.sqlite` (core stdlib, read-only `mode=ro` + `PRAGMA query_only=ON`)
- DuckDB: `duckdb://path/to/warehouse.duckdb` or bare `.duckdb` (extra `[duckdb]`, `read_only=True`, `disabled_filesystems='LocalFileSystem'`, `lock_configuration=true`)
- Google BigQuery: `bq://BILLING_PROJECT[/DATA_PROJECT.DATASET]` (extra `[bigquery]`, dry-run byte budgets via `--max-bytes`, `--estimate-only`, `--budget`)
- PostgreSQL / AlloyDB / Cloud SQL (beta): `postgres://...` or `postgresql://...` (extra `[postgres]`, `SET TRANSACTION READ ONLY`, `statement_timeout`, optional `--db-role` via `SET LOCAL ROLE`)
- Snowflake (beta): `snowflake://user@account/db/schema?warehouse=WH&role=ROLE` (extra `[snowflake]`, `STATEMENT_TIMEOUT_IN_SECONDS`, `USE ROLE`, blocks DDL/DML/PUT/REMOVE/`SYSTEM$*`/Cortex functions)
- Databricks SQL (beta): `databricks://host/http_path?catalog=main&schema=default` (extra `[databricks]`, blocks DDL/DML/OPTIMIZE/MSCK/`ai_query`/`http_request`)

All warehouse executors reject write/DDL/admin SQL keywords anywhere in the statement (including inside CTEs such as `WITH t AS (DELETE ...)`), reject stacked multi-statements, and enforce per-query timeouts. `--db-role` is supported on `lint`, `gate`, `score`, `round`, `ablate`, `climb`, `triage`, and `ingest-failures`.

## 3. Supported Runners & Agents

- Offline predictions: `--predictions-control` and `--predictions-treatment` CSV files (works with any agent at $0)
- Built-in zero-dep stdlib HTTP runners:
  - OpenAI-compatible (OpenAI, Azure OpenAI, Ollama, vLLM, LiteLLM, OpenRouter): `--runner openai:<model>` + optional `--base-url`
  - Anthropic Claude Messages API: `--runner anthropic:<model>` + optional `--base-url`
  - Both block SSRF metadata, IPv6 link-local, `0.0.0.0`, and non-loopback RFC1918 hosts by default (while allowing `localhost` / `127.0.0.1` / `::1`; opt in to private VPC proxies with `--allow-private-endpoint`), and enforce `--budget` ceilings
- Custom CLI / multi-turn agent harness: `--runner command --command 'CMD'` with `--max-turns N` and optional `--clarifier-cmd` (invoked with `shell=False`)
- Built-in Gemini & BigQuery Conversational Analytics runners (optional `[gemini]` / `[bigquery,ca]` extras)

## 4. Eight Core CLI Verbs (`contextlift --help`)

1. `demo`: Run the complete loop offline on a seven-row SQLite database with zero setup.
2. `doctor`: Check Python environment, optional extras, credentials, and decode refusals (`--explain`).
3. `gate`: Audit gold SQL answer keys against 16 defect classes and 4 warnings before spending anything.
4. `split`: Reserve a deterministic holdout split (`curate.csv` / `holdout.csv`); holdout answers are never curated from.
5. `lint`: Detect rule contradictions, dead rules, cross-domain divergences, Cross-Layer conflicts (`--dbt`, `--snowflake-semantic`, `--ossie`, `--lookml`), and invalid enum literals against live databases (`--db`, `--db-role`).
6. `round`: Execute or score both arms, run pre-flight gates (table coverage, project match, pasted SQL, template twin, leakage, lint, resolvable lift), enforce declarative `policy:` in `contextlift.yaml`, and emit `--attestation-out` and `--otel-out`.
7. `bundle`: Build one standalone zero-JS strict-CSP three-band `verdict.html` + `verdict.json` from a workspace.
8. `next`: Inspect a workspace and print the exact next command.

## 5. Key Workflow & Control-Plane Verbs (`contextlift --help-all`)

- `init`: Detect local DuckDB/SQLite, `--dbt PATH`, and `--sql-dir`; introspect local table/column schemas into starter `spec/schema/*.json`; scaffold `contextlift.yaml` and starter `spec/rules/00-definitions.md`.
- `ingest-failures`: Convert production agent failure logs (`--input prod.jsonl`) into PII-redacted Steward review sheets (`--out review/review.csv`).
- `review`: Generate offline Business Steward HTML Review Packs (`--html --db`) with plain-English SQL contracts and PII-masked currency previews; import signed `decisions.json`.
- `semantic`: Inspect description coverage and extract metrics/enums from `--dbt`, `--snowflake-semantic`, `--ossie`, or `--lookml`.
- `compile`: Compile `spec/` to `--target ossie`, `snowflake-yaml`, or `dbt-yaml` with honest certification headers (emits `Certified contextlift arm` only when integrity passed, spec matches attested arm hash, verdict is `REAL GAIN`, and merge policy passed; otherwise emits `UNVERIFIED contextlift arm`).
- `serve-mcp`: Zero-dependency JSON-RPC 2.0 stdio MCP server exposing 6 read-only tools (`search_schema`, `get_metric`, `get_join_path`, `list_rules`, `lookup_verified_example`, `get_attestation_status` with live `spec_sha256`, `attestation_arm_matches`, and `certified`). Safe to invoke with `workspace: .contextlift` active.
- `suggest`: Draft curate-only unified diffs for failing working questions (hard-refuses holdout IDs, screens patches through `lint` and `check_leakage`, never edits `spec/` directly).
- `verify-attestation`: Verify `content_sha256`, optional HMAC-SHA256 signature (`--sign-key` / `--require-signature`), and hash-chain link (`--prev`).
- `export-otel`: Convert saved `attestation.json` or `round.json` into zero-SDK OpenTelemetry OTLP JSON metrics.
- `attribute`: Weighted AST blame attribution mapping question fixes and regressions to `filename:line` rules.
- `pr-summary`: Render idempotent GitHub Markdown (`<!-- contextlift-pr-summary -->`) or JSON PR summaries.

## 6. Committed Empirical Findings (`docs/assets/results.json`)

- BIRD evidence sentences, 3 databases (`make example-bird`, 39 questions): `30.8% -> 53.8%`, `+23.1 pts [+1.2, +43.6]`, `p = 0.0352`, `REAL GAIN`.
- BIRD evidence sentences, 11 databases (`make example-bird-enterprise`, 65 questions): `+18.5 pts [+4.6, +32.7]`, `p = 0.0044`, `REAL GAIN`.
- BEAVER 97-table warehouse verified-query examples (`examples/beaver`, 69 questions): `+10.1 pts [+0.2, +21.8]`, `p = 0.0391`, `REAL GAIN` (hand-written rules scored `-0.7` on the working set).
- Undescribed LookML BI export (`examples/thelook/lookml-arm/round-2026-09-12.txt`, 102 questions): `+2.0 pts [-4.8, +9.3]`, `p = 0.6875`, `NOT PROVEN`.
- Oracle selection vs 22 KB full blob (`docs/evidence/blob-vs-selection.txt`): `-2.2 pts [-5.9, +1.4]` across 450 BIRD questions (`NOT PROVEN`) and `-8.6 pts [-17.0, -0.8]` on Toxicology (`p = 0.0290`, `REAL LOSS`).
- Self-Route escalation (`docs/evidence/self-route.txt`): `2 of 139 questions escalated, 1.4%`.

## 7. Documentation Map (`docs/`)

- `docs/quickstart.md`
- `docs/how-it-works.md`
- `docs/guides/ci.md`
- `docs/guides/connect.md`
- `docs/guides/questions.md`
- `docs/guides/semantic-layers.md`
- `docs/guides/extending.md`
- `docs/reference/cli.md`
- `docs/reference/formats.md`
- `docs/results.md`
- `docs/security.md`
- `docs/research/` (archived long-form monographs: `CASE_STUDY.md`, `WALKTHROUGH.md`, `METHODOLOGY.md`, `PRACTICES.md`, `CONTEXT-SOURCES.md`, `ATTRIBUTION.md`, `ONBOARDING.md`, `COLD-RUN.md`, `ROADMAP.md`, `decisions.md`)
