feat(ingestion): add Phase 1 database and application foundation

Add the scoped PostgreSQL/pgvector schema, independent ingestion settings and ports, embedding profile checks, and trusted administrator bootstrap.

Include repository contracts and guidance, organized provider-free and PostgreSQL tests, deployment setup, and byte-preserving migration attributes.

Validation: 163 tests passed; all 48 PostgreSQL cases passed with pgvector Python 0.5.0 and 0.3.6. No production schema or historical metadata was changed.
This commit is contained in:
amirhosein mazaheri
2026-10-05 16:38:28 +03:30
parent cb54a35c90
commit baf58da562
50 changed files with 4628 additions and 3 deletions
+631
View File
@@ -0,0 +1,631 @@
# Organization Knowledge Assistant — Software Architecture
| Document field | Value |
| --- | --- |
| Version | 1.1 — simplified document lifecycle |
| Date | 2026-10-05 |
| Status | Proposed implementation design; open decisions are listed in Section 19 |
| Audience | Project management, technical mentor, backend, frontend and AI developers |
| Application | Organization-managed document RAG with text and direct live voice conversations |
| Source baseline | Project requirements and architecture decisions recorded during design |
Document lifecycle decision (revision 1.1): every upload is an independent immutable document. Chunks and ingestion jobs reference it directly; answer sources use document/chunk IDs. Content versioning is not a current requirement. Settings revisions and embedding profile metadata remain technical controls, not document versions.
## 1. Purpose and Scope
The system enables authenticated users to ask questions in Persian, including conversational wording, and receive answers grounded in reference documents selected by their organization. It supports text chat and direct speech-to-speech interaction with a live AI model. Organization administrators manage the knowledge base without changing application code.
The initial business use case is a reliable demonstration and subsequent organizational service. Business success depends on understandable answers, verifiable sources, document coverage and dependable operation. This architecture does not guarantee commercial outcomes or zero hallucinations.
### 1.1 Confirmed design constraints
- PostgreSQL with pgvector stores application data and document embeddings.
- OpenAI supplies embedding and text generation capabilities; exact model identifiers remain configurable and must be evaluated.
- Voice conversations use a live speech-to-speech model and WebRTC. There is no separate application ASR or TTS pipeline.
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
- Documents are dynamically uploaded, updated and selected by the organization.
- The only initial knowledge tool is `search_documents`. A separate read-document tool is excluded.
- Text and voice have separate entry points but share retrieval, access rules, configuration and persistent history services.
- The dashboard includes login, document management, model configuration, text entry and microphone controls.
### 1.2 Proposed implementation choices
A modular monolith built with Python and FastAPI, plus a separate ingestion worker from the same codebase, is the proposed deployment baseline. PostgreSQL-backed jobs avoid requiring a separate broker initially. LangGraph may continue to orchestrate text-agent turns. The provider-native live session performs the voice conversation loop; LangGraph does not need to process every audio frame.
These choices are architecture recommendations, not claims that the existing repository already implements them. File formats, live provider/model, authentication integration, retention rules, capacity targets and delivery dates require confirmation.
### 1.3 Scope boundaries
The initial system includes document ingestion, organization-scoped retrieval, text and live voice conversations, citations, configuration, operational logging and basic administration. Fine-tuning, autonomous database writes by the model, internet search, arbitrary tools, CTI integration and a separate audio transcription service are outside the current scope. Raw audio recording is not a baseline requirement.
## 2. Architecture Principles
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
4. **Direct live audio:** browser-to-provider media is separate from backend session control and tool execution.
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
8. **Incremental implementation:** add extraction strategies and retrieval refinements based on actual documents and evaluation results.
## 3. System Context and Deployment Boundaries
| Component | Responsibilities | Deployment |
| --- | --- | --- |
| Web dashboard | Login, chat, microphone/speaker, captions, sources, document and settings screens | Browser over HTTPS |
| FastAPI application | Authorization, text orchestration, live session control, tools, document APIs and history | Backend process |
| Ingestion worker | Extraction, chunking, embedding, retries and publication | Separate process from the same codebase |
| PostgreSQL + pgvector | Metadata, jobs, history, configuration, chunks and vectors | Persistent database |
| File storage | Original uploaded document bytes | Durable volume or object storage |
| Text/embedding provider | Text-agent inference and vector generation | External OpenAI API |
| Live provider | Direct audio understanding and speech generation | External live model service |
A provider adapter is backend code. It is not the provider service. The browser connects to the provider's WebRTC media endpoint, while the backend owns credentials, session policy and private tool execution.
The two presentation diagrams are retained in Appendix A. They show logical responsibilities; they do not imply that the live model runs inside the backend deployment.
## 4. Backend Modules and Dependency Rules
| Module | Owns | Public application operations |
| --- | --- | --- |
| Identity | Users, organization memberships and session authorization | Authenticate user; resolve organization and role |
| Documents | File metadata, ingestion state and selection | Upload independent document; list; activate; deactivate |
| Knowledge | Chunk retrieval and evidence construction | Search authorized knowledge |
| Conversations | Conversations, turns, messages, citations and summaries | Start; submit turn; read history; close |
| Live Sessions | Provider session mapping, connection state and live event handling | Create; connect control channel; process event; close |
| Configuration | Allowed model profiles and retrieval settings | Read and update versioned settings |
| Audit/Operations | Administrative events, traces and health | Record audit event; expose operational status |
API handlers validate transport data, authenticate and call application services. Application services coordinate domain rules through interfaces. Provider clients, SQLAlchemy repositories and file-storage implementations belong to infrastructure. Tools call application services rather than API endpoints inside the same process.
Shared organization context is created from authenticated identity. Client input and model arguments cannot override it. Cross-module access uses explicit operations rather than arbitrary writes to another module's tables.
### 4.1 Suggested code organization
| Path | Purpose |
| --- | --- |
| `app/main.py` | API bootstrap and dependency wiring |
| `app/worker.py` | Ingestion worker entry point |
| `app/api/v1/` | HTTP and application event endpoints |
| `app/modules/identity/` | Authentication and authorization |
| `app/modules/documents/` | Document lifecycle |
| `app/modules/knowledge/` | Retrieval and search tool contracts |
| `app/modules/conversations/` | Text turns and persistent history |
| `app/modules/live/` | Live session controller |
| `app/modules/configuration/` | Model profiles and organization settings |
| `app/integrations/ai/` | Text, embedding and live provider adapters |
| `app/infrastructure/db/` | Repositories, migrations and database sessions |
| `app/infrastructure/storage/` | Original-file access |
| `app/infrastructure/jobs/` | Durable job claiming and retry implementation |
| `tests/` | Unit, integration, contract and scenario evaluations |
Use application/domain/infrastructure subdivisions where module complexity warrants them. Do not introduce empty abstractions solely to match the proposed directory structure.
## 5. Agentic Conversation Design
### 5.1 Agent responsibilities
The agent interprets the user's wording and conversation context, asks clarification when meaning is ambiguous, and calls `search_documents` for organization-specific facts. It can answer greetings and conversational coordination without retrieval. For factual questions about the documents, it is instructed to obtain supporting evidence before answering.
The agent may reformulate queries while preserving dates, negation, location, units and other constraints. It must distinguish, for example, general opening hours from Thursday-specific hours. It can issue another search when initial results are incomplete, subject to configured call and time limits.
Document content is evidence, not executable instructions. Retrieved text cannot grant permissions, change tools or override the agent policy. Answers should identify uncertainty and conflicting sources rather than silently resolve a policy dispute.
### 5.2 Agentic behavior and enforcement
The model's choice to search is probabilistic. A system prompt alone cannot guarantee that every factual response is grounded. The application enforces tool authorization, budgets and source validity; evaluation checks whether the model calls the tool appropriately and supports its claims.
For text responses, validate structured source references before finalizing a turn. If the model returns invalid references, use a bounded repair attempt or return a controlled error. A stricter pre-release factuality gate can be added if evaluation requires it.
For direct live speech, audio may reach the user before a server-side validation step finishes. This architecture therefore does not claim a prevalidated guarantee for every spoken sentence. If that guarantee becomes mandatory, the audio release/control design must be revisited and its latency impact accepted explicitly.
### 5.3 Text turn sequence
1. Authenticate the request and verify conversation ownership.
2. Persist the user message using a client request ID to detect retries.
3. Load bounded conversation context and a configuration/document-selection snapshot.
4. Run the text agent with the registered search tool.
5. Validate and execute tool calls through the shared knowledge service.
6. Return tool evidence to the same agent loop.
7. Produce a response, validate reference IDs and persist the assistant message and citations.
8. Return the final answer or stream supported application events.
A failed turn is recorded explicitly and does not appear as a completed assistant answer. Retrying a completed request returns the existing result instead of creating duplicate messages.
## 6. Search Tool Contract
### 6.1 Model-visible interface
```json
{
"name": "search_documents",
"description": "Search the organization's selected reference documents for evidence relevant to a question.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "A focused search question preserving the user's constraints."}
},
"required": ["query"],
"additionalProperties": false
}
}
```
The tool does not accept organization IDs, arbitrary document paths, SQL, credentials or a model-selected permission scope. The backend supplies identity, allowed documents, embedding profile, retrieval limits and trace identifiers through trusted execution context.
### 6.2 Result contract
```json
{
"status": "ok",
"search_id": "search_example",
"selection_revision": 7,
"results": [
{
"source_ref": "S1",
"document_id": "doc_example",
"chunk_id": "chunk_example",
"title": "Working Hours Policy",
"page": 3,
"section": "Thursday Schedule",
"text": "Illustrative evidence text from the uploaded document."
}
],
"warnings": []
}
```
The sample IDs and content are illustrative. Page and section are nullable when extraction cannot identify them. References are scoped to a turn/search; persistent citations use stable document/chunk IDs. Never fabricate page numbers.
Tool statuses distinguish `ok`, `no_results`, `knowledge_unavailable` and `error`. An empty authorized knowledge base is different from an unrelated query; a provider failure must not be presented as proof that no relevant document exists.
### 6.3 Execution pipeline
1. Validate non-empty query and enforce configured length/call budgets.
2. Resolve organization access and selected documents from trusted state.
3. Recheck current document permissions and deactivation before retrieval.
4. Normalize Persian query text without changing semantic constraints.
5. Embed the query using the compatible embedding profile of the active index.
6. Run filtered vector retrieval and optionally combine lexical results.
7. Deduplicate, select relevant chunks and cap the evidence token budget.
8. Build references from stored metadata and persist retrieval provenance.
9. Return evidence to the requesting text or live agent.
The semantic baseline is required. Lexical fusion and reranking are optional improvements enabled after measurement. Persian lexical behavior must be tested with actual data; a generic full-text configuration is not assumed to provide Persian stemming automatically.
Similarity values are ranking signals, not probabilities that an answer is correct. Any relevance threshold is calibrated against the evaluation set. For small datasets, exact vector search is an acceptable baseline. Approximate index choice, filtered recall and performance are measured before deployment.
## 7. Dynamic Document Lifecycle
### 7.1 Upload and extraction
The API validates the configured file allowlist, size and basic file signature, stores the original under a generated storage key, calculates a checksum, creates an independent document and enqueues a durable ingestion job. Client filenames are display metadata and never trusted filesystem paths.
Accepted formats remain an open requirement. The extraction interface supports implementations chosen after representative files are received. OCR is enabled only if scanned material requires it. Empty or unreadable extraction must fail visibly rather than publishing an empty index. Table structure and units must be preserved where needed by the actual corpus.
### 7.2 Document processing states
```mermaid
stateDiagram-v2
[*] --> queued
queued --> processing
processing --> ready
processing --> failed
failed --> queued: Retry
ready --> deleted: Delete
```
Activation/selection is separate from processing state: a ready document can remain unselected. Only selected ready documents can be searched.
### 7.3 Chunking and embedding
Each chunk preserves its document identity, order, text and available source location. Chunk size and overlap are configurable and recorded as processing metadata. The design must avoid splitting meaningful table rows or dropping headings when those structures carry meaning.
Embedding profiles record provider, model, dimensions and preprocessing version. Documents and queries must use the same compatible profile. Changing the embedding model creates a new index generation: re-embed, verify completion and switch the active generation atomically. Equal vector dimensions do not make two embedding models interchangeable.
### 7.4 Publication, updates and selection
Each upload creates a new independent document; there is no document-version entity or in-place content replacement. Upload the changed file, wait until it is ready, then deactivate the old document and activate the new one. The old document remains inactive for historical reference. Failure of the new upload leaves the old active document usable. Retry processes only the same failed document and creates no new identity.
An administrator selects ready document IDs for the organization. Every turn records the effective selection revision and the source document/chunk IDs. A selection change applies to subsequent turns. Current access revocation/deactivation overrides cached or snapshotted access immediately for new tool operations; sensitive in-flight results must be rechecked before delivery.
Previously sent evidence cannot be recalled from a provider context. On document revocation during a live conversation, invalidate affected context and reset or close the provider session when necessary. Previously delivered speech cannot be withdrawn. The UI must not imply that changing selection rewrites old answers.
Deletion first excludes the document from retrieval. Physical deletion follows the retention policy, including chunks, vectors, originals and derived copies. Historical citations retain minimal tombstone metadata when permitted; access to retained content still requires authorization.
### 7.5 Durable worker behavior
The worker claims jobs with a lease and claim token, updates progress and publishes only if it still owns the claim. Expired leases allow recovery after a crash. External embedding calls occur outside long database transactions. Idempotent chunk writes and publication prevent duplicate indexed chunks after retries.
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
## 8. Live Voice and WebRTC
### 8.1 Connection responsibilities
| Channel | Participants | Purpose |
| --- | --- | --- |
| HTTPS session request | Browser and FastAPI | Authenticate and initialize an authorized live session |
| WebRTC media | Browser and live provider | Microphone input and generated speech |
| Trusted control connection | Backend and live provider | Tool calls/results, policy updates and session events |
| Application event channel | Backend and browser | Source references, status and normalized captions when available |
OpenAI's WebRTC and server-control documentation establish the direct browser media and trusted server connection patterns [R1, R2]. Exact events and signaling depend on the selected API family. The adapter must implement one tested provider contract; event names from different API families must not be mixed.
### 8.2 Session establishment
1. The authenticated browser obtains microphone permission and creates a WebRTC offer.
2. The Live Session API verifies ownership, role, usage limits and selected knowledge.
3. The backend creates a local session record, resolves model/prompt/tool configuration and performs provider signaling.
4. The controller attaches the trusted control connection and confirms that private tool execution is ready.
5. The browser receives the session ID and signaling response, then establishes media.
6. The dashboard presents connected/listening states and enables conversation.
A provider-supported short-lived credential flow may replace server signaling. Persistent provider keys remain on the server. Failed setup triggers cleanup of any partially created provider/local session. Readiness of the control path is required before allowing organization-knowledge conversation.
### 8.3 Voice tool cycle
```mermaid
sequenceDiagram
participant U as Browser
participant L as Live Model
participant B as Backend Controller
participant K as Knowledge Service
U->>L: Audio over WebRTC
L->>B: search_documents call
B->>B: Validate identity, scope and call
B->>K: Execute search
K-->>B: Evidence and sources
B-->>L: Correlated tool result
B-->>U: Source references
L-->>U: Generated speech
```
The controller invokes the same search application service used by the text agent. Tool results are correlated by provider session and call ID, and executed once or replayed from a saved result on duplicate events. Allow only registered tool names. Partial argument events are accumulated until the call is complete and validated.
### 8.4 Turn-taking, interruption and disconnects
The live provider handles speech input and output. Its turn-detection and interruption capabilities are configured and tested for Persian conversation. When interrupted, the UI stops queued playback using supported provider/browser controls; history distinguishes a completed response from an interrupted one. Generated text must not automatically be treated as fully heard speech.
Closing the session stops microphone tracks, closes the peer connection and provider control connection, and records termination reason and known usage. Abandoned sessions expire. Reconnection creates or resumes a provider session only when supported; it must not imply transparent recovery after a backend restart.
If the control connection fails while media remains connected, pause or close knowledge conversation rather than continuing unsupported answers. Late tool results for canceled turns are discarded or recorded without triggering a new response. The dashboard can offer text chat when voice setup fails.
### 8.5 History and audio limitations
No separate ASR service is introduced for persistence. Save transcripts/captions only when supplied by the provider, with their source and completion state. Missing transcript events remain missing; do not invent them. Provider captions may differ from what a user meant or actually heard.
The backend does not automatically possess audio bytes because media travels directly to the provider. Recording audio would require a separate explicit feature and retention decision. Durable history survives a provider session, but continuing a conversation requires explicitly restoring selected history or a summary into the new model context.
## 9. Logical Data Model
This is a proposed model for the RAG service, independent of the earlier CTI module's database. Exact SQL migrations follow review of these invariants.
| Entity | Important fields and purpose |
| --- | --- |
| organizations | ID, name, status |
| users / memberships | Identity, organization, role and active state |
| organization_settings | Revision, allowed model profiles, retrieval limits, active selection revision |
| documents | Organization, display name, checksum, storage key, MIME, processing status/profile, selected flag, deletion state |
| ingestion_jobs | Document, stage, state, attempts, lease owner/token, lease expiry, next attempt, error |
| embedding_profiles | Provider/model, dimensions, preprocessing version, index generation and active state |
| chunks | Document, ordinal, original and normalized text, page/section, processing profile |
| chunk_embeddings | Chunk, embedding profile/generation and vector |
| conversations | Organization, owner, title, mode, state and timestamps |
| turns | Conversation, sequence, client request ID, configuration/selection snapshot, state |
| messages | Turn, role, content, modality, provider item ID, completion/interruption state |
| tool_calls | Turn/session, provider call ID, validated query, execution state, result references and latency |
| message_sources | Message, document/chunk, source reference and supporting excerpt if allowed |
| live_sessions | Conversation, provider session ID, controller owner, model, connection state and timestamps |
| audit_events | Actor, organization, action, target, timestamp and redacted metadata |
All organization-owned access must enforce organization scope. Use foreign keys and constraints to prevent cross-organization relationships, not only API checks. Add unique constraints for chunk ordinals per document, client request IDs per conversation and provider event/call IDs in their proper scope.
Use relational columns for identifiers, statuses and queryable fields; JSONB holds variable provider metadata and processing details. Do not store secrets in metadata. Use timezone-aware timestamps in UTC and display localized time in the UI. Page numbering semantics must be recorded by the extractor.
Vector dimension and storage type must match the chosen embedding profile. Separate incompatible vector generations by table/partition or another explicitly tested strategy. Index foreign keys and frequent organization/status filters. Select approximate vector indexes only after measuring filtered recall and query latency [R4].
## 10. Application API Contracts
These are proposed application endpoints, not provider API endpoints. The three core business capabilities are document ingestion, text chat and live voice; supporting administration requires additional routes.
| Method and route | Purpose | Result |
| --- | --- | --- |
| `POST /api/v1/auth/login` | Local login if local authentication is selected | Secure session; final identity contract TBD |
| `POST /api/v1/auth/logout` | End authenticated session | 204 |
| `GET /api/v1/me` | Current identity and organization roles | 200 |
| `POST /api/v1/documents` | Multipart file upload | 202 with document/job IDs |
| `GET /api/v1/documents` | Paginated organization documents | 200 |
| `GET /api/v1/documents/{id}` | Metadata and processing state | 200 |
| `PATCH /api/v1/knowledge-selection` | Replace selected document IDs using expected revision | 200 or 409 |
| `DELETE /api/v1/documents/{id}` | Exclude and schedule permitted cleanup | 202 |
| `GET /api/v1/configuration` | Read organization settings and capabilities | 200 |
| `PATCH /api/v1/configuration` | Admin settings update using expected revision | 200 or 409 |
| `POST /api/v1/conversations` | Start text, voice or mixed conversation | 201 |
| `GET /api/v1/conversations/{id}/messages` | Authorized, paginated history | 200 |
| `POST /api/v1/chat` | Submit a text turn | JSON result, or explicit SSE mode |
| `POST /api/v1/voice/sessions` | Initialize live session and signaling | 201 |
| `POST /api/v1/voice/sessions/{id}/close` | Idempotent close | 200 |
| `GET /api/v1/conversations/{id}/events` | Authorized application event stream | SSE |
| `GET /health/live` | Process liveness | 200 |
| `GET /health/ready` | Ability to serve required dependencies | 200 or 503 |
All IDs from clients are checked for ownership. Pagination and upload limits are bounded. The internal search tool is not an unauthenticated public endpoint. Final endpoint names can evolve before frontend contract freeze.
### 10.1 Text turn example
```json
{
"conversation_id": "conv_example",
"client_request_id": "request_example",
"message": "What are the organization's Thursday working hours?"
}
```
```json
{
"conversation_id": "conv_example",
"turn_id": "turn_example",
"message_id": "msg_example",
"status": "answered",
"answer": "An answer grounded in the selected reference documents.",
"sources": [
{"source_ref": "S1", "document_id": "doc_example", "chunk_id": "chunk_example", "page": 3}
]
}
```
Final application statuses include `answered`, `needs_clarification`, `insufficient_information` and `failed`. Streaming text is provisional until the completion event validates the final source mapping. The UI must preserve errors or interruption instead of implying successful completion.
### 10.2 Upload response example
```json
{
"document_id": "doc_example",
"job_id": "job_example",
"status": "queued",
"searchable": false
}
```
### 10.3 Live session application contract
The baseline request carries `conversation_id`, `client_request_id` and a WebRTC SDP offer. The response carries an application session ID, the provider adapter's signaling answer and normalized connection state. If a credential-based setup is selected, define a separate validated response variant. Never expose a persistent provider key. Do not log SDP or temporary credentials by default.
### 10.4 Error envelope
```json
{
"error": {
"code": "KNOWLEDGE_NOT_READY",
"message": "Selected documents are not ready for search.",
"request_id": "req_example",
"retryable": true
}
}
```
Use 401 for unauthenticated access, 403/404 according to the resource-disclosure policy, 409 for revision/idempotency conflict, 413 for size limit, 415 for unsupported type, 422 for invalid input, 429 for quotas and 503 for unavailable dependencies. Never return internal exception strings or credentials.
## 11. Configuration and Model Boundaries
Separate text, live and embedding model profiles. Changing the response model does not rebuild embeddings; changing the embedding profile does. A live profile must support the chosen media and trusted tool-control features. The UI exposes only administrator-approved, capability-compatible models.
Configuration is revisioned. Record model, prompt, tool schema, retrieval profile and selection revision per turn/session. Apply ordinary model changes to new turns or sessions; do not silently mutate an active live session. Document access revocation is handled immediately as described in Section 7.
Provider adapters normalize completion events, tool calls, timeouts, rate limits, usage and error categories. They must not assume every model implements identical event schemas. Business services depend on interfaces such as TextModel, EmbeddingProvider, LiveSessionProvider, KnowledgeRepository and FileStore.
## 12. Security and Organization Isolation
Authenticate every application entry point and authorize every tool operation. Proposed roles are organization administrator and conversation user; additional roles require a product need. Ordinary users cannot change model credentials or organization selections.
Use HTTPS, server-managed secrets, controlled CORS origins and an explicit session expiration policy. If cookies are selected, apply secure/HttpOnly attributes and CSRF protection to mutations. If external SSO is selected, replace local credential handling while preserving application membership checks.
Treat uploads, model arguments and extracted content as untrusted input. Validate upload paths, avoid executing embedded content, limit parser resources and refuse unregistered tools. Restrict client ability to update provider session instructions or inject trusted tool outputs using available provider permissions. Validate remaining access assumptions during the live integration spike.
Document bodies and full prompts are not ordinary operational logs. Log IDs, stage, latency and redacted errors by default. Access to stored message content and citations follows organization membership and resource permissions. Administrative changes generate audit records.
## 13. Reliability and Concurrency
| Failure | Required behavior |
| --- | --- |
| Embedding rate limit | Bounded retry; preserve job state |
| Unsupported/unreadable file | Failed document with actionable reason |
| Replacement ingestion failure | Keep prior active document available |
| Database outage | Reject dependent operations explicitly; do not invent answers |
| Search timeout | Return tool error; distinguish it from no evidence |
| Duplicate tool event | Reuse correlated result; avoid duplicate execution/history |
| Lost live control channel | Pause or close knowledge interaction and notify UI |
| Browser disconnect | Cleanup after grace period and record uncertain completion |
| Worker crash | Recover expired lease and continue idempotently |
| Invalid citation | Repair within budget or fail the response |
Serialize mutating turns per conversation in the initial implementation. A text turn must not race with an active voice turn against the same context. Keep live session control owned by one backend process; multi-instance deployment requires routing/ownership and a defined restart policy.
Retries of text generation and live session creation can incur duplicate provider work after an ambiguous timeout. Correlate application requests, reconcile known provider state where supported and avoid blind automatic recreation. Idempotency keys include a payload hash; reusing a key with a different request returns a conflict.
## 14. Observability and Performance
Correlate request, organization, conversation, turn, live session, tool call, document and job IDs. Measure text time to first output, total turn latency, query embedding latency, retrieval latency, live tool turnaround, available audio latency measurements, ingestion duration, error rates and provider usage.
Do not treat server tool latency as end-to-end voice latency. Browser measurements are required to include microphone, network and playback behavior. Usage may be incomplete if a session terminates before final provider events; represent it as partial rather than zero.
Capacity targets remain to be agreed: concurrent text users, active voice sessions, corpus size, ingestion throughput, maximum upload size and acceptable percentile latency. Test on the intended deployment network and representative Persian documents. Connection pools, evidence budgets and concurrency limits should be tuned from measurements.
## 15. Deployment and Operations
The first deployment consists of the dashboard/HTTPS entry point, one FastAPI service, one ingestion worker, PostgreSQL with pgvector and durable file storage. API and worker share code and configuration but run as separate processes. Redis and an external broker are optional future components, not baseline dependencies.
Apply reviewed database migrations as an explicit deployment step. Keep separate development, test and production credentials. Readiness checks should validate required local dependencies without making expensive model calls on every health probe. Perform provider connectivity checks as controlled diagnostics.
Backups must cover both the database and original files with a restorable mapping. Test restoration and reindexing. Recovery objectives, retention schedules and backup frequency are operational decisions requiring approval; no numeric guarantee is implied by this document.
Graceful shutdown stops new sessions/jobs, drains active work within a configured deadline and records interrupted work. Live sessions cannot be assumed migratable between processes. Monitor disk space, job backlog, database connections and external provider quotas.
## 16. Validation and Acceptance
Build a reference evaluation set from approved organization documents and expected answers before tuning prompts. Include natural Persian variants, follow-up pronouns, dates, numbers, conflicting documents, absent information and questions about unselected documents.
| Area | Acceptance evidence |
| --- | --- |
| Retrieval | Expected evidence appears for representative questions; numeric recall target agreed with stakeholders |
| Grounding | Answer claims supported by cited passages; unsupported questions handled explicitly |
| Agent behavior | Appropriate search calls, bounded retries and clarification for ambiguity |
| Isolation | Cross-organization IDs and model-supplied scope cannot expose documents |
| Dynamic documents | Upload, select, replace, deactivate and delete reflected in new retrieval |
| Text history | Retry does not duplicate messages; restart preserves completed conversations |
| Voice | Direct speech-to-speech, searchable document answers, interruption, reconnect and close tested |
| Control security | Client cannot escalate tool access or change protected session policy |
| Ingestion recovery | Crashes and provider failures recover without duplicate publication |
| Deployment | HTTPS/microphone behavior, backups and demonstration network verified |
Use unit tests for permissions and state transitions, integration tests with PostgreSQL/pgvector, provider contract tests, and a small controlled live evaluation. Stub-only tests do not validate actual provider signaling or Persian audio quality. Evaluate text and voice independently even though retrieval is shared.
## 17. Migration from the Existing Repository
The earlier review inspected commit `cb54a35`; this mapping refers to that snapshot and is not a claim about a newer branch.
| Existing area | Required evolution |
| --- | --- |
| `app/services/retriever.py` | Replace Chroma/FastEmbed with repository and embedding interfaces backed by pgvector/OpenAI |
| `app/services/doc_processor.py` | Replace folder-only Markdown ingestion with registered extraction strategies and document-linked jobs |
| `app/services/tools/retriever_tool.py` | Enforce trusted organization scope and structured evidence output |
| `app/services/agent/exec.py` | Retain the agentic tool loop; add bounded execution, injected services and durable context |
| `app/services/agent/prompt.py` | Replace technical-documentation persona with organization-knowledge policy |
| `app/schemas/chat.py` | Add conversation/turn identity, structured sources and explicit outcomes |
| `app/api/v1/chat.py` | Add authorization, idempotency, safe errors and optional streaming |
| `app/core/config.py` | Separate secrets from versioned organization/model settings |
| `app/main.py` | Explicit lifecycle initialization, bounded CORS and readiness |
Remove indexing side effects from module imports. Re-embed the source documents into the new compatible index; do not copy incompatible existing vectors. Treat in-memory conversation state as temporary unless explicitly migrated. Add dependency manifests, migrations, operational packaging and meaningful tests before claiming a reproducible release.
## 18. Implementation Sequence
1. Confirm representative documents, question set, live provider capabilities and UI expectations.
2. Implement a small WebRTC spike demonstrating direct audio plus a trusted backend tool call.
3. Establish the modular backend, database migrations, identity boundary and provider interfaces.
4. Implement ingestion, document lifecycle, pgvector retrieval and the search tool contract.
5. Deliver the text agent with evidence, durable history and evaluation.
6. Connect the live controller to the same tool service; add interruption, sources and failure behavior.
7. Deliver organization administration, document selection and model configuration.
8. Validate isolation, performance, recovery and the actual presentation environment.
The text path provides an inspectable foundation while the early voice spike exposes provider/network risk. Final calendar dates depend on the confirmed meeting year, corpus and capacity; this document does not infer a deadline from an ambiguous date.
## 19. Open Decisions and Owners
| Decision | Suggested owner | Architectural impact |
| --- | --- | --- |
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
| Organization-wide versus per-assistant document selections | Product owner | Selection model and API scope |
| Live provider/model and supported trusted control features | AI/backend team | Adapter, WebRTC signaling and tool execution |
| Text and embedding model profiles | AI team | Quality, cost and vector dimensions |
| Local authentication or SSO | IT / backend | Login contract and identity integration |
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
| Concurrent sessions and latency targets | Product / IT | Capacity, scaling and quotas |
| Whether spoken answers require pre-release validation | Product / AI | Compatibility with direct live audio |
| Hosting, outbound connectivity and data transfer approval | IT / organization | Provider reachability and deployment |
| Backup policy and recovery objectives | IT | Operations and restoration testing |
| Final UI details | Product owner / Mr. Siavash | Frontend flow and review |
| Meeting year and IT handover date | Project manager | Delivery plan |
These items must be resolved by their owners rather than silently converted into product policy.
## 20. Reference Documentation
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
- **[R1]** [OpenAI — WebRTC](https://developers.openai.com/api/docs/guides/voice-webrtc): browser media connection and signaling patterns.
- **[R2]** [OpenAI — Server-side controls](https://developers.openai.com/api/docs/guides/voice-server-controls): trusted backend control connection and private tool execution.
- **[R3]** [OpenAI — Realtime with tools](https://developers.openai.com/api/docs/guides/realtime-mcp): function tool calls and correlated results.
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
## Appendix A. Presentation Diagrams
The following diagrams retain the previously agreed overview. Detailed security, lifecycle and failure requirements are defined in the main sections.
### A.1 Agentic AI and Dynamic Documents
```mermaid
flowchart TD
USER["User — Text or Live Voice"] --> AGENT["AI Agent"]
subgraph AI["Agentic Conversation"]
AGENT --> DECISION{"Need Document Knowledge?"}
DECISION -->|"Yes"| CALL["Call Search Tool with Search Query"]
DECISION -->|"Ready to Answer"| ANSWER["Generate Response with Sources"]
end
subgraph TOOL["Tool: search_documents"]
CALL --> SCOPE["Apply Organization and Selected Document Filters"]
SCOPE --> QUERY["Embed Search Query"]
QUERY --> SEARCH["Semantic Search"]
SEARCH --> SELECT["Select Relevant Chunks"]
SELECT --> RESULT["Return Content, Document IDs and Sources"]
end
RESULT -->|"Tool Result"| AGENT
ANSWER --> USER
subgraph DOCS["Dynamic Organization Documents"]
ADMIN["Organization Admin"] --> MANAGE["Upload, Update and Select Documents"]
MANAGE --> PROCESS["Extract, Chunk and Embed"]
PROCESS --> DB[("PostgreSQL + pgvector")]
MANAGE --> ACTIVE["Active Document Selection"]
end
ACTIVE --> SCOPE
SEARCH <-->|"Retrieve Matching Chunks"| DB
```
### A.2 Layered Backend Overview
```mermaid
flowchart TD
subgraph L1["1. Presentation"]
UI["Web Dashboard"]
end
subgraph L2["2. Backend API — FastAPI"]
CHAT["Text Chat"]
SESSION["Live Session"]
DOCS["Documents and Configuration"]
end
subgraph L3["3. Agentic AI"]
TEXT["Text AI Agent"]
LIVE["Live AI Model"]
TOOL["Search Documents Tool"]
TEXT <-->|"Tool Calls and Evidence"| TOOL
LIVE <-->|"Tool Calls and Evidence via Backend"| TOOL
end
subgraph L4["4. Knowledge Management"]
INGEST["Extract, Chunk and Embed"]
SEARCH["Search Organization-selected Documents"]
end
subgraph L5["5. Storage"]
FILES[("Document Files")]
DB[("PostgreSQL + pgvector — Documents and Chat History")]
end
UI --> CHAT
UI --> SESSION
UI --> DOCS
CHAT <--> TEXT
SESSION -->|"Initialize and Control"| LIVE
UI <-->|"Direct Live Audio — WebRTC"| LIVE
TOOL <--> SEARCH
SEARCH <--> DB
DOCS -->|"Upload and Update"| INGEST
DOCS -->|"Active Document Selection"| SEARCH
DOCS -->|"Store Original Files"| FILES
FILES --> INGEST
INGEST --> DB
```
@@ -0,0 +1,231 @@
# Organization Knowledge Assistant — Phase 1 Delivery Plan
| Field | Value |
| --- | --- |
| Version | 1.1 |
| Date | 2026-10-05 |
| Status | Proposed delivery baseline based on the agreed 7–10 day target |
| Parent document | RAG-AI-Architecture.md, architecture baseline v1.1 |
| Capacity assumption | One primary developer, reusing working code and a simple UI |
| Milestone | Demonstrable integrated release by Day 7; stabilization through Day 10 |
| Scope authority | This document defines Phase 1 delivery scope; the parent defines the longer-term architecture |
## 1. Release Objective
Deliver an authenticated organization knowledge assistant that supports text chat and live voice. The model decides when to call `search_documents`; the backend executes retrieval against ready, active documents and returns evidence. An administrator can change the knowledge available to the assistant without changing application code.
The delivery target is a working, deployed demonstration with real documents and real provider calls. It is not a claim of general production readiness, unrestricted file support or capacity certification.
The schedule uses numbered implementation days. The actual start date, working calendar and presentation date must be confirmed before converting these into calendar commitments. Days 8–10 are stabilization time, not spare capacity for additional features.
## 2. Delivery Assumptions and Day 1 Decisions
The estimate depends on access to provider credentials, a deployment environment, representative files, and time for both backend and frontend work. Existing repository components may be reused only after checking their current behavior; prior architecture mappings do not certify the present codebase.
| Decision or dependency | Required outcome by end of Day 1 |
| --- | --- |
| Document samples | A small approved corpus and 1–2 explicitly supported formats |
| Extraction | Verify that the sample text can be extracted; scans and complex tables are excluded unless already working |
| Text and embedding models | One configured profile for each, tested with Persian samples |
| Live provider | Real WebRTC audio plus a backend-executed tool call proven together |
| Deployment | Confirm HTTPS, microphone access and outbound provider connectivity in the intended environment |
| Evaluation questions | A small reference set covering supported, unsupported and follow-up questions |
| Identity | One organization and pre-created administrator/user accounts |
If native WebRTC plus trusted backend tool execution fails, resolve the provider choice on Day 1. Removing voice from the release or routing all audio through the backend is a scope decision requiring product agreement, not a silent implementation fallback.
## 3. Included and Deferred Scope
| Area | Phase 1 | Deferred |
| --- | --- | --- |
| Identity | Simple login, fixed organization, pre-created accounts, admin/user permissions | Registration, invitations, SSO, multi-organization administration |
| Documents | Upload, list, status, activate/deactivate and logical delete | Document versioning (not required); automatic replacement workflows |
| Formats | 1–2 formats validated against real samples | General-purpose ingestion, OCR and complex table support |
| Processing | Separate worker, durable jobs, extraction, chunking, embedding, bounded retry | Distributed worker fleet and separate message broker |
| Search | One `search_documents` tool with organization and active-document filtering | Read-document tools, web tools and advanced retrieval tuning |
| Text | Agent tool loop, grounded answers, sources, clarification and insufficient-information response | Autonomous actions and advanced agent workflows |
| Voice | Start/end WebRTC session, live speech response, same backend search tool, visible connection state | Seamless reconnect, session migration and cross-mode continuation |
| History | Durable text messages and citations; live session/tool diagnostics | Guaranteed full live transcript, raw audio recording and unified text/voice history |
| Settings | Assistant name and organization instruction | Model selector, voice catalogue, retrieval tuning and retention controls |
| Models | Fixed server-configured text, embedding and live profiles | Multiple selectable providers and automatic failover |
| Deployment | One environment, basic health checks, logs, migrations and durable volumes | High availability, autoscaling and formal load/SLA certification |
Active-document controls live on the Documents page to avoid duplicating the same setting across screens. Organization instructions may shape tone and domain behavior but cannot override authorization or search scope.
## 4. User Interface
| Screen | Required elements |
| --- | --- |
| Login | Credentials, login action, clear invalid-login feedback and logout |
| Conversation | Text input, messages, loading/error state, evidence sources, conversation list, new conversation, voice start/end and connection status |
| Documents — admin | Upload, filename, processing state, readable failure reason, active toggle, delete and retry for eligible failures |
| Settings — admin | Assistant name, organization instruction, save and discard changes |
Live captions are optional if provider support is immediately available; they are not a release dependency. Display retrieved sources for a voice turn without claiming that every retrieved source was necessarily spoken or cited by the model. Mark them as retrieved sources when exact answer attribution is unavailable.
## 5. Phase 1 Implementation Architecture
Use one FastAPI modular application, one ingestion worker from the same codebase, PostgreSQL with pgvector, and durable file storage. Keep conversation, document, knowledge and live-session responsibilities separate in code. Do not introduce a separate service per module.
```mermaid
flowchart TB
UI["Web Dashboard"]
API["FastAPI Application"]
TOOL["Shared Search Documents Tool"]
WORKER["Document Worker"]
DB[("PostgreSQL + pgvector")]
FILES[("Document Files")]
LIVE["External Live Model"]
UI <-->|"Authenticated APIs"| API
API <-->|"Text and Voice Tool Execution"| TOOL
TOOL <--> DB
API -->|"Jobs and History"| DB
API -->|"Uploads"| FILES
WORKER <-->|"Claim Jobs and Publish Chunks"| DB
FILES --> WORKER
UI <-->|"WebRTC Audio"| LIVE
API <-->|"Session Control and Tool Results"| LIVE
```
The diagram shows deployment responsibilities. Text inference and document/query embeddings use backend provider adapters and are omitted from the diagram for readability. The live model is an external service, not a process inside the backend.
### 5.1 Text and search
1. Authenticate the request and load the user's conversation history.
2. Give the model the current question, relevant history and the registered search tool.
3. For organization-document claims, require evidence before answering. Greetings and clarification can avoid search.
4. Validate tool arguments. Resolve organization and active-document scope in the backend, never from model authority.
5. Embed the query with the same compatible embedding profile as document chunks.
6. Return relevant text, document identity, chunk identity and available source location.
7. Generate the answer; record messages and citations. If evidence is insufficient, say so or ask a clarifying question.
Set a small configurable tool-call limit, request timeout and result-size limit. Exhaustion returns a clear failure or insufficient-information result instead of looping indefinitely. Do not fabricate page numbers when the extractor only provides section or chunk locations.
### 5.2 Voice
The backend authenticates and establishes the session using the selected provider's supported signaling/control mechanism. Browser audio uses WebRTC directly to the provider. Long-lived provider credentials remain on the server. The backend executes live tool calls against the same search service as text chat.
On connection loss, show a disconnected state and allow the user to start a new session. Automatic recovery of provider context is deferred. Test speaking interruption using the selected provider's supported behavior; custom interruption orchestration is outside the initial scope.
### 5.3 Worker reliability
Persist jobs before processing. A worker claims a job with a lease/token, records progress and publishes only while it owns the claim. Retry transient provider/network errors within configured limits. Reject unsupported or unreadable input visibly. Repeated execution must not duplicate published chunks.
Keep provider calls outside long database transactions. Index only after processing succeeds; a partial set of chunks is not searchable. A simple maintenance operation can reconcile abandoned uploads; a dedicated reconciliation service is deferred.
## 6. Document Lifecycle and Updates
Processing state is `queued → processing → ready` or `failed`. Selection is a separate active flag. A ready document can remain inactive. Deleted, inactive, failed and partially processed documents must not enter new retrieval.
Phase 1 replacement procedure:
1. Upload the replacement as a separate document, initially inactive.
2. Wait for successful processing and inspect its extracted/searchable content.
3. Deactivate the old document and activate the new document.
4. Start a new conversation to demonstrate the new knowledge.
During manual replacement, a brief interval with neither document active is acceptable and must produce an insufficient-information response. Do not describe this as atomic version replacement. Document versioning is not required by the current architecture; a future change would need an explicit product decision.
Each upload creates a new immutable document ID. Store chunks and jobs directly against that document ID, and citations against document/chunk IDs. Do not overwrite a ready document; retry only processes the same failed upload. Historical references retain their original document identity. No version table or version-number fields are required.
Selection changes take effect on new tool operations. Before delivering an in-flight tool result, recheck document eligibility. On deactivation or deletion, mark affected text context stale and require a new conversation; close affected live sessions, or conservatively close organization live sessions if precise tracking is not implemented. New sessions must not receive revoked evidence from old history. Historical messages may remain visible according to authorized history access, but must not be silently reused as current evidence.
Delete first removes retrieval eligibility. Physical cleanup of files/chunks follows an explicit configured policy; automatic retention management and a retention settings UI are deferred. This document does not invent a retention duration.
## 7. Minimum Persistent Data
Use migrations and retain extension points without building unused administration features.
| Record | Minimum responsibility |
| --- | --- |
| Organization and users | Fixed organization identity, account, role and secure credential handling |
| Documents | Organization, filename, storage key, checksum, processing state, active/deleted flags and processing profile |
| Chunks | Document identity, text, source location, embedding and order |
| Ingestion jobs | Stage, status, lease/token, attempt count, next retry and error |
| Conversations and messages | Owner, organization, ordered text turns, status and timestamps |
| Citations/tool results | Evidence identity linked to the relevant turn |
| Organization settings | Assistant name, instruction and configuration revision |
| Live session metadata | User, provider session mapping, state and diagnostic identifiers; no raw audio |
These are logical records, not a demand for one table per row. Align physical tables with the parent architecture and the current repository. No unsupported assumption is made that these migrations already exist.
## 8. Delivery Schedule and Checkpoints
| Day | Work | Required checkpoint |
| --- | --- | --- |
| 1 | Confirm files and questions; real WebRTC and backend tool spike; inspect reusable code | Audio and a trusted tool call work together; supported formats and provider chosen |
| 2 | Application/database setup, migration, login, upload and early deployment skeleton | Authenticated upload persists across restart |
| 3 | Worker, extraction, chunks, embeddings and job status | A real uploaded document reaches ready; unreadable input fails visibly |
| 4 | Scoped search tool and source payload | Relevant chunks returned; inactive documents excluded |
| 5 | Text agent, grounded responses and durable text history | Complete text scenario with citations and unsupported-question handling |
| 6 | Connect live session to real shared retrieval | Spoken document question produces an evidence-based spoken answer |
| 7 | Finish four screens, settings and deployed integration | End-to-end demonstration on the actual target environment; feature freeze |
| 8 | Evaluate reference questions and improve retrieval/prompting | Main content failures corrected; text and voice tested separately |
| 9 | Error handling, access, restart and deactivation tests | No known critical access, duplication or stale-evidence defects |
| 10 | Fix remaining blockers, seed demo data, document startup and rehearse | Tagged/reproducible release and successful demonstration rehearsal |
Day 7 is a constrained demo milestone, not permission to skip critical tests. If only seven days are available, perform essential acceptance checks continuously on Days 2–7 and disclose the narrower validation coverage. Move optional UI polish and captions out first. Do not cut authorization or falsely mark unfinished voice as delivered.
## 9. Acceptance Criteria
| ID | Test | Pass condition |
| --- | --- | --- |
| P1-01 | Login and admin access | Unauthenticated requests fail; normal users cannot change documents/settings |
| P1-02 | Upload and readiness | Supported document persists and becomes ready; failed extraction cannot be activated |
| P1-03 | Dynamic selection | Newly active content is searchable; inactive/deleted content is absent from new tool results |
| P1-04 | Agentic search | Document questions trigger a real tool call; greeting/clarification does not require artificial retrieval |
| P1-05 | Text grounding | Curated answerable questions have correct supported answers with resolvable sources |
| P1-06 | Missing knowledge | Curated unsupported questions do not receive invented organization facts |
| P1-07 | Voice | Real browser WebRTC session invokes backend search and returns a spoken answer; start/end work |
| P1-08 | Failure recovery | Voice disconnect is visible and a new session can start; provider failure produces understandable feedback |
| P1-09 | Persistence | Text history survives restart; interrupted ingestion recovers without duplicate published chunks |
| P1-10 | Revocation | Deactivation prevents reuse in new retrieval and invalidates affected ongoing context as defined in Section 6 |
| P1-11 | Secrets and scope | Server keys absent from browser payloads; caller/model cannot override authorized organization scope |
| P1-12 | Deployment | Demo works over HTTPS with microphone and provider connectivity in the intended environment |
Use a proposed reference set of 15–20 questions, covering direct facts, Persian paraphrases, follow-ups, missing information and deactivated documents. Record expected evidence and observed outcomes. Agree any quantitative quality target with the product owner; passing a small demo set is not a general accuracy guarantee.
Automate authorization, active-document filtering, job retry/publication and persistence checks where practical. Validate actual text and live provider integration with real calls; stub tests alone do not establish readiness.
## 10. Demonstration Script
1. Log in as administrator and upload a prepared organization document.
2. Show queued/processing/ready state, then activate it.
3. Ask a text question; show the answer and its source.
4. Ask a follow-up to demonstrate conversation context.
5. Ask an unsupported question; show explicit insufficient information.
6. Start voice, ask an equivalent document question and hear the answer.
7. Deactivate the document; show affected session/context reset.
8. Start a new conversation and verify that the document is no longer used.
9. Optionally demonstrate a prepared replacement using the manual procedure.
Prepare both already-processed sample data and an upload example. If an external provider is unavailable during the presentation, disclose it; recorded or cached output must not be represented as a live execution.
## 11. Risks and Scope Control
| Risk | Response |
| --- | --- |
| Voice integration fails late | Prove WebRTC plus backend tool execution on Day 1 |
| File complexity exceeds estimate | Limit formats using real samples; reject unsupported inputs clearly |
| Backend plus UI exceeds one developer's capacity | Reuse working components; use basic screens; remove optional polish before core scope |
| Retrieval produces weak evidence | Test a small corpus early; preserve headings/source locations; tune against the reference set |
| Demo network/provider differs from development | Deploy early and rehearse on the actual environment |
| New feature requests consume stabilization | Freeze features at Day 7; track additions in the next-phase backlog |
A change that removes text, dynamic document selection or live voice changes the release promise and must be recorded explicitly. Additional features require either removing equivalent scope or moving the deadline.
## 12. Expansion After Phase 1
1. **Lifecycle and reliability:** cleanup policy, stronger recovery, better extraction and larger evaluation sets.
2. **Voice and conversation continuity:** provider-supported transcript capture, reconnect, unified history and safe context restoration.
3. **Administration:** model/voice selection, richer roles, SSO and multi-organization operations with validated isolation.
4. **Retrieval and scale:** richer search based on measured failures, capacity testing, additional workers and a broker only when operational need justifies it.
Keep provider calls behind small adapters, reuse one search service, persist stable document/chunk references and use migrations from the beginning. These boundaries support expansion without implementing the full product before the first demonstration.
## 13. Release Handoff
Deliver the deployed application, repository release identifier, migration/startup instructions, environment-variable template without secrets, sample corpus and question set, acceptance results, known limitations, and next-phase backlog.
The parent architecture remains the target design. For Phase 1, this document deliberately narrows model configuration, live history and operational scope. Implementations must not claim those deferred capabilities merely because they appear in the parent document.
@@ -0,0 +1,266 @@
# RAG Assistant — Phase 1 API Catalog
Version 1.1 · 2026-10-05 · Proposed application contract; no running endpoints are claimed.
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-Scenario-Report-FA.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
## 1. Transport and common conventions
Base path `/api/v1`; UTF-8 JSON except multipart upload; same-origin HTTPS. UUIDs identify application records. Timestamps are UTC RFC3339. `null` means unavailable, not an invented source location. Unexpected request fields return 422. Example UUIDs are illustrative.
Secure HttpOnly `rag_session` cookie authenticates requests. Login and all mutations enforce trusted Origin; authenticated mutations also require `X-CSRF-Token`. `/me` returns a CSRF token for refresh. No frontend persistent provider key, organization ID override or model override is accepted.
Roles: `admin` and `user`. Both can chat and read their own history/live state. Only admin manages documents, selection and settings. Hidden resource access returns 404. Admin does not implicitly own all conversations.
Lists use `limit` (default 20, maximum 100) and opaque `cursor`. Stable ordering is `(created_at DESC,id DESC)` except messages, ordered by ascending `sequence_no`. Responses use `{items:[],next_cursor:null}`. Unknown/invalid cursor returns 422. No total count is promised.
`X-Request-ID` response header and `error.request_id` correlate logs. Servers generate one if none is valid. `Idempotency-Key` is required on upload, manual ingestion retry and delete; UUID `client_request_id` is required in create-conversation, chat and create-live bodies. Keys are scoped to actor/organization and operation as specified below. Reuse with different normalized input returns 409.
Proposed field limits: text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200. File limits/formats and SDP byte cap come from deployment configuration and are exposed as capabilities where useful. These are implementation defaults to confirm, not provider guarantees.
## 2. Endpoint inventory
| ID | Method and path | Access | Success |
| --- | --- | --- | --- |
| A01 | POST `/auth/login` | Public, trusted Origin | 200 + cookie |
| A02 | POST `/auth/logout` | Authenticated; expired/missing session accepted | 204 |
| A03 | GET `/me` | Authenticated | 200 |
| D01 | POST `/documents` | Admin | 202 |
| D02 | GET `/documents` | Admin | 200 |
| D03 | GET `/documents/{document_id}` | Admin | 200 |
| D04 | POST `/documents/{document_id}/retry` | Admin | 202 |
| D05 | DELETE `/documents/{document_id}?expected_revision=N` | Admin | 202 |
| K01 | GET `/knowledge-selection` | Admin | 200 |
| K02 | PATCH `/knowledge-selection` | Admin | 200 |
| F01 | GET `/configuration` | Authenticated | 200 |
| F02 | PATCH `/configuration` | Admin | 200 |
| C01 | POST `/conversations` | Authenticated | 201 |
| C02 | GET `/conversations` | Owner | 200 |
| C03 | GET `/conversations/{conversation_id}/messages` | Owner | 200 |
| T01 | POST `/chat` | Owner of text conversation | 200 or 202 |
| T02 | GET `/conversations/{conversation_id}/turns/{client_request_id}` | Owner | 200 |
| V01 | POST `/voice/sessions` | Owner of voice conversation | 201 or 202 |
| V02 | GET `/voice/sessions/{session_id}` | Owner | 200 |
| V03 | GET `/voice/sessions/by-request/{client_request_id}` | Owner | 200 |
| V04 | POST `/voice/sessions/{session_id}/close` | Owner | 200 |
| H01 | GET `/health/live` | Deployment health access | 200 |
| H02 | GET `/health/ready` | Deployment health access | 200 or 503 |
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_documents` is internal and has no public HTTP route.
## 3. Authentication
### A01 — Login
```json
{"username":"demo.admin","password":"<password>"}
```
```json
{"user":{"id":"01000000-0000-4000-8000-000000000001","username":"demo.admin","role":"admin","organization_id":"02000000-0000-4000-8000-000000000001"},"csrf_token":"<session-csrf-token>","expires_at":"2026-10-05T18:00:00Z"}
```
Credentials invalid: 401 `INVALID_CREDENTIALS`; throttled: 429. Do not distinguish missing username from wrong password. Expiry above is illustrative. Set Secure/HttpOnly/SameSite=Lax cookie; rotate tokens after successful login.
### A02 — Logout
No body. Revoke current session, clear cookie and close owned live sessions linked to it. Repeated logout returns 204. For a valid session require CSRF; missing/expired session may simply clear cookie after Origin validation.
### A03 — Current identity
No body. Same identity/CSRF/expiry shape as login. Missing/expired session returns 401 `AUTH_REQUIRED`.
## 4. Documents and selected knowledge
### D01 — Upload
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
```json
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}
```
202 acknowledges durable metadata/job creation, not completed processing. Replay same upload returns these stable identities with current processing state and header `Idempotency-Replayed: true`. Scope key to organization; hash bytes and normalized title. 413 `FILE_TOO_LARGE`, 415 `UNSUPPORTED_FILE_TYPE`, 422 `INVALID_FILE`, 409 `IDEMPOTENCY_CONFLICT`. A parser failure after acceptance is represented by document status, not a later HTTP response to upload.
### D02 — List
Query: common pagination; optional `status=queued|processing|ready|failed`, `is_active=true|false`. Exclude deleted documents. Items use the D03 shape, except potentially omit verbose error detail. Return current `knowledge_revision` alongside the list.
### D03 — Detail / processing polling
```json
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
```
`searchable = ready AND active AND not deleted`. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
### D04 — Retry failed processing
No body; required `Idempotency-Key`. Eligible only for failed undeleted document and retained original. Requeue same job, reset attempt count, increment retry generation and audit. Same key replays without incrementing twice.
```json
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","retry_generation":1}
```
409 `DOCUMENT_NOT_RETRYABLE` for running/ready/permanent failure; 404 hidden/deleted. The retry-key record is retained in audit metadata with a database uniqueness constraint.
### D05 — Delete
Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.
```json
{"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"}
```
202; 409 `REVISION_CONFLICT` on stale initial request. Replay same delete/key returns recorded result before revision validation. A new delete request for an already-deleted owned document can return its tombstone result without changing revisions. No read or search route restores eligibility.
### K01 — Get selection
```json
{"revision":1,"access_epoch":1,"document_ids":[]}
```
### K02 — Replace selected set
This replaces the entire set, not a delta. UI reads current selection before toggling a document.
```json
{"expected_revision":1,"document_ids":["10000000-0000-4000-8000-000000000001"]}
```
```json
{"revision":2,"access_epoch":1,"document_ids":["10000000-0000-4000-8000-000000000001"],"conversations_invalidated":false}
```
Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected IDs in details; no partial update. Hidden ID: 404. Stale revision: 409 `REVISION_CONFLICT`. No-op preserves revision. Removing an active ID increments epoch and sets `conversations_invalidated=true`; all older organization conversations become unusable for new turns. After a timeout GET current state instead of blindly repeating with an old revision.
## 5. Configuration
### F01 — Read
```json
{"revision":1,"assistant_name":"Organization Assistant","instruction":"پاسخ‌ها کوتاه و بر اساس اسناد سازمان باشند.","capabilities":{"text":true,"voice":true,"captions":false,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}}
```
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
### F02 — Update
```json
{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"فارسی و رسمی پاسخ بده؛ نبود اطلاعات را اعلام کن."}
```
200 returns F01 with incremented revision. Both fields are required; no-op preserves revision. Stale value: 409 `REVISION_CONFLICT`. Text applies on subsequent turns; existing live session keeps its snapshot until restarted. Settings cannot relax system authorization or grounding rules.
## 6. Conversations and text
### C01 — Create
```json
{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours"}
```
```json
{"id":"60000000-0000-4000-8000-000000000001","mode":"text","title":"Working hours","status":"active","access_epoch":1,"created_at":"2026-10-05T09:05:00Z"}
```
`mode` is text or voice, never mixed. Title optional. Idempotency scope `(owner,client_request_id)`; same payload replays original 201. Different payload 409. New conversation snapshots current epoch. Voice history cannot be continued as text in Phase 1.
### C02 — List own conversations
Common pagination, optional `mode`. Items use C01 response plus `updated_at`; derive `status=stale` when epoch differs. Status values: active, stale, closed. List excludes other users regardless of role.
### C03 — Read messages
Common pagination, ascending sequence. Voice can return no messages because transcripts are not guaranteed. Old text history remains viewable even when stale.
```json
{"conversation_id":"60000000-0000-4000-8000-000000000001","conversation_status":"active","items":[{"id":"70000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","sequence_no":1,"role":"user","content":"پنجشنبه تا چه ساعتی باز هستید؟","created_at":"2026-10-05T09:06:00Z","sources":[]}],"next_cursor":null}
```
Assistant items also expose `turn_status` and source objects. Failed turns remain visible as state, not fabricated assistant answers. A user message may exist without an assistant reply; UI follows turn status.
### T01 — Submit text turn
```json
{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"پنجشنبه تا چه ساعتی باز هستید؟"}
```
```json
{"conversation_id":"60000000-0000-4000-8000-000000000001","turn_id":"80000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","status":"answered","message_id":"70000000-0000-4000-8000-000000000002","answer":"طبق سند ساعات کاری، پنجشنبه‌ها تا ساعت ۱۲ باز هستیم.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"پنجشنبه‌ها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null},"available":true}],"error":null}
```
200 returns terminal execution: answered, needs_clarification, insufficient_information or failed. `answer`/`message_id` are null on failed, with normalized error. A successfully processed unsupported question uses insufficient_information, human-readable answer and usually empty sources. Failed generation is not reported as a successful answer.
202 returns a running turn shape with `answer:null`, `message_id:null`, empty sources, `error:null` and `Location` pointing to T02. This occurs on duplicate running request or when the initial response deadline expires while the owned task is still running. Do not start a second task. Client disconnection must not silently create duplicate execution.
Scope key `(conversation_id,client_request_id)`. Changed message under same key: 409. Another different request while one runs: 409 `CONVERSATION_BUSY`. Wrong mode: 409 `MODE_MISMATCH`. Stale epoch: 409 `CONVERSATION_STALE`. Admission failures use the common HTTP error envelope; failures after a turn is persisted use its failed terminal result. Retry completed failures only with a new request ID.
### T02 — Recover/poll turn
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — provisional signaling, fixed ownership rules
The SDP variant below is the target application contract, conditional on Day 1 provider proof. It is not a claim that every Live provider supports it. Freeze a compatible variant before frontend implementation.
### V01 — Create session
```json
{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001","sdp_offer":"<browser-generated SDP>"}
```
```json
{"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","sdp_answer":"<provider-generated SDP>","expires_at":"2026-10-05T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"}
```
Conversation must be voice, current epoch and owned by caller. Scope key `(owner,client_request_id)`; hash conversation and SDP. Changed offer under same key is 409. One nonterminal session per conversation. A duplicate during creation returns 202 with session ID/state and null SDP answer, never another provider session. Completed replay returns 201 and the same short-lived answer while still valid. Closed/failed/expired reservations return 409 `LIVE_SESSION_UNUSABLE`; start a fresh request after resolving the old one.
Persist only encrypted short-lived SDP answer for replay, purge at close/expiry; do not store raw offer or log SDP. Provider creation timeout marks failed/uncertain, never blind automatic recreation. Validate trusted tool-control availability before returning usable signaling. 503 may be used for pre-reservation provider capability failure; a persisted reservation can be inspected with V03.
### V02 — Poll state and recent retrieved sources
```json
{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-05T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-05T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"پنجشنبه‌ها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null},"available":true}]}]}
```
Return at most 20 recent tool results in chronological order; clients deduplicate by tool_call_id. This is a bounded status snapshot, not a durable full event stream. Sources are retrieved evidence, not guaranteed spoken citations. Redact excerpts of revoked sources and mark unavailable. State is creating, connecting, connected, closed or failed. UI polling suggested every 2 seconds; terminal state stops polling. No client route can claim a session connected or inject a trusted tool result.
### V03 — Recover creation by request ID
200 returns V01 signaling shape while creating/connecting and still eligible; connected/terminal returns state with null SDP answer if replay is no longer useful. Owner-only; 404 if no reservation. This lookup does not create sessions. A client that has lost its peer connection must close/reconcile the old session before starting another, not apply an old SDP answer to a new offer.
### V04 — Close
No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Idempotent: already closed/failed returns its existing terminal state. Mark locally closed and attempt provider cleanup; unresolved cleanup is logged and bounded by provider expiry. Revocation/auth expiry/control loss can also terminate sessions; UI displays returned reason.
## 8. Health
H01: 200 `{"status":"ok"}` when the process is alive. H02: 200 `{"status":"ready","ingestion":"available"}` or degraded ingestion marker if worker heartbeat is stale; 503 `{"status":"not_ready"}` for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness.
## 9. Error envelope and mapping
```json
{"error":{"code":"REVISION_CONFLICT","message":"Selection changed; reload and try again.","request_id":"req-example","retryable":false,"details":{"current_revision":3}}}
```
| HTTP | Codes / use | Client action |
| --- | --- | --- |
| 401 | AUTH_REQUIRED, INVALID_CREDENTIALS | Login; do not retry provider work |
| 403 | FORBIDDEN, CSRF_INVALID | Show denial or refresh session token |
| 404 | NOT_FOUND | Stop; do not expose ownership details |
| 409 | REVISION_CONFLICT | Read latest selection/configuration |
| 409 | IDEMPOTENCY_CONFLICT | Correct client request/key handling |
| 409 | CONVERSATION_BUSY, CONVERSATION_STALE, MODE_MISMATCH | Poll current turn, start fresh conversation, or correct mode |
| 409 | DOCUMENT_NOT_READY, DOCUMENT_NOT_RETRYABLE, LIVE_SESSION_UNUSABLE | Follow returned state |
| 413/415/422 | FILE_TOO_LARGE, UNSUPPORTED_FILE_TYPE, VALIDATION_ERROR | Correct input |
| 429 | RATE_LIMITED | Honor Retry-After; reuse key when retrying same operation |
| 503 | DEPENDENCY_UNAVAILABLE | Show service failure; reconcile state before retry |
Inside persisted failed turns/jobs, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, INVALID_CITATION, PROCESS_INTERRUPTED and CONVERSATION_STALE. An HTTP 200 failed-turn result still represents application failure. Technical retryability does not authorize automatic regeneration under a new key.
## 10. Frontend implementation order and exclusions
Build A01/A03 and upload polling first, selection next, then C01/T01/T02/messages, then voice and settings. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.
Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.
@@ -0,0 +1,327 @@
# RAG Assistant — Phase 1 Database Design
Version 1.1 · 2026-10-05 · Proposed physical schema and migration specification; not executed migration SQL.
Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization at launch, durable text history and ingestion jobs, live metadata. No existing database was inspected; compare this proposal with actual migrations before applying it.
Schema revision 1.1 removes document versioning. The schema now contains 14 tables. Original-file and processing fields are merged into documents; chunks, jobs and citations reference documents directly. Configuration revisions and processing-profile identifiers remain unrelated technical metadata.
## 1. Conventions
All IDs are application-generated UUIDs. `uuid PK` means primary key. Timestamps are `timestamptz` in UTC; `created_at` defaults to database now. Unless marked nullable, fields are NOT NULL. JSON defaults are `{}` or `[]` as appropriate. Status fields use text plus CHECK constraints for simple evolution. Hashes use lowercase SHA-256 hex (`char(64)`), except password hashes which use the selected password library's encoded format. Counters use integer/bigint and CHECK >= 0; revisions/sequence numbers start at 1.
Tables other than settings have a UUID `id` PK. Settings uses `organization_id` as PK. Every organization-owned table has `organization_id uuid` referencing organizations, even where derivable. For all referenced scoped entities add `UNIQUE(organization_id,id)` and use composite scoped foreign keys. This prevents a valid UUID from another organization being attached accidentally. Do not treat UUID unpredictability as access control.
Use RESTRICT/NO ACTION for normal deletion; no broad CASCADE from users/documents into historical chats. Soft deletion and explicit cleanup control lifecycle. Owners/roles are checked by application queries. Single-organization deployment does not justify dropping organization filtering. Row-level security is deferred, not claimed to be enabled.
## 2. Relationship overview
```mermaid
erDiagram
documents ||--o{ document_chunks : contains
documents ||--|| ingestion_jobs : processes
conversations ||--o{ turns : contains
turns ||--o{ messages : records
turns ||--o{ citations : supports
conversations ||--o{ live_sessions : hosts
turns |o--o{ tool_calls : text_calls
live_sessions |o--o{ tool_calls : voice_calls
```
The diagram omits identity/configuration/audit for readability. Each tool call belongs to exactly one text turn OR one live session. A citation also references the exact tool call/evidence that produced its chunk. These relationships are defined below.
## 3. Identity and organization tables
### 3.1 organizations
| Column | Type/default | Meaning |
| --- | --- | --- |
| id | uuid PK | Fixed seeded organization |
| name | varchar(200) | Display name |
| created_at | timestamptz now | Creation |
### 3.2 users
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id | uuid | Identity and organization |
| username | varchar(120) | Canonical lowercase login name |
| password_hash | text | Salted adaptive password hash; never plaintext |
| role | text | admin or user |
| is_enabled | boolean true | Account authorization |
| created_at, updated_at | timestamptz | Audit timestamps |
Unique username globally for simple login without organization selector. CHECK role. Add UNIQUE(organization_id,id). Disabling a user revokes sessions and closes live sessions; account-management UI is deferred (maintenance command only).
### 3.3 auth_sessions
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, user_id | uuid | Session owner |
| token_hash | char(64) UNIQUE | Hash of opaque cookie token |
| created_at, expires_at, last_seen_at | timestamptz | Lifetime |
| revoked_at | timestamptz nullable | Explicit revocation |
Composite FK to users. CHECK expires_at > created_at. Index expires_at for cleanup. Never store raw cookie. Derive CSRF token from raw session cookie using a separate server-side HMAC secret (or an equivalent reviewed synchronizer mechanism); compare in constant time. `/me` can reproduce it without persisting a raw CSRF token.
### 3.4 organization_settings
| Column | Type/default | Meaning |
| --- | --- | --- |
| organization_id | uuid PK/FK | One row per organization |
| assistant_name | varchar(120) | UI/model name |
| instruction | text | Organization instruction, API length limit |
| revision | bigint 1 | Settings optimistic revision |
| knowledge_revision | bigint 1 | Selected-set revision |
| access_epoch | bigint 1 | Invalidation counter for removals |
| updated_by | uuid nullable | Actor; scoped FK to users |
| updated_at | timestamptz | Last configuration/selection mutation |
CHECK all counters >= 1. Selection uses documents.is_active; no assignment table in Phase 1. Lock this row first for selection, context creation and finalization to impose a consistent order.
## 4. Knowledge tables
### 4.1 documents
Each upload is one independent immutable document. This table owns file metadata and processing state directly. There is no document-version table or version-number field. Replacement means a new upload/document ID, followed by active-selection change after readiness. The same idempotent upload replay returns the original ID.
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, uploaded_by | uuid | Identity and admin actor |
| title | varchar(200) | Display title |
| original_filename | text | Display only, never trusted path |
| upload_request_id | uuid | Upload Idempotency-Key |
| upload_payload_hash | char(64) | File bytes + normalized metadata digest |
| storage_key | text UNIQUE | Generated original-file reference |
| file_sha256 | char(64) | Original bytes hash |
| mime_type | text | Validated MIME |
| size_bytes | bigint | Original size > 0 |
| status | text queued | queued, processing, ready, failed |
| processing_profile | jsonb | Extractor/chunk/embedding settings |
| chunk_count | integer 0 | Published chunk count |
| ready_at | timestamptz nullable | Successful publication |
| is_active | boolean false | Organization selection |
| deleted_at | timestamptz nullable | Soft deletion |
| content_purged_at | timestamptz nullable | Explicit future cleanup marker |
| created_at, updated_at | timestamptz | Timestamps |
UNIQUE(organization_id,upload_request_id). Scoped FK uploaded_by→users. CHECK size_bytes > 0, chunk_count >= 0. CHECK ready implies ready_at IS NOT NULL and chunk_count > 0. CHECK is_active implies status='ready', deleted_at IS NULL and content_purged_at IS NULL. Storage keys are generated and unique; no automatic same-hash deduplication between documents.
Do not overwrite the original bytes or republish a ready document. Manual retry accepts only eligible failed documents; first successful publication fixes the source/chunk identities. If content changes, upload a new independent document. Physical purging must first deactivate the document; retained metadata is a tombstone, never eligible search content.
Profile example (illustrative values, confirm Day 1):
```json
{"extractor":"approved-parser-v1","chunker":"paragraph-v1","chunk_size":800,"overlap":100,"size_unit":"tokens","embedding":{"provider":"openai","model":"<selected-model>","dimensions":1536,"preprocessing_version":"v1"}}
```
1536 is an example, not a model selection. Deployment must freeze actual dimension D and compatible profile before creating `vector(D)` and indexing. Do not mix equal-length vectors from different models.
### 4.2 document_chunks
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, document_id | uuid | Source identity |
| ordinal | integer | 0-based order |
| text | text | Extracted evidence |
| location | jsonb | `{page: integer-or-null, section: string-or-null}` |
| token_count | integer nullable | Actual tokenizer count if available |
| embedding | vector(D) | Model-compatible vector |
| created_at | timestamptz | Publication |
UNIQUE(document_id,ordinal); CHECK ordinal >= 0 and length(text)>0; token_count >= 0 when set. FK document scoped. Page is positive when present. Do not invent a page index for a format without pages.
Index document_id; initial small-corpus search uses exact cosine distance after eligibility joins. Defer ANN/HNSW until measured latency requires it. If later added, validate filtered-search recall. Example query is parameterized and conceptual (D is a migration parameter):
```sql
SELECT c.id, c.text, c.location, d.id AS document_id,
c.embedding <=> CAST(:query_vector AS vector) AS distance
FROM document_chunks c
JOIN documents d ON d.id = c.document_id AND d.organization_id = c.organization_id
WHERE d.organization_id = :organization_id
AND d.is_active = true AND d.deleted_at IS NULL
AND d.status = 'ready' AND d.content_purged_at IS NULL
ORDER BY c.embedding <=> CAST(:query_vector AS vector), c.id
LIMIT :top_k;
```
Server validates profile, dimension and bounded top_k before query. A nearest neighbor is not automatically sufficient evidence; no universal distance threshold is assumed.
### 4.3 ingestion_jobs
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, document_id | uuid | One job per document |
| status | text queued | queued, processing, succeeded, failed |
| stage | text extract | extract, chunk, embed, publish |
| attempt_count | integer 0 | Claims within current retry generation |
| retry_generation | integer 0 | Manual retries |
| next_attempt_at | timestamptz now | Backoff scheduling |
| claim_token | uuid nullable | Fencing token |
| lease_expires_at | timestamptz nullable | Worker lease |
| claimed_by | text nullable | Worker process identifier |
| error_code, error_message | text nullable | Redacted failure |
| error_retryable | boolean false | Eligibility hint |
| created_at, updated_at | timestamptz | Timestamps |
UNIQUE(document_id). CHECK processing requires claim_token and lease_expires_at; non-processing clears them. Index `(status,next_attempt_at)` and partial lease expiry for processing. Claim eligible rows with row lock/SKIP LOCKED, regenerate token and increment attempt count. Recovery excludes deleted documents and reclaims expired jobs within retry budget. Final publication locks job and checks token plus lease; an expired worker cannot publish even if its provider call completed. Manual retry uses audit idempotency record and updates this same job atomically.
## 5. Conversation and evidence tables
### 5.1 conversations
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, owner_user_id | uuid | Ownership |
| client_request_id | uuid | Create idempotency key |
| request_hash | char(64) | Normalized create payload |
| mode | text | text or voice |
| title | varchar(120) nullable | Optional display label |
| status | text active | active, stale, closed |
| access_epoch | bigint | Knowledge-removal snapshot |
| created_at, updated_at | timestamptz | Ordering |
UNIQUE(owner_user_id,client_request_id). Scoped FK owner. Index owner/created_at/id. Effective status is stale if epoch differs even before explicit row updates; this closes races in invalidation maintenance. Stale/closed history remains read-only.
### 5.2 turns
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, conversation_id | uuid | Text turn identity |
| client_request_id | uuid | Chat retry correlation |
| request_hash | char(64) | Conversation/message digest |
| status | text running | running, answered, needs_clarification, insufficient_information, failed |
| settings_revision, knowledge_revision, access_epoch | bigint | Actual snapshots |
| execution_profile | jsonb | Model, actual organization instruction, prompt version, tool schema version and limits |
| started_at, deadline_at | timestamptz | Execution timeout |
| finished_at | timestamptz nullable | Terminal completion |
| error_code, error_message | text nullable | Normalized failure |
| error_retryable | boolean false | Technical retry hint |
| created_at | timestamptz | Creation |
UNIQUE(conversation_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status='running'. CHECK terminal iff finished_at is not null; deadline_at > started_at. Scoped FK conversation. Mode=text is an application invariant checked while locking conversation. Message text resides in messages, not duplicated here. Reconstruct API response from messages/citations; replay does not call provider again. Startup/deadline cleanup marks interrupted turns failed.
### 5.3 messages
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, conversation_id, turn_id | uuid | Ownership and text turn |
| sequence_no | bigint | Stable conversation order, >=1 |
| role | text | user or assistant |
| content | text | Message body |
| created_at | timestamptz | Creation |
UNIQUE(conversation_id,sequence_no), UNIQUE(turn_id,role). Both roles may exist for completed turn; failed turn can have user only. Add UNIQUE(organization_id,conversation_id,id) as needed for matching references. Enforce `(organization_id,conversation_id,turn_id)` FK to a corresponding unique key on turns, not independent FKs that could attach a message to the wrong conversation. Allocate sequence while holding conversation row lock; no model tool/system messages in this table.
### 5.4 tool_calls
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id | uuid | Identity |
| turn_id | uuid nullable | Text parent |
| live_session_id | uuid nullable | Voice parent |
| external_call_id | text | Provider/orchestrator correlation |
| tool_name | text | search_documents only |
| arguments | jsonb | Validated query, no trusted scope from model |
| request_hash | char(64) | Canonical arguments digest |
| status | text running | running, succeeded, failed |
| knowledge_revision, access_epoch | bigint | Retrieval snapshots |
| result_json | jsonb nullable | Evidence IDs, text, locations or normalized tool error |
| error_code | text nullable | Failure |
| created_at | timestamptz | Creation |
| completed_at | timestamptz nullable | Completion |
CHECK exactly one parent is non-null. Separate partial unique indexes `(turn_id,external_call_id)` WHERE turn_id IS NOT NULL and `(live_session_id,external_call_id)` WHERE live_session_id IS NOT NULL. Scoped FKs to both parent types. CHECK terminal iff completed_at not null. Duplicate event with same hash reuses result; a different hash is conflict. Duplicate running event waits/polls, never executes twice. Failure/no_evidence distinction is retained in result_json. Evidence payload is sensitive retained content and must be covered by purge policy.
### 5.5 citations
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, turn_id, tool_call_id | uuid | Answer/evidence correlation |
| source_ref | text | S1, S2... unique across all searches within this turn |
| document_id, chunk_id | uuid | Stable actual source IDs |
| title_snapshot | text | Title at answer time |
| location_snapshot | jsonb | Actual source locator |
| excerpt | text nullable | Display evidence; cleared if policy requires purge |
| created_at | timestamptz | Answer commit |
UNIQUE(turn_id,source_ref). Scoped FKs for sources plus chain-consistent composite FKs: chunk belongs to the cited document, tool call belongs to the same turn. Add referenced unique keys on these chains. Application verifies source_ref belongs to tool result, not arbitrary model output. No assistant_message_id needed: UNIQUE(turn_id,role) resolves the assistant. Only terminal non-failed answers can have final citations (transaction invariant).
Keep source identity rows as tombstones if allowed. `available` in API is computed from current access and retention state; revoked source excerpts are not emitted by source endpoints. Old answer prose cannot be retroactively withdrawn and remains owner-visible under history policy. Do not hard-delete referenced chunks through ordinary application DELETE.
## 6. Live and audit tables
### 6.1 live_sessions
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, conversation_id, owner_user_id, auth_session_id | uuid | Session ownership and logout correlation |
| client_request_id | uuid | Creation correlation |
| request_hash | char(64) | Conversation + SDP-offer digest |
| provider, model | text | Chosen live profile |
| provider_session_id | text nullable | External reference |
| status | text creating | creating, connecting, connected, closed, failed |
| settings_revision, knowledge_revision, access_epoch | bigint | Creation snapshots |
| execution_profile | jsonb | Instruction/prompt profile snapshot |
| sdp_answer_ciphertext | bytea nullable | Short-lived encrypted replay material |
| expires_at, created_at, updated_at | timestamptz | TTL/lifecycle |
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
| close_reason, error_code | text nullable | Normalized reason |
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set and sdp_answer_ciphertext cleared. Store no raw SDP offer or audio. Provider credentials are server configuration, never database plaintext. Encryption key is outside database.
API instance owns live control in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript.
### 6.2 audit_events
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, actor_user_id | uuid (actor nullable) | Administrator/system action |
| action | text | upload, selection_changed, document_deleted, ingestion_retry, configuration_changed, session_revoked |
| target_id | uuid nullable | Referenced object; polymorphic diagnostic field |
| request_id | text nullable | HTTP tracing |
| idempotency_key | uuid nullable | Delete/retry idempotency |
| request_hash | char(64) nullable | Mutation payload hash |
| response_json | jsonb nullable | Replay of delete/retry outcome |
| metadata | jsonb | Changed IDs/revisions, redacted reason |
| created_at | timestamptz | Event time |
Partial UNIQUE(organization_id,actor_user_id,action,target_id,idempotency_key) WHERE idempotency_key IS NOT NULL. Delete/retry APIs require non-null actor and target. Insert audit replay record in SAME transaction as the mutation. Concurrent unique conflict reloads committed response. Preserve these records for the supported retry window; no cleanup duration is assumed. Avoid document text/secrets in audit metadata.
## 7. Transaction boundaries and invariant enforcement
| Operation | One database transaction | Outside transaction |
| --- | --- | --- |
| Upload | Document + job + audit | File staging/write; reconcile orphans |
| Claim | Row lock, new token/lease, attempt increment | Extraction and provider calls |
| Publish | Lock document/job; verify token/lease; replace chunks; ready/succeeded | Already prepared embeddings |
| Selection | Settings lock, expected revision, active flags, revision/epoch, stale conversations, audit | Best-effort closing provider sessions after logical invalidation |
| Chat admission | Settings/conversation locks, request lookup, turn + user message | Provider inference/tool loop |
| Chat completion | Settings/conversation locks, epoch validation, assistant + citations + terminal status | Browser delivery after commit |
| Live create | Reservation/idempotency/ownership first; state update after provider | Provider creation and trusted control |
| Delete/retry | State change + unique audit replay result | Physical cleanup or future worker execution |
Use consistent lock order where resources overlap: organization settings → conversation or document → job or turn/session. Do not hold settings lock during remote calls. Publication does not acquire settings after a document lock; it leaves selection unchanged. Retry/publish paths lock document then job to avoid inversion. Claims lock only jobs and commit quickly.
On active-document removal: database epoch invalidation is authoritative immediately for new operations. After transaction, notify/close provider sessions and discard stale pending evidence. Cannot recall previously delivered live audio. Session close failure remains observable and bounded by TTL; it is not represented as guaranteed erasure at the provider.
## 8. Migration plan
| Migration | Content | Gate |
| --- | --- | --- |
| 001_identity | organizations, users, auth_sessions, settings | Seed one org and admin/user securely |
| 002_knowledge | documents, jobs; enable vector extension; chunks with confirmed D | Real embedding profile dimension fixed |
| 003_conversations | conversations, turns, messages, live_sessions, tool_calls, citations | Ownership/chain constraints and partial unique indexes checked |
| 004_audit_indexes | audit_events and remaining query indexes | Upload/delete/retry transaction tests |
For a database already created from revision 1.0: first verify that each document has exactly one content row, copy its file/status/profile fields to documents, backfill direct document references for chunks/jobs/citations, validate counts and constraints, and only then remove the legacy content-version table/columns. Preserve document and chunk IDs. If more than one content row exists per document, stop and design an explicit data migration; do not silently discard rows. No migration has been run as part of this documentation edit.
These can be combined while no deployment exists; once applied, use new migrations rather than editing history. Create tables in FK dependency order (live_sessions before tool_calls; tool_calls before citations). Migration rollback that drops content is destructive; prefer forward fixes after data exists. Confirm extension privileges and back up before real deployment changes.
## 9. Essential database validation
Test: cross-org FK rejection; one running turn/session under concurrency; duplicate request hash conflict; same upload replay; stale worker publication; manual retry once per key; ready/active filtering; epoch race during answer finalization; deletion tombstone with old citation; matching document/chunk source chain; restart interruption states. The schema above is a reviewable design, not evidence that these tests have passed.
## 10. Deliberately absent from Phase 1
No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements.
@@ -0,0 +1,152 @@
# RAG Assistant — Phase 1 Implementation Guide
Version 1.1 · 2026-10-05 · Proposed implementation contract, not an implementation-completion report.
## 1. Purpose and authority
Implement the 7–10 day release described in `RAG-AI-Phase1-Delivery-Plan.md`. Use `RAG-Phase1-API-Catalog.md` for HTTP contracts and `RAG-Phase1-Database-Design.md` for persistence. `RAG-Phase1-Scenario-Report-FA.md` explains the same design through scenarios. These companion documents refine the delivery plan; they do not expand the release to the full parent architecture.
Assumptions: one primary developer, one organization, pre-created admin/user accounts, one backend instance, one ingestion worker, one PostgreSQL database with pgvector and persistent file storage. Reuse working application/UI components after inspection. No source repository was inspected in preparing this package, and no application or migration was executed.
## 2. Decisions for this implementation
| Topic | Phase 1 decision |
| --- | --- |
| Backend | FastAPI modular monolith; worker entry point in the same codebase |
| UI delivery | Same-origin HTTPS UI and API; four screens from the phase plan |
| Identity | Opaque server-side cookie sessions; admin/user roles; no signup |
| Jobs | PostgreSQL polling, lease and fenced publication; no Redis/broker |
| Text | Non-streaming JSON answer; durable turn status for timeout recovery |
| Agent | Retain existing orchestration if usable; do not add a framework only for this release |
| Voice | Browser/provider WebRTC; trusted server-side control and shared search; validate provider compatibility on Day 1 |
| Live UI updates | Poll application session state and recent tool evidence; SSE and durable captions deferred |
| Knowledge selection | Full selected-document ID set with optimistic revision; accessed through Documents UI |
| Document identity | No document versioning; every upload creates an independent immutable document |
| Retrieval | Exact semantic search initially; vector acceleration only after measurement |
| History | Durable text; live session/tool diagnostics only |
| Models | Fixed server profiles; text/embedding from planned OpenAI integration; live provider remains a Day 1 choice |
## 3. Modules and ports
| Module / suggested path | Responsibility | Allowed dependencies |
| --- | --- | --- |
| `app/api/v1/` | Transport DTOs, cookies, CSRF, HTTP error mapping | Application services |
| `modules/identity/` | Login, sessions, actor context | Users/session repository, password verifier |
| `modules/documents/` | Upload, status, selection, delete/retry | FileStore, document/job repository |
| `modules/knowledge/` | Search and evidence validation | EmbeddingProvider, knowledge repository |
| `modules/conversations/` | Turns, history, agent loop, citations | TextModel, search service, conversation repository |
| `modules/live/` | Signaling, control, tool dispatch, close/poll | LiveProvider, shared search, live repository |
| `modules/configuration/` | Assistant name/instruction and revisions | Settings repository |
| `infrastructure/` | SQLAlchemy, file I/O, provider clients, job claiming | Domain/application ports |
| `app/worker.py` | Claim and execute ingestion jobs | Document processing service |
Keep interfaces small: `TextModel.run_turn`, `EmbeddingProvider.embed`, `LiveProvider.create/control/close`, `FileStore.put/read`, and `KnowledgeRepository.search`. Their precise SDK calls depend on selected providers. Application services must not import provider-native response objects. The provider model emits a tool call; the dispatcher validates it; the search service queries storage. Models never receive SQL/database credentials.
## 4. Implementation order and deliverables
| Day | Build | Concrete exit condition |
| --- | --- | --- |
| 1 | Inspect reusable code; sample files; real voice/tool spike; freeze formats and live signaling | A real browser voice session causes one trusted backend tool execution |
| 2 | Database migrations, seed accounts, auth, upload, minimal deployment | Login and stored upload survive restart |
| 3 | Extractor, chunking, embedding, durable worker | Ready document and clear unreadable-file failure |
| 4 | Shared search, selection revision, scope checks | Selected ready chunks returned with source identities |
| 5 | Conversations, turns, agent loop, citations, recovery | Text question returns evidence-based answer; retry cannot duplicate a turn |
| 6 | Live adapter connected to real search | Spoken document question answered; disconnect/close visible |
| 7 | Four screens, settings, deployed scenario | Demo on intended HTTPS environment; feature freeze |
| 8–10 | Quality evaluation, defect fixes, failure checks, rehearsal | Acceptance evidence and reproducible release |
Complete meaningful checks during development, not only after Day 7. A provider delay or unextractable corpus changes the estimate; resolve it early. Do not silently drop voice to claim this plan was delivered.
## 5. Identity and request context
Login verifies a stored password hash using a maintained password-hashing implementation. Generate an unpredictable session token; store only its hash. Cookie `rag_session` is HttpOnly, Secure and SameSite=Lax. Restrict Origin on login and mutations. Return a session CSRF token after login and through `/me`; require `X-CSRF-Token` on authenticated mutations. Configure session expiry at deployment; no business retention period is assumed here.
Resolve `(user_id, organization_id, role)` exclusively from the session. Check owner for conversation/turn/live endpoints, including administrator requests: admin status does not automatically grant access to other users' chats. Return 404 for hidden resource IDs, 403 for an authenticated non-admin calling an admin-only collection operation. Rate-limit login/provider operations with conservative single-instance limits.
## 6. Document upload and ingestion
1. Validate admin access, idempotency key, size, approved MIME/signature and safe display filename.
2. Hash file bytes and normalized metadata. Write original to a generated storage key using temporary storage then atomic move where supported. Never use user filenames as paths.
3. In a short transaction create document and queued job. A unique organization/upload key detects repeated upload; changed payload under the same key returns 409. Clean unused staged bytes on replay.
4. Worker claims a queued eligible job or expired processing job with a fresh token and lease. Increment attempts. Extract, normalize and chunk outside a long transaction.
5. Preserve headings and available page/section positions. Empty extraction is failure. Unsupported scans/tables must not look successfully indexed.
6. Build embeddings with the configured profile. Stage vectors in worker memory for the bounded corpus, or temporary non-queryable storage if necessary.
7. In one transaction lock document/job, verify claim token and non-expired lease, recheck non-deletion, publish that document's chunks, mark document ready and job succeeded. Document remains inactive until selected.
In Phase 1, rerun the whole pipeline after a crash instead of building checkpoint orchestration. Uniqueness on `(document_id, ordinal)` and a single final publication transaction prevent duplicates. Heartbeat during long provider calls; a worker that loses its claim must discard its result.
For transient network/rate-limit errors, schedule bounded exponential backoff with jitter using `next_attempt_at`; after configured attempts, mark failed. For invalid input, fail immediately. Manual retry requeues the same job, resets attempt budget and increments `retry_generation`; audit the action. It does not change original file bytes.
Database and files are not one transaction. A maintenance command reports orphan file keys and missing originals; safe cleanup uses a grace interval. Soft deletion is immediate retrieval exclusion. Physical content purging awaits an explicit retention policy.
## 7. Selection, revisions and revocation
`organization_settings` has three counters: `revision` for assistant configuration, `knowledge_revision` for selected-set changes, and `access_epoch` for knowledge removals. All begin at 1.
Selection update locks the settings row, checks `expected_revision` against `knowledge_revision`, validates every selected document is ready/not deleted, and updates the selected flags atomically. If the set changes, increment `knowledge_revision`. If any document is removed, increment `access_epoch` too. A no-op preserves counters. Activation alone does not invalidate old conversations; new turns use the current selected set.
Each conversation records `access_epoch` on creation. For simple safe Phase 1 revocation, any active-document removal invalidates ALL older organization conversations for new turns. Close running live sessions and fail/stop running text turns; preserve old history for authorized viewing. UI asks the user to start a new conversation. No full history is copied into it.
Use settings-row serialization when creating/finalizing turns and initiating live sessions. Text finalization rechecks epoch while holding that row lock; commits before a removal are historical answers, and commits after it must fail as stale. Live tool results are rechecked before sending. Direct audio already sent cannot be recalled; provider close is best effort and must be tested. Logout and session expiry also close owned active live sessions.
## 8. Text turn execution
The UI creates a `mode=text` conversation, then sends `POST /chat` with a UUID `client_request_id`.
In a short transaction: authenticate, lock settings/conversation consistently, verify active conversation/current epoch, resolve the request key, reject another running turn, insert running turn and user message. Set a processing deadline. Then release database locks before provider calls.
Build model context from completed authorized turns within the token budget. Add assistant instruction, tool schema and current question. Treat document text as untrusted evidence, not instructions. A search query argument contains only query text; the server determines organization and selection.
Loop within configured tool-call and time limits. Store normalized tool results and correlate call IDs. Assign source references uniquely across the entire text turn (not separately as S1 for every search); remap tool evidence before returning it to the model. Persist the actual organization instruction in the execution snapshot so a later settings change does not destroy traceability. For substantive document claims, require current search evidence. Validate each cited source against evidence returned during this turn. Structural validation does not prove semantic accuracy; the reference evaluation set checks factual support.
At completion recheck epoch, write assistant message/citations and terminal turn status in one transaction. Terminal statuses: `answered`, `needs_clarification`, `insufficient_information`, `failed`. Search/provider errors produce `failed`, not `insufficient_information`.
If the browser times out, it queries the turn by client request ID. Retrying the same payload returns the existing result or 202 running state. Same key plus different payload returns 409. No automatic regeneration after an ambiguous provider timeout. An interrupted run is marked failed; a new user retry uses a new key. On API restart mark its interrupted running turns failed; periodic deadline cleanup handles stalled tasks. This is intentionally simpler than a durable text job queue.
## 9. Live lifecycle
Create a fresh `mode=voice` conversation. Proposed signaling is an SDP-offer request and SDP-answer response via backend. This shape is provisional until the Day 1 integration proves provider support; if credential-based signaling is required, revise the live API section before frontend freeze.
Persist a `creating` session reservation and request hash before calling the provider. Establish server control and install approved tools/instructions before returning the answer. An SDP answer means signaling is ready, not that audio is connected. State becomes connected only on trusted provider/adapter confirmation.
Route each tool event to the SAME search service with session owner and current epoch. Deduplicate by provider call ID and return the same result for duplicates; conflicting payloads fail. Persist recent tool evidence for UI polling. Live transcripts/captions are not required durable records.
States: `creating → connecting → connected → closed`; any nonterminal state can become `failed` or `closed`. Connection/control timeout closes provider resources. Browser can start a new session after failure, not automatically replay old signaling. On process restart, mark previously nonterminal sessions failed and attempt provider cleanup. One active live session per conversation; use configured session TTL to bound abandoned sessions.
## 10. Internal search contract
```json
{"name":"search_documents","arguments":{"query":"ساعت کاری پنجشنبه"}}
```
Only `query` is model-supplied. Reject extra scope fields. Proposed limit: 1–2000 characters. Server defaults for this demo: top 5 chunks and maximum 12000 evidence characters; tune using the corpus, not as a quality guarantee.
```json
{"status":"ok","knowledge_revision":2,"sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","text":"پنجشنبه‌ها از ساعت ۸ تا ۱۲","location":{"page":2,"section":null}}]}
```
Empty evidence: `status=no_evidence`, empty sources. Failure: `status=error` with normalized error code/retryability, never a fake empty-success result. Returned text must pass a final active/document/epoch check. Retrieval scope is ready active undeleted organization documents only. Use the same embedding profile for query and corpus. A new embedding profile requires reindexing; Phase 1 has no UI for it.
## 11. Deployment and configuration
Deploy UI/reverse proxy, one API process, one worker process and PostgreSQL. Mount persistent originals and database volumes. Configure HTTPS, cookie domain/origin, provider secrets, approved file formats, size cap, model profile IDs, embedding dimension, tool limits, request deadlines, job lease/retry budget and session TTL. Do not commit secrets. File-size/retention/session durations are deployment choices, not silently approved organization policy.
Readiness checks DB/schema/vector availability and writable/available required storage; report worker heartbeat age as a degraded ingestion indicator. For the single-host release, the worker can update a small heartbeat file on the shared durable volume; a separate heartbeat table is unnecessary. Liveness does not call AI providers. Provider failure must not make login/history unavailable by design. Log request/turn/job/session IDs and redacted error categories; avoid document bodies, SDP, prompts, cookies and keys.
## 12. Tests and handoff
| Test group | Required evidence |
| --- | --- |
| Access | User cannot mutate docs/settings or read another conversation; forged organization IDs ineffective |
| Ingestion | Empty extraction fails; crash/lease expiry recovered; stale claim cannot publish |
| Selection | Atomic revision conflict, inactive exclusion, revocation invalidates old context |
| Turns | Same-key replay, changed-payload conflict, concurrent-turn rejection and timeout lookup |
| Grounding | Answerable, absent, ambiguous and follow-up questions against curated evidence |
| Voice | Real WebRTC plus real tool call, provider/control loss, close, epoch revocation |
| Persistence | Restart preserves history and recovers jobs; active voice/text interruption is explicit |
Map results to P1-01 through P1-12 in the delivery plan. Hand off startup/migration/seed commands, secret-free environment example, API examples, known limitations, reference questions, release revision and actual test results. Do not report these tests as passed until implementation runs them.
## 13. Decisions still requiring confirmation
File formats and limits; text/embedding/live model identifiers; vector dimension; actual live signaling/control capabilities; hosting and provider reachability; account/session/retention policy; final quality threshold and delivery date. Technical defaults above are proposals to make work concrete, not assertions of client approval.
@@ -0,0 +1,256 @@
# گزارش فاز یک دستیار اسناد سازمان — پیاده‌سازی، API و دیتابیس با سناریو
نسخه ۱.۱ — تاریخ ۲۰۲۶/۱۰/۰۵
این گزارش طراحی پیشنهادی پیاده‌سازی است؛ به معنی ساخته‌شدن برنامه، اجرای مایگریشن یا موفقیت تست‌ها نیست. بازه تحویل همان ۷ تا ۱۰ روز و فرض ظرفیت، یک توسعه‌دهنده اصلی است.
## ۱. این مجموعه سند دقیقاً چه چیزی تحویل می‌دهد؟
| سند | کاربرد |
| --- | --- |
| `RAG-Phase1-Implementation-Guide.md` | توسعه‌دهنده بداند چه ماژول‌هایی بسازد، ترتیب کار چیست و هر جریان چگونه اجرا شود |
| `RAG-Phase1-API-Catalog.md` | فرانت و بک‌اند روی آدرس‌ها، ورودی، خروجی، دسترسی، وضعیت و خطا توافق کنند |
| `RAG-Phase1-Database-Design.md` | جداول، ستون‌ها، ارتباط‌ها، محدودیت‌ها و ترتیب مایگریشن مشخص باشند |
| همین گزارش | جریان محصول و ارتباط API، منطق و دیتابیس با مثال قابل فهم باشد |
مبنای محدوده، `RAG-AI-Phase1-Delivery-Plan.md` است. سند معماری اصلی مسیر محصول کامل را نگه می‌دارد؛ امکاناتی که آنجا آمده‌اند الزاماً در فاز یک پیاده نمی‌شوند.
سه سند فنی انگلیسی‌اند تا برای داکیومنت پروژه و توسعه قابل استفاده باشند. این گزارش فارسی است. قراردادهای تازه مثل روش احراز هویت و جزئیات جدول‌ها، پیشنهاد فنی مشخص برای شروع‌اند و تأیید قبلی کارفرما فرض نشده است.
## ۲. محصولی که در پایان فاز یک نشان می‌دهیم
مدیر وارد سامانه می‌شود، سند سازمان را آپلود می‌کند، آماده‌شدن آن را می‌بیند و فعالش می‌کند. کاربر از طریق متن یا صوت سؤال می‌پرسد. مدل تصمیم می‌گیرد ابزار سرچ را اجرا کند؛ بک‌اند شواهد را از اسناد فعال پیدا می‌کند و مدل بر اساس آن پاسخ می‌دهد.
چهار صفحه داریم: ورود، گفتگو، اسناد و تنظیمات. در تنظیمات فقط نام و دستورالعمل دستیار تغییر می‌کند. انتخاب اسناد در صفحه اسناد است. مدل‌ها از تنظیمات سرور تعیین می‌شوند. مدیریت مدل، نسخه‌بندی خودکار سند، OCR عمومی، SSO، ثبت‌نام و تاریخچه کامل صوتی به این تحویل اضافه نشده‌اند.
تصمیم ساده‌سازی: جدول نسخه‌ها حذف شده است. هر آپلود یک سند مستقل می‌سازد؛ قطعات و کار پردازش مستقیم به آن متصل‌اند. برای اصلاح محتوا، فایل جدید آپلود و پس از آماده‌شدن جای سند فعال قبلی انتخاب می‌شود. Retry همان سند را دوباره پردازش می‌کند و سند تازه نمی‌سازد. تعداد جدول‌ها اکنون ۱۴ است.
## ۳. تقسیم کار سیستم با زبان ساده
| جزء | کار واقعی |
| --- | --- |
| مرورگر | فرم‌ها، نمایش چت و منابع، میکروفون و پخش صوت |
| API | دریافت درخواست، بررسی هویت و دسترسی و برگرداندن نتیجه |
| سرویس گفتگو | اجرای نوبت متنی، نگهداری سابقه و مدیریت درخواست تکراری |
| مدل | تشخیص نیاز به سرچ و تولید پاسخ با شواهد |
| ابزار سرچ | اجرای جست‌وجو در اسناد آماده و فعال؛ مدل SQL اجرا نمی‌کند |
| Worker | استخراج متن و ساخت قطعات و Embedding در پس‌زمینه |
| PostgreSQL + pgvector | کاربران، اسناد، کارها، بردارها، گفتگوها و وضعیت‌ها |
| مخزن فایل | نگهداری فایل اصلی آپلودشده |
| کنترل‌کننده Live | ساخت و بستن جلسه صوتی و اجرای ابزارها در بک‌اند |
همه ماژول‌های بک‌اند در یک کدبیس‌اند. Worker یک فرایند جدا از API است تا پردازش فایل، پاسخگویی UI را معطل نکند. صف کارها همان جدول دیتابیس است و در این فاز Redis یا RabbitMQ لازم نشده است.
## ۴. سناریو اول: مدیر سند ساعات کاری را آپلود می‌کند
فرض کنیم فرمت فایل نمونه در روز اول تأیید شده و متن آن قابل استخراج است. سند می‌گوید: «پنجشنبه‌ها از ساعت ۸ تا ۱۲».
| قدم | درخواست یا رفتار | اتفاق در دیتابیس | نتیجه UI |
| --- | --- | --- | --- |
| ۱ | `POST /api/v1/auth/login` | نشست احراز هویت در `auth_sessions` | ورود موفق |
| ۲ | `POST /api/v1/documents` با فایل | یک سند مستقل در `documents` و کار متصل به همان سند در `ingestion_jobs` ساخته می‌شود | «در صف پردازش» |
| ۳ | Worker کار را می‌گیرد | وضعیت job و سند processing می‌شود | «در حال پردازش» |
| ۴ | استخراج، قطعه‌بندی و Embedding | هنوز قطعات ناقص وارد سرچ نمی‌شوند | کاربر منتظر وضعیت آماده می‌ماند |
| ۵ | انتشار موفق | قطعات در `document_chunks`؛ سند ready؛ job succeeded | «آماده، غیرفعال» |
| ۶ | مدیر فعال می‌کند | مجموعه انتخاب‌شده با `PATCH /knowledge-selection` تغییر می‌کند | «فعال برای پاسخگویی» |
آپلود پاسخ ۲۰۲ می‌دهد؛ یعنی فایل و کار پردازش ثبت شده‌اند، نه اینکه مدل همان لحظه آن را می‌شناسد. فرانت با `GET /documents/{id}` وضعیت را می‌خواند.
سند آماده ولی غیرفعال قابل سرچ نیست. این دو وضعیت مستقل‌اند: یکی می‌گوید پردازش انجام شده، دیگری می‌گوید سازمان اجازه استفاده داده است.
اگر فایل تصویر اسکن‌شده باشد و OCR در فرمت‌های تأییدشده نباشد، وضعیت failed با توضیح قابل فهم نمایش داده می‌شود. سند خالی به عنوان «آماده» ثبت نمی‌شود.
## ۵. سناریو دوم: کاربر متنی سؤال می‌پرسد
کاربر می‌نویسد: «پنجشنبه تا چه ساعتی باز هستید؟»
۱. فرانت با `POST /conversations` یک گفتگوی text می‌سازد.
۲. سؤال را همراه `conversation_id` و `client_request_id` به `POST /chat` می‌دهد.
۳. بک‌اند یک `turn` به معنی «یک نوبت سؤال و پاسخ» ثبت می‌کند. سؤال کاربر در `messages` ذخیره می‌شود.
۴. مدل می‌بیند برای پاسخ به اطلاعات سازمان نیاز دارد و ابزار `search_documents` را با کوئری «ساعت کاری پنجشنبه» صدا می‌زند.
۵. ابزار هویت سازمان را از نشست معتبر می‌گیرد؛ خود مدل نمی‌تواند سازمان یا اسناد مجاز را عوض کند.
۶. سؤال به بردار تبدیل می‌شود و قطعات مرتبط از اسناد آماده و فعال پیدا می‌شوند.
۷. متن قطعه، شناسه سند و قطعه و محل منبع به مدل برمی‌گردد.
۸. مدل پاسخ می‌دهد: «طبق سند ساعات کاری، پنجشنبه‌ها تا ساعت ۱۲ باز هستیم.»
۹. پاسخ در `messages` و ارجاع آن در `citations` ذخیره می‌شود؛ turn به answered می‌رسد.
۱۰. UI پاسخ و منبع را نمایش می‌دهد.
```mermaid
sequenceDiagram
participant U as User
participant B as Backend
participant M as AI Model
participant S as Search Tool
participant D as Database
U->>B: Text question
B->>D: Save running turn
B->>M: Question and tool schema
M->>B: Search tool call
B->>S: Execute authorized search
S->>D: Retrieve selected ready chunks
D-->>S: Evidence
S-->>B: Content and sources
B->>M: Tool result
M-->>B: Grounded answer
B->>D: Save answer and citations
B-->>U: Answer and sources
```
ایجنتیک بودن همین است: برای «سلام» لازم نیست سرچ انجام شود، اما برای ادعای مربوط به سند سازمان شواهد لازم است. ابزار جواب نهایی را تولید نمی‌کند؛ اطلاعات لازم را می‌آورد.
## ۶. سناریو سوم: اطلاعات پیدا نمی‌شود یا سؤال مبهم است
| سؤال/وضعیت | رفتار درست | وضعیت نوبت |
| --- | --- | --- |
| «پنجشنبه تا چند باز هستید؟» و سند مربوط موجود است | پاسخ مستند | answered |
| «اون روز تا چند باز هستید؟» بدون زمینه کافی | «منظورتان کدام روز است؟» | needs_clarification |
| «مبلغ پاداش امسال چقدره؟» و سندی درباره آن نیست | اعلام نبود اطلاعات در اسناد | insufficient_information |
| سرویس Embedding قطع است | اعلام مشکل سرویس؛ نه ادعای نبود اطلاعات | failed |
تفاوت دو ردیف آخر مهم است: «جست‌وجو انجام شد و مدرک نبود» با «جست‌وجو نتوانست اجرا شود» یکی نیست. API و دیتابیس این تفاوت را حفظ می‌کنند تا UI پیام اشتباه نشان ندهد.
## ۷. سناریو چهارم: کاربر دوبار ارسال می‌زند یا پاسخ HTTP گم می‌شود
فرض کنیم سؤال ثبت شده و مدل در حال پاسخ است، ولی اینترنت مرورگر برای لحظه‌ای قطع می‌شود.
فرانت نباید فوراً یک سؤال جدید با شناسه جدید بسازد. همان `client_request_id` را نگه می‌دارد و از این مسیر وضعیت را می‌پرسد:
`GET /api/v1/conversations/{conversation_id}/turns/{client_request_id}`
- اگر running باشد، منتظر می‌ماند.
- اگر answered باشد، همان جواب ثبت‌شده را نمایش می‌دهد.
- اگر failed باشد، خطا را نشان می‌دهد؛ تلاش جدید آگاهانه با شناسه جدید انجام می‌شود.
- اگر هنوز رکورد ثبت نشده باشد، همان درخواست و همان شناسه را دوباره می‌فرستد.
در دیتابیس ترکیب گفتگوی مشخص و شناسه درخواست یکتا است. بنابراین دو بار ارسال یک درخواست، دو نوبت مستقل نمی‌سازد. این همان کاربرد عملی Idempotency است.
اگر سؤال با همان شناسه عوض شود، ۴۰۹ می‌گیریم؛ این خطای برنامه فرانت است. اگر در یک گفتگو یک نوبت در حال اجرا باشد و سؤال جدید با شناسه دیگر برسد، `CONVERSATION_BUSY` برمی‌گردد. در فاز یک نوبت‌های یک گفتگو هم‌زمان اجرا نمی‌شوند.
## ۸. سناریو پنجم: کاربر صوتی سؤال می‌پرسد
۱. کاربر دکمه شروع مکالمه را می‌زند و دسترسی میکروفون می‌دهد.
۲. یک گفتگوی voice ساخته می‌شود.
۳. مرورگر اطلاعات برقراری WebRTC را به `POST /voice/sessions` می‌دهد.
۴. بک‌اند جلسه مدل Live و کانال کنترل معتبر را آماده می‌کند.
۵. پاسخ اتصال به مرورگر می‌رسد؛ صوت مستقیم میان مرورگر و ارائه‌دهنده منتقل می‌شود.
۶. کاربر می‌گوید: «پنجشنبه تا چند باز هستید؟»
۷. مدل Live ابزار سرچ را درخواست می‌کند؛ بک‌اند همان سرویس سرچ متن را اجرا می‌کند.
۸. شواهد به مدل Live می‌رسند و مدل پاسخ صوتی می‌دهد.
۹. UI از وضعیت جلسه و نتایج اخیر ابزار، منابع بازیابی‌شده را نشان می‌دهد.
**صوت از API ما عبور نمی‌کند؛ ولی جست‌وجو و کنترل دسترسی از بک‌اند می‌گذرد.** هیچ کلید دائمی ارائه‌دهنده در مرورگر قرار نمی‌گیرد.
جزئیات SDP در کاتالوگ یک قرارداد پیشنهادی است. روز اول باید با ارائه‌دهنده منتخب واقعاً تست شود؛ حمایت از WebRTC و کنترل معتبر ابزار برای همه ارائه‌دهندگان فرض نشده است.
در فاز یک تاریخچه کامل صوتی و ادامه بی‌وقفه جلسه پس از قطعی نداریم. اگر اتصال قطع شود، UI اعلام می‌کند و کاربر جلسه جدید می‌سازد. منابع نمایش‌داده‌شده در صوت «منابع بازیابی‌شده» هستند؛ ادعا نمی‌کنیم تک‌تک آن‌ها دقیقاً در جمله صوتی استفاده شده‌اند.
## ۹. سناریو ششم: سازمان سند ساعات کاری را عوض می‌کند
سند قدیمی ساعت پایان را ۱۲ نوشته؛ سند جدید ساعت ۱۳ را اعلام می‌کند.
۱. مدیر سند جدید را جداگانه آپلود می‌کند و منتظر آماده‌شدن می‌ماند.
۲. سند قدیمی را از انتخاب خارج و جدید را فعال می‌کند. API می‌تواند مجموعه نهایی انتخاب‌ها را در یک تغییر ثبت کند؛ هر دو فایل سند مستقل‌اند و هیچ شماره نسخه یا جدول نسخه‌ای نداریم.
۳. شمارنده تغییر منابع افزایش پیدا می‌کند.
۴. چون سندی حذف شده، شمارنده اعتبار زمینه گفتگو هم تغییر می‌کند.
۵. گفتگوهای قبلی سازمان برای سؤال جدید stale می‌شوند؛ UI دکمه «گفتگوی جدید» نشان می‌دهد.
۶. جلسه‌های صوتی قبلی بسته می‌شوند تا زمینه قدیمی دوباره استفاده نشود.
۷. گفتگوی جدید سؤال را از سند جدید جواب می‌دهد: ساعت ۱۳.
برای سرعت و سادگی فاز یک، هنگام حذف یک منبع فعال همه گفتگوهای قدیمی سازمان برای ادامه نامعتبر می‌شوند؛ نه فقط گفتگوهایی که قطعاً از همان سند استفاده کرده‌اند. این رفتار محافظه‌کارانه است و در فاز بعد می‌توان دقیق‌ترش کرد.
پاسخ قبلی که «۱۲» گفته، در تاریخچه همان پاسخ قبلی باقی می‌ماند؛ با تغییر سند بازنویسی نمی‌شود. صوتی که قبلاً پخش شده هم قابل پس‌گرفتن نیست. کنترل ما روی استفاده بعدی از اطلاعات است.
## ۱۰. سه عدد revision چه فرقی دارند؟
| فیلد | چه وقت تغییر می‌کند؟ | کاربرد |
| --- | --- | --- |
| revision | تغییر نام یا دستورالعمل دستیار | جلوگیری از ذخیره هم‌زمان روی تنظیمات قدیمی |
| knowledge_revision | تغییر مجموعه اسناد فعال | مشخص‌کردن مجموعه دانش هر نوبت |
| access_epoch | خارج‌کردن سند فعال یا حذف آن | نامعتبرکردن زمینه‌های قدیمی گفتگو |
مثال: فقط سندی اضافه کنیم، knowledge_revision تغییر می‌کند و سؤال بعدی آن را می‌بیند. سند فعالی را برداریم، access_epoch هم تغییر می‌کند تا اطلاعات قدیمی از حافظه گفتگو دوباره وارد پاسخ نشوند.
اگر دو مدیر هم‌زمان تنظیمات را باز کنند، درخواست دوم که revision قدیمی دارد ۴۰۹ می‌گیرد. UI تنظیمات تازه را می‌خواند تا تغییر مدیر اول ناخواسته از بین نرود.
## ۱۱. سناریو هفتم: Worker وسط کار قطع می‌شود
Worker فایل را گرفته و مشغول Embedding است. فرایند قطع می‌شود.
کار در دیتابیس مانده است. Worker برای مدت محدود اجازه پردازش داشته که Lease نام دارد. بعد از تمام‌شدن این مدت، کار قابل گرفتن دوباره است. دریافت‌کننده جدید یک claim token تازه می‌گیرد.
اگر Worker قبلی دیر برگردد، توکنش دیگر معتبر نیست و حق انتشار ندارد. Worker جدید می‌تواند پردازش را از ابتدا انجام دهد. در این فاز ادامه‌دادن دقیق از هر قطعه را پیاده نمی‌کنیم؛ انتشار نهایی یکپارچه است و محدودیت یکتایی، ساخت قطعات تکراری را می‌گیرد.
برای خطای موقت، تلاش مجدد با فاصله انجام می‌شود. برای فایل خراب، ادامه دادن بی‌فایده است و failed نمایش داده می‌شود. مدیر فقط برای خطای قابل تلاش مجدد می‌تواند Retry بزند. خود Retry هم کلید یکتا دارد تا دوبار کلیک، دو بار بودجه تلاش را بازنشانی نکند.
## ۱۲. چرا این جدول‌ها لازم‌اند؟
| گروه | جدول‌ها | مثال ساده |
| --- | --- | --- |
| هویت | organizations، users، auth_sessions | چه کسی وارد شده و چه اجازه‌ای دارد؟ |
| تنظیمات | organization_settings | اسم دستیار و نسخه تنظیمات و منابع چیست؟ |
| اسناد | documents | این فایل چیست، کجا ذخیره شده و آماده پاسخگویی است؟ |
| پردازش | ingestion_jobs | چه فایلی منتظر است و چرا پردازشش شکست خورده؟ |
| دانش | document_chunks | کدام تکه متن و بردار باید جست‌وجو شود؟ |
| گفتگو | conversations، turns، messages | کدام مکالمه، کدام نوبت، چه سؤال و پاسخی؟ |
| شواهد | tool_calls، citations | چه سرچ‌هایی انجام شد و جواب به چه منبعی استناد کرد؟ |
| صوت | live_sessions | کدام جلسه وصل است و چرا بسته شده؟ |
| تغییرات مدیریتی | audit_events | چه کسی سند را غیرفعال یا Retry کرده؟ |
تعداد جدول‌ها به معنی تعداد سرویس یا برنامه جدا نیست. برای مثال سه جدول گفتگو لازم‌اند چون «گفتگو»، «اجرای یک سؤال» و «متن پیام» وضعیت و مسئولیت متفاوت دارند. نگهداری صرف متن پیام برای تشخیص timeout و درخواست تکراری کافی نیست.
فایل اصلی در مخزن فایل است؛ مسیر تولیدشده آن در خود سند ذخیره می‌شود. بردارها در pgvector داخل همان PostgreSQL هستند. فایل صوتی خام ذخیره نمی‌کنیم.
## ۱۳. سناریو هشتم: حذف سند
مدیر حذف را تأیید می‌کند. ابتدا سند از سرچ خارج و deleted ثبت می‌شود. اگر فعال بوده، زمینه گفتگوها هم نامعتبر می‌شود. پاسخ API صریحاً می‌گوید پاک‌سازی فیزیکی منتظر سیاست نگهداری است؛ «حذف از پاسخگویی» را با «پاک‌شدن فوری تمام فایل‌ها و تاریخچه» یکی نمی‌کنیم.
دلیل نگه‌داشتن شناسه منبع این است که جواب قدیمی همچنان قابل ردیابی باشد. اینکه متن قطعات، فایل اصلی یا excerptها چه زمانی واقعاً پاک شوند، باید از سازمان مشخص شود. در این اسناد عدد دلخواه برای مدت نگهداری ننوشته‌ایم.
منبع غیرفعال/حذف‌شده در نمایش منابع جدید متن قابل دسترس ارائه نمی‌کند. تاریخچه پاسخ‌های قبلی متعلق به کاربر، طبق دسترسی تاریخچه باقی می‌ماند؛ وارد زمینه گفتگوی جدید نمی‌شود.
## ۱۴. برنامه عملی توسعه و معیار پیشرفت
| بازه | چیزی که باید بتوانیم نشان دهیم |
| --- | --- |
| روز ۱ | صوت واقعی و اجرای ابزار در بک‌اند؛ فرمت فایل و مدل‌ها مشخص |
| روز ۲ | ورود و آپلود ماندگار |
| روز ۳ | تبدیل فایل به سند ready و خطای قابل فهم برای فایل نامعتبر |
| روز ۴ | سرچ فقط روی اسناد فعال با منبع درست |
| روز ۵ | چت متنی و بازیابی وضعیت درخواست پس از timeout |
| روز ۶ | سؤال صوتی و سرچ واقعی در همان دانش |
| روز ۷ | چهار صفحه و دموی کامل روی HTTPS |
| روز ۸ تا ۱۰ | اصلاح کیفیت، تست شکست‌ها، آماده‌سازی نسخه ارائه |
این زمان‌بندی تضمین بدون شرط نیست. اگر UI از صفر و فایل‌ها پیچیده باشند یا اتصال مدل Live حل نشود، ریسک زمان بالا می‌رود. اول امکانات تزئینی و اختیاری حذف می‌شوند؛ دسترسی صحیح و سه قابلیت اصلی نباید پنهانی حذف شوند.
## ۱۵. چک‌لیست ارائه و پذیرش
- کاربر عادی نتواند تنظیمات یا اسناد را تغییر دهد و گفتگوی دیگری را بخواند.
- فایل آماده‌نشده وارد سرچ نشود.
- سؤال مستند جواب و منبع درست داشته باشد.
- سؤال بی‌پاسخ با اطلاعات ساختگی جواب داده نشود.
- ارسال تکراری، نوبت یا کار پردازشی تکراری نسازد.
- قطع Worker باعث از دست رفتن کار پذیرفته‌شده نشود.
- مکالمه صوتی واقعاً از WebRTC و ابزار بک‌اند استفاده کند.
- خروج کاربر، پایان جلسه یا تغییر منابع فعال، وضعیت Live را درست تغییر دهد.
- تاریخچه متن بعد از restart باقی بماند.
- دمو روی شبکه و مرورگر محیط ارائه تمرین شده باشد.
۱۵ تا ۲۰ سؤال مرجع از اسناد واقعی آماده می‌کنیم؛ برای هرکدام جواب مورد انتظار و قطعه منبع را می‌نویسیم. نتیجه اجرای متن و صوت جدا ثبت می‌شود. این مجموعه کوچک، تضمین دقت عمومی محصول نیست.
## ۱۶. مواردی که قبل از شروع باید قطعی شوند
| سؤال | مسئول پیشنهادی |
| --- | --- |
| فایل‌های واقعی چه فرمت و ساختاری دارند و حداکثر اندازه چیست؟ | صاحب محصول + توسعه‌دهنده |
| مدل Live منتخب اتصال و کنترل ابزار مورد نیاز را پشتیبانی می‌کند؟ | توسعه‌دهنده/تیم AI با آزمایش واقعی |
| مدل Embedding و تعداد ابعادش چیست؟ | تیم AI قبل از مایگریشن بردار |
| محیط HTTPS و دسترسی به ارائه‌دهنده آماده است؟ | توسعه‌دهنده/زیرساخت |
| مدت نشست و نگهداری فایل/گفتگو چقدر است؟ | صاحب محصول/سازمان |
| شروع کار و تاریخ ارائه دقیقاً چه روزی است؟ | مدیر پروژه |
## ۱۷. نحوه استفاده از اسناد توسط توسعه‌دهنده
ابتدا Implementation Guide برای ترتیب کار و مرز ماژول‌ها؛ سپس API Catalog برای DTO و هماهنگی فرانت؛ بعد Database Design برای مدل‌های ORM و مایگریشن. سناریوهای این گزارش باید تبدیل به تست‌های یکپارچه شوند.
قراردادها در این مجموعه با هم هماهنگ شده‌اند، اما هنوز تصمیم‌های روز اول بازند. پس از تأیید فرمت و مدل و اتصال Live، همین اسناد نسخه جدید می‌گیرند. افزودن قابلیت محصول کامل به کارهای این فاز باید با تغییر صریح محدوده یا زمان‌بندی انجام شود.
@@ -0,0 +1,193 @@
# Prompt: Create Repository Skills for the Phase 1 RAG Assistant
Paste the following prompt into the coding agent with the project repository open. Make the six current project documents available in the repository first; their exact directory is discovered by the agent. This prompt creates development skills, not application features.
---
You are working inside my Organization Knowledge Assistant repository. Create three practical, repository-scoped development skills:
1. `implement-feature`
2. `write-tests`
3. `review-change`
Integrate relevant real-provider RAG evaluation into `write-tests`; do not create a separate `verify-rag-flow` skill.
Implement the skill files and necessary references now. Do not stop at a proposal or print hypothetical file contents. Do not implement product features while creating these skills.
## 1. Inspect the repository and agent environment
Before writing:
- Locate the repository root and inspect Git status. Preserve unrelated modifications.
- Read applicable root and nested `AGENTS.md` files and any existing skill-authoring instructions.
- Inspect the agent's actual supported repository skill location and existing skill conventions. Use that supported location; do not assume a directory merely because it appears in an example. If no project skill discovery mechanism is available, create reusable skill documents in a clearly identified repository directory and report that automatic discovery is unverified. Do not claim installation without evidence.
- Inspect existing skills by frontmatter name. Update equivalent project-owned skills rather than creating duplicate names. Do not modify system, plugin or globally installed skills.
- Inspect the application tree, dependency manifests, test configuration, CI and existing commands. Do not prescribe a new framework or test runner when suitable conventions already exist.
- Prefer `rg` and `rg --files` for discovery.
Do not hardcode paths from another machine, ChatGPT scratch directories, Library IDs or inaccessible sandbox links.
## 2. Resolve the actual project references
Find these exact filenames, wherever they are located in the repository:
| Document | Purpose |
| --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | Phase 1 scope, delivery sequence and acceptance criteria |
| `RAG-Phase1-Implementation-Guide.md` | Modules, responsibilities, workflows and implementation boundaries |
| `RAG-Phase1-API-Catalog.md` | Routes, DTOs, permissions, errors, retry and idempotency contracts |
| `RAG-Phase1-Database-Design.md` | Current schema, constraints, transactions and migration approach |
| `RAG-Phase1-Scenario-Report-FA.md` | Business scenarios and Persian explanations |
| `RAG-AI-Architecture.md` | Wider architecture and future direction |
Read enough of each to verify it is the current simplified design. The current design has independent uploaded documents and no document-content versioning. Do not select an obsolete document just because its filename matches. Resolve duplicates using content, repository context and document status; ask a focused question only when competing authoritative copies cannot be distinguished.
Create or update one small shared reference index in the repository's existing documentation area. If there is no convention, use `docs/development/agent-reference-map.md`. Record:
- The actual relative path to each document and what it governs.
- Which sections each skill should consult, preferably with verified heading anchors or heading names.
- Actual relevant source/test directories and verified development commands.
- Any missing references or unresolved contradictions, explicitly labelled.
Do not copy whole documents into the skills. Do not fabricate missing contents, executable commands, schema fields or approval decisions. If a required document is missing, continue building the available skill structure; label the relevant workflow blocked on that reference and report exactly what is missing. Do not leave a broken link disguised as an existing reference.
Every skill must link directly to this reference index using a valid relative link from its own `SKILL.md`. Within the index, resolve links relative to the index file. Verify every path and any heading anchor you create. Avoid machine-specific absolute paths and symlinks outside the repository.
Reference authority:
- Follow governing instructions and the user's explicit current task.
- Use the Phase 1 plan for scope; API and database documents for their contracts; implementation guide for workflows.
- Treat the broader architecture as context, not permission to implement deferred features.
- Treat existing code as implementation evidence, not automatic proof that conflicting behavior is correct.
- Surface material contradictions; do not silently rewrite policy or expand scope. Continue unrelated work when a decision blocks only one part.
## 3. Keep shared project rules in AGENTS.md
Preserve existing instructions. Add a concise section only where the rules belong; avoid duplicating nested instructions. Include these current invariants:
- Deliver within Phase 1 scope using the existing modular backend and separate ingestion worker.
- Each upload creates an independent document; content is not overwritten in place.
- Do not introduce `document_versions`, `version_id` or `version_no` for document content.
- Chunks and ingestion jobs reference `document_id`; answer sources reference `document_id` and `chunk_id`.
- Retry processes the same eligible failed document; it does not create a new document identity.
- Only authorized, ready, active and undeleted documents are searchable.
- The backend derives trusted identity and search scope. Model arguments cannot override them.
- Text and Live use the same backend search implementation.
- Keep persistent provider secrets server-side.
- Follow documented request deduplication, worker claim/lease rules and context invalidation behavior where relevant.
- Keep API/schema documentation aligned with intentional contract changes. Never alter contracts just to excuse a bug.
- Avoid unnecessary dependencies, services, abstractions and unrelated refactoring.
Configuration revisions and embedding profile metadata are not document-content versioning and must not be removed accidentally.
Link to the shared reference map instead of embedding all requirements into AGENTS.md. Add verified project commands only; label commands not yet runnable rather than guessing that they work.
## 4. Skill structure and authoring requirements
For each skill create a `SKILL.md` with valid YAML frontmatter:
- `name`: exactly the requested skill name.
- `description`: concise purpose and specific triggering situations, including when not to use it if needed to prevent over-triggering.
Follow the actual agent's supported metadata schema. Add UI metadata only if supported and useful; validate it using the available authoring guidance. Never invent metadata keys.
Keep each skill procedural, specific and concise; aim for approximately 100–200 lines or less. Include relevant references, the workflow, verification requirements, stopping conditions and an output format. Do not add filler README files, duplicate manuals, unused resources or scripts that only wrap a single ordinary command.
Skills must not recursively invoke one another in a loop. Implementation includes its necessary validation; test-writing develops tests; review is read-only unless fixing is explicitly requested.
### Skill A: implement-feature
Trigger: implement or modify a scoped application capability in this repository.
Workflow:
1. Identify requested behavior, acceptance criteria and relevant references.
2. Inspect the existing implementation, test patterns and affected integration boundaries.
3. State a short implementation plan proportional to the task. Continue without routine permission requests.
4. Implement the smallest complete change across the necessary API, application, persistence/provider and UI boundaries. Do not force edits into layers the task does not affect.
5. Handle relevant permissions, state transitions, errors and concurrency/idempotency requirements.
6. Preserve provider-neutral application boundaries and shared retrieval.
7. Add meaningful tests for changed behavior and regressions. Reuse existing fixtures.
8. Run relevant checks using repository commands; update affected docs for intentional contract changes.
9. Report changed behavior, files, actual checks and remaining limitations.
If the task explicitly changes a contract, update its documentation and consumers coherently. If a product decision is genuinely missing, isolate it and request that decision without inventing it. Do not ask for permission for ordinary reversible implementation choices.
### Skill B: write-tests
Trigger: create, extend or improve tests for an identified behavior, regression or release risk.
Workflow:
1. Read the intended behavior and existing tests before choosing assertions.
2. Select the smallest useful test level: unit, integration, contract or end-to-end.
3. Cover relevant success, failure and boundary cases; avoid mechanically enumerating irrelevant combinations.
4. Use the repository's runner, fixtures and naming conventions.
5. Mock external providers at the adapter/transport boundary where appropriate. Do not mock the behavior under test or treat a fake database as proof of PostgreSQL constraints.
6. Use an isolated PostgreSQL/pgvector test environment when testing database-specific transactions, vector queries or constraints; never run destructive fixtures against production.
7. Keep ordinary automated tests deterministic and network-free by default. Control clocks and retries through injected dependencies where the code supports them.
8. Run the targeted tests and explain failures. Do not weaken assertions, skip regressions or change expected behavior merely to make the suite pass.
9. Distinguish a product bug, a test defect and an unavailable environment. Report an exposed product bug without silently expanding a tests-only task into a production fix.
Choose relevant cases from:
- Authorized upload, invalid files, failed extraction and no publication of partial chunks.
- Duplicate upload/chat request replay and changed-payload conflicts.
- Active/ready/deleted filtering and forged scope arguments.
- Worker lease expiry, stale claim rejection and duplicate-free publication.
- Turn state, conversation ownership, interruption and source mapping.
- Document deactivation and stale context handling.
- Live tool dispatch using shared retrieval, duplicate tool events and close/failure state.
Add a clearly separate optional section: **Real-provider RAG evaluation**.
Use it when real-output quality is requested or release readiness requires it and the environment/data access is authorized. Prepare a small corpus and questions with expected evidence, including paraphrases, missing knowledge and follow-ups. Check extraction, retrieved evidence, answer support and source identity separately. Test text and voice separately. Prefer factual assertions over exact full-answer wording. Label any model-based judging and human checks; do not present them as deterministic proof.
Use bounded requests, protect sensitive data and honor existing cost/network authorization. If credentials, corpus, a runnable service or required voice interaction are unavailable, report the evaluation as not run. Never fabricate metrics or claim mock results establish real-model quality. Keep this optional evaluation out of the default unit-test run.
### Skill C: review-change
Trigger: review a diff, implementation or proposed merge for defects and contract violations.
Workflow:
1. Resolve the requested review scope and base. Inspect the diff and relevant surrounding code/tests/docs.
2. Check correctness, authorization, contract alignment, data integrity, failure behavior and relevant concurrency/retry issues.
3. Pay particular attention to inactive-document leaks, stale context, duplicate provider work, invalid citations and application/provider boundary mistakes where those areas changed.
4. Use targeted read-only inspection or checks to validate suspected findings. Do not execute production writes.
5. Prioritize actionable defects over stylistic preferences; avoid speculative findings without a concrete failure path.
6. Report each finding with severity, actual file and location, trigger, impact and recommended correction direction.
7. If no defects are found, say so with the review scope and untested risks. Do not invent findings to populate the report.
Default to review-only. Do not modify code unless the user asks for fixes. Do not report unimplemented roadmap features as bugs when the Phase 1 plan defers them.
## 5. Validate the created skills
Validate in the repository where the skills will be used:
- Frontmatter parses; names match; descriptions distinguish the three workflows.
- All referenced files and heading anchors resolve from their actual locations.
- No scratch paths, fabricated commands, stale document-version requirements or placeholder links remain.
- Existing instructions and unrelated modifications are preserved.
- The three skills route these representative requests correctly:
- “Implement document upload and processing status.” → implement-feature.
- “Add regression tests for repeated chat submissions.” → write-tests.
- “Review this change for inactive-document exposure.” → review-change.
- “Evaluate these real questions before the demo.” → optional RAG evaluation within write-tests, with prerequisites checked.
- Review hypothetical behavior for missing docs, unavailable providers and a discovered product bug. Do not implement those product scenarios as part of skill creation.
Use the agent's available skill validator when present. If unavailable, validate YAML and links using existing tools and state the limitation. Do not install an unrelated toolchain merely for validation. If you add a reusable validation script, actually run it and verify its output.
Do not commit, push, deploy or install skills globally unless governing repository instructions or the user's authorization require it. Creating files is not evidence that the agent has discovered them: verify discovery if possible, otherwise explain how to invoke the files explicitly and label automatic discovery unverified.
## 6. Final report
Return:
1. The created/updated file tree and actual paths.
2. A brief explanation of each skill and one invocation example using this agent's supported syntax.
3. The actual project-document reference mapping.
4. Validation performed and results.
5. Any missing documents, unresolved decisions or discovery limitations.
Keep the final report concise. Do the file work before returning it.
+179
View File
@@ -0,0 +1,179 @@
# Phase 1 agent reference map
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Inventory verified on 2026-10-05; recheck it as implementation grows. Latest evidence: 163 combined tests passed, including 48 real PostgreSQL cases in both supported pgvector environments. The final acceptance section below supersedes earlier unavailable-database reports.
## Authority and document resolution
Follow governing instructions and the user's current task. The plan sets Phase 1 scope; API and database specifications set contracts; the implementation guide sets workflows. The Persian report explains scenarios. Architecture supplies context only. Code and README describe the prototype, not approval to override the Phase 1 contracts.
The six requested unsuffixed filenames do not exist. The only corresponding copies are the ` (1).md` files linked below. Content confirms the 2026-10-05 simplified design: independent immutable uploads, direct document references, no content versions, and retained technical revisions. English specifications identify revision 1.1 and proposed status; the Persian report explains the same lifecycle in sections 9-11. No competing copies were found. Preserve their names and untracked status unless the user requests otherwise.
Section numbers and heading names below are verified against these files; no inferred fragment anchors are used.
| Requested document | Actual file | Authority and sections to consult |
| --- | --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](<RAG-AI-Phase1-Delivery-Plan (1).md>) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Updates; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](<RAG-Phase1-Implementation-Guide (1).md>) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
| `RAG-Phase1-API-Catalog.md` | [API catalog](<RAG-Phase1-API-Catalog (1).md>) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and text; 7. Voice contract — provisional signaling, fixed ownership rules; 9. Error envelope and mapping |
| `RAG-Phase1-Database-Design.md` | [Database design](<RAG-Phase1-Database-Design (1).md>) | Schema/constraints/transactions: 4. Knowledge tables; 5. Conversation and evidence tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
| `RAG-Phase1-Scenario-Report-FA.md` | [Persian scenarios](<RAG-Phase1-Scenario-Report-FA (1).md>) | Business examples: sections 4-8 (upload, text, missing knowledge, duplicate submission, voice), 9-11 (replacement, revisions, worker crash), 13 (delete), 15 (acceptance), 16 (open decisions) |
| `RAG-AI-Architecture.md` | [Architecture](<RAG-AI-Architecture (1).md>) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Migration from the Existing Repository; 19. Open Decisions and Owners |
## Reading by workflow
- `implement-feature`: Plan 3/8/9 for boundaries and acceptance; guide 3 and the affected workflow in 5-10; API endpoint and error sections; database affected tables plus 7/8. Use Persian scenarios to clarify observable behavior and architecture 17 for migration context.
- `write-tests`: Plan 9/10; guide 12 and affected workflow; API replay/error/permission rules; database 7/9 for races and constraints; Persian scenarios 4-11/13/15 for concrete cases. Consult architecture only for relevant context.
- `review-change`: Plan 3/9 to avoid roadmap findings; guide 5-10 for changed boundaries; exact API contracts and database 7/8/9. Use Persian scenarios for trigger/impact and architecture dependency rules only where relevant.
## Actual implementation and commands
| Existing path | Observed responsibility |
| --- | --- |
| [Application entry point](../../app/main.py) | FastAPI routes, CORS, static health response |
| [API directory](../../app/api/v1/) and [schemas](../../app/schemas/) | Prototype chat transport and DTOs |
| [Services](../../app/services/) | Document loading/chunking and Chroma/FastEmbed retrieval |
| [Agent](../../app/services/agent/) and [tools](../../app/services/tools/) | LangGraph text loop, in-memory history, retrieval tool |
| [Configuration](../../app/core/config.py) and [environment example](../../.env.example) | Settings and provider configuration |
| [README](../../README.md) | Prototype startup instructions; not Phase 1 implementation evidence |
| [Document processor](../../app/services/doc_processor.py) | Recursively ingests Markdown under this documentation directory |
Ingestion foundation now exists: [manifest](../../pyproject.toml), [settings/types/ports](../../app/modules/documents/), [database access](../../app/infrastructure/database.py), [initial migration](../../migrations/versions/0001_ingestion_foundation.py), [Alembic environment](../../migrations/env.py), [trusted bootstrap](../../app/bootstrap.py), and [tests](../../tests/). Read [foundation setup](../../docs/ingestion-foundation-setup.md) before migration/bootstrap/database testing. Only the seven requested foundation tables are implemented; no auth sessions, conversation or Live tables. There is still no lockfile, CI, frontend, ingestion intake CLI, concrete FileStore/embedding adapter or worker. Redis/broker and a new orchestration framework are unnecessary.
| Command from repository root | Verification status |
| --- | --- |
| `git status --short` | Executed for working-tree inspection |
| `git diff --check` | Executed for tracked whitespace validation; untracked new files need separate inspection |
| `rg --files --hidden -g '!.git/**'` | Executed for file discovery |
| `uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload` | README example and entry point verified statically; runtime not verified |
| `python -m app.services.agent.exec` | README example and CLI entry point verified statically; provider smoke harness, not automated regression tests; not run |
Runtime prerequisites remain unverified: dependencies, configured credentials, approved corpus, writable vector storage, and provider/model access. Importing the application creates settings/retrieval singletons and can load embeddings/index documents. Do not use imports as a supposedly network-free smoke test. README installation now uses pyproject.toml extras. Foundation imports are independent of those prototype prerequisites. Verified foundation commands are listed below; no worker is implemented; see the latest local database acceptance evidence below.
## Gaps and decisions
- Required document content is available under suffixed names; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it.
- Material implementation gap: Chroma/local Markdown/in-memory history and the prototype chat DTO differ from the Phase 1 PostgreSQL/pgvector, uploaded documents, authenticated durable turns, and separate worker target. README production-readiness claims are not acceptance evidence. Skill creation does not implement that migration.
- Open decisions: approved formats/size limits, model IDs and vector dimension, live provider/signaling/control proof, hosting/connectivity, account/session/retention policy, quality threshold, and delivery date. See guide 13 and plan 2. Do not turn proposals into recorded approvals.
- Live SDP signaling is provisional; resolve compatibility before freezing frontend contracts. Broader architecture features must not override Phase 1 exclusions such as model selectors and guaranteed voice transcripts.
- Documentation shares the prototype ingestion directory, so this index may enter its Markdown corpus. Use a deliberately isolated, approved corpus for real-provider evaluation and report this limitation; do not silently change product ingestion during skill authoring.
## Skill discovery
Skills are stored at repository-root `.agents/skills/<name>/SKILL.md`, the repository location documented in [official Codex skill guidance](https://learn.chatgpt.com/docs/build-skills). No equivalent project-owned skills or prior AGENTS.md files were found.
Use `$implement-feature`, `$write-tests`, or `$review-change` in Codex. Automatic discovery was verified on 2026-10-05: all three repository skills appeared in this session's available-skills catalog after creation. In another client/session where selection is unavailable, explicitly ask Codex to read the relevant SKILL.md by repository path and follow it. No global installation or optional UI metadata is required.
## Ingestion foundation commands and evidence (2026-10-05)
- python -m venv .venv and .venv/Scripts/python -m pip install -e ".[test]": executed successfully with Python 3.14.6.
- .venv/Scripts/python -m pytest -m "not postgres": 13 passed; no real providers.
- .venv/Scripts/alembic history: initial revision discovered successfully.
- .venv/Scripts/python -m pytest -m postgres: requires TEST_DATABASE_URL targeting a dedicated database ending in _test. PostgreSQL tests use disposable schemas and real independent connections. Ordinary-suite missing configuration skips them with a non-acceptance reason; add --require-postgres to the acceptance command so missing configuration fails.
- .venv/Scripts/alembic upgrade head: operator command, not yet executed against PostgreSQL. Requires explicit INGEST embedding identity/dimension; initial vector(D) and profile are frozen in the database. Equal dimensions with a different model fail compatibility.
- .venv/Scripts/python -m app.bootstrap: trusted initial organization/admin command; requires explicit display/settings arguments and an interactive password prompt or --password-stdin. No HTTP authentication is implemented.
- docker info --format '{{.ServerVersion}}': failed both inside and outside the sandbox because Docker Desktop WSL bootstrap could not start. PostgreSQL/pgvector acceptance is unverified in this environment.
- git diff --check: tracked whitespace validation only; newly added files also need separate inspection.
The ingestion pipeline plan remains an untracked specification; its later phases are not implemented by foundation work. All seven tables use the database contract's direct document identities, scoped FKs, state constraints and uniqueness. The initial revision already exists and must be treated as potentially applied. Repair work does not assume it is unapplied: preserve it byte-for-byte and use forward revisions for any future persisted changes. Processing-profile snapshots contain character units and embedding identity without secrets. Compatibility and native vector registration are explicit functions; importing ingestion modules opens no database/provider connection or corpus.
- Final .venv/Scripts/python -m pytest: 13 passed, 31 PostgreSQL tests skipped because TEST_DATABASE_URL was absent. .venv/Scripts/python -m pip check: no broken requirements. Database migration/constraint/concurrency/bootstrap runtime remains unverified.
## Phase 1 repair evidence (2026-10-05)
Scope is foundation repair only. No intake, worker, HTTP authentication,
conversation/Live tables or chat behavior was added.
- Settings reject credential-bearing or unsupported endpoint URLs, preserving supported endpoint identity. Error strings and structured validation errors omit raw input values. Credentials remain separate SecretStr values. Every floating-point duration rejects NaN and both infinities in direct and environment construction.
- [PostgreSQL fixture support](../../tests/support/postgres.py) keeps public out of disposable search paths. pgvector resides in the dedicated test_vector namespace; an existing extension elsewhere is refused, not relocated. Alembic explicitly scopes version_table_schema. Every foundation relation is checked before test connections are used and before migration/downgrade. [Isolation regressions](../../tests/integration/test_isolation.py) create their own temporary database to prove public tables/data survive setup, mutation, downgrade/upgrade and teardown.
- Manifest support remains pgvector >=0.3.6,<1. Vector acceptance handles both NumPy (0.3.6) and Vector (0.5.0) results. The minimum was installed in .venv/minimum; package imports/provider-free checks are not real database adaptation proof.
- Initial revision SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567. No revision file or persisted schema was changed; no forward data migration was needed for these code/config/test repairs. Historical URL-secret cleanup is unresolved if an older deployment actually persisted such inputs.
- Provider-free commands .venv/Scripts/python -m pytest -m "not postgres" and .venv/minimum/Scripts/python -m pytest -m "not postgres": 88 passed in each environment (pgvector 0.5.0 and 0.3.6).
- Explicit PostgreSQL acceptance commands in both environments, -m postgres --require-postgres --tb=no, fail fixture setup when TEST_DATABASE_URL is absent. Docker info still fails inside and outside the sandbox with DockerDesktop/Wsl/ExecError and WSL bootstrap exit 0x40010004. No PostgreSQL migration/constraint/isolation/concurrency/vector evidence is claimed.
- README now agrees with requires-python >=3.11. Pipeline inventory and AGENTS.md point to the actual manifest, migrations and tests.
Final repair checks:
- .venv/Scripts/python -m pytest: 88 passed, 48 skipped. Skips are PostgreSQL cases with missing TEST_DATABASE_URL and do not count as acceptance.
- .venv/Scripts/python -m pytest -m postgres --require-postgres --tb=no -q and the same command using .venv/minimum/Scripts/python: 48 setup errors in each environment, zero PostgreSQL passes/skips; database configuration is absent. An earlier run before constraint coverage expansion had 34 setup errors.
- .venv/Scripts/python -m pip check and .venv/minimum/Scripts/python -m pip check: no broken requirements.
- .venv/Scripts/alembic history: unchanged initial revision discovered.
- git diff --check: passed; new-file syntax/whitespace inspection is separate.
## Final foundation acceptance evidence (2026-10-05)
Remaining settings defects were reproduced first: malformed port values leaked
dummy secrets into Pydantic output/context, malformed URL structure escaped as
SQLAlchemy ArgumentError, and valid ambient limit overrides broke baseline tests.
[Settings](../../app/modules/documents/settings.py) now converts parser failures
to a generic validation error outside the parser handler and raises sanitized
ValidationError outside its handler, retaining no raw parser/input exception
chain. [Regressions](../../tests/unit/test_database_urls.py) inspect str/repr/json,
errors and context/cause, exercise valid Psycopg URLs and rerun the ordinary suite
with external overrides. [Fixtures](../../tests/conftest.py) clear ambient
INGEST_* variables per test without changing production loading or TEST_DATABASE_URL.
Docker became available. A dedicated temporary PostgreSQL/pgvector container,
rag-foundation-acceptance-7e382b6f, ran on localhost:54918 with the dedicated
rag_foundation_test database. The server was PostgreSQL 16.15; pgvector extension
0.8.7. Python adapter versions were 0.5.0 and minimum 0.3.6.
[Prerequisite check](../../tests/postgres_prerequisites.py) verifies connectivity,
dedicated database configuration, CREATE/DROP DATABASE and extension privileges,
and the safe extension namespace before the suite. Both environments passed it.
No existing deployment/database or metadata was changed.
Final commands/results:
- .venv/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
- .venv/minimum/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected.
- .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected.
- .venv/Scripts/python -m pytest --require-postgres -q: 163 passed.
- .venv/Scripts/python -m tests.postgres_prerequisites and .venv/minimum/Scripts/python -m tests.postgres_prerequisites: passed.
- Both environments' python -m pip check: no broken requirements.
- .venv/Scripts/alembic history: initial revision discovered.
All final test runs had zero failures, setup errors or skips.
First real-DB run: 46 passed/2 failed in 0.5.0; first 0.3.6 run after initial test
repairs: 47 passed/1 failed. Repaired test SQL JSON binding, replaced
search-path-dependent deparsed constraint comparisons with complete stable
catalog comparisons, and used 0.3.6's supported NumPy native input. Assertions
continue to prove numeric vector values and unchanged public relations/data.
Public preservation, scoped downgrade/upgrade, constraints, profile checks and
concurrent bootstrap now have real PostgreSQL evidence.
The initial revision remains byte-for-byte unchanged with SHA-256
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
No persisted schema change or forward migration was needed. Historical credential
remediation is conditional on identifying an affected deployment and explicit
authorization; see setup instructions for rotation and targeted forward metadata
migration while preserving agreed embedding identity. No remediation is claimed.
Remaining limits: local acceptance does not prove production deployment,
real-provider compatibility/quality or any later ingestion phase. The standalone
operator migration/bootstrap commands remain separately documented; the suite
executes the real Alembic migration path and bootstrap database function.
Final cleanup/inspection: the dedicated database reported zero leftover disposable
schemas, zero generated foundation_*_test databases and zero public application
tables. The temporary acceptance container and its anonymous test volume were
removed; no other container was touched. git diff --check passed, syntax and
new-file whitespace checks passed, and the original migration hash was preserved.
Test organization: tests/unit contains provider-free configuration, endpoint,
database URL, import and test-environment cases. tests/integration contains
PostgreSQL migrations/profile, constraints, concurrency, vector and isolation
cases, with database-only fixtures and a directory-wide postgres marker.
tests/support contains reusable PostgreSQL and row helpers; tests never import
helpers from another test module. Shared settings fixtures remain in root
conftest.py. The tests.postgres_prerequisites command remains unchanged.
Organization validation: .venv/Scripts/python -m pytest --require-postgres -q:
163 passed. .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres
-q: 48 passed, 115 deselected. Both prerequisite commands passed on a temporary
dedicated PostgreSQL/pgvector container. Final runs had no failures/errors/skips.
The first moved-helper run exposed a repository-root path error, which was fixed
before these final checks. Initial migration hash, test syntax/whitespace and
git diff --check passed. See [test layout](../../tests/README.md).