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.