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:
amirhosein mazaheri
2026-10-07 16:19:24 +03:30
parent baf58da562
commit ca8833dd2f
30 changed files with 6121 additions and 2768 deletions
+49
View File
@@ -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.
@@ -0,0 +1,193 @@
# Prompt: Create Repository Skills for the Phase 1 RAG Assistant
Paste the following prompt into the coding agent with the project repository open. Make the six current project documents available in the repository first; their exact directory is discovered by the agent. This prompt creates development skills, not application features.
---
You are working inside my Organization Knowledge Assistant repository. Create three practical, repository-scoped development skills:
1. `implement-feature`
2. `write-tests`
3. `review-change`
Integrate relevant real-provider RAG evaluation into `write-tests`; do not create a separate `verify-rag-flow` skill.
Implement the skill files and necessary references now. Do not stop at a proposal or print hypothetical file contents. Do not implement product features while creating these skills.
## 1. Inspect the repository and agent environment
Before writing:
- Locate the repository root and inspect Git status. Preserve unrelated modifications.
- Read applicable root and nested `AGENTS.md` files and any existing skill-authoring instructions.
- Inspect the agent's actual supported repository skill location and existing skill conventions. Use that supported location; do not assume a directory merely because it appears in an example. If no project skill discovery mechanism is available, create reusable skill documents in a clearly identified repository directory and report that automatic discovery is unverified. Do not claim installation without evidence.
- Inspect existing skills by frontmatter name. Update equivalent project-owned skills rather than creating duplicate names. Do not modify system, plugin or globally installed skills.
- Inspect the application tree, dependency manifests, test configuration, CI and existing commands. Do not prescribe a new framework or test runner when suitable conventions already exist.
- Prefer `rg` and `rg --files` for discovery.
Do not hardcode paths from another machine, ChatGPT scratch directories, Library IDs or inaccessible sandbox links.
## 2. Resolve the actual project references
Find these exact filenames, wherever they are located in the repository:
| Document | Purpose |
| --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | Phase 1 scope, delivery sequence and acceptance criteria |
| `RAG-Phase1-Implementation-Guide.md` | Modules, responsibilities, workflows and implementation boundaries |
| `RAG-Phase1-API-Catalog.md` | Routes, DTOs, permissions, errors, retry and idempotency contracts |
| `RAG-Phase1-Database-Design.md` | Current schema, constraints, transactions and migration approach |
| `RAG-Phase1-Scenario-Report-FA.md` | Business scenarios and Persian explanations |
| `RAG-AI-Architecture.md` | Wider architecture and future direction |
Read enough of each to verify it is the current simplified design. The current design has independent uploaded documents and no document-content versioning. Do not select an obsolete document just because its filename matches. Resolve duplicates using content, repository context and document status; ask a focused question only when competing authoritative copies cannot be distinguished.
Create or update one small shared reference index in the repository's existing documentation area. If there is no convention, use `docs/development/agent-reference-map.md`. Record:
- The actual relative path to each document and what it governs.
- Which sections each skill should consult, preferably with verified heading anchors or heading names.
- Actual relevant source/test directories and verified development commands.
- Any missing references or unresolved contradictions, explicitly labelled.
Do not copy whole documents into the skills. Do not fabricate missing contents, executable commands, schema fields or approval decisions. If a required document is missing, continue building the available skill structure; label the relevant workflow blocked on that reference and report exactly what is missing. Do not leave a broken link disguised as an existing reference.
Every skill must link directly to this reference index using a valid relative link from its own `SKILL.md`. Within the index, resolve links relative to the index file. Verify every path and any heading anchor you create. Avoid machine-specific absolute paths and symlinks outside the repository.
Reference authority:
- Follow governing instructions and the user's explicit current task.
- Use the Phase 1 plan for scope; API and database documents for their contracts; implementation guide for workflows.
- Treat the broader architecture as context, not permission to implement deferred features.
- Treat existing code as implementation evidence, not automatic proof that conflicting behavior is correct.
- Surface material contradictions; do not silently rewrite policy or expand scope. Continue unrelated work when a decision blocks only one part.
## 3. Keep shared project rules in AGENTS.md
Preserve existing instructions. Add a concise section only where the rules belong; avoid duplicating nested instructions. Include these current invariants:
- Deliver within Phase 1 scope using the existing modular backend and separate ingestion worker.
- Each upload creates an independent document; content is not overwritten in place.
- Do not introduce `document_versions`, `version_id` or `version_no` for document content.
- Chunks and ingestion jobs reference `document_id`; answer sources reference `document_id` and `chunk_id`.
- Retry processes the same eligible failed document; it does not create a new document identity.
- Only authorized, ready, active and undeleted documents are searchable.
- The backend derives trusted identity and search scope. Model arguments cannot override them.
- Text and Live use the same backend search implementation.
- Keep persistent provider secrets server-side.
- Follow documented request deduplication, worker claim/lease rules and context invalidation behavior where relevant.
- Keep API/schema documentation aligned with intentional contract changes. Never alter contracts just to excuse a bug.
- Avoid unnecessary dependencies, services, abstractions and unrelated refactoring.
Configuration revisions and embedding profile metadata are not document-content versioning and must not be removed accidentally.
Link to the shared reference map instead of embedding all requirements into AGENTS.md. Add verified project commands only; label commands not yet runnable rather than guessing that they work.
## 4. Skill structure and authoring requirements
For each skill create a `SKILL.md` with valid YAML frontmatter:
- `name`: exactly the requested skill name.
- `description`: concise purpose and specific triggering situations, including when not to use it if needed to prevent over-triggering.
Follow the actual agent's supported metadata schema. Add UI metadata only if supported and useful; validate it using the available authoring guidance. Never invent metadata keys.
Keep each skill procedural, specific and concise; aim for approximately 100–200 lines or less. Include relevant references, the workflow, verification requirements, stopping conditions and an output format. Do not add filler README files, duplicate manuals, unused resources or scripts that only wrap a single ordinary command.
Skills must not recursively invoke one another in a loop. Implementation includes its necessary validation; test-writing develops tests; review is read-only unless fixing is explicitly requested.
### Skill A: implement-feature
Trigger: implement or modify a scoped application capability in this repository.
Workflow:
1. Identify requested behavior, acceptance criteria and relevant references.
2. Inspect the existing implementation, test patterns and affected integration boundaries.
3. State a short implementation plan proportional to the task. Continue without routine permission requests.
4. Implement the smallest complete change across the necessary API, application, persistence/provider and UI boundaries. Do not force edits into layers the task does not affect.
5. Handle relevant permissions, state transitions, errors and concurrency/idempotency requirements.
6. Preserve provider-neutral application boundaries and shared retrieval.
7. Add meaningful tests for changed behavior and regressions. Reuse existing fixtures.
8. Run relevant checks using repository commands; update affected docs for intentional contract changes.
9. Report changed behavior, files, actual checks and remaining limitations.
If the task explicitly changes a contract, update its documentation and consumers coherently. If a product decision is genuinely missing, isolate it and request that decision without inventing it. Do not ask for permission for ordinary reversible implementation choices.
### Skill B: write-tests
Trigger: create, extend or improve tests for an identified behavior, regression or release risk.
Workflow:
1. Read the intended behavior and existing tests before choosing assertions.
2. Select the smallest useful test level: unit, integration, contract or end-to-end.
3. Cover relevant success, failure and boundary cases; avoid mechanically enumerating irrelevant combinations.
4. Use the repository's runner, fixtures and naming conventions.
5. Mock external providers at the adapter/transport boundary where appropriate. Do not mock the behavior under test or treat a fake database as proof of PostgreSQL constraints.
6. Use an isolated PostgreSQL/pgvector test environment when testing database-specific transactions, vector queries or constraints; never run destructive fixtures against production.
7. Keep ordinary automated tests deterministic and network-free by default. Control clocks and retries through injected dependencies where the code supports them.
8. Run the targeted tests and explain failures. Do not weaken assertions, skip regressions or change expected behavior merely to make the suite pass.
9. Distinguish a product bug, a test defect and an unavailable environment. Report an exposed product bug without silently expanding a tests-only task into a production fix.
Choose relevant cases from:
- Authorized upload, invalid files, failed extraction and no publication of partial chunks.
- Duplicate upload/chat request replay and changed-payload conflicts.
- Active/ready/deleted filtering and forged scope arguments.
- Worker lease expiry, stale claim rejection and duplicate-free publication.
- Turn state, conversation ownership, interruption and source mapping.
- Document deactivation and stale context handling.
- Live tool dispatch using shared retrieval, duplicate tool events and close/failure state.
Add a clearly separate optional section: **Real-provider RAG evaluation**.
Use it when real-output quality is requested or release readiness requires it and the environment/data access is authorized. Prepare a small corpus and questions with expected evidence, including paraphrases, missing knowledge and follow-ups. Check extraction, retrieved evidence, answer support and source identity separately. Test text and voice separately. Prefer factual assertions over exact full-answer wording. Label any model-based judging and human checks; do not present them as deterministic proof.
Use bounded requests, protect sensitive data and honor existing cost/network authorization. If credentials, corpus, a runnable service or required voice interaction are unavailable, report the evaluation as not run. Never fabricate metrics or claim mock results establish real-model quality. Keep this optional evaluation out of the default unit-test run.
### Skill C: review-change
Trigger: review a diff, implementation or proposed merge for defects and contract violations.
Workflow:
1. Resolve the requested review scope and base. Inspect the diff and relevant surrounding code/tests/docs.
2. Check correctness, authorization, contract alignment, data integrity, failure behavior and relevant concurrency/retry issues.
3. Pay particular attention to inactive-document leaks, stale context, duplicate provider work, invalid citations and application/provider boundary mistakes where those areas changed.
4. Use targeted read-only inspection or checks to validate suspected findings. Do not execute production writes.
5. Prioritize actionable defects over stylistic preferences; avoid speculative findings without a concrete failure path.
6. Report each finding with severity, actual file and location, trigger, impact and recommended correction direction.
7. If no defects are found, say so with the review scope and untested risks. Do not invent findings to populate the report.
Default to review-only. Do not modify code unless the user asks for fixes. Do not report unimplemented roadmap features as bugs when the Phase 1 plan defers them.
## 5. Validate the created skills
Validate in the repository where the skills will be used:
- Frontmatter parses; names match; descriptions distinguish the three workflows.
- All referenced files and heading anchors resolve from their actual locations.
- No scratch paths, fabricated commands, stale document-version requirements or placeholder links remain.
- Existing instructions and unrelated modifications are preserved.
- The three skills route these representative requests correctly:
- “Implement document upload and processing status.” → implement-feature.
- “Add regression tests for repeated chat submissions.” → write-tests.
- “Review this change for inactive-document exposure.” → review-change.
- “Evaluate these real questions before the demo.” → optional RAG evaluation within write-tests, with prerequisites checked.
- Review hypothetical behavior for missing docs, unavailable providers and a discovered product bug. Do not implement those product scenarios as part of skill creation.
Use the agent's available skill validator when present. If unavailable, validate YAML and links using existing tools and state the limitation. Do not install an unrelated toolchain merely for validation. If you add a reusable validation script, actually run it and verify its output.
Do not commit, push, deploy or install skills globally unless governing repository instructions or the user's authorization require it. Creating files is not evidence that the agent has discovered them: verify discovery if possible, otherwise explain how to invoke the files explicitly and label automatic discovery unverified.
## 6. Final report
Return:
1. The created/updated file tree and actual paths.
2. A brief explanation of each skill and one invocation example using this agent's supported syntax.
3. The actual project-document reference mapping.
4. Validation performed and results.
5. Any missing documents, unresolved decisions or discovery limitations.
Keep the final report concise. Do the file work before returning it.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+331
View File
@@ -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.
+302
View File
@@ -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.
-214
View File
@@ -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).
-316
View File
@@ -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.
+416
View File
@@ -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.
+123
View File
@@ -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.
+737
View File
@@ -0,0 +1,737 @@
# Organization Knowledge Assistant — Software Architecture
| Document field | Value |
| --- | --- |
| Version | 1.3 - LangChain Live document MVP; existing embedding pipeline retained |
| Date | 2026-10-07 |
| Status | Proposed implementation design; open decisions are listed in Section 19 |
| Audience | Project management, technical mentor, backend, frontend and AI developers |
| 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 |
Document lifecycle decision (revision 1.1): every upload is an independent immutable document. Chunks and ingestion jobs reference it directly; answer sources use document/chunk IDs. Content versioning is not a current requirement. Settings revisions and embedding profile metadata remain technical controls, not document versions.
## 1. Purpose and Scope
The 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.
### 1.1 Confirmed design constraints
- PostgreSQL with pgvector stores application data and document embeddings.
- 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.
- 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.
- Documents are dynamically uploaded, updated and selected by the organization.
- The only initial knowledge tool is `search_knowledge`. A separate read-document tool is excluded.
- 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 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
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 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
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
1. **Agentic interaction:** the model chooses a registered tool; the backend validates and executes the call. Models never receive database credentials or generate executable SQL for direct execution.
2. **Organization-controlled knowledge:** retrieval is restricted to authorized, selected and ready documents.
3. **Shared retrieval:** both conversation modes use one search implementation and evidence contract.
4. **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.
6. **Explicit lifecycle:** uploading a file does not immediately make it searchable. Ingestion must complete before publication.
7. **Traceable answers:** evidence links identify actual documents and chunks. Presence of a citation alone does not prove semantic correctness.
8. **Incremental implementation:** add extraction strategies and retrieval refinements based on actual documents and evaluation results.
## 3. System Context and Deployment Boundaries
| Component | Responsibilities | Deployment |
| --- | --- | --- |
| Web dashboard | Login, voice/microphone/speaker, available transcripts/sources, admin upload/status/review/selection | Same-origin HTTPS |
| 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 |
| PostgreSQL + pgvector | Existing foundation/jobs/chunks/vectors; retained review metadata and new auth/voice/tool records | Persistent database |
| File storage | Immutable originals and retained extraction artifacts | Existing durable volume; object storage only if already selected |
| 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 |
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.
## 4. Backend Modules and Dependency Rules
| Module | Owns | Public application operations |
| --- | --- | --- |
| Identity | Users, organization memberships and session authorization | Authenticate user; resolve organization and role |
| Documents | File metadata, ingestion state and selection | Upload independent document; list; activate; deactivate |
| Knowledge | Chunk retrieval and evidence construction | Search authorized knowledge |
| Conversations | 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 |
| 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 |
API handlers validate transport data, authenticate and call application services. Application services coordinate domain rules through interfaces. Provider clients, SQLAlchemy repositories and file-storage implementations belong to infrastructure. Tools call application services rather than API endpoints inside the same process.
Shared organization context is created from authenticated identity. Client input and model arguments cannot override it. Cross-module access uses explicit operations rather than arbitrary writes to another module's tables.
### 4.1 Suggested code organization
| Path | Purpose |
| --- | --- |
| `app/main.py` | API bootstrap and dependency wiring |
| `app/worker.py` | Ingestion worker entry point |
| `app/api/v1/` | HTTP and application event endpoints |
| `app/modules/identity/` | Authentication and authorization |
| `app/modules/documents/` | Document lifecycle |
| `app/modules/knowledge/` | Retrieval and search tool contracts |
| `app/modules/conversations/` | Minimal owned voice context; text/history later |
| `app/modules/live/` | Live session controller |
| `app/modules/configuration/` | Model profiles and organization settings |
| `app/integrations/ai/` | Text, embedding and live provider adapters |
| `app/infrastructure/db/` | Repositories, migrations and database sessions |
| `app/infrastructure/storage/` | Original-file access |
| `app/infrastructure/jobs/` | Durable job claiming and retry implementation |
| `tests/` | Unit, integration, contract and scenario evaluations |
Use application/domain/infrastructure subdivisions where module complexity warrants them. Do not introduce empty abstractions solely to match the proposed directory structure.
## 5. Agentic Conversation Design
### 5.1 Agent responsibilities
The agent interprets the user's wording and conversation context, asks clarification when meaning is ambiguous, and calls `search_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.
Document content is evidence, not executable instructions. Retrieved text cannot grant permissions, change tools or override the agent policy. Answers should identify uncertainty and conflicting sources rather than silently resolve a policy dispute.
### 5.2 Agentic behavior and enforcement
The model's choice to search is probabilistic. A system prompt alone cannot guarantee that every factual response is grounded. The application enforces tool authorization, budgets and source validity; evaluation checks whether the model calls the tool appropriately and supports its claims.
For text responses, validate structured source references before finalizing a turn. If the model returns invalid references, use a bounded repair attempt or return a controlled error. A stricter pre-release factuality gate can be added if evaluation requires it.
For 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 (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.
2. Persist the user message using a client request ID to detect retries.
3. Load bounded conversation context and a configuration/document-selection snapshot.
4. Run the text agent with the registered search tool.
5. Validate and execute tool calls through the shared knowledge service.
6. Return tool evidence to the same agent loop.
7. Produce a response, validate reference IDs and persist the assistant message and citations.
8. Return the final answer or stream supported application events.
A failed turn is recorded explicitly and does not appear as a completed assistant answer. Retrying a completed request returns the existing result instead of creating duplicate messages.
## 6. Search Tool Contract
### 6.1 Model-visible interface
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
{
"name": "search_knowledge",
"description": "Retrieve authorized evidence for a document-dependent question.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"context": {"type": "string", "description": "Optional resolved conversational reference; never authorization."}
},
"required": ["query"],
"additionalProperties": false
}
}
```
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
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.
`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.
### 6.3 Execution pipeline
1. Validate non-empty query and enforce configured length/call budgets.
2. Resolve organization access and selected documents from trusted state.
3. Recheck current document permissions and deactivation before retrieval.
4. Normalize Persian query text without changing semantic constraints.
5. Embed the query using the compatible embedding profile of the active index.
6. Run filtered vector retrieval and optionally combine lexical results.
7. Deduplicate, select relevant chunks and cap the evidence token budget.
8. Build references from stored metadata and persist retrieval provenance.
9. Return evidence to the requesting text or live agent.
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.
## 7. Dynamic Document Lifecycle
### 7.1 Upload and extraction
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.
```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
```mermaid
stateDiagram-v2
[*] --> queued
queued --> processing
processing --> ready
processing --> failed
failed --> queued: Retry
ready --> deleted: Delete
```
Activation/selection is separate from processing state: a ready document can remain unselected. Only selected ready documents can be searched.
### 7.3 Chunking and embedding
Each chunk preserves its document identity, order, text and available source location. Chunk size and overlap are configurable and recorded as processing metadata. 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 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
Each upload creates a new independent document; there is no document-version entity or in-place content replacement. Upload the changed file, wait until it is ready, then deactivate the old document and activate the new one. The old document remains inactive for historical reference. Failure of the new upload leaves the old active document usable. Retry processes only the same failed document and creates no new identity.
An administrator selects ready document IDs for the organization. Every turn records the effective selection revision and the source document/chunk IDs. A selection change applies to subsequent turns. Current access revocation/deactivation overrides cached or snapshotted access immediately for new tool operations; sensitive in-flight results must be rechecked before delivery.
Previously sent evidence cannot be recalled from a provider context. On document revocation during a live conversation, invalidate affected context and reset or close the provider session when necessary. Previously delivered speech cannot be withdrawn. The UI must not imply that changing selection rewrites old answers.
Deletion first excludes the document from retrieval. Physical deletion follows the retention policy, including chunks, vectors, originals and derived copies. Historical citations retain minimal tombstone metadata when permitted; access to retained content still requires authorization.
### 7.5 Durable worker behavior
The worker claims jobs with a lease and claim token, updates progress and publishes only if it still owns the claim. Expired leases allow recovery after a crash. External embedding calls occur outside long database transactions. Idempotent chunk writes and publication prevent duplicate indexed chunks after retries.
Store job attempts, next retry time, stage, error category and processing profile. Retry temporary network/rate-limit failures with bounded backoff; unsupported formats and invalid input require correction. File storage and PostgreSQL do not share a transaction: use staged storage and reconciliation to clean abandoned uploads or recover incomplete metadata transitions.
## 8. Live Voice with direct Gemini API access
### 8.1 Connection responsibilities
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).
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
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).
### 8.3 Voice tool cycle
```mermaid
sequenceDiagram
participant U as Browser or approved audio bridge
participant B as Backend Live controller
participant L as Gemini Live
participant K as Shared knowledge service
participant D as PostgreSQL and pgvector
U->>B: Authenticated audio stream
B->>L: Audio on direct Live WSS session
L->>B: search_knowledge(query, optional context)
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
L-->>B: Persian speech and available transcription
B-->>U: Audio, transcript and source references
```
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.
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.
### 8.4 Conversation, interruption and failure behavior
| 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 |
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 Audio, transcripts and telephony boundaries
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).
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
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 |
| --- | --- |
| organizations | ID, name, status |
| users / memberships | Identity, organization, role and active state |
| organization_settings | Revision, allowed model profiles, retrieval limits, active selection revision |
| documents | Organization, display name, checksum, storage key, MIME, processing status/profile, selected flag, deletion state |
| ingestion_jobs | Document, stage, state, attempts, lease owner/token, lease expiry, next attempt, error |
| embedding_profiles | Provider/model, dimensions, preprocessing version, index generation and active state |
| chunks | Document, ordinal, original and normalized text, page/section, processing profile |
| chunk_embeddings | Chunk, embedding profile/generation and vector |
| conversations | Organization, owner, title, mode, state and timestamps |
| turns | Conversation, sequence, client request ID, configuration/selection snapshot, state |
| messages | Turn, role, content, modality, provider item ID, completion/interruption state |
| tool_calls | Turn/session, provider call ID, validated query, execution state, result references and latency |
| message_sources | Message, document/chunk, source reference and supporting excerpt if allowed |
| live_sessions | Conversation, provider session ID, controller owner, model, connection state and timestamps |
| audit_events | Actor, organization, action, target, timestamp and redacted metadata |
All organization-owned access must enforce organization scope. Use foreign keys and constraints to prevent cross-organization relationships, not only API checks. Add unique constraints for chunk ordinals per document, client request IDs per conversation and provider event/call IDs in their proper scope.
Use relational columns for identifiers, statuses and queryable fields; JSONB holds variable provider metadata and processing details. Do not store secrets in metadata. Use timezone-aware timestamps in UTC and display localized time in the UI. Page numbering semantics must be recorded by the extractor.
Vector dimension and storage type must match the chosen embedding profile. Separate incompatible vector generations by table/partition or another explicitly tested strategy. Index foreign keys and frequent organization/status filters. Select approximate vector indexes only after measuring filtered recall and query latency [R4].
## 10. Application API Contracts
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 |
| --- | --- | --- |
| `POST /api/v1/auth/login` | Local login if local authentication is selected | Secure session; final identity contract TBD |
| `POST /api/v1/auth/logout` | End authenticated session | 204 |
| `GET /api/v1/me` | Current identity and organization roles | 200 |
| `POST /api/v1/documents` | Multipart file upload | 202 with document/job IDs |
| `GET /api/v1/documents` | Paginated organization documents | 200 |
| `GET /api/v1/documents/{id}` | Metadata and processing state | 200 |
| `PATCH /api/v1/knowledge-selection` | Replace selected document IDs using expected revision | 200 or 409 |
| `DELETE /api/v1/documents/{id}` | Exclude and schedule permitted cleanup | 202 |
| `GET /api/v1/configuration` | Read organization settings and capabilities | 200 |
| `PATCH /api/v1/configuration` | Admin settings update using expected revision | 200 or 409 |
| `POST /api/v1/conversations` | Start text, voice or mixed conversation | 201 |
| `GET /api/v1/conversations/{id}/messages` | Authorized, paginated history | 200 |
| `POST /api/v1/chat` | Submit a text turn | JSON result, or explicit SSE mode |
| `POST /api/v1/voice/sessions` | Initialize live session and signaling | 201 |
| `POST /api/v1/voice/sessions/{id}/close` | Idempotent close | 200 |
| `GET /api/v1/conversations/{id}/events` | Authorized application event stream | SSE |
| `GET /health/live` | Process liveness | 200 |
| `GET /health/ready` | Ability to serve required dependencies | 200 or 503 |
All IDs from clients are checked for ownership. Pagination and upload limits are bounded. The internal search tool is not an unauthenticated public endpoint. Final endpoint names can evolve before frontend contract freeze.
### 10.1 Text turn example (deferred)
```json
{
"conversation_id": "conv_example",
"client_request_id": "request_example",
"message": "What are the organization's Thursday working hours?"
}
```
```json
{
"conversation_id": "conv_example",
"turn_id": "turn_example",
"message_id": "msg_example",
"status": "answered",
"answer": "An answer grounded in the selected reference documents.",
"sources": [
{"source_ref": "S1", "document_id": "doc_example", "chunk_id": "chunk_example", "page": 3}
]
}
```
Final application statuses include `answered`, `needs_clarification`, `insufficient_information` and `failed`. Streaming text is provisional until the completion event validates the final source mapping. The UI must preserve errors or interruption instead of implying successful completion.
### 10.2 Upload response example
```json
{
"document_id": "doc_example",
"job_id": "job_example",
"status": "queued",
"searchable": false
}
```
### 10.3 Live session application contract
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
```json
{
"error": {
"code": "KNOWLEDGE_NOT_READY",
"message": "Selected documents are not ready for search.",
"request_id": "req_example",
"retryable": true
}
}
```
Use 401 for unauthenticated access, 403/404 according to the resource-disclosure policy, 409 for revision/idempotency conflict, 413 for size limit, 415 for unsupported type, 422 for invalid input, 429 for quotas and 503 for unavailable dependencies. Never return internal exception strings or credentials.
## 11. Configuration and Model Boundaries
Separate text, live and embedding model profiles. Changing the response model does not rebuild embeddings; changing the embedding profile does. A live profile must support the chosen media and trusted tool-control features. The UI exposes only administrator-approved, capability-compatible models.
Configuration is revisioned. Record model, prompt, tool schema, retrieval profile and selection revision per turn/session. Apply ordinary model changes to new turns or sessions; do not silently mutate an active live session. Document access revocation is handled immediately as described in Section 7.
Provider adapters normalize completion events, tool calls, timeouts, rate limits, usage and error categories. They must not assume every model implements identical event schemas. Business services depend on interfaces such as TextModel, EmbeddingProvider, LiveSessionProvider, KnowledgeRepository and FileStore.
## 12. Security and Organization Isolation
Authenticate every application entry point and authorize every tool operation. Proposed roles are organization administrator and conversation user; additional roles require a product need. Ordinary users cannot change model credentials or organization selections.
Use HTTPS, server-managed secrets, controlled CORS origins and an explicit session expiration policy. If cookies are selected, apply secure/HttpOnly attributes and CSRF protection to mutations. If external SSO is selected, replace local credential handling while preserving application membership checks.
Treat uploads, model arguments and extracted content as untrusted input. Validate upload paths, avoid executing embedded content, limit parser resources and refuse unregistered tools. Restrict client ability to update provider session instructions or inject trusted tool outputs using available provider permissions. Validate remaining access assumptions during the live integration spike.
Document bodies and full prompts are not ordinary operational logs. Log IDs, stage, latency and redacted errors by default. Access to stored message content and citations follows organization membership and resource permissions. Administrative changes generate audit records.
## 13. Reliability and Concurrency
| Failure | Required behavior |
| --- | --- |
| Embedding rate limit | Bounded retry; preserve job state |
| Unsupported/unreadable file | Failed document with actionable reason |
| Replacement ingestion failure | Keep prior active document available |
| Database outage | Reject dependent operations explicitly; do not invent answers |
| Search timeout | Return tool error; distinguish it from no evidence |
| Duplicate tool event | Reuse correlated result; avoid duplicate execution/history |
| Lost live control channel | Pause or close knowledge interaction and notify UI |
| Browser disconnect | Cleanup after grace period and record uncertain completion |
| Worker crash | Recover expired lease and continue idempotently |
| Invalid citation | Repair within budget or fail the response |
Serialize mutating turns per conversation in the initial implementation. A text turn must not race with an active voice turn against the same context. Keep live session control owned by one backend process; multi-instance deployment requires routing/ownership and a defined restart policy.
Retries of text generation and live session creation can incur duplicate provider work after an ambiguous timeout. Correlate application requests, reconcile known provider state where supported and avoid blind automatic recreation. Idempotency keys include a payload hash; reusing a key with a different request returns a conflict.
## 14. Observability and Performance
Correlate request, organization, conversation, turn, live session, tool call, document and job IDs. Measure text time to first output, total turn latency, query embedding latency, retrieval latency, live tool turnaround, available audio latency measurements, ingestion duration, error rates and provider usage.
Do not treat server tool latency as end-to-end voice latency. Browser measurements are required to include microphone, network and playback behavior. Usage may be incomplete if a session terminates before final provider events; represent it as partial rather than zero.
Capacity targets remain to be agreed: concurrent text users, active voice sessions, corpus size, ingestion throughput, maximum upload size and acceptable percentile latency. Test on the intended deployment network and representative Persian documents. Connection pools, evidence budgets and concurrency limits should be tuned from measurements.
## 15. Deployment and Operations
The first deployment consists of the dashboard/HTTPS entry point, one FastAPI service, one ingestion worker, PostgreSQL with pgvector and durable file storage. API and worker share code and configuration but run as separate processes. Redis and an external broker are optional future components, not baseline dependencies.
Apply reviewed database migrations as an explicit deployment step. Keep separate development, test and production credentials. Readiness checks should validate required local dependencies without making expensive model calls on every health probe. Perform provider connectivity checks as controlled diagnostics.
Backups must cover both the database and original files with a restorable mapping. Test restoration and reindexing. Recovery objectives, retention schedules and backup frequency are operational decisions requiring approval; no numeric guarantee is implied by this document.
Graceful shutdown stops new sessions/jobs, drains active work within a configured deadline and records interrupted work. Live sessions cannot be assumed migratable between processes. Monitor disk space, job backlog, database connections and external provider quotas.
## 16. Validation and Acceptance
Build a reference evaluation set from approved organization documents and expected answers before tuning prompts. Include natural Persian variants, follow-up pronouns, dates, numbers, conflicting documents, absent information and questions about unselected documents.
| Area | Acceptance evidence |
| --- | --- |
| Retrieval | Expected evidence appears for representative questions; numeric recall target agreed with stakeholders |
| Grounding | Answer claims supported by cited passages; unsupported questions handled explicitly |
| Agent behavior | Appropriate search calls, bounded retries and clarification for ambiguity |
| Isolation | Cross-organization IDs and model-supplied scope cannot expose documents |
| Dynamic documents | Upload, select, replace, deactivate and delete reflected in new retrieval |
| Voice/session persistence | Upload/review/retry/live create replay correctly; restart preserves jobs/documents and makes old media sessions terminal |
| 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 |
| Ingestion recovery | Crashes and provider failures recover without duplicate publication |
| Deployment | HTTPS/microphone behavior, backups and demonstration network verified |
Use unit tests for permissions and state transitions, integration tests with PostgreSQL/pgvector, provider contract tests, and a small controlled live evaluation. Stub-only tests do not validate actual provider signaling or Persian audio quality. Evaluate 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
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 |
| --- | --- |
| `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/tools/retriever_tool.py` | Enforce trusted organization scope and structured evidence output |
| `app/services/agent/exec.py` | Retain the agentic tool loop; add bounded execution, injected services and durable context |
| `app/services/agent/prompt.py` | Replace technical-documentation persona with organization-knowledge policy |
| `app/schemas/chat.py` | Add conversation/turn identity, structured sources and explicit outcomes |
| `app/api/v1/chat.py` | Add authorization, idempotency, safe errors and optional streaming |
| `app/core/config.py` | Separate secrets from versioned organization/model settings |
| `app/main.py` | Explicit lifecycle initialization, bounded CORS and readiness |
Remove indexing side effects from module imports. Re-embed the source documents into the new compatible index; do not copy incompatible existing vectors. Treat in-memory conversation state as temporary unless explicitly migrated. Add dependency manifests, migrations, operational packaging and meaningful tests before claiming a reproducible release.
## 18. Implementation Sequence
1. Prove actual funded Gemini Persian audio/transcripts/tools and target-network access early.
2. Reuse ingestion Phases 1-4; implement Phase 5 worker, exact-output review/resume and complete publication.
3. Add minimal cookie identity and new-document HTTP upload/status/review/selection.
4. Implement one scoped pgvector search service using compatible existing embeddings.
5. Expose the service through LangChain retriever/tool boundaries; evaluate evidence with an internal query harness.
6. Reserve owned voice contexts/sessions; connect native Live function calls to the same tool, audio relay, sources, cancellation and epoch checks.
7. Finish the basic workspace, limits/failure feedback, unseen-file evaluation and actual HTTPS rehearsal.
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
| Decision | Suggested owner | Architectural impact |
| --- | --- | --- |
| File formats, scans, tables, document languages and size | Product owner / organization | Extractors, OCR, chunking and acceptance set |
| Organization-wide selection | Confirmed MVP direction | Preserve selected-set revision and backend eligibility |
| Exact Gemini Live model and account/tool/transcript capabilities | AI/backend team | Backend WSS adapter, audio and tool proof |
| Funded embedding/extraction/Live profiles | AI team | Preserve current embedding compatibility; prove real quality/access |
| 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 |
| Concurrent sessions and latency targets | Product / IT | Capacity, scaling and quotas |
| Whether spoken answers require pre-release validation | Product / AI | Compatibility with direct live audio |
| Hosting, outbound connectivity and data transfer approval | IT / organization | Provider reachability and deployment |
| Backup policy and recovery objectives | IT | Operations and restoration testing |
| 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 |
These items must be resolved by their owners rather than silently converted into product policy.
## 20. Reference Documentation
External references establish platform capabilities. Module boundaries, contracts and lifecycle rules in this document are project design proposals. Model/API availability must be checked when implementing the selected adapter.
- **[R1]** [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api): initial direct provider/session access.
- **[R2]** [Gemini Live capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities): audio, transcription and interruption.
- **[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.
## Appendix A. Presentation Diagrams
The following diagrams retain the previously agreed overview. Detailed security, lifecycle and failure requirements are defined in the main sections.
### A.1 Agentic AI and Dynamic Documents
```mermaid
flowchart TD
USER["User — Text or Live Voice"] --> AGENT["AI Agent"]
subgraph AI["Agentic Conversation"]
AGENT --> DECISION{"Need Document Knowledge?"}
DECISION -->|"Yes"| CALL["Call Search Tool with Search Query"]
DECISION -->|"Ready to Answer"| ANSWER["Generate Response with Sources"]
end
subgraph TOOL["Tool: search_knowledge"]
CALL --> SCOPE["Apply Organization and Selected Document Filters"]
SCOPE --> QUERY["Embed Search Query"]
QUERY --> SEARCH["Semantic Search"]
SEARCH --> SELECT["Select Relevant Chunks"]
SELECT --> RESULT["Return Content, Document IDs and Sources"]
end
RESULT -->|"Tool Result"| AGENT
ANSWER --> USER
subgraph DOCS["Dynamic Organization Documents"]
ADMIN["Organization Admin"] --> MANAGE["Upload, Update and Select Documents"]
MANAGE --> PROCESS["Extract, Chunk and Embed"]
PROCESS --> DB[("PostgreSQL + pgvector")]
MANAGE --> ACTIVE["Active Document Selection"]
end
ACTIVE --> SCOPE
SEARCH <-->|"Retrieve Matching Chunks"| DB
```
### A.2 Layered Backend Overview
```mermaid
flowchart TD
subgraph L1["1. Presentation"]
UI["Web Dashboard"]
end
subgraph L2["2. Backend API — FastAPI"]
CHAT["Text Chat"]
SESSION["Live Session"]
DOCS["Documents and Configuration"]
end
subgraph L3["3. Agentic AI — logical; Live model is external"]
TEXT["Text AI Agent"]
LIVE["Live AI Model"]
TOOL["Search Documents Tool"]
TEXT <-->|"Tool Calls and Evidence"| TOOL
LIVE <-->|"Tool Calls and Evidence via Backend"| TOOL
end
subgraph L4["4. Knowledge Management"]
INGEST["Extract, Chunk and Embed"]
SEARCH["Search Organization-selected Documents"]
end
subgraph L5["5. Storage"]
FILES[("Document Files")]
DB[("PostgreSQL + pgvector — Documents and Chat History")]
end
UI --> CHAT
UI --> SESSION
UI --> DOCS
CHAT <--> TEXT
SESSION -->|"Initialize and Control"| LIVE
UI <-->|"Authenticated audio WSS"| SESSION
SESSION <-->|"Direct Gemini Live WSS"| LIVE
TOOL <--> SEARCH
SEARCH <--> DB
DOCS -->|"Upload and Update"| INGEST
DOCS -->|"Active Document Selection"| SEARCH
DOCS -->|"Store Original Files"| FILES
FILES --> INGEST
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.
@@ -0,0 +1,456 @@
# RAG Assistant — Phase 1 Database Design
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, 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.
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
All IDs are application-generated UUIDs. `uuid PK` means primary key. Timestamps are `timestamptz` in UTC; `created_at` defaults to database now. Unless marked nullable, fields are NOT NULL. JSON defaults are `{}` or `[]` as appropriate. Status fields use text plus CHECK constraints for simple evolution. Hashes use lowercase SHA-256 hex (`char(64)`), except password hashes which use the selected password library's encoded format. Counters use integer/bigint and CHECK >= 0; revisions/sequence numbers start at 1.
Tables other than settings have a UUID `id` PK. Settings uses `organization_id` as PK. Every organization-owned table has `organization_id uuid` referencing organizations, even where derivable. For all referenced scoped entities add `UNIQUE(organization_id,id)` and use composite scoped foreign keys. This prevents a valid UUID from another organization being attached accidentally. Do not treat UUID unpredictability as access control.
Use RESTRICT/NO ACTION for normal deletion; no broad CASCADE from users/documents into historical chats. Soft deletion and explicit cleanup control lifecycle. Owners/roles are checked by application queries. Single-organization deployment does not justify dropping organization filtering. Row-level security is deferred, not claimed to be enabled.
## 2. Relationship overview
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
erDiagram
documents ||--o{ document_chunks : contains
documents ||--|| ingestion_jobs : processes
conversations ||--o{ turns : contains
turns ||--o{ messages : records
turns ||--o{ citations : supports
conversations ||--o{ live_sessions : hosts
turns |o--o{ tool_calls : text_calls
live_sessions |o--o{ tool_calls : voice_calls
```
The diagram omits identity/configuration/audit for readability. Each tool call belongs to exactly one text turn OR one live session. A citation also references the exact tool call/evidence that produced its chunk. These relationships are defined below.
## 3. Identity and organization tables
### 3.1 organizations
| Column | Type/default | Meaning |
| --- | --- | --- |
| id | uuid PK | Fixed seeded organization |
| name | varchar(200) | Display name |
| created_at | timestamptz now | Creation |
### 3.2 users
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id | uuid | Identity and organization |
| username | varchar(120) | Canonical lowercase login name |
| password_hash | text | Salted adaptive password hash; never plaintext |
| role | text | admin or user |
| is_enabled | boolean true | Account authorization |
| created_at, updated_at | timestamptz | Audit timestamps |
Unique username globally for simple login without organization selector. CHECK role. Add UNIQUE(organization_id,id). Disabling a user revokes sessions and closes live sessions; account-management UI is deferred (maintenance command only).
### 3.3 auth_sessions
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, user_id | uuid | Session owner |
| token_hash | char(64) UNIQUE | Hash of opaque cookie token |
| created_at, expires_at, last_seen_at | timestamptz | Lifetime |
| revoked_at | timestamptz nullable | Explicit revocation |
Composite FK to users. CHECK expires_at > created_at. Index expires_at for cleanup. Never store raw cookie. Derive CSRF token from raw session cookie using a separate server-side HMAC secret (or an equivalent reviewed synchronizer mechanism); compare in constant time. `/me` can reproduce it without persisting a raw CSRF token.
### 3.4 organization_settings
| Column | Type/default | Meaning |
| --- | --- | --- |
| organization_id | uuid PK/FK | One row per organization |
| assistant_name | varchar(120) | UI/model name |
| instruction | text | Organization instruction, API length limit |
| revision | bigint 1 | Settings optimistic revision |
| knowledge_revision | bigint 1 | Selected-set revision |
| access_epoch | bigint 1 | Invalidation counter for removals |
| updated_by | uuid nullable | Actor; scoped FK to users |
| updated_at | timestamptz | Last configuration/selection mutation |
CHECK all counters >= 1. Selection uses documents.is_active; no assignment table in Phase 1. Lock this row first for selection, context creation and finalization to impose a consistent order.
## 4. Knowledge tables
### 4.1 documents
Each upload is one independent immutable document. This table owns file metadata and processing state directly. There is no document-version table or version-number field. Replacement means a new upload/document ID, followed by active-selection change after readiness. The same idempotent upload replay returns the original ID.
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, uploaded_by | uuid | Identity and admin actor |
| title | varchar(200) | Display title |
| original_filename | text | Display only, never trusted path |
| upload_request_id | uuid | Upload Idempotency-Key |
| upload_payload_hash | char(64) | File bytes + normalized metadata digest |
| storage_key | text UNIQUE | Generated original-file reference |
| file_sha256 | char(64) | Original bytes hash |
| mime_type | text | Validated MIME |
| size_bytes | bigint | Original size > 0 |
| status | text queued | queued, processing, ready, failed |
| processing_profile | jsonb | Extractor/chunk/embedding settings |
| chunk_count | integer 0 | Published chunk count |
| ready_at | timestamptz nullable | Successful publication |
| is_active | boolean false | Organization selection |
| deleted_at | timestamptz nullable | Soft deletion |
| content_purged_at | timestamptz nullable | Explicit future cleanup marker |
| created_at, updated_at | timestamptz | Timestamps |
UNIQUE(organization_id,upload_request_id). Scoped FK uploaded_by→users. CHECK size_bytes > 0, chunk_count >= 0. CHECK ready implies ready_at IS NOT NULL and chunk_count > 0. CHECK is_active implies status='ready', deleted_at IS NULL and content_purged_at IS NULL. Storage keys are generated and unique; no automatic same-hash deduplication between documents.
Do not overwrite the original bytes or republish a ready document. Manual retry accepts only eligible failed documents; first successful publication fixes the source/chunk identities. If content changes, upload a new independent document. Physical purging must first deactivate the document; retained metadata is a tombstone, never eligible search content.
Freeze the actual snapshot produced by IngestionSettings.processing_profile,
including current schema-2 extraction/normalization/chunking and embedding
identity/request limits. Do not replace it with the older illustrative flat
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
does not change these snapshots or require re-embedding compatible vectors.
### 4.2 document_chunks
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, document_id | uuid | Source identity |
| ordinal | integer | 0-based order |
| text | text | Extracted evidence |
| location | jsonb | `{page: integer-or-null, section: string-or-null}`; section may identify table/row/Q&A or image group |
| token_count | integer nullable | Actual tokenizer count if available |
| embedding | vector(D) | Model-compatible vector |
| created_at | timestamptz | Publication |
UNIQUE(document_id,ordinal); CHECK ordinal >= 0 and length(text)>0; token_count >= 0 when set. FK document scoped. Page is positive when present. Do not invent a page index for a format without pages.
Index document_id; initial small-corpus search uses exact cosine distance after eligibility joins. Defer ANN/HNSW until measured latency requires it. If later added, validate filtered-search recall. Example query is parameterized and conceptual (D is a migration parameter):
```sql
SELECT c.id, c.text, c.location, d.id AS document_id,
c.embedding <=> CAST(:query_vector AS vector) AS distance
FROM document_chunks c
JOIN documents d ON d.id = c.document_id AND d.organization_id = c.organization_id
WHERE d.organization_id = :organization_id
AND d.is_active = true AND d.deleted_at IS NULL
AND d.status = 'ready' AND d.content_purged_at IS NULL
ORDER BY c.embedding <=> CAST(:query_vector AS vector), c.id
LIMIT :top_k;
```
Server validates profile, dimension and bounded top_k before query. A nearest neighbor is not automatically sufficient evidence; no universal distance threshold is assumed.
### 4.3 ingestion_jobs
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, document_id | uuid | One job per document |
| status | text queued | queued, processing, succeeded, failed |
| stage | text extract | extract, chunk, embed, publish |
| attempt_count | integer 0 | Claims within current retry generation |
| retry_generation | integer 0 | Manual retries |
| next_attempt_at | timestamptz now | Backoff scheduling |
| claim_token | uuid nullable | Fencing token |
| lease_expires_at | timestamptz nullable | Worker lease |
| claimed_by | text nullable | Worker process identifier |
| error_code, error_message | text nullable | Redacted failure |
| error_retryable | boolean false | Eligibility hint |
| created_at, updated_at | timestamptz | Timestamps |
UNIQUE(document_id). CHECK processing requires claim_token and lease_expires_at; non-processing clears them. Index `(status,next_attempt_at)` and partial lease expiry for processing. Claim eligible rows with row lock/SKIP LOCKED, regenerate token and increment attempt count. Recovery excludes deleted documents and reclaims expired jobs within retry budget. Final publication locks job and checks token plus lease; an expired worker cannot publish even if its provider call completed. Manual retry uses audit idempotency record and updates this same job atomically.
### 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
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, owner_user_id | uuid | Ownership |
| client_request_id | uuid | Create idempotency key |
| request_hash | char(64) | Normalized create payload |
| mode | text | text or voice |
| title | varchar(120) nullable | Optional display label |
| status | text active | active, stale, closed |
| access_epoch | bigint | Knowledge-removal snapshot |
| created_at, updated_at | timestamptz | Ordering |
UNIQUE(owner_user_id,client_request_id). Scoped FK owner. Index owner/created_at/id. Effective status is stale if epoch differs even before explicit row updates. 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 (deferred)
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, conversation_id | uuid | Text turn identity |
| client_request_id | uuid | Chat retry correlation |
| request_hash | char(64) | Conversation/message digest |
| status | text running | running, answered, needs_clarification, insufficient_information, failed |
| settings_revision, knowledge_revision, access_epoch | bigint | Actual snapshots |
| execution_profile | jsonb | Model, actual organization instruction, prompt version, tool schema version and limits |
| started_at, deadline_at | timestamptz | Execution timeout |
| finished_at | timestamptz nullable | Terminal completion |
| error_code, error_message | text nullable | Normalized failure |
| error_retryable | boolean false | Technical retry hint |
| created_at | timestamptz | Creation |
UNIQUE(conversation_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status='running'. CHECK terminal iff finished_at is not null; deadline_at > started_at. Scoped FK conversation. Mode=text is an application invariant checked while locking conversation. Message text resides in messages, not duplicated here. Reconstruct API response from messages/citations; replay does not call provider again. Startup/deadline cleanup marks interrupted turns failed.
### 5.3 messages (deferred)
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, conversation_id, turn_id | uuid | Ownership and text turn |
| sequence_no | bigint | Stable conversation order, >=1 |
| role | text | user or assistant |
| content | text | Message body |
| created_at | timestamptz | Creation |
UNIQUE(conversation_id,sequence_no), UNIQUE(turn_id,role). Both roles may exist for completed turn; failed turn can have user only. Add UNIQUE(organization_id,conversation_id,id) as needed for matching references. Enforce `(organization_id,conversation_id,turn_id)` FK to a corresponding unique key on turns, not independent FKs that could attach a message to the wrong conversation. Allocate sequence while holding conversation row lock; no model tool/system messages in this table.
### 5.4 tool_calls (voice-only MVP)
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, live_session_id | uuid | Owned voice parent; live_session_id NOT NULL |
| external_call_id | text | Provider call correlation |
| tool_name | text | search_knowledge only |
| arguments | jsonb | Validated query/context without model scope |
| request_hash | char(64) | Canonical argument digest |
| status | text running | running, succeeded, failed |
| knowledge_revision, access_epoch | bigint | Retrieval snapshots |
| result_json | jsonb nullable | Evidence IDs/text/locations, no_evidence or normalized error |
| error_code | text nullable | Technical/cancellation reason |
| created_at | timestamptz | Creation |
| completed_at | timestamptz nullable | Terminal completion |
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.
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 |
| --- | --- | --- |
| id, organization_id, turn_id, tool_call_id | uuid | Answer/evidence correlation |
| source_ref | text | S1, S2... unique across all searches within this turn |
| document_id, chunk_id | uuid | Stable actual source IDs |
| title_snapshot | text | Title at answer time |
| location_snapshot | jsonb | Actual source locator |
| excerpt | text nullable | Display evidence; cleared if policy requires purge |
| created_at | timestamptz | Answer commit |
UNIQUE(turn_id,source_ref). Scoped FKs for sources plus chain-consistent composite FKs: chunk belongs to the cited document, tool call belongs to the same turn. Add referenced unique keys on these chains. Application verifies source_ref belongs to tool result, not arbitrary model output. No assistant_message_id needed: UNIQUE(turn_id,role) resolves the assistant. Only terminal non-failed answers can have final citations (transaction invariant).
Keep source identity rows as tombstones if allowed. `available` in API is computed from current access and retention state; revoked source excerpts are not emitted by source endpoints. Old answer prose cannot be retroactively withdrawn and remains owner-visible under history policy. Do not hard-delete referenced chunks through ordinary application DELETE.
## 6. Live and audit tables
### 6.1 live_sessions
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, conversation_id, owner_user_id, auth_session_id | uuid | Session ownership and logout correlation |
| client_request_id | uuid | Creation correlation |
| request_hash | char(64) | Normalized conversation/create-options digest; no SDP |
| provider, model | text | Chosen live profile |
| provider_session_id | text nullable | External reference |
| status | text creating | creating, connecting, connected, closed, failed |
| settings_revision, knowledge_revision, access_epoch | bigint | Creation snapshots |
| execution_profile | jsonb | Instruction/prompt plus proposed audio/transcription capability snapshot |
| expires_at, created_at, updated_at | timestamptz | TTL/lifecycle |
| connected_at, closed_at | timestamptz nullable | Transition timestamps |
| close_reason, error_code | text nullable | Normalized reason |
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. 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 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
| Column | Type/default | Meaning |
| --- | --- | --- |
| id, organization_id, actor_user_id | uuid (actor nullable) | Administrator/system action |
| action | text | upload, selection_changed, document_deleted, ingestion_retry, extraction_review, configuration_changed, session_revoked |
| target_id | uuid nullable | Referenced object; polymorphic diagnostic field |
| request_id | text nullable | HTTP tracing |
| idempotency_key | uuid nullable | Delete/retry idempotency |
| request_hash | char(64) nullable | Mutation payload hash |
| response_json | jsonb nullable | Replay of delete/retry outcome |
| metadata | jsonb | Changed IDs/revisions, redacted reason |
| created_at | timestamptz | Event time |
Partial UNIQUE(organization_id,actor_user_id,action,target_id,idempotency_key) WHERE idempotency_key IS NOT NULL. Delete/retry/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
| Operation | One database transaction | Outside transaction |
| --- | --- | --- |
| Upload | Document + job + audit | File staging/write; reconcile orphans |
| Claim | Row lock, new token/lease, attempt increment | Extraction and provider calls |
| Publish | Lock document/job; verify token/lease; 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 |
| Review decision | Document/job lock, exact candidate/source/profile check, decision + audit replay | Reading exact retained preview; no provider call |
| 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 |
| Delete/retry | State change + unique audit replay result | Physical cleanup or future worker execution |
Use consistent lock order where resources overlap: organization settings → conversation or document → job or turn/session. Do not hold settings lock during remote calls. Publication does not acquire settings after a document lock; it leaves selection unchanged. Retry/publish paths lock document then job to avoid inversion. Claims lock only jobs and commit quickly.
On active-document removal: database epoch invalidation is authoritative immediately for new operations. After transaction, notify/close provider sessions and discard stale pending evidence. Cannot recall previously delivered live audio. Session close failure remains observable and bounded by TTL; it is not represented as guaranteed erasure at the provider.
## 8. Migration plan
Treat migrations/versions/0001_ingestion_foundation.py as applied and immutable.
The generic 001_identity/002_knowledge/003_conversations sequence from revision
1.2 is not an instruction to recreate or combine the current foundation.
| 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 |
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
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
No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements.
@@ -0,0 +1,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.
@@ -0,0 +1,315 @@
> 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 و دیتابیس با سناریو
نسخه ۱.۲ — تاریخ ۲۰۲۶/۱۰/۰۶
این گزارش طراحی پیشنهادی پیاده‌سازی است؛ به معنی ساخته‌شدن برنامه، اجرای مایگریشن یا موفقیت تست‌ها نیست. بازه تحویل همان ۷ تا ۱۰ روز و فرض ظرفیت، یک توسعه‌دهنده اصلی است.
## ۱. این مجموعه سند دقیقاً چه چیزی تحویل می‌دهد؟
| سند | کاربرد |
| --- | --- |
| `RAG-Phase1-Implementation-Guide.md` | توسعه‌دهنده بداند چه ماژول‌هایی بسازد، ترتیب کار چیست و هر جریان چگونه اجرا شود |
| `RAG-Phase1-API-Catalog.md` | فرانت و بک‌اند روی آدرس‌ها، ورودی، خروجی، دسترسی، وضعیت و خطا توافق کنند |
| `RAG-Phase1-Database-Design.md` | جداول، ستون‌ها، ارتباط‌ها، محدودیت‌ها و ترتیب مایگریشن مشخص باشند |
| همین گزارش | جریان محصول و ارتباط API، منطق و دیتابیس با مثال قابل فهم باشد |
مبنای محدوده، `RAG-AI-Phase1-Delivery-Plan.md` است. سند معماری اصلی مسیر محصول کامل را نگه می‌دارد؛ امکاناتی که آنجا آمده‌اند الزاماً در فاز یک پیاده نمی‌شوند.
سه سند فنی انگلیسی‌اند تا برای داکیومنت پروژه و توسعه قابل استفاده باشند. این گزارش فارسی است. قراردادهای تازه مثل روش احراز هویت و جزئیات جدول‌ها، پیشنهاد فنی مشخص برای شروع‌اند و تأیید قبلی کارفرما فرض نشده است.
## ۲. محصولی که در پایان فاز یک نشان می‌دهیم
مدیر وارد سامانه می‌شود، سند سازمان را آپلود می‌کند، آماده‌شدن آن را می‌بیند و فعالش می‌کند. کاربر از طریق متن یا صوت سؤال می‌پرسد. مدل تصمیم می‌گیرد ابزار سرچ را اجرا کند؛ بک‌اند شواهد را از اسناد فعال پیدا می‌کند و مدل بر اساس آن پاسخ می‌دهد.
چهار صفحه داریم: ورود، گفتگو، اسناد و تنظیمات. در تنظیمات فقط نام و دستورالعمل دستیار تغییر می‌کند. انتخاب اسناد در صفحه اسناد است. مدل‌ها از تنظیمات سرور تعیین می‌شوند. مدیریت مدل، نسخه‌بندی خودکار سند، SSO، ثبت‌نام و تاریخچه ماندگار کامل صوتی خارج از این تحویل‌اند. استخراج تصویر، fallback صفحه PDF و جدول‌های DOCX نمونه در محدوده MVP هستند؛ OCR عمومی همه فرمت‌ها الزام نیست.
تصمیم ساده‌سازی: جدول نسخه‌ها حذف شده است. هر آپلود یک سند مستقل می‌سازد؛ قطعات و کار پردازش مستقیم به آن متصل‌اند. برای اصلاح محتوا، فایل جدید آپلود و پس از آماده‌شدن جای سند فعال قبلی انتخاب می‌شود. Retry همان سند را دوباره پردازش می‌کند و سند تازه نمی‌سازد. تعداد جدول‌ها اکنون ۱۴ است.
## ۳. تقسیم کار سیستم با زبان ساده
| جزء | کار واقعی |
| --- | --- |
| مرورگر | فرم‌ها، نمایش چت و منابع، میکروفون و پخش صوت |
| API | دریافت درخواست، بررسی هویت و دسترسی و برگرداندن نتیجه |
| سرویس گفتگو | اجرای نوبت متنی، نگهداری سابقه و مدیریت درخواست تکراری |
| مدل | تشخیص نیاز به سرچ و تولید پاسخ با شواهد |
| ابزار سرچ | اجرای جست‌وجو در اسناد آماده و فعال؛ مدل SQL اجرا نمی‌کند |
| Worker | استخراج متن و ساخت قطعات و Embedding در پس‌زمینه |
| PostgreSQL + pgvector | کاربران، اسناد، کارها، بردارها، گفتگوها و وضعیت‌ها |
| مخزن فایل | نگهداری فایل اصلی آپلودشده |
| کنترل‌کننده Live | ساخت و بستن جلسه صوتی و اجرای ابزارها در بک‌اند |
همه ماژول‌های بک‌اند در یک کدبیس‌اند. Worker یک فرایند جدا از API است تا پردازش فایل، پاسخگویی UI را معطل نکند. صف کارها همان جدول دیتابیس است و در این فاز Redis یا RabbitMQ لازم نشده است.
## ۴. سناریو اول: مدیر سند ساعات کاری را آپلود می‌کند
فرض کنیم فرمت فایل نمونه در روز اول تأیید شده و متن آن قابل استخراج است. سند می‌گوید: «پنجشنبه‌ها از ساعت ۸ تا ۱۲».
| قدم | درخواست یا رفتار | اتفاق در دیتابیس | نتیجه UI |
| --- | --- | --- | --- |
| ۱ | `POST /api/v1/auth/login` | نشست احراز هویت در `auth_sessions` | ورود موفق |
| ۲ | `POST /api/v1/documents` با فایل | یک سند مستقل در `documents` و کار متصل به همان سند در `ingestion_jobs` ساخته می‌شود | «در صف پردازش» |
| ۳ | Worker کار را می‌گیرد | وضعیت job و سند processing می‌شود | «در حال پردازش» |
| ۴ | استخراج، قطعه‌بندی و Embedding | هنوز قطعات ناقص وارد سرچ نمی‌شوند | کاربر منتظر وضعیت آماده می‌ماند |
| ۵ | انتشار موفق | قطعات در `document_chunks`؛ سند ready؛ job succeeded | «آماده، غیرفعال» |
| ۶ | مدیر فعال می‌کند | مجموعه انتخاب‌شده با `PATCH /knowledge-selection` تغییر می‌کند | «فعال برای پاسخگویی» |
آپلود پاسخ ۲۰۲ می‌دهد؛ یعنی فایل و کار پردازش ثبت شده‌اند، نه اینکه مدل همان لحظه آن را می‌شناسد. فرانت با `GET /documents/{id}` وضعیت را می‌خواند.
سند آماده ولی غیرفعال قابل سرچ نیست. این دو وضعیت مستقل‌اند: یکی می‌گوید پردازش انجام شده، دیگری می‌گوید سازمان اجازه استفاده داده است.
در MVP جدید تصویر و صفحه اسکن‌شده نمونه با vision/OCR پردازش می‌شوند. اگر خروجی ناخوانا، ناقص یا از نظر عدد/استثنا غیرقابل اعتماد باشد، failed با دلیل روشن نمایش داده می‌شود؛ متن خالی یا غیرقابل اعتماد ready نمی‌شود.
## ۵. سناریو دوم: کاربر متنی سؤال می‌پرسد
کاربر می‌نویسد: «پنجشنبه تا چه ساعتی باز هستید؟»
۱. فرانت با `POST /conversations` یک گفتگوی text می‌سازد.
۲. سؤال را همراه `conversation_id` و `client_request_id` به `POST /chat` می‌دهد.
۳. بک‌اند یک `turn` به معنی «یک نوبت سؤال و پاسخ» ثبت می‌کند. سؤال کاربر در `messages` ذخیره می‌شود.
۴. مدل می‌بیند برای پاسخ به اطلاعات سازمان نیاز دارد و ابزار `search_knowledge` را با کوئری «ساعت کاری پنجشنبه» صدا می‌زند.
۵. ابزار هویت سازمان را از نشست معتبر می‌گیرد؛ خود مدل نمی‌تواند سازمان یا اسناد مجاز را عوض کند.
۶. سؤال به بردار تبدیل می‌شود و قطعات مرتبط از اسناد آماده و فعال پیدا می‌شوند.
۷. متن قطعه، شناسه سند و قطعه و محل منبع به مدل برمی‌گردد.
۸. مدل پاسخ می‌دهد: «طبق سند ساعات کاری، پنجشنبه‌ها تا ساعت ۱۲ باز هستیم.»
۹. پاسخ در `messages` و ارجاع آن در `citations` ذخیره می‌شود؛ turn به answered می‌رسد.
۱۰. UI پاسخ و منبع را نمایش می‌دهد.
```mermaid
sequenceDiagram
participant U as User
participant B as Backend
participant M as AI Model
participant S as Search Tool
participant D as Database
U->>B: Text question
B->>D: Save running turn
B->>M: Question and tool schema
M->>B: Search tool call
B->>S: Execute authorized search
S->>D: Retrieve selected ready chunks
D-->>S: Evidence
S-->>B: Content and sources
B->>M: Tool result
M-->>B: Grounded answer
B->>D: Save answer and citations
B-->>U: Answer and sources
```
ایجنتیک بودن همین است: برای «سلام» لازم نیست سرچ انجام شود، اما برای ادعای مربوط به سند سازمان شواهد لازم است. ابزار جواب نهایی را تولید نمی‌کند؛ اطلاعات لازم را می‌آورد.
## ۶. سناریو سوم: اطلاعات پیدا نمی‌شود یا سؤال مبهم است
| سؤال/وضعیت | رفتار درست | وضعیت نوبت |
| --- | --- | --- |
| «پنجشنبه تا چند باز هستید؟» و سند مربوط موجود است | پاسخ مستند | answered |
| «اون روز تا چند باز هستید؟» بدون زمینه کافی | «منظورتان کدام روز است؟» | needs_clarification |
| «مبلغ پاداش امسال چقدره؟» و سندی درباره آن نیست | اعلام نبود اطلاعات در اسناد | insufficient_information |
| سرویس Embedding قطع است | اعلام مشکل سرویس؛ نه ادعای نبود اطلاعات | failed |
تفاوت دو ردیف آخر مهم است: «جست‌وجو انجام شد و مدرک نبود» با «جست‌وجو نتوانست اجرا شود» یکی نیست. API و دیتابیس این تفاوت را حفظ می‌کنند تا UI پیام اشتباه نشان ندهد.
## ۷. سناریو چهارم: کاربر دوبار ارسال می‌زند یا پاسخ HTTP گم می‌شود
فرض کنیم سؤال ثبت شده و مدل در حال پاسخ است، ولی اینترنت مرورگر برای لحظه‌ای قطع می‌شود.
فرانت نباید فوراً یک سؤال جدید با شناسه جدید بسازد. همان `client_request_id` را نگه می‌دارد و از این مسیر وضعیت را می‌پرسد:
`GET /api/v1/conversations/{conversation_id}/turns/{client_request_id}`
- اگر running باشد، منتظر می‌ماند.
- اگر answered باشد، همان جواب ثبت‌شده را نمایش می‌دهد.
- اگر failed باشد، خطا را نشان می‌دهد؛ تلاش جدید آگاهانه با شناسه جدید انجام می‌شود.
- اگر هنوز رکورد ثبت نشده باشد، همان درخواست و همان شناسه را دوباره می‌فرستد.
در دیتابیس ترکیب گفتگوی مشخص و شناسه درخواست یکتا است. بنابراین دو بار ارسال یک درخواست، دو نوبت مستقل نمی‌سازد. این همان کاربرد عملی Idempotency است.
اگر سؤال با همان شناسه عوض شود، ۴۰۹ می‌گیریم؛ این خطای برنامه فرانت است. اگر در یک گفتگو یک نوبت در حال اجرا باشد و سؤال جدید با شناسه دیگر برسد، `CONVERSATION_BUSY` برمی‌گردد. در فاز یک نوبت‌های یک گفتگو هم‌زمان اجرا نمی‌شوند.
## ۸. سناریو پنجم: کاربر صوتی سؤال می‌پرسد
۱. کاربر دسترسی میکروفون می‌دهد و گفتگوی voice متعلق به خودش ایجاد می‌کند.
۲. `POST /api/v1/voice/sessions` شناسه جلسه و مسیر WSS برنامه را می‌دهد؛ قرارداد SDP قبلی برای MVP جدید کنار گذاشته شده است.
۳. بک‌اند با کلید سروری به Gemini Live مستقیم وصل می‌شود و دستور فارسی، ابزار `search_knowledge` و transcription قابل پشتیبانی را تنظیم می‌کند.
۴. صوت کاربر از مرورگر به بک‌اند و سپس جلسه Gemini می‌رود.
۵. برای سؤال وابسته به سند، مدل ابزار را فراخوانی می‌کند؛ بک‌اند با هویت و محدوده خودش همان سرچ مشترک متن را اجرا می‌کند.
۶. قطعات واقعی و محل منبع به مدل می‌رسند؛ مدل می‌تواند بدون فراخوانی جداگانه مدل متنی پاسخ فارسی صوتی بسازد.
۷. UI صوت، متن پاسخ موجود و منابع را نشان می‌دهد. منبع بازیابی‌شده لزوماً استناد دقیق جمله صوتی نیست.
۸. وقفه کاربر پخش صف‌شده را متوقف می‌کند؛ نتیجه دیررس ابزار نوبت لغوشده پاسخ تازه نمی‌سازد.
**بک‌اند جلسه و انتقال صوت را مدیریت می‌کند و کلید دائمی در مرورگر نیست.** نام رویدادها و مسیر WSS در کاتالوگ، پیشنهاد فنی‌اند و هنوز پیاده‌سازی نشده‌اند. OpenRouter برای مقایسه متن/vision است؛ دریافت فایل صوتی یا خروجی صوتی stream به معنی پشتیبانی جلسه دوطرفه Gemini Live نیست.
در قطعی، UI وضعیت را نشان می‌دهد؛ جلسه قدیمی تعیین تکلیف و جلسه جدید ساخته می‌شود. بازیابی بی‌وقفه زمینه و تاریخچه ماندگار کامل صوتی خارج از فاز یک‌اند. متن موجود در همان جلسه نگه داشته می‌شود؛ متن ناموجود یا ناقص صریحاً مشخص است و به جای گفتار واقعی جعل نمی‌شود. تلفظ و فهم فارسی، اسم‌های محلی، تاریخ، درصد و مبلغ باید با صوت واقعی بررسی شود.
## ۹. سناریو ششم: سازمان سند ساعات کاری را عوض می‌کند
سند قدیمی ساعت پایان را ۱۲ نوشته؛ سند جدید ساعت ۱۳ را اعلام می‌کند.
۱. مدیر سند جدید را جداگانه آپلود می‌کند و منتظر آماده‌شدن می‌ماند.
۲. سند قدیمی را از انتخاب خارج و جدید را فعال می‌کند. API می‌تواند مجموعه نهایی انتخاب‌ها را در یک تغییر ثبت کند؛ هر دو فایل سند مستقل‌اند و هیچ شماره نسخه یا جدول نسخه‌ای نداریم.
۳. شمارنده تغییر منابع افزایش پیدا می‌کند.
۴. چون سندی حذف شده، شمارنده اعتبار زمینه گفتگو هم تغییر می‌کند.
۵. گفتگوهای قبلی سازمان برای سؤال جدید stale می‌شوند؛ UI دکمه «گفتگوی جدید» نشان می‌دهد.
۶. جلسه‌های صوتی قبلی بسته می‌شوند تا زمینه قدیمی دوباره استفاده نشود.
۷. گفتگوی جدید سؤال را از سند جدید جواب می‌دهد: ساعت ۱۳.
برای سرعت و سادگی فاز یک، هنگام حذف یک منبع فعال همه گفتگوهای قدیمی سازمان برای ادامه نامعتبر می‌شوند؛ نه فقط گفتگوهایی که قطعاً از همان سند استفاده کرده‌اند. این رفتار محافظه‌کارانه است و در فاز بعد می‌توان دقیق‌ترش کرد.
پاسخ قبلی که «۱۲» گفته، در تاریخچه همان پاسخ قبلی باقی می‌ماند؛ با تغییر سند بازنویسی نمی‌شود. صوتی که قبلاً پخش شده هم قابل پس‌گرفتن نیست. کنترل ما روی استفاده بعدی از اطلاعات است.
## ۱۰. سه عدد revision چه فرقی دارند؟
| فیلد | چه وقت تغییر می‌کند؟ | کاربرد |
| --- | --- | --- |
| revision | تغییر نام یا دستورالعمل دستیار | جلوگیری از ذخیره هم‌زمان روی تنظیمات قدیمی |
| knowledge_revision | تغییر مجموعه اسناد فعال | مشخص‌کردن مجموعه دانش هر نوبت |
| access_epoch | خارج‌کردن سند فعال یا حذف آن | نامعتبرکردن زمینه‌های قدیمی گفتگو |
مثال: فقط سندی اضافه کنیم، knowledge_revision تغییر می‌کند و سؤال بعدی آن را می‌بیند. سند فعالی را برداریم، access_epoch هم تغییر می‌کند تا اطلاعات قدیمی از حافظه گفتگو دوباره وارد پاسخ نشوند.
اگر دو مدیر هم‌زمان تنظیمات را باز کنند، درخواست دوم که revision قدیمی دارد ۴۰۹ می‌گیرد. UI تنظیمات تازه را می‌خواند تا تغییر مدیر اول ناخواسته از بین نرود.
## ۱۱. سناریو هفتم: Worker وسط کار قطع می‌شود
Worker فایل را گرفته و مشغول Embedding است. فرایند قطع می‌شود.
کار در دیتابیس مانده است. Worker برای مدت محدود اجازه پردازش داشته که Lease نام دارد. بعد از تمام‌شدن این مدت، کار قابل گرفتن دوباره است. دریافت‌کننده جدید یک claim token تازه می‌گیرد.
اگر Worker قبلی دیر برگردد، توکنش دیگر معتبر نیست و حق انتشار ندارد. Worker جدید می‌تواند پردازش را از ابتدا انجام دهد. در این فاز ادامه‌دادن دقیق از هر قطعه را پیاده نمی‌کنیم؛ انتشار نهایی یکپارچه است و محدودیت یکتایی، ساخت قطعات تکراری را می‌گیرد.
برای خطای موقت، تلاش مجدد با فاصله انجام می‌شود. برای فایل خراب، ادامه دادن بی‌فایده است و failed نمایش داده می‌شود. مدیر فقط برای خطای قابل تلاش مجدد می‌تواند Retry بزند. خود Retry هم کلید یکتا دارد تا دوبار کلیک، دو بار بودجه تلاش را بازنشانی نکند.
## ۱۲. چرا این جدول‌ها لازم‌اند؟
| گروه | جدول‌ها | مثال ساده |
| --- | --- | --- |
| هویت | organizations، users، auth_sessions | چه کسی وارد شده و چه اجازه‌ای دارد؟ |
| تنظیمات | organization_settings | اسم دستیار و نسخه تنظیمات و منابع چیست؟ |
| اسناد | documents | این فایل چیست، کجا ذخیره شده و آماده پاسخگویی است؟ |
| پردازش | ingestion_jobs | چه فایلی منتظر است و چرا پردازشش شکست خورده؟ |
| دانش | document_chunks | کدام تکه متن و بردار باید جست‌وجو شود؟ |
| گفتگو | conversations، turns، messages | کدام مکالمه، کدام نوبت، چه سؤال و پاسخی؟ |
| شواهد | tool_calls، citations | چه سرچ‌هایی انجام شد و جواب به چه منبعی استناد کرد؟ |
| صوت | live_sessions | کدام جلسه وصل است و چرا بسته شده؟ |
| تغییرات مدیریتی | audit_events | چه کسی سند را غیرفعال یا Retry کرده؟ |
تعداد جدول‌ها به معنی تعداد سرویس یا برنامه جدا نیست. برای مثال سه جدول گفتگو لازم‌اند چون «گفتگو»، «اجرای یک سؤال» و «متن پیام» وضعیت و مسئولیت متفاوت دارند. نگهداری صرف متن پیام برای تشخیص timeout و درخواست تکراری کافی نیست.
فایل اصلی در مخزن فایل است؛ مسیر تولیدشده آن در خود سند ذخیره می‌شود. بردارها در pgvector داخل همان PostgreSQL هستند. فایل صوتی خام ذخیره نمی‌کنیم.
## ۱۳. سناریو هشتم: حذف سند
مدیر حذف را تأیید می‌کند. ابتدا سند از سرچ خارج و deleted ثبت می‌شود. اگر فعال بوده، زمینه گفتگوها هم نامعتبر می‌شود. پاسخ API صریحاً می‌گوید پاک‌سازی فیزیکی منتظر سیاست نگهداری است؛ «حذف از پاسخگویی» را با «پاک‌شدن فوری تمام فایل‌ها و تاریخچه» یکی نمی‌کنیم.
دلیل نگه‌داشتن شناسه منبع این است که جواب قدیمی همچنان قابل ردیابی باشد. اینکه متن قطعات، فایل اصلی یا excerptها چه زمانی واقعاً پاک شوند، باید از سازمان مشخص شود. در این اسناد عدد دلخواه برای مدت نگهداری ننوشته‌ایم.
منبع غیرفعال/حذف‌شده در نمایش منابع جدید متن قابل دسترس ارائه نمی‌کند. تاریخچه پاسخ‌های قبلی متعلق به کاربر، طبق دسترسی تاریخچه باقی می‌ماند؛ وارد زمینه گفتگوی جدید نمی‌شود.
## ۱۴. برنامه عملی توسعه و معیار پیشرفت
| بازه | چیزی که باید بتوانیم نشان دهیم |
| --- | --- |
| روز ۱ | بررسی نمونه‌ها، کیفیت استخراج، اعتبار حساب و شبکه و پروفایل‌های مدل |
| روز ۲ | ورود و آپلود ماندگار |
| روز ۳ | استخراج/QC و ایندکس متن، تصویر و جدول نمونه؛ خطای روشن برای خروجی غیرقابل اعتماد |
| روز ۴ | سرچ فقط روی اسناد فعال با منبع درست |
| روز ۵ | پاسخ مستند متنی و بازیابی نوبت؛ سپس صوت مستقل Gemini Live و متن پاسخ |
| روز ۶ | اتصال ابزار دانش به Live، follow-up، تغییر موضوع و وقفه فارسی |
| روز ۷ | چهار صفحه و دموی کامل روی HTTPS |
| روز ۸ تا ۱۰ | اصلاح کیفیت، تست شکست‌ها، آماده‌سازی نسخه ارائه |
این زمان‌بندی تضمین بدون شرط نیست. اگر UI از صفر و فایل‌ها پیچیده باشند یا اتصال مدل Live حل نشود، ریسک زمان بالا می‌رود. اول امکانات تزئینی و اختیاری حذف می‌شوند؛ دسترسی صحیح و سه قابلیت اصلی نباید پنهانی حذف شوند.
## ۱۵. چک‌لیست ارائه و پذیرش
- کاربر عادی نتواند تنظیمات یا اسناد را تغییر دهد و گفتگوی دیگری را بخواند.
- فایل آماده‌نشده وارد سرچ نشود.
- سؤال مستند جواب و منبع درست داشته باشد.
- سؤال بی‌پاسخ با اطلاعات ساختگی جواب داده نشود.
- ارسال تکراری، نوبت یا کار پردازشی تکراری نسازد.
- قطع Worker باعث از دست رفتن کار پذیرفته‌شده نشود.
- مکالمه صوتی فارسی واقعاً از Gemini Live مستقیم، WSS مدیریت‌شده بک‌اند و بازیابی سند استفاده کند؛ متن پاسخ موجود و منابع در UI دیده شوند.
- خروج کاربر، پایان جلسه یا تغییر منابع فعال، وضعیت Live را درست تغییر دهد.
- تاریخچه متن بعد از restart باقی بماند.
- دمو روی شبکه و مرورگر محیط ارائه تمرین شده باشد.
۱۵ تا ۲۰ سؤال مرجع از اسناد واقعی آماده می‌کنیم؛ برای هرکدام جواب مورد انتظار و قطعه منبع را می‌نویسیم. نتیجه اجرای متن و صوت جدا ثبت می‌شود. این مجموعه کوچک، تضمین دقت عمومی محصول نیست.
## ۱۶. مواردی که قبل از شروع باید قطعی شوند
| سؤال | مسئول پیشنهادی |
| --- | --- |
| فایل‌های واقعی چه فرمت و ساختاری دارند و حداکثر اندازه چیست؟ | صاحب محصول + توسعه‌دهنده |
| مدل Live منتخب اتصال و کنترل ابزار مورد نیاز را پشتیبانی می‌کند؟ | توسعه‌دهنده/تیم AI با آزمایش واقعی |
| مدل Embedding و تعداد ابعادش چیست؟ | تیم AI قبل از مایگریشن بردار |
| محیط HTTPS و دسترسی به ارائه‌دهنده آماده است؟ | توسعه‌دهنده/زیرساخت |
| مدت نشست و نگهداری فایل/گفتگو چقدر است؟ | صاحب محصول/سازمان |
| شروع کار و تاریخ ارائه دقیقاً چه روزی است؟ | مدیر پروژه |
## ۱۷. نحوه استفاده از اسناد توسط توسعه‌دهنده
ابتدا Implementation Guide برای ترتیب کار و مرز ماژول‌ها؛ سپس API Catalog برای DTO و هماهنگی فرانت؛ بعد Database Design برای مدل‌های ORM و مایگریشن. سناریوهای این گزارش باید تبدیل به تست‌های یکپارچه شوند.
قراردادها با جهت 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 و تأیید دانش/اعداد، دروازه‌های وابسته را مسدود می‌کنند تا واقعاً بررسی شوند.