Prompt 01 of the 32-prompt Enterprise AI Analytics & Recommendation
Platform initiative (00_MASTER_IMPLEMENTATION_CONTRACT.md). INSPECT
only — no application code was changed to produce this document. Every
claim below was verified against the actual source at commit 97d8a2f
(git log --oneline -1), not against prior memory of this repo alone —
file lists, node-graph wiring, permission enums, and duplication checks
were all re-run fresh for this report (see “How this was verified” at the
end).
Two pieces of untracked clutter found during inspection, neither part of the real source tree, neither touched:
env/, env1/ at repo root — two stray, self-.gitignore‘d Python
virtualenvs (dated 2026-09-17/18), separate from the project’s real
.venv that every doc/script actually references. Not tracked, not
referenced by tasks.ps1/Makefile/CLAUDE.md. Safe to delete
whenever convenient; not touched here since deleting wasn’t asked for.eval/load/k6;C — an empty, untracked, oddly-named directory (likely a
path-splitting artifact from an earlier Windows shell command). Harmless.eval/load/.env.loadtest exists on disk but is byte-for-byte identical
to the committed .env.loadtest.example and is correctly gitignored
(git check-ignore confirms) — exactly the “generated by make
load-test, throwaway credentials” behavior .gitignore’s own comment
documents. No secret leak.agent/graph.py::build_graph() (verified via add_node/add_edge calls,
not assumed) wires exactly these 12 nodes, entry point sanitize_input:
sanitize_input -> classify_followup -> retrieve_schema -> retrieve_golden_examples
-> retrieve_business_context -> plan_query -> generate_sql -> review_sql
-> validate_sql -> estimate_cost -> execute_sql -> generate_insight -> END
Conditional edges (not shown above) route a review/validation/cost/execution
failure back to generate_sql, or a “missing reference” execution error
back to retrieve_schema, bounded by state["max_retries"]
(agent/complexity.py::compute_max_retries, not a flat constant) — see
docs/ARCHITECTURE.md §2 for the full per-category routing table, which
was spot-checked against agent/nodes.py’s actual routing functions and
found accurate.
AgentState (agent/state.py, a TypedDict) carries selected_database
and selected_model — both resolved exactly once, read-only downstream,
verified as the pattern every retry path actually reuses rather than
re-selecting.
When ENABLE_MULTI_SOURCE_ROUTER=true, agent/orchestrator/graph.py
wraps this entire graph as one opaque sql_subgraph node alongside
document_rag/policy_rag/web_search/generation/media_search/
attachments — confirmed the flag-off path (agent.orchestrator.graph
.run_orchestrated) still calls agent.graph.run_agent directly with the
orchestrator graph never constructed, by reading the function body, not
by trusting the docs.
| Capability | Location | Status | Decision for future prompts | Key dependencies |
|---|---|---|---|---|
| LangGraph SQL pipeline (12 nodes) | agent/graph.py, agent/nodes.py, agent/state.py |
Working, extensively tested | REUSE as-is. This is the core; any new analytics/recommendation capability should sit beside or downstream of this graph’s output, never fork it. | langgraph, agent/llm_client.py, db/ |
| Multi-source orchestrator | agent/orchestrator/ |
Working, flag-gated off by default | EXTEND. Adding a new source (e.g. a recommendation engine) means one more node in get_available_sources/route_after_router, not a new orchestration layer. |
agent/graph.py (wrapped, not modified) |
| Generic Tool/MCP registry | agent/tools/ |
Built, tested, not wired into the live request path (docs/TOOLS.md discloses this explicitly) |
REUSE the abstraction, finish the wiring if a future prompt needs dynamic tool selection (e.g. an AI agent choosing “run analytics query” vs “fetch recommendation” at runtime) rather than a fixed graph edge — this is the one piece already built for exactly that shape of problem. | agent/orchestrator/nodes.py’s six real functions |
| SQL generation | agent/llm_client.py::generate_sql_from_llm |
Working | REUSE. Model-selectable (AgentState["selected_model"]), prompt-injection-hardened. |
Ollama, config/ollama_models.py |
| SQLGlot/AST validation | agent/sql_validator.py |
Working, single source of truth (grep-confirmed: no second validator anywhere in agent/api) |
REUSE, EXTEND the violation taxonomy if needed. SAFETY_VIOLATION_TYPES is a frozenset an analytics feature can add to (e.g. a new disallowed pattern) without touching the allow-list logic itself. |
sqlglot |
| SQL cost estimation | db/query_cost.py |
Working | REUSE. Dialect-aware, four backends. | db/connection.py |
| Multi-database routing | embeddings/retriever.py::select_database |
Working, single-database-common-case short-circuit verified | REUSE. Any new per-database analytics feature already has a real database-selection hook to key off AgentState["selected_database"]. |
embeddings/schema_indexer.py (one Chroma collection per DB) |
| Schema retrieval / value sampling | db/schema_introspection.py, db/value_sampling.py, embeddings/schema_indexer.py |
Working | REUSE. Live introspection, not a cached/hardcoded schema — a new analytics feature over the same databases gets this for free. | ChromaDB, SQLAlchemy Inspector |
| Golden examples (confirmed-correct SQL) | embeddings/golden_examples.py |
Working | REUSE — closest existing analog to “confirmed business truth” for SQL, see §4 below. | ChromaDB |
| Business-context retrieval (glossary/metrics/relationships) | retrieval/ |
Working, 7 typed chunk kinds | REUSE/EXTEND. A recommendation engine’s own business rules/metric definitions are a natural 8th chunk kind here rather than a new retrieval system. | ChromaDB (shared client) |
| Document/policy RAG | rag/ |
Working, requires SQL Server 2025+/Azure SQL VECTOR (see §5) |
REUSE. One implementation parameterized by collection name already. | Dedicated SQL Server connection, separate from DB_CONNECTIONS |
| Grounded insights | agent/insight.py |
Working — deterministic ResultSummary computed in Python, is_insight_grounded() rejects any LLM claim not traceable to allowed_values()/allowed_percents() |
EXTEND — this is the real foundation for rule 9/10’s truth-provenance requirement. See §4. trend/outliers/stddev fields exist and are tested but explicitly not yet wired into the live prompt (a disclosed, deliberate gap, not an oversight). |
None new |
| Feedback (golden + general) | embeddings/golden_examples.py, feedback/store.py, POST /feedback/golden-example, POST /feedback/message |
Working | REUSE. Two purposes already cleanly separated: few-shot correction vs. general answer rating. | ChromaDB |
| Authentication | security/oidc.py, security/google_oidc.py, identity/ (local accounts), api/auth.py, api/identity_auth.py |
Working, 4 modes (none/static_token/oidc/local) |
REUSE. Do not add a fifth auth mechanism for a new platform surface — gate it behind the existing Settings.auth_mode dispatch. |
PostgreSQL (AUTH_DATABASE_URL), Argon2id, JWT |
| Authorization (AI-feature RBAC) | agent/authz.py (Permission enum, 15 values, verified by direct read) |
Working | REUSE, extend the enum. A new analytics/recommendation capability is a new Permission value + role mapping, not a new authz system. |
agent/orchestrator/nodes.py::router_node (already enforces this pre-subgraph) |
| Authorization (account/admin RBAC) | identity/rbac.py (separate, more granular permission set — deliberately not the same enum as agent/authz.py, bridged via base role names) |
Working. Permission.ADMIN_DASHBOARD_READ is defined and assigned to roles but is never checked by any real route today (grep-confirmed zero non-test call sites). |
EXTEND — this is a ready-made, unused hook for exactly the kind of admin analytics dashboard this platform mission implies. No new RBAC plumbing needed; wire this permission into new routes. | identity/rbac.py |
| Tenant isolation | security/tenancy.py |
Single-tenant by design, disclosed explicitly in the module’s own docstring. One function, resolve_actor_tenant_id, returns one constant ("default") for every real user today. Only the conversation-sharing feature’s ABAC engine (identity/share_policy.py) actually threads a tenant_id through and enforces a tenant-match condition — genuinely tested (tests/test_share_policy.py::TestCrossTenantIsolation), not just scaffolded. |
NEW / real gap. No other table, route, or RBAC check in the codebase is tenant-scoped. A real multi-tenant analytics platform needs this extended app-wide, not just for sharing — see §6. | None yet |
| Observability (structured logs, correlation IDs, metrics) | observability/metrics.py, observability/redaction.py, security/audit_log.py |
Working, single-process/in-memory (disclosed limitation) | REUSE. PerformanceMetrics singleton already aggregates per-stage timing; a new analytics feature’s own instrumentation should feed the same singleton, not a parallel metrics store. |
None new |
| Rate limiting / admission control | agent/rate_limit.py (single source — grep-confirmed no second RateLimiter class anywhere), api/rate_limit.py (thin wrapper, identity-aware) |
Working | REUSE. Sliding-window + bounded-concurrency primitives already exist for exactly “protect an expensive AI/DB call.” | None new |
| Load testing | eval/load/ (k6 scenarios, mock Ollama server, seeded Postgres) |
Working, Phase 0 only (docs/SCALE_BASELINE.md) |
REUSE/EXTEND. Add a new k6 scenario for a new endpoint rather than a new harness. | Docker Compose |
| Evaluation harness | eval/ (dataset loader, evaluators, metrics, regression) |
Working, execution-accuracy-first | REUSE/EXTEND. A recommendation feature needs its own dataset + evaluator, same shape as eval/rag_evaluators.py/eval/web_search_evaluators.py, not a new harness. |
None new |
| Frontend (React dashboard) | frontend/src/ |
Working | REUSE/EXTEND. No admin/analytics page exists yet (find frontend/src -iname "*admin*" -o -iname "*dashboard*" returns nothing) — a new page under pages/, not a new frontend app. |
Vite, Zustand, react-query |
| Deployment/config | docker-compose.yml, Dockerfile, config/settings.py (218 real fields, pydantic_settings.BaseSettings) |
Working | REUSE. New settings are new typed Settings fields with real defaults, following the existing convention. |
— |
Grep-verified, not assumed, scoped to real project source (excluding
.venv/env/env1/node_modules):
agent/sql_validator.py);
agent/nodes.py only calls it.*Limiter class
(agent/rate_limit.py); api/rate_limit.py wraps it rather than
reimplementing._issue_tokens helper
(api/identity_auth.py); Google sign-in (security/google_oidc.py)
calls into it rather than minting its own session shape.get_chroma_client
(embeddings/schema_indexer.py), reused by every other Chroma-backed
module (golden_examples.py, retrieval/, media/store.py,
feedback/store.py).security/redaction.py,
observability/redaction.py) but are not duplicates — verified by
reading both docstrings: one redacts secret strings from arbitrary
text, the other summarizes a query result’s shape for logging (never
touches secrets). Distinct, complementary concerns, correctly named
apart.No further duplication found in the areas this prompt required inspecting.
No DATABASE_FACT/AI_INFERENCE/CONFIRMED_BUSINESS_TRUTH vocabulary
exists anywhere in this codebase today (repo-wide grep, project source
only, zero hits). This is genuinely new work, not a rename of something
existing. But three real mechanisms already enforce a version of this
distinction in practice and are the concrete extension points:
agent/insight.py’s grounding gate is the strongest existing
analog to “never silently convert AI_INFERENCE into
CONFIRMED_BUSINESS_TRUTH.” ResultSummary (a ColumnStat/aggregate
summary) is computed deterministically in Python from the actual
query result — this is DATABASE_FACT. generate_insight_from_llm’s
output is AI_INFERENCE — an LLM narrative sentence. is_insight_grounded()
rejects any numeric/percent claim in that narrative that isn’t
traceable to ResultSummary.allowed_values()/allowed_percents(),
i.e. it structurally prevents an ungrounded inference from reaching
the user framed as fact. This pattern (compute-then-constrain, never
let the LLM assert an unverifiable number) is exactly what a future
prompt should generalize into an explicit typed contract, rather than
reinventing grounding logic per feature.embeddings/golden_examples.py) are the closest
existing analog to CONFIRMED_BUSINESS_TRUTH for SQL specifically — a
human explicitly promotes an AI-drafted-then-corrected query into a
trusted, reusable example via an explicit UI action (thumbs-up after
“Confirm and Run”), never automatically. The promotion step already
exists; it’s just not labeled with this vocabulary or generalized
beyond SQL.config/table_descriptions.yaml/config/sensitive_columns.yaml
are hand-reviewed, human-authored business semantics overlaid onto
live schema DDL at retrieval time — another real (if narrow) example
of “a human, not the LLM, is the source of confirmed business
meaning.”Recommendation for a later prompt: introduce one small, shared typed
module (e.g. agent/provenance.py) defining the three states as an
explicit enum/tagged union, and retrofit ResultSummary/insight output,
golden examples, and any new recommendation output to carry this tag —
rather than each new feature inventing its own ad hoc “is this confirmed”
flag.
rag/store.py (document/policy RAG) requires SQL Server 2025+ or
Azure SQL specifically, for the native VECTOR column type — a real,
disclosed constraint separate from the four DB_TYPEs
(postgresql/mysql/mssql/oracle) the core SQL pipeline supports.moderation/store.py also requires a dedicated SQL Server
connection, for the same reason.config/table_descriptions.yaml/config/sensitive_columns.yaml
are keyed by bare table name, not (database, table) — a disclosed,
narrow limitation if two configured databases share a table name.config/column_labels.py’s ABBREVIATION_EXPANSIONS dict
("Cust" -> "Customer", "Qty" -> "Quantity", etc.) is hand-tuned
for the AdventureWorksDW2025 sample schema’s own naming conventions —
a real, narrow, disclosed piece of hard-coded business semantics that
a genuinely generic analytics platform would need to make
schema-configurable rather than a single static dict.data/knowledge/’s sample business-context content (glossary,
metrics) is explicitly labeled illustrative demo content, not reviewed
production documentation (CLAUDE.md’s own disclosure, confirmed
still true by inspection).db.connection.check_write_privileges startup-checks it) -> RBAC
(agent/authz.py, enforced before the orchestrator router picks a
subgraph, not just at the API edge) -> tenant/ownership scoping
(currently real only for conversation sharing, see §2/§6 tenant row).agent/llm_client.py)
and every SQL execution (db/execution.py) is a synchronous call
occupying a request thread — bounded now by Settings
.max_concurrent_ask_requests’s ThreadPoolExecutor (real admission
control, added in the Scale-out program), but there is still no true
async request handling or cross-thread cancellation
(docs/SCALE_OUT_PROMPT.md’s own disclosed Phase 1 scope). Any new
analytics/recommendation feature that adds its own LLM/DB calls
inherits this same constraint and should be sized against the existing
max_concurrent_ask_requests-vs-DB-pool sizing warning
(api/main.py::_warn_on_ask_concurrency_pool_mismatch), not a fresh
capacity assumption.api/main.py’s StaticFiles mount) at the same
origin — no /api prefix, no CORS needed for the common deployment
shape. A new analytics/recommendation UI surface should follow this
same single-origin convention rather than introducing a second
frontend origin/build.No application code changed in this prompt, so the existing test suite
was not expected to move — verified this is genuinely true (git status
shows only the two new 00_/01_ documents as untracked, git log -1
unchanged) rather than assumed, and the following results are the
already-current, just-verified state at this exact commit
(97d8a2f), not a re-run of unrelated work:
| Suite | Result |
|---|---|
pytest (backend, 140 test files) |
2,303 passed |
vitest run (frontend, 41 test files) |
277 passed |
ruff check . |
7 pre-existing findings (disclosed in CLAUDE.md’s own CI-hygiene note), none touched by this prompt |
black --check . |
11 pre-existing findings, none touched by this prompt |
mypy . |
236 pre-existing errors, none touched by this prompt |
tsc --noEmit (frontend) |
Clean |
oxlint (frontend) |
Exit 0, pre-existing warnings only |
npm run build (frontend) |
Succeeds |
Every table row and claim above traces to a specific command run against
the live repository during this prompt, not to recalled documentation:
git log/git status for commit state; ls/find/Glob for every
module’s actual file list; grep -n "add_node|add_edge" against
agent/graph.py for the node graph; grep for class Permission/Permission\.
against agent/authz.py/identity/rbac.py for the two RBAC enums and
the unused ADMIN_DASHBOARD_READ finding; repo-scoped grep (explicitly
excluding .venv/env/env1/node_modules) for the duplication scan
and the truth-provenance vocabulary search; direct reads of
security/tenancy.py, observability/redaction.py,
config/column_labels.py, and agent/insight.py for the sections that
needed more than a file listing.