feat(backend): deliver Phase 3 document and voice integration

Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
11linear11
2026-10-09 17:43:52 -04:00
parent 9be47191d6
commit a73a496c54
67 changed files with 5988 additions and 234 deletions
@@ -1,15 +1,18 @@
# RAG Assistant — Phase 1 Implementation Guide
Current voice decision (2026-10-09): **Gemini Live is temporarily the sole voice
provider because an OpenAI Realtime voice key is unavailable.** The validated
backend Gemini model/voice configuration is shared by reservation, stream and
operator smoke. No OpenAI voice key is required. Extraction/embedding providers,
frozen profiles, measured calibration and canonical search are unchanged.
The provider-independent browser audio/events, direct document/chunk identities
and durable owner/replay/revocation rules remain authoritative. Historical
OpenAI checkpoints below remain historical. Gemini interruption closes safely
where native sample-level context truncation cannot be verified; seamless
barge-in is not certified. See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
one backend adapter. Gemini remains the temporary default because an OpenAI
Realtime voice key is unavailable.** Reservation, authenticated stream and
operator smoke share the selected model/voice/profile. Only the selected voice
key is required; there is no fallback or frontend provider selector. Legacy
PROVIDER and existing GEMINI_* settings remain supported; conflicting provider
aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change
embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions.
Pinned reservations cannot switch providers on connection or replay. Gemini
interruption requiring unverified context truncation closes safely; OpenAI keeps
its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](../guides/realtime-agent-phase2-repair.md).
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
@@ -44,7 +47,7 @@ declared format/structure/resource limits must run without developer changes.
| Upload | New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count |
| QC | Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state |
| Retrieval | Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need |
| Voice | Direct OpenAI Realtime audio over backend WSS; shared LangChain knowledge tool |
| Voice | Backend-selected Gemini Live/OpenAI Realtime audio over WSS; shared LangChain knowledge tool |
| Evidence | Current-session provider transcripts/sources; durable owned session/tool diagnostics |
| Deferred | Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI |
| Settings | Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities |
@@ -126,7 +129,7 @@ Resolve `(user_id, organization_id, role)` exclusively from the session. Check o
embedding components. Validate original checksum and actual provider identity.
A legacy profile is dispatched explicitly, never silently reinterpreted.
6. Retain exact extraction output for review/reuse, then stage every embedding.
The current PageBlockExtractor requires review for PDF pages and vision output;
The current PageBlockExtractor requires review for direct PDF pages and, by default, OCR/vision output;
this is an actual implementation gate, not an optional UI decoration.
7. Publish all chunks and ready/succeeded state in one fenced transaction.
Verify token, unexpired lease, original/profile, non-deletion, complete vectors,
@@ -144,7 +147,8 @@ be indexed. Crash recovery must not attach uncommitted or stale candidates.
D06 shows retained candidates to the admin. D07 records approval/rejection of
the exact evidence digest and required checks. New OCR output has a different
review identity and requires a new decision. Server validates/recomputes digests;
review identity and requires a new decision when the frozen supervisor gate or
independent validation requires review. Server validates/recomputes digests;
client supplied text, paths, profile identity and reviewer identity are forbidden.
Use job/document locks and current failed-candidate identity for decisions.
Decisions neither activate nor mark a document ready.
@@ -180,8 +184,9 @@ Factual preparation validates the whole retained source structure before selecti
groups. Explicit heading ancestry associates governing headings and introductory
conditions with each descendant Q&A pair; existing whole-group context stays
exclusive to that pair. Preserve conditions, negation, exceptions and their real
locators in every affected draft. Ambiguous unheaded preambles, detached prose or
unresolved relationships fail visibly instead of becoming unrestricted answers.
locators in every affected draft. Leading unheaded titles/preambles are top-level
document context and accompany each approved pair, including pairs under later
headings. Detached prose after pairs or unresolved relationships still fail visibly.
Factual review exposes that context from the same immutable complete artifact.
Reviewer identity/checks/note are bounded review metadata, not machine quality
warnings; administrator prose never changes extraction readability decisions.
@@ -227,7 +232,7 @@ If the browser times out, it queries the turn by client request ID. Retrying the
## 9. Live lifecycle
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to direct OpenAI Realtime WSS, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
Create a fresh owned `mode=voice` conversation. Persist a session reservation before remote setup, then connect the backend to the pinned Gemini Live/OpenAI Realtime WSS profile, install Persian instructions and `search_knowledge`, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.
Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.
@@ -292,3 +297,45 @@ LangChain, existing embedding reuse and direct OpenAI Realtime are confirmed dir
Exact-output retention/review, FAQ inclusion decisions and their forward schema/
HTTP mechanisms in this revision are implementation proposals made concrete for
review, not already implemented behavior or approval of every fact in a file.
### OCR supervisor deployment policy (2026-10-09)
`INGEST_OCR_REVIEW_REQUIRED` defaults to true and is backend-only. New ingestion
jobs freeze the boolean in `processing_profile.extraction.ocr_review_required`
(the existing immutable document-owned snapshot for its one job). Workers and
retries use that snapshot; absent fields in legacy profiles mean true. Preserve
existing profile bytes/digests; do not backfill applied records. False permits
clean OCR/vision output that passes existing automatic validation without a human
extraction decision. It never waives non-OCR review, warning/integrity/coverage
checks, independent factual-corpus approval, or explicit knowledge selection.
Automatic extraction remains quality_decision=passed; mixed inspected/automatic
PDFs use partially_reviewed with annotations only for inspected locators. Neither
automatic OCR nor its portions in mixed PDFs creates a human review
annotation/audit record. Ready publication remains inactive. Retained pending or
rejected candidates still block retry; deployment changes cannot waive them.
F01 capabilities.ocr_review_required is current deployment policy; D03 reports
frozen ocr_review_required, review_state and extraction_quality_decision.
See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
### Phase 3/4 recognition and transport-testing amendment (2026-10-09)
Vision complete=false and recognition warnings preserve nonempty legible candidate
blocks with their diagnostics. They force exact-output extraction review even when
the job's frozen OCR supervisor policy is false. They are not complete validated
artifacts until genuine review approves completeness and the other required checks.
Malformed/empty/truncated native output, invalid provenance/relationships, unreadable
source text and bounded input/output violations remain fatal. Warning wording alone
is not evidence of corrupt source text. Retained approved candidates resume without
repeating vision; separate factual approval and explicit knowledge selection remain.
VOICE_TRANSPORT_TESTING defaults false. Explicit true permits authenticated voice
transport testing without finalized calibration, after configured embedding adapter
construction validates credentials, identity and request limits without inference.
Uncalibrated reservations pin transport_testing and embedding identity in the existing
execution_profile JSON and expose calibration_status=uncalibrated through create,
recovery and poll. Shared canonical retrieval still returns CALIBRATION_REQUIRED
with no evidence; no arbitrary threshold or synthetic calibration is installed.
Current policy/profile must still match the reservation on stream admission; policy
changes cannot silently upgrade, downgrade or switch a reserved provider. Health
remains provider-free. Real voice/retrieval quality acceptance remains separate.