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