Files
rag-technical-docs-assistant/data/documents/RAG-AI-Phase1-Delivery-Plan (1).md
T
amirhosein mazaheri baf58da562 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.
2026-10-05 16:38:28 +03:30

19 KiB
Raw Blame History

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.

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.

  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.