# AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall — Complete AI & LLM Reference Corpus (`llms-full.txt`)
- Repository: https://github.com/mohan-n-swamy/ai-analyst-public
- Web Discovery URL: https://mohan-n-swamy.github.io/repos/ai-analyst-public/
- License: MIT
- Keywords: text-to-sql, ai-analyst, slack-bot, snowflake, bigquery, postgresql, semantic-layer, business-intelligence, data-analytics, python
---
## File: `AI-README.md` — AI-README.md
---
repo: "mohan-n-swamy/ai-analyst-public"
title: "AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall"
license: "MIT"
keywords: [text-to-sql, ai-analyst, slack-bot, snowflake, bigquery, postgresql, semantic-layer, business-intelligence, data-analytics, python]
capabilities:
- "Owner-signed, effective-dated Semantic Metric Catalog (`analyst/catalog.py`, `catalog/metrics.example.yaml`) resolving historical weeks accurately."
- "`sqlglot` Read-Only SQL AST Firewall (`analyst/firewall.py`) blocking multi-statement queries, 13+ write/DDL AST node types, and unbounded `SELECT` scans."
- "Zero-configuration seeded `SQLiteDemoWarehouse` (`analyst/warehouse.py`) so `wbr` and `check-sql` run in `<0.2s` right after clone."
- "Weekly Operational Review Markdown & JSON compiler (`analyst/report.py`) stamping `(metric_id, formula_version, signed_by, sql_sha256)` on every section."
when_to_use:
- "A Slack-ready and CLI data analyst engine combining an owner-signed, effective-dated YAML semantic metric registry (`old weeks keep their formula`), a `sqlglot` read-only SQL AST firewall, SHA-256 query receipts, and a zero-config seeded demo warehouse alongside Snowflake, DuckDB, and PostgreSQL support."
- "Pointing an LLM directly at 200 raw warehouse tables produces plausible-looking wrong numbers, silently mutates historical WBR figures whenever definitions evolve, and exposes databases to prompt-injected DDL/DML statements. `ai-analyst-public` enforces one owner-signed SQL formula per metric with effective dates, validates every query through a `sqlglot` AST firewall, and attaches a SHA-256 SQL receipt to every reported number."
inputs_required:
- "WAREHOUSE_BACKEND: Active warehouse adapter (`sqlite_demo`, `duckdb`, `postgres`, or `snowflake`)"
- "METRIC_CATALOG_PATH: Path to your signed semantic metric registry YAML"
- "SQL_DEFAULT_ROW_LIMIT: Automatic `LIMIT` injected into ad-hoc read queries lacking an explicit limit"
- "SNOWFLAKE_ROLE: Read-only database role for defense-in-depth alongside the AST firewall"
- "SLACK_BOT_TOKEN: Optional Slack Bot token for WBR channel posting and thread Q&A"
quickstart:
- "python3 bin/analyst-cli.py wbr --week 2026-10-19 # evaluates using historical v1 formula"
- "python3 bin/analyst-cli.py wbr --week 2026-11-16 # evaluates using post-cutover v2 formula"
- "python3 bin/analyst-cli.py check-sql "SELECT region, COUNT(*) FROM fact_orders GROUP BY 1""
- "pytest -q tests/ # run all 10 cutover & SQL AST firewall tests"
---
# AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall — Machine-Readable Agent Guide
A Slack-ready and CLI data analyst engine combining an owner-signed, effective-dated YAML semantic metric registry (`old weeks keep their formula`), a `sqlglot` read-only SQL AST firewall, SHA-256 query receipts, and a zero-config seeded demo warehouse alongside Snowflake, DuckDB, and PostgreSQL support.
Pointing an LLM directly at 200 raw warehouse tables produces plausible-looking wrong numbers, silently mutates historical WBR figures whenever definitions evolve, and exposes databases to prompt-injected DDL/DML statements. `ai-analyst-public` enforces one owner-signed SQL formula per metric with effective dates, validates every query through a `sqlglot` AST firewall, and attaches a SHA-256 SQL receipt to every reported number.
Key modules and entry points in this repository:
- `catalog/metrics.example.yaml`: Canonical metric definitions with `id`, `owner`, `versions[]`, `effective_from`, and `signed_by`
- `analyst/catalog.py`: `MetricCatalog` loader failing closed on unsigned metrics and resolving formulas by week
- `analyst/firewall.py`: `validate_and_cap_sql()` AST validator and automatic `LIMIT` injector
- `analyst/warehouse.py`: Seeded `SQLiteDemoWarehouse` and `QueryReceipt` SHA-256 provenance generator
- `analyst/report.py`: Weekly Operational Review (`WBR`) Markdown and JSON compiler
- `bin/analyst-cli.py`: Command-line runner for `wbr` generation and `check-sql` firewall verification
- `tests/test_ai_analyst.py`: Pytest suite covering v1->v2 date cutovers, unsigned YAML rejection, and DDL/DML/injection blocking
Every organization-specific value enters through `.env` (copied from `.env.example`) or external adapter files. No source edit is needed to change organization names, endpoints, database URLs, webhook secrets, or thresholds.
When a human asks an AI coding agent to deploy or adapt `ai-analyst-public` into their stack:
1. Copy `catalog/metrics.example.yaml` to `catalog/metrics.yaml` and add your organization's core KPIs with owner sign-offs and `effective_from` dates.
2. Subclass/wire your read-only Snowflake, DuckDB, or PostgreSQL connection in `analyst/warehouse.py` (keeping `validate_and_cap_sql` at the execution choke point).
3. Schedule `bin/analyst-cli.py wbr --json` in cron/GitHub Actions to post signed weekly digests to Slack.
- Product Requirements: `docs/PRD.md`
- Working-Backwards PR-FAQ: `docs/PR-FAQ.md`
- High-Level Architecture: `docs/HLD.md`
- Low-Level Interfaces & Runbook: `docs/LLD.md`
- Coding Agent Rules: `AGENTS.md`
---
## File: `.env.example` — Environment Contract (.env.example)
```ini
# ai-analyst-public — Governed Semantic Metric Engine & Slack Warehouse Analyst
WAREHOUSE_BACKEND=sqlite_demo
METRIC_CATALOG_PATH=./catalog/metrics.example.yaml
SQL_DEFAULT_ROW_LIMIT=1000
SNOWFLAKE_ACCOUNT=your_account_locator
SNOWFLAKE_USER=readonly_analyst_bot
SNOWFLAKE_ROLE=ANALYST_READONLY
SNOWFLAKE_WAREHOUSE=COMPUTE_WH
SLACK_BOT_TOKEN=xoxb-replace-me
SLACK_APP_TOKEN=xapp-replace-me
ANTHROPIC_API_KEY=replace_with_llm_api_key
```
---
## File: `AGENTS.md` — AGENTS.md
# AGENTS.md — AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall
Read this file first before modifying `ai-analyst-public`.
## Purpose
A Slack-ready and CLI data analyst engine combining an owner-signed, effective-dated YAML semantic metric registry (`old weeks keep their formula`), a `sqlglot` read-only SQL AST firewall, SHA-256 query receipts, and a zero-config seeded demo warehouse alongside Snowflake, DuckDB, and PostgreSQL support.
## Commands
```bash
python3 bin/analyst-cli.py wbr --week 2026-10-19 # evaluates using historical v1 formula
python3 bin/analyst-cli.py wbr --week 2026-11-16 # evaluates using post-cutover v2 formula
python3 bin/analyst-cli.py check-sql "SELECT region, COUNT(*) FROM fact_orders GROUP BY 1"
pytest -q tests/ # run all 10 cutover & SQL AST firewall tests
```
## Module Map
- `catalog/metrics.example.yaml`: Canonical metric definitions with `id`, `owner`, `versions[]`, `effective_from`, and `signed_by`
- `analyst/catalog.py`: `MetricCatalog` loader failing closed on unsigned metrics and resolving formulas by week
- `analyst/firewall.py`: `validate_and_cap_sql()` AST validator and automatic `LIMIT` injector
- `analyst/warehouse.py`: Seeded `SQLiteDemoWarehouse` and `QueryReceipt` SHA-256 provenance generator
- `analyst/report.py`: Weekly Operational Review (`WBR`) Markdown and JSON compiler
- `bin/analyst-cli.py`: Command-line runner for `wbr` generation and `check-sql` firewall verification
- `tests/test_ai_analyst.py`: Pytest suite covering v1->v2 date cutovers, unsigned YAML rejection, and DDL/DML/injection blocking
## Invariants
1. Keep all organization names, credentials, domains, and thresholds in `.env` or external config files. Never hardcode company names, host IPs, or secrets in source files.
2. Deterministic business logic belongs in code and lookup tables, not inside LLM prompts.
3. Update `docs/HLD.md`, `docs/LLD.md`, and `.env.example` in the same commit whenever an interface or environment variable changes.
4. Run the repository smoke check and secret scan before opening a pull request.
---
## File: `docs/PRD.md` — Product Requirements Document (docs/PRD.md)
# Product Requirements Document — AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall
A Slack-ready and CLI data analyst engine combining an owner-signed, effective-dated YAML semantic metric registry (`old weeks keep their formula`), a `sqlglot` read-only SQL AST firewall, SHA-256 query receipts, and a zero-config seeded demo warehouse alongside Snowflake, DuckDB, and PostgreSQL support.
## 1. Problem
Pointing an LLM directly at 200 raw warehouse tables produces plausible-looking wrong numbers, silently mutates historical WBR figures whenever definitions evolve, and exposes databases to prompt-injected DDL/DML statements. `ai-analyst-public` enforces one owner-signed SQL formula per metric with effective dates, validates every query through a `sqlglot` AST firewall, and attaches a SHA-256 SQL receipt to every reported number.
## 2. Users and Jobs-to-be-Done
| Persona | Job-to-be-Done |
|---|---|
| COO / VP Operations / Analytics Lead | Publish Weekly Operational Reviews (WBR/WOR) where every metric has one signed definition and historical weeks never shift retroactively. |
| Data / Analytics Engineer | Version metric SQL in git (`catalog/metrics.example.yaml`) with mandatory owner sign-off and automated pytest checks. |
| Security Engineer | Enforce AST-level read-only `SELECT` verification (`sqlglot`) and automatic row limits before any query touches Snowflake or Postgres. |
## 3. Core Capabilities
- Owner-signed, effective-dated Semantic Metric Catalog (`analyst/catalog.py`, `catalog/metrics.example.yaml`) resolving historical weeks accurately.
- `sqlglot` Read-Only SQL AST Firewall (`analyst/firewall.py`) blocking multi-statement queries, 13+ write/DDL AST node types, and unbounded `SELECT` scans.
- Zero-configuration seeded `SQLiteDemoWarehouse` (`analyst/warehouse.py`) so `wbr` and `check-sql` run in `<0.2s` right after clone.
- Weekly Operational Review Markdown & JSON compiler (`analyst/report.py`) stamping `(metric_id, formula_version, signed_by, sql_sha256)` on every section.
## 4. Configurable Inputs
Adopters configure the system for their own organization without editing core application logic:
| Variable | Default / Example | Purpose |
|---|---|---|
| `WAREHOUSE_BACKEND` | `sqlite_demo` | Active warehouse adapter (`sqlite_demo`, `duckdb`, `postgres`, or `snowflake`) |
| `METRIC_CATALOG_PATH` | `./catalog/metrics.example.yaml` | Path to your signed semantic metric registry YAML |
| `SQL_DEFAULT_ROW_LIMIT` | `1000` | Automatic `LIMIT` injected into ad-hoc read queries lacking an explicit limit |
| `SNOWFLAKE_ROLE` | `ANALYST_READONLY` | Read-only database role for defense-in-depth alongside the AST firewall |
| `SLACK_BOT_TOKEN` | `xoxb-...` | Optional Slack Bot token for WBR channel posting and thread Q&A |
## 5. Phasing and Stability Exit Criteria
1. **Phase 1 (Local Synthetic Run):** Clone the repository, copy `.env.example` to `.env`, and run the quickstart commands against synthetic seed data. Exit criterion: smoke checks pass with zero external credentials.
2. **Phase 2 (Read-Only Shadow Wiring):** Connect read-only credentials or webhook listeners in shadow/dry-run mode. Exit criterion: 100 consecutive events or queries reconcile cleanly against source records.
3. **Phase 3 (Production Cutover):** Enable live writes, alerts, or routing behind bounded retry and idempotency guards.
## 6. Non-Goals
- Shipping organization-specific business rules hardcoded in application source.
- Storing credentials, personal customer records, or tenant URLs inside version control.
- Replacing deterministic validation or arithmetic with unconstrained model prompts.
---
## File: `docs/PR-FAQ.md` — Working-Backwards PR-FAQ (docs/PR-FAQ.md)
# Working-Backwards PR-FAQ — AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall
**Release Summary:** `ai-analyst-public` gives engineering and operations teams a self-hosted, open-source implementation of AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall that configures via `.env` and runs on standard infrastructure in minutes.
## Press Release
Operations and engineering teams often rebuild the same internal workflows behind closed doors or pay per-seat SaaS markups for rigid tools that cannot match their field reality. `ai-analyst-public` open-sources a battle-tested implementation of AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall, stripped of all single-company assumptions and packaged with clear adapter boundaries, synthetic demo data, and machine-readable agent documentation.
Any team can fork `ai-analyst-public`, supply their own `.env` inputs and taxonomy config, and deploy locally or in production with Docker, Python, or Node. AI coding assistants such as Claude Code, Codex, and Cursor can read `AI-README.md` and `llms.txt` to wire custom ERP, CRM, or warehouse adapters in a single session.
## External Adopter FAQ
**Q1: How long does it take to run locally after cloning?**
Under five minutes. Copy `.env.example` to `.env` and run the quickstart commands in `README.md`. Synthetic fixtures let you inspect the workflow before connecting live credentials.
**Q2: Do I need to rewrite source files to use my own company name, channels, or rules?**
No. Organization names, endpoints, thresholds, and credentials sit in `.env` and declarative config files. External system specifics live behind narrow adapter modules documented in `docs/LLD.md`.
**Q3: What license governs this repository?**
MIT License. You can fork, modify, self-host, and use it commercially without restriction.
## Internal Engineering & Security FAQ
**Q4: How do we prevent tenant or employer data from ever entering a public fork?**
The repository starts from a clean git history, excludes raw exports and binary dumps, validates every commit through `gitleaks`, and ships only synthetic fixtures.
**Q5: What happens when an upstream API or model provider is slow or unavailable?**
Inbound webhooks persist raw payloads before processing, outbound writes carry idempotency keys with bounded exponential backoff, and model-backed paths fail open to deterministic rules or explicit human queues.
---
## File: `docs/HLD.md` — High-Level Design (docs/HLD.md)
# High-Level Design (HLD) — AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall
A Slack-ready and CLI data analyst engine combining an owner-signed, effective-dated YAML semantic metric registry (`old weeks keep their formula`), a `sqlglot` read-only SQL AST firewall, SHA-256 query receipts, and a zero-config seeded demo warehouse alongside Snowflake, DuckDB, and PostgreSQL support.
## 1. System Topology
```mermaid
flowchart LR
YAML["Signed metrics.yaml (v1, v2...)"] --> Catalog["effective_from Resolver"]
Catalog --> AST["sqlglot Read-Only AST Firewall"]
AdHoc["Slack Thread Q&A SQL"] --> AST
AST -->|"SELECT + LIMIT"| WH["Snowflake / DuckDB / Seeded Demo"]
WH --> Receipt["WBR Report + SHA-256 SQL Receipt"]
```
## 2. Architectural Decisions and Rejected Alternatives
| Decision | Why It Holds | Rejected Alternative |
|---|---|---|
| Effective-dated metric versions (`effective_from`) | Preserves exact historical WBR accountability when business definitions tighten (e.g., excluding test orders from Nov 1 onward). | Overwriting a single SQL view in place |
| `sqlglot` AST parsing instead of regex keyword bans | Accurately inspects CTEs, unions, and dialect syntax while injecting `LIMIT` cleanly. | Brittle `if 'DROP' in sql` string checks |
| Built-in seeded `SQLiteDemoWarehouse` | Lets evaluators test version cutovers, receipts, and AST blocking in 200ms with zero cloud credentials. | Requiring a live Snowflake account just to run `hello world` |
## 3. Data Flow and Failure Boundaries
1. **Configuration Boundary:** Startup validates `.env` variables and declarative config schemas before accepting traffic or running scheduled jobs.
2. **Adapter Boundary:** External services (databases, chat channels, HRMS, warehouses, or LLM providers) sit behind explicit adapter modules so failures stay isolated and testable with local mocks.
3. **Observability and Audit:** State transitions and job executions emit structured logs and deterministic status records rather than mutating state silently.
## 4. Scaling Notes
- **1x to 10x load:** Single-node Docker Compose or process supervisor handles standard team workloads with indexed database queries and bounded worker concurrency.
- **First bottleneck at 10x+:** High-frequency webhook or batch ingestion queues; mitigate by separating the stateless HTTP receiver from background worker processes sharing Redis or PostgreSQL locks.
---
## File: `docs/LLD.md` — Low-Level Design & Runbook (docs/LLD.md)
# Low-Level Design (LLD) & Operations Runbook — AI Analyst — Governed Warehouse Data Analyst & SQL AST Firewall
This document defines the module responsibilities, environment contract, and operational procedures for `ai-analyst-public`.
## 1. Module and File Inventory
| Path | Responsibility |
|---|---|
| `catalog/metrics.example.yaml` | Canonical metric definitions with `id`, `owner`, `versions[]`, `effective_from`, and `signed_by` |
| `analyst/catalog.py` | `MetricCatalog` loader failing closed on unsigned metrics and resolving formulas by week |
| `analyst/firewall.py` | `validate_and_cap_sql()` AST validator and automatic `LIMIT` injector |
| `analyst/warehouse.py` | Seeded `SQLiteDemoWarehouse` and `QueryReceipt` SHA-256 provenance generator |
| `analyst/report.py` | Weekly Operational Review (`WBR`) Markdown and JSON compiler |
| `bin/analyst-cli.py` | Command-line runner for `wbr` generation and `check-sql` firewall verification |
| `tests/test_ai_analyst.py` | Pytest suite covering v1->v2 date cutovers, unsigned YAML rejection, and DDL/DML/injection blocking |
## 2. Environment Variable Contract
| Variable | Default / Example | Required | Description |
|---|---|---|---|
| `WAREHOUSE_BACKEND` | `sqlite_demo` | Yes | Active warehouse adapter (`sqlite_demo`, `duckdb`, `postgres`, or `snowflake`) |
| `METRIC_CATALOG_PATH` | `./catalog/metrics.example.yaml` | Yes | Path to your signed semantic metric registry YAML |
| `SQL_DEFAULT_ROW_LIMIT` | `1000` | Yes | Automatic `LIMIT` injected into ad-hoc read queries lacking an explicit limit |
| `SNOWFLAKE_ROLE` | `ANALYST_READONLY` | Yes | Read-only database role for defense-in-depth alongside the AST firewall |
| `SLACK_BOT_TOKEN` | `xoxb-...` | Yes | Optional Slack Bot token for WBR channel posting and thread Q&A |
## 3. Extension Recipe
1. Copy `catalog/metrics.example.yaml` to `catalog/metrics.yaml` and add your organization's core KPIs with owner sign-offs and `effective_from` dates.
2. Subclass/wire your read-only Snowflake, DuckDB, or PostgreSQL connection in `analyst/warehouse.py` (keeping `validate_and_cap_sql` at the execution choke point).
3. Schedule `bin/analyst-cli.py wbr --json` in cron/GitHub Actions to post signed weekly digests to Slack.
## 4. Operations Runbook
### 1. Generate Markdown WBR for a target week
```bash
python3 bin/analyst-cli.py wbr --week 2026-11-16
```
### 2. Emit machine-readable JSON WBR with SHA-256 receipts
```bash
python3 bin/analyst-cli.py wbr --week 2026-11-16 --json
```
### 3. Run full AST firewall & metric cutover test suite
```bash
pytest -q tests/
```
---
## File: `docs/RESEARCH-2026.md` — 2026 Research & Landscape Notes (docs/RESEARCH-2026.md)
# 2026 Conversational Data Analyst & Semantic Layer Research
In 2026, raw schema-dump Text-to-SQL tools routinely fail executive adoption for two non-ML reasons:
1. **Metric Drift Across Teams:** Auditing real enterprise warehouses commonly uncovers 30-40 conflicting SQL definitions for core KPIs (`completed_orders`, `net_revenue`, `on_time_sla`) across BI sheets, Slack bots, and Python notebooks.
2. **Retroactive History Mutation:** Updating a SQL view overwrites prior weeks' numbers, breaking week-over-week accountability unless formulas are **effective-dated**.
3. **Regex SQL Filters Are Trivial to Bypass:** Keyword blocklists fail on CTEs or vendor-specific commands; parsing into a typed AST (`sqlglot`) combined with `READ ONLY` warehouse credentials provides true defense-in-depth.
`ai-analyst-public` packages all three into a clean, dependency-light Python foundation with an instant built-in demo warehouse.