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.
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.
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.
db/schema.sql, or scripts/seed_db.py are stale — treat them as
wrong, not as a parallel supported mode.frontend/ is the only UI. Two
non-UI modules were relocated rather than deleted:
ui/session_history.py → eval/history.py, ui/column_formatting.py →
db/column_formatting.py (mirrored on the frontend by
frontend/src/lib/columnFormatting.ts). References to ui/app.py,
ui.session_history, or ui.column_formatting are stale.| 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 |
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).
These hold across the platform. Breaking one is a regression even if tests pass.
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.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.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.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.)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.
agent/sql_validator.py parses with sqlglot and accepts only a single
SELECT/UNION/EXCEPT/INTERSECT — an allowlist of the parsed
statement type, never a regex blocklist. It also rejects system
catalog/data-dictionary references (information_schema, pg_catalog,
mssql sys, Oracle ALL_*/DBA_*/USER_*/V$/GV$), nested
aggregates, and unsafe query hints.DB_USER. db.connection.check_write_privileges is
startup-enforced. If asked to harden further, push on the database role.LIMIT/FETCH in the SQL text and
fetchmany() at the cursor — so a mistranslated query cannot bypass it.
The query timeout is enforced at the driver level or by forced connection
abort.agent/authz.py is the base-role permission layer (viewer/user/
analyst/admin); identity/rbac.py is the granular layer for identity,
admin and governed-lifecycle routes. An unrecognized role grants zero
permissions.router_node filters the LLM’s own source
selection through a permission check before any subgraph runs. A routing
decision can request access; it can never grant it.POST
/navigation/access-denied audit-logs a refused screen.ENVIRONMENT=production fails closed at startup when identity is
unconfigured.User row this server loaded, this app’s own signature-verified JWT
tid claim, or an IdP-signed claim. security.tenancy.reject_client_tenant_override
refuses (400) any request carrying X-Tenant-Id/X-Tenant/
Tenant-Id/X-Tenant-Override, before authentication, in every auth mode.WHERE clause, never applied
as a post-hoc filter.governance/ is the centralized engine every request passes through: what
may be asked (request_policy), what may be returned (result_policy),
what may be recommended (recommendation_safety).config/sensitive_columns.yaml ships as an empty template, so
governance.classification’s name-pattern inference fills the gap. An
explicit human classification always wins — including when it loosens.Permission.VIEW_RESTRICTED_COLUMNS sees [restricted].
CREDENTIAL and PAYMENT are withheld from every caller, including an
admin — no role unlocks them.execute_sql_node before state["result_rows"] is set, so the
insight step, recommendation engine, chart builder and response all receive
protected rows.UNION, or SELECT * reaches the same protection.DomainPolicy.export_row_limit) is the one control that does remove rows,
and it must always be disclosed — /execute reports truncated=True, and
the result gate names it in actions.api.artifacts._result_out and
api.shares._governed_result_snapshot. A share is the sharpest case — an
“anyone with the link” viewer holds no roles at all — so a new surface that
serves a persisted result_snapshot must re-govern it too.security/injection_patterns.py is a detection signal, not the
boundary — agent/sql_validator.py and the RBAC/restricted-column gates
bound consequences. Attachment scanning is detection-only and never blocks.sensitivity_category is never summarized
into an answer — checked before the LLM sees the chunk, fail-closed,
regardless of caller role. DocumentRecord.restricted_roles is a second,
independent RBAC gate.agent/llm_client.py uses
in-code constants, because making a database row the system prompt would
turn every write into prompt injection with full pipeline reach.pydantic.SecretStr; call sites must use
.get_secret_value(). A leftover str(secret) silently sends the literal
"**********".DB_TYPE/DB_NAME/table names/row counts only. This is a security
property of this codebase, not a style preference.agent.exceptions.AgentError carries both full internal detail and a short
.safe_message. Response bodies use .safe_message; two global handlers
in api/main.py are the last-resort net. security.redaction.redact_secrets
is applied to any text this app did not construct itself.identity.models.OnboardingJob has no password column.moderation/gate.py is mandatory whenever
media search or document/policy RAG is on — a hard reject on any chunk
rejects the entire asset, and nothing from a rejected file is stored./ask has real admission control (bounded pool + per-caller cap → immediate
429 before any LLM/DB work). Rate limits are keyed by real identity, not
raw client IP, and X-Forwarded-For is read only when an operator sets
trusted_proxy_count.ruff, black --check, bandit, pytest,
pip-audit (with an individually justified ignore list) and
detect-secrets — except mypy, which is report-only
(continue-on-error: true, and deliberately the last step in the job).
It was made non-blocking because the test job’s steps run sequentially
and a failing mypy silently stopped bandit/pytest/pip-audit from
running at all. So treat a type error as a real defect to fix — CI will
report it and still go green. The standing backlog is in §13.
mypy is not the only non-blocking step — gitleaks, the Trivy
container scan and the load-test smoke scenario are too, for their own
dated reasons. §13’s “Four CI steps are non-blocking” bullet is the
authoritative list; read it before concluding that a green CI run
proves anything about those four.08f385e: ruff, bandit and pip-audit all exit
non-zero, so three blocking steps fail, while black and pytest
pass. Every one of the three is a verified-benign finding awaiting an
owner decision, not a vulnerability — see §13 and
docs/certification/2026-10-17_release_gate_v2.md
§11.6. Never “fix” one by weakening the gate.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:
BASELINE_RESTRICTED_CATEGORIES (PII, SPI, PHI, compensation, performance,
credential, payment, banking) is unioned into every domain. Always read
DomainPolicy.effective_restricted_categories, never
restricted_categories directly — otherwise detecting a domain could
loosen protection.GENERAL fallback prohibits all 14 actions, not none. If the
domain is unknown, no decision about an individual is safe to make or
recommend.ProhibitedAction list drives both the request gate and the
recommendation filter, so “what we refuse to be asked” and “what we refuse
to propose” cannot drift. An unsafe recommendation is withheld and
reported, never rewritten — editing it would leave the evidence attached
to a claim it no longer supports.ENABLE_REQUEST_GOVERNANCE, ENABLE_RESULT_GOVERNANCE,
ENABLE_RECOMMENDATION_SAFETY.No compliance with any named regulatory regime is claimed. These are technical controls supporting privacy and governance requirements.
pyproject.toml. Run .\tasks.ps1 lint before considering a change done.print() except in the standalone CLI scripts meant to be read as
terminal output (scripts/test_db_connection.py,
scripts/integration_test.py). Everything else uses logging
(level from LOG_LEVEL in .env). Agent nodes log each state transition,
so the terminal shows the agent’s steps live.sanitizeLabel on any
database-derived string before display or re-submission.api/schemas.py response models are frozen
and widely consumed; an added field must be optional with a default.Settings
field with a Field(...) constraint and a comment explaining the default,
not a literal in code.server_default for any ORM-filled timestamp column
(pinned by tests/test_identity_schema_invariants.py after a real
production-only breakage)..\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/.
scripts/integration_test.py, scripts/run_benchmark.py and
eval/security_benchmark/ are manual and require real infrastructure; CI
never runs them.tests/conftest.py strips every env var a Settings field could read, so a
test never silently inherits the developer’s real .env. It also clears the
three process-lifetime caches between tests.tests/security/ is for adversarial-scenario regressions that do not fit a
single module’s test file. Check whether a scenario is already covered
before adding one.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.
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 |
.sln-driven project. A minimal
.sln exists only so “Open Solution” also works; it defines no real build
configurations..venv\Scripts\Activate.ps1.
If script execution is blocked, check Get-ExecutionPolicy and set
RemoteSigned for CurrentUser — never suggest machine-wide
Unrestricted.DB_TYPE=mssql needs the Microsoft ODBC Driver for SQL Server installed as
a system package. ENABLE_MEDIA_SEARCH=true needs the Tesseract OCR
binary likewise (OCR fails open without it — reduced accuracy, not a
blocker). Ollama must be running before the API starts
(OLLAMA_HOST in .env, default http://localhost:11434)..vs/ is gitignored. Chroma writes local files under
embeddings/.chroma/, regenerated by scripts/build_embeddings.py.The workflow every numbered prompt in this repo has followed:
INSPECT → PLAN → IMPLEMENT → TEST → REVIEW → FIX → DOCUMENT → REPORT
vite.config.ts/i18n/tests if the change implies
them..\tasks.ps1 lint and .\tasks.ps1 test pass, or every failure is
attributed with evidence.npm run test, npm run lint, and
tsc --noEmit pass.Only when a task is specifically about them — never as a side effect:
.env — real, populated DB_PASSWORD,
RAG_STORE_CONNECTION_STRING, WEB_SEARCH_API_KEY and JWT keys. Never
read into a commit, log line, or response. .env.example is the template and is safe to edit.
.secrets.baseline is tool-generated; regenerate, never hand-edit.identity/migrations/ — the only real migrations here.
Never hand-edit an applied revision; add a new one.embeddings/.chroma/,
frontend/dist/, any node_modules/, .venv/, __pycache__/,
.mypy_cache/, .ruff_cache/, .pytest_cache/, .vs/, media_library/.agent.llm_client._INSIGHT_SYSTEM_PROMPT
and the generation system prompt. docs/EVALUATION_CURRENT.md’s accuracy
numbers were measured against their exact wording; changing them without
being able to re-run that benchmark invalidates the only real accuracy
figures this project has.Named so a future session does not rediscover them. Each feature’s own contract lists its specific limitations; these are the cross-cutting ones.
search/ has no dedicated mocked unit test file.tests/test_web_search.py (14 tests, httpx.post mocked throughout) now
pins the Tavily request shape, response parsing, empty/missing results,
HTTP error propagation, secret non-leakage and SUPPORTED_SEARCH_PROVIDERS
dispatch. Verified 2026-10-14; the entry had outlived the gap by some time.
Treat every item below as dated — confirm a gap still exists before
acting on it, the same way §13 asks you to measure before claiming a
finding is yours.DB_<NAME>_SCHEMA is one schema per connection, not “all schemas”. A
database whose tables span many schemas exposes one at a time.agent.graph.run_agent, not multi-source or cross-source questions.agent/followup.py’s classify_followup_node sees only the
conversation_history the caller resends, capped at
MAX_FOLLOWUP_EXCHANGES; no LangGraph checkpointer exists (none ships for
SQL Server, so it would need a custom BaseCheckpointSaver).
Corrected 2026-10-17: this entry cited langgraph==0.2.62.
The real pin is langgraph==1.0.10rc1 (requirements.txt:2) — three
major versions on, and a release candidate in a production requirements
file, which is itself worth a deliberate decision. The conclusion is
unchanged and re-verified: zero BaseCheckpointSaver/checkpointer=
usage anywhere in this repo.identity.users row to attach a conversation to.identity.models.AiOutput.metadata_json); charts, retrieved DDL and
per-source citations are not.scripts/ are the cron entry points. Nothing is emailed,
posted or messaged.POST /ask/stream
(api/streaming.py) emits per-node progress over SSE and then the same
AskResponse POST /ask returns – it calls that handler rather than
reimplementing it, so every control applies identically. What is still
absent is token-level streaming: agent/llm_client.py makes one
blocking call per step and the generation/insight prompts are
benchmark-pinned (§12), so streaming the model’s own tokens is a
separate, evidence-gated change. No WebSocket endpoint exists.jobs/) and the compiled graph/Ollama
singletons are all per-worker. A multi-worker deployment has one of each
per worker. The queue is the sharpest case, because its cap is advertised
to users: N workers admit up to N x MAX_CONCURRENT_QUESTIONS_PER_USER,
and queued/running jobs do not survive a restart. See
docs/CONCURRENCY.md 2.9.POST /questions returns 403 in none/static_token auth mode, by
design: those modes give every caller the same subject, so job ownership
cannot be enforced, and one shared bucket would let each caller read the
others’ results. Deny-by-default — not a gap to close by relaxing it.SOURCE_CONFIDENCE_THRESHOLD (0.70),
MIN_SOURCE_CONFIDENCE (0.70) and
guardrails.grounding.MIN_LEXICAL_OVERLAP (0.15) were chosen to err
toward deferring to the LLM classifier and toward not refusing a
correct answer. The deterministic router’s signal patterns are
hand-authored, and the eval harness still covers the SQL path only, so
routing accuracy has no labelled-corpus measurement behind it. Treat
AskResponse.source_confidence as evidence, never as a probability that
an answer is correct.docs/EVALUATION_CURRENT.md’s accuracy numbers predate
many pipeline changes, and the question queue’s 100-concurrent path has
only been exercised against a mocked runner — never against a live
database and Ollama, which is what python scripts/integration_test.py
is for.mypy . reports 631 errors across 115 files, of
which 616 are in tests/ and 8 in eval/security_benchmark/ (largely
AgentState-vs-dict looseness) — a bounded, separate hygiene pass.
black --check . is clean (1,635 files) and ruff check . has exactly
one finding, an import-order I001 in agent/multiagent/agents.py.
The “production modules are otherwise clean” claim this entry used to
make is no longer true — seven of those errors are in production code,
so it is named here rather than left for a session to trip over:
agent/sql_validator.py:839 (two errors — a # type: ignore[union-attr]
that no longer covers the code actually reported; introduced by 933cfff,
2026-10-17, so not ancient), db/schema_introspection.py:376
(25073964, 2026-10-04), and four SQLAlchemy
SQLCoreOperations[...]-vs-None assignments in
identity/repositories/semantic_intelligence.py:199,200,242 and
identity/repositories/recommendation_governance.py:402. mypy is
report-only in CI (§5.7), so nothing is blocking them.
Re-measured 2026-10-17 at 08f385e: every figure above still holds
exactly — 631 mypy errors in 115 files with the same 7 production
findings, black clean over 1,635 files, one ruff I001. No drift, so a
new finding is attributable. The one addition: bandit now reports 4
Low findings, not 3 — agent/sql_validator.py:842
(B112 try_except_continue) joined the set, introduced by 933cfff’s
describe_sql, alongside agent/harness/retry.py:75 (B311),
api/streaming.py:82 (B101) and security/audit_log.py:255 (B110).
Still 0 High and 0 Medium, and all four are deliberate and already
annotated for ruff but not for bandit — which is why that blocking
gate fails (§5.7).Three tests fail only in file order, and the cause is cross-file
state, not the tests. Measured 2026-10-22: a full pytest run
reports 6 failures, three of which are
tests/test_agent_nodes.py::TestGenerateRecommendationsNodeQueryStore::{test_non_mssql_database_never_calls_query_store,test_feature_flag_off_never_calls_query_store,test_query_store_failure_fails_open}.
All three pass when that file runs alone and fail when
tests/security/ runs first (pytest tests/security
tests/test_agent_nodes.py::TestGenerateRecommendationsNodeQueryStore
reproduces it in ~1 min) — tests/security/ sorts before every root
test_*.py, so a default full run always hits it. Each asserts
recommendations == [], so something in tests/security/ leaves a
recommendation-producing state behind that tests/conftest.py’s three
cache clears do not cover. Verified pre-existing, by stashing the
working tree and reproducing identically. Not yet attributed to a
specific leaking test.
The local 7B model still refuses some answerable terse questions.
Measured 2026-10-22, after the retrieval fix in
embeddings.retriever._select_by_relevance (see
docs/ARCHITECTURE.md’s retrieve_schema_node
entry): of six phrasings of “top selling products”, four now answer
correctly, while “Worst selling products” and “Most popular
products” still end in rejection_reason=off_topic. This is no
longer a retrieval problem – the generation prompt verifiably contains
FactResellerSales and SalesAmount (19,494 chars, one model call),
and qwen2.5-coder:7b returns the literal string NOT_A_QUERY
anyway. Deterministic across repeated runs. Confirmed to be model
capacity, not the pipeline: re-running the same two questions with
model="llama3.1:8b" answered both – “Worst selling products” in
316.1s (10 rows) and “Most popular products” in 110.7s (10 rows),
through the identical graph, schema and prompt. So OLLAMA_MODEL is a
real lever an operator already has; note the latency it costs on this
hardware (see docs/PERFORMANCE.md), which is
why it is not simply changed here. The other lever is the generation
system prompt, and that is benchmark-pinned (§12), so changing it needs
the benchmark re-run – a deliberate, separate exercise at ~80s per
question. Do not “fix” this
by retrying the off-topic sentinel: agent.nodes.generate_sql_node
deliberately never retries it (there is no error to feed back), and
turning a refusal path into a retry path would both cost a second full
generation cycle and weaken a control. Note also that SQL quality on
these terse questions is uneven even when they succeed – one phrasing
returned a bare product list with no measure column, another a single
row – which is the same model-capacity limitation, not a pipeline bug.
gitleaks, mypy (§5.7), the Trivy container scan — report-only because
the action only fails a step when its exit-code input is set, which it
deliberately is not, making that step’s continue-on-error redundant —
and the load-test smoke scenario. Every other gate blocks (§5.7).
Note that .github/workflows/ci.yml’s own comment on the mypy step still
describes the older measurement (“281 … all in test files”); the figures
above are the current ones.
See docs/security/CVE_TRIAGE.md.