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