# 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.