# AI Query Engine Architecture

## Integration Points

The assistant is implemented inside the existing Electron/React/TypeScript architecture:

* Shared contracts live in `packages/shared/src/contracts/ipc.ts`.
* Backend orchestration lives in `apps/backend/src/application/services/ai-query-service.ts`.
* Electron IPC handlers live in `apps/desktop/src/main/ipc/register-ipc.ts`.
* Renderer access uses the existing `posApi` preload/dev bridge pattern.
* The UI is mounted from `TopBar` as a right-side chat drawer.

## Backend Flow

1. Read Prisma DMMF metadata at service startup and cache it by model name.
2. Normalize the user question and resolve the best model from schema/table/field terms.
3. Generate a read-only Query AST.
4. Validate AST operations, table, selected fields, filters, grouping, ordering, and limit.
5. Apply RBAC and branch scoping from the current auth session.
6. Execute via Prisma delegates only. No generated raw SQL is accepted or executed.
7. Format rows, aggregates, and query insights into a conversational response.
8. Persist conversation messages in memory per session and write AI activity to `AuditLog`.

## Runtime Metadata

The metadata generator uses Prisma model definitions and does not require module mappings, aliases, or manually maintained business dictionaries. Each model record contains:

* model name
* table name
* fields
* scalar types
* enum references
* relation targets
* unique fields
* indexed fields when available from Prisma metadata

## Permission Model

The assistant inherits the logged-in user context. It allows read-only analytical access only when the user has at least one reporting/dashboard/module read permission or a privileged admin role. Branch-scoped models automatically receive a `branchId` filter unless the user is allowed to query all branches.

## Non-Goals

This implementation does not execute arbitrary LLM SQL, mutation operations, or ad hoc raw database statements. A future external model can be attached only at the AST-planning boundary and must pass the same validator.
