ai-powered-conversational-intelligence

CLAUDE.md — Project Context for Claude Code Sessions

This file orients any session working in this repo. Read it before making changes. It holds the rules that apply to every task; the detail for any one subsystem lives in a reference document this file names.

Start here for navigation: docs/architecture/context-map.md — which document owns which topic, which is authoritative, and what to read before touching a given area.


1. Project overview

An AI-Powered Conversational Intelligence platform, originally and still primarily a Text-to-SQL agent. A user asks a question in plain English in a React dashboard (frontend/); a LangGraph agent turns it into SQL against a real, user-configured database (relevant tables retrieved from ChromaDB, embedded from live schema introspection — never a hardcoded sample); the SQL is validated (AST-based SELECT-only allowlist), executed read-only, and the result is rendered as a table plus an opt-in chart. The LLM runs locally via Ollama — no network calls for the LLM and no API keys for that part.

Database connectivity is entirely .env-driven. There is no hardcoded connection string, host, or schema anywhere in the codebase.

Layered on top, each optional and most off by default: multi-source orchestration (documents, policies, web, media, attachments), a deterministic analytics/forecasting/recommendation stack, governed semantic metadata, a multi-tenant identity system, and a set of admin and review dashboards.

Implementation status is not uniform — do not assume

This platform was built over ~55 numbered prompts. Capabilities fall into four genuinely different states, and conflating them is the most common mistake a session makes here:

State Meaning Example
Live Wired into a request path and running the 19-node SQL graph, RBAC, result governance
Built, not wired Implemented and tested, no live caller analytics.root_cause (needs a second dataset the pipeline never produces), recommendation.RecommendationProvider (Protocol only), agent.translation (no route, node or setting calls it)
Off by default Live only when an operator enables it web search, media search/generation, result cache, model routing, BI integrations
Disclosed gap Deliberately absent, with a reason no scheduler/background worker, no delivery channel for alerts or briefings, no streaming

Never document an assumed capability as implemented, and never remove a requirement because the feature is not yet implemented. When unsure, read the feature’s own contract document (§8) rather than inferring from code.

Two history notes that prevent real mistakes


2. Verified technology stack

Concern Choice
LLM runtime Ollama, default llama3.1:8b (swappable via .env — e.g. sqlcoder, duckdb-nsql). Per-request selection via AskRequest.model, validated against Settings.ollama_allowed_models
Orchestration LangGraph — explicit state machines, not free-form agents. agent/graph.py (the 19-node SQL pipeline) and, when multi-source is on, agent/orchestrator/graph.py in front of it
Config / validation Pydantic v2. config/settings.py::Settings is a frozen pydantic_settings.BaseSettings; secrets are pydantic.SecretStr
User’s database PostgreSQL, MySQL, SQL Server, or Oracle via SQLAlchemy. One or more named connections (DB_CONNECTIONS), auto-routed per question
SQL parsing / validation sqlglot — AST allowlist in the dialect matching the target DB_TYPE
Schema retrieval ChromaDB, one collection per configured database, embedded from live introspection
Business-context retrieval Same Chroma client, a second collection (retrieval/) — 8 typed chunk kinds, deterministic ids
Identity / chat history Optional (LOCAL_AUTH_ENABLED), dedicated PostgreSQL DB (identity/) — Argon2id + JWT, SQLAlchemy 2.0 ORM, Alembic. The only ORM and the only real migrations in this repo
Document / policy RAG SQL Server 2025+/Azure SQL native VECTOR (rag/store.py), a dedicated connection. Off by default
Web search Pluggable provider (search/web_search.py); Tavily implemented. Off by default
UI React 19 + Vite + TypeScript + Tailwind + Zustand + @tanstack/react-query + i18next (en/es/fr/hi/mr). Charting is Plotly-figure-JSON in, Chart.js out (agent/result_charting.py builds it, frontend/src/lib/chartAdapter.ts renders it)
Streaming SSE via api/streaming.py (POST /ask/stream) — per-node progress from agent/progress.py, then the same AskResponse. Calls api.main.ask, never a second handler. Token-level streaming is not implemented
Outbound HTTP safety security/outbound_url.py — host allowlist checked before DNS, blocklist on every resolved address, redirects re-validated hop by hop
Backend tests pytest, fully mocked — no real DB, no Ollama. Opt-in live tests in tests/live/ are deselected by default (-m 'not live')
Frontend tests vitest + @testing-library/react; oxlint
Python 3.11 is the target per spec, but this machine only has 3.14, so .venv is built against 3.14. See docs/architecture/overview.md for two real 3.14 issues already hit and fixed

3. Repository navigation

One line per package. Full per-package conventions and the reasons behind each boundary: docs/architecture/repository-map.md.

Core pipeline

Path Owns
config/ Every tunable, sourced from .env. Never hardcode a model, path, or connection detail elsewhere
db/ Engine lifecycle, live schema introspection (the sole source of truth for schema shape), read-only execution, cost estimation, adapters, result cache
embeddings/ Per-database schema indexing and retrieval; the multi-database auto-router
retrieval/ Business-context vector retrieval (table/column/relationship/glossary/metric/sql_example/documentation/business_concept chunks)
agent/ LangGraph nodes (nodes.py), graph wiring (graph.py), sql_validator.py — the security boundary, authz, intent, complexity, planning, provenance
agent/orchestrator/ The multi-source router and subgraphs, one level above agent/ — never the reverse
agent/tools/, agent/analyst/, agent/multiagent/ MCP-shaped tool registry (this app’s capabilities exposed to a client); the AI Data Analyst loop; the fixed-routing specialist supervisor
sources/ The source-type contract and registry — single owner of each source’s routing description, permission and availability. agent/orchestrator/ derives its tables from here
rest/ REST/OpenAPI connector, read-only over allowlisted hosts. Off by default; not routable yet (no descriptor, no orchestrator node)
mcp_client/ Client of remote MCP servers — the opposite direction to agent/tools/, no shared code. Off by default. Administrator-controlled trust only
jobs/ The asynchronous question queue – per-user concurrency, queueing, job status, cancellation, graceful shutdown. Sits below api/ and never imports it: the work a job performs is injected as a JobRunner, so there is no second pipeline to drift from the governed one
guardrails/ The configurable façade over the layered safety controls, plus the grounding/citation gate. Adds a seam, not a second security model – GUARDRAIL_ACTION governs advisory layers only and can never soften a fail-closed control
api/ The FastAPI app — the REST surface every UI action goes through, and (once frontend/dist exists) the server for the dashboard itself
frontend/ The React dashboard, the only UI this project ships

Analytics and intelligence — analytics/ (engine, anomaly, root cause, causal, forecasting, visualization, scenario, predictive), recommendation/, semantic/ (catalog, metrics, intelligence), optimization/, data_quality/, lineage/, schema_drift/, kpi_monitoring/, briefing/, decision_center/, artifacts/.

Governance and platform — governance/ (the runtime request/result policy engine), governance_center/ (the asset lifecycle — a different concern), identity/, onboarding/, eval_platform/, bi_integration/, model_routing/, workflow/, security/, observability/, moderation/.

Optional sources — rag/, search/, media/, media_gen/, attachments/, voice/.

Supporting — scripts/ (standalone entry points), eval/ (the execution-accuracy benchmark, the security benchmark, the component benchmark), tests/ (mirrors package names; tests/security/ holds adversarial-scenario regressions).


4. Core architecture rules

These hold across the platform. Breaking one is a regression even if tests pass.

  1. The graph is an explicit, bounded state machine. agent/graph.py is 19 nodes with a conditional retry edge back to generate_sql (or to retrieve_schema for a missing reference), capped by state["max_retries"]. Never introduce an unbounded loop or a second retry budget. Adding or renaming a node means updating tests/test_sql_agent_integration.py::test_existing_nodes_are_all_still_present (an exhaustive equality check) and frontend/src/components/sql/QueryLifecycle.tsx’s stage map.
  2. An accuracy aid fails open; a safety control fails closed. Planning, golden examples, business-context retrieval, insight, analytics, recommendations, and persistence all degrade to “no extra help” on error and are never a reason a question cannot be answered. Validation, authorization, tenant resolution, moderation, and the restricted-column gate refuse instead.
  3. The LLM may propose; it never decides. Every routing choice, tool call, and generated statement passes a deterministic check the model cannot influence. A model’s own refusal is never the control.
  4. Provenance is mandatory and never upgraded silently. agent.provenance.DataTruthLevel (DATABASE_FACT / AI_INFERENCE / CONFIRMED_BUSINESS_TRUTH) travels with every claim. Never present inference, simulation, forecast, or prediction as observed fact. Only an explicit human action (publishing a catalog entry, accepting a finding, resolving a recommendation) confirms anything.
  5. Reuse the governed path; never build a second one. SQL execution is validate_sql → enforce_row_limit → qualify_table_schema → execute_readonly_sql → govern_rows_for_caller. Every caller (agent.nodes.execute_sql_node, POST /execute, BI refresh, artifact refresh) uses that exact sequence. A new caller reuses it rather than reimplementing any part.
  6. Request-scoped state, never process-global mutation. The selected database, model, tenant, and roles are values in the per-request AgentState. The Ollama client and compiled graphs are process-lifetime singletons and must stay stateless. (tests/conftest.py clears those caches between tests — without it a monkeypatched fake is silently ignored.)
  7. Additive, not a rewrite. Several subsystems are deliberately built and tested without a live caller (§1). Do not “finish the wiring” as a side effect of an unrelated change, and do not delete them as dead code.
  8. One owner per fact. Where two surfaces could state the same thing, exactly one does. This is load-bearing in the UI especially — before adding a badge, panel, or field, check which component already owns it.

5. Mandatory security and privacy rules

Never weaken one of these to simplify a change, and never rely on a UI restriction as a boundary. Full detail: SECURITY.md, docs/AUTHORIZATION.md, docs/AUTHENTICATION.md, docs/security/THREAT_MODEL.md, docs/MULTI_TENANCY.md.

5.1 SQL is untrusted output, always

5.2 Authorization

5.3 Tenant isolation

5.4 Data classification, restricted fields and result governance

5.5 Untrusted content and prompt injection

5.6 Secrets, logging and outbound calls

5.7 Uploads, rate limits and release gates

5.8 Domain privacy and safety — consult the policy before changing behavior

Authoritative document: docs/DATA_PRIVACY_GOVERNANCE_ENGINE.md. Read it before changing anything that affects what the platform may be asked, may return, or may recommend in a business domain.

governance/domains.py defines 19 domains plus a GENERAL fallback (the mission’s 18, plus CONSTRUCTION, which was added later and derived from its neighbours rather than specified — the enum’s own docstring says so), and 14 ProhibitedAction values. The rules that must not regress:

No compliance with any named regulatory regime is claimed. These are technical controls supporting privacy and governance requirements.


6. Coding and implementation standards

6.1 Before writing code

  1. Inspect the existing implementation first. This repo’s single most repeated lesson: nearly every “new” requirement turns out to be partly built. Grep for the capability, read the owning module’s docstring, and read the relevant contract document (§8).
  2. Reuse existing components and services. Extend a function rather than writing a parallel one. If two implementations would answer the same question, that is a defect regardless of test results.
  3. Do not rewrite working behavior as a side effect of an unrelated change. Preserve public signatures where callers depend on them.
  4. Follow the surrounding conventions — comment density, naming, module layout, error handling, and the fail-open/fail-closed split (§4.2).

6.2 Style and typing

6.3 Changes and compatibility

6.4 Reporting


7. Testing and validation

.\tasks.ps1 test      # pytest
.\tasks.ps1 lint      # ruff check + black --check + mypy
.\tasks.ps1 format    # black + ruff --fix

Equivalent make test / make lint / make format targets exist for WSL/macOS/Linux. Frontend: npm run test / npm run lint / npx tsc --noEmit -p tsconfig.app.json inside frontend/.


8. Documentation references

Read docs/architecture/context-map.md first — it maps every topic to its owning document, says which is authoritative, and explains how to resolve a conflict.

Need Document
Where code lives, and why docs/architecture/repository-map.md
Cross-cutting design decisions and their invariants docs/architecture/overview.md
Per-node graph walkthrough, diagrams, retry routing table docs/ARCHITECTURE.md
Analytics / forecasting / recommendation / lineage features docs/architecture/features-analytics.md
Identity, tenancy, governed lifecycles, admin surfaces docs/architecture/features-governance-and-admin.md
Frontend and chat-workspace features docs/architecture/features-frontend.md
Security posture, threat model, CVE triage SECURITY.md, docs/security/
Domain privacy and prohibited outputs docs/DATA_PRIVACY_GOVERNANCE_ENGINE.md
Authentication / authorization docs/AUTHENTICATION.md, docs/AUTHORIZATION.md
Multi-tenancy rules and limitations docs/MULTI_TENANCY.md
Configuration reference docs/CONFIGURATION.md
Entity display names: metadata, SQL repair, join and chart-label rules docs/DISPLAY_NAMES.md
Result-column semantics and chart axis binding (measure vs key) docs/CHART_AXIS_BINDING.md
Measured latency, what causes it, and the hardware ceiling docs/PERFORMANCE.md
Per-user concurrency, the question queue, deterministic source routing, per-task model pins, guardrails, grounding docs/CONCURRENCY.md
Production readiness verdict docs/PRODUCTION_READINESS_RELEASE_GATE.md
One feature’s full design, tests and limitations NN_*_CONTRACT.md at the repo root — one per numbered prompt; indexed in the context map

A feature’s own NN_*_CONTRACT.md is authoritative for that feature. The reference files above carry the invariants and the known limitations; the contract carries the inspection findings, the design, and the testing summary.


9. How to run

See README.md for full setup. Short version:

.venv\Scripts\Activate.ps1
ollama pull llama3.1:8b
# fill in .env with your real DB connection details first
python scripts\test_db_connection.py
python scripts\build_embeddings.py
python -m scripts.ingest_schema --database-id default   # optional, business-context retrieval
alembic -c identity\alembic.ini upgrade head            # only if LOCAL_AUTH_ENABLED=true
cd frontend; npm install; npm run build; cd ..
uvicorn api.main:app --host 127.0.0.1 --port 8000

Open http://localhost:8000/ — the API process also serves the built dashboard. For frontend hot-reload, run npm run dev in frontend/ instead (Vite proxies API calls to the uvicorn process; a new backend route prefix must be added to vite.config.ts’s BACKEND_ROUTES — a recurring, easy miss).

Task PowerShell Make
Create venv + install deps .\tasks.ps1 setup make setup
Verify DB connection python scripts\test_db_connection.py same
Build/refresh embeddings python scripts\build_embeddings.py same
Ingest business context python -m scripts.ingest_schema --database-id default same
Apply identity migrations alembic -c identity\alembic.ini upgrade head same
Run app .\tasks.ps1 run make run
Manual real-DB check python scripts\integration_test.py same

Windows / Visual Studio notes


10. Standard task workflow

The workflow every numbered prompt in this repo has followed:

INSPECT → PLAN → IMPLEMENT → TEST → REVIEW → FIX → DOCUMENT → REPORT

  1. Inspect — find what already exists for this capability. Read the owning module’s docstring and the relevant contract (§8). Record what you found and what it means for the design.
  2. Plan — state which existing code you will reuse, what is genuinely new, and which invariants (§4, §5) the change touches.
  3. Implement — incrementally, reusing the governed paths, following the surrounding conventions.
  4. Test — add the tests the change warrants; run the suites and read the output. Attribute any pre-existing failure before claiming it is yours or not.
  5. Review — re-read your own diff against §4 and §5. Check for duplicated facts, a weakened control, or a stated limitation that is now false.
  6. Fix — including anything the tests found that you did not expect.
  7. Document — update the feature’s contract or reference doc, this file if a rule changed, and vite.config.ts/i18n/tests if the change implies them.
  8. Report — commands run, results, assumptions, limitations, and what you deliberately did not do.

11. Definition of done


12. Never touch

Only when a task is specifically about them — never as a side effect:


13. Known gaps and follow-ups

Named so a future session does not rediscover them. Each feature’s own contract lists its specific limitations; these are the cross-cutting ones.