docs: restructure documentation hierarchy and update agent reference map
- Organize architecture, specifications, plans, and guides into dedicated subdirectories under docs/ - Remove legacy and duplicate documents from data/documents/ - Update AGENTS.md, README.md, and agent skills to target canonical docs paths
This commit is contained in:
@@ -5,7 +5,7 @@ description: "Implement or modify a scoped application capability in this reposi
|
|||||||
|
|
||||||
# Implement a Phase 1 feature
|
# Implement a Phase 1 feature
|
||||||
|
|
||||||
Read applicable AGENTS.md instructions and the [shared reference map](../../../data/documents/agent-reference-map.md). Use its implement-feature reading route and current implementation inventory; planned modules are not proof of existing code.
|
Read applicable AGENTS.md instructions and the [shared reference map](../../../docs/agent-reference-map.md). Use its implement-feature reading route and current implementation inventory; planned modules are not proof of existing code.
|
||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description: "Review a repository diff, implementation, or proposed merge for ac
|
|||||||
|
|
||||||
# Review a Phase 1 change
|
# Review a Phase 1 change
|
||||||
|
|
||||||
Read applicable AGENTS.md instructions and the [shared reference map](../../../data/documents/agent-reference-map.md). Follow its review-change reading route, including Phase 1 exclusions and the distinction between the prototype and planned design.
|
Read applicable AGENTS.md instructions and the [shared reference map](../../../docs/agent-reference-map.md). Follow its review-change reading route, including Phase 1 exclusions and the distinction between the prototype and planned design.
|
||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ description: "Create or improve tests for repository behavior, regressions, or r
|
|||||||
|
|
||||||
# Test Phase 1 behavior
|
# Test Phase 1 behavior
|
||||||
|
|
||||||
Read applicable AGENTS.md instructions and the [shared reference map](../../../data/documents/agent-reference-map.md). Follow its write-tests reading route. The initial repository has no automated test runner or fixtures; inspect current files before selecting a harness or reporting commands.
|
Read applicable AGENTS.md instructions and the [shared reference map](../../../docs/agent-reference-map.md). Follow its write-tests reading route. The initial repository has no automated test runner or fixtures; inspect current files before selecting a harness or reporting commands.
|
||||||
|
|
||||||
## Automated test workflow
|
## Automated test workflow
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
## Phase 1 development
|
## Phase 1 development
|
||||||
|
|
||||||
Use the [shared reference map](data/documents/agent-reference-map.md) for document authority, current source locations, commands, and unresolved decisions. Read applicable nested instructions before editing.
|
Use the [shared reference map](docs/agent-reference-map.md) for document authority, current source locations, commands, and unresolved decisions. Read applicable nested instructions before editing.
|
||||||
|
|
||||||
- Deliver Phase 1 with a modular FastAPI backend and a separate ingestion worker from the same codebase. The current prototype does not yet implement that target.
|
- Deliver Phase 1 with a modular FastAPI backend and a separate ingestion worker from the same codebase. The current prototype does not yet implement that target.
|
||||||
- Each upload creates an independent document; never overwrite its original content in place. Do not introduce `document_versions`, `version_id`, or `version_no` for document content.
|
- Each upload creates an independent document; never overwrite its original content in place. Do not introduce `document_versions`, `version_id`, or `version_no` for document content.
|
||||||
@@ -20,4 +20,4 @@ The Phase 1 plan governs scope, API/database documents govern their contracts, a
|
|||||||
|
|
||||||
Repository skills live in `.agents/skills/`: `implement-feature`, `write-tests`, and `review-change`. Implementation includes necessary validation; tests-only work reports product defects without silently fixing them; review is read-only unless fixes are requested. Do not recursively dispatch between skills.
|
Repository skills live in `.agents/skills/`: `implement-feature`, `write-tests`, and `review-change`. Implementation includes necessary validation; tests-only work reports product defects without silently fixing them; review is read-only unless fixes are requested. Do not recursively dispatch between skills.
|
||||||
|
|
||||||
Verified inspection commands from the repository root: `git status --short`, `git diff --check`, and `rg --files --hidden -g '!.git/**'`. The dependency manifest is pyproject.toml; provider-free checks use .venv/Scripts/python -m pytest -m "not postgres". PostgreSQL acceptance uses .venv/Scripts/python -m pytest -m postgres --require-postgres with an isolated TEST_DATABASE_URL. Missing configuration must fail acceptance; ordinary-suite skips do not prove database behavior. No build/lint pipeline exists. See the reference map and docs/ingestion-foundation-setup.md for setup and actual results. Treat applied revisions as immutable.
|
Verified inspection commands from the repository root: `git status --short`, `git diff --check`, and `rg --files --hidden -g '!.git/**'`. The dependency manifest is pyproject.toml; provider-free checks use .venv/Scripts/python -m pytest -m "not postgres". PostgreSQL acceptance uses .venv/Scripts/python -m pytest -m postgres --require-postgres with an isolated TEST_DATABASE_URL. Missing configuration must fail acceptance; ordinary-suite skips do not prove database behavior. No build/lint pipeline exists. See the reference map and docs/guides/ingestion-foundation-setup.md for setup and actual results. Treat applied revisions as immutable.
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
For the new ingestion foundation (independent of prototype chat), see [setup and validation](docs/ingestion-foundation-setup.md). Only ingestion phase 1 is implemented; database acceptance must be verified on PostgreSQL/pgvector.
|
Phase 6 adds [integration validation and operator handoff](docs/guides/ingestion-operator-handoff.md), redacted worker heartbeat/stage diagnostics and an opt-in real-provider smoke command. The existing chat retriever still uses Chroma/FastEmbed and does not search uploaded PostgreSQL chunks. Scoped pgvector search and authorized knowledge selection are the next milestone; published documents remain inactive.
|
||||||
|
|
||||||
|
Current target: the English [LangChain Live document MVP](docs/specifications/RAG-AI-Phase1-Delivery-Plan.md), with new browser uploads and direct Persian speech-to-speech. Ingestion Phases 1-4 plus the [Phase 5 worker, publication and retry](docs/guides/worker-orchestration.md) are implemented. Durable review decisions/resume and factual FAQ inclusion are implemented behind trusted backend services. Scoped uploaded-document retrieval, HTTP identity/upload/review transport, Live and UI remain planned. See [documentation and implementation order](docs/README.md) and [recorded setup/validation](docs/guides/ingestion-foundation-setup.md). The four sample files are acceptance examples, not the accepted corpus. The startup/API details below describe the legacy prototype.
|
||||||
|
|
||||||
# 🤖 Technical Documentation Assistant (RAG Agent)
|
# 🤖 Technical Documentation Assistant (RAG Agent)
|
||||||
|
|
||||||
@@ -10,7 +12,7 @@ For the new ingestion foundation (independent of prototype chat), see [setup and
|
|||||||
[](https://www.python.org/)
|
[](https://www.python.org/)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
|
|
||||||
An intelligent, production-ready **Retrieval-Augmented Generation (RAG)** assistant built with **FastAPI**, **LangGraph**, **LangChain**, and **ChromaDB**. The assistant is specialized in indexing, searching, and reasoning over technical documentation to provide developers with accurate, source-grounded answers and production-ready code examples with zero hallucinations.
|
A **Retrieval-Augmented Generation (RAG)** prototype built with **FastAPI**, **LangGraph**, **LangChain**, and **ChromaDB**. The sections below document that existing Markdown/text prototype. The target Live MVP will connect the separate PostgreSQL/pgvector ingestion pipeline through shared LangChain retrieval; production readiness and zero-hallucination behavior are not established.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,231 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -1,266 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -1,152 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -1,643 +0,0 @@
|
|||||||
# Docker Documentation Style Guide
|
|
||||||
|
|
||||||
This guide consolidates voice, grammar, formatting, and terminology
|
|
||||||
standards for Docker documentation. Follow these guidelines to create
|
|
||||||
clear, consistent, and helpful content. For instructions on how to use
|
|
||||||
components, shortcodes, and other features, see [COMPONENTS.md](COMPONENTS.md).
|
|
||||||
|
|
||||||
## Voice and tone
|
|
||||||
|
|
||||||
Write like a knowledgeable colleague explaining something useful. We're
|
|
||||||
developers writing for developers.
|
|
||||||
|
|
||||||
### Core principles: The 4Cs
|
|
||||||
|
|
||||||
1. **Correct** - Information is accurate
|
|
||||||
2. **Concise** - Succinct without unnecessary words
|
|
||||||
3. **Complete** - Includes enough detail to complete the task
|
|
||||||
4. **Clear** - Easy to understand
|
|
||||||
|
|
||||||
### Writing approach
|
|
||||||
|
|
||||||
- **Be honest.** Give all the facts. Don't use misdirection or
|
|
||||||
ambiguous statements.
|
|
||||||
- **Be concise.** Don't bulk up communication with fluffy words or
|
|
||||||
complex metaphors. Get to the point.
|
|
||||||
- **Be relaxed.** Casual but not lazy, smart but not arrogant, focused
|
|
||||||
but not cold. Be welcoming and warm.
|
|
||||||
- **Be inclusive.** Every person is part of our community, regardless
|
|
||||||
of experience level.
|
|
||||||
|
|
||||||
### Tone guidelines
|
|
||||||
|
|
||||||
- Use a natural, friendly, and respectful tone
|
|
||||||
- Use contractions to sound conversational (it's, you're, don't)
|
|
||||||
- Avoid overdoing politeness - skip "please" in most technical documentation
|
|
||||||
- Be clear over comical
|
|
||||||
- Use positive language - emphasize what users can do, not what they can't
|
|
||||||
|
|
||||||
**Positive language example:**
|
|
||||||
|
|
||||||
Instead of: "Features such as Single Sign-on (SSO), Image Access
|
|
||||||
Management, Registry Access Management are not available in Docker Team
|
|
||||||
subscription."
|
|
||||||
|
|
||||||
Use: "Features such as Single Sign-on (SSO), Image Access Management,
|
|
||||||
Registry Access Management are available in Docker Business subscription."
|
|
||||||
|
|
||||||
### Avoiding marketing language
|
|
||||||
|
|
||||||
Documentation should be factual and direct, not promotional.
|
|
||||||
|
|
||||||
**Avoid hedge words** that overstate ease or capability:
|
|
||||||
|
|
||||||
- ❌ simply, just, easily, seamlessly (implies ease when it may not be
|
|
||||||
easy)
|
|
||||||
- ❌ robust, powerful (marketing language)
|
|
||||||
- ✅ Instead: describe what it actually does
|
|
||||||
|
|
||||||
**Avoid excessive enthusiasm:**
|
|
||||||
|
|
||||||
- ❌ "powerful feature", "game-changing", "revolutionary", "amazing"
|
|
||||||
- ✅ Instead: describe the feature and its benefits factually
|
|
||||||
|
|
||||||
**Avoid meta-commentary:**
|
|
||||||
|
|
||||||
These phrases add no value - state the fact directly:
|
|
||||||
|
|
||||||
- ❌ "It's worth noting that..."
|
|
||||||
- ❌ "It's important to understand that..."
|
|
||||||
- ❌ "Keep in mind that..."
|
|
||||||
- ✅ Instead: state the information directly
|
|
||||||
|
|
||||||
### Voice and perspective
|
|
||||||
|
|
||||||
- **Use "you" not "we"**: Focus on what the user can do, not what "we"
|
|
||||||
created
|
|
||||||
- ❌ "We provide a feature that helps you deploy"
|
|
||||||
- ✅ "Deploy your applications with..."
|
|
||||||
- **Avoid "please"**: Don't use in normal explanations or "please note"
|
|
||||||
phrases
|
|
||||||
- **Write timelessly**: Avoid "currently" or "as of this writing" - the
|
|
||||||
documentation describes the product as it is today
|
|
||||||
|
|
||||||
### Explain technical behavior
|
|
||||||
|
|
||||||
Explain behavior from the reader's perspective. Lead with the observable
|
|
||||||
outcome, then add the implementation details needed to explain it.
|
|
||||||
|
|
||||||
Prefer:
|
|
||||||
|
|
||||||
> Changes made by the agent stay inside the sandbox until you fetch them. The
|
|
||||||
> agent works in a separate Git clone inside the sandbox.
|
|
||||||
|
|
||||||
Avoid:
|
|
||||||
|
|
||||||
> A session that works directly in the sandbox clone still can't modify your
|
|
||||||
> host repository.
|
|
||||||
|
|
||||||
The preferred version tells readers where changes happen and when they become
|
|
||||||
visible. The second version makes readers reconstruct the relationship between
|
|
||||||
the session, sandbox clone, and host repository.
|
|
||||||
|
|
||||||
Separate guarantees from variable behavior. Don't present behavior controlled
|
|
||||||
by another tool as a product default or guarantee. When behavior varies,
|
|
||||||
structure the explanation in this order:
|
|
||||||
|
|
||||||
1. State what always happens
|
|
||||||
2. State what the product doesn't control
|
|
||||||
3. Tell the reader what to do
|
|
||||||
|
|
||||||
For example:
|
|
||||||
|
|
||||||
> The `--clone` flag creates the clone, but it doesn't separate one task from
|
|
||||||
> another. To keep parallel tasks isolated, instruct your agent tool to create
|
|
||||||
> a separate branch or worktree for each task.
|
|
||||||
|
|
||||||
Avoid chains of qualifications such as "may," "can," and "depends" that leave
|
|
||||||
the reader without a conclusion. Keep qualifiers that are needed for accuracy.
|
|
||||||
State what controls the behavior and what the reader should do.
|
|
||||||
|
|
||||||
### Scope preservation
|
|
||||||
|
|
||||||
When updating existing documentation, resist the urge to expand
|
|
||||||
unnecessarily. Users value brevity.
|
|
||||||
|
|
||||||
**Understand the current document:**
|
|
||||||
Read it fully to grasp its scope, length, and character. Is it a minimal
|
|
||||||
how-to or a comprehensive reference?
|
|
||||||
|
|
||||||
**Match the existing character:**
|
|
||||||
If the document is brief and direct (90 lines), keep it that way. Don't
|
|
||||||
transform a focused guide into an exhaustive tutorial.
|
|
||||||
|
|
||||||
**Add only what's genuinely missing:**
|
|
||||||
Fill gaps, don't elaborate. If the document already covers a topic
|
|
||||||
adequately, don't expand it.
|
|
||||||
|
|
||||||
**Value brevity:**
|
|
||||||
Say what needs to be said, then stop. Not every topic needs
|
|
||||||
prerequisites, troubleshooting, best practices, and examples sections.
|
|
||||||
|
|
||||||
**Respect the original intent:**
|
|
||||||
The document exists in its current form for a reason. Improve it, don't
|
|
||||||
remake it.
|
|
||||||
|
|
||||||
Good additions fill genuine gaps. Bad additions change the document's
|
|
||||||
character. When in doubt, add less rather than more.
|
|
||||||
|
|
||||||
Include caveats, failure scenarios, and fallback behavior only when they affect
|
|
||||||
a decision or action. Don't turn a clarification into a catalog of edge
|
|
||||||
cases.
|
|
||||||
|
|
||||||
## Grammar and style
|
|
||||||
|
|
||||||
Write in US English with US grammar.
|
|
||||||
|
|
||||||
### Acronyms and initialisms
|
|
||||||
|
|
||||||
- Spell out lesser-known acronyms on first use, then follow with the
|
|
||||||
acronym in parentheses: "single sign-on (SSO)"
|
|
||||||
- Don't spell out common acronyms like URL, HTML, API
|
|
||||||
- Use all caps for file type acronyms: JPEG, PNG
|
|
||||||
- Don't use apostrophes for plurals: URLs not URL's
|
|
||||||
- Avoid introducing acronyms in headings - introduce them in the body
|
|
||||||
text that follows
|
|
||||||
|
|
||||||
### Capitalization
|
|
||||||
|
|
||||||
Use sentence case for almost everything: headings, titles, links, buttons,
|
|
||||||
navigation labels.
|
|
||||||
|
|
||||||
- Capitalize Docker solutions: Docker Desktop, Docker Hub, Docker Extensions
|
|
||||||
- Capitalize job titles only when they immediately precede a name:
|
|
||||||
"Chief Executive Officer Scott Johnston" but "Scott Johnston, chief
|
|
||||||
executive officer"
|
|
||||||
- Follow company capitalization preferences: DISH, bluecrux
|
|
||||||
- Match UI capitalization when referring to specific interface elements
|
|
||||||
|
|
||||||
### Contractions
|
|
||||||
|
|
||||||
Use contractions to maintain a conversational tone, but don't overdo it.
|
|
||||||
|
|
||||||
- Stay consistent - don't switch between "you are" and "you're" in the
|
|
||||||
same content
|
|
||||||
- Avoid negative contractions when possible (can't, don't, won't) -
|
|
||||||
rewrite to be positive
|
|
||||||
- Never contract a noun with a verb (your container is ready, not your
|
|
||||||
container's ready)
|
|
||||||
|
|
||||||
### Clear subjects and modifiers
|
|
||||||
|
|
||||||
Name the actor when a system includes multiple tools or components. Repeat the
|
|
||||||
noun instead of using an ambiguous pronoun. For example, distinguish between
|
|
||||||
what a CLI creates, what an agent edits, and what remains on the host.
|
|
||||||
|
|
||||||
Avoid unclear subjects:
|
|
||||||
|
|
||||||
- ❌ After enabling auto-log-out, your users are logged out
|
|
||||||
- ✅ When you enable auto-log-out, your users are logged out
|
|
||||||
|
|
||||||
### Dates and numbers
|
|
||||||
|
|
||||||
- Use US date format: June 26, 2021 or Jun. 26, 2021
|
|
||||||
- Spell out numbers one through nine, except in units: 4 MB
|
|
||||||
- Use numerals for 10 and above: 10, 625, 1000
|
|
||||||
- Use decimals instead of fractions: 0.5 not ½
|
|
||||||
- For numbers with five or more digits, use spaces instead of commas:
|
|
||||||
14 586 not 14,586
|
|
||||||
- For version numbers: version 4.8.2, v1.0, Docker Hub API v2
|
|
||||||
|
|
||||||
### Punctuation
|
|
||||||
|
|
||||||
- **Commas:** Use the Oxford comma (serial comma) in lists
|
|
||||||
- **Colons:** Use to introduce lists or provide explanations
|
|
||||||
- **Semicolons:** Don't use - write two sentences instead
|
|
||||||
- **Em dashes:** Use sparingly with spaces on either side: "text - like
|
|
||||||
this - text"
|
|
||||||
- **Hyphens:** Use for compound adjectives before nouns:
|
|
||||||
"up-to-date documentation"
|
|
||||||
- **Exclamation marks:** Avoid
|
|
||||||
- **Parentheses:** Avoid in technical documentation - they reduce
|
|
||||||
readability
|
|
||||||
|
|
||||||
### Conciseness and redundant phrases
|
|
||||||
|
|
||||||
Remove unnecessary words to make documentation clearer and more direct.
|
|
||||||
|
|
||||||
Keep an adjective or qualifier only when it changes how readers understand the
|
|
||||||
behavior or complete the task. If removing it doesn't change an outcome,
|
|
||||||
decision, or next step, remove it. Apply the same test to implementation
|
|
||||||
details.
|
|
||||||
|
|
||||||
**Eliminate redundant phrases:**
|
|
||||||
|
|
||||||
- ❌ "in order to" → ✅ "to"
|
|
||||||
- ❌ "serves the purpose of" → ✅ state what it does directly
|
|
||||||
- ❌ "allows you to" → ✅ "lets you" or state what it does
|
|
||||||
- ❌ "enables you to" → ✅ "lets you" or state what it does
|
|
||||||
|
|
||||||
### Bold and italics
|
|
||||||
|
|
||||||
Use bold **only** for UI elements (buttons, menus, field labels). Never
|
|
||||||
use bold for emphasis, product names, or feature names.
|
|
||||||
|
|
||||||
- ✅ Select **Save** (UI button - use bold)
|
|
||||||
- ✅ Docker Hub provides storage (product name - no bold)
|
|
||||||
- ✅ This is important to understand (emphasis - no bold)
|
|
||||||
- ❌ **Docker Desktop** is a tool (product name - don't bold)
|
|
||||||
- ❌ This is **very important** (emphasis - don't bold)
|
|
||||||
- ❌ The **build** command (command name - don't bold)
|
|
||||||
|
|
||||||
**Italics:**
|
|
||||||
Use italics sparingly, as this formatting can be difficult to read in
|
|
||||||
digital experiences. Notable exceptions are titles of articles, blog
|
|
||||||
posts, or specification documents.
|
|
||||||
|
|
||||||
## Formatting
|
|
||||||
|
|
||||||
### Content types and detail balance
|
|
||||||
|
|
||||||
Different content types require different writing approaches. Match your
|
|
||||||
style and detail level to the content type.
|
|
||||||
|
|
||||||
**Getting Started / Tutorials:**
|
|
||||||
|
|
||||||
- Step-by-step instructions
|
|
||||||
- Assume beginner knowledge
|
|
||||||
- Explain _why_ at each step
|
|
||||||
- Include more context and explanation
|
|
||||||
|
|
||||||
**How-to Guides:**
|
|
||||||
|
|
||||||
- Task-focused and goal-oriented
|
|
||||||
- Assume intermediate knowledge
|
|
||||||
- Focus on _how_ efficiently
|
|
||||||
- Less explanation, more direct steps
|
|
||||||
|
|
||||||
**Reference Documentation:**
|
|
||||||
|
|
||||||
- Comprehensive and exhaustive
|
|
||||||
- Assume advanced knowledge
|
|
||||||
- Focus on _what_ precisely
|
|
||||||
- Complete parameter lists and options
|
|
||||||
|
|
||||||
**Concept Explanations:**
|
|
||||||
|
|
||||||
- Educational and foundational
|
|
||||||
- Any skill level
|
|
||||||
- Focus on _understanding_ over doing
|
|
||||||
- Theory before practice
|
|
||||||
|
|
||||||
**Match detail to context:**
|
|
||||||
|
|
||||||
- **First mention** of a concept: explain it
|
|
||||||
- **Subsequent mentions**: link to the explanation or use the term
|
|
||||||
directly if recently explained
|
|
||||||
- **Common knowledge** (to your audience): state it, don't explain it
|
|
||||||
- **Edge cases**: mention them but don't let them dominate the main flow
|
|
||||||
|
|
||||||
### Headings
|
|
||||||
|
|
||||||
- Keep headings short (no more than eight words)
|
|
||||||
- Front-load the most important words
|
|
||||||
- Use descriptive, action-oriented language
|
|
||||||
- Skip leading articles (a, the)
|
|
||||||
- Avoid puns, teasers, and cultural references
|
|
||||||
- Page titles should be action-oriented: "Install Docker Desktop",
|
|
||||||
"Enable SCIM"
|
|
||||||
|
|
||||||
### Page structure and flow
|
|
||||||
|
|
||||||
Every page should answer two questions in the first paragraph:
|
|
||||||
|
|
||||||
1. **What will I learn?** - State what the page covers
|
|
||||||
2. **Why does this matter?** - Explain the benefit or use case
|
|
||||||
|
|
||||||
**Good opening:**
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
Docker Compose Watch automatically updates your running containers when
|
|
||||||
you change code. This eliminates the manual rebuild-restart cycle during
|
|
||||||
development.
|
|
||||||
```
|
|
||||||
|
|
||||||
**Weak opening:**
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
Docker Compose Watch is a powerful feature that enables developers to
|
|
||||||
streamline their development workflow by providing automatic
|
|
||||||
synchronization capabilities.
|
|
||||||
```
|
|
||||||
|
|
||||||
**Transitions and flow:**
|
|
||||||
Connect ideas naturally. Each section should flow logically from the
|
|
||||||
previous one. Save detailed discussions for after showing basic usage -
|
|
||||||
don't front-load complexity.
|
|
||||||
|
|
||||||
**Good flow:**
|
|
||||||
|
|
||||||
1. Prerequisites
|
|
||||||
2. Basic usage (show the simple case first)
|
|
||||||
3. Advanced options (add complexity after basics are clear)
|
|
||||||
|
|
||||||
**Jarring flow:**
|
|
||||||
|
|
||||||
1. Prerequisites
|
|
||||||
2. Overview of all capabilities (too much before seeing it work)
|
|
||||||
3. Basic usage
|
|
||||||
|
|
||||||
**Avoid structural problems:**
|
|
||||||
|
|
||||||
- Don't start multiple sentences or sections with the same structure
|
|
||||||
(varies pacing and improves readability)
|
|
||||||
- Don't over-explain obvious things (trust the reader's competence)
|
|
||||||
- Don't use "**Bold:** format" for subsection labels (use plain text
|
|
||||||
with colon)
|
|
||||||
|
|
||||||
### Guide structure
|
|
||||||
|
|
||||||
Guides are single-page - don't split a guide into multiple sub-pages
|
|
||||||
(for example, separate "overview", "configure", and "deploy" pages for
|
|
||||||
one guide). Cover the full task on one page and use headings to
|
|
||||||
organize sections.
|
|
||||||
|
|
||||||
Store each guide as a single Markdown file directly under
|
|
||||||
`content/guides/` (for example, `content/guides/django.md`), not
|
|
||||||
wrapped in its own directory with an `index.md`. Guide images belong in
|
|
||||||
the shared `content/guides/images/` folder, prefixed with the guide's
|
|
||||||
slug, not in a per-guide directory - see [Images](STYLE.md#images).
|
|
||||||
|
|
||||||
### Lists
|
|
||||||
|
|
||||||
- Limit bulleted lists to five items when possible
|
|
||||||
- Don't add commas or semicolons to list item ends
|
|
||||||
- Capitalize list items for ease of scanning
|
|
||||||
- Make all list items parallel in structure
|
|
||||||
- Start each item with a capital letter unless it's a parameter or
|
|
||||||
command
|
|
||||||
- For nested sequential lists, use lowercase letters: 1. Top level,
|
|
||||||
a. Child step
|
|
||||||
|
|
||||||
**Avoid marketing-style list formatting:**
|
|
||||||
|
|
||||||
Don't use "**Term** - Description" format, which reads like marketing
|
|
||||||
copy:
|
|
||||||
|
|
||||||
❌ **Bad example:**
|
|
||||||
|
|
||||||
- **Build** - Creates images from Dockerfiles
|
|
||||||
- **Run** - Starts containers from images
|
|
||||||
- **Push** - Uploads images to registries
|
|
||||||
|
|
||||||
✅ **Good alternatives:**
|
|
||||||
|
|
||||||
Use simple descriptive bullets:
|
|
||||||
|
|
||||||
- Build images from Dockerfiles
|
|
||||||
- Start containers from images
|
|
||||||
- Upload images to registries
|
|
||||||
|
|
||||||
Or use proper prose when appropriate:
|
|
||||||
"Docker lets you build images from Dockerfiles, start containers from
|
|
||||||
images, and upload images to registries."
|
|
||||||
|
|
||||||
### Code and commands
|
|
||||||
|
|
||||||
Format Docker commands, instructions, filenames, and package names as
|
|
||||||
inline code using backticks: `docker build`
|
|
||||||
|
|
||||||
**Code example pattern:**
|
|
||||||
|
|
||||||
Follow this three-step pattern for code examples:
|
|
||||||
|
|
||||||
1. **State** what you're doing (brief)
|
|
||||||
2. **Show** the command or code
|
|
||||||
3. **Explain** the result or key parts (if not obvious)
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
|
|
||||||
````markdown
|
|
||||||
Build your image:
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ docker build -t my-app .
|
|
||||||
```
|
|
||||||
|
|
||||||
This creates an image tagged `my-app` using the Dockerfile in the
|
|
||||||
current directory.
|
|
||||||
````
|
|
||||||
|
|
||||||
**When to show command output:**
|
|
||||||
|
|
||||||
- Show output when it helps understanding
|
|
||||||
- Show output when users need to verify results
|
|
||||||
- Don't show output for commands with obvious results
|
|
||||||
- Don't show output when it's not relevant to the point
|
|
||||||
|
|
||||||
For code block syntax, language hints, variables, and advanced features
|
|
||||||
(line highlighting, collapsible blocks), see
|
|
||||||
[COMPONENTS.md](COMPONENTS.md#code-blocks).
|
|
||||||
|
|
||||||
### Links
|
|
||||||
|
|
||||||
- Use plain, descriptive language (around five words)
|
|
||||||
- Front-load important terms at the beginning
|
|
||||||
- Avoid generic calls to action like "click here" or "find out more"
|
|
||||||
- Don't include end punctuation in link text
|
|
||||||
- Use relative links with source filenames for internal links
|
|
||||||
- Don't make link text bold or italic unless it would be in normal
|
|
||||||
body copy
|
|
||||||
|
|
||||||
### Images
|
|
||||||
|
|
||||||
**Best practices:**
|
|
||||||
|
|
||||||
- Capture only relevant UI - don't include unnecessary white space
|
|
||||||
- Use realistic text, not lorem ipsum
|
|
||||||
- Keep images small and focused
|
|
||||||
- Compress images before adding to repository
|
|
||||||
- Remove unused images from repository
|
|
||||||
|
|
||||||
**File organization:**
|
|
||||||
|
|
||||||
- Store guide images in the shared `content/guides/images/` folder,
|
|
||||||
not in a per-guide directory
|
|
||||||
- Prefix filenames with the guide's slug to avoid collisions (for
|
|
||||||
example, `kafka-architecture.webp`)
|
|
||||||
|
|
||||||
For image syntax and parameters (sizing, borders), see
|
|
||||||
[COMPONENTS.md](COMPONENTS.md#images).
|
|
||||||
|
|
||||||
### Callouts
|
|
||||||
|
|
||||||
Use callouts sparingly to emphasize important information. Use them only
|
|
||||||
when information truly deserves special emphasis - for warnings, critical
|
|
||||||
notes, or important context that affects how users approach a task.
|
|
||||||
|
|
||||||
Callout types: Note (informational), Tip (helpful suggestion), Important
|
|
||||||
(moderate issue), Warning (potential damage/loss), Caution (serious risk).
|
|
||||||
|
|
||||||
For syntax and detailed usage guidelines, see
|
|
||||||
[COMPONENTS.md](COMPONENTS.md#callouts).
|
|
||||||
|
|
||||||
### Tables
|
|
||||||
|
|
||||||
- Use sentence case for table headings
|
|
||||||
- Don't leave cells empty - use "N/A" or "None" if needed
|
|
||||||
- Align decimals on the decimal point
|
|
||||||
|
|
||||||
### Navigation instructions
|
|
||||||
|
|
||||||
- Use location, then action: "From the **Visibility** drop-down list, select Public"
|
|
||||||
- Be brief and specific: "Select **Save**"
|
|
||||||
- Start with the reason if a step needs one: "To view changes, select the link"
|
|
||||||
|
|
||||||
### Optional steps
|
|
||||||
|
|
||||||
Start optional steps with "Optional." followed by the instruction:
|
|
||||||
|
|
||||||
_1. Optional. Enter a description for the job._
|
|
||||||
|
|
||||||
### File types and units
|
|
||||||
|
|
||||||
- Use formal file type names: "a PNG file" not "a .png file"
|
|
||||||
- Use abbreviated units with spaces: "10 GB" not "10GB" or
|
|
||||||
"10 gigabytes"
|
|
||||||
|
|
||||||
## Word list
|
|
||||||
|
|
||||||
### Recommended terms
|
|
||||||
|
|
||||||
| Use | Don't use |
|
|
||||||
| ------------------------------------- | ---------------------- |
|
|
||||||
| lets | allows |
|
|
||||||
| turn on, toggle on | enable |
|
|
||||||
| turn off, toggle off | disable |
|
|
||||||
| select | click |
|
|
||||||
| following | below |
|
|
||||||
| previous | above |
|
|
||||||
| checkbox | check box |
|
|
||||||
| username | account name |
|
|
||||||
| sign in | sign on, log in, login |
|
|
||||||
| sign up, create account | register |
|
|
||||||
| for example, such as | e.g. |
|
|
||||||
| run | execute |
|
|
||||||
| want | wish |
|
|
||||||
| Kubernetes | K8s |
|
|
||||||
| repository | repo |
|
|
||||||
| administrator (first use), admin (UI) | - |
|
|
||||||
| and | & (ampersand) |
|
|
||||||
| move through, navigate to | scroll |
|
|
||||||
| (be more precise) | respectively |
|
|
||||||
| versus | vs, vs. |
|
|
||||||
| use | utilize |
|
|
||||||
| help | facilitate |
|
|
||||||
|
|
||||||
Use "turn on" and "turn off" for UI toggles, switches, and settings a user
|
|
||||||
flips in the interface. In general prose, "enable" and "disable" are
|
|
||||||
acceptable when describing a feature or capability becoming available — for
|
|
||||||
example, "When you enable auto-log-out, your users are logged out." Don't
|
|
||||||
treat every "enable" or "disable" as a violation.
|
|
||||||
|
|
||||||
### Version numbers
|
|
||||||
|
|
||||||
- Use "earlier" not "lower": Docker Desktop 4.1 and earlier
|
|
||||||
- Use "later" not "higher" or "above": Docker Desktop 4.1 and later
|
|
||||||
|
|
||||||
### Quick transformations
|
|
||||||
|
|
||||||
Common phrases to transform for clearer, more direct writing:
|
|
||||||
|
|
||||||
| Instead of... | Write... |
|
|
||||||
| ------------------------ | ---------------------------- |
|
|
||||||
| In order to build | To build |
|
|
||||||
| This allows you to build | This lets you build / Build |
|
|
||||||
| Simply run the command | Run the command |
|
|
||||||
| We provide a feature | Docker provides / You can |
|
|
||||||
| Utilize the API | Use the API |
|
|
||||||
| This facilitates testing | This helps test / This tests |
|
|
||||||
| Click the button | Select the button |
|
|
||||||
| It's worth noting that X | X (state it directly) |
|
|
||||||
|
|
||||||
### UI elements
|
|
||||||
|
|
||||||
- **tab vs view** - Use "view" for major UI sections, "tab" for
|
|
||||||
sub-sections
|
|
||||||
- **toggle** - You "turn on" or "turn off" a toggle
|
|
||||||
|
|
||||||
## Docker terminology
|
|
||||||
|
|
||||||
### Products and features
|
|
||||||
|
|
||||||
- **Docker Compose** - The application or all functionality associated
|
|
||||||
with it
|
|
||||||
- **`docker compose`** - Use code formatting for commands
|
|
||||||
- **Docker Compose CLI** - The family of Compose commands from
|
|
||||||
Docker CLI
|
|
||||||
- **Compose plugin** - The add-on for Docker CLI that can be
|
|
||||||
enabled/disabled
|
|
||||||
- **compose.yaml** - Current designation for the Compose file (use
|
|
||||||
code formatting)
|
|
||||||
|
|
||||||
### Technical terms
|
|
||||||
|
|
||||||
- **Digest** - Long string automatically created when you push an
|
|
||||||
image
|
|
||||||
- **Member** - A user of Docker Hub who is part of an organization
|
|
||||||
- **Namespace** - Organization or user name; every image needs a
|
|
||||||
namespace
|
|
||||||
- **Node** - Physical or virtual machine running Docker Engine in
|
|
||||||
swarm mode
|
|
||||||
- Manager nodes: Perform swarm management and orchestration
|
|
||||||
- Worker nodes: Execute tasks
|
|
||||||
- **Registry** - Online storage for Docker images
|
|
||||||
- **Repository** - Lets users share container images with team,
|
|
||||||
customers, or community
|
|
||||||
|
|
||||||
### Platform terminology
|
|
||||||
|
|
||||||
- **Multi-platform** - Broad: Mac/Linux/Windows; Narrow: Linux/amd64
|
|
||||||
and Linux/arm64
|
|
||||||
- **Multi-architecture (multi-arch)** - CPU architecture or
|
|
||||||
hardware-architecture-based; don't use as synonym for multi-platform
|
|
||||||
|
|
||||||
## Quick reference
|
|
||||||
|
|
||||||
### Voice checklist
|
|
||||||
|
|
||||||
- ✅ Direct and practical
|
|
||||||
- ✅ Conversational with active voice
|
|
||||||
- ✅ Specific and actionable
|
|
||||||
- ✅ Lead with observable outcomes
|
|
||||||
- ❌ Corporate-speak
|
|
||||||
- ❌ Condescending
|
|
||||||
- ❌ Overly formal
|
|
||||||
|
|
||||||
### Structure checklist
|
|
||||||
|
|
||||||
- ✅ Answer "What will I learn?" in the first paragraph
|
|
||||||
- ✅ Answer "Why does this matter?" in the first paragraph
|
|
||||||
- ✅ Front-load important information in headings and lists
|
|
||||||
- ✅ Connect ideas naturally between sections
|
|
||||||
- ✅ Use examples to clarify concepts
|
|
||||||
- ✅ Match content type (tutorial vs how-to vs reference vs concept)
|
|
||||||
- ✅ Follow code example pattern: state → show → explain
|
|
||||||
- ✅ Preserve document scope (don't unnecessarily expand)
|
|
||||||
|
|
||||||
### Common mistakes
|
|
||||||
|
|
||||||
- ❌ Using "click" instead of "select"
|
|
||||||
- ❌ Using "below" instead of "following"
|
|
||||||
- ❌ Starting sentences with numbers (recast the sentence)
|
|
||||||
- ❌ Using apostrophes in plural acronyms
|
|
||||||
- ❌ Leaving table cells empty
|
|
||||||
- ❌ Using commas in large numbers (use spaces)
|
|
||||||
- ❌ Referring to file types by extension (.png file)
|
|
||||||
- ❌ Using bold for product names or emphasis (only for UI elements)
|
|
||||||
- ❌ Using "**Term** - Description" format in lists
|
|
||||||
- ❌ Using hedge words (simply, easily, just, seamlessly)
|
|
||||||
- ❌ Using meta-commentary (it's worth noting that...)
|
|
||||||
- ❌ Using "we" instead of "you" or "Docker"
|
|
||||||
- ❌ Showing command output when it's not needed
|
|
||||||
- ❌ Not explaining what users will learn in first paragraph
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
# 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).
|
|
||||||
@@ -1,244 +0,0 @@
|
|||||||
# Handling Errors { #handling-errors }
|
|
||||||
|
|
||||||
There are many situations in which you need to report an error to a client that is using your API.
|
|
||||||
|
|
||||||
This client could be a browser with a frontend, a code from someone else, an IoT device, etc.
|
|
||||||
|
|
||||||
You could need to tell the client that:
|
|
||||||
|
|
||||||
* The client doesn't have enough privileges for that operation.
|
|
||||||
* The client doesn't have access to that resource.
|
|
||||||
* The item the client was trying to access doesn't exist.
|
|
||||||
* etc.
|
|
||||||
|
|
||||||
In these cases, you would normally return an **HTTP status code** in the range of **400** (from 400 to 499).
|
|
||||||
|
|
||||||
This is similar to the 200 HTTP status codes (from 200 to 299). Those "200" status codes mean that somehow there was a "success" in the request.
|
|
||||||
|
|
||||||
The status codes in the 400 range mean that there was an error from the client.
|
|
||||||
|
|
||||||
Remember all those **"404 Not Found"** errors (and jokes)?
|
|
||||||
|
|
||||||
## Use `HTTPException` { #use-httpexception }
|
|
||||||
|
|
||||||
To return HTTP responses with errors to the client you use `HTTPException`.
|
|
||||||
|
|
||||||
### Import `HTTPException` { #import-httpexception }
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial001_py310.py hl[1] *}
|
|
||||||
|
|
||||||
### Raise an `HTTPException` in your code { #raise-an-httpexception-in-your-code }
|
|
||||||
|
|
||||||
`HTTPException` is a normal Python exception with additional data relevant for APIs.
|
|
||||||
|
|
||||||
Because it's a Python exception, you don't `return` it, you `raise` it.
|
|
||||||
|
|
||||||
This also means that if you are inside a utility function that you are calling inside of your *path operation function*, and you raise the `HTTPException` from inside of that utility function, it won't run the rest of the code in the *path operation function*, it will terminate that request right away and send the HTTP error from the `HTTPException` to the client.
|
|
||||||
|
|
||||||
The benefit of raising an exception over returning a value will be more evident in the section about Dependencies and Security.
|
|
||||||
|
|
||||||
In this example, when the client requests an item by an ID that doesn't exist, raise an exception with a status code of `404`:
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial001_py310.py hl[11] *}
|
|
||||||
|
|
||||||
### The resulting response { #the-resulting-response }
|
|
||||||
|
|
||||||
If the client requests `http://example.com/items/foo` (an `item_id` `"foo"`), that client will receive an HTTP status code of 200, and a JSON response of:
|
|
||||||
|
|
||||||
```JSON
|
|
||||||
{
|
|
||||||
"item": "The Foo Wrestlers"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
But if the client requests `http://example.com/items/bar` (a non-existent `item_id` `"bar"`), that client will receive an HTTP status code of 404 (the "not found" error), and a JSON response of:
|
|
||||||
|
|
||||||
```JSON
|
|
||||||
{
|
|
||||||
"detail": "Item not found"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
When raising an `HTTPException`, you can pass any value that can be converted to JSON as the parameter `detail`, not only `str`.
|
|
||||||
|
|
||||||
You could pass a `dict`, a `list`, etc.
|
|
||||||
|
|
||||||
They are handled automatically by **FastAPI** and converted to JSON.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
## Add custom headers { #add-custom-headers }
|
|
||||||
|
|
||||||
There are some situations where it's useful to be able to add custom headers to the HTTP error. For example, for some types of security.
|
|
||||||
|
|
||||||
You probably won't need to use it directly in your code.
|
|
||||||
|
|
||||||
But in case you needed it for an advanced scenario, you can add custom headers:
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial002_py310.py hl[14] *}
|
|
||||||
|
|
||||||
## Install custom exception handlers { #install-custom-exception-handlers }
|
|
||||||
|
|
||||||
You can add custom exception handlers with [the same exception utilities from Starlette](https://starlette.dev/exceptions/).
|
|
||||||
|
|
||||||
Let's say you have a custom exception `UnicornException` that you (or a library you use) might `raise`.
|
|
||||||
|
|
||||||
And you want to handle this exception globally with FastAPI.
|
|
||||||
|
|
||||||
You could add a custom exception handler with `@app.exception_handler()`:
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial003_py310.py hl[5:7,13:18,24] *}
|
|
||||||
|
|
||||||
Here, if you request `/unicorns/yolo`, the *path operation* will `raise` a `UnicornException`.
|
|
||||||
|
|
||||||
But it will be handled by the `unicorn_exception_handler`.
|
|
||||||
|
|
||||||
So, you will receive a clean error, with an HTTP status code of `418` and a JSON content of:
|
|
||||||
|
|
||||||
```JSON
|
|
||||||
{"message": "Oops! yolo did something. There goes a rainbow..."}
|
|
||||||
```
|
|
||||||
|
|
||||||
/// note | Technical Details
|
|
||||||
|
|
||||||
You could also use `from starlette.requests import Request` and `from starlette.responses import JSONResponse`.
|
|
||||||
|
|
||||||
**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette. The same with `Request`.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
## Override the default exception handlers { #override-the-default-exception-handlers }
|
|
||||||
|
|
||||||
**FastAPI** has some default exception handlers.
|
|
||||||
|
|
||||||
These handlers are in charge of returning the default JSON responses when you `raise` an `HTTPException` and when the request has invalid data.
|
|
||||||
|
|
||||||
You can override these exception handlers with your own.
|
|
||||||
|
|
||||||
### Override request validation exceptions { #override-request-validation-exceptions }
|
|
||||||
|
|
||||||
When a request contains invalid data, **FastAPI** internally raises a `RequestValidationError`.
|
|
||||||
|
|
||||||
And it also includes a default exception handler for it.
|
|
||||||
|
|
||||||
To override it, import the `RequestValidationError` and use it with `@app.exception_handler(RequestValidationError)` to decorate the exception handler.
|
|
||||||
|
|
||||||
The exception handler will receive a `Request` and the exception.
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial004_py310.py hl[2,14:19] *}
|
|
||||||
|
|
||||||
Now, if you go to `/items/foo`, instead of getting the default JSON error with:
|
|
||||||
|
|
||||||
```JSON
|
|
||||||
{
|
|
||||||
"detail": [
|
|
||||||
{
|
|
||||||
"loc": [
|
|
||||||
"path",
|
|
||||||
"item_id"
|
|
||||||
],
|
|
||||||
"msg": "value is not a valid integer",
|
|
||||||
"type": "type_error.integer"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
you will get a text version, with:
|
|
||||||
|
|
||||||
```
|
|
||||||
Validation errors:
|
|
||||||
Field: ('path', 'item_id'), Error: Input should be a valid integer, unable to parse string as an integer
|
|
||||||
```
|
|
||||||
|
|
||||||
### Override the `HTTPException` error handler { #override-the-httpexception-error-handler }
|
|
||||||
|
|
||||||
The same way, you can override the `HTTPException` handler.
|
|
||||||
|
|
||||||
For example, you could want to return a plain text response instead of JSON for these errors:
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial004_py310.py hl[3:4,9:11,25] *}
|
|
||||||
|
|
||||||
/// note | Technical Details
|
|
||||||
|
|
||||||
You could also use `from starlette.responses import PlainTextResponse`.
|
|
||||||
|
|
||||||
**FastAPI** provides the same `starlette.responses` as `fastapi.responses` just as a convenience for you, the developer. But most of the available responses come directly from Starlette.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
/// warning
|
|
||||||
|
|
||||||
Have in mind that the `RequestValidationError` contains the information of the file name and line where the validation error happens so that you can show it in your logs with the relevant information if you want to.
|
|
||||||
|
|
||||||
But that means that if you just convert it to a string and return that information directly, you could be leaking a bit of information about your system, that's why here the code extracts and shows each error independently.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
### Use the `RequestValidationError` body { #use-the-requestvalidationerror-body }
|
|
||||||
|
|
||||||
The `RequestValidationError` contains the `body` it received with invalid data.
|
|
||||||
|
|
||||||
You could use it while developing your app to log the body and debug it, return it to the user, etc.
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial005_py310.py hl[14] *}
|
|
||||||
|
|
||||||
Now try sending an invalid item like:
|
|
||||||
|
|
||||||
```JSON
|
|
||||||
{
|
|
||||||
"title": "towel",
|
|
||||||
"size": "XL"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
You will receive a response telling you that the data is invalid containing the received body:
|
|
||||||
|
|
||||||
```JSON hl_lines="12-15"
|
|
||||||
{
|
|
||||||
"detail": [
|
|
||||||
{
|
|
||||||
"loc": [
|
|
||||||
"body",
|
|
||||||
"size"
|
|
||||||
],
|
|
||||||
"msg": "value is not a valid integer",
|
|
||||||
"type": "type_error.integer"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"body": {
|
|
||||||
"title": "towel",
|
|
||||||
"size": "XL"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### FastAPI's `HTTPException` vs Starlette's `HTTPException` { #fastapis-httpexception-vs-starlettes-httpexception }
|
|
||||||
|
|
||||||
**FastAPI** has its own `HTTPException`.
|
|
||||||
|
|
||||||
And **FastAPI**'s `HTTPException` error class inherits from Starlette's `HTTPException` error class.
|
|
||||||
|
|
||||||
The only difference is that **FastAPI**'s `HTTPException` accepts any JSON-able data for the `detail` field, while Starlette's `HTTPException` only accepts strings for it.
|
|
||||||
|
|
||||||
So, you can keep raising **FastAPI**'s `HTTPException` as normally in your code.
|
|
||||||
|
|
||||||
But when you register an exception handler, you should register it for Starlette's `HTTPException`.
|
|
||||||
|
|
||||||
This way, if any part of Starlette's internal code, or a Starlette extension or plug-in, raises a Starlette `HTTPException`, your handler will be able to catch and handle it.
|
|
||||||
|
|
||||||
In this example, to be able to have both `HTTPException`s in the same code, Starlette's exceptions is renamed to `StarletteHTTPException`:
|
|
||||||
|
|
||||||
```Python
|
|
||||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
||||||
```
|
|
||||||
|
|
||||||
### Reuse **FastAPI**'s exception handlers { #reuse-fastapis-exception-handlers }
|
|
||||||
|
|
||||||
If you want to use the exception along with the same default exception handlers from **FastAPI**, you can import and reuse the default exception handlers from `fastapi.exception_handlers`:
|
|
||||||
|
|
||||||
{* ../../docs_src/handling_errors/tutorial006_py310.py hl[2:5,15,21] *}
|
|
||||||
|
|
||||||
In this example you are just printing the error with a very expressive message, but you get the idea. You can use the exception and then just reuse the default exception handlers.
|
|
||||||
@@ -1,326 +0,0 @@
|
|||||||
# Settings and Environment Variables { #settings-and-environment-variables }
|
|
||||||
|
|
||||||
In many cases your application could need some external settings or configurations, for example secret keys, database credentials, credentials for email services, etc.
|
|
||||||
|
|
||||||
Most of these settings are variable (can change), like database URLs. And many could be sensitive, like secrets.
|
|
||||||
|
|
||||||
For this reason it's common to provide them in environment variables that are read by the application.
|
|
||||||
|
|
||||||
An **environment variable** (also known as an **env var**) is a value that lives outside of the Python code, in the operating system, and can be read by your application and other programs.
|
|
||||||
|
|
||||||
You can create an environment variable for a command when you run it. You will see the platform-specific commands below.
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
Read the [Environment Variables guide](https://tiangolo.com/guides/environment-variables/) for a detailed explanation of how environment variables work.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
## Types and validation { #types-and-validation }
|
|
||||||
|
|
||||||
These environment variables can only handle text strings, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, such as Linux, Windows, and macOS).
|
|
||||||
|
|
||||||
That means that any value read in Python from an environment variable will be a `str`, and any conversion to a different type or any validation has to be done in code.
|
|
||||||
|
|
||||||
## Pydantic `Settings` { #pydantic-settings }
|
|
||||||
|
|
||||||
Fortunately, Pydantic provides a great utility to handle these settings coming from environment variables with [Pydantic: Settings management](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/).
|
|
||||||
|
|
||||||
### Install `pydantic-settings` { #install-pydantic-settings }
|
|
||||||
|
|
||||||
Add the `pydantic-settings` package to your project:
|
|
||||||
|
|
||||||
<div class="termy">
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ uv add pydantic-settings
|
|
||||||
---> 100%
|
|
||||||
```
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
It also comes included when you install the `all` extras with:
|
|
||||||
|
|
||||||
<div class="termy">
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ uv add "fastapi[all]"
|
|
||||||
---> 100%
|
|
||||||
```
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
### Create the `Settings` object { #create-the-settings-object }
|
|
||||||
|
|
||||||
Import `BaseSettings` from Pydantic and create a sub-class, very much like with a Pydantic model.
|
|
||||||
|
|
||||||
The same way as with Pydantic models, you declare class attributes with type annotations, and possibly default values.
|
|
||||||
|
|
||||||
You can use all the same validation features and tools you use for Pydantic models, like different data types and additional validations with `Field()`.
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/tutorial001_py310.py hl[2,5:8,11] *}
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
If you want something quick to copy and paste, don't use this example, use the last one below.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
Then, when you create an instance of that `Settings` class (in this case, in the `settings` object), Pydantic will read the environment variables in a case-insensitive way, so, an upper-case variable `APP_NAME` will still be read for the attribute `app_name`.
|
|
||||||
|
|
||||||
Next it will convert and validate the data. So, when you use that `settings` object, you will have data of the types you declared (e.g. `items_per_user` will be an `int`).
|
|
||||||
|
|
||||||
### Use the `settings` { #use-the-settings }
|
|
||||||
|
|
||||||
Then you can use the new `settings` object in your application:
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/tutorial001_py310.py hl[18:20] *}
|
|
||||||
|
|
||||||
### Run the server { #run-the-server }
|
|
||||||
|
|
||||||
Next, you would run the server passing the configurations as environment variables, for example you could set an `ADMIN_EMAIL` and `APP_NAME` with:
|
|
||||||
|
|
||||||
//// tab | Linux, macOS, Windows Bash
|
|
||||||
|
|
||||||
<div class="termy">
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ ADMIN_EMAIL="deadpool@example.com" APP_NAME="ChimichangApp" uv run fastapi run main.py
|
|
||||||
|
|
||||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
|
||||||
```
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
////
|
|
||||||
|
|
||||||
//// tab | Windows PowerShell
|
|
||||||
|
|
||||||
<div class="termy">
|
|
||||||
|
|
||||||
```console
|
|
||||||
$ $Env:ADMIN_EMAIL = "deadpool@example.com"
|
|
||||||
$ $Env:APP_NAME = "ChimichangApp"
|
|
||||||
$ uv run fastapi run main.py
|
|
||||||
|
|
||||||
<span style="color: green;">INFO</span>: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
|
|
||||||
```
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
////
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
In Bash, to set multiple env vars for a single command, separate them with a space and put them all before the command.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
And then the `admin_email` setting would be set to `"deadpool@example.com"`.
|
|
||||||
|
|
||||||
The `app_name` would be `"ChimichangApp"`.
|
|
||||||
|
|
||||||
And the `items_per_user` would keep its default value of `50`.
|
|
||||||
|
|
||||||
## Settings in another module { #settings-in-another-module }
|
|
||||||
|
|
||||||
You could put those settings in another module file as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md).
|
|
||||||
|
|
||||||
For example, you could have a file `config.py` with:
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app01_py310/config.py *}
|
|
||||||
|
|
||||||
And then use it in a file `main.py`:
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app01_py310/main.py hl[3,11:13] *}
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
You would also need a file `__init__.py` as you saw in [Bigger Applications - Multiple Files](../tutorial/bigger-applications.md).
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
## Settings in a dependency { #settings-in-a-dependency }
|
|
||||||
|
|
||||||
In some occasions it might be useful to provide the settings from a dependency, instead of having a global object with `settings` that is used everywhere.
|
|
||||||
|
|
||||||
This could be especially useful during testing, as it's very easy to override a dependency with your own custom settings.
|
|
||||||
|
|
||||||
### The config file { #the-config-file }
|
|
||||||
|
|
||||||
Coming from the previous example, your `config.py` file could look like:
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app02_an_py310/config.py hl[10] *}
|
|
||||||
|
|
||||||
Notice that now we don't create a default instance `settings = Settings()`.
|
|
||||||
|
|
||||||
### The main app file { #the-main-app-file }
|
|
||||||
|
|
||||||
Now we create a dependency that returns a new `config.Settings()`.
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app02_an_py310/main.py hl[6,12:13] *}
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
We'll discuss the `@lru_cache` in a bit.
|
|
||||||
|
|
||||||
For now you can assume `get_settings()` is a normal function.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
And then we can require it from the *path operation function* as a dependency and use it anywhere we need it.
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app02_an_py310/main.py hl[17,19:21] *}
|
|
||||||
|
|
||||||
### Settings and testing { #settings-and-testing }
|
|
||||||
|
|
||||||
Then it would be very easy to provide a different settings object during testing by creating a dependency override for `get_settings`:
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app02_an_py310/test_main.py hl[9:10,13,21] *}
|
|
||||||
|
|
||||||
In the dependency override we set a new value for the `admin_email` when creating the new `Settings` object, and then we return that new object.
|
|
||||||
|
|
||||||
Then we can test that it is used.
|
|
||||||
|
|
||||||
## Reading a `.env` file { #reading-a-env-file }
|
|
||||||
|
|
||||||
If you have many settings that possibly change a lot, maybe in different environments, it might be useful to put them on a file and then read them from it as if they were environment variables.
|
|
||||||
|
|
||||||
This practice is common enough that it has a name, these environment variables are commonly placed in a file `.env`, and the file is called a "dotenv".
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
A file starting with a dot (`.`) is a hidden file in Unix-like systems, like Linux and macOS.
|
|
||||||
|
|
||||||
But a dotenv file doesn't really have to have that exact filename.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
Pydantic has support for reading from these types of files using an external library. You can read more at [Pydantic Settings: Dotenv (.env) support](https://pydantic.dev/docs/validation/latest/concepts/pydantic_settings/#dotenv-env-support).
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
For this to work, add `python-dotenv` to your project with `uv add python-dotenv`.
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
### The `.env` file { #the-env-file }
|
|
||||||
|
|
||||||
You could have a `.env` file with:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
ADMIN_EMAIL="deadpool@example.com"
|
|
||||||
APP_NAME="ChimichangApp"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Read settings from `.env` { #read-settings-from-env }
|
|
||||||
|
|
||||||
And then update your `config.py` with:
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app03_an_py310/config.py hl[9] *}
|
|
||||||
|
|
||||||
/// tip
|
|
||||||
|
|
||||||
The `model_config` attribute is used just for Pydantic configuration. You can read more at [Pydantic: Concepts: Configuration](https://pydantic.dev/docs/validation/latest/concepts/config/).
|
|
||||||
|
|
||||||
///
|
|
||||||
|
|
||||||
Here we define the config `env_file` inside of your Pydantic `Settings` class, and set the value to the filename with the dotenv file we want to use.
|
|
||||||
|
|
||||||
### Creating the `Settings` only once with `lru_cache` { #creating-the-settings-only-once-with-lru-cache }
|
|
||||||
|
|
||||||
Reading a file from disk is normally a costly (slow) operation, so you probably want to do it only once and then reuse the same settings object, instead of reading it for each request.
|
|
||||||
|
|
||||||
But every time we do:
|
|
||||||
|
|
||||||
```Python
|
|
||||||
Settings()
|
|
||||||
```
|
|
||||||
|
|
||||||
a new `Settings` object would be created, and at creation it would read the `.env` file again.
|
|
||||||
|
|
||||||
If the dependency function was just like:
|
|
||||||
|
|
||||||
```Python
|
|
||||||
def get_settings():
|
|
||||||
return Settings()
|
|
||||||
```
|
|
||||||
|
|
||||||
we would create that object for each request, and we would be reading the `.env` file for each request. ⚠️
|
|
||||||
|
|
||||||
But as we are using the `@lru_cache` decorator on top, the `Settings` object will be created only once, the first time it's called. ✔️
|
|
||||||
|
|
||||||
{* ../../docs_src/settings/app03_an_py310/main.py hl[1,11] *}
|
|
||||||
|
|
||||||
Then for any subsequent call of `get_settings()` in the dependencies for the next requests, instead of executing the internal code of `get_settings()` and creating a new `Settings` object, it will return the same object that was returned on the first call, again and again.
|
|
||||||
|
|
||||||
#### `lru_cache` Technical Details { #lru-cache-technical-details }
|
|
||||||
|
|
||||||
`@lru_cache` modifies the function it decorates to return the same value that was returned the first time, instead of computing it again, executing the code of the function every time.
|
|
||||||
|
|
||||||
So, the function below it will be executed once for each combination of arguments. And then the values returned by each of those combinations of arguments will be used again and again whenever the function is called with exactly the same combination of arguments.
|
|
||||||
|
|
||||||
For example, if you have a function:
|
|
||||||
|
|
||||||
```Python
|
|
||||||
@lru_cache
|
|
||||||
def say_hi(name: str, salutation: str = "Ms."):
|
|
||||||
return f"Hello {salutation} {name}"
|
|
||||||
```
|
|
||||||
|
|
||||||
your program could execute like this:
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
sequenceDiagram
|
|
||||||
|
|
||||||
participant code as Code
|
|
||||||
participant function as say_hi()
|
|
||||||
participant execute as Execute function
|
|
||||||
|
|
||||||
rect rgba(0, 255, 0, .1)
|
|
||||||
code ->> function: say_hi(name="Camila")
|
|
||||||
function ->> execute: execute function code
|
|
||||||
execute ->> code: return the result
|
|
||||||
end
|
|
||||||
|
|
||||||
rect rgba(0, 255, 255, .1)
|
|
||||||
code ->> function: say_hi(name="Camila")
|
|
||||||
function ->> code: return stored result
|
|
||||||
end
|
|
||||||
|
|
||||||
rect rgba(0, 255, 0, .1)
|
|
||||||
code ->> function: say_hi(name="Rick")
|
|
||||||
function ->> execute: execute function code
|
|
||||||
execute ->> code: return the result
|
|
||||||
end
|
|
||||||
|
|
||||||
rect rgba(0, 255, 0, .1)
|
|
||||||
code ->> function: say_hi(name="Rick", salutation="Mr.")
|
|
||||||
function ->> execute: execute function code
|
|
||||||
execute ->> code: return the result
|
|
||||||
end
|
|
||||||
|
|
||||||
rect rgba(0, 255, 255, .1)
|
|
||||||
code ->> function: say_hi(name="Rick")
|
|
||||||
function ->> code: return stored result
|
|
||||||
end
|
|
||||||
|
|
||||||
rect rgba(0, 255, 255, .1)
|
|
||||||
code ->> function: say_hi(name="Camila")
|
|
||||||
function ->> code: return stored result
|
|
||||||
end
|
|
||||||
```
|
|
||||||
|
|
||||||
In the case of our dependency `get_settings()`, the function doesn't even take any arguments, so it always returns the same value.
|
|
||||||
|
|
||||||
That way, it behaves almost as if it was just a global variable. But as it uses a dependency function, then we can override it easily for testing.
|
|
||||||
|
|
||||||
`@lru_cache` is part of `functools` which is part of Python's standard library, you can read more about it in the [Python docs for `@lru_cache`](https://docs.python.org/3/library/functools.html#functools.lru_cache).
|
|
||||||
|
|
||||||
## Recap { #recap }
|
|
||||||
|
|
||||||
You can use Pydantic Settings to handle the settings or configurations for your application, with all the power of Pydantic models.
|
|
||||||
|
|
||||||
* By using a dependency you can simplify testing.
|
|
||||||
* You can use `.env` files with it.
|
|
||||||
* Using `@lru_cache` lets you avoid reading the dotenv file again and again for each request, while allowing you to override it during testing.
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# Project documentation
|
||||||
|
|
||||||
|
The current implementation baseline is the English revision 1.3
|
||||||
|
[Live document MVP delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md).
|
||||||
|
It targets a conditional four-day demo using the existing ingestion/embedding
|
||||||
|
Phases 1-4, LangChain RAG/tools, new browser uploads and direct Gemini Live.
|
||||||
|
The four supplied examples are mandatory initial tests, not an upload allowlist.
|
||||||
|
Full text chat/history and settings editing are deferred.
|
||||||
|
|
||||||
|
## Implementation reading order
|
||||||
|
|
||||||
|
1. [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md): active scope, gates, Days 1-4 and MVP-01 through MVP-14.
|
||||||
|
2. [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md): work packages, embedding/LangChain boundary, worker and retained review/resume.
|
||||||
|
3. [API catalog](specifications/RAG-Phase1-API-Catalog.md): active/deferred routes, D06/D07 exact review and authenticated Live.
|
||||||
|
4. [Database design](specifications/RAG-Phase1-Database-Design.md): existing foundation, proposed forward review/identity/voice changes and invariants.
|
||||||
|
5. [English scenarios](specifications/RAG-Phase1-MVP-Scenarios.md): supplied and unseen uploads, factual FAQ, voice and failure walkthroughs.
|
||||||
|
6. [Architecture](specifications/RAG-AI-Architecture.md): dependency boundaries; broader deferred sections are context.
|
||||||
|
|
||||||
|
The plan governs scope, API/database govern contracts and the guide governs
|
||||||
|
workflows. Proposed mechanisms are not implementation-completion reports.
|
||||||
|
|
||||||
|
Implementation progress is tracked in the [Live document MVP TODO](plans/live-document-mvp-todo.md). Checked baseline components do not prove complete MVP acceptance.
|
||||||
|
|
||||||
|
## Current code and recorded evidence
|
||||||
|
|
||||||
|
- [Reference map](agent-reference-map.md): source inventory, agent routes and historical acceptance.
|
||||||
|
- [Ingestion pipeline plan](plans/ingestion-pipeline-plan.md): implemented ingestion Phases 1-6 backend/validation and pending HTTP/search/Live integration.
|
||||||
|
- [Setup and validation](guides/ingestion-foundation-setup.md): actual commands and recorded checks; real provider/voice quality remains separate.
|
||||||
|
- [Repository instructions](../AGENTS.md) and [test guidance](../tests/README.md).
|
||||||
|
|
||||||
|
Phase 5 worker/publication/retry and retained review/resume backend services are
|
||||||
|
implemented; [Phase 6 operator handoff](guides/ingestion-operator-handoff.md)
|
||||||
|
records integration acceptance and the separate opt-in provider smoke command.
|
||||||
|
Authenticated D06/D07 transport, scoped pgvector search/selection, HTTP
|
||||||
|
identity/upload, browser integration, Live and UI remain pending. Real-provider
|
||||||
|
compatibility and Persian extraction/semantic quality are not certified by mocks.
|
||||||
|
The [root README](../README.md) retains prototype startup instructions.
|
||||||
|
|
||||||
|
## Historical context and corpus boundary
|
||||||
|
|
||||||
|
The [Persian scenario report](specifications/RAG-Phase1-Scenario-Report-FA.md)
|
||||||
|
is preserved as historical revision 1.2. New MVP instructions/scenarios are English.
|
||||||
|
Older text/history/settings promises do not override revision 1.3.
|
||||||
|
|
||||||
|
Project documentation stays under docs; uploaded/sample corpus stays under data.
|
||||||
|
Documentation changes do not clean/rebuild any existing vector index.
|
||||||
|
Preserve applied migrations, independent immutable document IDs, technical
|
||||||
|
revisions and compatible embedding profiles. Do not index project specifications
|
||||||
|
as organization knowledge.
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,331 @@
|
|||||||
|
# Ingestion integration validation and operator handoff
|
||||||
|
|
||||||
|
Phase 6 validates import -> real extraction -> chunking -> deterministic embedding
|
||||||
|
batches -> atomic PostgreSQL publication. It adds structured worker diagnostics
|
||||||
|
and a separate opt-in provider probe. This is ingestion acceptance; it does not
|
||||||
|
certify the complete Live MVP.
|
||||||
|
|
||||||
|
**The existing chat retriever still uses Chroma and FastEmbed.** It does not read
|
||||||
|
uploaded PostgreSQL chunks. Scoped pgvector search and authorized knowledge
|
||||||
|
selection are the next milestone: only ready, active, undeleted documents
|
||||||
|
authorized for the caller may be searched. Publication deliberately leaves
|
||||||
|
documents inactive. Do not set is_active manually to connect the two pipelines.
|
||||||
|
|
||||||
|
## Setup and configuration
|
||||||
|
|
||||||
|
From the repository root, install the ingestion/test dependencies:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
python -m venv .venv
|
||||||
|
.venv/Scripts/python -m pip install -e ".[test]"
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Use PostgreSQL with pgvector available. Configure the deployment through .env
|
||||||
|
or INGEST_ environment variables; see [.env.example](../../.env.example) and
|
||||||
|
[foundation setup](ingestion-foundation-setup.md). Set INGEST_DATABASE_URL using
|
||||||
|
postgresql+psycopg://, and explicitly select INGEST_EMBEDDING_PROVIDER,
|
||||||
|
INGEST_EMBEDDING_ENDPOINT, INGEST_EMBEDDING_MODEL and INGEST_EMBEDDING_DIMENSIONS.
|
||||||
|
Supply INGEST_EMBEDDING_API_KEY separately on the server. Specify
|
||||||
|
INGEST_EMBEDDING_LIMITS as JSON with unit, max_input_units, max_batch_units and
|
||||||
|
max_batch_inputs. Token units also require an explicit compatible tokenizer and
|
||||||
|
the embedding extra (pip install -e ".[embedding]"). Do not assume a provider's
|
||||||
|
limits or supported dimension.
|
||||||
|
|
||||||
|
Set INGEST_ORIGINAL_DIRECTORY and INGEST_EXTRACTION_DIRECTORY to separate,
|
||||||
|
non-nested writable directories. Originals are immutable independent uploads;
|
||||||
|
extraction candidates have their own namespace. Preserve both across worker
|
||||||
|
restarts. Storage, deployment credentials and frozen document processing profiles
|
||||||
|
must remain compatible. Vision work additionally requires the explicit
|
||||||
|
INGEST_VISION_PROVIDER, ENDPOINT, MODEL and API_KEY settings. PDF/image output
|
||||||
|
requires inspection; factual FAQ inclusion has its own authority decision.
|
||||||
|
|
||||||
|
## Migrate and bootstrap
|
||||||
|
|
||||||
|
Apply head with the chosen embedding identity and dimension before importing:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/alembic upgrade head
|
||||||
|
.venv/Scripts/alembic current
|
||||||
|
.venv/Scripts/python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from organization documents."
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Bootstrap prompts for the initial password without echo and returns organization
|
||||||
|
and administrator IDs. It refuses an existing organization. Automation may use
|
||||||
|
--password-stdin through a securely supplied pipe. These commands are trusted
|
||||||
|
operator tools, not HTTP authentication. Applied revisions 0001-0003 remain
|
||||||
|
immutable; no Phase 6 schema migration is needed. Model/profile changes do not
|
||||||
|
silently alter vector(D) or rewrite existing processing profiles.
|
||||||
|
|
||||||
|
## Import, status, worker and retry
|
||||||
|
|
||||||
|
Use the returned administrator ID. Generate a UUID idempotency key once per
|
||||||
|
intended import and retain it for replay; the same key and payload returns the
|
||||||
|
same document. A new key creates an independent document even for identical bytes.
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m app.ingest import <approved-file> --administrator-id <admin-id> --idempotency-key <import-uuid>
|
||||||
|
.venv/Scripts/python -m app.ingest status <document-id> --administrator-id <admin-id>
|
||||||
|
.venv/Scripts/python -m app.worker --once
|
||||||
|
.venv/Scripts/python -m app.worker
|
||||||
|
.venv/Scripts/python -m app.ingest retry <document-id> --administrator-id <admin-id> --idempotency-key <retry-uuid>
|
||||||
|
.venv/Scripts/python -m app.ingest reconcile
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Replace angle-bracket placeholders. --once processes at most one eligible job;
|
||||||
|
an empty queue exits successfully. Continuous polling stops on Ctrl+C. A handled
|
||||||
|
job failure can also exit successfully: use status to inspect the durable outcome.
|
||||||
|
A successful publication has ready document, succeeded job, exact chunk_count,
|
||||||
|
ready_at and is_active=false. Before publication there are zero chunk rows, even
|
||||||
|
when some embedding batches have already completed.
|
||||||
|
|
||||||
|
Manual retry requires an eligible failed document/job, enabled administrator and
|
||||||
|
valid original. It preserves document/job IDs, resets attempts and increments
|
||||||
|
retry_generation once per key. Replaying that key returns the saved receipt,
|
||||||
|
including after successful completion. Pending/rejected review evidence cannot
|
||||||
|
be bypassed with retry. Use the trusted review services described in
|
||||||
|
[worker operations](worker-orchestration.md); authenticated D06/D07 HTTP transport
|
||||||
|
still awaits identity/organization/Origin/CSRF integration.
|
||||||
|
|
||||||
|
After interruption, allow the old lease to expire and restart the worker.
|
||||||
|
Complete attached extraction may be reused after validation. Embedding batches
|
||||||
|
restart from scratch; there are no batch checkpoints. An expired/stale claim
|
||||||
|
cannot publish. Publication rolls back chunk/state changes together; a committed
|
||||||
|
ready document is never republished, including after a lost commit acknowledgement.
|
||||||
|
|
||||||
|
Reconcile is report-only: missing originals, orphan originals, temporary files
|
||||||
|
and extraction inventory. It never deletes files, attaches orphan evidence,
|
||||||
|
requeues jobs or repairs durable state. A missing original must be investigated;
|
||||||
|
do not replace an original in place or manually change profile metadata.
|
||||||
|
|
||||||
|
## Worker diagnostics
|
||||||
|
|
||||||
|
The worker CLI emits JSON lines on stderr for claimed jobs, stage starts
|
||||||
|
(extract, chunk, embed, publish), periodic heartbeat renewal, success, review
|
||||||
|
requirements, ownership loss and error categories. Each job diagnostic carries
|
||||||
|
document_id, job_id, stage and category. No document text, filename, storage path,
|
||||||
|
endpoint, API key, claim token, raw exception or provider response is logged.
|
||||||
|
The library logger is app.modules.documents.worker; the CLI installs/removes its
|
||||||
|
handler without changing application-wide logging.
|
||||||
|
|
||||||
|
heartbeat/renewed confirms a successful fenced lease renewal during extraction
|
||||||
|
and provider waits. heartbeat/ownership_unavailable means renewal failed and the
|
||||||
|
worker cannot assume ownership. At terminal completion a concurrent heartbeat
|
||||||
|
may observe the released claim; the final publish/succeeded event and durable
|
||||||
|
status establish completion. Error categories distinguish embedding_error,
|
||||||
|
extraction_error, storage_error, validation_error, interrupted and ownership_lost.
|
||||||
|
The status CLI supplies durable error codes/stage. Inspect it after an interrupted
|
||||||
|
event before taking action; uncertain commits are resolved from database state.
|
||||||
|
Poll/heartbeat/lease/backoff limits remain documented in worker operations.
|
||||||
|
|
||||||
|
## Deterministic PostgreSQL acceptance
|
||||||
|
|
||||||
|
Ordinary tests are provider-free and do not require PostgreSQL:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
|
||||||
|
~~~
|
||||||
|
|
||||||
|
For actual database acceptance, start a fresh dedicated test database whose name
|
||||||
|
ends in _test. For example:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
docker run --name rag-phase6-test -e POSTGRES_PASSWORD=test-only -e POSTGRES_DB=rag_phase6_test -p 127.0.0.1:55436:5432 -d pgvector/pgvector:pg16
|
||||||
|
docker exec rag-phase6-test pg_isready -U postgres -d rag_phase6_test
|
||||||
|
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:test-only@127.0.0.1:55436/rag_phase6_test"
|
||||||
|
.venv/Scripts/python -m tests.postgres_prerequisites
|
||||||
|
.venv/Scripts/python -m pytest tests/integration/test_phase6.py -q --require-postgres --tb=short
|
||||||
|
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Wait for readiness. Missing TEST_DATABASE_URL fails --require-postgres acceptance.
|
||||||
|
The fixture uses disposable schemas without public fallback, migrates head, checks
|
||||||
|
relation scope on every connection and requires vector in test_vector. It refuses
|
||||||
|
a pre-existing vector extension in another schema instead of relocating it.
|
||||||
|
Tests use temporary original/extraction directories and real Markdown/DOCX
|
||||||
|
extractors with hash-derived, three-dimensional fake embeddings. They make no
|
||||||
|
provider requests and use no production database or corpus.
|
||||||
|
|
||||||
|
The new tests observe each incomplete batch from an independent database
|
||||||
|
connection and read completion/chunk count in one SQL snapshot. They verify exact
|
||||||
|
row count, contiguous ordinals, faithful text/locations, frozen profile, dimension
|
||||||
|
and deterministic vector correspondence, ready/succeeded state and inactivity.
|
||||||
|
Literal fixture evidence supplies independent expected rows, including 25 bar,
|
||||||
|
40 liters per minute, 15 Nm, temperature/blocked-inlet conditions, negation and
|
||||||
|
exceptions. A shared-chunker mutation of 25 bar to 26 bar is detected for both
|
||||||
|
Markdown and DOCX, even when implementation-derived drafts agree.
|
||||||
|
Publication barriers pause after every chunk has been inserted and again after
|
||||||
|
document/job completion writes, before commit. An independent connection reads
|
||||||
|
rows and completion together in one SQL snapshot: zero chunks and no completion
|
||||||
|
are visible at either barrier; all expected rows and ready/succeeded state are
|
||||||
|
visible after commit. Event waits are bounded and released during cleanup;
|
||||||
|
these checks use no sleep-based race assertions.
|
||||||
|
They exercise final-batch failure, duplicate-request replay versus independent
|
||||||
|
imports, manual retry/replay, pre-publication and post-commit interruption,
|
||||||
|
expired ownership, deletion before publication, missing originals/reconciliation
|
||||||
|
and heartbeat reporting during a blocked batch. Existing Phase 5 acceptance adds
|
||||||
|
actual lock/lease races, partial-insert rollback, ambiguous commit outcomes and
|
||||||
|
inspected PDF/image/FAQ resume. A simulated crash throws at the named boundary;
|
||||||
|
the suite does not claim operating-system power-loss or storage-durability proof.
|
||||||
|
|
||||||
|
After acceptance, remove only the test container you created and its anonymous
|
||||||
|
volume: docker rm -f -v rag-phase6-test. Never clean unrelated services.
|
||||||
|
|
||||||
|
## Separate opt-in real-provider smoke
|
||||||
|
|
||||||
|
This command is outside pytest and never migrates, imports, publishes or activates
|
||||||
|
documents. It requires explicit approved file paths and authorization to send
|
||||||
|
their contents to configured embedding/vision providers. It does not infer the
|
||||||
|
sample corpus or load .env. Export all six required environment settings:
|
||||||
|
INGEST_EMBEDDING_PROVIDER, ENDPOINT, MODEL, DIMENSIONS, API_KEY and LIMITS (each
|
||||||
|
with the INGEST_EMBEDDING_ prefix). Supply vision configuration if needed.
|
||||||
|
Install the embedding extra when the selected policy uses tiktoken token counts.
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m app.ingestion_smoke --corpus <approved-file> --corpus <another-approved-file> --allow-provider-calls
|
||||||
|
~~~
|
||||||
|
|
||||||
|
The first JSON result reports provider_compatibility from a small embedding
|
||||||
|
probe: endpoint/model/dimension, vector validity and configured request-policy
|
||||||
|
compatibility. The probe is a public one-character ASCII value from a bounded
|
||||||
|
candidate set, measured against the actual input/batch policy and the configured
|
||||||
|
compatible token counter. A valid one-byte input and batch policy is supported.
|
||||||
|
No limits or frozen profile are relaxed and no unreviewed corpus content is used
|
||||||
|
as a substitute probe.
|
||||||
|
|
||||||
|
Local configuration failures return configuration=failed with the redacted
|
||||||
|
invalid_configuration category. Local probe/counter/staging validation failures
|
||||||
|
report provider_compatibility=not_run and probe_validation_failed. After adapter
|
||||||
|
invocation, failed checks report provider_error (classified transport/provider
|
||||||
|
error), provider_response_invalid (returned vectors rejected by staging), or
|
||||||
|
provider_check_failed (adapter invocation failed). The last category does not
|
||||||
|
prove a remote request was transmitted; use provider diagnostics separately.
|
||||||
|
No raw exception, response, counter identity or credentials are printed. This is not semantic retrieval quality or persisted-database
|
||||||
|
compatibility. Each subsequent result identifies corpus_index and separately
|
||||||
|
reports extraction_quality, factual_authority, corpus_embedding and semantic_quality. Automated
|
||||||
|
extraction checks do not establish Persian OCR accuracy, table completeness,
|
||||||
|
numeric/negation fidelity or factual authority; semantic_quality remains
|
||||||
|
manual_review_required. Review-required PDF/image/FAQ content is reported without
|
||||||
|
bypassing review or embedding unapproved content. Factual authority can require
|
||||||
|
review even when faithful extraction passes; failed provider compatibility skips
|
||||||
|
corpus embeddings while continuing independent extraction checks. Nonzero exit means invalid
|
||||||
|
configuration, failed compatibility, failed input/extraction/embedding, or a
|
||||||
|
review gate. Reports omit contents, paths, secrets and raw errors. This transient
|
||||||
|
smoke command does not retain or approve review candidates.
|
||||||
|
|
||||||
|
Use the durable operator import/review workflow to inspect exact output against
|
||||||
|
the approved originals and record extraction quality separately from provider
|
||||||
|
compatibility. Real-provider results require an approved corpus, funded model
|
||||||
|
access and independently recorded quality decisions. Fake-provider acceptance
|
||||||
|
does not establish any of them. No real-provider call is part of ordinary tests.
|
||||||
|
|
||||||
|
## Executed Phase 6 acceptance (2026-10-07)
|
||||||
|
|
||||||
|
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
|
||||||
|
**1076 passed, 3 skipped, 204 deselected**. The three skips are existing
|
||||||
|
Windows symlink-privilege checks. No real providers were called.
|
||||||
|
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
|
||||||
|
**204 passed, 1077 deselected**, no failures/errors/skips.
|
||||||
|
- Final worker/publication rerun:
|
||||||
|
.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py -q --require-postgres --tb=short:
|
||||||
|
**87 passed**. This verifies the final exact row/source assertions and reporting
|
||||||
|
changes after the full database run.
|
||||||
|
- Isolated container rag-phase6-20261007, database rag_phase6_test,
|
||||||
|
127.0.0.1:54936; prerequisite command passed on PostgreSQL **16.15** /
|
||||||
|
pgvector **0.8.7**. Only disposable test schemas were migrated/written.
|
||||||
|
- pip check passed. git diff --check passed; separate AST/whitespace checks
|
||||||
|
covered all seven affected Python files and the new handoff guide, whose local
|
||||||
|
links passed. Inherited README whitespace was preserved.
|
||||||
|
- Applied 0001/0002 SHA-256 values remain
|
||||||
|
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567 and
|
||||||
|
0BFFBA5014A136E3FD251DB8870395FAA056A6277B317506CCF91812C6748ECE.
|
||||||
|
No migration was changed.
|
||||||
|
- Post-test inspection found zero leftover disposable schemas and zero public
|
||||||
|
tables. The verified Phase 6 container and its anonymous volume were removed;
|
||||||
|
the three pre-existing containers were preserved.
|
||||||
|
|
||||||
|
Real-provider smoke, production model/tokenizer compatibility, Persian
|
||||||
|
extraction/semantic quality, HTTP/browser and Live acceptance were not run.
|
||||||
|
The separate opt-in command is available; successful deterministic/database
|
||||||
|
acceptance does not certify those gates.
|
||||||
|
|
||||||
|
## Phase 6 findings repair acceptance (2026-10-07)
|
||||||
|
|
||||||
|
The current repair changes app/ingestion_smoke.py, tests/unit/test_phase6.py and
|
||||||
|
tests/integration/test_phase6.py, plus current status/operator documentation.
|
||||||
|
Production publication code, all applied migrations, immutable originals,
|
||||||
|
frozen profiles and unrelated mixed working-tree changes are unchanged.
|
||||||
|
|
||||||
|
The harmless compatibility probe uses a bounded set of one-byte ASCII candidates
|
||||||
|
and measures the actual frozen input/batch policy with the compatible token
|
||||||
|
counter. Restrictive byte/token policies and one-input batches now succeed;
|
||||||
|
the one-byte regression reaches the hosted adapter's fake HTTP request boundary.
|
||||||
|
Local probe/counter/staging failures are reported as not_run/probe_validation_failed,
|
||||||
|
separately from adapter/provider failures and invalid returned vectors. No real
|
||||||
|
provider is contacted by any ordinary test.
|
||||||
|
|
||||||
|
Independent literal Markdown/DOCX evidence expects exactly three rows and their
|
||||||
|
original paragraph locators. Exact text, ordinals, vector correspondence, profile,
|
||||||
|
ready/succeeded state and inactivity are checked together. Critical evidence
|
||||||
|
includes 25 bar, 60 C, 40 liters per minute, 30 days, 15 Nm, conditions, negation
|
||||||
|
and exceptions. A shared-chunker 25-to-26 bar mutation is detected for both formats,
|
||||||
|
even though implementation-derived expected and actual drafts otherwise agree.
|
||||||
|
The originals are not changed by this mutation test.
|
||||||
|
|
||||||
|
Deterministic event barriers pause production publication after all chunk
|
||||||
|
inserts and after both completion updates, before commit. An independent
|
||||||
|
PostgreSQL connection observes rows/count and document/job state in one SQL
|
||||||
|
snapshot at both barriers: zero visible rows and no ready/succeeded state.
|
||||||
|
After commit the entire expected publication is visible in one snapshot.
|
||||||
|
All event/future waits are bounded; cleanup releases both barriers and removes
|
||||||
|
the listener. There are no sleep-based assertions in the new visibility tests.
|
||||||
|
The existing Phase 5 rollback, claim/lease fencing and ambiguous-commit coverage
|
||||||
|
still passes; no production publication defect was exposed.
|
||||||
|
|
||||||
|
Reproduction before fixes:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_phase6.py -k "restrictive or one_byte or local_probe or bad_provider_vectors" -q --tb=short
|
||||||
|
# 9 failed, 12 deselected: restrictive-policy rejection and insufficient error categories.
|
||||||
|
.venv/Scripts/python -m pytest tests/integration/test_phase6.py -k shared_chunker -q --require-postgres --tb=short
|
||||||
|
# 2 failed, 10 deselected: the shared-chunker numeric mutation was not detected.
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Final executed checks from the repository root:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:repair-test-only@127.0.0.1:54937/rag_phase6_repair_test"
|
||||||
|
.venv/Scripts/python -m pytest tests/unit/test_phase6.py tests/integration/test_phase6.py -q --require-postgres --tb=short
|
||||||
|
# 34 passed.
|
||||||
|
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
|
||||||
|
# 1086 passed, 3 skipped, 208 deselected.
|
||||||
|
.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py -q --require-postgres --tb=short
|
||||||
|
# 91 passed.
|
||||||
|
.venv/Scripts/python -m tests.postgres_prerequisites
|
||||||
|
# Passed: PostgreSQL 16.15, pgvector 0.8.7.
|
||||||
|
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
|
||||||
|
# 208 passed, 1089 deselected; no failures/errors/skips.
|
||||||
|
.venv/Scripts/python -m pip check
|
||||||
|
# No broken requirements found.
|
||||||
|
git diff --check
|
||||||
|
# Passed (existing LF/CRLF notices only).
|
||||||
|
~~~
|
||||||
|
|
||||||
|
The three ordinary-suite skips are existing Windows symlink-privilege checks.
|
||||||
|
Database acceptance used only the fresh rag-phase6-repair-20261007 container and
|
||||||
|
rag_phase6_repair_test database, disposable scoped schemas and temporary file
|
||||||
|
directories. Missing PostgreSQL configuration is not acceptance. Separate
|
||||||
|
Python AST/whitespace and documentation local-link checks covered affected
|
||||||
|
untracked files. Baseline SHA-256 comparisons confirm preservation of unrelated
|
||||||
|
files and applied migrations; publication code was not changed.
|
||||||
|
|
||||||
|
Earlier exact validation records above remain historical evidence. Phase 5
|
||||||
|
worker/review/resume backend services and Phase 6 validation/handoff are
|
||||||
|
implemented. Authenticated D06/D07 transport still requires trusted
|
||||||
|
identity/organization/Origin/CSRF integration. Chroma still serves existing chat;
|
||||||
|
scoped pgvector search and authorized selection are next. Real-provider smoke,
|
||||||
|
funded production model/tokenizer compatibility, Persian extraction/semantic
|
||||||
|
quality, browser integration and Live acceptance were not run or certified.
|
||||||
|
|
||||||
|
Repair cleanup: inspection found zero leftover disposable schemas and zero public
|
||||||
|
tables. Only the verified rag-phase6-repair-20261007 container and its anonymous
|
||||||
|
volume were removed; all three pre-existing containers were preserved.
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
# Durable ingestion worker
|
||||||
|
|
||||||
|
Phase 5 adds the worker, complete-extraction attachment, atomic publication and
|
||||||
|
trusted operator retry to the existing Phases 1-4 services. Extended Phase 5 now
|
||||||
|
retains exact review candidates, records evidence-bound decisions, resumes approved
|
||||||
|
output and applies whole-group factual FAQ inclusion. D06/D07 backend services
|
||||||
|
are implemented; their HTTP transport remains blocked on authenticated admin/session,
|
||||||
|
organization, Origin and CSRF integration. No unsafe public review route was added.
|
||||||
|
HTTP upload, selection and uploaded-document search remain separate work.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
Use the configuration and isolated database instructions in
|
||||||
|
[foundation setup](ingestion-foundation-setup.md). Apply the forward migration:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/alembic upgrade head
|
||||||
|
.venv/Scripts/python -m app.worker --once
|
||||||
|
.venv/Scripts/python -m app.worker
|
||||||
|
~~~
|
||||||
|
|
||||||
|
--once processes at most one eligible queued/expired job; an empty poll exits
|
||||||
|
successfully. Continuous polling uses INGEST_POLL_SECONDS and exits on Ctrl+C.
|
||||||
|
A job failure is reported durably through the existing status CLI. Unexpected
|
||||||
|
database/programming errors are redacted on stderr and leave ownership for lease
|
||||||
|
recovery. A worker restart always starts extraction/staging again; there are no
|
||||||
|
embedding batch checkpoints.
|
||||||
|
|
||||||
|
Worker configuration already present in IngestionSettings controls heartbeat,
|
||||||
|
lease, automatic attempts and capped retry backoff with jitter. The serial worker
|
||||||
|
uses an independent heartbeat thread throughout extraction, storage validation and
|
||||||
|
provider waits. Claim transactions lock only jobs with SKIP LOCKED and commit
|
||||||
|
quickly. All later transactions lock document then job and verify the current
|
||||||
|
token and unexpired database clock lease, including a final conditional write.
|
||||||
|
Recovery claims increment attempts; an exhausted recovery claim terminally fails
|
||||||
|
without running extraction or providers. Operational durations are validated before
|
||||||
|
threads/claims and before lease/retry SQL: at least one PostgreSQL microsecond and
|
||||||
|
at most min(threading.TIMEOUT_MAX, 2147483.647 seconds). Heartbeat < lease and
|
||||||
|
retry-base <= retry-cap remain required. Nonfinite and overflow-prone finite values
|
||||||
|
fail with redacted errors. These bounds establish representability, not capacity.
|
||||||
|
|
||||||
|
Providers use the document's frozen extraction/embedding identities and request
|
||||||
|
limits, with current server-side credentials. Vision is constructed lazily from the
|
||||||
|
frozen profile when actually needed; its secret is checked independently of current
|
||||||
|
model/provider defaults. Direct extraction needs no unused vision credentials.
|
||||||
|
Changing deployment defaults does not rewrite old profiles. Token-unit embedding profiles require the optional
|
||||||
|
embedding extra and a supported explicit tiktoken:<encoding> identity. Legacy
|
||||||
|
extractor profiles fail explicitly rather than being interpreted as page-block OCR.
|
||||||
|
|
||||||
|
## Complete extraction and publication
|
||||||
|
|
||||||
|
0002_worker_artifact adds documents.extraction_state JSONB with complete_artifact
|
||||||
|
holding a trusted candidate key, digest, document/original and extraction identity.
|
||||||
|
Forward 0003_extraction_review adds the extraction_review action and mandatory
|
||||||
|
actor/target/key/hash/saved-response audit check. Both 0001 and 0002 remain immutable.
|
||||||
|
Extended workers/review services require head 0003, the extraction_state column and
|
||||||
|
review audit/replay checks. Foundation intake/bootstrap still accepts 0001/0002. Existing table and embedding profile identities are retained.
|
||||||
|
|
||||||
|
Artifacts remain bounded files in the separate, non-nested extraction namespace,
|
||||||
|
created atomically without replacement. Attachment validates the candidate digest,
|
||||||
|
original checksum, frozen extraction identity, completeness, order, source coverage
|
||||||
|
and warnings outside long transactions, then checks current ownership and immutable
|
||||||
|
metadata under locks. An existing successful attachment is never replaced.
|
||||||
|
Inventory scanning does not grant attachment/reuse authority.
|
||||||
|
|
||||||
|
Recovery accepts only the database-attached complete artifact, never an orphan
|
||||||
|
discovered by scanning. Reuse revalidates bytes and source coverage. Direct text/DOCX
|
||||||
|
coverage is compared with deterministic direct extraction; PDF coverage requires
|
||||||
|
all original pages and reviewed output; images require reviewed evidence. These
|
||||||
|
checks do not repeat OCR. Chunk/embedding changes alone do not invalidate the
|
||||||
|
extraction identity. Corrupt, partial or unreviewed output cannot reach publication.
|
||||||
|
|
||||||
|
Embedding batches check ownership before and after the provider response. Full
|
||||||
|
staging is validated against faithful chunks derived from the trusted extraction.
|
||||||
|
Publication verifies source/profile compatibility, ownership, lease, eligible
|
||||||
|
undeleted state and empty existing chunks, then inserts every chunk and commits
|
||||||
|
ready/inactive document plus succeeded job together. Failure or mid-publication
|
||||||
|
lease loss rolls back all chunk/state writes. Interrupted commit acknowledgement
|
||||||
|
is reconciled through a fresh durable-state read; an unreadable outcome leaves
|
||||||
|
recovery to a later poll. A committed ready document is never republished.
|
||||||
|
|
||||||
|
## Retry and reconciliation
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m app.ingest retry <document-id> --administrator-id <admin-id> --idempotency-key <uuid>
|
||||||
|
.venv/Scripts/python -m app.ingest reconcile
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Retry requires a currently enabled administrator and an eligible failed,
|
||||||
|
undeleted document/job with a valid retained original. It reuses both IDs, resets
|
||||||
|
attempts, increments retry_generation once per key and stores the audit/replay
|
||||||
|
response in the same transaction. Replay is resolved after authorization and before
|
||||||
|
new eligibility/storage checks. Review-required jobs requeue only after all current
|
||||||
|
evidence-bound approvals exist and retained source/candidates validate. A rejection
|
||||||
|
stays failed and returns DOCUMENT_NOT_RETRYABLE; pending decisions return
|
||||||
|
EXTRACTION_REVIEW_PENDING. Approval itself never queues, activates or marks ready. Ready/running/removed documents cannot be requeued.
|
||||||
|
|
||||||
|
Reconcile still compares only original keys against original references. It adds
|
||||||
|
extraction_inventory as a report of candidate/temp/unexpected entries; it never
|
||||||
|
deletes, attaches, repairs or mutates files.
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
|
||||||
|
Provider-free command:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
|
||||||
|
~~~
|
||||||
|
|
||||||
|
PostgreSQL acceptance requires a dedicated TEST_DATABASE_URL ending in _test:
|
||||||
|
|
||||||
|
~~~powershell
|
||||||
|
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
|
||||||
|
~~~
|
||||||
|
|
||||||
|
Worker regressions are in tests/unit/test_phase5.py and
|
||||||
|
tests/integration/test_phase5.py. They exercise actual PostgreSQL claims/locks,
|
||||||
|
expiry, stale/late writes, slow-call heartbeats, exhausted recovery, publication
|
||||||
|
rollback including lease loss after inserts, lost commit acknowledgement,
|
||||||
|
unreadable commit recovery, attachment races, orphan/complete-artifact recovery,
|
||||||
|
source/profile/digest/coverage/warning checks, rechunk reuse and retry replay.
|
||||||
|
Real extraction/embedding providers and Persian semantic quality are separate
|
||||||
|
validation; these tests do not establish them.
|
||||||
|
|
||||||
|
Executed on 2026-10-07: full provider-free suite **1004 passed, 3 existing Windows
|
||||||
|
symlink privilege skips**; full PostgreSQL suite **160 passed, no skips**; final
|
||||||
|
pointer-validation rerun **43 worker database tests passed**. The isolated
|
||||||
|
rag_phase5_test container used PostgreSQL 16.15 / pgvector 0.8.7 on localhost:54933.
|
||||||
|
Inspection found zero leftover disposable schemas and public tables. Dependency
|
||||||
|
and whitespace checks passed. The initial migration checksum is unchanged.
|
||||||
|
|
||||||
|
## Retained review and factual authority
|
||||||
|
|
||||||
|
ReviewRequired is handled separately from ordinary processing errors. The worker
|
||||||
|
writes bounded immutable .review.json files containing exact image/blocks, source
|
||||||
|
and frozen extraction identity, locator, reasons and recomputed evidence digest.
|
||||||
|
It attaches only trusted key/digest references and progress under the current token
|
||||||
|
and valid lease, then atomically fails document/job with EXTRACTION_REVIEW_REQUIRED
|
||||||
|
and releases ownership. Zero chunks are published. Partial review candidates are
|
||||||
|
never complete artifacts and orphan inventory never grants trust.
|
||||||
|
|
||||||
|
SqlReviewRepository exposes read, preview and decide as trusted backend services.
|
||||||
|
They require AdministratorIdentity from a trusted authentication/operator boundary
|
||||||
|
and independently validate current enabled admin and organization in PostgreSQL.
|
||||||
|
Decisions recheck authorization under document-before-job locks; no client reviewer,
|
||||||
|
block text, path, profile or provider arguments are accepted. ReviewDecision rejects extra
|
||||||
|
fields, duplicate checks/groups, invalid digests and empty/invalid notes. Notes are
|
||||||
|
trimmed and limited to 2000 characters; required checks are returned by read.
|
||||||
|
The service reports pending candidates with bounded pagination (1-20 items),
|
||||||
|
returns no raw storage keys, and provides preview bytes/MIME through preview.
|
||||||
|
preview_path is null until an authenticated HTTP adapter supplies the real route.
|
||||||
|
Read/preview recheck authorization, source and attached evidence before output.
|
||||||
|
|
||||||
|
Decision plus extraction_review audit receipt commit together. Authorized replay
|
||||||
|
is resolved before new eligibility/source checks; changed payload conflicts.
|
||||||
|
Canonical hashes include digest, decision, sorted checks/exclusions and note.
|
||||||
|
A new key cannot replace a decided candidate. Stale evidence/source/profile is
|
||||||
|
rejected. Rejection leaves the document failed; approval does not enqueue it.
|
||||||
|
|
||||||
|
After all current approvals, the existing retry CLI requeues the same document/job.
|
||||||
|
The extractor looks up the exact approved retained output by source location before
|
||||||
|
any OCR call. Each page and each provider result checks ownership. A later page
|
||||||
|
can require another review while earlier approved pages remain reusable across
|
||||||
|
restart. Source/rendering, candidate digest, profile and required checks are
|
||||||
|
revalidated; approval cannot transfer to a different response. Only full approved
|
||||||
|
coverage can assemble a validated complete extraction artifact.
|
||||||
|
|
||||||
|
For FAQs, extract_for_review is an explicit faithful-retention boundary: it may
|
||||||
|
retain placeholder text only inside whole Q&A source groups, including associated
|
||||||
|
context. Standalone extract/chunk defaults retain their existing protections.
|
||||||
|
Complete faithful extraction stays attached independently of factual authority.
|
||||||
|
A factual_corpus candidate binds the exact artifact digest and existing Q&A IDs.
|
||||||
|
Approval records reviewer and whole excluded group IDs separately; required checks
|
||||||
|
are factual_authority, whole_pair_association, behavioral_separation, placeholders.
|
||||||
|
Unknown groups, an empty eligible set or included placeholders are rejected.
|
||||||
|
Excluded behavioral/placeholder Q&A and their associated context remain in the
|
||||||
|
artifact/original and never enter chunks. prepare_chunks is shared by worker
|
||||||
|
staging and publication validation; it preserves complete pairs/locators and
|
||||||
|
contiguous chunk ordinals. Publication rechecks the manifest and full retained
|
||||||
|
state under its original ownership/lease/atomicity guarantees.
|
||||||
|
|
||||||
|
The repository currently has no authenticated HTTP admin/session/Origin/CSRF
|
||||||
|
boundary. Therefore D06/D07 routes and authenticated preview endpoints are not
|
||||||
|
exposed, and users cannot yet complete this flow through a browser. Integrate the
|
||||||
|
services after that prerequisite exists; a request-supplied administrator UUID is
|
||||||
|
not a replacement. Do not treat backend acceptance as full extended Phase 5 or
|
||||||
|
Live MVP completion.
|
||||||
|
|
||||||
|
## Extended Phase 5 backend repair acceptance (2026-10-07)
|
||||||
|
|
||||||
|
Implemented durable partial review retention, current-claim attachment and progress,
|
||||||
|
failed ownership release, trusted administrator read/preview/decide services,
|
||||||
|
evidence-bound atomic audit decisions/replay, exact approved-output restart/resume,
|
||||||
|
and whole-group factual authority/inclusion. Worker staging and publication use
|
||||||
|
one validated preparation boundary. Standalone extraction/chunking protections,
|
||||||
|
immutable complete artifacts, original files, atomic publication and ambiguous
|
||||||
|
commit recovery remain enabled. Vision now constructs lazily from frozen profile
|
||||||
|
identity/policy with independently checked current server credentials. Operational
|
||||||
|
poll/heartbeat/lease/retry durations reject runtime/SQL-unrepresentable values.
|
||||||
|
|
||||||
|
Affected application sources: app/worker.py; modules/documents/{worker,extraction,
|
||||||
|
chunking,settings,review,operational_limits}.py; infrastructure/{database,
|
||||||
|
worker_repository,extraction_candidates,review_candidates,review_repository}.py.
|
||||||
|
New forward migration: migrations/versions/0003_extraction_review.py. Tests:
|
||||||
|
unit/test_phase5_review.py, integration/test_phase5.py and unit/test_imports.py.
|
||||||
|
Current README, worker guide, plan and reference-map inventory describe these changes.
|
||||||
|
|
||||||
|
Exact final checks:
|
||||||
|
|
||||||
|
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
|
||||||
|
**1050 passed, 3 skipped, 186 deselected**. Skips are existing Windows symlink
|
||||||
|
privilege cases. No real providers were called.
|
||||||
|
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
|
||||||
|
**186 passed, 1053 deselected**, no failures/errors/skips. This includes all
|
||||||
|
**69 worker/review database cases**, compared with the previous 43 worker cases.
|
||||||
|
- Dedicated container rag-phase5-review-20261007; database rag_phase5_review_test;
|
||||||
|
localhost:54934; PostgreSQL **16.15**, pgvector **0.8.7**. Only disposable test
|
||||||
|
schemas were migrated/written. No production database was migrated or modified.
|
||||||
|
- .venv/Scripts/python -m pip check: no broken requirements.
|
||||||
|
- git diff --check and separate AST/whitespace checks for all 16 affected Python
|
||||||
|
files passed. Applied revision 0001 SHA-256 remains
|
||||||
|
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567;
|
||||||
|
applied revision 0002 SHA-256 remains
|
||||||
|
0BFFBA5014A136E3FD251DB8870395FAA056A6277B317506CCF91812C6748ECE.
|
||||||
|
|
||||||
|
D06/D07 HTTP transport and authenticated preview still depend on the absent
|
||||||
|
administrator/session/organization/Origin/CSRF boundary. No unsafe route trusting
|
||||||
|
a request administrator ID was introduced. Full extended Phase 5 is **not complete**
|
||||||
|
until that integration exists. Real providers, Persian OCR quality, semantic factual
|
||||||
|
authority, browser integration and Live release acceptance were not validated.
|
||||||
|
|
||||||
|
|
||||||
|
## Remaining backend defect repairs (2026-10-07)
|
||||||
|
|
||||||
|
Factual preparation now preserves governing context through explicit Markdown
|
||||||
|
heading ancestry and existing whole-group relationships. Shared ancestor
|
||||||
|
conditions are repeated with each affected pair; section-specific conditions,
|
||||||
|
negation and exceptions remain with their answers and actual source locators.
|
||||||
|
Excluded pairs and their exclusive context never enter chunks. Unheaded
|
||||||
|
preambles, detached prose after pairs, unresolved/noncontiguous groups and
|
||||||
|
unsupported context hierarchy fail visibly before filtering. Context with no
|
||||||
|
associated pair is not silently indexed. Oversized atomic drafts still fail
|
||||||
|
rather than splitting off conditions. Standalone chunking protections remain
|
||||||
|
enabled. DOCX/visual context already inside a whole group stays supported;
|
||||||
|
unassociated context without a supported explicit heading hierarchy fails.
|
||||||
|
|
||||||
|
Factual review now exposes governing context once in original source order.
|
||||||
|
New candidates include it; existing immutable candidates with only grouped
|
||||||
|
blocks remain readable by deriving context from their already digest-bound
|
||||||
|
complete artifact. Candidate files, evidence/group identities, decisions,
|
||||||
|
faithful artifacts and originals are never rewritten. Worker preparation and
|
||||||
|
publication use the same context-preserving drafts; mismatched staging is rejected
|
||||||
|
without chunk/status changes.
|
||||||
|
|
||||||
|
Approved extraction notes are recorded once per location in the bounded envelope
|
||||||
|
review_annotations collection, with evidence digest, reviewer and checked items.
|
||||||
|
They are not block warnings or chunk text. Existing retained candidate/decision
|
||||||
|
shapes still resume exact approved OCR. Original provider/evidence warnings stay
|
||||||
|
strict: genuine unreadability still fails. Note limits and full artifact byte
|
||||||
|
limits include the annotations. This optional file field requires no database
|
||||||
|
migration; applied revisions 0001, 0002 and 0003 remain unchanged.
|
||||||
|
|
||||||
|
Complete-artifact attachment now compares the existing pointer with the validated
|
||||||
|
candidate under document-before-job locks. Identical attachment preserves review,
|
||||||
|
factual and progress metadata. A conflicting pointer, expired lease or stale token
|
||||||
|
cannot attach or replace anything.
|
||||||
|
|
||||||
|
Reproductions before fixes: eligibility lost its heading/condition; the approved
|
||||||
|
English note "No unreadable regions; checked all fields." failed source quality;
|
||||||
|
real PostgreSQL identical attachment raised NameError for undefined state.
|
||||||
|
Regression sources: tests/unit/test_phase5_repairs.py and the expanded
|
||||||
|
tests/integration/test_phase5.py. Tests use fake providers only.
|
||||||
|
|
||||||
|
Verified checks for this repair:
|
||||||
|
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
|
||||||
|
**1064 passed, 3 skipped, 196 deselected** (52.49 seconds).
|
||||||
|
The three existing skips are Windows symlink privilege checks.
|
||||||
|
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
|
||||||
|
**196 passed, 1067 deselected**, zero failures/errors/skips (128.54 seconds).
|
||||||
|
Includes 79 worker/review cases and 10 new database regressions.
|
||||||
|
- Dedicated rag-phase5-context-20261007 container, rag_phase5_context_test
|
||||||
|
database on 127.0.0.1:54935; PostgreSQL 16.15 / pgvector 0.8.7.
|
||||||
|
Only disposable isolated test schemas were written; no production DB access.
|
||||||
|
- pip check, git diff --check, and AST/whitespace checks of the nine affected
|
||||||
|
Python files passed. No broken requirements.
|
||||||
|
- All three applied migrations and unrelated baseline files remain unchanged.
|
||||||
|
|
||||||
|
Affected sources: app/modules/documents/{chunking,extraction,review,types}.py;
|
||||||
|
app/infrastructure/{review_candidates,review_repository,worker_repository}.py;
|
||||||
|
tests/unit/test_phase5_repairs.py and tests/integration/test_phase5.py.
|
||||||
|
The workflow/API/database contracts and operations/reference/plan docs describe
|
||||||
|
the context-preserving review/preparation boundary and metadata distinction.
|
||||||
|
No real providers, Persian OCR quality, HTTP/browser or Live acceptance was run.
|
||||||
|
D06/D07 transport still requires trusted admin/session/organization, Origin and
|
||||||
|
CSRF integration and remains outside this repair.
|
||||||
|
|
||||||
|
## Phase 6 operator handoff
|
||||||
|
|
||||||
|
See [integration validation and operator handoff](ingestion-operator-handoff.md)
|
||||||
|
for the consolidated command sequence, JSON heartbeat/stage/error reporting,
|
||||||
|
end-to-end PostgreSQL acceptance and opt-in app.ingestion_smoke command.
|
||||||
|
Existing chat remains on Chroma; scoped pgvector search/selection is next.
|
||||||
@@ -1,214 +0,0 @@
|
|||||||
# Ingestion foundation setup
|
|
||||||
|
|
||||||
This implements ingestion pipeline phase 1 only: schema, settings, ports and trusted
|
|
||||||
initial-account bootstrap. Import/status/retry CLI, extraction, embedding adapter,
|
|
||||||
worker, publication and retrieval are subsequent phases. Prototype chat still uses
|
|
||||||
Chroma and its separate credentials.
|
|
||||||
|
|
||||||
## Install
|
|
||||||
|
|
||||||
Use Python 3.11+ and PostgreSQL with pgvector installed on the server.
|
|
||||||
The migration role needs CREATE EXTENSION privileges (or a DBA must preinstall
|
|
||||||
vector), plus schema/table creation privileges.
|
|
||||||
|
|
||||||
~~~powershell
|
|
||||||
python -m venv .venv
|
|
||||||
.venv/Scripts/python -m pip install -e ".[test]"
|
|
||||||
~~~
|
|
||||||
|
|
||||||
Optional prototype dependencies: pip install -e ".[prototype]". Foundation
|
|
||||||
installation neither imports the prototype nor downloads an embedding model.
|
|
||||||
This manifest uses bounded dependency ranges, not a reproducible lockfile.
|
|
||||||
|
|
||||||
## Configure and migrate
|
|
||||||
|
|
||||||
Copy .env.example to .env. Supply INGEST_DATABASE_URL with the
|
|
||||||
postgresql+psycopg:// scheme and explicitly select provider, endpoint, model and
|
|
||||||
dimension. No production embedding model or dimension is supplied by default.
|
|
||||||
Keep secrets out of shell history and source control. Foundation/bootstrap need
|
|
||||||
no embedding API key; the future hosted adapter requires its separate key.
|
|
||||||
|
|
||||||
~~~powershell
|
|
||||||
.venv/Scripts/alembic upgrade head
|
|
||||||
~~~
|
|
||||||
|
|
||||||
The initial migration explicitly creates vector(D) using the configured positive
|
|
||||||
dimension and stores the full provider/endpoint/model/dimension/preprocessing
|
|
||||||
identity as a column comment. Applied migration files are never regenerated when
|
|
||||||
configuration changes. Subsequent upgrade head verifies the pinned profile;
|
|
||||||
changing environment settings cannot alter an existing schema. Model changes
|
|
||||||
require an explicit new migration/reindexing design, even for equal dimensions.
|
|
||||||
Do not manually edit the comment to bypass compatibility checks. The future worker
|
|
||||||
must call check_compatibility before processing. SQLAlchemy connections can call register_vector_types after migration for native Psycopg pgvector values.
|
|
||||||
|
|
||||||
Migration downgrade drops these tables and their content; use forward migrations
|
|
||||||
once data exists. The extension is retained.
|
|
||||||
|
|
||||||
## Initial trusted administrator
|
|
||||||
|
|
||||||
Run from an interactive terminal; the password is prompted twice without echo:
|
|
||||||
|
|
||||||
~~~powershell
|
|
||||||
.venv/Scripts/python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from organization documents."
|
|
||||||
~~~
|
|
||||||
|
|
||||||
For automation, --password-stdin reads one line from a securely supplied pipe.
|
|
||||||
There is deliberately no password argument or password environment variable.
|
|
||||||
Bootstrap creates organization, enabled lowercase administrator (Argon2id hash),
|
|
||||||
and settings with all three revisions at 1 in one transaction. A transaction
|
|
||||||
advisory lock serializes concurrent bootstrap. It refuses an existing organization
|
|
||||||
and never resets credentials. Output contains only the new organization/admin IDs.
|
|
||||||
This is operator tooling, not HTTP authentication.
|
|
||||||
|
|
||||||
## Tests
|
|
||||||
|
|
||||||
Ordinary tests are deterministic and do not call providers:
|
|
||||||
|
|
||||||
~~~powershell
|
|
||||||
.venv/Scripts/python -m pytest -m "not postgres"
|
|
||||||
~~~
|
|
||||||
|
|
||||||
Database tests require a dedicated disposable PostgreSQL database whose name ends
|
|
||||||
in _test; never point them at production. They create a randomly named schema
|
|
||||||
for each test, migrate it, use independent connections for concurrency checks,
|
|
||||||
and remove only that schema on teardown. They install vector into the dedicated test_vector namespace, never relocate an existing extension, and refuse a database with vector in another namespace. Use a fresh dedicated test database if vector was previously installed in public. The application search path contains the disposable schema and test_vector only; it never includes public. Every test connection checks relation ownership before use, and migrations explicitly qualify their version table and validate relation resolution before downgrade. The extension namespace must contain no foundation relations.
|
|
||||||
|
|
||||||
Example local service (requires working Docker):
|
|
||||||
|
|
||||||
~~~powershell
|
|
||||||
docker run --name rag-foundation-test -e POSTGRES_PASSWORD=test-only -e POSTGRES_DB=rag_foundation_test -p 127.0.0.1:55432:5432 -d pgvector/pgvector:pg16
|
|
||||||
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:test-only@127.0.0.1:55432/rag_foundation_test"
|
|
||||||
.venv/Scripts/python -m tests.postgres_prerequisites
|
|
||||||
.venv/Scripts/python -m pytest -m postgres --require-postgres
|
|
||||||
~~~
|
|
||||||
|
|
||||||
Wait for PostgreSQL readiness before tests. Stop/remove the explicitly named
|
|
||||||
test container after use. The acceptance command fails if TEST_DATABASE_URL is missing; it must never be interpreted as successful acceptance from skips. Running the general suite without this flag skips PostgreSQL tests with an explicit non-acceptance reason. A configured unavailable database fails rather than replacing it with mocks. The public-table preservation regression also needs CREATEDB permission: it creates its own UUID-named database ending in _test, installs pre-existing public foundation tables/data there, exercises disposable-schema setup, writes, downgrade/upgrade and normal/exception teardown, compares public OIDs/rows/constraints/profile comments, then drops only that generated database.
|
|
||||||
Required evidence covers scoped foreign keys, state/counter checks, vector
|
|
||||||
dimension, duplicate requests/jobs/chunk ordinals/audit replay under concurrency,
|
|
||||||
profile compatibility and serialized bootstrap.
|
|
||||||
|
|
||||||
INGEST_ACCEPTED_FORMATS is a JSON array, for example [".md"].
|
|
||||||
All configured limits are validated when IngestionSettings is explicitly
|
|
||||||
constructed. Worker concurrency is constrained to one document for this milestone.
|
|
||||||
Retry policy is bounded exponential backoff with jitter in a later worker phase;
|
|
||||||
this phase only supplies validated base/cap/attempt settings. The processing
|
|
||||||
snapshot uses character units, retains extraction/chunking/embedding metadata and
|
|
||||||
excludes credentials. Types/ports do not claim to validate or publish complete
|
|
||||||
staged results yet. Immutable original storage is a FileStore contract; its
|
|
||||||
concrete adapter arrives with intake, and no file is modified by this foundation.
|
|
||||||
|
|
||||||
|
|
||||||
## Endpoint structure and secret handling
|
|
||||||
|
|
||||||
Supported endpoints are absolute HTTP or HTTPS URLs with an ASCII DNS/IP host,
|
|
||||||
optional valid nonzero port, and an optional path made of ASCII letters, digits,
|
|
||||||
slashes, dots, underscores, tildes and hyphens. For example
|
|
||||||
https://api.example.invalid/v1 or http://localhost:8080/tenant/deployment-01/v1.
|
|
||||||
IPv6 literals use brackets. Host casing, explicit ports and path identity are
|
|
||||||
preserved; the existing profile convention strips trailing slashes only.
|
|
||||||
User information, query strings (including an empty query marker), fragments,
|
|
||||||
path parameters, percent-encoded components, backslashes, control characters and
|
|
||||||
whitespace are rejected rather than stripped or persisted. Supply authentication
|
|
||||||
only through INGEST_EMBEDDING_API_KEY (SecretStr). Printed and structured settings
|
|
||||||
validation errors omit input values. Snapshots contain no credentials.
|
|
||||||
All duration settings require finite positive numbers; NaN and both infinities
|
|
||||||
are invalid in direct construction and environment configuration.
|
|
||||||
|
|
||||||
Existing applied profile comments/document profiles are not silently rewritten.
|
|
||||||
No affected historical deployment has been identified or remediated by this work.
|
|
||||||
Do not change existing profile comments, document profiles or original files merely
|
|
||||||
because they could contain a historical credential. If a deployment is identified:
|
|
||||||
first record a redacted inventory and obtain explicit remediation authorization.
|
|
||||||
Then rotate the exposed credential through the deployment's secret-management
|
|
||||||
process. With that authorization, prepare a reviewed forward migration targeting
|
|
||||||
only affected profile metadata and the matching pinned comment. Preserve provider,
|
|
||||||
model, dimensions, preprocessing identity, original bytes and unrelated revisions;
|
|
||||||
agree the credential-free endpoint identity explicitly rather than stripping URL
|
|
||||||
components silently. If the service/model identity changes, design reindexing
|
|
||||||
before claiming compatibility. Restrict affected backup/log access and handle
|
|
||||||
their cleanup only under an authorized retention policy. Verify compatibility
|
|
||||||
and absence of credentials afterward. Never edit the initial migration or
|
|
||||||
claim rotation/metadata cleanup occurred without evidence.
|
|
||||||
|
|
||||||
## Declared pgvector compatibility
|
|
||||||
|
|
||||||
The manifest retains pgvector >=0.3.6,<1. Native vector acceptance handles the
|
|
||||||
NumPy loader in 0.3.6 and the Vector loader in 0.5.0, preserving equal numeric
|
|
||||||
round-trip assertions. Run the same PostgreSQL tests in both environments:
|
|
||||||
|
|
||||||
~~~powershell
|
|
||||||
python -m venv .venv/minimum
|
|
||||||
.venv/minimum/Scripts/python -m pip install -e ".[test]" "pgvector==0.3.6"
|
|
||||||
.venv/minimum/Scripts/python -m tests.postgres_prerequisites
|
|
||||||
.venv/minimum/Scripts/python -m pytest -m postgres --require-postgres
|
|
||||||
.venv/Scripts/python -m tests.postgres_prerequisites
|
|
||||||
.venv/Scripts/python -m pytest -m postgres --require-postgres
|
|
||||||
~~~
|
|
||||||
|
|
||||||
Native vector round trips have now passed against real PostgreSQL in both versions. The 0.3.6 test uses its supported NumPy input/output adapter; 0.5.0 uses native Vector. The numeric assertions are identical. Package imports alone are not adaptation evidence.
|
|
||||||
|
|
||||||
|
|
||||||
## Current acceptance status (2026-10-05)
|
|
||||||
|
|
||||||
Docker is now operational. A dedicated localhost-only temporary
|
|
||||||
pgvector/pgvector:pg16 container provided PostgreSQL 16.15 and extension 0.8.7.
|
|
||||||
Both prerequisite commands passed, including actual CREATE/DROP DATABASE and
|
|
||||||
extension installation privileges. The database was rag_foundation_test on the
|
|
||||||
temporary localhost port 54918. Test credentials belonged only to this container.
|
|
||||||
|
|
||||||
Exact checks (all final test runs have zero failures/errors/skips):
|
|
||||||
- .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 (pgvector Python 0.5.0).
|
|
||||||
- .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected (pgvector Python 0.3.6).
|
|
||||||
- .venv/Scripts/python -m pytest --require-postgres -q: 163 passed.
|
|
||||||
- Both environments' python -m tests.postgres_prerequisites: passed.
|
|
||||||
- Both environments' python -m pip check: no broken requirements.
|
|
||||||
- .venv/Scripts/alembic history: unchanged initial revision discovered.
|
|
||||||
|
|
||||||
Database tests prove empty-schema upgrade, scoped FKs, state/uniqueness
|
|
||||||
constraints, full profile compatibility, concurrent bootstrap, native vectors,
|
|
||||||
pre-existing public-table/data preservation and scoped downgrade/upgrade.
|
|
||||||
Initial real-DB runs exposed test defects: inline JSON was mistaken for a bind
|
|
||||||
parameter; deparsed constraints varied with search_path; 0.3.6 lacked the root
|
|
||||||
Vector export. JSON now uses a bind, public constraints are compared through
|
|
||||||
stable complete catalog rows, and native vector inputs match each supported
|
|
||||||
adapter. No assertion was weakened.
|
|
||||||
|
|
||||||
Malformed database URLs now produce one generic settings validation error;
|
|
||||||
raw SQLAlchemy parser exceptions are discarded before raising. str/repr/json,
|
|
||||||
structured errors and exposed context/cause chains are checked with dummy
|
|
||||||
credentials in direct and environment construction. Valid Psycopg URLs retain
|
|
||||||
their identity. Tests clear ambient INGEST_* overrides (case-insensitively) per
|
|
||||||
test while preserving TEST_DATABASE_URL. Explicit environment tests install
|
|
||||||
their own values, and the ordinary suite is also rerun under external valid
|
|
||||||
limit/duration overrides. Production environment loading is unchanged.
|
|
||||||
|
|
||||||
The initial migration's bytes and SHA-256 remain unchanged. These repairs
|
|
||||||
require no persisted schema changes or forward migration. No historical metadata
|
|
||||||
was changed. Test acceptance is local evidence only: no deployment, real-provider
|
|
||||||
quality, HTTP authentication or later ingestion phase is validated.
|
|
||||||
|
|
||||||
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).
|
|
||||||
@@ -1,316 +0,0 @@
|
|||||||
# Document ingestion pipeline: six implementation phases
|
|
||||||
|
|
||||||
## 1. Target and boundaries
|
|
||||||
|
|
||||||
Build this pipeline:
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart LR
|
|
||||||
A["Import PDF or Markdown"] --> B["Save immutable original + queued job"]
|
|
||||||
B --> C["Worker claims job"]
|
|
||||||
C --> D["Extract and normalize"]
|
|
||||||
D --> E["Chunk"]
|
|
||||||
E --> F["Embed batches"]
|
|
||||||
F --> G["Stage all results in memory"]
|
|
||||||
G --> H{"Every chunk valid?"}
|
|
||||||
H -->|Yes| I["One transaction: insert chunks + mark ready"]
|
|
||||||
H -->|No| J["Discard staging; retry or fail"]
|
|
||||||
I --> K["PostgreSQL + pgvector"]
|
|
||||||
```
|
|
||||||
|
|
||||||
**Publication is atomic per document.** If a document produces 100 chunks, all 100 embeddings must succeed before any chunk is committed to `document_chunks`.
|
|
||||||
|
|
||||||
Document metadata and its ingestion job are persisted before processing. After publication, the document is `ready` but remains inactive.
|
|
||||||
|
|
||||||
This milestone includes a local import/status/retry CLI and a separate worker. Authenticated upload APIs, selection controls, and replacing the existing Chroma chat retriever are later milestones. Completing this pipeline will not yet make chat search pgvector.
|
|
||||||
|
|
||||||
The prototype has Markdown loading, character chunking, and Chroma/FastEmbed indexing. Ingestion Phase 1 now has a pyproject.toml manifest, Alembic foundation migration, independent settings/ports/database access, trusted bootstrap, and pytest regressions. Local PostgreSQL foundation acceptance has now passed in both supported pgvector Python environments; see the setup guide for exact results and remaining deployment/provider limitations. There is no ingestion intake CLI or worker yet; Phases 2-6 remain planned. See [foundation setup](ingestion-foundation-setup.md).
|
|
||||||
|
|
||||||
## 2. Shared implementation decisions
|
|
||||||
|
|
||||||
Use the repository's database and workflow contracts through [the reference map](../data/documents/agent-reference-map.md).
|
|
||||||
|
|
||||||
- Implement application services under `app/modules/documents/`, storage/database/provider adapters under `app/infrastructure/`, and worker orchestration in `app/worker.py`.
|
|
||||||
- Use PostgreSQL jobs, SQLAlchemy, Alembic, Psycopg, and pgvector. No message broker or staging table.
|
|
||||||
- Use a PDF parser such as `pypdf` for text-based PDFs; UTF-8 decoding for Markdown. OCR and complex table reconstruction remain excluded.
|
|
||||||
- Define small internal types: extracted blocks, chunk drafts, embedding profile, and a complete staged document. Keep provider response objects inside the embedding adapter.
|
|
||||||
- Preserve immutable originals and direct `document_id` references. Do not add document-content versions.
|
|
||||||
- Record extraction, normalization, chunking, and embedding settings in `documents.processing_profile`. Retries use that recorded profile.
|
|
||||||
- Keep the new ingestion entry points independent of the prototype retriever and its import-time indexing.
|
|
||||||
|
|
||||||
**Configuration defaults**
|
|
||||||
|
|
||||||
All limits are environment-configurable, validated at startup, and documented in `.env.example`.
|
|
||||||
|
|
||||||
| Setting | Initial default |
|
|
||||||
| --- | --- |
|
|
||||||
| Accepted formats | `.pdf`, `.md` |
|
|
||||||
| Maximum original size | 20 MiB |
|
|
||||||
| Maximum PDF pages | 200 |
|
|
||||||
| Maximum normalized characters | 1,000,000 |
|
|
||||||
| Maximum chunks per document | 2,000 |
|
|
||||||
| Chunk size / overlap | 1,000 / 200 characters |
|
|
||||||
| Embedding batch size | 32 chunks |
|
|
||||||
| Maximum staged payload | 128 MiB, measured using text bytes and packed vector storage |
|
|
||||||
| Worker concurrency | One document |
|
|
||||||
| Poll / heartbeat / lease | 2 / 20 / 120 seconds |
|
|
||||||
| Maximum automatic attempts | 3 |
|
|
||||||
| Retry delay | Exponential backoff with jitter, capped at 300 seconds |
|
|
||||||
|
|
||||||
Keep character units explicit; leave `token_count` null unless actually calculated. The adapter must additionally enforce the selected model's input and batch limits.
|
|
||||||
|
|
||||||
Embedding endpoint, API key, model, and vector dimension are required deployment configuration, with no silently chosen production model. Freeze dimension before creating `vector(D)`; worker startup must reject schema/profile incompatibility. Equal dimensions alone do not establish model compatibility.
|
|
||||||
|
|
||||||
The hosted adapter must map returned vectors using response indexes and only send optional dimension parameters when supported. These requirements follow the [official embedding API contract](https://developers.openai.com/api/reference/resources/embeddings/methods/create). Other compatible endpoints require their own compatibility check.
|
|
||||||
|
|
||||||
## 3. Phases and implementation prompts
|
|
||||||
|
|
||||||
Run these phases sequentially. For each phase, use the following shared instruction followed by its phase prompt.
|
|
||||||
|
|
||||||
**Shared instruction**
|
|
||||||
|
|
||||||
```text
|
|
||||||
Use $implement-feature. Read AGENTS.md, applicable nested instructions, and
|
|
||||||
data/documents/agent-reference-map.md. Follow the referenced Phase 1
|
|
||||||
database and ingestion workflow contracts.
|
|
||||||
|
|
||||||
Implement only the requested phase and its necessary tests. Inspect the
|
|
||||||
current repository and previous phase outputs first. Preserve unrelated
|
|
||||||
working-tree changes, including untracked specifications.
|
|
||||||
|
|
||||||
Keep original documents immutable, use direct document_id references,
|
|
||||||
and preserve processing-profile metadata. Keep the ingestion CLI and
|
|
||||||
worker independent of the prototype chat/retriever initialization.
|
|
||||||
|
|
||||||
Do not add upload APIs, selection UI, a broker, document versions, or
|
|
||||||
chat/Live changes. Ordinary tests must not call real providers. Test
|
|
||||||
database constraints and concurrency against isolated PostgreSQL with
|
|
||||||
pgvector.
|
|
||||||
|
|
||||||
Update setup instructions and the reference map when commands or source
|
|
||||||
locations change. Report implemented behavior, exact checks and results,
|
|
||||||
and remaining limitations. Do not claim unexecuted checks passed.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 1 — Database and application foundation
|
|
||||||
|
|
||||||
**Outcome:** A reproducible database schema and isolated ingestion configuration.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Phase 1: ingestion foundation.
|
|
||||||
|
|
||||||
Create a dependency manifest and pytest setup. Add SQLAlchemy/Psycopg
|
|
||||||
database access, Alembic migrations, and pgvector support.
|
|
||||||
|
|
||||||
Create the contract-defined organizations, users, organization_settings,
|
|
||||||
documents, ingestion_jobs, document_chunks, and audit_events tables in
|
|
||||||
dependency order. Include scoped foreign keys, state checks, request-key
|
|
||||||
uniqueness, one job per document, and unique document/ordinal chunks.
|
|
||||||
Do not create conversation or Live tables for this milestone.
|
|
||||||
|
|
||||||
Require the embedding model and dimension as deployment inputs. Configure
|
|
||||||
vector(D) explicitly at initial migration; never rewrite applied migrations
|
|
||||||
when environment settings change. Add schema/profile compatibility checks.
|
|
||||||
|
|
||||||
Implement the configurable limits from this plan and separate ingestion
|
|
||||||
settings from prototype chat credentials. Add provider-neutral processing
|
|
||||||
types and narrow repository/FileStore/EmbeddingProvider interfaces.
|
|
||||||
|
|
||||||
Provide a trusted operator bootstrap command for the initial organization
|
|
||||||
and administrator, using a securely supplied password and maintained
|
|
||||||
password hashing. Do not implement HTTP authentication yet.
|
|
||||||
|
|
||||||
Acceptance: migrations work on an empty PostgreSQL/pgvector database;
|
|
||||||
invalid states, cross-organization references, and duplicate chunk
|
|
||||||
ordinals are rejected. Ingestion modules import without provider calls,
|
|
||||||
model downloads, corpus scanning, or chat credentials.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 2 — Durable document intake
|
|
||||||
|
|
||||||
**Outcome:** Importing a file safely creates one immutable original and one queued job.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Phase 2: local document intake.
|
|
||||||
|
|
||||||
Add `python -m app.ingest import`, accepting an explicit file path,
|
|
||||||
administrator ID, UUID idempotency key, and optional title. Resolve the
|
|
||||||
organization from the enabled administrator record. This is a trusted
|
|
||||||
operator command, not an HTTP authorization substitute.
|
|
||||||
|
|
||||||
Validate size, supported format, safe display filename, and content/type
|
|
||||||
consistency. Store originals using generated keys, temporary writes,
|
|
||||||
and atomic finalization. Hash original bytes and normalized title.
|
|
||||||
|
|
||||||
Create document, queued job, and upload audit in one short transaction.
|
|
||||||
Snapshot the processing profile. Same key and payload returns the same
|
|
||||||
document/job IDs; changed payload conflicts. Different keys create
|
|
||||||
independent documents even for identical bytes.
|
|
||||||
|
|
||||||
Add `python -m app.ingest status` with structured document/job output.
|
|
||||||
New documents are inactive, with zero published chunks.
|
|
||||||
|
|
||||||
Handle duplicate-import races and unused temporary files. Provide a
|
|
||||||
report-only reconciliation command for orphan files and missing originals;
|
|
||||||
do not introduce physical document purging.
|
|
||||||
|
|
||||||
Acceptance: originals survive restart, replay is stable under concurrency,
|
|
||||||
changed-payload conflicts work, filenames cannot escape storage, and
|
|
||||||
failed database writes cannot create acknowledged jobs.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 3 — Extraction, normalization, and chunking
|
|
||||||
|
|
||||||
**Outcome:** A stored original produces deterministic, traceable chunk drafts.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Phase 3: PDF/Markdown processing.
|
|
||||||
|
|
||||||
Read originals through FileStore. Verify retained bytes against the stored
|
|
||||||
hash. Extract PDF text page by page and decode Markdown as UTF-8.
|
|
||||||
|
|
||||||
Normalize line endings and Unicode conservatively. Preserve Persian
|
|
||||||
characters and ZWNJ, Markdown code indentation, paragraphs, and headings.
|
|
||||||
Avoid destructive whitespace collapsing or rewriting document meaning.
|
|
||||||
|
|
||||||
Create extracted blocks with page/section metadata. PDF pages are 1-based;
|
|
||||||
Markdown has page=null. Never invent unavailable locations. Fail empty,
|
|
||||||
corrupt, encrypted, and detected unsupported scanned content visibly.
|
|
||||||
Report extraction limitations instead of claiming OCR or table fidelity.
|
|
||||||
|
|
||||||
Chunk deterministically within page/section boundaries, preferring
|
|
||||||
paragraph and line boundaries. Default to 1000 characters with 200
|
|
||||||
characters overlap; validate overlap < size. Split oversized blocks,
|
|
||||||
discard empty output, and assign contiguous zero-based ordinals.
|
|
||||||
Preserve heading context and source location.
|
|
||||||
|
|
||||||
Enforce configured page, extracted-character, and chunk limits during
|
|
||||||
processing. Exceeding a limit fails the document; never silently truncate.
|
|
||||||
|
|
||||||
Acceptance: fixtures cover Markdown headings/code, English and Persian,
|
|
||||||
text PDFs, blank/scanned PDFs, malformed input, overlap, oversized
|
|
||||||
paragraphs, deterministic ordering, and configurable limits.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 4 — Embeddings and memory staging
|
|
||||||
|
|
||||||
**Outcome:** Every chunk has a validated vector before publication is possible.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Phase 4: embedding adapter and staging.
|
|
||||||
|
|
||||||
Implement one OpenAI-compatible hosted embedding adapter with separately
|
|
||||||
configured endpoint, secret, model, dimension, timeout, and batch limits.
|
|
||||||
Keep credentials server-side and provider objects inside the adapter.
|
|
||||||
|
|
||||||
Implement profile-specific input/batch limit validation. Require compatible
|
|
||||||
token counting where the selected endpoint uses token limits. Do not
|
|
||||||
assume character count equals token count or silently truncate inputs.
|
|
||||||
|
|
||||||
Embed batches outside database transactions. Map responses by returned
|
|
||||||
index and validate completeness, unique indexes, dimension, finite values,
|
|
||||||
and nonzero vectors suitable for cosine distance.
|
|
||||||
|
|
||||||
Accumulate chunk text, metadata, and vectors in a bounded in-memory staged
|
|
||||||
document. Require exactly one vector per ordinal and one consistent
|
|
||||||
profile. Exceeding the memory budget fails explicitly.
|
|
||||||
|
|
||||||
Do not write document_chunks here. Any failed batch makes the staged
|
|
||||||
document unpublishable. Release staging after completion or failure.
|
|
||||||
Normalize provider errors into transient and permanent categories; leave
|
|
||||||
automatic job retries to the worker to avoid stacked retry budgets.
|
|
||||||
|
|
||||||
Acceptance: fake-provider tests cover shuffled responses, missing and
|
|
||||||
duplicate indexes, wrong dimensions, NaN/infinite/zero vectors, timeouts,
|
|
||||||
rate limits, permanent errors, and staging limits. A failed final batch
|
|
||||||
must leave zero published chunks.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 5 — Durable worker and atomic publication
|
|
||||||
|
|
||||||
**Outcome:** The full pipeline runs safely across failures and restarts.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Phase 5: worker orchestration and atomic publication.
|
|
||||||
|
|
||||||
Add `python -m app.worker`, with continuous polling and a --once mode
|
|
||||||
that processes at most one eligible job.
|
|
||||||
|
|
||||||
Claim eligible queued or expired jobs with SKIP LOCKED, a fresh claim
|
|
||||||
token, lease, and incremented attempt count. Exclude deleted documents.
|
|
||||||
Commit claims quickly and use the documented document-before-job lock
|
|
||||||
order for subsequent updates.
|
|
||||||
|
|
||||||
Run extract -> chunk -> embed -> publish with durable stage reporting.
|
|
||||||
Maintain heartbeats during extraction and provider waits. Fence all
|
|
||||||
progress, heartbeat, retry, failure, and publication writes by the claim
|
|
||||||
token and valid lease. A stale worker must discard its results.
|
|
||||||
|
|
||||||
Publish in one transaction: lock document then job; verify ownership,
|
|
||||||
unexpired lease, eligible document state, non-deletion, original/profile
|
|
||||||
compatibility, and complete staged results; insert all chunks; update
|
|
||||||
chunk_count/ready_at/status and mark the job succeeded. Keep is_active=false.
|
|
||||||
Never republish a ready document.
|
|
||||||
|
|
||||||
Rollback everything on publication failure. Recover ambiguous commit
|
|
||||||
outcomes by re-reading durable state before retrying. A successful commit
|
|
||||||
followed by a worker crash must not duplicate chunks.
|
|
||||||
|
|
||||||
Schedule transient failures with bounded backoff/jitter. Fail permanent
|
|
||||||
errors immediately and exhausted jobs terminally. Crash recovery reruns
|
|
||||||
the entire document; no batch checkpoints.
|
|
||||||
|
|
||||||
Add `python -m app.ingest retry` for eligible failed documents, with an
|
|
||||||
idempotency key and administrator validation. Reuse the same document/job,
|
|
||||||
reset attempts, increment retry_generation once, and audit atomically.
|
|
||||||
|
|
||||||
Acceptance: real database tests cover concurrent claims, lease expiry,
|
|
||||||
stale worker writes, late provider responses, exhausted recovery,
|
|
||||||
publication rollback, ambiguous completion, and retry replay.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 6 — Integration proof and handoff
|
|
||||||
|
|
||||||
**Outcome:** A reproducible demonstration proves the pipeline's guarantees.
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Phase 6: integration validation and operator handoff.
|
|
||||||
|
|
||||||
Build end-to-end tests using isolated PostgreSQL/pgvector, a temporary
|
|
||||||
original-file directory, real extractors, and a deterministic fake
|
|
||||||
embedding provider.
|
|
||||||
|
|
||||||
Prove that chunks remain absent while embedding batches are incomplete,
|
|
||||||
then appear together with ready/succeeded state after publication.
|
|
||||||
Verify exact row count, contiguous ordinals, source locations, profile,
|
|
||||||
and vector dimension. Confirm documents remain inactive.
|
|
||||||
|
|
||||||
Exercise crashes before publication and after commit, a failed final
|
|
||||||
embedding batch, expired claims, deletion before publication, missing
|
|
||||||
originals, duplicate imports, and idempotent manual retry.
|
|
||||||
|
|
||||||
Add worker heartbeat reporting and redacted logs containing document/job
|
|
||||||
IDs and stage/error categories. Document setup, migration, bootstrap,
|
|
||||||
import, status, retry, worker, and reconciliation commands.
|
|
||||||
|
|
||||||
Provide a separate opt-in real-provider smoke command requiring explicit
|
|
||||||
corpus and provider configuration. Keep it out of ordinary tests and
|
|
||||||
report provider compatibility and extraction quality separately.
|
|
||||||
|
|
||||||
Update README and the reference map. Clearly document that the existing
|
|
||||||
chat retriever still uses Chroma and that pgvector search/selection is
|
|
||||||
the next milestone.
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. Final acceptance criteria
|
|
||||||
|
|
||||||
This milestone is complete when:
|
|
||||||
|
|
||||||
- A PDF or Markdown import creates a durable, independent document and job.
|
|
||||||
- Extraction and chunking preserve usable evidence locations.
|
|
||||||
- **Every chunk is embedded before any chunk is published.**
|
|
||||||
- Publication commits all chunks and completion state together.
|
|
||||||
- Failures, restarts, duplicate requests, and stale workers cannot create partial or duplicate publication.
|
|
||||||
- Configuration overrides work and processing profiles remain traceable.
|
|
||||||
- Published documents remain inactive until a later authorized selection workflow.
|
|
||||||
- Automated PostgreSQL evidence and documented operator commands support these claims; real-provider validation is reported separately.
|
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
# Document ingestion pipeline: six implementation phases
|
||||||
|
|
||||||
|
## 1. Target and boundaries
|
||||||
|
|
||||||
|
**Current milestone (2026-10-07):** delivery plan revision 1.3 targets a
|
||||||
|
conditional four-day LangChain Live document MVP. Continue from the implemented
|
||||||
|
ingestion Phases 1-6 backend and validation below; do not rebuild embedding validation/staging or alter applied
|
||||||
|
profiles/migrations. Phase 5 must include exact-output review/resume for new PDF/
|
||||||
|
image uploads and explicit factual FAQ approval/inclusion before publication.
|
||||||
|
The four supplied examples are mandatory tests, not an accepted-file allowlist.
|
||||||
|
General bounded browser upload, scoped pgvector search, LangChain and native
|
||||||
|
Live are subsequent integrations; full public text chat/history is deferred.
|
||||||
|
|
||||||
|
[Implementation guide](../specifications/RAG-Phase1-Implementation-Guide.md)
|
||||||
|
Section 6 and API D06/D07 define the new retained review workflow. Use reviewed
|
||||||
|
forward schema changes and current-claim fencing; no unfenced finalizer,
|
||||||
|
waiting-review lifecycle or four-document capacity assumption is introduced.
|
||||||
|
|
||||||
|
Build this pipeline:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
A["Import approved PDF, DOCX, image or readable text"] --> B["Save immutable original + queued job"]
|
||||||
|
B --> C["Worker claims job"]
|
||||||
|
C --> D["Page or block extraction, fallback and QC"]
|
||||||
|
D --> E["Chunk"]
|
||||||
|
E --> F["Embed batches"]
|
||||||
|
F --> G["Stage all results in memory"]
|
||||||
|
G --> H{"Every chunk valid?"}
|
||||||
|
H -->|Yes| I["One transaction: insert chunks + mark ready"]
|
||||||
|
H -->|No| J["Discard staging; retry or fail"]
|
||||||
|
I --> K["PostgreSQL + pgvector"]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Publication is atomic per document.** If a document produces 100 chunks, all 100 embeddings must succeed before any chunk is committed to `document_chunks`.
|
||||||
|
|
||||||
|
Document metadata and its ingestion job are persisted before processing. After publication, the document is `ready` but remains inactive.
|
||||||
|
|
||||||
|
The 2026-10-06 MVP scope includes representative PDF page fallback, DOCX tables and image extraction; it supersedes the earlier OCR/table exclusion. Foundation/intake validates PDF/Markdown/DOCX/JPEG/PNG. Phase 3 implements direct extraction, opt-in vision/QC, semantic chunk drafts and bounded immutable artifact candidates; Phase 5 worker orchestration and fenced attachment/publication are implemented; authenticated review transport remains pending. Intake acceptance never proves extractability. The detailed page-fallback diagram is in [architecture Section 7.1](../specifications/RAG-AI-Architecture.md).
|
||||||
|
|
||||||
|
This milestone includes a local import/status/retry CLI and a separate worker. Authenticated upload APIs, selection controls, and replacing the existing Chroma chat retriever are later milestones. Completing this pipeline will not yet make chat search pgvector.
|
||||||
|
|
||||||
|
The prototype has Markdown loading, character chunking, and Chroma/FastEmbed indexing. Ingestion Phase 1 now has a pyproject.toml manifest, Alembic foundation migration, independent settings/ports/database access, trusted bootstrap, and pytest regressions. Local PostgreSQL foundation acceptance has now passed in both supported pgvector Python environments; see the setup guide for exact results and remaining deployment/provider limitations. Phase 2 now implements local import/status/reconciliation and immutable original storage. Phase 3 extraction/QC/chunk drafts and candidate retention are implemented. Phase 4 hosted embedding validation and bounded memory staging are implemented. Phase 5 worker/publication/retry and retained review/resume backend services, plus Phase 6 validation/operator handoff, are implemented. Authenticated D06/D07 transport remains pending. Real-provider quality and manual Persian fidelity acceptance remain unverified. See [foundation setup](../guides/ingestion-foundation-setup.md).
|
||||||
|
|
||||||
|
## 2. Shared implementation decisions
|
||||||
|
|
||||||
|
Use the repository's database and workflow contracts through [the reference map](../agent-reference-map.md).
|
||||||
|
|
||||||
|
- Implement application services under `app/modules/documents/`, storage/database/provider adapters under `app/infrastructure/`, and worker orchestration in `app/worker.py`.
|
||||||
|
- Use PostgreSQL jobs, SQLAlchemy, Alembic, Psycopg, and pgvector. No message broker or staging table.
|
||||||
|
- Attempt direct PDF extraction page by page; use rendering plus configurable Gemini Flash vision/OCR for unusable or uncertain pages after simple checks/manual inspection. Extract DOCX paragraphs/tables and pair FAQ rows; use vision for the infographic. Readable text and extracted image text feed one downstream pipeline. Mistral OCR/PaddleOCR remain optional evaluation/future alternatives.
|
||||||
|
- Define small internal types: extracted blocks, chunk drafts, embedding profile, and a complete staged document. Keep provider response objects inside the embedding adapter.
|
||||||
|
- Preserve immutable originals and direct `document_id` references. Do not add document-content versions.
|
||||||
|
- Record extraction, normalization, chunking, and embedding settings in `documents.processing_profile`. Retries use that recorded profile.
|
||||||
|
- Keep the new ingestion entry points independent of the prototype retriever and its import-time indexing.
|
||||||
|
|
||||||
|
**Configuration defaults**
|
||||||
|
|
||||||
|
The defaults below and DOCX/image bounds in the setup guide are environment-configurable engineering deployment choices, not recorded product-owner approvals. Foundation/intake validation, frozen schema-2 snapshots and Phase 3 extraction/opt-in vision/QC/semantic drafts/candidates are implemented. Phase 5 implements durable artifact attachment and runtime reuse under current-claim fencing.
|
||||||
|
|
||||||
|
| Setting | Initial default |
|
||||||
|
| --- | --- |
|
||||||
|
| Current accepted formats | `.pdf`, `.md`, `.docx`, `.jpg`, `.jpeg`, `.png`; PNG is the additional supported image format |
|
||||||
|
| Maximum original size | 20 MiB |
|
||||||
|
| Maximum PDF pages | 200 |
|
||||||
|
| Maximum normalized characters | 1,000,000 |
|
||||||
|
| Maximum chunks per document | 2,000 |
|
||||||
|
| Chunk size / overlap | 1,000 / 200 characters |
|
||||||
|
| Embedding batch size | 32 chunks |
|
||||||
|
| Maximum staged payload | 128 MiB, measured using text bytes and packed vector storage |
|
||||||
|
| Worker concurrency | One document |
|
||||||
|
| Poll / heartbeat / lease | 2 / 20 / 120 seconds |
|
||||||
|
| Maximum automatic attempts | 3 |
|
||||||
|
| Retry delay | Exponential backoff with jitter, capped at 300 seconds |
|
||||||
|
|
||||||
|
Keep character units explicit; leave `token_count` null unless actually calculated. The adapter must additionally enforce the selected model's input and batch limits.
|
||||||
|
|
||||||
|
Embedding endpoint, model and vector dimension are required deployment configuration, with no silently chosen production model. A separate secret is required only when the future hosted embedding adapter runs; bootstrap/intake require no provider credentials. Freeze dimension before creating `vector(D)`; worker startup must reject schema/profile incompatibility. Equal dimensions alone do not establish model compatibility.
|
||||||
|
|
||||||
|
The hosted adapter must map returned vectors using response indexes and only send optional dimension parameters when supported. These requirements follow the [official embedding API contract](https://developers.openai.com/api/reference/resources/embeddings/methods/create). Other compatible endpoints require their own compatibility check.
|
||||||
|
|
||||||
|
## 3. Phases and implementation prompts
|
||||||
|
|
||||||
|
Run these phases sequentially. For each phase, use the following shared instruction followed by its phase prompt.
|
||||||
|
|
||||||
|
**Shared instruction**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use $implement-feature. Read AGENTS.md, applicable nested instructions, and
|
||||||
|
docs/agent-reference-map.md. Follow the referenced Phase 1
|
||||||
|
database and ingestion workflow contracts.
|
||||||
|
|
||||||
|
Implement only the requested phase and its necessary tests. Inspect the
|
||||||
|
current repository and previous phase outputs first. Preserve unrelated
|
||||||
|
working-tree changes, including untracked specifications.
|
||||||
|
|
||||||
|
Keep original documents immutable, use direct document_id references,
|
||||||
|
and preserve processing-profile metadata. Keep the ingestion CLI and
|
||||||
|
worker independent of the prototype chat/retriever initialization.
|
||||||
|
|
||||||
|
Do not add upload APIs, selection UI, a broker, document versions, or
|
||||||
|
chat/Live changes. Ordinary tests must not call real providers. Test
|
||||||
|
database constraints and concurrency against isolated PostgreSQL with
|
||||||
|
pgvector.
|
||||||
|
|
||||||
|
Update setup instructions and the reference map when commands or source
|
||||||
|
locations change. Report implemented behavior, exact checks and results,
|
||||||
|
and remaining limitations. Do not claim unexecuted checks passed.
|
||||||
|
```
|
||||||
|
|
||||||
|
The implementation prompts and dated phase evidence below retain their original
|
||||||
|
phase boundaries. Future-tense dependencies inside earlier prompts describe that
|
||||||
|
phase, not current absence of the implemented Phase 5/6 backend and validation.
|
||||||
|
|
||||||
|
### Phase 1 — Database and application foundation
|
||||||
|
|
||||||
|
**Outcome:** A reproducible database schema and isolated ingestion configuration.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Phase 1: ingestion foundation.
|
||||||
|
|
||||||
|
Create a dependency manifest and pytest setup. Add SQLAlchemy/Psycopg
|
||||||
|
database access, Alembic migrations, and pgvector support.
|
||||||
|
|
||||||
|
Create the contract-defined organizations, users, organization_settings,
|
||||||
|
documents, ingestion_jobs, document_chunks, and audit_events tables in
|
||||||
|
dependency order. Include scoped foreign keys, state checks, request-key
|
||||||
|
uniqueness, one job per document, and unique document/ordinal chunks.
|
||||||
|
Do not create conversation or Live tables for this milestone.
|
||||||
|
|
||||||
|
Require the embedding model and dimension as deployment inputs. Configure
|
||||||
|
vector(D) explicitly at initial migration; never rewrite applied migrations
|
||||||
|
when environment settings change. Add schema/profile compatibility checks.
|
||||||
|
|
||||||
|
Implement the configurable limits from this plan and separate ingestion
|
||||||
|
settings from prototype chat credentials. Add provider-neutral ordered extraction
|
||||||
|
blocks/envelope with faithful versus normalized text, locators, FAQ groups and
|
||||||
|
infographic parent/child relationships; add small extraction/vision ports.
|
||||||
|
Snapshot strategy, optional vision identity, fallback/quality policies, rendering
|
||||||
|
and resource bounds, normalization/chunking and pinned embedding identity.
|
||||||
|
Exclude credentials; bootstrap/intake require no OCR/provider access.
|
||||||
|
Classify legacy snapshots explicitly without rewriting or OCR reinterpretation.
|
||||||
|
Retain existing preprocessing semantics; incompatible normalization requires a
|
||||||
|
migration/reindex decision. Define bounded artifact integrity and a separate
|
||||||
|
namespace, with attachment deferred until current-worker fencing exists.
|
||||||
|
Complete FileStore inventory/confirmed-unused cleanup contracts. Reject equal or
|
||||||
|
nested original/extraction namespaces after canonical resolution, without creating
|
||||||
|
or mutating directories. Application intake/status/reconciliation receive an
|
||||||
|
IntakeRepository; wire the SQL implementation only at the CLI composition boundary.
|
||||||
|
|
||||||
|
Provide a trusted operator bootstrap command for the initial organization
|
||||||
|
and administrator, using a securely supplied password and maintained
|
||||||
|
password hashing. Do not implement HTTP authentication yet.
|
||||||
|
|
||||||
|
Acceptance: migrations work on an empty PostgreSQL/pgvector database;
|
||||||
|
invalid states, cross-organization references, and duplicate chunk
|
||||||
|
ordinals are rejected. Ingestion modules import without provider calls,
|
||||||
|
model downloads, corpus scanning, or chat credentials.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2 — Durable document intake
|
||||||
|
|
||||||
|
**Outcome:** Importing a file safely creates one immutable original and one queued job.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Phase 2: local document intake.
|
||||||
|
|
||||||
|
Add `python -m app.ingest import`, accepting an explicit file path,
|
||||||
|
administrator ID, UUID idempotency key, and optional title. Resolve the
|
||||||
|
organization from the enabled administrator record. This is a trusted
|
||||||
|
operator command, not an HTTP authorization substitute.
|
||||||
|
|
||||||
|
Validate size, safe display filename and explicit PDF/Markdown/DOCX/JPEG/PNG
|
||||||
|
format/MIME consistency under configurable policy. DOCX needs bounded package,
|
||||||
|
XML and full raw-stream length/CRC/completion/boundary validation without member
|
||||||
|
extraction; images need bounded validation
|
||||||
|
and dimension/pixel limits. Enforce actual STORED/DEFLATED expansion and ratio
|
||||||
|
budgets with bounded early stopping, including supported ZIP32 data descriptors;
|
||||||
|
matching dishonest local/central declarations cannot establish integrity.
|
||||||
|
No OCR or provider calls occur during intake. Store originals using generated keys, temporary writes,
|
||||||
|
and atomic finalization. Hash original bytes and normalized title.
|
||||||
|
|
||||||
|
Use a small transactional intake repository to revalidate/lock administrators and
|
||||||
|
create document, queued job, and upload audit in one short transaction.
|
||||||
|
Snapshot the processing profile. Same key and payload returns the same
|
||||||
|
document/job IDs; changed payload conflicts. Different keys create
|
||||||
|
independent documents even for identical bytes.
|
||||||
|
|
||||||
|
Add `python -m app.ingest status` with structured document/job output.
|
||||||
|
New documents are inactive, with zero published chunks.
|
||||||
|
|
||||||
|
Handle duplicate-import races and unused temporary files. Provide a
|
||||||
|
report-only reconciliation command for orphan files and missing originals;
|
||||||
|
do not introduce physical document purging.
|
||||||
|
|
||||||
|
Acceptance: originals survive restart, replay is stable under concurrency,
|
||||||
|
changed-payload conflicts work, filenames cannot escape storage, and
|
||||||
|
failed database writes cannot create acknowledged jobs. Replay survives policy
|
||||||
|
changes and returns the original profile, including legacy profiles. Test malformed
|
||||||
|
archives/images, format mismatches, Unicode metadata, secret-free profiles and
|
||||||
|
source-relationship JSON round trips without providers. Prove new-format atomic
|
||||||
|
creation, concurrent replay/conflict, rollback and profile retention on isolated
|
||||||
|
PostgreSQL; intake acceptance does not establish extraction quality.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3 — Extraction, normalization, and chunking
|
||||||
|
|
||||||
|
**Outcome:** A stored original produces deterministic, traceable chunk drafts.
|
||||||
|
|
||||||
|
**Implementation status (2026-10-06):** extraction/QC, readable-text FAQ pairing, bounded candidates and chunk drafts are implemented. Confirmed repairs reject unsupported DOCX content/automatic numbering and ambiguous dependencies explicitly. See the setup guide and reference map for executed evidence. The prompt and acceptance requirements below remain governing; real-provider quality/manual Persian fidelity and later pipeline phases are not established by ordinary tests.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Phase 3: representative Persian extraction, QC and chunking.
|
||||||
|
|
||||||
|
Read the implemented envelope/ports and schema-2 snapshots first. Dispatch legacy
|
||||||
|
profiles explicitly or fail safely; do not rewrite them. Cross-check model/method
|
||||||
|
provenance against the frozen profile. Direct blocks carry no provider model;
|
||||||
|
vision/OCR require configured identity and exact requested/actual model equality.
|
||||||
|
Aliases require a future explicit frozen resolution rule. Read immutable originals
|
||||||
|
through FileStore; verify hash. Extract readable text and PDF pages directly, checking readability/order/completeness and
|
||||||
|
important numbers, dates, negation and exceptions. A nonempty text layer
|
||||||
|
is insufficient. Render affected PDF pages for configurable Flash vision
|
||||||
|
fallback; record each page's method/model/warnings.
|
||||||
|
|
||||||
|
Extract DOCX paragraphs and tables in source order, keeping each question
|
||||||
|
with its corresponding answer even across rows. Preserve table/row/Q&A
|
||||||
|
locators with page=null. For images preserve parent headings and their
|
||||||
|
descriptions, reading order and unreadable-region warnings. Require
|
||||||
|
complete transcription, no summaries, guessed numbers or inferred prose.
|
||||||
|
|
||||||
|
Use simple checks and manual inspection for uncertain pages. Fail visibly
|
||||||
|
unreliable extraction before indexing, within the existing lifecycle;
|
||||||
|
do not implement an elaborate classifier or review-state subsystem.
|
||||||
|
Review cannot hold a worker lease indefinitely. No calibrated confidence
|
||||||
|
percentage is invented.
|
||||||
|
|
||||||
|
Retain complete faithful extraction plus normalized search text as proposed
|
||||||
|
durable artifacts per database Section 4.4. Produce bounded candidates in the separate configured namespace and validate
|
||||||
|
original/profile integrity. Enable attachment/reuse only after Phase 5 implements
|
||||||
|
durable current-claim finalization fencing; Phase 3 adds no unfenced finalizer. Chunk/embedding changes
|
||||||
|
alone should not rerun OCR; crash recovery can reuse a validated artifact.
|
||||||
|
Use the shared unicode-line-endings-v1 NFC/CRLF-or-CR-to-LF transformation;
|
||||||
|
validate stored search text against faithful evidence, or rederive faithful-only
|
||||||
|
inputs, enforcing the aggregate normalized-character budget before consumption.
|
||||||
|
Preserve spacing, numbers, dates, negation, exceptions, Persian/Arabic variants
|
||||||
|
and ZWNJ. Persian character folding remains dependent on an explicit incompatible
|
||||||
|
preprocessing migration/reindex design; never change pinned v1 semantics.
|
||||||
|
Keep provider-native objects behind the extraction adapter.
|
||||||
|
|
||||||
|
Prefer regulation article/clause plus note, circular decision with conditions
|
||||||
|
and exclusions, FAQ Q&A, infographic parent/child description. Use bounded
|
||||||
|
size/overlap only as needed; do not separate rules from required exceptions.
|
||||||
|
Keep page/section and contiguous zero-based ordinals. Never invent pagination.
|
||||||
|
|
||||||
|
Keep approved factual Q&A separate from behavioral evaluation and live-data
|
||||||
|
placeholders; do not index placeholders as authoritative values.
|
||||||
|
|
||||||
|
Enforce configured page/text/chunk/provider limits; no silent truncation.
|
||||||
|
Acceptance includes readable/mixed PDFs, numeric order and exclusions,
|
||||||
|
DOCX pairing, infographic grouping/unreadable regions, deterministic chunks
|
||||||
|
and original/artifact retention. Real extraction-provider quality is a
|
||||||
|
separate opt-in sample evaluation, not ordinary test evidence.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 4 — Embeddings and memory staging
|
||||||
|
|
||||||
|
**Implementation status (2026-10-07):** hosted embedding validation and bounded
|
||||||
|
staging are implemented. Repaired findings: vector validation consumes at most D+1
|
||||||
|
elements, never trusting `__len__` alone, packing the same captured elements once into
|
||||||
|
exact 4*D byte storage; float32 cosine safety requires normal accumulated norm and at least
|
||||||
|
one normal component square (`FLT_MIN = 2**-126`), rejecting `[3e-23,0,0]` and `[1e-21]*16000`
|
||||||
|
while preserving `[1e-30,1,0]`; unrepresentable timeouts (`1e20`) are rejected upfront without
|
||||||
|
starting threads or requests; and endpoint hostnames validate syntax and IDNA encoding without DNS,
|
||||||
|
rejecting empty interior labels and labels > 63 characters.
|
||||||
|
Provider-free checks pass (990 tests, three unrelated Windows symlink skips); isolated
|
||||||
|
PostgreSQL acceptance passes all 117 tests without skips, including multi-dimensional
|
||||||
|
cosine references across boundary magnitudes, dimensions, signs, and directions.
|
||||||
|
At this historical Phase 4 checkpoint, Phase 5 remained planned. It is now implemented as described in the Phase 5/6 sections; the recorded results above are unchanged.
|
||||||
|
|
||||||
|
**Outcome:** Every chunk has a validated vector before publication is possible.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Phase 4: embedding adapter and staging.
|
||||||
|
|
||||||
|
Implement one OpenAI-compatible hosted embedding adapter with separately
|
||||||
|
configured endpoint, secret, model, dimension, timeout, and batch limits.
|
||||||
|
Keep credentials server-side and provider objects inside the adapter.
|
||||||
|
|
||||||
|
Implement profile-specific input/batch limit validation. Require compatible
|
||||||
|
token counting where the selected endpoint uses token limits. Do not
|
||||||
|
assume character count equals token count or silently truncate inputs.
|
||||||
|
|
||||||
|
Embed batches outside database transactions. Map responses by returned
|
||||||
|
index and validate completeness, unique indexes, dimension, finite values,
|
||||||
|
and nonzero vectors suitable for cosine distance.
|
||||||
|
|
||||||
|
Accumulate chunk text, metadata, and vectors in a bounded in-memory staged
|
||||||
|
document. Require exactly one vector per ordinal and one consistent
|
||||||
|
profile. Exceeding the memory budget fails explicitly.
|
||||||
|
|
||||||
|
Do not write document_chunks here. Any failed batch makes the staged
|
||||||
|
document unpublishable. Release staging after completion or failure.
|
||||||
|
Normalize provider errors into transient and permanent categories; leave
|
||||||
|
automatic job retries to the worker to avoid stacked retry budgets.
|
||||||
|
|
||||||
|
Acceptance: fake-provider tests cover shuffled responses, missing and
|
||||||
|
duplicate indexes, wrong dimensions, NaN/infinite/zero vectors, timeouts,
|
||||||
|
rate limits, permanent errors, and staging limits. A failed final batch
|
||||||
|
must leave zero published chunks.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 5 — Durable worker and atomic publication
|
||||||
|
|
||||||
|
**Outcome:** The full pipeline runs safely across failures and restarts, including exact retained-output review/resume for arbitrary new supported uploads.
|
||||||
|
|
||||||
|
The existing prompt below is extended by implementation guide Section 6.1/6.2 and API D06/D07: retain bounded review candidates under the current claim, release leases on review-required failure, record evidence-bound decisions, resume inspected output without repeated OCR, and keep factual FAQ group inclusion separate from faithful originals. These backend extensions are now implemented with forward revision 0003_extraction_review. D06/D07 HTTP integration still requires authenticated administrator/organization, Origin and CSRF support; this prerequisite is absent and full extended Phase 5 is not complete. See [worker operations](../guides/worker-orchestration.md) for actual behavior and checks. Governing FAQ context, review-note metadata separation and identical complete-artifact attachment replay are repaired with provider-free and isolated PostgreSQL regressions; see the latest operations acceptance. Applied revisions 0001-0003 are unchanged.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Phase 5: worker orchestration and atomic publication.
|
||||||
|
|
||||||
|
Add `python -m app.worker`, with continuous polling and a --once mode
|
||||||
|
that processes at most one eligible job.
|
||||||
|
|
||||||
|
Claim eligible queued or expired jobs with SKIP LOCKED, a fresh claim
|
||||||
|
token, lease, and incremented attempt count. Exclude deleted documents.
|
||||||
|
Commit claims quickly and use the documented document-before-job lock
|
||||||
|
order for subsequent updates.
|
||||||
|
|
||||||
|
Run extract -> chunk -> embed -> publish with durable stage reporting.
|
||||||
|
Maintain heartbeats during extraction and provider waits. Fence all
|
||||||
|
progress, heartbeat, retry, failure, and publication writes by the claim
|
||||||
|
token and valid lease. A stale worker must discard its results.
|
||||||
|
|
||||||
|
Implement durable extraction attachment/finalization under that same ownership
|
||||||
|
check. Validate bounded candidates, trusted artifact digest, original checksum,
|
||||||
|
frozen extraction identity, completeness/source coverage and warnings before reuse.
|
||||||
|
Use the separate extraction namespace and no-replace candidates; do not overwrite
|
||||||
|
successful extraction with stale results. Keep original reconciliation accurate
|
||||||
|
and artifact inventory report-only. Prefer file/JSONB storage; if a persisted
|
||||||
|
pointer is necessary, use a forward migration and update compatibility checks,
|
||||||
|
never edit the initial revision. No block/page/staging tables are needed.
|
||||||
|
|
||||||
|
Publish in one transaction: lock document then job; verify ownership,
|
||||||
|
unexpired lease, eligible document state, non-deletion, original/profile
|
||||||
|
compatibility, and complete staged results; insert all chunks; update
|
||||||
|
chunk_count/ready_at/status and mark the job succeeded. Keep is_active=false.
|
||||||
|
Never republish a ready document.
|
||||||
|
|
||||||
|
Rollback everything on publication failure. Recover ambiguous commit
|
||||||
|
outcomes by re-reading durable state before retrying. A successful commit
|
||||||
|
followed by a worker crash must not duplicate chunks.
|
||||||
|
|
||||||
|
Schedule transient failures with bounded backoff/jitter. Fail permanent
|
||||||
|
errors immediately and exhausted jobs terminally. Crash recovery restarts
|
||||||
|
processing and may reuse a complete validated extraction artifact; no
|
||||||
|
embedding batch checkpoints or repeated OCR solely for re-chunking.
|
||||||
|
|
||||||
|
Add `python -m app.ingest retry` for eligible failed documents, with an
|
||||||
|
idempotency key and administrator validation. Reuse the same document/job,
|
||||||
|
reset attempts, increment retry_generation once, and audit atomically.
|
||||||
|
|
||||||
|
Acceptance: real database tests cover concurrent claims, lease expiry,
|
||||||
|
stale worker writes, late provider responses, exhausted recovery,
|
||||||
|
publication rollback, ambiguous completion, artifact attachment/lease races,
|
||||||
|
crash-safe validated extraction reuse, and retry replay.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 6 — Integration proof and handoff
|
||||||
|
|
||||||
|
**Outcome:** A reproducible demonstration proves the pipeline's guarantees.
|
||||||
|
|
||||||
|
Phase 6 implementation is recorded in the [operator handoff](../guides/ingestion-operator-handoff.md): real-extractor/deterministic-provider PostgreSQL integration tests, redacted worker heartbeat/stage reporting and a separate opt-in provider smoke command. See the reference map for actual validation results. Scoped pgvector search/selection is next; existing chat remains on Chroma. Real-provider compatibility and extraction/semantic quality require independent approved-corpus validation.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Phase 6: integration validation and operator handoff.
|
||||||
|
|
||||||
|
Build end-to-end tests using isolated PostgreSQL/pgvector, a temporary
|
||||||
|
original-file directory, real extractors, and a deterministic fake
|
||||||
|
embedding provider.
|
||||||
|
|
||||||
|
Prove that chunks remain absent while embedding batches are incomplete,
|
||||||
|
then appear together with ready/succeeded state after publication.
|
||||||
|
Verify exact row count, contiguous ordinals, source locations, profile,
|
||||||
|
and vector dimension. Confirm documents remain inactive.
|
||||||
|
|
||||||
|
Exercise crashes before publication and after commit, a failed final
|
||||||
|
embedding batch, expired claims, deletion before publication, missing
|
||||||
|
originals, duplicate imports, and idempotent manual retry.
|
||||||
|
|
||||||
|
Add worker heartbeat reporting and redacted logs containing document/job
|
||||||
|
IDs and stage/error categories. Document setup, migration, bootstrap,
|
||||||
|
import, status, retry, worker, and reconciliation commands.
|
||||||
|
|
||||||
|
Provide a separate opt-in real-provider smoke command requiring explicit
|
||||||
|
corpus and provider configuration. Keep it out of ordinary tests and
|
||||||
|
report provider compatibility and extraction quality separately.
|
||||||
|
|
||||||
|
Update README and the reference map. Clearly document that the existing
|
||||||
|
chat retriever still uses Chroma and that pgvector search/selection is
|
||||||
|
the next milestone.
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Final acceptance criteria
|
||||||
|
|
||||||
|
The current release also requires delivery-plan MVP-01 through MVP-14 and unseen new browser uploads. Completing ingestion alone does not certify the voice MVP. Review-required/resume/factual-group checks extend the worker acceptance; prior Phase 1-4 recorded results remain unchanged.
|
||||||
|
|
||||||
|
This milestone is complete when:
|
||||||
|
|
||||||
|
- Approved readable text, PDF, DOCX and image sample intake creates a durable, independent document/job; format validation is implemented; this is intake evidence only.
|
||||||
|
- Extraction and chunking preserve source locators, numeric meaning/exclusions, FAQ pairs and infographic heading relationships; visibly unreliable output never reaches search.
|
||||||
|
- **Every chunk is embedded before any chunk is published.**
|
||||||
|
- Publication commits all chunks and completion state together.
|
||||||
|
- Failures, restarts, duplicate requests, and stale workers cannot create partial or duplicate publication.
|
||||||
|
- Configuration overrides work and processing profiles remain traceable.
|
||||||
|
- Published documents remain inactive until a later authorized selection workflow.
|
||||||
|
- Automated PostgreSQL evidence and documented operator commands support these claims; real-provider validation is reported separately.
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# Live document MVP TODO
|
||||||
|
|
||||||
|
Updated 2026-10-07 against the revision 1.3 specifications.
|
||||||
|
|
||||||
|
This checklist tracks implementation; it does not replace the governing
|
||||||
|
[delivery plan](../specifications/RAG-AI-Phase1-Delivery-Plan.md),
|
||||||
|
[implementation guide](../specifications/RAG-Phase1-Implementation-Guide.md),
|
||||||
|
[API catalog](../specifications/RAG-Phase1-API-Catalog.md) or
|
||||||
|
[database design](../specifications/RAG-Phase1-Database-Design.md).
|
||||||
|
Checked baseline items mean existing component implementation, not end-to-end
|
||||||
|
MVP acceptance. See the reference map for executed component checks; these do not certify the full MVP.
|
||||||
|
|
||||||
|
## Existing baseline to reuse
|
||||||
|
|
||||||
|
- [x] Phase 1: PostgreSQL/pgvector foundation, frozen processing/embedding profiles and trusted bootstrap.
|
||||||
|
- [x] Phase 2: bounded CLI intake, immutable originals, independent document/job IDs and request replay.
|
||||||
|
- [x] Phase 3: extraction, normalization, semantic chunk drafts, QC and immutable artifact candidates.
|
||||||
|
- [x] Phase 4: hosted embedding adapter, vector validation and bounded in-memory staging.
|
||||||
|
- [x] English revision 1.3 scope, workflow, API/database proposals and acceptance scenarios documented.
|
||||||
|
- [x] Phase 5 backend: worker, durable fenced artifact attachment, review/resume and atomic publication. Authenticated D06/D07 transport remains pending.
|
||||||
|
- [x] Phase 6: ingestion end-to-end acceptance and operational handoff; real-provider/Persian quality remains separate.
|
||||||
|
|
||||||
|
Do not rebuild Phases 1-4 for LangChain. A custom retriever/tool can call the
|
||||||
|
existing application services; a thin Embeddings wrapper is optional.
|
||||||
|
The prototype Chroma/Markdown chat does not search this upload pipeline.
|
||||||
|
|
||||||
|
## WP1 - Early real-provider proof
|
||||||
|
|
||||||
|
- [ ] Configure funded fixed embedding, extraction and Live profiles; verify compatible embedding identity/dimension.
|
||||||
|
- [ ] Prove Persian microphone input, spoken output and available transcripts on the target network.
|
||||||
|
- [ ] Prove a Live tool call executes on the backend and returns evidence.
|
||||||
|
- [ ] Verify provider audio formats, turn completion, interruption and error behavior.
|
||||||
|
- [ ] Record measured latency, provider cost and the delivery gate result.
|
||||||
|
|
||||||
|
Run this gate early while independent worker/API work continues. Four days is
|
||||||
|
conditional; three days is optimistic. A failed provider/network proof must be
|
||||||
|
reported before promising a live demo.
|
||||||
|
|
||||||
|
## WP2 - Identity and general browser upload
|
||||||
|
|
||||||
|
- [ ] Add forward auth/session schema and pre-created admin/user accounts; preserve the applied initial migration.
|
||||||
|
- [ ] Implement login, logout and current-user endpoints with trusted cookie identity, expiry, Origin and CSRF checks.
|
||||||
|
- [ ] Implement bounded authenticated multipart upload using the existing intake service.
|
||||||
|
- [ ] Preserve byte/title deduplication, immutable originals and independent documents for new upload keys.
|
||||||
|
- [ ] Expose document/job status and failure details according to the API catalog.
|
||||||
|
- [ ] Enforce declared format/structure/resource limits for future uploads of unknown total count.
|
||||||
|
|
||||||
|
The four supplied examples are acceptance fixtures, not a filename allowlist
|
||||||
|
or a four-document capacity limit.
|
||||||
|
|
||||||
|
## WP3 - Worker, review and publication (backend implemented; transport/selection pending)
|
||||||
|
|
||||||
|
- [x] Add reviewed forward extraction-state/audit changes without editing applied revisions.
|
||||||
|
- [x] Implement separate worker claim tokens, leases, heartbeats, bounded attempts and recovery.
|
||||||
|
- [x] Run existing extraction/chunking/embedding under the frozen processing profile.
|
||||||
|
- [x] Attach retained candidates/artifacts only under the current fenced claim.
|
||||||
|
- [x] Implement trusted D06/D07 backend services for exact-output review and evidence/digest-bound approval or rejection.
|
||||||
|
- [ ] Integrate authenticated D06/D07 transport with identity/organization/Origin/CSRF.
|
||||||
|
- [x] Release review-required work as failed with EXTRACTION_REVIEW_REQUIRED; avoid automatic repeated provider calls.
|
||||||
|
- [x] Resume the same eligible failed document/job through the trusted retry backend/CLI after approval; fresh output requires fresh review. Authenticated D04 transport remains pending.
|
||||||
|
- [x] Retain faithful complete FAQ extraction and explicitly approve included factual Q&A groups.
|
||||||
|
- [x] Publish all validated chunks plus ready state in one transaction; keep new ready documents inactive.
|
||||||
|
- [ ] Implement activation/selection revisions, access epochs and invalidation with the documented lock order.
|
||||||
|
- [x] Verify duplicate workers, expired leases, stale approvals, retries and partial failures against isolated PostgreSQL.
|
||||||
|
|
||||||
|
## WP4 - Shared scoped search
|
||||||
|
|
||||||
|
- [ ] Implement one backend pgvector search service using compatible bounded query embeddings.
|
||||||
|
- [ ] Derive organization/user/conversation scope from backend identity.
|
||||||
|
- [ ] Filter to authorized, ready, active and undeleted documents.
|
||||||
|
- [ ] Combine semantic evidence with exact normalized identifiers and bounded context.
|
||||||
|
- [ ] Return faithful text and document_id/chunk_id/location sources.
|
||||||
|
- [ ] Evaluate real Persian questions, numbers, conditions, exceptions and insufficient-evidence behavior.
|
||||||
|
- [ ] Record the measured decision on reranking/ANN; implement only if evaluation demonstrates a need.
|
||||||
|
|
||||||
|
## WP5 - LangChain and native Live
|
||||||
|
|
||||||
|
- [ ] Expose the shared search through a small LangChain retriever/tool boundary.
|
||||||
|
- [ ] Keep persistent secrets and provider-specific objects behind server adapters.
|
||||||
|
- [ ] Add minimal owned voice conversations, Live sessions and voice tool-call persistence through forward migrations.
|
||||||
|
- [ ] Implement session reservation and authenticated backend WSS audio relay to Gemini Live.
|
||||||
|
- [ ] Dispatch tools with trusted backend context; model arguments cannot override identity or knowledge scope.
|
||||||
|
- [ ] Correlate current-session transcripts, tool results and displayed sources.
|
||||||
|
- [ ] Handle follow-up context, interruption/cancellation, provider failure and session termination.
|
||||||
|
- [ ] Suppress stale evidence/audio after knowledge changes, access revocation or cancellation.
|
||||||
|
- [ ] Keep blocking embedding/provider calls off the audio event loop with bounded concurrency/deadlines.
|
||||||
|
|
||||||
|
## WP6 - UI, deployment and acceptance
|
||||||
|
|
||||||
|
- [ ] Build same-origin login and a minimal voice workspace with connection/microphone states.
|
||||||
|
- [ ] Add an admin Documents area for upload, status, retained review, retry and activation.
|
||||||
|
- [ ] Show available current-session transcripts/sources and actionable failures.
|
||||||
|
- [ ] Deploy one API and one separate worker with PostgreSQL/pgvector, persistent files and HTTPS/WSS.
|
||||||
|
- [ ] Validate both sample PDFs: reading order, dates, percentages, conditions and exceptions.
|
||||||
|
- [ ] Validate the sample infographic: headings and group relationships.
|
||||||
|
- [ ] Validate the sample DOCX: all 100 Q&A pairs and explicit factual inclusion.
|
||||||
|
- [ ] Validate unseen in-scope documents uploaded through the UI without code changes.
|
||||||
|
- [ ] Run provider-free regressions and isolated PostgreSQL acceptance with required database configuration.
|
||||||
|
- [ ] Run separately configured real-provider quality/voice checks; ordinary test skips are not acceptance.
|
||||||
|
- [ ] Rehearse upload-to-reviewed-ready-to-active-to-live-answer, follow-ups and interruption on the deployed target.
|
||||||
|
- [ ] Verify restart recovery, revocation, failure reporting and all MVP-01 through MVP-14 criteria.
|
||||||
|
- [ ] Record actual results, remaining limits and demo run instructions.
|
||||||
|
|
||||||
|
## Conditional delivery checkpoints
|
||||||
|
|
||||||
|
| Checkpoint | Required progress |
|
||||||
|
| --- | --- |
|
||||||
|
| Day 1 | WP1 proof started/completed; WP3 worker foundation and WP2 identity/upload underway |
|
||||||
|
| Day 2 | Reviewed complete ingestion/publication and activation; WP4 scoped evidence search |
|
||||||
|
| Day 3 | WP5 LangChain/Live connected; minimal WP6 browser flows |
|
||||||
|
| Day 4 | Example/unseen-file acceptance, failures/revocation/restart and HTTPS rehearsal |
|
||||||
|
|
||||||
|
Dependencies govern order; this table does not assume parallel staffing or
|
||||||
|
guarantee completion. Use delivery-plan Section 8 for the governing schedule.
|
||||||
|
|
||||||
|
## Deferred beyond this MVP
|
||||||
|
|
||||||
|
Full text chat and durable message/history UI, settings editing, rich management/
|
||||||
|
delete UI, recording, seamless reconnect, CTI and reranker/ANN without evidence.
|
||||||
|
Preserve their documented future contracts without making them Live prerequisites.
|
||||||
|
|
||||||
|
When an item is completed, attach the relevant implementation and actual
|
||||||
|
verification evidence. Do not check it solely because its design is documented.
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
# Fast-Track Search MVP - Implementation Plan
|
||||||
|
|
||||||
|
**Date:** 2026-10-07
|
||||||
|
**Target file:** `docs/plans/scoped-search-implementation-plan.md`
|
||||||
|
**Status:** Approved planning direction; implementation and acceptance remain pending. This four-phase plan replaces the earlier seven-phase proposal.
|
||||||
|
|
||||||
|
## 1. Delivery Strategy
|
||||||
|
|
||||||
|
**The first phase must deliver a visible search result.** Selection, compatible query embeddings, pgvector retrieval, and a minimal inspection CLI are implemented together.
|
||||||
|
|
||||||
|
There are four phases:
|
||||||
|
|
||||||
|
| Phase | Deliverable | Observable checkpoint |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | Working vertical slice | Ask a question and see actual uploaded-document chunks and sources |
|
||||||
|
| 2 | Retrieval correctness | Exact identifiers, bounded evidence, calibrated outcomes, and revocation tests |
|
||||||
|
| 3 | LangChain integration | The model-facing tool invokes the same search service |
|
||||||
|
| 4 | Quality gate and handoff | Real Persian evaluation passes and operator instructions are complete |
|
||||||
|
|
||||||
|
Do not postpone the first result until all adapters, evaluation infrastructure, or documentation are finished. Run targeted checks while building; run full regression acceptance at the final checkpoint.
|
||||||
|
|
||||||
|
The first result depends on a working PostgreSQL/pgvector database, one approved processed document, and compatible funded embedding credentials. If credentials are unavailable, deterministic database evidence can prove the connection, but must be labeled as provider-free validation.
|
||||||
|
|
||||||
|
No fixed completion time is promised before these prerequisites are checked. **The first-result checkpoint is the end of Phase 1.**
|
||||||
|
|
||||||
|
## 2. Shared Contracts and Scope
|
||||||
|
|
||||||
|
Read `AGENTS.md`, the [reference map](../agent-reference-map.md), and the applicable sections of the [implementation guide](../specifications/RAG-Phase1-Implementation-Guide.md), [API catalog](../specifications/RAG-Phase1-API-Catalog.md), [database design](../specifications/RAG-Phase1-Database-Design.md), and [MVP scenarios](../specifications/RAG-Phase1-MVP-Scenarios.md). The [delivery plan](../specifications/RAG-AI-Phase1-Delivery-Plan.md) governs Phase 1 scope.
|
||||||
|
|
||||||
|
This plan uses milestone phases 1-4; these labels do not replace the existing ingestion phase numbering or the product's Phase 1 contracts.
|
||||||
|
|
||||||
|
Preserve these requirements from the beginning:
|
||||||
|
|
||||||
|
- Reuse existing ingestion, embeddings, worker, review, and publication.
|
||||||
|
- Resolve organization and role from the persisted enabled actor.
|
||||||
|
- Search only authorized, ready, active, undeleted, unpurged documents.
|
||||||
|
- Activate through an atomic selection service, never direct SQL shortcuts.
|
||||||
|
- Preserve selection revisions, access epochs, and audit behavior.
|
||||||
|
- Keep provider calls outside database transactions.
|
||||||
|
- Verify full embedding identity, input limits, normalization, and float32 vectors.
|
||||||
|
- Return faithful text, document/chunk IDs, and actual locators.
|
||||||
|
- Preserve applied migrations and unrelated working-tree changes.
|
||||||
|
- Technical failures remain errors, never "no evidence."
|
||||||
|
- Keep one retrieval implementation for inspection, LangChain, and later Live.
|
||||||
|
- Do not introduce document-content versioning or overwrite original uploads.
|
||||||
|
|
||||||
|
Backend defaults are five returned chunks and 12,000 evidence-text characters. Return whole chunks; skip a chunk that cannot fit rather than removing its conditions or exceptions.
|
||||||
|
|
||||||
|
Public HTTP search, browser authentication, UI, text/history, Live transport, persistent tool dispatch, reranking, and ANN are outside this milestone.
|
||||||
|
|
||||||
|
The inspection CLI may show uncalibrated retrieval candidates, clearly labeled as such. This is an operator diagnostic format, not the model-tool contract or a quality claim. It uses the same retrieval core and eligibility rules.
|
||||||
|
|
||||||
|
The final tool accepts only required `query` and optional `context`, each bounded by the existing API contract: query is 1-2000 characters; context is at most 2000 characters. Reject unknown fields and whitespace-only queries. Context is an untrusted retrieval hint, not evidence or authority. Authority, profile, limits, execution IDs, and source-reference allocation remain backend-owned.
|
||||||
|
|
||||||
|
The operator CLI follows the existing trusted intake model. An operator-supplied user UUID is not HTTP authentication and must never become an unauthenticated web identity mechanism. Enabled administrators manage selection; enabled administrators and normal users may execute authorized search.
|
||||||
|
|
||||||
|
Search captures and rechecks access epoch and enabled actor around remote work. No conversation or Live tables are required here. Future sessions must integrate with the same epoch boundary; this milestone does not claim to close sessions that do not yet exist.
|
||||||
|
|
||||||
|
All phases must inspect Git status, preserve unrelated tracked and untracked files, and report actual checks. Do not delegate to sub-agents. Missing infrastructure is an unrun prerequisite, not successful acceptance. Keep ordinary tests deterministic and provider-free.
|
||||||
|
|
||||||
|
## 3. Implementation Phases and Exact Prompts
|
||||||
|
|
||||||
|
### Phase 1 - First Search Result
|
||||||
|
|
||||||
|
**Build only what is needed to exercise one complete path:**
|
||||||
|
|
||||||
|
1. Read this saved plan and inspect the baseline.
|
||||||
|
2. Implement trusted actor resolution and selection get/replace.
|
||||||
|
3. Add compatible one-input query embedding and scoped cosine retrieval.
|
||||||
|
4. Add a single-query inspection CLI.
|
||||||
|
5. Demonstrate retrieval from one approved uploaded document.
|
||||||
|
|
||||||
|
Selection uses the existing K01/K02 semantics: full-set replacement, expected revision, atomic validation, unchanged counters for no-op, knowledge revision for changes, access epoch for removals, and an audit event for successful changes. Lock settings before affected documents, using stable document-ID order. Reject duplicate IDs, hidden/deleted/purged IDs, unready documents, and stale revisions without a partial update. Preserve configuration revision.
|
||||||
|
|
||||||
|
Use existing provider and validation utilities. Add no dependency for this phase.
|
||||||
|
|
||||||
|
**Planned commands**
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m app.knowledge selection get --administrator-id <admin-id>
|
||||||
|
|
||||||
|
.venv/Scripts/python -m app.knowledge selection replace `
|
||||||
|
--administrator-id <admin-id> `
|
||||||
|
--expected-revision <revision> `
|
||||||
|
--document-id <document-id>
|
||||||
|
|
||||||
|
.venv/Scripts/python -m app.search `
|
||||||
|
--inspect `
|
||||||
|
--user-id <user-id> `
|
||||||
|
--query "<Persian question>" `
|
||||||
|
--allow-provider-calls
|
||||||
|
```
|
||||||
|
|
||||||
|
Document IDs are repeatable; explicit `--clear` replaces the selection with an empty set and is mutually exclusive with document IDs. Result JSON goes to stdout; safe diagnostics go to stderr.
|
||||||
|
|
||||||
|
**Acceptance:** an inactive document yields no candidates; after legitimate selection, a query returns actual chunk text and source identities. Foreign and ineligible documents remain excluded.
|
||||||
|
|
||||||
|
**Execution prompt**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use $implement-feature to implement Phase 1 of the Fast-Track Search MVP.
|
||||||
|
|
||||||
|
Read docs/plans/scoped-search-implementation-plan.md, AGENTS.md, the
|
||||||
|
reference map, and governing selection/search/database contracts.
|
||||||
|
Inspect Git status and preserve all unrelated tracked and untracked
|
||||||
|
changes. Preserve applied migrations.
|
||||||
|
|
||||||
|
Deliver a working vertical slice in this phase:
|
||||||
|
persisted enabled-actor resolution -> atomic knowledge selection ->
|
||||||
|
compatible query embedding -> scoped pgvector cosine retrieval ->
|
||||||
|
single-query inspection CLI.
|
||||||
|
|
||||||
|
Reuse existing ingestion, embedding adapter, preprocessing, input-limit,
|
||||||
|
tokenizer, float32-vector, and database compatibility utilities.
|
||||||
|
Do not import the prototype Chroma retriever.
|
||||||
|
|
||||||
|
Implement full-set selection with expected revision, documented
|
||||||
|
counter behavior, settings-first locking, and atomic audit updates.
|
||||||
|
Search derives organization from the actor and applies every eligibility
|
||||||
|
filter. Revalidate actor and access epoch before delivering results.
|
||||||
|
Keep remote calls outside transactions and use finite provider/SQL
|
||||||
|
timeouts.
|
||||||
|
|
||||||
|
Inspection output must identify results as uncalibrated candidates and
|
||||||
|
include faithful text, title, document_id, chunk_id, and location.
|
||||||
|
Require explicit provider-call opt-in. This diagnostic output is not
|
||||||
|
a model-tool response or semantic-quality certification.
|
||||||
|
|
||||||
|
Add targeted tests for selection/counters, organization isolation,
|
||||||
|
eligibility, profile mismatch, invalid vectors, and inactive-to-active
|
||||||
|
retrieval using real PostgreSQL.
|
||||||
|
|
||||||
|
As soon as targeted checks pass, demonstrate one approved real document
|
||||||
|
and query if prerequisites are available. Otherwise demonstrate the
|
||||||
|
provider-free database path and identify the missing prerequisite.
|
||||||
|
|
||||||
|
Stop at the first-result checkpoint. Do not build LangChain, UI,
|
||||||
|
evaluation infrastructure, ANN, or unrelated abstractions.
|
||||||
|
Report the exact demonstration command and observed result.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2 - Make Retrieval Reliable
|
||||||
|
|
||||||
|
**Add:**
|
||||||
|
|
||||||
|
- Normalized exact identifier/date/article matching alongside cosine candidates.
|
||||||
|
- Deterministic merge and deduplication.
|
||||||
|
- Whole-chunk evidence budgeting and source references.
|
||||||
|
- Canonical `ok`, `no_evidence`, and `error` results.
|
||||||
|
- Profile-specific cutoff calibrated from ten separate cases.
|
||||||
|
- Revocation, publication-boundary, and failure tests.
|
||||||
|
|
||||||
|
Lexical comparison handles Persian/Arabic digit equivalence, kaf/yeh equivalence, NFC, case, and whitespace. Preserve dates, separators, source text, and embedding preprocessing. Use boundary-aware matching; arbitrary isolated numbers are not identifiers.
|
||||||
|
|
||||||
|
Each semantic/exact branch retrieves at most 50 eligible candidates. Deduplicate by chunk ID; rank exact matches first, then cosine distance and stable chunk ID. Exact matching cannot bypass evidence admission.
|
||||||
|
|
||||||
|
Successful sources follow API Section 7.2: `source_ref`, `document_id`, `chunk_id`, `title`, faithful `text`, and `location.page/section`. Preserve nullable locators; do not invent pagination. Allocate source references consistently across searches in one execution. No evidence means completed retrieval with insufficient support; provider, SQL, profile, timeout, and revoked-context failures are normalized errors.
|
||||||
|
|
||||||
|
Calibrate on six answerable and four unsupported questions. Select the cutoff maximizing complete-support coverage with zero unsupported false positives; choose the stricter cutoff on ties. If none works, report the measured failure and repair the baseline. Do not change the pinned embedding profile or weaken expected evidence to obtain a pass.
|
||||||
|
|
||||||
|
**Execution prompt**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use $implement-feature to implement Phase 2 only.
|
||||||
|
|
||||||
|
Read the plan and governing contracts. Preserve unrelated changes,
|
||||||
|
applied migrations, and the Phase 1 working path.
|
||||||
|
|
||||||
|
Extend the SAME retrieval core with parameterized normalized exact
|
||||||
|
identifier/date/article matching. Apply all eligibility predicates
|
||||||
|
before ranking and limits in every branch. Preserve evidence and
|
||||||
|
embedding preprocessing.
|
||||||
|
|
||||||
|
Implement bounded candidate merge, deterministic ordering, deduplication,
|
||||||
|
whole-chunk budgeting, actual locators, and execution-wide source
|
||||||
|
references. Enforce five chunks and 12000 evidence-text characters.
|
||||||
|
|
||||||
|
Add canonical tool-result outcomes. Provider, SQL, timeout, compatibility,
|
||||||
|
and revoked-context failures remain normalized technical errors.
|
||||||
|
|
||||||
|
Create ten independently annotated calibration cases: six answerable,
|
||||||
|
four unsupported. Use the configured compatible real model only with
|
||||||
|
explicit provider-call authorization. Calibrate and record the cutoff
|
||||||
|
using the plan's selection rule; do not invent a universal threshold.
|
||||||
|
|
||||||
|
Capture and recheck access epoch and enabled actor around provider work.
|
||||||
|
Use short settings-locked retrieval transactions. Add bounded barrier
|
||||||
|
tests for removal and actor disablement during execution.
|
||||||
|
|
||||||
|
Add real PostgreSQL integration coverage from ingestion/publication
|
||||||
|
through selection/search, including independent literal expected
|
||||||
|
numbers, conditions, negation, and exceptions. Verify partial publication
|
||||||
|
and failed batches never become searchable.
|
||||||
|
|
||||||
|
Run affected unit and database tests. Keep the inspection CLI available.
|
||||||
|
If calibration prerequisites are missing, finish independent technical
|
||||||
|
work and report model-quality acceptance as pending.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3 - Thin LangChain Tool
|
||||||
|
|
||||||
|
**Add only the framework boundary required by the MVP.**
|
||||||
|
|
||||||
|
- Dedicated `search` extra: `langchain-core>=1,<2`.
|
||||||
|
- Strict `search_knowledge` arguments: `query`, optional `context`.
|
||||||
|
- Trusted execution context captured outside model arguments.
|
||||||
|
- Synchronous and asynchronous calls to the same service.
|
||||||
|
- Lazy framework imports and bounded blocking execution.
|
||||||
|
|
||||||
|
Use a thin `StructuredTool` adapter with an explicit argument schema and synchronous/asynchronous entrypoints; see the [official LangChain API reference](https://reference.langchain.com/python/langchain-core/tools/structured/StructuredTool/from_function).
|
||||||
|
|
||||||
|
Default execution limits: four running calls, eight waiting calls, and a 75-second total deadline. SQL statement/lock timeouts are five/two seconds. Validate configuration; retain the explicit provider timeout policy.
|
||||||
|
|
||||||
|
Cancellation suppresses late results. A running blocking call holds its slot until it exits, even if its caller times out. Queue waiting consumes the deadline. Saturation and timeout return normalized technical errors. Do not create unbounded executor queues or internal provider retries.
|
||||||
|
|
||||||
|
**Execution prompt**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use $implement-feature to implement Phase 3 only.
|
||||||
|
|
||||||
|
Follow AGENTS.md, the plan, and the canonical internal tool contract.
|
||||||
|
|
||||||
|
Add the minimal search dependency extra and a lazy LangChain
|
||||||
|
search_knowledge adapter. Expose only query and optional context with
|
||||||
|
strict validation. Capture persisted backend authority, deadline,
|
||||||
|
epoch, cancellation, and source-reference context outside model input.
|
||||||
|
|
||||||
|
Delegate directly to the Phase 2 service. Do not build another retriever,
|
||||||
|
vector store, embedding pipeline, text agent, or Live dispatcher.
|
||||||
|
|
||||||
|
Provide sync and async entrypoints. Run blocking provider/database work
|
||||||
|
off the event loop with the plan's bounded concurrency and admission
|
||||||
|
limits. Queue waiting consumes the deadline. Suppress cancelled or late
|
||||||
|
results, retaining running-work slots until actual completion.
|
||||||
|
|
||||||
|
Test CLI/tool equivalence, forged-scope and unknown-field rejection,
|
||||||
|
canonical results, event-loop responsiveness, saturation, timeout,
|
||||||
|
cancellation, and lazy imports.
|
||||||
|
|
||||||
|
Keep core search and ingestion usable without LangChain. Run actual
|
||||||
|
adapter tests with the declared extra installed; missing dependencies
|
||||||
|
do not count as skipped acceptance.
|
||||||
|
|
||||||
|
Report the tool schema, verified invocation, and remaining final
|
||||||
|
quality gate.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 4 - Persian Quality Gate and Minimal Handoff
|
||||||
|
|
||||||
|
Use the four required example structures and additional unseen documents.
|
||||||
|
|
||||||
|
**Held-out evaluation:**
|
||||||
|
|
||||||
|
- Twenty answerable Persian questions, including at least four about unseen documents.
|
||||||
|
- Six unsupported questions.
|
||||||
|
- Original-source annotations created independently of retrieval output.
|
||||||
|
- Explicit bindings between original hashes and database document IDs.
|
||||||
|
- Frozen profile, cutoff, labels, and search settings before evaluation.
|
||||||
|
|
||||||
|
An answerable case passes when its first five chunks collectively contain every required evidence group. Matching a title or one number is insufficient.
|
||||||
|
|
||||||
|
**Required gate:**
|
||||||
|
|
||||||
|
- At least 18 of 20 answerable cases pass.
|
||||||
|
- Every critical number/condition/negation/exception case passes.
|
||||||
|
- All six unsupported cases return `no_evidence`.
|
||||||
|
- No unauthorized or ineligible evidence appears.
|
||||||
|
- Technical errors are failures, not unsupported-question successes.
|
||||||
|
|
||||||
|
Do not tune against the held-out cases or remove failures from reports. Calibration and held-out questions remain separate. Failure requires a measured repair and a valid reevaluation; do not claim practical retrieval readiness from technical tests alone.
|
||||||
|
|
||||||
|
**Execution prompt**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Use $write-tests for final evaluation and acceptance.
|
||||||
|
|
||||||
|
Read the plan and current implementation. This phase does not silently
|
||||||
|
fix production defects; report failures with their responsible phase.
|
||||||
|
|
||||||
|
Prepare twenty independently annotated answerable Persian questions
|
||||||
|
and six unsupported questions. Cover both supplied PDFs, the infographic,
|
||||||
|
approved factual DOCX content, and at least four unseen-document
|
||||||
|
questions. Annotate evidence from originals, including qualifiers.
|
||||||
|
Do not generate expected facts from search results or indexed FAQs alone.
|
||||||
|
|
||||||
|
Bind approved original hashes to actual document IDs. Use existing
|
||||||
|
intake, worker, review, and selection services. Do not force readiness,
|
||||||
|
activate with raw SQL, or automatically approve human review decisions.
|
||||||
|
|
||||||
|
Run the same search service with the pinned funded model and the
|
||||||
|
Phase 2 frozen cutoff. Require explicit provider-call opt-in and a
|
||||||
|
bounded call budget. Keep real evaluation outside ordinary pytest.
|
||||||
|
|
||||||
|
Apply the exact 18-of-20, all-critical, all-unsupported gate. Record
|
||||||
|
per-case evidence, sources, outcomes, latency, provider calls, and
|
||||||
|
available usage. Mark unavailable billing information as unavailable.
|
||||||
|
|
||||||
|
Classify failures by extraction/review, chunking, publication, selection,
|
||||||
|
compatibility, retrieval/ranking, evidence budgeting, or technical
|
||||||
|
provider/database errors. Preserve every failed case.
|
||||||
|
|
||||||
|
Run the full provider-free and mandatory isolated PostgreSQL suites,
|
||||||
|
pip check, whitespace/new-file inspection, and migration preservation
|
||||||
|
checks.
|
||||||
|
|
||||||
|
Write a short operator guide with actual setup, selection, query,
|
||||||
|
evaluation, troubleshooting, and results. Update plan/reference status.
|
||||||
|
Claim retrieval readiness only if both technical and quality gates pass.
|
||||||
|
Do not claim generated-answer or Live readiness.
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. Verification and Completion
|
||||||
|
|
||||||
|
Run targeted checks before the first-result demonstration. Run full acceptance at Phase 4:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
|
||||||
|
|
||||||
|
.venv/Scripts/python -m tests.postgres_prerequisites
|
||||||
|
|
||||||
|
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
|
||||||
|
|
||||||
|
.venv/Scripts/python -m pip check
|
||||||
|
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Use an isolated `TEST_DATABASE_URL`; missing configuration must fail PostgreSQL acceptance. Inspect untracked files separately and verify the preservation of applied migrations.
|
||||||
|
|
||||||
|
Each phase reports its working command, observed output, actual checks, and remaining prerequisites. Documentation stays proportional to the work. Record technical acceptance and real-provider quality acceptance separately. Historical test results are not checks performed by this plan.
|
||||||
|
|
||||||
|
No latency or concurrent-user service-level target has been approved. Measure timings and enforce the stated execution bounds without claiming an unapproved performance target. Actual provider runs require explicit opt-in, compatible credentials, approved inputs, and a bounded operator call budget.
|
||||||
|
|
||||||
|
**Speed rule:** finish and demonstrate each usable checkpoint before expanding it. Optimize only a reproduced quality or latency problem. The MVP search milestone remains incomplete until the confirmed real-quality gate passes.
|
||||||
+226
-120
@@ -2,48 +2,51 @@
|
|||||||
|
|
||||||
| Document field | Value |
|
| Document field | Value |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| Version | 1.1 — simplified document lifecycle |
|
| Version | 1.3 - LangChain Live document MVP; existing embedding pipeline retained |
|
||||||
| Date | 2026-10-05 |
|
| Date | 2026-10-07 |
|
||||||
| Status | Proposed implementation design; open decisions are listed in Section 19 |
|
| Status | Proposed implementation design; open decisions are listed in Section 19 |
|
||||||
| Audience | Project management, technical mentor, backend, frontend and AI developers |
|
| Audience | Project management, technical mentor, backend, frontend and AI developers |
|
||||||
| Application | Organization-managed document RAG with text and direct live voice conversations |
|
| Application | New-document uploads and direct Persian Live voice; broader text/history design is deferred |
|
||||||
| Source baseline | Project requirements and architecture decisions recorded during design |
|
| 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.
|
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
|
## 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 current milestone is the conditional four-day Live document MVP governed by delivery plan revision 1.3. Known users in one organization upload new supported documents through the browser, activate ready knowledge and ask Persian spoken questions. LangChain exposes the shared scoped retrieval/tool boundary; Gemini Live owns native audio conversation. Full text chat, durable messages and settings editing are deferred. Historical/broader sections below do not expand this active scope.
|
||||||
|
|
||||||
|
The four supplied PDFs/DOCX/image examples are mandatory initial tests, not an upload allowlist or a known final corpus. New files within declared structure/resource limits require no developer code changes.
|
||||||
|
|
||||||
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.
|
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
|
### 1.1 Confirmed design constraints
|
||||||
|
|
||||||
- PostgreSQL with pgvector stores application data and document embeddings.
|
- 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.
|
- Preserve the implemented hosted embedding adapter, validation and staging from ingestion Phases 1-4, including compatible profiles/vectors; funded deployment identity and Persian quality still need proof. Provider comparison is optional, not required delivery work.
|
||||||
- Voice conversations use a live speech-to-speech model and WebRTC. There is no separate application ASR or TTS pipeline.
|
- Initial voice uses direct Gemini Live API access managed by the backend over WSS. There is no mandatory separate ASR, TTS or answer-generation call for each voice turn.
|
||||||
- The agent decides whether to call the knowledge search tool and can repeat a search when necessary.
|
- 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.
|
- 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.
|
- The only initial knowledge tool is `search_knowledge`. 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 internal text-query harness, current Live path and later text chat share one retrieval implementation, access rules and embedding identity. Durable text history is deferred.
|
||||||
- The dashboard includes login, document management, model configuration, text entry and microphone controls.
|
- The MVP UI has login and one workspace with voice and admin upload/status/review/selection. Name/instruction/profiles stay seeded/server-configured; settings editing and full text UI are deferred.
|
||||||
|
- LangChain is the selected RAG/tool framework. Provider-neutral ingestion does not need a wholesale framework refactor.
|
||||||
|
|
||||||
### 1.2 Proposed implementation choices
|
### 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.
|
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. A custom LangChain retriever/tool invokes the existing application search service. Use a thin Embeddings wrapper only where needed, preserving profile/preprocessing, bounds and validation. The provider-native Live session performs the audio conversation loop; optional future LangGraph text orchestration is not an MVP prerequisite.
|
||||||
|
|
||||||
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.
|
These choices separate confirmed product/framework direction from proposed implementation mechanisms, not claims of operational completion. The 2026-10-07 user direction confirms new-document upload, all four initial examples, existing embedding reuse, LangChain and limited-demo scope. Current integration mechanisms remain proposed. Broader model catalogues, SSE/mixed history and extra logical tables below remain future context, not Phase 1 requirements. Representative PDF, DOCX and image extraction are now in MVP scope. Exact model IDs, format/size caps, account eligibility, retention, capacity and delivery dates still require validation. Local-cookie authentication is the proposed Phase 1 implementation.
|
||||||
|
|
||||||
### 1.3 Scope boundaries
|
### 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.
|
The current MVP includes document ingestion/review, organization-scoped retrieval, owned Live voice sessions, retrieved evidence and basic administration/logging. Full text conversations/citations/history and configuration mutation belong to a later milestone. 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
|
## 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.
|
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.
|
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.
|
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.
|
4. **Backend-managed live audio:** the backend relays client audio to direct Gemini Live and executes authorized tools on the same controlled session.
|
||||||
5. **Persistent application state:** provider session state and local process memory are not authoritative conversation history.
|
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.
|
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.
|
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
|
||||||
@@ -53,15 +56,15 @@ The initial system includes document ingestion, organization-scoped retrieval, t
|
|||||||
|
|
||||||
| Component | Responsibilities | Deployment |
|
| Component | Responsibilities | Deployment |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Web dashboard | Login, chat, microphone/speaker, captions, sources, document and settings screens | Browser over HTTPS |
|
| Web dashboard | Login, voice/microphone/speaker, available transcripts/sources, admin upload/status/review/selection | Same-origin HTTPS |
|
||||||
| FastAPI application | Authorization, text orchestration, live session control, tools, document APIs and history | Backend process |
|
| FastAPI application | Authorization, owned voice/session/tool control, document/review/selection APIs and read-only capabilities | Backend process |
|
||||||
| Ingestion worker | Extraction, chunking, embedding, retries and publication | Separate process from the same codebase |
|
| 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 |
|
| PostgreSQL + pgvector | Existing foundation/jobs/chunks/vectors; retained review metadata and new auth/voice/tool records | Persistent database |
|
||||||
| File storage | Original uploaded document bytes | Durable volume or object storage |
|
| File storage | Immutable originals and retained extraction artifacts | Existing durable volume; object storage only if already selected |
|
||||||
| Text/embedding provider | Text-agent inference and vector generation | External OpenAI API |
|
| Embedding/extraction providers | Existing compatible vector generation and direct/vision extraction | Fixed funded profiles; preserve embedding identity |
|
||||||
| Live provider | Direct audio understanding and speech generation | External live model service |
|
| 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.
|
A provider adapter is backend code. It is not the provider service. The browser uses an authenticated application WSS stream to the backend. The backend owns the Gemini Live connection, credentials, policy and tool execution; the provider service remains external.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
@@ -72,9 +75,9 @@ The two presentation diagrams are retained in Appendix A. They show logical resp
|
|||||||
| Identity | Users, organization memberships and session authorization | Authenticate user; resolve organization and role |
|
| 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 |
|
| Documents | File metadata, ingestion state and selection | Upload independent document; list; activate; deactivate |
|
||||||
| Knowledge | Chunk retrieval and evidence construction | Search authorized knowledge |
|
| Knowledge | Chunk retrieval and evidence construction | Search authorized knowledge |
|
||||||
| Conversations | Conversations, turns, messages, citations and summaries | Start; submit turn; read history; close |
|
| Conversations | Owned voice identity/epoch now; text turns/messages/citations later | Create owned voice context; invalidate/close |
|
||||||
| Live Sessions | Provider session mapping, connection state and live event handling | Create; connect control channel; process event; 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 |
|
| Configuration | Seeded instruction/name, fixed profiles and technical revisions | Read capabilities now; editor later |
|
||||||
| Audit/Operations | Administrative events, traces and health | Record audit event; expose operational status |
|
| 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.
|
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.
|
||||||
@@ -91,7 +94,7 @@ Shared organization context is created from authenticated identity. Client input
|
|||||||
| `app/modules/identity/` | Authentication and authorization |
|
| `app/modules/identity/` | Authentication and authorization |
|
||||||
| `app/modules/documents/` | Document lifecycle |
|
| `app/modules/documents/` | Document lifecycle |
|
||||||
| `app/modules/knowledge/` | Retrieval and search tool contracts |
|
| `app/modules/knowledge/` | Retrieval and search tool contracts |
|
||||||
| `app/modules/conversations/` | Text turns and persistent history |
|
| `app/modules/conversations/` | Minimal owned voice context; text/history later |
|
||||||
| `app/modules/live/` | Live session controller |
|
| `app/modules/live/` | Live session controller |
|
||||||
| `app/modules/configuration/` | Model profiles and organization settings |
|
| `app/modules/configuration/` | Model profiles and organization settings |
|
||||||
| `app/integrations/ai/` | Text, embedding and live provider adapters |
|
| `app/integrations/ai/` | Text, embedding and live provider adapters |
|
||||||
@@ -106,7 +109,7 @@ Use application/domain/infrastructure subdivisions where module complexity warra
|
|||||||
|
|
||||||
### 5.1 Agent responsibilities
|
### 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 interprets the user's wording and conversation context, asks clarification when meaning is ambiguous, and calls `search_knowledge` 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.
|
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.
|
||||||
|
|
||||||
@@ -118,9 +121,11 @@ The model's choice to search is probabilistic. A system prompt alone cannot guar
|
|||||||
|
|
||||||
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 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.
|
For live speech, generated audio may be relayed to the user before a server-side semantic 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
|
### 5.3 Text turn sequence (deferred)
|
||||||
|
|
||||||
|
This sequence is preserved for the follow-up text milestone. Current retrieval is tested through an internal query harness; voice is not dependent on a shipped text model/turn loop.
|
||||||
|
|
||||||
1. Authenticate the request and verify conversation ownership.
|
1. Authenticate the request and verify conversation ownership.
|
||||||
2. Persist the user message using a client request ID to detect retries.
|
2. Persist the user message using a client request ID to detect retries.
|
||||||
@@ -137,14 +142,17 @@ A failed turn is recorded explicitly and does not appear as a completed assistan
|
|||||||
|
|
||||||
### 6.1 Model-visible interface
|
### 6.1 Model-visible interface
|
||||||
|
|
||||||
|
The Phase 1 model tool is `search_knowledge`, replacing the earlier proposed `search_documents` name. It maps to one shared backend knowledge service used by text and Live. The prototype's `retriever_tool` is a different, implemented interface.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"name": "search_documents",
|
"name": "search_knowledge",
|
||||||
"description": "Search the organization's selected reference documents for evidence relevant to a question.",
|
"description": "Retrieve authorized evidence for a document-dependent question.",
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"query": {"type": "string", "description": "A focused search question preserving the user's constraints."}
|
"query": {"type": "string"},
|
||||||
|
"context": {"type": "string", "description": "Optional resolved conversational reference; never authorization."}
|
||||||
},
|
},
|
||||||
"required": ["query"],
|
"required": ["query"],
|
||||||
"additionalProperties": false
|
"additionalProperties": false
|
||||||
@@ -152,33 +160,13 @@ A failed turn is recorded explicitly and does not appear as a completed assistan
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
This is a proposed tool schema, not a REST endpoint. Query is required; optional `context` carries a resolved reference such as the circular just discussed. Document filters are deferred until a supported, backend-validated filter contract exists. Reject organization/user IDs, SQL, arbitrary paths and model-selected access scope. Backend execution context supplies identity, allowed documents, embedding profile, limits and correlation IDs.
|
||||||
|
|
||||||
### 6.2 Result contract
|
### 6.2 Result contract
|
||||||
|
|
||||||
```json
|
The canonical proposed `ok | no_evidence | error` payload and JSON examples are in [API catalog Section 7.2](RAG-Phase1-API-Catalog.md). Evidence contains `source_ref`, `document_id`, `chunk_id`, `title`, `text` and `location.page/section`; unavailable locations are null. References identify actual retained chunks and are unique within their turn. Never fabricate an excerpt or page number.
|
||||||
{
|
|
||||||
"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.
|
`no_evidence` means retrieval completed but sufficient supporting evidence was not found. A timeout, embedding/provider failure or revoked context produces `error`, not a fabricated empty-success result.
|
||||||
|
|
||||||
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
|
### 6.3 Execution pipeline
|
||||||
|
|
||||||
@@ -192,7 +180,7 @@ Tool statuses distinguish `ok`, `no_results`, `knowledge_unavailable` and `error
|
|||||||
8. Build references from stored metadata and persist retrieval provenance.
|
8. Build references from stored metadata and persist retrieval provenance.
|
||||||
9. Return evidence to the requesting text or live agent.
|
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.
|
Recommend semantic plus lexical retrieval for document/article numbers, dates and organization names using the existing PostgreSQL stack. If hybrid fusion exceeds the schedule, semantic retrieval plus exact normalized identifier matching is the minimum proposed option. Apply the same eligibility checks and evidence budget to both paths. Reranking remains optional. 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.
|
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.
|
||||||
|
|
||||||
@@ -200,9 +188,76 @@ Similarity values are ranking signals, not probabilities that an answer is corre
|
|||||||
|
|
||||||
### 7.1 Upload and extraction
|
### 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.
|
Authenticated upload preserves an immutable original under a generated storage key and creates an independent document plus durable job. Filename is display metadata, never a path. Use one downstream text pipeline for readable text and image-derived text; choose extraction by actual page content and quality.
|
||||||
|
|
||||||
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.
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
U["Upload: independent document and immutable original"] --> J["Queued job; worker claims lease"]
|
||||||
|
J --> F{"Actual content"}
|
||||||
|
F -->|DOCX or readable text| D["Paragraphs and tables; keep Q and A together"]
|
||||||
|
F -->|PDF page| P["Attempt direct extraction on this page"]
|
||||||
|
F -->|Image or scanned page| O["OCR or vision: faithful transcription"]
|
||||||
|
P --> Q{"Readable, complete, ordered; numbers checked?"}
|
||||||
|
Q -->|Yes| B["Common extracted blocks and page method"]
|
||||||
|
Q -->|No or uncertain| R["Render affected page"]
|
||||||
|
R --> O
|
||||||
|
D --> B
|
||||||
|
O --> B
|
||||||
|
B --> C{"Simple checks and manual review where uncertain"}
|
||||||
|
C -->|Reliable| A["Retain source text and normalized search text"]
|
||||||
|
C -->|Visibly unreliable| X["Fail visibly; no indexing"]
|
||||||
|
A --> K["Semantic chunks and compatible embeddings"]
|
||||||
|
K --> T["Fenced atomic publication; ready and inactive"]
|
||||||
|
T --> S["Admin inspects and activates"]
|
||||||
|
```
|
||||||
|
|
||||||
|
For DOCX, extract paragraphs and tables in meaningful order, preserving headings, cells and question/answer relationships. This sample bank stores many questions and answers in adjacent rows: pair by the actual labels/order, not by assuming one FAQ per row. Use `page=null` and a `section` locator containing table/row range or Q&A identifier; DOCX pagination is not reliable.
|
||||||
|
|
||||||
|
For each PDF page, attempt direct extraction if text is usable. Check reading order, completeness and important numeric fields against the page. A non-empty text layer does not prove readability. Render only affected pages for OCR/vision fallback; mixed extraction methods within one PDF are supported and recorded per page. This is simple checks plus manual inspection for uncertain pages, not a required automatic quality classifier.
|
||||||
|
|
||||||
|
Preferred initial extraction API candidate: a configurable Gemini Flash vision model; `gemini-2.5-flash` appears in the official pricing catalog checked on 2026-10-06. Availability and account access must be verified before use. PDF vision can retain layout information; raw non-PDF input should not be assumed to retain DOCX table structure. See [Gemini document processing](https://ai.google.dev/gemini-api/docs/document-processing) and [pricing](https://ai.google.dev/gemini-api/docs/pricing). Mistral OCR is an optional benchmark alternative; PaddleOCR is a future local candidate only after verifying Persian support. Neither is mandatory.
|
||||||
|
|
||||||
|
Proposed extraction instruction:
|
||||||
|
|
||||||
|
> Transcribe all visible source content; do not summarize. Preserve headings, subheadings, lists, conditions, exclusions and reading order. Associate each infographic heading with its own description and parent group. Mark unreadable regions explicitly. Do not guess or silently correct numbers, dates, names or identifiers. Keep any warning or interpretation separate from the transcribed text.
|
||||||
|
|
||||||
|
The common logical representation extends the existing `ExtractedBlock` concept with document ID/title supplied by its envelope, `page` or `section`, block type/heading, faithful `text`, extraction method/model and warnings. These are logical fields, not one table per concept. Proposed artifact example; the text placeholder is deliberately not a source quotation:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"document_id": "10000000-0000-4000-8000-000000000003",
|
||||||
|
"title": "Administrative reform infographic",
|
||||||
|
"blocks": [{
|
||||||
|
"page": null,
|
||||||
|
"section": "image/group-right/item-1",
|
||||||
|
"block_type": "heading_with_description",
|
||||||
|
"heading": "<verified parent and child headings>",
|
||||||
|
"text": "<complete manually checked transcription>",
|
||||||
|
"extraction_method": "vision",
|
||||||
|
"model": "<configured-extraction-model>",
|
||||||
|
"warnings": []
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep original bytes, faithful extracted text and derived normalized search text separately where practical. Normalize Persian/Arabic character variants and whitespace for search while preserving source display, ZWNJ where meaningful, digit order, decimal separators, units and numeric meaning. Record the preprocessing profile. Extraction artifacts allow chunking or embedding changes without paying for OCR again; see [database Section 4.4](RAG-Phase1-Database-Design.md).
|
||||||
|
|
||||||
|
Quality checks explicitly cover reversed dates/digits, dropped negation or exclusions, missing/duplicated blocks, wrong reading order and unreadable regions. Compare critical fields to the original; do not fix them by guesswork. No invented model confidence percentage. Proposed simple gate: uncertain pages are manually checked before publication; visibly unreliable extraction fails with a redacted quality reason and no chunks. The existing queued/processing/ready/failed lifecycle remains. Review does not require a new document state or approval subsystem.
|
||||||
|
|
||||||
|
### 7.1.1 Retained review for arbitrary new uploads
|
||||||
|
|
||||||
|
Current PDF page/vision extraction requires evidence-bound review. Retain exact
|
||||||
|
bounded page images/blocks under the worker claim, fail visibly with a review
|
||||||
|
reason and release the lease. Admin inspection/decision and same-job retry use
|
||||||
|
API D06/D07/D04. New OCR output cannot inherit an old approval. Incomplete
|
||||||
|
candidates remain non-queryable; complete artifacts are attached only after
|
||||||
|
coverage/quality validation under a current claim.
|
||||||
|
|
||||||
|
Preserve the implemented embedding/staging path. Unknown upload count requires
|
||||||
|
durable backlog, pagination, configured file/page/resource bounds and capacity
|
||||||
|
measurement. No hardcoded examples, four-document cap or per-file coding.
|
||||||
|
Factual FAQ approval and whole-group exclusions preserve faithful original
|
||||||
|
content while keeping behavioral scenarios/placeholders out of answer evidence.
|
||||||
|
|
||||||
### 7.2 Document processing states
|
### 7.2 Document processing states
|
||||||
|
|
||||||
@@ -220,9 +275,9 @@ Activation/selection is separate from processing state: a ready document can rem
|
|||||||
|
|
||||||
### 7.3 Chunking and embedding
|
### 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.
|
Each chunk preserves its document identity, order, text and available source location. Chunk size and overlap are configurable and recorded as processing metadata. Prefer regulation article/clause plus its note, circular decision plus conditions/exclusions, FAQ question plus answer, and infographic parent heading plus child description. Size limits and overlap apply when necessary, without losing the exception that qualifies a rule. Image-derived text uses the same embedding model as other text. Local BGE-M3 or Qwen embedding models are optional future alternatives, not required hosted services.
|
||||||
|
|
||||||
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.
|
Embedding profiles record provider, model, dimensions and preprocessing version. Documents and queries must use the same compatible profile. Changing the embedding model requires a controlled corpus reindex from retained extracted text, with incompatible vectors isolated and a verified cutover. Ready document/chunk identities and originals remain immutable; do not use failed-document retry to republish a ready document. The maintenance/cutover mechanism requires a separate implementation design before any deployed profile change. Equal vector dimensions do not make two embedding models interchangeable.
|
||||||
|
|
||||||
### 7.4 Publication, updates and selection
|
### 7.4 Publication, updates and selection
|
||||||
|
|
||||||
@@ -240,67 +295,75 @@ The worker claims jobs with a lease and claim token, updates progress and publis
|
|||||||
|
|
||||||
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.
|
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. Live Voice with direct Gemini API access
|
||||||
|
|
||||||
### 8.1 Connection responsibilities
|
### 8.1 Connection responsibilities
|
||||||
|
|
||||||
| Channel | Participants | Purpose |
|
Use direct Gemini Live for the initial voice MVP. The provider connection is stateful WSS; the backend relays client audio and controls private tools. Browser-to-provider SDP/WebRTC from revision 1.1 is superseded for this MVP, not assumed compatible with Gemini. See [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api).
|
||||||
| --- | --- | --- |
|
|
||||||
| 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.
|
OpenRouter is for bounded comparisons of two or three text/vision candidates. Its [audio interface](https://openrouter.ai/docs/guides/overview/multimodal/audio) supports request audio and streamed response audio; that does not establish a compatible bidirectional Gemini Live session.
|
||||||
|
|
||||||
### 8.2 Session establishment
|
### 8.2 Session establishment
|
||||||
|
|
||||||
1. The authenticated browser obtains microphone permission and creates a WebRTC offer.
|
Authenticate the HTTP creation request; persist the owned reservation and idempotency hash before provider setup. Validate session/auth/access epoch again at the application WSS handshake using cookie and trusted Origin. The backend connects to Gemini with its server credential, installs Persian instructions and `search_knowledge`, and enables available input/output transcription. Mark connected only after trusted adapter confirmation. The application WSS transport/event fields are proposed in [API catalog Section 7](RAG-Phase1-API-Catalog.md).
|
||||||
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
|
### 8.3 Voice tool cycle
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
sequenceDiagram
|
sequenceDiagram
|
||||||
participant U as Browser
|
participant U as Browser or approved audio bridge
|
||||||
participant L as Live Model
|
participant B as Backend Live controller
|
||||||
participant B as Backend Controller
|
participant L as Gemini Live
|
||||||
participant K as Knowledge Service
|
participant K as Shared knowledge service
|
||||||
U->>L: Audio over WebRTC
|
participant D as PostgreSQL and pgvector
|
||||||
L->>B: search_documents call
|
U->>B: Authenticated audio stream
|
||||||
B->>B: Validate identity, scope and call
|
B->>L: Audio on direct Live WSS session
|
||||||
B->>K: Execute search
|
L->>B: search_knowledge(query, optional context)
|
||||||
K-->>B: Evidence and sources
|
B->>B: Validate owner, scope, epoch and call ID
|
||||||
|
B->>K: Retrieve authorized evidence
|
||||||
|
K->>D: Query embedding plus eligible semantic/identifier search
|
||||||
|
D-->>K: Relevant chunks and locators
|
||||||
|
K-->>B: ok, no_evidence or error
|
||||||
B-->>L: Correlated tool result
|
B-->>L: Correlated tool result
|
||||||
B-->>U: Source references
|
L-->>B: Persian speech and available transcription
|
||||||
L-->>U: Generated speech
|
B-->>U: Audio, transcript and source references
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
The Live model may answer directly from returned evidence. A separate text-generation call on every voice turn is not mandatory. The existing prototype text agent is not a prerequisite for this milestone. The trusted dispatcher invokes the shared LangChain knowledge tool; adding a separate answer model would require a measured purpose and re-estimated latency/cost.
|
||||||
|
|
||||||
### 8.4 Turn-taking, interruption and disconnects
|
Backend dispatch correlates session/call IDs, validates complete arguments, deduplicates same-ID calls and rejects changed arguments. Recheck current document eligibility and epoch before releasing evidence, including cached duplicates. [Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools) require application handling of function responses; validate the chosen model's blocking/asynchronous capabilities rather than combining incompatible examples.
|
||||||
|
|
||||||
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.
|
### 8.4 Conversation, interruption and failure behavior
|
||||||
|
|
||||||
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.
|
| Situation | Required behavior |
|
||||||
|
| --- | --- |
|
||||||
|
| Follow-up | Resolve “its exceptions” to the last clearly identified circular/article; send a focused query with optional resolved context and retrieve current evidence again |
|
||||||
|
| Topic changes | Replace the topic anchor; do not carry article/document assumptions into the new question |
|
||||||
|
| Ambiguous reference | Ask which document/article; do not choose solely from similarity |
|
||||||
|
| Insufficient evidence | State the missing support and ask a useful clarification; no invented policy or number |
|
||||||
|
| Conflicting evidence | Identify the disagreement and sources; ask which applies or refer to an authorized reviewer |
|
||||||
|
| Retrieval timeout/provider failure | Technical failure with bounded retry/visible status; never claim the document does not exist |
|
||||||
|
| Interruption/cancel | Stop and clear queued playback, mark partial transcription interrupted, cancel outstanding tool work when possible and discard late results |
|
||||||
|
| Disconnect/restart | Show disconnection, reconcile/close old session, start a new session; do not replay old audio or silently restore context |
|
||||||
|
| Duplicate call | Same session/call ID and hash reuses an eligible saved result; running duplicates do not execute twice |
|
||||||
|
|
||||||
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.
|
Seamless reconnect and provider context restoration are deferred. A new session must ask the user to repeat unresolved references. Account logout, session expiry and knowledge removal close sessions under the existing epoch rules. Provider cleanup is best effort, bounded by TTL.
|
||||||
|
|
||||||
### 8.5 History and audio limitations
|
### 8.5 Audio, transcripts and telephony boundaries
|
||||||
|
|
||||||
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 proposed application stream uses mono raw PCM matching Gemini: 16-bit little-endian input at 16 kHz and output at 24 kHz. Capture/resample browser audio and convert output for playback; do not forward compressed browser blobs as PCM. The provider accepts explicitly declared input rates, but standardizing the bridge simplifies the MVP. Interruption clears playback buffers. Verify these behaviors against the configured model using [Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
|
||||||
|
|
||||||
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.
|
Keep available answer transcription and source references visible for the current session. Missing transcription is labeled unavailable, never reconstructed as if spoken; partial generated text does not prove what was heard. Durable full voice history and raw recording remain deferred. The chosen demo model must prove output-transcription delivery; API/storage details must not imply voice messages already exist in the current text-only schema.
|
||||||
|
|
||||||
|
Answers should be concise Persian, with fuller references in the UI; do not recite long chunk IDs or technical citations. Test real Persian utterances and comprehension, local names, dates, percentages and amounts. Multilingual support alone does not prove acceptable quality.
|
||||||
|
|
||||||
|
CTI/Asterisk remains outside the web MVP; no operator behavior analysis requirements are imported. If later explicitly commissioned, an audio bridge must connect the call media/control to the backend, negotiate actual codecs, decode/resample telephony input to PCM and convert 24 kHz output to the negotiated call format. Telephone credentials, routing, hangup/interruption and network rehearsal are separate integration work; API credit does not create a phone connection.
|
||||||
|
|
||||||
## 9. Logical Data Model
|
## 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.
|
The database specification is authoritative. The active MVP preserves seven foundation tables and adds auth_sessions, voice conversations, live_sessions and voice-only tool_calls, plus retained-review metadata in a forward migration. No text-table dependency is required for voice.
|
||||||
|
|
||||||
|
The broader logical entities below are future context, independent of the earlier CTI module's database. They are not a requirement for new embedding profile/generation tables, text history or another vector-store layout in the current milestone.
|
||||||
|
|
||||||
| Entity | Important fields and purpose |
|
| Entity | Important fields and purpose |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -328,7 +391,7 @@ Vector dimension and storage type must match the chosen embedding profile. Separ
|
|||||||
|
|
||||||
## 10. Application API Contracts
|
## 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.
|
The API catalog revision 1.3 is authoritative for active/deferred delivery status. Core MVP capabilities are new-document upload/review/selection and Live voice. Public text chat/history, settings mutation, mixed mode and SSE are deferred. The broader route table below is retained future context and cannot override the catalog.
|
||||||
|
|
||||||
| Method and route | Purpose | Result |
|
| Method and route | Purpose | Result |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -353,7 +416,7 @@ These are proposed application endpoints, not provider API endpoints. The three
|
|||||||
|
|
||||||
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.
|
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
|
### 10.1 Text turn example (deferred)
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -391,7 +454,7 @@ Final application statuses include `answered`, `needs_clarification`, `insuffici
|
|||||||
|
|
||||||
### 10.3 Live session application contract
|
### 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.
|
For Phase 1, the request carries `conversation_id` and `client_request_id`; the response contains session ID, state and an owned application WSS path. The backend connects to direct Gemini Live. No SDP or provider credential is returned. See the canonical API catalog for proposed events and ownership/replay behavior.
|
||||||
|
|
||||||
### 10.4 Error envelope
|
### 10.4 Error envelope
|
||||||
|
|
||||||
@@ -474,21 +537,21 @@ Build a reference evaluation set from approved organization documents and expect
|
|||||||
| Agent behavior | Appropriate search calls, bounded retries and clarification for ambiguity |
|
| Agent behavior | Appropriate search calls, bounded retries and clarification for ambiguity |
|
||||||
| Isolation | Cross-organization IDs and model-supplied scope cannot expose documents |
|
| Isolation | Cross-organization IDs and model-supplied scope cannot expose documents |
|
||||||
| Dynamic documents | Upload, select, replace, deactivate and delete reflected in new retrieval |
|
| Dynamic documents | Upload, select, replace, deactivate and delete reflected in new retrieval |
|
||||||
| Text history | Retry does not duplicate messages; restart preserves completed conversations |
|
| Voice/session persistence | Upload/review/retry/live create replay correctly; restart preserves jobs/documents and makes old media sessions terminal |
|
||||||
| Voice | Direct speech-to-speech, searchable document answers, interruption, reconnect and close tested |
|
| Voice | Persian speech and document retrieval, available transcript/sources, interruption, explicit disconnection/new-session recovery and close tested |
|
||||||
| Control security | Client cannot escalate tool access or change protected session policy |
|
| Control security | Client cannot escalate tool access or change protected session policy |
|
||||||
| Ingestion recovery | Crashes and provider failures recover without duplicate publication |
|
| Ingestion recovery | Crashes and provider failures recover without duplicate publication |
|
||||||
| Deployment | HTTPS/microphone behavior, backups and demonstration network verified |
|
| 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.
|
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 internal text-query retrieval and real spoken answers independently even though search is shared. Include the four supplied examples and unseen new uploads. Full text-history acceptance is deferred.
|
||||||
|
|
||||||
## 17. Migration from the Existing Repository
|
## 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.
|
The earlier review inspected commit `cb54a35`; the mapping below describes that historical prototype and the broader future text design. It is not an instruction to rebuild ingestion Phases 1-4, convert all services to LangChain, migrate text history now or alter applied embedding profiles. Current component progress and next work are in delivery plan Section 2 and the reference map.
|
||||||
|
|
||||||
| Existing area | Required evolution |
|
| Existing area | Required evolution |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `app/services/retriever.py` | Replace Chroma/FastEmbed with repository and embedding interfaces backed by pgvector/OpenAI |
|
| `app/services/retriever.py` | Replace Chroma/FastEmbed with repository and embedding interfaces backed by pgvector and the compatible configured embedding provider |
|
||||||
| `app/services/doc_processor.py` | Replace folder-only Markdown ingestion with registered extraction strategies and document-linked jobs |
|
| `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/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/exec.py` | Retain the agentic tool loop; add bounded execution, injected services and durable context |
|
||||||
@@ -502,32 +565,34 @@ Remove indexing side effects from module imports. Re-embed the source documents
|
|||||||
|
|
||||||
## 18. Implementation Sequence
|
## 18. Implementation Sequence
|
||||||
|
|
||||||
1. Confirm representative documents, question set, live provider capabilities and UI expectations.
|
1. Prove actual funded Gemini Persian audio/transcripts/tools and target-network access early.
|
||||||
2. Implement a small WebRTC spike demonstrating direct audio plus a trusted backend tool call.
|
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
|
||||||
3. Establish the modular backend, database migrations, identity boundary and provider interfaces.
|
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
|
||||||
4. Implement ingestion, document lifecycle, pgvector retrieval and the search tool contract.
|
4. Implement one scoped pgvector search service using compatible existing embeddings.
|
||||||
5. Deliver the text agent with evidence, durable history and evaluation.
|
5. Expose the service through LangChain retriever/tool boundaries; evaluate evidence with an internal query harness.
|
||||||
6. Connect the live controller to the same tool service; add interruption, sources and failure behavior.
|
6. Reserve owned voice contexts/sessions; connect native Live function calls to the same tool, audio relay, sources, cancellation and epoch checks.
|
||||||
7. Deliver organization administration, document selection and model configuration.
|
7. Finish the basic workspace, limits/failure feedback, unseen-file evaluation and actual HTTPS rehearsal.
|
||||||
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.
|
Map this sequence to the conditional Days 1-4 in the delivery plan; execute
|
||||||
|
independent provider proof early. Durable text chat/history, rich settings,
|
||||||
|
optional ranking and broader operational expansion are later work. Actual dates
|
||||||
|
and capacity/quality targets require confirmation. Documentation is not runtime evidence.
|
||||||
|
|
||||||
## 19. Open Decisions and Owners
|
## 19. Open Decisions and Owners
|
||||||
|
|
||||||
| Decision | Suggested owner | Architectural impact |
|
| Decision | Suggested owner | Architectural impact |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
|
| 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 |
|
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
|
||||||
| Live provider/model and supported trusted control features | AI/backend team | Adapter, WebRTC signaling and tool execution |
|
| Exact Gemini Live model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
|
||||||
| Text and embedding model profiles | AI team | Quality, cost and vector dimensions |
|
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
|
||||||
| Local authentication or SSO | IT / backend | Login contract and identity integration |
|
| Cookie session TTL/account operation | IT / backend | Pre-created local accounts now; SSO deferred |
|
||||||
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
|
| Raw audio recording and content retention | Organization / IT | Storage, lifecycle and consent requirements |
|
||||||
| Concurrent sessions and latency targets | Product / IT | Capacity, scaling and quotas |
|
| 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 |
|
| 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 |
|
| Hosting, outbound connectivity and data transfer approval | IT / organization | Provider reachability and deployment |
|
||||||
| Backup policy and recovery objectives | IT | Operations and restoration testing |
|
| Backup policy and recovery objectives | IT | Operations and restoration testing |
|
||||||
| Final UI details | Product owner / Mr. Siavash | Frontend flow and review |
|
| Review usability and quantitative quality | Product owner / AI | Exact-output decisions and factual FAQ approval without per-file coding |
|
||||||
| Meeting year and IT handover date | Project manager | Delivery plan |
|
| 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.
|
These items must be resolved by their owners rather than silently converted into product policy.
|
||||||
@@ -536,9 +601,9 @@ These items must be resolved by their owners rather than silently converted into
|
|||||||
|
|
||||||
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.
|
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.
|
- **[R1]** [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api): initial direct provider/session access.
|
||||||
- **[R2]** [OpenAI — Server-side controls](https://developers.openai.com/api/docs/guides/voice-server-controls): trusted backend control connection and private tool execution.
|
- **[R2]** [Gemini Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities): audio, transcription and interruption.
|
||||||
- **[R3]** [OpenAI — Realtime with tools](https://developers.openai.com/api/docs/guides/realtime-mcp): function tool calls and correlated results.
|
- **[R3]** [Gemini Live tools](https://ai.google.dev/gemini-api/docs/live-api/tools): correlated function calls/results.
|
||||||
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
|
- **[R4]** [pgvector — Official repository](https://github.com/pgvector/pgvector): vector search, index types and filtering considerations.
|
||||||
|
|
||||||
## Appendix A. Presentation Diagrams
|
## Appendix A. Presentation Diagrams
|
||||||
@@ -557,7 +622,7 @@ flowchart TD
|
|||||||
DECISION -->|"Ready to Answer"| ANSWER["Generate Response with Sources"]
|
DECISION -->|"Ready to Answer"| ANSWER["Generate Response with Sources"]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph TOOL["Tool: search_documents"]
|
subgraph TOOL["Tool: search_knowledge"]
|
||||||
CALL --> SCOPE["Apply Organization and Selected Document Filters"]
|
CALL --> SCOPE["Apply Organization and Selected Document Filters"]
|
||||||
SCOPE --> QUERY["Embed Search Query"]
|
SCOPE --> QUERY["Embed Search Query"]
|
||||||
QUERY --> SEARCH["Semantic Search"]
|
QUERY --> SEARCH["Semantic Search"]
|
||||||
@@ -593,7 +658,7 @@ flowchart TD
|
|||||||
DOCS["Documents and Configuration"]
|
DOCS["Documents and Configuration"]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph L3["3. Agentic AI"]
|
subgraph L3["3. Agentic AI — logical; Live model is external"]
|
||||||
TEXT["Text AI Agent"]
|
TEXT["Text AI Agent"]
|
||||||
LIVE["Live AI Model"]
|
LIVE["Live AI Model"]
|
||||||
TOOL["Search Documents Tool"]
|
TOOL["Search Documents Tool"]
|
||||||
@@ -618,7 +683,8 @@ flowchart TD
|
|||||||
|
|
||||||
CHAT <--> TEXT
|
CHAT <--> TEXT
|
||||||
SESSION -->|"Initialize and Control"| LIVE
|
SESSION -->|"Initialize and Control"| LIVE
|
||||||
UI <-->|"Direct Live Audio — WebRTC"| LIVE
|
UI <-->|"Authenticated audio WSS"| SESSION
|
||||||
|
SESSION <-->|"Direct Gemini Live WSS"| LIVE
|
||||||
|
|
||||||
TOOL <--> SEARCH
|
TOOL <--> SEARCH
|
||||||
SEARCH <--> DB
|
SEARCH <--> DB
|
||||||
@@ -629,3 +695,43 @@ flowchart TD
|
|||||||
FILES --> INGEST
|
FILES --> INGEST
|
||||||
INGEST --> DB
|
INGEST --> DB
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 21. Historical MVP decision log and implementation evidence - 2026-10-06
|
||||||
|
|
||||||
|
No standalone ADR directory or separate requirements specification was found. This focused decision log records the current user-authorized MVP changes; the delivery plan retains requirement IDs P1-01–P1-12 and adds sample/voice acceptance.
|
||||||
|
|
||||||
|
| Classification | Decision or evidence |
|
||||||
|
| --- | --- |
|
||||||
|
| Confirmed product direction | Complete upload → extraction/QC → chunk/index → Persian voice → retrieval → grounded spoken answer; text-only or voice without retrieval is insufficient |
|
||||||
|
| Confirmed existing lifecycle | Independent immutable uploads; direct document/chunk references; manual replacement; same eligible failed document/job retry; existing scope/revision/epoch/fencing rules |
|
||||||
|
| Confirmed provider direction | Direct Gemini Live; Flash vision extraction candidate; OpenRouter comparisons; USD 20 initial allocation and USD 30 planned budget |
|
||||||
|
| Proposed details | Application WSS event schema, optional tool context, derived extraction artifact, manual quality gate, identifier matching alongside semantic retrieval |
|
||||||
|
| Verified by static inspection | Markdown folder loader and character splitter; Chroma/FastEmbed `BAAI/bge-small-en-v1.5`; LangGraph `MemorySaver`; configurable OpenAI-compatible text client; prototype chat route without the planned auth/turn contracts |
|
||||||
|
| Verified by static inspection | Seven-table ingestion foundation and trusted intake CLI/local immutable originals; settings allow only PDF/Markdown; `ExtractedBlock` has text/page/section; no extraction worker, hosted embedding adapter, pgvector chat search, Live adapter or frontend |
|
||||||
|
| Not verified here | Provider calls, Persian audio, comparative OCR, full PDF text/layout, deployed account/model access or operational voice MVP |
|
||||||
|
|
||||||
|
The pre-existing setup guide records earlier database acceptance; those results were not rerun for this documentation task. The current foundation's explicit embedding profile is authoritative when deployed; the English-only prototype model is not evidence of Persian retrieval quality. Preserve an approved existing profile until a separately reviewed controlled reindex. Planned OpenAI-compatible embedding access needs funded credentials; the Gemini/OpenRouter allocation does not itself fund a separate OpenAI account.
|
||||||
|
|
||||||
|
See the [Persian sample scenarios](RAG-Phase1-Scenario-Report-FA.md) for local inspection limits and worked examples, and [delivery plan Section 14](RAG-AI-Phase1-Delivery-Plan.md) for pricing, account/quota checks and budget.
|
||||||
|
|
||||||
|
## 22. Current Live document MVP decisions - 2026-10-07
|
||||||
|
|
||||||
|
| Category | Current baseline |
|
||||||
|
| --- | --- |
|
||||||
|
| Confirmed product | Limited demo for known users; new browser uploads; all four examples; unknown future document count |
|
||||||
|
| Confirmed framework | LangChain RAG/tools; direct Gemini Live audio loop |
|
||||||
|
| Confirmed reuse | Implemented ingestion/embedding Phases 1-4 and repaired validation/staging; no wholesale embedding refactor |
|
||||||
|
| Required next implementation | Fenced worker/review/resume/publication, scoped pgvector search, HTTP identity/upload, owned Live and minimal workspace |
|
||||||
|
| Deferred milestone | Full text/history/citations, rich settings/delete UI, raw recording, seamless reconnect and CTI |
|
||||||
|
| Proposed concrete contracts | D06/D07 evidence-bound review and preview, FAQ inclusion manifest, retained extraction_state and voice-only tool_calls |
|
||||||
|
| Conditional delivery | Four implementation days; three optimistic; provider/QC/sample/network failure requires re-estimation |
|
||||||
|
|
||||||
|
Use delivery plan revision 1.3 for scope, API/database revision 1.3 for contracts
|
||||||
|
and the implementation guide for workflows. Section 21 is a historical snapshot;
|
||||||
|
older text/settings assumptions do not govern this milestone. No runtime,
|
||||||
|
provider, database acceptance or quality result was executed by this document edit.
|
||||||
|
|
||||||
|
References for the integration boundary:
|
||||||
|
[LangChain Embeddings](https://reference.langchain.com/python/langchain-core/embeddings/embeddings/Embeddings),
|
||||||
|
[LangChain tools](https://docs.langchain.com/oss/python/langchain/tools),
|
||||||
|
[retrieve and rerank](https://sbert.net/examples/sentence_transformer/applications/retrieve_rerank/README.html).
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
# Organization Knowledge Assistant - Live Document MVP Delivery Plan
|
||||||
|
|
||||||
|
| Field | Value |
|
||||||
|
| --- | --- |
|
||||||
|
| Version | 1.3 |
|
||||||
|
| Date | 2026-10-07 |
|
||||||
|
| Status | Current implementation baseline; mechanisms and unresolved deployment choices are proposed, not completion evidence |
|
||||||
|
| Capacity assumption | One primary developer, existing ingestion Phases 1-4, basic same-origin UI |
|
||||||
|
| Milestone | Four implementation days as a conditional demo target; three days is optimistic |
|
||||||
|
| Scope authority | This plan governs the current MVP; it supersedes the previous 7-10 day text-and-voice milestone |
|
||||||
|
|
||||||
|
## 1. Release Objective
|
||||||
|
|
||||||
|
Deliver an authenticated Persian document assistant with this actual workflow:
|
||||||
|
upload a new document in the browser -> extract and review where required ->
|
||||||
|
chunk and embed -> publish completely -> activate -> ask a spoken question ->
|
||||||
|
retrieve authorized evidence -> hear a grounded Persian answer and see sources.
|
||||||
|
|
||||||
|
Users upload new documents without developer intervention or per-file code.
|
||||||
|
The total number of future uploads is unknown. The four supplied files are
|
||||||
|
mandatory initial acceptance examples, not a filename/hash allowlist or the
|
||||||
|
entire corpus. A session that speaks without searching uploaded knowledge does
|
||||||
|
not fulfill the MVP.
|
||||||
|
|
||||||
|
The release is a limited demonstration for known users in one organization,
|
||||||
|
with general upload within declared format, structural and resource bounds.
|
||||||
|
It is not universal document parsing or a production capacity/SLA claim.
|
||||||
|
Full text chat and durable message history move to the follow-up milestone.
|
||||||
|
|
||||||
|
## 2. Confirmed Direction, Current State and Day 1 Dependencies
|
||||||
|
|
||||||
|
Confirmed user direction: browser upload, all four supplied examples, new
|
||||||
|
documents beyond those examples, LangChain, reuse of the implemented embedding
|
||||||
|
pipeline, and backend-managed direct Gemini Live speech-to-speech.
|
||||||
|
|
||||||
|
| Existing component | Evidence and reuse boundary |
|
||||||
|
| --- | --- |
|
||||||
|
| Ingestion Phase 1 | Foundation settings, ports, bootstrap and seven-table migration exist |
|
||||||
|
| Phase 2 | Immutable originals and trusted CLI intake/status/reconciliation exist; HTTP upload is not implemented |
|
||||||
|
| Phase 3 | Extraction, normalization, semantic chunk drafts, QC gates and non-queryable candidates exist |
|
||||||
|
| Phase 4 | Hosted embedding adapter, profile/token/vector validation and bounded memory staging exist |
|
||||||
|
| Phase 5/6 | Worker, claim/lease fencing, retained-output review/resume backend services, retry, atomic publication and integration/operator handoff are implemented; authenticated D06/D07 transport remains pending |
|
||||||
|
| Prototype | Markdown/Chroma/FastEmbed/LangGraph text path exists; it does not search the new uploaded-document pipeline |
|
||||||
|
| Missing integration | HTTP identity/upload, review workflow, pgvector retrieval, LangChain integration, Live and UI remain planned |
|
||||||
|
|
||||||
|
Keep implemented validation, frozen processing/embedding profiles and applied
|
||||||
|
migrations. Framework integration does not require changing embedding model,
|
||||||
|
dimension, preprocessing or rebuilding compatible vectors. Recorded tests
|
||||||
|
establish component behavior only; real hosted-provider quality, Persian
|
||||||
|
speech and the complete workflow remain unverified.
|
||||||
|
|
||||||
|
In the first Day 1 work block, prove real Gemini audio, Persian output,
|
||||||
|
transcription and a backend-executed function call on the intended network.
|
||||||
|
Confirm funded embedding/extraction profiles and actual HTTPS hosting in the
|
||||||
|
same day. Failed provider access changes the dependent estimate; it does not
|
||||||
|
justify quietly replacing Live with text.
|
||||||
|
|
||||||
|
## 3. Included and Deferred Scope
|
||||||
|
|
||||||
|
| Area | Current MVP | Follow-up / deferred |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Identity | Fixed organization, pre-created accounts, simple cookie login, admin/user permissions and owner checks | Signup, invitations, SSO, multi-organization administration |
|
||||||
|
| Documents | New browser uploads, list/status, minimal review and retry, active selection | Rich management, replacement automation, delete UI and retention automation |
|
||||||
|
| Formats | PDF, DOCX, JPEG/PNG and existing UTF-8 Markdown, within configured structural/resource limits | Universal layout support and arbitrary formats |
|
||||||
|
| Processing | Existing extraction/chunking/embedding components, separate durable worker, fenced recovery and complete publication | Distributed fleet, broker, batch checkpoint orchestration |
|
||||||
|
| QC | Evidence-bound review of retained output and explicit factual FAQ approval; clear failures | Elaborate review editor and automatic quality classifier |
|
||||||
|
| Search/framework | LangChain tool/retriever integration over one scoped pgvector search service; compatible query embedding and exact identifiers | Retrieval tuning UI; reranker/ANN only if measured failures justify them |
|
||||||
|
| Voice | Direct Gemini Live through backend WSS, Persian speech, follow-ups, topic changes, interruption and visible failure | Seamless reconnect, raw recording, telephony/CTI |
|
||||||
|
| Visible evidence | Current-session provider transcripts when delivered, retrieved sources with real locators | Guaranteed durable transcript, complete message history and exact spoken-claim attribution |
|
||||||
|
| Persistence | Original files, jobs/chunks, review decisions, identity, owned voice/session/tool metadata | Durable text turns/messages/citations and cross-mode continuation |
|
||||||
|
| Configuration | Fixed server profiles and seeded assistant name/instruction; read-only capabilities | Settings editor, model/voice selector and provider comparisons as required delivery work |
|
||||||
|
| Deployment | One API, one worker, PostgreSQL/pgvector, durable files and same-origin HTTPS | High availability, autoscaling and certified load/SLA |
|
||||||
|
|
||||||
|
Deletion is not a required UI feature. Existing deletion exclusion, worker
|
||||||
|
non-deletion checks and maintenance lifecycle invariants still apply.
|
||||||
|
Simple retry is included where needed to resume approved extraction or an
|
||||||
|
eligible failed job; it is not a new document or ready-document reindex.
|
||||||
|
|
||||||
|
## 4. User Interface
|
||||||
|
|
||||||
|
Use login plus one workspace with a voice area and an admin-only Documents area.
|
||||||
|
Do not build the previous four-screen dashboard for this milestone.
|
||||||
|
|
||||||
|
The Documents area provides upload, title/filename, real processing state,
|
||||||
|
safe error/retry feedback, inspection of retained extraction evidence where
|
||||||
|
required, a minimal approval/rejection action and active selection controls.
|
||||||
|
Expose configured upload limits. Do not promise arbitrary file success.
|
||||||
|
An unreadable/unsupported accepted file fails visibly and remains unsearchable.
|
||||||
|
|
||||||
|
The voice area provides start/end, microphone/playback controls, connection
|
||||||
|
state, partial/completed/interrupted provider transcripts when available,
|
||||||
|
retrieved sources and clear recovery guidance. Do not invent transcript text
|
||||||
|
or page numbers. Label evidence as retrieved sources unless actual answer
|
||||||
|
attribution has been proved. Refreshing the page need not recover a full transcript.
|
||||||
|
|
||||||
|
## 5. Implementation Architecture
|
||||||
|
|
||||||
|
Use one modular FastAPI application, a separate ingestion worker from the
|
||||||
|
same codebase, PostgreSQL/pgvector and durable file storage. LangChain is the
|
||||||
|
RAG/tool framework; Gemini Live owns the native audio conversation loop.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TB
|
||||||
|
UI["Same-origin web workspace"] -->|"Upload and authenticated control"| API["FastAPI"]
|
||||||
|
API --> FILES["Immutable originals and retained extraction"]
|
||||||
|
API -->|"Durable jobs"| DB[("PostgreSQL + pgvector")]
|
||||||
|
FILES --> WORKER["Existing pipeline + fenced worker"]
|
||||||
|
WORKER -->|"Atomic publication"| DB
|
||||||
|
API --> SEARCH["Shared search service / LangChain tool"]
|
||||||
|
SEARCH --> DB
|
||||||
|
UI <-->|"Authenticated audio/events WSS"| API
|
||||||
|
API <-->|"Direct audio + correlated function calls/results"| LIVE["Gemini Live"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.1 Existing embedding pipeline and LangChain boundary
|
||||||
|
|
||||||
|
Retain EmbeddingProvider.embed, OpenAICompatibleEmbeddings and stage_document.
|
||||||
|
Use a thin LangChain Embeddings adapter only if an integration requires it;
|
||||||
|
otherwise the custom retriever can call the existing service directly.
|
||||||
|
Query embedding uses compatible identity and normalization. Preserve token,
|
||||||
|
batch, response, float32/vector and memory limits; do not add stacked retries,
|
||||||
|
silent truncation or a framework-driven replacement ingestion/index path.
|
||||||
|
Provider/SQL work must not block audio handling.
|
||||||
|
|
||||||
|
### 5.2 Retrieval and native voice
|
||||||
|
|
||||||
|
The model requests search_knowledge; backend scope, budgets, deduplication and
|
||||||
|
epoch checks govern execution. Search returns actual document/chunk IDs,
|
||||||
|
evidence and nullable locators. Validate retrieval separately using an internal
|
||||||
|
text-query harness; a shipped text chat/model loop is not a prerequisite.
|
||||||
|
|
||||||
|
Native Live can answer directly from returned evidence without a second text
|
||||||
|
model per voice turn. Recheck scope before sending tool results. Flush queued
|
||||||
|
playback on interruption and suppress late/cancelled results. Provider loss is
|
||||||
|
visible; reconcile/close the old session before starting a fresh one.
|
||||||
|
|
||||||
|
### 5.3 Worker and review reliability
|
||||||
|
|
||||||
|
Persist uploads/jobs first. Claim with a token/lease, heartbeat during slow
|
||||||
|
provider work and publish only under current ownership. Publish all chunks
|
||||||
|
with ready/succeeded state in one transaction. Partial/staged output is never
|
||||||
|
searchable. Keep new ready documents inactive until admin selection.
|
||||||
|
|
||||||
|
ReviewRequired currently stops PDF/image extraction. Implement bounded
|
||||||
|
retained review candidates and decisions before claiming those formats work
|
||||||
|
through the UI. Release the lease and use failed state with a review-required
|
||||||
|
reason; do not add a waiting-review document state or hold a lease for a human.
|
||||||
|
Approval applies to exact retained output, not a fresh OCR response.
|
||||||
|
Reuse approved retained page output on same-document retry. Preserve complete
|
||||||
|
extraction separately from vectors so OCR need not repeat solely for chunking.
|
||||||
|
|
||||||
|
## 6. Document Lifecycle and Knowledge Changes
|
||||||
|
|
||||||
|
Each upload is an independent immutable document. Jobs/chunks reference
|
||||||
|
document_id and evidence references document_id/chunk_id. No content versions.
|
||||||
|
An idempotent retry of an upload returns the same IDs; a new upload key creates
|
||||||
|
an independent document even for identical bytes.
|
||||||
|
|
||||||
|
Document states remain queued -> processing -> ready or failed; active selection
|
||||||
|
is separate. Retry reuses the same eligible failed document/job and frozen profile.
|
||||||
|
New content needs a new upload. A replacement can be uploaded inactive, checked,
|
||||||
|
then selected while the prior document is deselected.
|
||||||
|
|
||||||
|
Preserve configuration revision, knowledge_revision and access_epoch. Any active
|
||||||
|
removal invalidates older organization conversation context and closes active
|
||||||
|
Live sessions conservatively. A fresh session retrieves current evidence;
|
||||||
|
it does not copy revoked history. Future deletion and current maintenance
|
||||||
|
tombstones exclude content immediately. Physical purge policy is unresolved.
|
||||||
|
|
||||||
|
## 7. Minimum Persistent Data
|
||||||
|
|
||||||
|
Keep the seven existing foundation tables. Add reviewed forward migrations
|
||||||
|
for auth_sessions, owned conversations, live_sessions, voice tool_calls and
|
||||||
|
bounded retained extraction/review references as specified in the database design.
|
||||||
|
Text turns/messages/citations are deferred; do not create a dependency on them
|
||||||
|
for voice tool persistence. No raw audio or persistent provider credentials.
|
||||||
|
|
||||||
|
Unknown corpus size requires pagination, bounded per-document processing,
|
||||||
|
durable backlog, disk/quota observation and explicit admission failure when
|
||||||
|
capacity is exhausted. File/page/chunk/session limits are configurable
|
||||||
|
deployment choices, not evidence of unlimited capacity or approved business policy.
|
||||||
|
|
||||||
|
## 8. Delivery Schedule and Checkpoints
|
||||||
|
|
||||||
|
| Day | Work | Exit condition |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 1 | Early Live/account/network/tool proof; confirm profiles; identity and durable browser upload | Persian audio/tool proof recorded and authenticated upload persists |
|
||||||
|
| 2 | Phase 5 worker, retained extraction/review, retry and atomic publication using Phases 1-4 | All four example structures can reach ready through the actual workflow |
|
||||||
|
| 3 | Scoped pgvector search, LangChain integration, Live knowledge tool, sources/follow-up/interruption | A newly uploaded active document supports a real spoken answer |
|
||||||
|
| 4 | Finish basic UI, real HTTPS deployment, unseen-file and failure checks, rehearse | Full acceptance walkthrough succeeds on target device/network |
|
||||||
|
|
||||||
|
This is a conditional four-day target from the inspected current state, not
|
||||||
|
four days to rebuild ingestion. Three days is optimistic. Numbered working days
|
||||||
|
are not calendar commitments. If review/resume, sample fidelity, funded profiles
|
||||||
|
or real audio/tool access fails, re-estimate and report the blocked gate.
|
||||||
|
Do not meet the deadline by dropping sample support, upload, authorization or voice.
|
||||||
|
|
||||||
|
## 9. Acceptance Criteria
|
||||||
|
|
||||||
|
| ID | Check | Required outcome |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| MVP-01 | Identity and ownership | Unauthenticated/normal-user mutations and other users' voice state are denied |
|
||||||
|
| MVP-02 | New upload | A file not hardcoded in the repository is uploaded in the browser and persists |
|
||||||
|
| MVP-03 | Sample coverage | Both supplied PDFs, the infographic and DOCX complete the workflow |
|
||||||
|
| MVP-04 | Extraction fidelity | Dates/numbers/negation/exclusions, visual groups and all DOCX Q&A pair associations are retained |
|
||||||
|
| MVP-05 | Review and FAQ | Exact retained output is approved/rejected; uncertain/unapproved/placeholder or behavioral content cannot become facts |
|
||||||
|
| MVP-06 | Worker publication | Partial vectors remain absent; stale claims fail; crash/retry cannot duplicate publication |
|
||||||
|
| MVP-07 | Scoped retrieval | Only authorized ready active undeleted documents return evidence with real IDs/locators |
|
||||||
|
| MVP-08 | Voice grounding | Real Persian audio invokes backend search and receives supported spoken answers with visible evidence/transcript behavior |
|
||||||
|
| MVP-09 | Conversation behavior | Follow-up, ambiguity, topic switch and interruption work without resurrecting cancelled output |
|
||||||
|
| MVP-10 | Missing evidence and faults | Missing/conflicting evidence gets limitation/clarification; technical failures get explicit errors |
|
||||||
|
| MVP-11 | Revocation and cleanup | Removal/logout/expiry closes sessions; revoked context and late results are not reused |
|
||||||
|
| MVP-12 | Replay and restart | Repeated upload/review/retry/live create does not duplicate work; restart makes old media sessions unusable |
|
||||||
|
| MVP-13 | Unseen documents and limits | Several new files of supported structures run without code changes; limit/unsupported failures are understandable |
|
||||||
|
| MVP-14 | Deployment and handoff | Actual HTTPS/microphone/speaker/provider rehearsal plus reproducible startup and evidence |
|
||||||
|
|
||||||
|
Use an initial reference set of roughly 15-20 questions, then include unseen
|
||||||
|
documents. Independently mark expected source passages; separate retrieval,
|
||||||
|
answer support and spoken quality. A model score or successful fixture suite
|
||||||
|
is not a factual accuracy percentage. Agree any numeric quality/concurrency/
|
||||||
|
latency target; record observed latency and failures without inventing a SLA.
|
||||||
|
All full text-chat/history acceptance belongs to the follow-up milestone.
|
||||||
|
|
||||||
|
## 10. Demonstration Script
|
||||||
|
|
||||||
|
1. Log in as admin and upload documents through the browser, including a new file.
|
||||||
|
2. Show queued/processing and any required exact-output review, then ready.
|
||||||
|
3. Activate the documents and start an owned voice session.
|
||||||
|
4. Ask supported Persian questions from both PDFs, the infographic and factual FAQ.
|
||||||
|
5. Show real evidence locators, number/exception fidelity and available transcript.
|
||||||
|
6. Ask a follow-up, an ambiguous question, an unsupported question and switch topics.
|
||||||
|
7. Interrupt the answer; show stopped playback and a correct new request.
|
||||||
|
8. Deactivate a used source; show old-session invalidation and a fresh scoped session.
|
||||||
|
9. Exercise provider loss, repeated requests and worker restart independently.
|
||||||
|
10. Repeat upload/retrieval with previously unseen supported files.
|
||||||
|
|
||||||
|
Do not satisfy this script with pre-seeded hardcoded answers, a filename
|
||||||
|
allowlist or a voice demo that never searches the uploaded documents.
|
||||||
|
|
||||||
|
## 11. Risks and Scope Control
|
||||||
|
|
||||||
|
Primary risks: exact-output review/resume backend services exist but authenticated
|
||||||
|
D06/D07 transport is pending; mixed-source FAQ still needs real factual review; funded providers and Persian quality are
|
||||||
|
unproven; the target network may fail; new file complexity and unknown backlog
|
||||||
|
may exceed limits. Test these early and expose bounded failures.
|
||||||
|
|
||||||
|
Reduce UI polish, settings/history and optional ranking work first. Reranking
|
||||||
|
is a measured follow-up or an explicitly re-estimated corrective task, not a
|
||||||
|
guarantee that extraction/retrieval defects disappear. Stable framework and
|
||||||
|
data-integrity boundaries are retained throughout.
|
||||||
|
|
||||||
|
## 12. Expansion After This MVP
|
||||||
|
|
||||||
|
Full grounded text chat with durable turns/messages/citations; richer settings
|
||||||
|
and document administration; larger evaluation/capacity work; measured reranking
|
||||||
|
or ANN; retention/cleanup; seamless audio reconnect and durable voice history.
|
||||||
|
Broader architecture is context, not authority to add these to the four-day scope.
|
||||||
|
|
||||||
|
## 13. Release Handoff
|
||||||
|
|
||||||
|
Provide release revision, startup/migration/seed/worker commands, secret-free
|
||||||
|
configuration, supported structure/limit matrix, reference and unseen-file
|
||||||
|
results, actual provider/deployment evidence and known limitations.
|
||||||
|
This documentation revision does not implement or certify the release.
|
||||||
|
|
||||||
|
## 14. Provider Budget and Validation
|
||||||
|
|
||||||
|
Select one funded Live profile, one compatible embedding profile and one
|
||||||
|
extraction profile. Keep their usage separate. Confirm billing, account/region
|
||||||
|
eligibility, current prices, quotas and remaining credit before paid trials.
|
||||||
|
Reserve rehearsal capacity; no fixed dollar allocation or session count is
|
||||||
|
guaranteed by this revision. The prior comparison budget is not a requirement
|
||||||
|
to buy or integrate an extra text provider. Preserve already approved embedding
|
||||||
|
identity; incompatible changes need a separately reviewed reindex/cutover.
|
||||||
|
|
||||||
|
## 15. Implementation Entry Gate and Remaining Decisions
|
||||||
|
|
||||||
|
Start with a real Live spike while completing worker/review integration.
|
||||||
|
Confirm actual format/structure bounds, upload/page/storage limits, factual FAQ
|
||||||
|
approval, funded model identities/dimension, reviewer availability, session
|
||||||
|
TTL/capacity, HTTPS hosting, target-network reachability, quality targets and
|
||||||
|
presentation date. Unknown future document count does not authorize unbounded
|
||||||
|
resources. Storage retention/purge remains an owner decision.
|
||||||
|
|
||||||
|
Read the implementation guide for work packages, API/database contracts for
|
||||||
|
transport/persistence and the English scenario report for concrete walkthroughs.
|
||||||
|
The reference map/setup guide remain the evidence of existing component progress.
|
||||||
@@ -0,0 +1,406 @@
|
|||||||
|
# RAG Assistant — Phase 1 API Catalog
|
||||||
|
|
||||||
|
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational.
|
||||||
|
|
||||||
|
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.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 create owned voice conversations and read/control their own Live state. Only admin manages uploads, review, retry and selection. Hidden resource access returns 404. Admin does not implicitly own all conversations. Full text chat/history, delete UI and settings mutation are deferred.
|
||||||
|
|
||||||
|
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: deferred text message 8000 characters; assistant name 120; instruction 8000; search query 2000; conversation title 120; document title 200; review note 2000. File limits/formats and audio frame caps 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 | Delivery |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| A01 | POST `/auth/login` | Public, trusted Origin | 200 + cookie | MVP |
|
||||||
|
| A02 | POST `/auth/logout` | Authenticated; expired/missing session accepted | 204 | MVP |
|
||||||
|
| A03 | GET `/me` | Authenticated | 200 | MVP |
|
||||||
|
| D01 | POST `/documents` | Admin | 202 | MVP |
|
||||||
|
| D02 | GET `/documents` | Admin | 200 | MVP |
|
||||||
|
| D03 | GET `/documents/{document_id}` | Admin | 200 | MVP |
|
||||||
|
| D04 | POST `/documents/{document_id}/retry` | Admin | 202 | MVP |
|
||||||
|
| D05 | DELETE `/documents/{document_id}?expected_revision=N` | Admin | 202 | Deferred |
|
||||||
|
| D06 | GET `/documents/{document_id}/extraction-review` | Admin | 200 | MVP |
|
||||||
|
| D07 | POST `/documents/{document_id}/extraction-review/decisions` | Admin | 200 | MVP |
|
||||||
|
| K01 | GET `/knowledge-selection` | Admin | 200 | MVP |
|
||||||
|
| K02 | PATCH `/knowledge-selection` | Admin | 200 | MVP |
|
||||||
|
| F01 | GET `/configuration` | Authenticated | 200 | MVP |
|
||||||
|
| F02 | PATCH `/configuration` | Admin | 200 | Deferred |
|
||||||
|
| C01 | POST `/conversations` | Authenticated | 201 | MVP: voice only |
|
||||||
|
| C02 | GET `/conversations` | Owner | 200 | Deferred |
|
||||||
|
| C03 | GET `/conversations/{conversation_id}/messages` | Owner | 200 | Deferred |
|
||||||
|
| T01 | POST `/chat` | Owner of text conversation | 200 or 202 | Deferred |
|
||||||
|
| T02 | GET `/conversations/{conversation_id}/turns/{client_request_id}` | Owner | 200 | Deferred |
|
||||||
|
| V01 | POST `/voice/sessions` | Owner of voice conversation | 201 or 202 | MVP |
|
||||||
|
| V02 | GET `/voice/sessions/{session_id}` | Owner | 200 | MVP |
|
||||||
|
| V03 | GET `/voice/sessions/by-request/{client_request_id}` | Owner | 200 | MVP |
|
||||||
|
| V04 | POST `/voice/sessions/{session_id}/close` | Owner | 200 | MVP |
|
||||||
|
| H01 | GET `/health/live` | Deployment health access | 200 | MVP |
|
||||||
|
| H02 | GET `/health/ready` | Deployment health access | 200 or 503 | MVP |
|
||||||
|
|
||||||
|
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
|
||||||
|
|
||||||
|
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider Gemini WSS connection. Internal model tools have no public REST route.
|
||||||
|
|
||||||
|
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` 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.
|
||||||
|
|
||||||
|
Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport remains planned.
|
||||||
|
|
||||||
|
```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 AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail may include `review_required:false` for other outcomes. D06 supplies retained review evidence only to admins. 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/unrecoverable failure; 404 hidden/deleted. Review-required retry becomes eligible only after all currently pending evidence-bound approvals exist; additional pages can require later review. An unapproved candidate returns 409 `EXTRACTION_REVIEW_PENDING`; rejection stays failed. Successful factual-corpus review is a separate precondition where required. No ready document is reindexed through retry. The retry-key record is retained in audit metadata with a database uniqueness constraint.
|
||||||
|
|
||||||
|
### D06 - Read retained extraction/factual review
|
||||||
|
|
||||||
|
Admin-only, paginated bounded review candidates. No provider calls. Return 404
|
||||||
|
for hidden/deleted documents. A document with no pending candidates returns an
|
||||||
|
empty items list. Example application shape:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"document_id":"10000000-0000-4000-8000-000000000001","status":"failed","review_required":true,"items":[{"evidence_sha256":"<server-computed-digest>","review_kind":"extraction","location":{"page":1,"section":"pdf/page/1"},"blocks":[{"block_id":"pdf/page/1/block/1","text":"<retained exact extraction>","group_id":null}],"required_checks":["readability","order","completeness","numbers","dates","negation","exceptions"],"decision":null,"preview_path":"/api/v1/documents/10000000-0000-4000-8000-000000000001/extraction-review/<digest>/preview"}],"next_cursor":null}
|
||||||
|
```
|
||||||
|
|
||||||
|
Serve the retained image on authenticated GET
|
||||||
|
`/documents/{document_id}/extraction-review/{evidence_sha256}/preview`.
|
||||||
|
This is a D06 subresource with the same admin/organization/candidate checks,
|
||||||
|
configured byte/pixel limits, a validated image MIME and Cache-Control: no-store.
|
||||||
|
It accepts no raw path or redirect and exposes no internal storage key.
|
||||||
|
For factual_corpus candidates, preview_path may be null and blocks are grouped
|
||||||
|
Q&A and their governing context with real source locators from the retained complete
|
||||||
|
extraction. Context association is deterministic; ambiguous scope fails visibly.
|
||||||
|
required_checks then includes factual
|
||||||
|
authority, whole-pair association, behavioral separation and placeholders.
|
||||||
|
Locators/digests are actual server values; illustrative strings are not API values.
|
||||||
|
|
||||||
|
### D07 - Decide on retained evidence
|
||||||
|
|
||||||
|
Required Idempotency-Key; normal admin Origin/CSRF checks. Server derives actor.
|
||||||
|
One candidate decision per request; UI may submit multiple requests.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"evidence_sha256":"<digest-from-D06>","decision":"approve","checked":["readability","order","completeness","numbers","dates","negation","exceptions"],"note":"Compared retained extraction against the original page.","excluded_group_ids":[]}
|
||||||
|
```
|
||||||
|
|
||||||
|
200 returns document_id, evidence_sha256, decision and review_required indicating
|
||||||
|
whether current pending decisions remain. It does not enqueue, activate or
|
||||||
|
mark ready; D04 resumes the same failed job with its own key.
|
||||||
|
|
||||||
|
Allow approve/reject only. Require a nonblank bounded note; approval checked
|
||||||
|
must match the server-required check set. For extraction, excluded_group_ids
|
||||||
|
must be empty. For factual_corpus, permit only whole existing Q&A group IDs
|
||||||
|
to exclude unapproved facts, behavioral entries or live-data placeholders.
|
||||||
|
Store the inclusion manifest separately; never edit original/faithful extraction.
|
||||||
|
An empty eligible factual set cannot be indexed.
|
||||||
|
|
||||||
|
Scope idempotency to organization/actor/document/extraction_review/key; hash
|
||||||
|
the canonical decision, checks, note, evidence digest and excluded group IDs.
|
||||||
|
Replay is resolved before new state checks but after authorization; it returns
|
||||||
|
the saved decision without mutating current candidate state. Changed payload
|
||||||
|
returns 409 IDEMPOTENCY_CONFLICT. A new conflicting decision for an already
|
||||||
|
decided candidate returns 409 REVIEW_ALREADY_DECIDED. Removed/superseded evidence,
|
||||||
|
wrong failed-job state or profile/source mismatch returns 409 REVIEW_STALE.
|
||||||
|
Invalid digest/check/group shape returns 422 VALIDATION_ERROR.
|
||||||
|
|
||||||
|
A valid digest alone grants no access. Recompute/validate trusted retained
|
||||||
|
candidate identity under the document/job locks; don't trust client blocks,
|
||||||
|
paths, models or reviewer fields. Rejecting keeps zero publication and a safe
|
||||||
|
failure reason. Lost worker ownership cannot attach candidates; an admin cannot
|
||||||
|
approve a fresh OCR response using an old digest.
|
||||||
|
|
||||||
|
### D05 — Delete (deferred HTTP/UI)
|
||||||
|
|
||||||
|
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 (read-only in MVP)
|
||||||
|
|
||||||
|
### F01 — Read
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"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. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
|
||||||
|
|
||||||
|
### F02 — Update (deferred)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"expected_revision":1,"assistant_name":"HR Assistant","instruction":"Use formal Persian and state when supporting evidence is missing."}
|
||||||
|
```
|
||||||
|
|
||||||
|
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 deferred text
|
||||||
|
|
||||||
|
### C01 — Create
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"client_request_id":"50000000-0000-4000-8000-000000000001","mode":"voice","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"}
|
||||||
|
```
|
||||||
|
|
||||||
|
The current MVP accepts `mode=voice` only; text/mixed requests return 409 `MODE_MISMATCH`. Follow-up text support uses a separate mode and must not silently alter the voice contract. 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 (deferred history UI)
|
||||||
|
|
||||||
|
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 (deferred)
|
||||||
|
|
||||||
|
Common pagination, ascending sequence. Voice can return no durable messages: current-session answer transcripts are delivered through Live events when available; durable full voice history is deferred. 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":"What are the Thursday opening hours?","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 (deferred)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"conversation_id":"60000000-0000-4000-8000-000000000001","client_request_id":"90000000-0000-4000-8000-000000000001","message":"What are the Thursday opening hours?"}
|
||||||
|
```
|
||||||
|
|
||||||
|
```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":"The illustrative working-hours document states Thursday closing is noon.","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Working Hours","excerpt":"Illustrative Thursday hours: 08:00 to 12:00.","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 (deferred)
|
||||||
|
|
||||||
|
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 — direct Gemini Live; proposed application WSS
|
||||||
|
|
||||||
|
The initial provider is direct Gemini Live managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Audio/event field names below are proposed application names, not provider-native event names.
|
||||||
|
|
||||||
|
### V01 — Create session (HTTP)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"conversation_id":"61000000-0000-4000-8000-000000000001","client_request_id":"91000000-0000-4000-8000-000000000001"}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"session_id":"a0000000-0000-4000-8000-000000000001","conversation_id":"61000000-0000-4000-8000-000000000001","status":"connecting","stream_path":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001/stream","expires_at":"2026-10-06T09:30:00Z","poll_url":"/api/v1/voice/sessions/a0000000-0000-4000-8000-000000000001"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Voice conversation must be owned and current-epoch. Reserve session before provider creation. Scope key `(owner,client_request_id)`; hash normalized conversation/create options, with no SDP. Changed payload is 409. One nonterminal session per conversation. Duplicate creation returns 202 and the existing ID/state; completed replay returns 201 with the same still-eligible session. Replay never creates another provider connection. Closed/failed/expired returns 409 `LIVE_SESSION_UNUSABLE`.
|
||||||
|
|
||||||
|
No persistent provider secret or provider credential is returned. Backend adapter installs tools/Persian policy and enables available transcription before marking usable. Provider timeout leaves failed/uncertain reservation: inspect with V03, never blind recreation. 503 can represent a capability failure before reservation. `connecting` is not proof of working audio.
|
||||||
|
|
||||||
|
### V02 — Poll state, diagnostics and recent retrieved sources (HTTP)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"session_id":"a0000000-0000-4000-8000-000000000001","status":"connected","close_reason":null,"expires_at":"2026-10-06T09:30:00Z","recent_tool_results":[{"tool_call_id":"b0000000-0000-4000-8000-000000000001","status":"succeeded","created_at":"2026-10-06T09:08:00Z","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","excerpt":"<verified source passage>","location":{"page":1,"section":"<verified clause>"},"available":true}]}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
Illustrative payload; not an extracted source quotation. At most 20 recent results, chronological, deduplicate by tool_call_id. Sources are retrieved evidence unless exact answer attribution is verified. Redact revoked excerpts and mark unavailable. States: creating, connecting, connected, closed, failed. Poll approximately every 2 seconds while active; stop at terminal state. Polling is not durable transcript recovery. A client cannot claim connected state or inject a trusted tool result.
|
||||||
|
|
||||||
|
### V03 — Recover creation by request ID (HTTP)
|
||||||
|
|
||||||
|
200 returns V01's session/path shape if reservation remains eligible, otherwise terminal state and `stream_path:null`. Owner-only, 404 if no reservation, never creates a session. Before starting a fresh request after media loss, reconcile/close the old session. The old path does not restore provider context.
|
||||||
|
|
||||||
|
### V04 — Close (HTTP)
|
||||||
|
|
||||||
|
No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Already terminal returns its existing state. Close application stream/microphone/playback and attempt provider cleanup. Unresolved cleanup is logged and bounded by expiry; logout, auth expiry, epoch revocation and provider loss also close the session.
|
||||||
|
|
||||||
|
### 7.1 Application Live stream (WebSocket)
|
||||||
|
|
||||||
|
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
|
||||||
|
|
||||||
|
Proposed binary client frames carry mono PCM16 little-endian at 16 kHz; server audio frames carry PCM16 at 24 kHz. These rates and bounded frame/buffer limits are agreed at stream setup. JSON control/events are distinguished from binary audio. Bridge/transcoding is backend/client work, not a public provider key flow.
|
||||||
|
|
||||||
|
Illustrative proposed control/event shapes:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":16000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"transcript","turn_ref":"live-turn-1","role":"assistant","text":"<provider-supplied Persian transcript>","status":"completed"}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"sources","turn_ref":"live-turn-1","tool_call_id":"call-1","sources":[{"source_ref":"S1","document_id":"10000000-0000-4000-8000-000000000001","chunk_id":"30000000-0000-4000-8000-000000000001","title":"Illustrative circular","location":{"page":1,"section":null}}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"turn_interrupted","turn_ref":"live-turn-1","cancelled_tool_call_ids":["call-1"]}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Transcript status is partial, completed or interrupted. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
|
||||||
|
|
||||||
|
On interruption, flush audio buffers, mark partial output, cancel outstanding calls when possible and suppress late results. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
|
||||||
|
|
||||||
|
### 7.2 Internal model tool — `search_knowledge`
|
||||||
|
|
||||||
|
Model arguments, identical for the internal text-query harness, later text chat and Live. The LangChain tool uses this schema while trusted dispatcher context supplies authority:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"query":"What are the conditions and exceptions of the circular?","context":"The circular identified as source S1 in the preceding exchange."}
|
||||||
|
```
|
||||||
|
|
||||||
|
`query` required, 1–2000 characters; optional `context` proposed maximum 2000 characters, a conversation-resolved textual reference. Reject unknown fields. Context does not grant permission or turn previous model prose into evidence. No model-supplied organization/user IDs or paths; supported document filters remain deferred. Backend derives identity, current selected ready/active/undeleted scope, profile, bounded top_k/evidence size and execution IDs.
|
||||||
|
|
||||||
|
Illustrative successful result; text/location must be populated from actual retained chunks, never from these placeholders:
|
||||||
|
|
||||||
|
```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":"Illustrative administrative circular",
|
||||||
|
"text":"<verified decision together with conditions and exclusions>",
|
||||||
|
"location":{"page":1,"section":"<verified clause or heading>"}
|
||||||
|
}],
|
||||||
|
"warnings":[]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"status":"no_evidence","knowledge_revision":2,"sources":[],"warnings":["insufficient_support"]}
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"status":"error","sources":[],"error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
|
||||||
|
```
|
||||||
|
|
||||||
|
`no_evidence` is completed retrieval with insufficient support, not a provider failure. Contradictory passages may be returned with `warnings:["conflicting_evidence"]`; ask clarification or disclose conflict instead of silently resolving policy. `error` also covers provider unavailable/profile mismatch/revoked context, with normalized codes and safe retryability. Document claims require current supporting passages; greeting/clarification may omit search.
|
||||||
|
|
||||||
|
Locators use existing `location.page/section`. DOCX and image use page null, with table/row/Q&A or visual-group location in section. Same search backend/profile serves all extracted text. Source refs are unique across a turn and validated against returned evidence.
|
||||||
|
|
||||||
|
Deduplicate by parent session/turn plus provider call ID and normalized argument hash. Same running call waits; same completed call replays only after fresh eligibility/epoch checks; changed payload conflicts. Cancelled/closed/stale-parent results are not sent back to generate a new answer. No tool request becomes a public REST upload/search endpoint. The MVP persists voice tool_calls independently of deferred text turns/messages/citations. Cancelled work is terminal failed with a cancellation reason and cannot be replayed to resume speech.
|
||||||
|
|
||||||
|
## 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 |
|
||||||
|
| 409 | EXTRACTION_REVIEW_PENDING, REVIEW_STALE, REVIEW_ALREADY_DECIDED | Refresh exact review evidence or follow the recorded decision |
|
||||||
|
| 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 jobs/sessions/tool calls, normalized codes include PROVIDER_TIMEOUT, PROVIDER_UNAVAILABLE, SEARCH_FAILED, PROCESS_INTERRUPTED, CONVERSATION_STALE, TOOL_CANCELLED and EXTRACTION_REVIEW_REQUIRED. Review-required is a controlled human-action failure, not an automatic transient-provider retry. INVALID_CITATION and failed text-turn responses belong to the deferred text contract. 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
|
||||||
|
|
||||||
|
Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. 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.
|
||||||
+176
-47
@@ -1,10 +1,10 @@
|
|||||||
# RAG Assistant — Phase 1 Database Design
|
# RAG Assistant — Phase 1 Database Design
|
||||||
|
|
||||||
Version 1.1 · 2026-10-05 · Proposed physical schema and migration specification; not executed migration SQL.
|
Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations.
|
||||||
|
|
||||||
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.
|
Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization, existing ingestion foundation, retained review decisions and owned voice/session/tool metadata. Durable text turns/messages/citations are deferred. No deployed database was queried; the repository foundation migration was inspected statically for this documentation update. Only seven foundation tables are currently implemented; compare this complete proposal with actual migrations before applying it. Live tables/SDP fields are not applied foundation schema.
|
||||||
|
|
||||||
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.
|
Document revision 1.3 is not an Alembic schema revision. Preserve the seven applied foundation tables/migration. The active MVP adds four tables: auth_sessions, conversations, live_sessions and voice-only tool_calls (eleven total), plus forward changes for retained review state/audit action. The fourteen-table broader text design is deferred. Document identities remain direct; technical revisions/profiles are not content versions.
|
||||||
|
|
||||||
## 1. Conventions
|
## 1. Conventions
|
||||||
|
|
||||||
@@ -16,6 +16,21 @@ Use RESTRICT/NO ACTION for normal deletion; no broad CASCADE from users/document
|
|||||||
|
|
||||||
## 2. Relationship overview
|
## 2. Relationship overview
|
||||||
|
|
||||||
|
The active MVP uses owned voice conversations and voice tool records:
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
erDiagram
|
||||||
|
documents ||--o{ document_chunks : contains
|
||||||
|
documents ||--|| ingestion_jobs : processes
|
||||||
|
users ||--o{ auth_sessions : authenticates
|
||||||
|
users ||--o{ conversations : owns
|
||||||
|
conversations ||--o{ live_sessions : hosts
|
||||||
|
auth_sessions ||--o{ live_sessions : authorizes
|
||||||
|
live_sessions ||--o{ tool_calls : executes
|
||||||
|
```
|
||||||
|
|
||||||
|
The following diagram is the deferred text-and-voice model; it is not a migration requirement for the current milestone:
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
erDiagram
|
erDiagram
|
||||||
documents ||--o{ document_chunks : contains
|
documents ||--o{ document_chunks : contains
|
||||||
@@ -109,13 +124,13 @@ UNIQUE(organization_id,upload_request_id). Scoped FK uploaded_by→users. CHECK
|
|||||||
|
|
||||||
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.
|
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):
|
Freeze the actual snapshot produced by IngestionSettings.processing_profile,
|
||||||
|
including current schema-2 extraction/normalization/chunking and embedding
|
||||||
```json
|
identity/request limits. Do not replace it with the older illustrative flat
|
||||||
{"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"}}
|
JSON profile. Current extraction/chunking/embedding components are implemented;
|
||||||
```
|
their worker integration and atomic publication are implemented for the requested Phase 5 worker scope. Dimension D is explicit;
|
||||||
|
equal dimensions alone do not make models compatible. LangChain integration
|
||||||
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.
|
does not change these snapshots or require re-embedding compatible vectors.
|
||||||
|
|
||||||
### 4.2 document_chunks
|
### 4.2 document_chunks
|
||||||
|
|
||||||
@@ -124,7 +139,7 @@ Profile example (illustrative values, confirm Day 1):
|
|||||||
| id, organization_id, document_id | uuid | Source identity |
|
| id, organization_id, document_id | uuid | Source identity |
|
||||||
| ordinal | integer | 0-based order |
|
| ordinal | integer | 0-based order |
|
||||||
| text | text | Extracted evidence |
|
| text | text | Extracted evidence |
|
||||||
| location | jsonb | `{page: integer-or-null, section: string-or-null}` |
|
| location | jsonb | `{page: integer-or-null, section: string-or-null}`; section may identify table/row/Q&A or image group |
|
||||||
| token_count | integer nullable | Actual tokenizer count if available |
|
| token_count | integer nullable | Actual tokenizer count if available |
|
||||||
| embedding | vector(D) | Model-compatible vector |
|
| embedding | vector(D) | Model-compatible vector |
|
||||||
| created_at | timestamptz | Publication |
|
| created_at | timestamptz | Publication |
|
||||||
@@ -166,7 +181,83 @@ Server validates profile, dimension and bounded top_k before query. A nearest ne
|
|||||||
|
|
||||||
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.
|
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
|
### 4.4 Retained extraction, review and factual inclusion
|
||||||
|
|
||||||
|
Existing code validates extraction envelopes and stores non-queryable candidates.
|
||||||
|
Phase 5 implements durable current-claim complete_artifact attachment/reuse in
|
||||||
|
forward revision 0002_worker_artifact, with documents.extraction_state jsonb
|
||||||
|
NOT NULL DEFAULT '{}' and CHECK jsonb_typeof(extraction_state)='object'.
|
||||||
|
Partial review candidates, decisions and factual inclusion below are implemented
|
||||||
|
behind trusted backend services in forward revision 0003_extraction_review.
|
||||||
|
Authenticated D06/D07 HTTP transport still requires identity/Origin/CSRF integration. This is derived-processing
|
||||||
|
metadata, not a new document lifecycle or content version.
|
||||||
|
|
||||||
|
Keep large image/block/envelope bodies in the separate durable extraction
|
||||||
|
namespace. extraction_state holds bounded trusted references and decisions:
|
||||||
|
|
||||||
|
| Logical field | Requirement |
|
||||||
|
| --- | --- |
|
||||||
|
| original_sha256, extraction_profile_sha256 | Source/frozen extraction identity |
|
||||||
|
| complete_artifact | Nullable trusted storage key/digest for a complete validated envelope |
|
||||||
|
| candidates | Bounded array of exact retained page/block or factual-corpus references, review kind, locator and evidence digest |
|
||||||
|
| decisions | Evidence-bound approved/rejected status, required checks, note and authenticated reviewer identity |
|
||||||
|
| factual_inclusion | Nullable approved extraction digest and whole excluded Q&A group IDs; never rewrites faithful text |
|
||||||
|
|
||||||
|
Persist candidate image/block hashes and storage keys privately; public API
|
||||||
|
returns authenticated preview paths and faithful blocks, not raw storage keys.
|
||||||
|
Server recomputes review_digest using original, frozen extraction identity,
|
||||||
|
locator, exact image and exact blocks. Bind factual approval/inclusion to the
|
||||||
|
complete extraction digest and existing group IDs. Bound JSON/reference count,
|
||||||
|
preview bytes, notes and groups under the recorded processing/deployment limits.
|
||||||
|
|
||||||
|
Worker attachment/progress/completion writes lock document then job and verify
|
||||||
|
current token, unexpired lease, original/profile and non-deletion. Write immutable
|
||||||
|
file candidates before short transactions; orphan candidates are report-only
|
||||||
|
until a separately approved cleanup policy. An unfenced late result cannot
|
||||||
|
replace retained output or an approved decision.
|
||||||
|
|
||||||
|
Complete-artifact attachment compares the validated candidate pointer under those
|
||||||
|
locks: the identical pointer replays without changing other extraction_state
|
||||||
|
fields; a different pointer cannot replace it. Both paths still require the
|
||||||
|
current claim and valid lease. No replay bypasses fencing.
|
||||||
|
|
||||||
|
When PDF/vision review is required, retain exact candidate output under the
|
||||||
|
current claim, mark job/document failed with EXTRACTION_REVIEW_REQUIRED, clear
|
||||||
|
claim ownership and publish zero chunks. Do not hold a lease for a human or add
|
||||||
|
waiting_review. This outcome is not an automatically retried provider error.
|
||||||
|
|
||||||
|
Admin D07 locks document then job, validates the same failed candidate/source/
|
||||||
|
profile, and commits decision plus unique extraction_review audit replay record
|
||||||
|
atomically. Resolve an authorized replay before rechecking changing state.
|
||||||
|
Concurrent changed decisions fail with REVIEW_ALREADY_DECIDED; stale candidate
|
||||||
|
identity fails with REVIEW_STALE. Decisions do not mark ready or activate.
|
||||||
|
D04 requeues the same eligible failed job after required approvals.
|
||||||
|
|
||||||
|
Reuse exact approved retained page/block candidates to resume QC. An incomplete
|
||||||
|
candidate is never treated as an indexable complete envelope. A fresh vision
|
||||||
|
response requires fresh review. After all coverage and approvals succeed,
|
||||||
|
assemble/validate and attach the complete extraction artifact under a valid
|
||||||
|
claim. Preserve it independently of vector staging; no OCR repeat solely
|
||||||
|
because chunking/embedding changes.
|
||||||
|
|
||||||
|
For FAQ, record explicit factual authority and whole-group exclusions
|
||||||
|
separately. Preserve all original Q&A associations in faithful extraction;
|
||||||
|
only approved factual groups feed chunking. Governing context is resolved from the
|
||||||
|
whole retained structure before selection and stays with each affected answer;
|
||||||
|
context exclusive to excluded pairs is omitted. Review exposes the same context.
|
||||||
|
Reviewer prose is stored as bounded inspection metadata separately from quality
|
||||||
|
warnings and never interpreted as an extraction unreadability flag. Behavioral scenarios and live-data
|
||||||
|
placeholders remain unsearchable factual content. No trustworthy remaining
|
||||||
|
groups means visible failure. Client text/group labels cannot bypass validation.
|
||||||
|
|
||||||
|
Chunk text stays faithful evidence; its embedding input and lexical/identifier
|
||||||
|
matching use recorded normalization. Do not reverse numbers, drop exceptions
|
||||||
|
or change meaning. Reindexing ready documents is separately designed controlled
|
||||||
|
maintenance, not failed-job retry. Purging applies to originals, extraction
|
||||||
|
candidates/artifacts, decisions, chunks and retained tool excerpts under an
|
||||||
|
explicit policy; immediate logical exclusion remains required.
|
||||||
|
|
||||||
|
## 5. Minimal voice conversation and evidence; deferred text tables
|
||||||
|
|
||||||
### 5.1 conversations
|
### 5.1 conversations
|
||||||
|
|
||||||
@@ -181,9 +272,9 @@ UNIQUE(document_id). CHECK processing requires claim_token and lease_expires_at;
|
|||||||
| access_epoch | bigint | Knowledge-removal snapshot |
|
| access_epoch | bigint | Knowledge-removal snapshot |
|
||||||
| created_at, updated_at | timestamptz | Ordering |
|
| 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.
|
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. The MVP accepts mode=voice only, records owned identity/epoch and retains no message history. The proposed future mode=text branch is not enabled by merely adding the column. Add chain keys needed for live ownership; stale/closed conversations cannot start new media.
|
||||||
|
|
||||||
### 5.2 turns
|
### 5.2 turns (deferred)
|
||||||
|
|
||||||
| Column | Type/default | Meaning |
|
| Column | Type/default | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -201,7 +292,7 @@ UNIQUE(owner_user_id,client_request_id). Scoped FK owner. Index owner/created_at
|
|||||||
|
|
||||||
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.
|
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
|
### 5.3 messages (deferred)
|
||||||
|
|
||||||
| Column | Type/default | Meaning |
|
| Column | Type/default | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -213,27 +304,41 @@ UNIQUE(conversation_id,client_request_id). Partial UNIQUE(conversation_id) WHERE
|
|||||||
|
|
||||||
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.
|
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
|
### 5.4 tool_calls (voice-only MVP)
|
||||||
|
|
||||||
| Column | Type/default | Meaning |
|
| Column | Type/default | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| id, organization_id | uuid | Identity |
|
| id, organization_id, live_session_id | uuid | Owned voice parent; live_session_id NOT NULL |
|
||||||
| turn_id | uuid nullable | Text parent |
|
| external_call_id | text | Provider call correlation |
|
||||||
| live_session_id | uuid nullable | Voice parent |
|
| tool_name | text | search_knowledge only |
|
||||||
| external_call_id | text | Provider/orchestrator correlation |
|
| arguments | jsonb | Validated query/context without model scope |
|
||||||
| tool_name | text | search_documents only |
|
| request_hash | char(64) | Canonical argument digest |
|
||||||
| arguments | jsonb | Validated query, no trusted scope from model |
|
|
||||||
| request_hash | char(64) | Canonical arguments digest |
|
|
||||||
| status | text running | running, succeeded, failed |
|
| status | text running | running, succeeded, failed |
|
||||||
| knowledge_revision, access_epoch | bigint | Retrieval snapshots |
|
| knowledge_revision, access_epoch | bigint | Retrieval snapshots |
|
||||||
| result_json | jsonb nullable | Evidence IDs, text, locations or normalized tool error |
|
| result_json | jsonb nullable | Evidence IDs/text/locations, no_evidence or normalized error |
|
||||||
| error_code | text nullable | Failure |
|
| error_code | text nullable | Technical/cancellation reason |
|
||||||
| created_at | timestamptz | Creation |
|
| created_at | timestamptz | Creation |
|
||||||
| completed_at | timestamptz nullable | Completion |
|
| completed_at | timestamptz nullable | Terminal 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.
|
UNIQUE(live_session_id,external_call_id); scoped FK to live_sessions.
|
||||||
|
CHECK terminal iff completed_at is non-null; CHECK tool_name='search_knowledge'.
|
||||||
|
No turn_id or FK to deferred turns/messages/citations is required in this
|
||||||
|
migration. A later text extension must explicitly add its parent/constraint
|
||||||
|
design; it is not implicit scope for this MVP.
|
||||||
|
|
||||||
### 5.5 citations
|
Same call ID/hash waits or replays saved output after fresh eligibility/epoch
|
||||||
|
checks. Different hash conflicts. Cancelled, expired, stale or closed-parent work
|
||||||
|
is terminal failed with safe reason, and cannot release late evidence or resume
|
||||||
|
audio. API restart fails interrupted running calls and their old media sessions.
|
||||||
|
Provider work is outside transactions.
|
||||||
|
|
||||||
|
Source references are unique within a live turn; result_json retains actual
|
||||||
|
document_id/chunk_id, title, faithful excerpt and nullable location. UI labels
|
||||||
|
them retrieved evidence unless spoken attribution is verified. Redact revoked
|
||||||
|
excerpts on poll/replay. Retained tool content is covered by purge policy;
|
||||||
|
diagnostic logs must not contain document bodies/audio/secrets.
|
||||||
|
|
||||||
|
### 5.5 citations (deferred)
|
||||||
|
|
||||||
| Column | Type/default | Meaning |
|
| Column | Type/default | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -257,27 +362,26 @@ Keep source identity rows as tombstones if allowed. `available` in API is comput
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| id, organization_id, conversation_id, owner_user_id, auth_session_id | uuid | Session ownership and logout correlation |
|
| id, organization_id, conversation_id, owner_user_id, auth_session_id | uuid | Session ownership and logout correlation |
|
||||||
| client_request_id | uuid | Creation correlation |
|
| client_request_id | uuid | Creation correlation |
|
||||||
| request_hash | char(64) | Conversation + SDP-offer digest |
|
| request_hash | char(64) | Normalized conversation/create-options digest; no SDP |
|
||||||
| provider, model | text | Chosen live profile |
|
| provider, model | text | Chosen live profile |
|
||||||
| provider_session_id | text nullable | External reference |
|
| provider_session_id | text nullable | External reference |
|
||||||
| status | text creating | creating, connecting, connected, closed, failed |
|
| status | text creating | creating, connecting, connected, closed, failed |
|
||||||
| settings_revision, knowledge_revision, access_epoch | bigint | Creation snapshots |
|
| settings_revision, knowledge_revision, access_epoch | bigint | Creation snapshots |
|
||||||
| execution_profile | jsonb | Instruction/prompt profile snapshot |
|
| execution_profile | jsonb | Instruction/prompt plus proposed audio/transcription capability snapshot |
|
||||||
| sdp_answer_ciphertext | bytea nullable | Short-lived encrypted replay material |
|
|
||||||
| expires_at, created_at, updated_at | timestamptz | TTL/lifecycle |
|
| expires_at, created_at, updated_at | timestamptz | TTL/lifecycle |
|
||||||
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
|
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
|
||||||
| close_reason, error_code | text nullable | Normalized reason |
|
| 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.
|
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. No SDP replay field is required for the proposed Gemini WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
|
||||||
|
|
||||||
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.
|
API instance owns the direct Gemini Live WSS connection and audio relay 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. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
|
||||||
|
|
||||||
### 6.2 audit_events
|
### 6.2 audit_events
|
||||||
|
|
||||||
| Column | Type/default | Meaning |
|
| Column | Type/default | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| id, organization_id, actor_user_id | uuid (actor nullable) | Administrator/system action |
|
| 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 |
|
| action | text | upload, selection_changed, document_deleted, ingestion_retry, extraction_review, configuration_changed, session_revoked |
|
||||||
| target_id | uuid nullable | Referenced object; polymorphic diagnostic field |
|
| target_id | uuid nullable | Referenced object; polymorphic diagnostic field |
|
||||||
| request_id | text nullable | HTTP tracing |
|
| request_id | text nullable | HTTP tracing |
|
||||||
| idempotency_key | uuid nullable | Delete/retry idempotency |
|
| idempotency_key | uuid nullable | Delete/retry idempotency |
|
||||||
@@ -286,7 +390,7 @@ API instance owns live control in memory; DB stores mapping/state, not recoverab
|
|||||||
| metadata | jsonb | Changed IDs/revisions, redacted reason |
|
| metadata | jsonb | Changed IDs/revisions, redacted reason |
|
||||||
| created_at | timestamptz | Event time |
|
| 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.
|
Partial UNIQUE(organization_id,actor_user_id,action,target_id,idempotency_key) WHERE idempotency_key IS NOT NULL. Delete/retry/review require non-null actor and target. A forward migration extends the action CHECK and replay-required CHECK to extraction_review; never edit the initial revision. 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
|
## 7. Transaction boundaries and invariant enforcement
|
||||||
|
|
||||||
@@ -294,10 +398,12 @@ Partial UNIQUE(organization_id,actor_user_id,action,target_id,idempotency_key) W
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Upload | Document + job + audit | File staging/write; reconcile orphans |
|
| Upload | Document + job + audit | File staging/write; reconcile orphans |
|
||||||
| Claim | Row lock, new token/lease, attempt increment | Extraction and provider calls |
|
| 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 |
|
| Publish | Lock document/job; verify token/lease; insert all chunks once; ready/succeeded | Already complete staged embeddings |
|
||||||
| Selection | Settings lock, expected revision, active flags, revision/epoch, stale conversations, audit | Best-effort closing provider sessions after logical invalidation |
|
| 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 |
|
| Review decision | Document/job lock, exact candidate/source/profile check, decision + audit replay | Reading exact retained preview; no provider call |
|
||||||
| Chat completion | Settings/conversation locks, epoch validation, assistant + citations + terminal status | Browser delivery after commit |
|
| Review/artifact attachment | Document/job lock, current token/lease, trusted references/progress | Bounded candidate/artifact file writes |
|
||||||
|
| Deferred chat admission | Settings/conversation locks, request lookup, turn + user message | Provider inference/tool loop |
|
||||||
|
| Deferred 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 |
|
| 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 |
|
| Delete/retry | State change + unique audit replay result | Physical cleanup or future worker execution |
|
||||||
|
|
||||||
@@ -307,20 +413,43 @@ On active-document removal: database epoch invalidation is authoritative immedia
|
|||||||
|
|
||||||
## 8. Migration plan
|
## 8. Migration plan
|
||||||
|
|
||||||
| Migration | Content | Gate |
|
Treat migrations/versions/0001_ingestion_foundation.py as applied and immutable.
|
||||||
| --- | --- | --- |
|
The generic 001_identity/002_knowledge/003_conversations sequence from revision
|
||||||
| 001_identity | organizations, users, auth_sessions, settings | Seed one org and admin/user securely |
|
1.2 is not an instruction to recreate or combine the current foundation.
|
||||||
| 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.
|
| Forward change | Content and gate |
|
||||||
|
| --- | --- |
|
||||||
|
| Retained extraction/review | documents.extraction_state; extraction_review audit/check support; test fencing, stale decisions and idempotency |
|
||||||
|
| Identity and voice | auth_sessions, owned voice conversations, live_sessions, voice-only tool_calls; scoped/owner-chain FKs and replay/partial uniqueness |
|
||||||
|
| Later text milestone | turns/messages/citations plus explicit text-tool parent extension; not needed for voice shipment |
|
||||||
|
|
||||||
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.
|
Choose actual revision IDs after inspecting Alembic head. Create tables in FK
|
||||||
|
dependency order and update compatibility/schema checks for new revisions
|
||||||
|
without weakening original frozen embedding checks. Inspect bootstrap/consumers
|
||||||
|
of changed contracts. Validate upgrades against isolated real PostgreSQL.
|
||||||
|
|
||||||
|
The seven foundation tables already hold organizations/users/settings,
|
||||||
|
documents/jobs/chunks and audit. Preserve IDs, profile snapshots, vectors and
|
||||||
|
original files. No model/dimension/preprocessing change or content rewrite is
|
||||||
|
authorized by framework integration. No applied migration was changed or new
|
||||||
|
migration executed by this documentation update.
|
||||||
|
|
||||||
## 9. Essential database validation
|
## 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.
|
Require real PostgreSQL evidence for current MVP changes: cross-organization/
|
||||||
|
owner-chain FK rejection; upload/review/retry/live-create replay and changed
|
||||||
|
payload conflicts; concurrent live reservation; claim/lease fencing; exact
|
||||||
|
retained-output decisions and attachment races; retry of the same document/job;
|
||||||
|
complete publication rollback/ambiguous commit/crash; inactive/deleted exclusion;
|
||||||
|
epoch race before tool-result delivery; cancellation/restart terminal states.
|
||||||
|
Tool sources must resolve to the actual document/chunk chain.
|
||||||
|
|
||||||
|
Ordinary-suite skips do not establish database acceptance. Use the documented
|
||||||
|
isolated TEST_DATABASE_URL with --require-postgres. Existing recorded foundation/
|
||||||
|
Phase 3/4 historical results and current Phase 5/6 worker/database acceptance
|
||||||
|
are separate from pending authenticated transport/browser/Live acceptance and
|
||||||
|
real-provider/Persian quality.
|
||||||
|
Text finalization/history/citation tests belong to the later text milestone.
|
||||||
|
|
||||||
## 10. Deliberately absent from Phase 1
|
## 10. Deliberately absent from Phase 1
|
||||||
|
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
# RAG Assistant — Phase 1 Implementation Guide
|
||||||
|
|
||||||
|
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
|
||||||
|
|
||||||
|
## 1. Purpose and authority
|
||||||
|
|
||||||
|
Implement the conditional four-day Live document MVP in
|
||||||
|
`RAG-AI-Phase1-Delivery-Plan.md`. API/database specifications govern their
|
||||||
|
contracts. The English `RAG-Phase1-MVP-Scenarios.md` supplies acceptance
|
||||||
|
walkthroughs; the older Persian report is historical context.
|
||||||
|
|
||||||
|
One organization, pre-created users, one API instance and one separate worker.
|
||||||
|
Reuse ingestion Phases 1-4, including the current hosted embedding/staging
|
||||||
|
implementation and reviewed repairs. Phase 5 worker/publication/retry and retained
|
||||||
|
review/resume backend services, plus Phase 6 ingestion validation/handoff, are
|
||||||
|
implemented. Authenticated D06/D07 transport and HTTP/search/Live/UI integrations
|
||||||
|
remain pending. The four supplied files are required
|
||||||
|
examples, not the accepted corpus or a filename allowlist. New documents within
|
||||||
|
declared format/structure/resource limits must run without developer changes.
|
||||||
|
|
||||||
|
## 2. Decisions for this implementation
|
||||||
|
|
||||||
|
| Topic | Current MVP decision |
|
||||||
|
| --- | --- |
|
||||||
|
| Backend | Modular FastAPI API and separate worker from the same codebase |
|
||||||
|
| Framework | LangChain for retriever/tool integration; keep provider-neutral application services |
|
||||||
|
| Existing embeddings | Preserve EmbeddingProvider.embed, OpenAICompatibleEmbeddings and stage_document; a thin Embeddings wrapper is optional |
|
||||||
|
| UI | Same-origin HTTPS login plus one voice workspace with an admin Documents area |
|
||||||
|
| Identity | Opaque cookie sessions, admin/user roles, owned voice conversations; no signup |
|
||||||
|
| Jobs | PostgreSQL polling, current-claim lease fencing and complete atomic publication |
|
||||||
|
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
|
||||||
|
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
|
||||||
|
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
|
||||||
|
| Voice | Direct Gemini Live audio over backend WSS; shared LangChain knowledge tool |
|
||||||
|
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
|
||||||
|
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
|
||||||
|
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
|
||||||
|
|
||||||
|
## 3. Modules and ports
|
||||||
|
|
||||||
|
| Module / path | Responsibility |
|
||||||
|
| --- | --- |
|
||||||
|
| `app/api/v1/` | DTOs, cookie/Origin/CSRF validation and safe HTTP errors |
|
||||||
|
| `modules/identity/` | Login, sessions and trusted actor context |
|
||||||
|
| `modules/documents/` | Existing intake/extraction/chunking/embedding; review, status, retry and selection |
|
||||||
|
| `modules/knowledge/` | One scoped search/evidence service and bounded query embedding |
|
||||||
|
| `modules/conversations/` | Minimal owned voice conversation identity/epoch; text execution deferred |
|
||||||
|
| `modules/live/` | Session reservation, audio relay, trusted tool dispatch, cancellation and lifecycle |
|
||||||
|
| `infrastructure/` | Existing SQL/file/provider adapters plus a small LangChain integration boundary |
|
||||||
|
| `app/worker.py` | Fenced claim, heartbeat, processing, review interruption, publication and recovery |
|
||||||
|
|
||||||
|
Application services retain provider-neutral values. LangChain Documents carry
|
||||||
|
faithful chunk text plus document_id/chunk_id/title/location metadata, but
|
||||||
|
neither a Document nor model metadata grants scope. A custom retriever invokes
|
||||||
|
the shared search service with authenticated backend context. The registered
|
||||||
|
search_knowledge tool exposes only query and optional resolved context.
|
||||||
|
|
||||||
|
If a LangChain component requires Embeddings, map embed_query and bounded
|
||||||
|
embed_documents to the existing provider. Respect per-input/token/batch limits,
|
||||||
|
frozen model/dimension/preprocessing identity and float32 validation. Handle
|
||||||
|
empty document lists at the wrapper boundary; do not call an adapter that
|
||||||
|
requires a nonempty batch. Bound aggregate requests and preserve input order.
|
||||||
|
Do not add internal retries, truncation, fresh normalization or provider defaults.
|
||||||
|
Async calls must run existing blocking I/O off the audio/event loop with bounded
|
||||||
|
concurrency/deadlines; cancellation cannot recall a blocking network request.
|
||||||
|
|
||||||
|
Ingestion continues to use stage_document and its publication contract.
|
||||||
|
Do not replace it with a framework vector-store insertion helper that bypasses
|
||||||
|
staging, authorization, IDs, profile checks or atomic publication. A custom
|
||||||
|
retriever is sufficient; using LangChain does not require a new vector database,
|
||||||
|
LangGraph rewrite or a separate text-model inference on each audio turn.
|
||||||
|
|
||||||
|
## 4. Implementation order and deliverables
|
||||||
|
|
||||||
|
| Work package | Work and completion proof |
|
||||||
|
| --- | --- |
|
||||||
|
| WP1 - Early provider proof | Real Persian audio/transcripts plus one backend-executed tool call on target network; configure fixed funded profiles |
|
||||||
|
| WP2 - Identity and upload | Secure sessions and bounded multipart transport reuse intake; new upload persists and duplicate key replays |
|
||||||
|
| WP3 - Worker and review | Continue ingestion Phase 5; fence claims, candidates/decisions, artifact reuse, retries and complete publication |
|
||||||
|
| WP4 - Shared search | Compatible query vectors, exact identifier matching and eligibility joins; independently marked evidence evaluation |
|
||||||
|
| WP5 - LangChain and Live | Expose the same search tool, reserve owned sessions, relay PCM, correlate tools/transcripts/sources and suppress cancellation |
|
||||||
|
| WP6 - UI/deployment/acceptance | Minimal workspace, all four examples plus unseen uploads, provider/restart/revocation checks and actual HTTPS rehearsal |
|
||||||
|
|
||||||
|
Map these packages to Days 1-4 in the delivery plan. WP1 is an early risk gate,
|
||||||
|
not work postponed until the other packages finish. A developer can progress
|
||||||
|
independent worker/API work while provider validation is unresolved; no agent
|
||||||
|
delegation, parallel staffing or completed proof is assumed.
|
||||||
|
|
||||||
|
Recommended first implementation task: complete WP3 using existing Phases 1-4
|
||||||
|
and forward schema changes for retained review state, while running WP1 early.
|
||||||
|
Keep the original migration byte-for-byte and report actual check outcomes.
|
||||||
|
|
||||||
|
## 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. Authenticate admin and validate upload idempotency key, bounded bytes,
|
||||||
|
actual type/signature/package structure and safe display title/filename.
|
||||||
|
Never read an unbounded multipart body or use a filename as a storage path.
|
||||||
|
2. Reuse the intake service/ports with bounded temporary input where needed.
|
||||||
|
Preserve the replay digest of bytes and normalized title; no new model/profile
|
||||||
|
or client organization fields enter the request. Repeated same key/input
|
||||||
|
returns the original document/job. A new key creates an independent document.
|
||||||
|
3. Save the immutable original and create document/job/audit in a short transaction.
|
||||||
|
Hash/reconcile files outside long transactions. New document is inactive.
|
||||||
|
4. Claim eligible work with token/lease, attempts and documented lock order.
|
||||||
|
Provider work runs outside long transactions. Heartbeat throughout slow calls.
|
||||||
|
5. Dispatch existing frozen-profile extraction/normalization/chunking and
|
||||||
|
embedding components. Validate original checksum and actual provider identity.
|
||||||
|
A legacy profile is dispatched explicitly, never silently reinterpreted.
|
||||||
|
6. Retain exact extraction output for review/reuse, then stage every embedding.
|
||||||
|
The current PageBlockExtractor requires review for PDF pages and vision output;
|
||||||
|
this is an actual implementation gate, not an optional UI decoration.
|
||||||
|
7. Publish all chunks and ready/succeeded state in one fenced transaction.
|
||||||
|
Verify token, unexpired lease, original/profile, non-deletion, complete vectors,
|
||||||
|
ordinals and eligibility; keep is_active=false. Never republish a ready document.
|
||||||
|
|
||||||
|
### 6.1 Exact-output review and resume
|
||||||
|
|
||||||
|
A ReviewRequired outcome is mapped by the new worker to a bounded,
|
||||||
|
non-automatically-retried failed attempt with EXTRACTION_REVIEW_REQUIRED.
|
||||||
|
It is distinct from a malformed/permanently unreadable source. Persist trusted
|
||||||
|
references to the exact bounded image/block candidate, source/extraction
|
||||||
|
identity, locator, digest and progress under the current claim before releasing
|
||||||
|
the lease. Unreviewed candidates are not complete validated artifacts and cannot
|
||||||
|
be indexed. Crash recovery must not attach uncommitted or stale candidates.
|
||||||
|
|
||||||
|
D06 shows retained candidates to the admin. D07 records approval/rejection of
|
||||||
|
the exact evidence digest and required checks. New OCR output has a different
|
||||||
|
review identity and requires a new decision. Server validates/recomputes digests;
|
||||||
|
client supplied text, paths, profile identity and reviewer identity are forbidden.
|
||||||
|
Use job/document locks and current failed-candidate identity for decisions.
|
||||||
|
Decisions neither activate nor mark a document ready.
|
||||||
|
|
||||||
|
After approval, D04 requeues the same eligible job once per key. Resume using
|
||||||
|
the retained inspected page/block output; do not rerun vision and assume the
|
||||||
|
new response was approved. Additional pages may need further review. Rejecting
|
||||||
|
a candidate keeps it failed/unsearchable with zero publication. Never hold a
|
||||||
|
lease waiting for a person. No waiting_review lifecycle status is introduced.
|
||||||
|
|
||||||
|
The implementation must persist complete extraction independently of vectors.
|
||||||
|
On validated complete-artifact reuse, check original digest, extraction identity,
|
||||||
|
coverage, warnings and trusted attachment. Chunk/embedding changes alone are
|
||||||
|
not a reason to repeat OCR. Partial review candidates can resume QC but cannot
|
||||||
|
bypass complete-artifact validation or create partial publication.
|
||||||
|
|
||||||
|
### 6.2 Factual FAQ gate
|
||||||
|
|
||||||
|
Existing chunking requires approved_factual for Q&A. New uploaded FAQs need an
|
||||||
|
explicit admin approval route, not a hardcoded filename exemption or CLI-only
|
||||||
|
flag. D06 exposes factual-corpus review bound to the extraction digest and
|
||||||
|
groups. D07 can record whole Q&A groups excluded because they are behavioral
|
||||||
|
scenarios, placeholders or unapproved facts. Never split a question from its answer.
|
||||||
|
|
||||||
|
Preserve the complete faithful extraction/original. Store an inclusion decision
|
||||||
|
separately with reviewer, digest and excluded group IDs. Only approved factual
|
||||||
|
groups form chunk drafts, with original locators; placeholders cannot become
|
||||||
|
answers by virtue of approval. If no reliable groups remain, fail visibly.
|
||||||
|
Existing validation stays enabled; any new manifest-aware preparation boundary
|
||||||
|
requires regression tests. Numeric/source fidelity and authority are distinct.
|
||||||
|
|
||||||
|
Factual preparation validates the whole retained source structure before selecting
|
||||||
|
groups. Explicit heading ancestry associates governing headings and introductory
|
||||||
|
conditions with each descendant Q&A pair; existing whole-group context stays
|
||||||
|
exclusive to that pair. Preserve conditions, negation, exceptions and their real
|
||||||
|
locators in every affected draft. Ambiguous unheaded preambles, detached prose or
|
||||||
|
unresolved relationships fail visibly instead of becoming unrestricted answers.
|
||||||
|
Factual review exposes that context from the same immutable complete artifact.
|
||||||
|
Reviewer identity/checks/note are bounded review metadata, not machine quality
|
||||||
|
warnings; administrator prose never changes extraction readability decisions.
|
||||||
|
|
||||||
|
### 6.3 Retry, recovery and capacity
|
||||||
|
|
||||||
|
Transient network/rate-limit errors use bounded backoff/jitter and the existing
|
||||||
|
retry budget. Permanent malformed input fails immediately. Review-required work
|
||||||
|
waits as failed for a valid decision, without automatic provider loops.
|
||||||
|
Manual retry resets attempts and increments retry_generation on the same job
|
||||||
|
once per key. Source modifications require a new upload.
|
||||||
|
|
||||||
|
Maintain file reconciliation and safe redacted diagnostics. Unknown document
|
||||||
|
count requires durable backlog, pagination, disk/quota observation and bounded
|
||||||
|
processing/admission. Configured defaults are deployment choices, not capacity
|
||||||
|
proof. Physical purging and retention periods remain unresolved.
|
||||||
|
|
||||||
|
## 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. Deferred text turn execution
|
||||||
|
|
||||||
|
This section preserves the follow-up text contract; it is not required by the current Live MVP. No new public text chat or durable message history is required. The internal query harness invokes the SAME scoped search service without implementing this turn lifecycle.
|
||||||
|
|
||||||
|
In that follow-up milestone, 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 owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct Gemini Live WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
|
||||||
|
|
||||||
|
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
|
||||||
|
|
||||||
|
States: `creating → connecting → connected → closed`; any nonterminal state may fail/close. Adapter-confirmed setup defines connected, not client assertions. Use deadlines, bounded audio buffers and TTL; provider calls occur outside database transactions. Restart marks previous nonterminal sessions failed and attempts cleanup.
|
||||||
|
|
||||||
|
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On interruption flush playback, mark output partial/interrupted, cancel outstanding work where possible and discard late results. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
|
||||||
|
|
||||||
|
Capture/resample client audio and convert returned PCM for playback as specified in architecture Section 8.5. Test real Persian names, dates, percentages and amounts. CTI/Asterisk is outside this web MVP and would need an explicitly commissioned audio bridge.
|
||||||
|
|
||||||
|
## 10. Internal search contract
|
||||||
|
|
||||||
|
Use the canonical proposed `search_knowledge` schema/outcomes in [API catalog Section 7.2](RAG-Phase1-API-Catalog.md). Required query plus optional resolved context; no model-supplied scope. Proposed backend defaults remain top 5 chunks and maximum 12000 evidence characters, to calibrate against the corpus.
|
||||||
|
|
||||||
|
Return actual document/chunk identities and nullable source locators. Distinguish `ok`, `no_evidence`, `error`; similarity alone does not prove sufficient evidence. Use semantic pgvector search plus normalized exact identifier/date/article matching as the initial baseline. Full hybrid fusion, reranking and ANN are conditional on measured failures; adding them must preserve all eligibility checks and the deadline must be re-estimated if required. No new vector store.
|
||||||
|
|
||||||
|
Queries and all text-derived chunks share a compatible fixed profile. A changed embedding model requires a controlled isolated reindex/cutover; no ready-document republishing through retry or content versioning. Preserve extracted text so OCR need not repeat.
|
||||||
|
|
||||||
|
Separate approved factual FAQs from behavioral evaluation/configuration and live-data placeholders. Retrieved instructions are untrusted source data. Without approved live-data tools, explicitly state that current tariffs, land availability, balances and case status cannot be verified; offer an authorized organizational contact/process without claiming an automated transfer.
|
||||||
|
|
||||||
|
## 11. Deployment and configuration
|
||||||
|
|
||||||
|
Deploy UI/reverse proxy, one API process, one worker process and PostgreSQL. Mount persistent originals, extraction artifacts 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, audio payloads, prompts, cookies and keys.
|
||||||
|
|
||||||
|
## 12. Tests and handoff
|
||||||
|
|
||||||
|
| Test group | Required evidence |
|
||||||
|
| --- | --- |
|
||||||
|
| Access/replay | Admin/user permissions, voice ownership, Origin/CSRF, forged scope, upload/review/retry/create replay and changed-payload conflict |
|
||||||
|
| Worker/database | Real PostgreSQL claims, expired/stale leases, heartbeat, failed final batch, rollback, ambiguous commit and restart without duplicate publication |
|
||||||
|
| Review/FAQ | Trusted retained candidate/digest, stale approval rejection, whole-group inclusion, resume same inspected output and zero chunks before complete approval |
|
||||||
|
| Selection | Revision conflict, inactive/deleted exclusion and removal closing old context |
|
||||||
|
| LangChain | Query/document adapter limits/order/compatible preprocessing if wrapper used; tool schema cannot inject identity; same retrieval implementation |
|
||||||
|
| Files | Both PDFs, infographic, DOCX pair associations plus previously unseen supported files through browser upload |
|
||||||
|
| Grounding | Independently marked evidence, unsupported/conflicting questions, placeholders and prompt-like source content |
|
||||||
|
| Real voice | Persian audio/transcripts, actual knowledge tool, follow-up/topic switch/interrupt, provider loss/logout/expiry and fresh-session recovery |
|
||||||
|
| Deployment | Target HTTPS/microphone/speaker/network and durable file/DB mapping |
|
||||||
|
|
||||||
|
Map results to MVP-01 through MVP-14 in the delivery plan. Ordinary provider-free
|
||||||
|
tests do not prove hosted model quality; configured PostgreSQL acceptance must
|
||||||
|
not skip missing infrastructure. Existing recorded results are historical,
|
||||||
|
not checks executed by this documentation revision. Run necessary affected
|
||||||
|
checks during implementation; do not extend unrelated component repairs.
|
||||||
|
|
||||||
|
Hand off startup/migration/seed/worker/retry commands, configuration, format/
|
||||||
|
structural bounds, reference questions/unseen-file results, actual latency/
|
||||||
|
provider evidence, known failures and release revision. Public text/history
|
||||||
|
acceptance stays deferred.
|
||||||
|
|
||||||
|
## 13. Decisions still requiring confirmation
|
||||||
|
|
||||||
|
Actual file/page/storage/corpus admission and session limits; factual authority
|
||||||
|
and reviewer availability; fixed funded extraction/embedding/Live identities and
|
||||||
|
vector dimension; account/quotas/Persian capability proof; hosting/connectivity;
|
||||||
|
session TTL, retention/purge, quantitative quality/latency targets and actual
|
||||||
|
presentation date. General browser upload, all four example structures,
|
||||||
|
LangChain, existing embedding reuse and direct Gemini Live are confirmed direction.
|
||||||
|
|
||||||
|
Exact-output retention/review, FAQ inclusion decisions and their forward schema/
|
||||||
|
HTTP mechanisms in this revision are implementation proposals made concrete for
|
||||||
|
review, not already implemented behavior or approval of every fact in a file.
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# Live Document MVP - English Scenarios
|
||||||
|
|
||||||
|
Version 1.3 | 2026-10-07 | Current scenario reference; examples are acceptance
|
||||||
|
requirements, not observed runtime results.
|
||||||
|
|
||||||
|
Companions: [delivery plan](RAG-AI-Phase1-Delivery-Plan.md),
|
||||||
|
[implementation guide](RAG-Phase1-Implementation-Guide.md),
|
||||||
|
[API catalog](RAG-Phase1-API-Catalog.md) and
|
||||||
|
[database design](RAG-Phase1-Database-Design.md).
|
||||||
|
|
||||||
|
## 1. Product and user journey
|
||||||
|
|
||||||
|
Known users in one organization sign in. An admin uploads new supported files
|
||||||
|
from the browser, inspects uncertain extraction, activates ready documents and
|
||||||
|
starts a Persian voice conversation. Users hear supported document answers and
|
||||||
|
see retrieved sources plus available provider transcripts.
|
||||||
|
|
||||||
|
LangChain supplies the RAG/tool integration boundary. Gemini Live manages
|
||||||
|
native audio; the backend owns secrets, identity, tools and scope. Existing
|
||||||
|
ingestion/embedding Phases 1-4 remain the processing foundation.
|
||||||
|
|
||||||
|
## 2. Four mandatory examples and unseen documents
|
||||||
|
|
||||||
|
| Example file | Required quality checks |
|
||||||
|
| --- | --- |
|
||||||
|
| 7364346504113364738_13450847753183.pdf | PDF reading order, word/digit order, real page locators and direct/page-fallback coverage |
|
||||||
|
| 5905170444656189186_13450510740952.pdf | Circular dates, percentages, conditions, negation and exceptions |
|
||||||
|
| photo_1_2026-10-06_09-05-11.jpg | Separate infographic groups and correct parent heading/description associations |
|
||||||
|
| -2348240626507047168_13449360743721.docx | Preserve all 100 Q&A associations; distinguish factual answers, behavioral scenarios and live-data placeholders |
|
||||||
|
|
||||||
|
These examples reveal required structures; they are not an upload filename/hash
|
||||||
|
allowlist or a four-document capacity limit. Upload additional previously unseen
|
||||||
|
files of the supported structures through the same UI without code changes.
|
||||||
|
Record declared limitations and understandable failures for unsupported/
|
||||||
|
unreadable/oversized content. Future total upload count is unknown; resource
|
||||||
|
bounds/backlog/capacity are explicit deployment decisions.
|
||||||
|
|
||||||
|
## 3. New browser upload and duplicate submission
|
||||||
|
|
||||||
|
The admin selects a new file/title. D01 validates actual type and configured
|
||||||
|
limits, stores immutable bytes and creates one inactive document/job.
|
||||||
|
A replay of the same idempotency key and bytes/title returns the same IDs.
|
||||||
|
A changed payload under that key conflicts. The same bytes with a new key
|
||||||
|
create a new independent document; no original overwrite or content version.
|
||||||
|
|
||||||
|
Show real queued/processing/ready/failed state; do not invent percentage progress.
|
||||||
|
A successful upload acknowledgement does not mean the file is searchable.
|
||||||
|
|
||||||
|
## 4. PDF/image review and same-output resume
|
||||||
|
|
||||||
|
Worker extraction identifies required page review and retains the exact bounded
|
||||||
|
image/block candidate under its current claim. It fails with a review-required
|
||||||
|
reason, zero published chunks and released lease.
|
||||||
|
|
||||||
|
The admin opens D06 and compares retained text with the original/rendered page.
|
||||||
|
D07 approves/rejects the digest with the required readability/order/completeness/
|
||||||
|
number/date/negation/exception checks and a note. D04 resumes the same eligible
|
||||||
|
document/job after approval. Retained inspected output is reused, rather than a
|
||||||
|
new OCR response silently inheriting approval. Further pages may need review.
|
||||||
|
|
||||||
|
A stale digest, other-organization candidate, client-supplied replacement text
|
||||||
|
or conflicting decision cannot alter evidence. Rejection keeps it unsearchable.
|
||||||
|
Partial candidates cannot be passed off as a complete validated artifact.
|
||||||
|
All pages/quality checks must finish before complete publication.
|
||||||
|
|
||||||
|
## 5. Word FAQ authority and inclusion
|
||||||
|
|
||||||
|
Extraction retains all original question/answer associations and locators.
|
||||||
|
This preserves source content, not proof that every entry is valid knowledge.
|
||||||
|
|
||||||
|
An explicit factual-corpus decision identifies approved factual FAQ groups
|
||||||
|
and excludes whole pairs that contain unapproved facts, behavioral scenarios
|
||||||
|
or current-value placeholders. Store that manifest separately from faithful
|
||||||
|
extraction; do not edit the original. Preserve valid question/answer grouping
|
||||||
|
through chunking. Empty eligible factual content fails clearly.
|
||||||
|
|
||||||
|
An entry that says a price or tariff is current without an approved value does
|
||||||
|
not authorize invented pricing. A behavioral example does not become a system
|
||||||
|
instruction through retrieval. No live business-data/telephony tool is promised.
|
||||||
|
|
||||||
|
## 6. Complete publication and active selection
|
||||||
|
|
||||||
|
Worker stages every vector using the frozen compatible profile and current
|
||||||
|
limits. A failed final batch leaves zero published chunks. Publish chunks,
|
||||||
|
ready state and succeeded job together under a valid token/unexpired lease.
|
||||||
|
A ready document stays inactive until the admin selects it.
|
||||||
|
|
||||||
|
A stale worker after lease expiry, interrupted claim, repeated publication
|
||||||
|
or uncertain commit cannot create a partial/duplicate searchable document.
|
||||||
|
Activation uses current knowledge_revision; stale selection conflicts.
|
||||||
|
|
||||||
|
## 7. Grounded spoken circular question
|
||||||
|
|
||||||
|
Create an owned voice conversation/session. Ask in Persian the equivalent of:
|
||||||
|
"What conditions and exceptions does this circular contain?"
|
||||||
|
|
||||||
|
The model calls search_knowledge with query and optional resolved context.
|
||||||
|
The backend resolves scope, embeds with the same compatible profile and returns
|
||||||
|
real evidence/document/chunk IDs and locators. The native Live model speaks a
|
||||||
|
concise answer with actual supported numbers/conditions; UI shows retrieved
|
||||||
|
sources and provider transcription when available. No numerical source content
|
||||||
|
is invented in this scenario description.
|
||||||
|
|
||||||
|
## 8. Follow-up, topic switch and ambiguity
|
||||||
|
|
||||||
|
Ask "What were its exceptions?" after a clearly identified circular.
|
||||||
|
Resolve the reference, retrieve fresh evidence and answer from it.
|
||||||
|
|
||||||
|
Then ask about a group in the infographic. Replace the old topic anchor and
|
||||||
|
retrieve that group's verified description. Do not carry unrelated circular
|
||||||
|
article/date assumptions into the new topic.
|
||||||
|
|
||||||
|
Ask "What about the next article?" without an unambiguous article/document.
|
||||||
|
Request clarification rather than choose an arbitrary similarity match.
|
||||||
|
|
||||||
|
## 9. Interruption and failure
|
||||||
|
|
||||||
|
Interrupt with the Persian equivalent of "Wait, only tell me the exceptions."
|
||||||
|
Stop/clear queued playback, mark partial output interrupted and suppress cancelled
|
||||||
|
tool results. A late result cannot restart the prior answer.
|
||||||
|
|
||||||
|
For no supporting evidence, state the limitation. For conflicting evidence,
|
||||||
|
disclose conflict or ask clarification. For query embedding/search/provider
|
||||||
|
timeout, show a technical failure; do not report that no document exists.
|
||||||
|
If Live is disconnected, the UI shows the failure without inventing a spoken
|
||||||
|
response from the unavailable provider. Reconcile/close and start a fresh
|
||||||
|
session; seamless context restoration is deferred.
|
||||||
|
|
||||||
|
## 10. Knowledge removal, logout and ownership
|
||||||
|
|
||||||
|
Deactivate a document used in a session. Increment knowledge revision/access
|
||||||
|
epoch and make older context unusable; conservatively close active organization
|
||||||
|
sessions. A fresh session searches current active evidence. Old excerpts must
|
||||||
|
not reappear through poll, cached tool replay or late result delivery.
|
||||||
|
|
||||||
|
Logout/expiry closes linked sessions. A normal user cannot upload/review/select;
|
||||||
|
another user's conversation/session cannot be read, streamed or closed by
|
||||||
|
guessing its UUID. Admin status does not grant conversation ownership.
|
||||||
|
|
||||||
|
## 11. Persistence, unknown backlog and restart
|
||||||
|
|
||||||
|
New uploads wait durably while the single worker is busy. UI lists are paginated.
|
||||||
|
Admission/resource failures are explicit, and limits are published. This scenario
|
||||||
|
does not certify unlimited corpus size or concurrent voice capacity.
|
||||||
|
|
||||||
|
Restart preserves originals/jobs/ready documents and recorded decisions.
|
||||||
|
Interrupted jobs recover under fresh claims without duplicate publication.
|
||||||
|
Old API-owned media sessions/running tools become terminal and unusable;
|
||||||
|
users start fresh. Current-session transcript may be lost on page refresh;
|
||||||
|
durable full voice history and raw recording are deferred.
|
||||||
|
|
||||||
|
## 12. Evaluation and handoff
|
||||||
|
|
||||||
|
Map checks to MVP-01 through MVP-14. Independently annotate expected source
|
||||||
|
passages; do not use an indexed FAQ as the sole proof of its own retrieval.
|
||||||
|
Evaluate retrieval, answer support and spoken quality separately with roughly
|
||||||
|
15-20 initial questions and unseen-file questions.
|
||||||
|
|
||||||
|
Rehearse browser upload -> review if needed -> ready -> activate -> real Persian
|
||||||
|
voice -> shared retrieval -> spoken answer/sources on target HTTPS/network.
|
||||||
|
Record actual errors/latency/provider usage and limits, not invented accuracy
|
||||||
|
percentages or unexecuted acceptance claims.
|
||||||
+82
-23
@@ -1,6 +1,8 @@
|
|||||||
|
> Historical Persian report (revision 1.2). For the current English Live document MVP baseline and scenarios, use [Live Document MVP Scenarios](RAG-Phase1-MVP-Scenarios.md) and delivery/API/database revision 1.3. Older text/history/settings delivery requirements below do not govern this milestone. The historical body is preserved unchanged.
|
||||||
|
|
||||||
# گزارش فاز یک دستیار اسناد سازمان — پیادهسازی، API و دیتابیس با سناریو
|
# گزارش فاز یک دستیار اسناد سازمان — پیادهسازی، API و دیتابیس با سناریو
|
||||||
|
|
||||||
نسخه ۱.۱ — تاریخ ۲۰۲۶/۱۰/۰۵
|
نسخه ۱.۲ — تاریخ ۲۰۲۶/۱۰/۰۶
|
||||||
|
|
||||||
این گزارش طراحی پیشنهادی پیادهسازی است؛ به معنی ساختهشدن برنامه، اجرای مایگریشن یا موفقیت تستها نیست. بازه تحویل همان ۷ تا ۱۰ روز و فرض ظرفیت، یک توسعهدهنده اصلی است.
|
این گزارش طراحی پیشنهادی پیادهسازی است؛ به معنی ساختهشدن برنامه، اجرای مایگریشن یا موفقیت تستها نیست. بازه تحویل همان ۷ تا ۱۰ روز و فرض ظرفیت، یک توسعهدهنده اصلی است.
|
||||||
|
|
||||||
@@ -21,7 +23,7 @@
|
|||||||
|
|
||||||
مدیر وارد سامانه میشود، سند سازمان را آپلود میکند، آمادهشدن آن را میبیند و فعالش میکند. کاربر از طریق متن یا صوت سؤال میپرسد. مدل تصمیم میگیرد ابزار سرچ را اجرا کند؛ بکاند شواهد را از اسناد فعال پیدا میکند و مدل بر اساس آن پاسخ میدهد.
|
مدیر وارد سامانه میشود، سند سازمان را آپلود میکند، آمادهشدن آن را میبیند و فعالش میکند. کاربر از طریق متن یا صوت سؤال میپرسد. مدل تصمیم میگیرد ابزار سرچ را اجرا کند؛ بکاند شواهد را از اسناد فعال پیدا میکند و مدل بر اساس آن پاسخ میدهد.
|
||||||
|
|
||||||
چهار صفحه داریم: ورود، گفتگو، اسناد و تنظیمات. در تنظیمات فقط نام و دستورالعمل دستیار تغییر میکند. انتخاب اسناد در صفحه اسناد است. مدلها از تنظیمات سرور تعیین میشوند. مدیریت مدل، نسخهبندی خودکار سند، OCR عمومی، SSO، ثبتنام و تاریخچه کامل صوتی به این تحویل اضافه نشدهاند.
|
چهار صفحه داریم: ورود، گفتگو، اسناد و تنظیمات. در تنظیمات فقط نام و دستورالعمل دستیار تغییر میکند. انتخاب اسناد در صفحه اسناد است. مدلها از تنظیمات سرور تعیین میشوند. مدیریت مدل، نسخهبندی خودکار سند، SSO، ثبتنام و تاریخچه ماندگار کامل صوتی خارج از این تحویلاند. استخراج تصویر، fallback صفحه PDF و جدولهای DOCX نمونه در محدوده MVP هستند؛ OCR عمومی همه فرمتها الزام نیست.
|
||||||
|
|
||||||
تصمیم سادهسازی: جدول نسخهها حذف شده است. هر آپلود یک سند مستقل میسازد؛ قطعات و کار پردازش مستقیم به آن متصلاند. برای اصلاح محتوا، فایل جدید آپلود و پس از آمادهشدن جای سند فعال قبلی انتخاب میشود. Retry همان سند را دوباره پردازش میکند و سند تازه نمیسازد. تعداد جدولها اکنون ۱۴ است.
|
تصمیم سادهسازی: جدول نسخهها حذف شده است. هر آپلود یک سند مستقل میسازد؛ قطعات و کار پردازش مستقیم به آن متصلاند. برای اصلاح محتوا، فایل جدید آپلود و پس از آمادهشدن جای سند فعال قبلی انتخاب میشود. Retry همان سند را دوباره پردازش میکند و سند تازه نمیسازد. تعداد جدولها اکنون ۱۴ است.
|
||||||
|
|
||||||
@@ -58,7 +60,7 @@
|
|||||||
|
|
||||||
سند آماده ولی غیرفعال قابل سرچ نیست. این دو وضعیت مستقلاند: یکی میگوید پردازش انجام شده، دیگری میگوید سازمان اجازه استفاده داده است.
|
سند آماده ولی غیرفعال قابل سرچ نیست. این دو وضعیت مستقلاند: یکی میگوید پردازش انجام شده، دیگری میگوید سازمان اجازه استفاده داده است.
|
||||||
|
|
||||||
اگر فایل تصویر اسکنشده باشد و OCR در فرمتهای تأییدشده نباشد، وضعیت failed با توضیح قابل فهم نمایش داده میشود. سند خالی به عنوان «آماده» ثبت نمیشود.
|
در MVP جدید تصویر و صفحه اسکنشده نمونه با vision/OCR پردازش میشوند. اگر خروجی ناخوانا، ناقص یا از نظر عدد/استثنا غیرقابل اعتماد باشد، failed با دلیل روشن نمایش داده میشود؛ متن خالی یا غیرقابل اعتماد ready نمیشود.
|
||||||
|
|
||||||
## ۵. سناریو دوم: کاربر متنی سؤال میپرسد
|
## ۵. سناریو دوم: کاربر متنی سؤال میپرسد
|
||||||
|
|
||||||
@@ -67,7 +69,7 @@
|
|||||||
۱. فرانت با `POST /conversations` یک گفتگوی text میسازد.
|
۱. فرانت با `POST /conversations` یک گفتگوی text میسازد.
|
||||||
۲. سؤال را همراه `conversation_id` و `client_request_id` به `POST /chat` میدهد.
|
۲. سؤال را همراه `conversation_id` و `client_request_id` به `POST /chat` میدهد.
|
||||||
۳. بکاند یک `turn` به معنی «یک نوبت سؤال و پاسخ» ثبت میکند. سؤال کاربر در `messages` ذخیره میشود.
|
۳. بکاند یک `turn` به معنی «یک نوبت سؤال و پاسخ» ثبت میکند. سؤال کاربر در `messages` ذخیره میشود.
|
||||||
۴. مدل میبیند برای پاسخ به اطلاعات سازمان نیاز دارد و ابزار `search_documents` را با کوئری «ساعت کاری پنجشنبه» صدا میزند.
|
۴. مدل میبیند برای پاسخ به اطلاعات سازمان نیاز دارد و ابزار `search_knowledge` را با کوئری «ساعت کاری پنجشنبه» صدا میزند.
|
||||||
۵. ابزار هویت سازمان را از نشست معتبر میگیرد؛ خود مدل نمیتواند سازمان یا اسناد مجاز را عوض کند.
|
۵. ابزار هویت سازمان را از نشست معتبر میگیرد؛ خود مدل نمیتواند سازمان یا اسناد مجاز را عوض کند.
|
||||||
۶. سؤال به بردار تبدیل میشود و قطعات مرتبط از اسناد آماده و فعال پیدا میشوند.
|
۶. سؤال به بردار تبدیل میشود و قطعات مرتبط از اسناد آماده و فعال پیدا میشوند.
|
||||||
۷. متن قطعه، شناسه سند و قطعه و محل منبع به مدل برمیگردد.
|
۷. متن قطعه، شناسه سند و قطعه و محل منبع به مدل برمیگردد.
|
||||||
@@ -128,21 +130,18 @@ sequenceDiagram
|
|||||||
|
|
||||||
## ۸. سناریو پنجم: کاربر صوتی سؤال میپرسد
|
## ۸. سناریو پنجم: کاربر صوتی سؤال میپرسد
|
||||||
|
|
||||||
۱. کاربر دکمه شروع مکالمه را میزند و دسترسی میکروفون میدهد.
|
۱. کاربر دسترسی میکروفون میدهد و گفتگوی voice متعلق به خودش ایجاد میکند.
|
||||||
۲. یک گفتگوی voice ساخته میشود.
|
۲. `POST /api/v1/voice/sessions` شناسه جلسه و مسیر WSS برنامه را میدهد؛ قرارداد SDP قبلی برای MVP جدید کنار گذاشته شده است.
|
||||||
۳. مرورگر اطلاعات برقراری WebRTC را به `POST /voice/sessions` میدهد.
|
۳. بکاند با کلید سروری به Gemini Live مستقیم وصل میشود و دستور فارسی، ابزار `search_knowledge` و transcription قابل پشتیبانی را تنظیم میکند.
|
||||||
۴. بکاند جلسه مدل Live و کانال کنترل معتبر را آماده میکند.
|
۴. صوت کاربر از مرورگر به بکاند و سپس جلسه Gemini میرود.
|
||||||
۵. پاسخ اتصال به مرورگر میرسد؛ صوت مستقیم میان مرورگر و ارائهدهنده منتقل میشود.
|
۵. برای سؤال وابسته به سند، مدل ابزار را فراخوانی میکند؛ بکاند با هویت و محدوده خودش همان سرچ مشترک متن را اجرا میکند.
|
||||||
۶. کاربر میگوید: «پنجشنبه تا چند باز هستید؟»
|
۶. قطعات واقعی و محل منبع به مدل میرسند؛ مدل میتواند بدون فراخوانی جداگانه مدل متنی پاسخ فارسی صوتی بسازد.
|
||||||
۷. مدل Live ابزار سرچ را درخواست میکند؛ بکاند همان سرویس سرچ متن را اجرا میکند.
|
۷. UI صوت، متن پاسخ موجود و منابع را نشان میدهد. منبع بازیابیشده لزوماً استناد دقیق جمله صوتی نیست.
|
||||||
۸. شواهد به مدل Live میرسند و مدل پاسخ صوتی میدهد.
|
۸. وقفه کاربر پخش صفشده را متوقف میکند؛ نتیجه دیررس ابزار نوبت لغوشده پاسخ تازه نمیسازد.
|
||||||
۹. UI از وضعیت جلسه و نتایج اخیر ابزار، منابع بازیابیشده را نشان میدهد.
|
|
||||||
|
|
||||||
**صوت از API ما عبور نمیکند؛ ولی جستوجو و کنترل دسترسی از بکاند میگذرد.** هیچ کلید دائمی ارائهدهنده در مرورگر قرار نمیگیرد.
|
**بکاند جلسه و انتقال صوت را مدیریت میکند و کلید دائمی در مرورگر نیست.** نام رویدادها و مسیر WSS در کاتالوگ، پیشنهاد فنیاند و هنوز پیادهسازی نشدهاند. OpenRouter برای مقایسه متن/vision است؛ دریافت فایل صوتی یا خروجی صوتی stream به معنی پشتیبانی جلسه دوطرفه Gemini Live نیست.
|
||||||
|
|
||||||
جزئیات SDP در کاتالوگ یک قرارداد پیشنهادی است. روز اول باید با ارائهدهنده منتخب واقعاً تست شود؛ حمایت از WebRTC و کنترل معتبر ابزار برای همه ارائهدهندگان فرض نشده است.
|
در قطعی، UI وضعیت را نشان میدهد؛ جلسه قدیمی تعیین تکلیف و جلسه جدید ساخته میشود. بازیابی بیوقفه زمینه و تاریخچه ماندگار کامل صوتی خارج از فاز یکاند. متن موجود در همان جلسه نگه داشته میشود؛ متن ناموجود یا ناقص صریحاً مشخص است و به جای گفتار واقعی جعل نمیشود. تلفظ و فهم فارسی، اسمهای محلی، تاریخ، درصد و مبلغ باید با صوت واقعی بررسی شود.
|
||||||
|
|
||||||
در فاز یک تاریخچه کامل صوتی و ادامه بیوقفه جلسه پس از قطعی نداریم. اگر اتصال قطع شود، UI اعلام میکند و کاربر جلسه جدید میسازد. منابع نمایشدادهشده در صوت «منابع بازیابیشده» هستند؛ ادعا نمیکنیم تکتک آنها دقیقاً در جمله صوتی استفاده شدهاند.
|
|
||||||
|
|
||||||
## ۹. سناریو ششم: سازمان سند ساعات کاری را عوض میکند
|
## ۹. سناریو ششم: سازمان سند ساعات کاری را عوض میکند
|
||||||
|
|
||||||
@@ -212,12 +211,12 @@ Worker فایل را گرفته و مشغول Embedding است. فرایند ق
|
|||||||
|
|
||||||
| بازه | چیزی که باید بتوانیم نشان دهیم |
|
| بازه | چیزی که باید بتوانیم نشان دهیم |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| روز ۱ | صوت واقعی و اجرای ابزار در بکاند؛ فرمت فایل و مدلها مشخص |
|
| روز ۱ | بررسی نمونهها، کیفیت استخراج، اعتبار حساب و شبکه و پروفایلهای مدل |
|
||||||
| روز ۲ | ورود و آپلود ماندگار |
|
| روز ۲ | ورود و آپلود ماندگار |
|
||||||
| روز ۳ | تبدیل فایل به سند ready و خطای قابل فهم برای فایل نامعتبر |
|
| روز ۳ | استخراج/QC و ایندکس متن، تصویر و جدول نمونه؛ خطای روشن برای خروجی غیرقابل اعتماد |
|
||||||
| روز ۴ | سرچ فقط روی اسناد فعال با منبع درست |
|
| روز ۴ | سرچ فقط روی اسناد فعال با منبع درست |
|
||||||
| روز ۵ | چت متنی و بازیابی وضعیت درخواست پس از timeout |
|
| روز ۵ | پاسخ مستند متنی و بازیابی نوبت؛ سپس صوت مستقل Gemini Live و متن پاسخ |
|
||||||
| روز ۶ | سؤال صوتی و سرچ واقعی در همان دانش |
|
| روز ۶ | اتصال ابزار دانش به Live، follow-up، تغییر موضوع و وقفه فارسی |
|
||||||
| روز ۷ | چهار صفحه و دموی کامل روی HTTPS |
|
| روز ۷ | چهار صفحه و دموی کامل روی HTTPS |
|
||||||
| روز ۸ تا ۱۰ | اصلاح کیفیت، تست شکستها، آمادهسازی نسخه ارائه |
|
| روز ۸ تا ۱۰ | اصلاح کیفیت، تست شکستها، آمادهسازی نسخه ارائه |
|
||||||
|
|
||||||
@@ -231,7 +230,7 @@ Worker فایل را گرفته و مشغول Embedding است. فرایند ق
|
|||||||
- سؤال بیپاسخ با اطلاعات ساختگی جواب داده نشود.
|
- سؤال بیپاسخ با اطلاعات ساختگی جواب داده نشود.
|
||||||
- ارسال تکراری، نوبت یا کار پردازشی تکراری نسازد.
|
- ارسال تکراری، نوبت یا کار پردازشی تکراری نسازد.
|
||||||
- قطع Worker باعث از دست رفتن کار پذیرفتهشده نشود.
|
- قطع Worker باعث از دست رفتن کار پذیرفتهشده نشود.
|
||||||
- مکالمه صوتی واقعاً از WebRTC و ابزار بکاند استفاده کند.
|
- مکالمه صوتی فارسی واقعاً از Gemini Live مستقیم، WSS مدیریتشده بکاند و بازیابی سند استفاده کند؛ متن پاسخ موجود و منابع در UI دیده شوند.
|
||||||
- خروج کاربر، پایان جلسه یا تغییر منابع فعال، وضعیت Live را درست تغییر دهد.
|
- خروج کاربر، پایان جلسه یا تغییر منابع فعال، وضعیت Live را درست تغییر دهد.
|
||||||
- تاریخچه متن بعد از restart باقی بماند.
|
- تاریخچه متن بعد از restart باقی بماند.
|
||||||
- دمو روی شبکه و مرورگر محیط ارائه تمرین شده باشد.
|
- دمو روی شبکه و مرورگر محیط ارائه تمرین شده باشد.
|
||||||
@@ -253,4 +252,64 @@ Worker فایل را گرفته و مشغول Embedding است. فرایند ق
|
|||||||
|
|
||||||
ابتدا Implementation Guide برای ترتیب کار و مرز ماژولها؛ سپس API Catalog برای DTO و هماهنگی فرانت؛ بعد Database Design برای مدلهای ORM و مایگریشن. سناریوهای این گزارش باید تبدیل به تستهای یکپارچه شوند.
|
ابتدا Implementation Guide برای ترتیب کار و مرز ماژولها؛ سپس API Catalog برای DTO و هماهنگی فرانت؛ بعد Database Design برای مدلهای ORM و مایگریشن. سناریوهای این گزارش باید تبدیل به تستهای یکپارچه شوند.
|
||||||
|
|
||||||
قراردادها در این مجموعه با هم هماهنگ شدهاند، اما هنوز تصمیمهای روز اول بازند. پس از تأیید فرمت و مدل و اتصال Live، همین اسناد نسخه جدید میگیرند. افزودن قابلیت محصول کامل به کارهای این فاز باید با تغییر صریح محدوده یا زمانبندی انجام شود.
|
قراردادها با جهت MVP جدید هماهنگ شدهاند؛ Gemini Live مستقیم و استخراج تصویر/جدول نمونه تصمیم محدودهاند، اما مدل دقیق، حساب واجد شرایط، بودجه Embedding و کیفیت واقعی هنوز باید بررسی شوند. پس از تأیید فرمت و مدل و اتصال Live، همین اسناد نسخه جدید میگیرند. افزودن قابلیت محصول کامل به کارهای این فاز باید با تغییر صریح محدوده یا زمانبندی انجام شود.
|
||||||
|
|
||||||
|
## ۱۸. فایلهای نمونه و حدود بررسی محلی — ۲۰۲۶/۱۰/۰۶
|
||||||
|
|
||||||
|
هر چهار فایل در `data/documents/` موجود است. بررسی این نوبت بدون نصب وابستگی و بدون ارسال فایل به ارائهدهنده انجام شد:
|
||||||
|
|
||||||
|
| فایل | بررسی انجامشده و زمینه تأمینشده |
|
||||||
|
| --- | --- |
|
||||||
|
| `7364346504113364738_13450847753183.pdf` | بررسی ساختار خام PDF: پنج شیء صفحه و ارجاع فونت/ToUnicode. طبق مشاهده اولیه تأمینشده توسط کاربر، متن دارد ولی ترتیب واژه/عدد گاهی خراب است |
|
||||||
|
| `5905170444656189186_13450510740952.pdf` | بررسی ساختار خام: یک صفحه و ارجاع فونت/ToUnicode. طبق زمینه کاربر، بخشنامه دارای تاریخ، درصد، شرط و استثنا است |
|
||||||
|
| `photo_1_2026-10-06_09-05-11.jpg` | تصویر محلی دیده شد: گروه اصلی سمت راست، گروه سمت چپ و گروه پایین؛ عنوانها و توضیحها باید با گروه خود نگه داشته شوند |
|
||||||
|
| `-2348240626507047168_13449360743721.docx` | XML داخل DOCX خوانده شد: دو جدول و ۲۰۰ ردیف. در ردیفهای بررسیشده سؤال و جواب عمدتاً پشت سر هماند؛ جاینگهدار قیمت/تعرفه و سناریوی رفتاری هم وجود دارد |
|
||||||
|
|
||||||
|
ابزار استخراج/رندر PDF در محیط محلی این نوبت موجود نبود؛ بررسی متن و چیدمان کامل PDF انجام نشد. نتیجه استخراج اولیه کاربر با این بررسی ساختاری یکی نیست. هیچ Gemini، Mistral یا OCR محلی روی این فایلها آزمایش نشده و هیچ برنده benchmark معرفی نشده است.
|
||||||
|
|
||||||
|
## ۱۹. مثال عملی: اینفوگرافیک از تصویر به دانش قابل بازیابی
|
||||||
|
|
||||||
|
این مثال جریان پیشنهادی است، نه خروجی OCR اجراشده. در تصویر، گروه سمت راست با عنوان «هوشمندسازی و ارتقای بهرهوری» دیده میشود و زیرعنوان «استقرار دولت هوشمند و دادهمحور» در همان گروه است. این دو عنوان از مشاهده تصویر آمدهاند؛ متن کامل توضیح عمداً اینجا ساخته نمیشود.
|
||||||
|
|
||||||
|
۱. تصویر به عنوان سند مستقل آپلود و اصل آن حفظ میشود.
|
||||||
|
۲. Flash vision با دستور رونویسی کامل، بلوکهای هر گروه را جدا میکند: عنوان والد، زیرعنوان، توضیح مربوط، محل بصری و هشدار ناخوانایی.
|
||||||
|
۳. بازبین، ارتباط گروه راست، چپ و پایین و نبود بلوک تکراری/افتاده را با تصویر مقایسه میکند. توضیح یک ستون به عنوان ستون دیگر چسبانده نمیشود.
|
||||||
|
۴. برای هر موضوع، عنوان والد و زیرعنوان همراه توضیح همان موضوع قطعه میشوند. محل پیشنهادی `page=null, section=image/group-right/item-1` است، نه شماره صفحه ساختگی.
|
||||||
|
۵. متن وفادار و متن جستوجوی نرمالشده نگه داشته میشوند؛ همان Embedding و index متن استفاده میشود.
|
||||||
|
۶. سؤال نمونه «در این نمودار، بخش دولت هوشمند چه توضیحی دارد؟» باید بلوک مربوط را برگرداند؛ پاسخ فقط از توضیح تأییدشده ساخته شود. اگر ریزنوشته خوانا نیست، محدودیت اعلام و از نمای واضحتر/بازبینی استفاده شود.
|
||||||
|
|
||||||
|
## ۲۰. مثال عملی: بازیابی بخشنامه و سؤال بعدی صوتی
|
||||||
|
|
||||||
|
این مثال سؤال و روند بازیابی است؛ هیچ عدد یا نقلقول استخراجنشده از PDF اختراع نشده است.
|
||||||
|
|
||||||
|
۱. بخشنامه تکصفحهای با استخراج مستقیم شروع میشود. بازبین تاریخ، درصد، شرطها و استثناها را با اصل صفحه کنترل میکند. اگر عدد وارونه یا ترتیب خراب باشد، همان صفحه رندر و با vision/OCR رونویسی میشود.
|
||||||
|
۲. تصمیم، شرایط و موارد مستثنا با هم قطعه میشوند؛ محل منبع صفحه ۱ و عنوان/بند واقعی است. برای مقررات پنجصفحهای نیز ماده، تبصره و یادداشت مرتبط کنار هم میمانند.
|
||||||
|
۳. کاربر میپرسد: «در این بخشنامه، شرایط اعمال درصد اعلامشده چیست؟» اگر چند بخشنامه فعال باشد، مدل ابتدا مشخص میکند کدام.
|
||||||
|
۴. `search_knowledge` سؤال متمرکز را با زمینه مجاز میگیرد؛ سرچ معنایی و تطبیق دقیق شناسه/ماده/تاریخ، قطعه واجد شرط و استثنا را برمیگردانند.
|
||||||
|
۵. مدل درصد یا تاریخ را فقط از متن بررسیشده میخواند؛ شواهد ناسازگار را پنهانی حل نمیکند. UI عنوان، صفحه و محل واقعی را نشان میدهد.
|
||||||
|
|
||||||
|
نمونه follow-up صوتی: «استثناهاش چی بود؟» مدل مرجع را به همان بخشنامه مشخصشده حل و دوباره شواهد استثنا را بازیابی میکند؛ جمله کوتاه فارسی با استثناهای واقعی میسازد. سپس «حالا درباره دولت هوشمند در اینفوگرافیک بگو» موضوع را عوض میکند؛ ماده/تاریخ بخشنامه به سؤال جدید تحمیل نمیشود. عبارت مبهم «ماده بعدی چی؟» بدون ماده/سند مشخص، سؤال روشنکننده میگیرد.
|
||||||
|
|
||||||
|
اگر کاربر وسط پاسخ بگوید «صبر کن، فقط استثناها»، پخش باقیمانده متوقف و نتیجه ابزار لغوشده کنار گذاشته میشود؛ نوبت جدید با محدودیت تازه بازیابی میکند.
|
||||||
|
|
||||||
|
## ۲۱. بانک سؤالوجواب: دانش، رفتار و داده جاری
|
||||||
|
|
||||||
|
| نوع محتوا | استفاده مجاز پیشنهادی |
|
||||||
|
| --- | --- |
|
||||||
|
| واقعیت تأییدشده سازمان، با اعتبار و محل منبع | پس از تأیید صاحب دانش برای retrieval |
|
||||||
|
| انتظار رفتاری، مانند حفظ زمینه یا نحوه پاسخ به وقفه | سناریوی evaluation یا تنظیم صریح بازبینیشده؛ دستور داخل سند سیاست سیستم را عوض نمیکند |
|
||||||
|
| `[قیمت روز]`، `[تعرفه جاری]`، سؤال بدون مقدار معتبر | شواهد پاسخ factual نیست؛ نیاز به داده/ابزار جاری تأییدشده یا اعلام محدودیت |
|
||||||
|
|
||||||
|
بانک DOCX خودبهخود مرجع رسمی همه پاسخها نیست. قیمت جاری، موجودی زمین، مانده حساب و وضعیت پرونده با RAG ایستا قابل تأیید نیستند. ابزار سازمانی برخط در این فاز تعریف نشده؛ دستیار محدودیت را اعلام و مسیر مراجعه مجاز سازمان را پیشنهاد میکند، نه اینکه اتصال/انتقال خودکار ساختهنشده را وعده دهد.
|
||||||
|
|
||||||
|
نمونه کمبود شواهد، متن پاسخ پیشنهادی: «در اسناد فعال، مقدار معتبر تعرفه جاری را پیدا نکردم؛ برای عدد امروز باید منبع رسمی بهروز بررسی شود.» جاینگهدار به عنوان مقدار خوانده نمیشود.
|
||||||
|
|
||||||
|
نمونه شکست ارائهدهنده، متن پاسخ پیشنهادی: «جستوجوی اسناد فعلاً با خطای اتصال روبهرو شد. لطفاً دوباره تلاش کنید.» UI خطای فنی را نشان میدهد؛ نمیگوید «چنین سندی وجود ندارد». اگر خود Live قطع باشد، همین پیام در UI نمایش داده میشود و پاسخ صوتی از ارائهدهنده قطعشده فرض نمیشود.
|
||||||
|
|
||||||
|
## ۲۲. پذیرش و بودجه MVP جدید
|
||||||
|
|
||||||
|
ترتیب عملی: استخراج/کنترل کیفیت/ایندکس نمونهها؛ retrieval و پاسخ مستند متنی؛ صوت مستقل Live؛ اتصال ابزار دانش؛ بررسی فارسی، follow-up، تغییر موضوع و وقفه؛ تمرین کامل روی شبکه و تجهیزات ارائه. بودجه پیشنهادی: ۱۰ دلار Gemini، ۱۰ دلار OpenRouter و ۱۰ دلار ذخیره اختیاری؛ خرج اولیه ۲۰ و بودجه قابل برنامهریزی ۳۰ دلار. حدود ۵ دلار Gemini برای تمرین نهایی/ارائه نگه داشته شود. این تضمین هزینه کل نیست؛ نرخ رسمی، حساب، سقف واقعی و هزینه جداگانه Embedding باید بررسی شوند.
|
||||||
|
|
||||||
|
معیارهای P1-01 تا P1-12 حفظ و P1-13 تا P1-17 در [برنامه تحویل](RAG-AI-Phase1-Delivery-Plan.md) اضافه شدهاند: متن و تصویر، حفظ رابطه عنوانها، عدد/استثنا، صوت فارسی مستند، منبع قابل مشاهده، زمینه/تغییر موضوع، نبود جعل و خطای قابل فهم. evaluation بازیابی با محلهای مستقل علامتگذاریشده انجام میشود؛ کیفیت تولید و صوت جدا ثبت میشود. یک FAQ ایندکسشده تنها شاهد موفقیت خودش نیست.
|
||||||
|
|
||||||
|
تصمیم قطعی محصول با پیشنهاد DTO/مخزن استخراج و شواهد کد فعلی متفاوت است. کد فعلی شامل prototype Markdown/Chroma و foundation/intake است؛ worker، retrieval آپلودها، احراز هویت HTTP و Live هنوز ساخته نشدهاند. این ویرایش مستندات به معنی MVP عملیاتی نیست. اعتبار حساب/شبکه، مدل و بودجه Embedding و تأیید دانش/اعداد، دروازههای وابسته را مسدود میکنند تا واقعاً بررسی شوند.
|
||||||
Reference in New Issue
Block a user