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
@@ -0,0 +1,483 @@
# راهنمای اتصال UI به backend دستیار اسناد و مکالمهٔ صوتی
تاریخ تهیه: ۲۰۲۶-۱۰-۰۹
این فایل برای توسعه‌دهندهٔ frontend تهیه شده است تا UI موجود را به backend فعلی وصل کند. قرارداد مرورگر برای Gemini Live و OpenAI Realtime یکسان است؛ انتخاب provider و کلیدهای آن فقط سمت backend قرار دارند. فعلاً Gemini پیش‌فرض موقت است.
این راهنما دستور اتصال است و به معنی پذیرش اجراشدهٔ UI، کیفیت گفتار فارسی یا سخت‌افزار مرورگر نیست. نمونه‌های JSON شکل داده را نشان می‌دهند؛ شناسه، digest، revision و مسیر نشست باید از پاسخ واقعی سرور گرفته شوند.
## ۱. اطلاعاتی که تیم backend باید تحویل دهد
پیش از تست مشترک، جدول زیر با اطلاعات محیط واقعی تکمیل شود. جای‌خالی‌ها نباید به تنظیمات اجرایی تبدیل شوند.
| مورد | مقدار مورد توافق |
| --- | --- |
| آدرس backend قابل‌دسترسی از ماشین اجرای پراکسی | `TO_BE_PROVIDED`؛ پیش‌فرض محلی Compose: `http://localhost:8080` |
| آدرس و Origin دقیق UI | `TO_BE_PROVIDED`؛ نمونهٔ محلی: `http://localhost:5173` |
| نسخهٔ مشترک backend و فایل‌های نمونه | commit یا snapshot مورد توافق: `TO_BE_PROVIDED` |
| حساب تست administrator | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| حساب تست user | نام کاربری و رمز از مسیر جداگانه و امن تحویل شوند |
| فایل نمونه برای آپلود و بازبینی انسانی | `TO_BE_PROVIDED` |
| سند آماده و انتخاب‌شده برای تست مکالمه | شناسهٔ واقعی و سؤال دارای پاسخ در همان سند: `TO_BE_PROVIDED` |
| آمادگی صوت و calibration | تیم backend وضعیت واقعی را اعلام کند؛ UI نیز F01 را بخواند |
| زمان تست مشترک مرورگر، میکروفن و بلندگو | `TO_BE_PROVIDED` |
اگر frontend و backend روی دو ماشین جدا اجرا می‌شوند، `localhost` در target پراکسی به ماشین frontend اشاره می‌کند. آدرس قابل‌دسترسی backend را جایگزین کنید.
کلید provider، رمز دیتابیس و فایل `.env` حاوی اسرار وارد کد، build، تنظیمات عمومی یا storage مرورگر نشوند. UI برای ورود فقط اطلاعات حساب کاربردی دریافت می‌کند.
## ۲. فایل‌های همراه و مرجع قرارداد
این فایل Markdown همراه با فایل‌های زیر تحویل شود. لینک‌ها نسبت به محل این فایل در repository هستند؛ برای تحویل خارج از repository، فایل‌های اشاره‌شده را نیز ارسال کنید.
| فایل | کاربرد |
| --- | --- |
| [راهنمای backend فاز ۳](realtime-agent-phase3-handoff.md) | قرارداد اسناد، review، retry، selection و تنظیمات توسعه |
| [راهنمای صوت](frontend-voice-integration-example.md) | جریان صوت، کنترل‌ها، رویدادها و recovery |
| [API catalog](../specifications/RAG-Phase1-API-Catalog.md) | قرارداد مرجع API؛ فقط endpointهای MVP در این تحویل استفاده شوند |
| [document-client.js](../../examples/document-client.js) | helper عملیات اسناد و configuration |
| [voice-client.js](../../examples/voice-client.js) | helper ورود، ساخت نشست، صوت و cleanup |
| [voice-audio-worklet.js](../../examples/voice-audio-worklet.js) | capture و playback و گزارش نمونه‌های واقعاً پخش‌شده |
| [vite-proxy.config.js](../../examples/vite-proxy.config.js) | پراکسی توسعهٔ HTTP و WebSocket |
helperها نمونهٔ توسعه‌اند؛ مدیریت صفحات، وضعیت UI، خطا، درخواست‌های لغوشده و ذخیرهٔ تلاش‌های نامطمئن بر عهدهٔ frontend است. در صورت اختلاف با یک پاسخ واقعی، کد خطا و request ID را به تیم backend بدهید؛ پاسخ یا قرارداد را خودسرانه بازتعریف نکنید.
## ۳. محدودهٔ UI و مسئولیت طرفین
| قابلیت | مسئولیت UI | مسئولیت backend |
| --- | --- | --- |
| ورود و نقش | فرم ورود، نگهداری وضعیت کاربر، نمایش قابلیت‌های مجاز | cookie، اعتبارسنجی حساب و مجوز هر درخواست |
| اسناد | آپلود، نمایش وضعیت، مرور شواهد، approve/reject، retry و selection | ذخیرهٔ immutable، پردازش worker، کنترل review و انتشار |
| صوت | میکروفن، playback، transcript، منابع، توقف و recovery | اتصال provider، ابزار جست‌وجو، lifecycle و کنترل دسترسی |
| خطا | پیام قابل‌فهم و اقدام مناسب، نگهداری شناسهٔ خطا | error envelope امن و correlation |
`admin` به اسناد، review، retry و selection دسترسی دارد. `admin` و `user` می‌توانند configuration را بخوانند و مکالمهٔ صوتی متعلق به خودشان را بسازند. پنهان‌کردن دکمه در UI جای کنترل مجوز سرور را نمی‌گیرد.
در MVP فعلی UI برای ثبت‌نام عمومی، مدیریت حساب، حذف سند، ویرایش configuration، انتخاب مدل/provider، public text chat یا تاریخچهٔ کامل و پایدار transcript ساخته نشود. routeهای deferred در API catalog به معنی route قابل‌استفاده نیستند.
## ۴. تنظیم اتصال محلی
### پراکسی same-origin
در مثال فعلی UI روی `http://localhost:5173` است و API از میزبان روی `8080` در دسترس خواهد بود. مرورگر تمام HTTPها را به `/api/v1/...` روی Origin خود UI می‌فرستد. پراکسی همان مسیر `/api` را بدون حذف prefix به backend منتقل می‌کند.
نمونهٔ Vite را در configuration موجود ادغام کنید؛ تنظیمات دیگر پروژه را جایگزین نکنید:
```js
export default {
server: {
host: 'localhost',
port: 5173,
strictPort: true,
proxy: {
'/api': {
target: 'http://127.0.0.1:8080',
ws: true,
changeOrigin: false
}
}
}
};
```
`changeOrigin: false`، Host مرورگر را حفظ می‌کند. تیم backend برای این مثال محلی تنظیم کند:
```dotenv
TRUSTED_HOSTS=["localhost:5173","localhost:8080"]
TRUSTED_ORIGINS=["http://localhost:5173"]
COOKIE_SECURE=false
```
Host دوم برای دسترسی مستقیم محلی به health و schema است؛ اجرای mutation از Origin دیگری نیازمند تنظیم صریح همان Origin است. در محیط HTTPS، cookie باید Secure باشد و اتصال صوت WSS باشد. از wildcard برای CORS همراه credentials استفاده نشود. مرورگر برای میکروفن و AudioWorklet به secure context، مثل HTTPS یا localhost، نیاز دارد.
پیش‌فرض Docker Compose: API داخل container روی `8000` و روی میزبان با `${API_PORT:-8080}` منتشر می‌شود. اگر `API_PORT` عوض شد، target پراکسی را هماهنگ کنید. برای اجرای مستقیم مطابق این مثال، تیم backend از یک API process روی `8080` و worker جداگانه استفاده کند:
```sh
python -m app.server --host 0.0.0.0 --port 8080
python -m app.worker
```
آماده‌سازی دیتابیس، migration، حساب‌ها، storage، credentials و calibration وظیفهٔ تیم backend است. شروع worker می‌تواند provider call ایجاد کند و باید مطابق مجوز محیط انجام شود. frontend چند API worker یا reload برای محیط تست صوت درخواست نکند.
### تشخیص اتصال
با Host مجاز و backend آماده:
- `GET http://localhost:8080/health/live`: پاسخ `200` و `{"status":"ok"}`.
- `GET http://localhost:8080/health/ready`: پاسخ `200` هنگام readiness و `503` هنگام آماده‌نبودن.
- `GET http://localhost:8080/openapi.json`: schema محیط جاری.
- `http://localhost:8080/docs`: نمایش schema؛ اجرای درخواست‌های تعاملی نیز باید الزامات Origin/CSRF را رعایت کند.
پراکسی نمونه فقط `/api` را منتقل می‌کند؛ برای health از آدرس مستقیم مجاز استفاده کنید، یا مسیر health را صریحاً در پراکسی خود اضافه کنید. هیچ‌کدام از healthها گواه کیفیت provider نیستند.
## ۵. احراز هویت و قرارداد HTTP
تمام routeهای جدول‌های بعدی زیر `/api/v1` هستند.
| عملیات | درخواست | نتیجه |
| --- | --- | --- |
| ورود | `POST /auth/login` با `username` و `password` | `200`، cookie و user/CSRF/expiry |
| خواندن یا refresh هویت | `GET /me` | `200` با همان شکل هویت؛ یا `401` |
| خروج | `POST /auth/logout` بدون body | `204` بدون JSON |
| خواندن قابلیت‌ها | `GET /configuration` | `200` برای هر دو نقش |
نمونهٔ ورود:
```json
{"username":"<test-account>","password":"<password-from-login-form>"}
```
شکل پاسخ ورود و `/me`:
```json
{
"user": {
"id": "<server-user-id>",
"username": "<actual-username>",
"role": "admin",
"organization_id": "<server-organization-id>"
},
"csrf_token": "<server-csrf-token>",
"expires_at": "<server-ISO-timestamp>"
}
```
- cookie به نام `rag_session`، HttpOnly است؛ آن را از JavaScript نخوانید و token جایگزین نسازید.
- در معماری same-origin از `credentials: 'same-origin'` استفاده کنید.
- mutationهای authenticated، شامل upload و ساخت نشست، `X-CSRF-Token` می‌خواهند. CSRF از login یا `/me` گرفته شود. login خودش trusted Origin می‌خواهد.
- پس از reload ابتدا `/me` را بخوانید. روی `401` وضعیت authenticated را پاک و ورود مجدد را نمایش دهید.
- برای `FormData`، Content-Type را دستی ننویسید؛ browser باید boundary را بسازد. برای JSON از `application/json` استفاده کنید.
- پاسخ `204` را با `response.json()` نخوانید.
- `organization_id`، actor، reviewer یا مدل را برای تحمیل scope در درخواست‌ها اضافه نکنید.
configuration شامل `revision`، `assistant_name`، `instruction` و `capabilities` است. UI از مقادیر واقعی `text`، `voice`، `captions`، `supported_upload_types`، `max_upload_bytes`، `max_pdf_pages` و مشخصات audio استفاده کند. در صورت `voice=false`، شروع صوت غیرفعال و پیش‌نیاز به تیم backend اعلام شود؛ این flag گواه کیفیت گفتار نیست. `ocr_review_required` در configuration سیاست فعلی deployment است، نه سیاست همهٔ اسناد قبلی.
## ۶. جریان اسناد برای administrator
| عملیات | route | موفقیت و نکته |
| --- | --- | --- |
| آپلود | `POST /documents` | `202`؛ multipart؛ required `Idempotency-Key` |
| فهرست | `GET /documents` | `200`؛ pagination و فیلتر |
| polling جزئیات | `GET /documents/{document_id}` | `200`؛ وضعیت واقعی processing/review/retry |
| شواهد pending | `GET /documents/{document_id}/extraction-review` | `200`؛ paginated |
| preview | مسیر `preview_path` در پاسخ شواهد | تصویر authenticated؛ بدون path ساخته‌شده توسط UI |
| تصمیم انسانی | `POST /documents/{document_id}/extraction-review/decisions` | `200`؛ JSON و required `Idempotency-Key` |
| retry همان job | `POST /documents/{document_id}/retry` | `202`؛ بدون body و required `Idempotency-Key` |
| خواندن selection | `GET /knowledge-selection` | `200` |
| جایگزینی selection | `PATCH /knowledge-selection` | `200`؛ کل مجموعه با expected revision |
### آپلود و وضعیت
body فقط یک `file` و `title` اختیاری دارد. title حداکثر ۲۰۰ کاراکتر است؛ محدودیت فایل را از configuration بخوانید. UI اعتبارسنجی اولیه انجام دهد، ولی format و محتوا را سرور تصمیم می‌گیرد.
```js
const uploadKey = crypto.randomUUID();
const uploaded = await documents.upload(file, title, uploadKey);
// uploaded.document_id و uploaded.job_id را از پاسخ واقعی نگه دارید.
```
هر upload با کلید تازه یک سند مستقل می‌سازد. برای نتیجهٔ نامطمئن همان File، title و کلید را نگه دارید و همان درخواست را replay کنید؛ تولید کلید جدید می‌تواند سند دیگری بسازد. کلید در header `Idempotency-Key` ارسال می‌شود. replay موفق header `Idempotency-Replayed: true` دارد؛ تغییر payload زیر همان کلید، `409 IDEMPOTENCY_CONFLICT` می‌دهد.
تا زمانی که document وضعیت `queued` یا `processing` دارد polling کنید؛ فاصلهٔ پیشنهادی دو ثانیه است، در tab پنهان آهسته‌تر شود. polling با خروج از صفحه لغو شود و پاسخ دیررس نتواند سند جدیدِ انتخاب‌شده در UI را بازنویسی کند. درصد پیشرفت ساختگی نمایش ندهید؛ از `job.stage` و وضعیت واقعی استفاده کنید.
| وضعیت یا فیلد پاسخ | رفتار UI |
| --- | --- |
| `queued` / `processing` | نمایش انتظار و مرحله، ادامهٔ polling |
| `failed` و `review_required=true` | دریافت و نمایش شواهد pending |
| `failed` و `job.can_retry=true` | امکان retry صریح؛ علت خطا نیز نمایش داده شود |
| `failed` و `review_state=rejected` | نمایش رد؛ retry خودکار انجام نشود |
| `ready` و `is_active=false` | آمادهٔ انتخاب؛ هنوز وارد جست‌وجو نشده است |
| `searchable=true` | سند طبق پاسخ فعلی سرور قابل جست‌وجو است |
`job.error` ممکن است null یا شامل `code`، `message` و `retryable` باشد. امکان retry را از `job.can_retry` بگیرید؛ صرف `retryable=true` مجوز retry خودکار نیست.
فهرست اسناد `limit` پیش‌فرض ۲۰ و حداکثر ۱۰۰ دارد؛ فیلترهای `status` و `is_active` پشتیبانی می‌شوند. پاسخ شامل `items`، `next_cursor` و `knowledge_revision` است. cursor opaque است؛ آن را تغییر ندهید و در query URL encode کنید.
### review و سیاست OCR
شواهد review پیش‌فرض ۱۰ و حداکثر ۲۰ item در هر صفحه دارد. از `next_cursor` برای ادامه استفاده کنید. اگر مجموعه پس از تصمیم‌ها تغییر کرد و cursor نامعتبر شد، pendingها را دوباره از ابتدای مجموعه بخوانید. item شامل digest واقعی، `review_kind`، blocks، `required_checks` و preview احتمالی است.
UI برای انسان، متن دقیق، گروه‌های Q&A و تصویر موجود را نمایش دهد. تصمیم approve/reject و یادداشت از انسان گرفته شود؛ روی دکمهٔ approve تمام چک‌ها به‌طور خودکار تأیید نشوند.
```json
{
"evidence_sha256": "<digest-from-current-review-item>",
"decision": "approve",
"checked": ["<actual-required-check-names-confirmed-by-human>"],
"note": "<nonblank-human-review-note>",
"excluded_group_ids": []
}
```
برای approval، مجموعهٔ `checked` باید دقیقاً با چک‌های موردنیاز item تطبیق کند. note غیرخالی و حداکثر ۲۰۰۰ کاراکتر است. برای rejection نیز note لازم است؛ چک‌های تکمیل‌نشده را تأییدشده وانمود نکنید.
در review استخراج، `excluded_group_ids` باید خالی باشد. در `factual_corpus` فقط گروه‌های کامل موجود را می‌توان exclude کرد؛ دست‌کاری متن اصلی یا حذف نیمهٔ سؤال/پاسخ مجاز نیست. approval باید دست‌کم یک گروه factual واجد شرایط باقی بگذارد و placeholderهای نامعتبر را وارد corpus نکند. `preview_path` برای factual ممکن است null باشد.
سیاست `INGEST_OCR_REVIEW_REQUIRED` فقط تنظیم backend است، default آن true است و در هر job ثابت می‌ماند. UI از فیلدهای همان document استفاده کند:
- `ocr_review_required`: سیاست frozen آن سند.
- `review_required`: وجود تصمیم pending.
- `review_state`: `not_evaluated`، `not_required`، `pending`، `approved` یا `rejected`.
- `extraction_quality_decision`: null، `passed`، `reviewed` یا `partially_reviewed`؛ بدون ساختن ادعای تأیید انسانی.
false بودن سیاست OCR، review factual یا reviewهای دیگر را حذف نمی‌کند. UI toggle برای تغییر این سیاست ندارد. در preview از URL سرور با cookie استفاده کنید؛ path ذخیره‌سازی یا URL provider ساخته نشود.
approve به‌تنهایی retry، انتشار یا activation نمی‌کند. پس از تکمیل pendingها، detail را بخوانید و در صورت `job.can_retry=true`، retry صریح با کلید مستقل ارسال کنید. صفحات بعدی استخراج نیز ممکن است review تازه بخواهند. retry همان سند و همان job را ادامه می‌دهد. retry با body غیرخالی، `422 VALIDATION_ERROR` است.
### selection
برای اضافه یا حذف یک سند، ابتدا K01 را بخوانید، مجموعهٔ کامل جدید را بسازید و K02 را ارسال کنید:
```json
{
"expected_revision": 3,
"document_ids": ["<all-selected-document-ids-in-the-desired-new-set>"]
}
```
`expected_revision` در مثال فرضی است و باید از آخرین K01 بیاید. PATCH یک delta نیست؛ ارسال فقط یک ID می‌تواند بقیهٔ اسناد را حذف کند. شناسه‌ها unique و سندها ready باشند.
بعد از timeout یا `REVISION_CONFLICT` ابتدا K01 را دوباره بخوانید. درخواست قبلی ممکن است commit شده باشد؛ آن را کورکورانه تکرار نکنید. حذف سند فعال می‌تواند epoch را تغییر دهد و نشست‌های صوت قبلی را ببندد. UI منابع قدیمی را معتبر نمایش ندهد و ساخت مکالمهٔ تازه را پیشنهاد کند.
## ۷. ساخت و کنترل نشست صوت
| عملیات | route | کاربرد |
| --- | --- | --- |
| C01 | `POST /conversations` | ساخت owned conversation با `mode=voice`؛ `201` |
| V01 | `POST /voice/sessions` | رزرو session؛ `201` یا replay با `201/202` |
| V02 | `GET /voice/sessions/{session_id}` | وضعیت، diagnostics امن و toolهای اخیر |
| V03 | `GET /voice/sessions/by-request/{client_request_id}` | بازیابی رزرو بدون اتصال provider |
| V04 | `POST /voice/sessions/{session_id}/close` | بستن صریح بدون body؛ `200` |
| media | WebSocket روی `stream_path` دریافتی | یک اتصال فعال؛ cookie و Origin |
ابتدا C01 و سپس V01:
```json
{"client_request_id":"<conversation-request-uuid>","mode":"voice"}
```
```json
{"conversation_id":"<id-from-C01>","client_request_id":"<session-request-uuid>"}
```
این دو request ID جدا هستند و در JSON می‌آیند؛ با header کلید عملیات سند اشتباه نشوند. پاسخ V01 شامل `session_id`، `conversation_id`، `status`، `stream_path`، `expires_at` و `poll_url` است. مسیر اتصال را از `stream_path` بگیرید؛ route provider یا path ثابت اختراع نکنید.
برای نتیجهٔ نامطمئن، payload و IDهای همان تلاش حفظ و replay شوند. V03 برای reconciliation است و provider جدید باز نمی‌کند. نشست connected یا terminal اتصال media را از نو احیا نمی‌کند؛ recovery به معنی seamless reconnect نیست.
دو WebSocket هم‌زمان برای یک session ساخته نشود. پس از loss، وضعیت را از V02/V03 بگیرید، رزرو قدیمی را ببندید و با اقدام صریح کاربر مکالمه و نشست تازه بسازید. هنگام refresh صفحه، helper فعلی تلاش ایجاد را فقط در حافظهٔ همان instance نگه می‌دارد؛ اگر recovery بین reload لازم است، UI باید IDها و payload همان تلاش را بدون provider secret نگه دارد و ابتدا با سرور reconcile کند.
## ۸. راه‌اندازی helper و فایل صوت
در پروژهٔ UI، دو client module را در مسیر source قرار دهید و worklet را به‌عنوان asset مستقل از همان Origin سرو کنید. برای Vite می‌توان worklet را در `public/voice-audio-worklet.js` گذاشت و URL زیر را به constructor داد. متن worklet باید JavaScript باشد؛ fallback HTML مربوط به SPA برای این URL برنگردد.
```js
import {VoiceClient} from './integrations/voice-client.js';
import {DocumentClient} from './integrations/document-client.js';
// handleVoiceEvent و showFailure توابع UI خودتان هستند.
const voice = new VoiceClient(handleVoiceEvent, '/voice-audio-worklet.js');
const documents = new DocumentClient(voice);
async function signIn(username, password) {
const identity = await voice.login(username, password);
const configuration = await documents.configuration();
return {identity, configuration};
}
async function prepareVoice() {
const configuration = await documents.configuration();
if (!configuration.capabilities.voice) throw new Error('VOICE_UNAVAILABLE');
voice.newCreationAttempt(); // فقط برای یک تلاش واقعاً تازه
return voice.reserve();
}
// ابتدا prepareVoice موفق شود؛ سپس دکمهٔ شروع برای کاربر فعال شود.
// connect مستقیماً از gesture کاربر فراخوانی شود تا AudioContext مجاز باشد.
startButton.addEventListener('click', () => {
void voice.connect().catch(showFailure);
});
stopButton.addEventListener('click', () => {
void voice.close().catch(showFailure);
});
// logoutButton در handler خود voice.logout() را فراخوانی کند.
// route/component هنگام خروج باید voice.close() را await کند و خطا را مدیریت کند.
```
`prepareVoice` را با نشست فعال دوباره اجرا نکنید. پس از timeout ایجاد، به‌جای `newCreationAttempt` از `retryCreation()` همان تلاش استفاده کنید. شروع و cleanup باید برای هر connection مالکیت مشخص داشته باشند؛ جواب دیررس permission یا callback نشست قدیمی نباید نشست جدید را ببندد.
متدهای اصلی نمونه:
| client | متدها |
| --- | --- |
| VoiceClient | `login`، `refreshIdentity`، `newCreationAttempt`، `reserve`، `retryCreation`، `recover`، `poll`، `connect`، `close`، `logout`، `freshSession` |
| DocumentClient | `configuration`، `upload`، `list`، `poll`، `review`، `decide`، `retry`، `selection`، `replace` |
برای recovery صوت، اگر از `freshSession()` استفاده می‌کنید آن را با gesture مناسب کاربر اجرا کنید و روی browser واقعی مجازبودن AudioContext را تست کنید. UI نباید پس از refresh یا قطع شبکه خودکار میکروفن را باز کند.
## ۹. قرارداد صوت و رویدادها
صوت در هر دو جهت raw mono signed PCM16 little-endian با نرخ **۲۴۰۰۰ Hz**، یک channel و بدون WAV header است؛ معادل ۴۸۰۰۰ byte در ثانیه. WebM، Opus یا blob خروجی MediaRecorder را روی این stream نفرستید. capture دستگاه باید به نرخ قرارداد تبدیل شود. helper و worklet این مسیر را پیاده می‌کنند و AudioContext با نرخ نامعتبر را رد می‌کنند.
میکروفن فقط پس از `session_ready` شروع به ارسال کند. سقف هر پیام binary در نمونهٔ فعلی ۹۶۰۰ byte است و طول باید sample-aligned باشد. capture و playback نمونه دارای دو سقف مستقل ۹۶۰۰۰ byte و ۱۰۰ پیام هستند. در adaptation، هر دو کنترل و cleanup آن‌ها حفظ شوند؛ ظرفیت پرشده باید با failure امن پایان یابد، نه با حذف بی‌صدای PCM و ادامهٔ همان context.
| رویداد سرور | رفتار UI |
| --- | --- |
| `session_ready` | session ID و audio format را تطبیق دهید؛ آماده‌شدن واقعی را نمایش دهید |
| `user_speech_started` | turn جدید را با `turn_ref` ثبت کنید |
| `transcript` | برحسب turn و role، partial را به‌روز و completed را نهایی کنید |
| `sources` | منابع را به همان turn/tool call مرتبط کنید؛ منابع turnهای دیگر مخلوط نشوند |
| `audio_started` | `audio_ref` فعلی را برای binaryهای بعدی تعیین کنید |
| `audio_ended` | پایان generation همان audio ref؛ به معنی شنیده‌شدن نیست |
| `turn_interrupted` | صوت صف‌شده را flush و progress نهایی مصرف‌شده را گزارش کنید |
| `error` | خطای turn یا session را با قواعد راهنمای صوت مدیریت کنید |
شکل readiness:
```json
{
"type": "session_ready",
"session_id": "<reserved-session-id>",
"input_audio": {"encoding":"pcm_s16le","sample_rate":24000,"channels":1},
"output_audio": {"encoding":"pcm_s16le","sample_rate":24000,"channels":1}
}
```
شکل transcript:
```json
{"type":"transcript","turn_ref":"<server-turn-ref>","role":"assistant","text":"<actual-transcript>","status":"completed"}
```
تنها کنترل JSON از سمت client:
```json
{"type":"playback_progress","audio_ref":"<server-audio-ref>","played_ms":120}
```
`played_ms` مقدار تجمعی واقعی است؛ از sampleهای مصرف‌شدهٔ worklet محاسبه می‌شود، نه elapsed timer، دریافت شبکه یا طول کل فایل. flush یا admission به معنی شنیدن نیست. مقدار را برای هر `audio_ref` جدا نگه دارید و گزارش نهایی interruption را بفرستید. helper این کار را انجام می‌دهد؛ UI کانال progress موازی با شمارش حدسی اضافه نکند.
برای sources از `source_ref`، title و location دریافتی استفاده کنید. location می‌تواند page یا section خالی داشته باشد. منبع، excerpt، لینک دانلود یا مسیر اصل سند را از خودتان نسازید؛ API دانلود اصل سند در این تحویل وجود ندارد. در polling، `available=false` یعنی excerpt قبلی معتبر نیست و نباید همچنان نمایش داده شود.
خطای canonical search برای turn واجد شرایط می‌تواند با توضیح صوتی امن ادامه یابد. خطای setup، transport، overflow، authority یا context sync نشست را متوقف می‌کند. fatal بودن را فقط از `retryable` استنتاج نکنید؛ رفتار helper و قرارداد guide را حفظ کنید. UI ابزار backend را خودش دوباره اجرا نمی‌کند.
### محدودیت‌های فعلی که در UX رعایت شوند
- Gemini فعلاً truncation نمونه‌دقیقِ تأییدشده برای context ندارد؛ interruption می‌تواند نشست را ببندد و نیازمند مکالمهٔ تازه باشد. seamless barge-in وعده داده نشود.
- ورودی commitنشده، شامل سکوت، سقف ده ثانیه دارد. UI ack یا مرز گفتار ساختگی برای دورزدن این محدودیت نفرستد؛ شکست و recovery را مطابق سرور مدیریت کند.
- transcript و منابع متعلق به نشست فعلی‌اند؛ history کامل و ماندگار وعده داده نشود.
- logout، خروج از صفحه و توقف باید trackهای میکروفن، worklet، AudioContext و WebSocket را آزاد کنند. در توقف عمدی، progress نهایی و V04 پیش از بسته‌شدن transport انجام شوند؛ `voice.close()` این ترتیب را اجرا می‌کند.
## ۱۰. خطا و بازیابی
شکل HTTP error:
```json
{
"error": {
"code": "REVISION_CONFLICT",
"message": "Request could not be completed.",
"request_id": "<correlation-uuid>",
"retryable": false
}
}
```
header `X-Request-ID` همان correlation را فراهم می‌کند؛ بعضی خطاها `details` دارند. متن خام error را به‌عنوان تنها UX استفاده نکنید؛ برحسب code پیام فارسی مناسب نمایش دهید. لایهٔ request در UI، status، code و request ID را حفظ کند. DocumentClient این فیلدها را ارائه می‌کند؛ VoiceClient.request نمونه فقط code/status را در exception نگه می‌دارد و برای diagnostics کامل باید metadata امن response را در adaptation حفظ کنید.
| کد یا وضعیت | اقدام |
| --- | --- |
| `401 AUTH_REQUIRED` | cleanup رسانه و ورود مجدد؛ `/me` برای وضعیت هویت |
| `403 CSRF_INVALID` | در صورت باقی‌بودن هویت، refresh از `/me`؛ replay فقط با همان کلید/payload و پس از رفع علت |
| `403 FORBIDDEN` | بررسی نقش یا Host/Origin؛ درخواست تکراری بدون تغییر علت مفید نیست |
| `404 NOT_FOUND` | ID مخفی/حذف‌شده یا رزرو پیدا نشده؛ ابتدا نوع عملیات و تلاش ایجاد را بررسی کنید |
| `409 IDEMPOTENCY_CONFLICT` | payload زیر کلید تغییر کرده؛ تلاش اصلی را reconcile کنید |
| `409 REVISION_CONFLICT` | K01 جدید و اقدام کاربر بر اساس state تازه |
| `409 DOCUMENT_NOT_READY` | موارد rejected در details را نمایش دهید؛ selection ناقص نفرستید |
| `409 EXTRACTION_REVIEW_PENDING` | pendingها را بخوانید و review انسانی را تکمیل کنید |
| `409 DOCUMENT_NOT_RETRYABLE` | detail تازه و شرایط retry؛ دکمه بر اساس can_retry |
| `409 REVIEW_STALE` / `REVIEW_ALREADY_DECIDED` | شواهد و وضعیت تازه؛ approval قدیمی را روی output جدید کپی نکنید |
| `409 LIVE_SESSION_BUSY` | نشست موجود را reconcile کنید؛ اتصال دوم نسازید |
| `CONTEXT_REVOKED` / `CONVERSATION_STALE` | context و خروجی قدیمی را کنار بگذارید؛ نشست تازه، بدون کپی context revoked |
| `413 FILE_TOO_LARGE` / `PAYLOAD_TOO_LARGE` | محدودیت فایل یا envelope درخواست؛ تغییر اندازه به معنی تغییر payload است |
| `415 UNSUPPORTED_FILE_TYPE` | فایل مجاز طبق configuration انتخاب شود |
| `422 INVALID_FILE` / `VALIDATION_ERROR` | مشکل file یا شکل درخواست را اصلاح کنید |
| `429 RATE_LIMITED` | `Retry-After` را رعایت کنید؛ از retry burst جلوگیری کنید |
| `503 DEPENDENCY_UNAVAILABLE` / `CALIBRATION_REQUIRED` | آمادگی backend بررسی شود؛ نتیجهٔ mutation ممکن است نامطمئن باشد |
| قطع WebSocket یا API restart | cleanup، polling/reconciliation و تلاش تازهٔ صریح؛ ادامهٔ context فرضی ممنوع |
انتظار برای دریافت JSON در backend ۱۵ ثانیه و برای body خالی retry پنج ثانیه است؛ محدودیت envelope تصمیم ۶۰٬۱۵۱٬۰۷۲ byte و selection یک MiB است. این‌ها تضمین مدت تکمیل processing نیستند. تایم‌اوت کوتاه client به معنی rollback نیست. helper صوت HTTP deadline پنج ثانیه دارد؛ helper اسناد deadline اختصاصی ندارد و UI باید سیاست timeout و لغو خود را با حفظ semantics عملیات اضافه کند.
هیچ retry خودکار نباید کلید تازهٔ upload/decision/retry بسازد. K02 کلید عملیات سند ندارد و با revision کنترل می‌شود. پس از timeout آن K01 بخوانید. در logout حتی اگر V04 شکست خورد، تلاش برای A02 و پاک‌سازی محلی انجام شود؛ helper فعلی این کار را می‌کند.
در diagnostics فقط زمان، نوع عملیات، status، code، request/session/turn/audio refs لازم ثبت شوند؛ رمز، cookie، CSRF، audio، متن سند و متن خصوصی transcript در log ثبت نشوند.
## ۱۱. معیارهای تست مشترک UI و backend
| سناریو | نتیجهٔ مورد انتظار |
| --- | --- |
| ورود admin و user، reload و `/me` | هویت واقعی و مجوز صحیح؛ CSRF تازه |
| logout هنگام صوت | توقف میکروفن و پخش، revoke حساب session و UI خارج‌شده |
| user روی عملیات اسناد | دسترسی UI محدود و رد واقعی سرور |
| آپلود فایل تازه | document/job واقعی و مستقل، ابتدا inactive |
| timeout یا double-click آپلود | replay با همان کلید؛ سند تکراری ناخواسته ساخته نشود |
| فایل نامعتبر یا بیش‌ازحد | پیام برحسب code و حفظ امکان انتخاب فایل جدید |
| processing و تغییر صفحه | وضعیت واقعی، polling قابل‌لغو و عدم نمایش پاسخ دیررس برای سند دیگر |
| review چندصفحه‌ای و preview | شواهد واقعی، cookie، چک انسانی و تصمیم evidence-bound |
| approve/reject و retry | approve خودکار منتشر نکند؛ rejected ادامه نگیرد؛ retry همان job باشد |
| OCR اختیاری و factual | UI سیاست frozen سند و نیاز مستقل factual را رعایت کند |
| selection و revision conflict | ready-only، کل مجموعه، re-read پس از conflict یا timeout |
| قطع پاسخ C01/V01 | همان تلاش با UUID و payload قبلی replay/reconcile شود |
| شروع صوت با کلیک و permission ردشده | صدای واقعی یا پیام قابل‌فهم، بدون میکروفن یا context رهاشده |
| سؤال فارسی و پیگیری | transcript و sourceها به turn صحیح متصل باشند؛ شنیده‌شدن انسانی بررسی شود |
| پاسخ بی‌مدرک یا خطای جست‌وجو | منبع ساختگی نشان داده نشود؛ خطای turn با fatal session اشتباه نشود |
| interruption هنگام جست‌وجو و playback | صوت قدیمی متوقف، progress واقعی، recovery مطابق provider منتخب |
| قطع provider، شبکه و API restart | cleanup و state سرور روشن؛ اتصال خودکار به همان نشست فرض نشود |
| حذف سند از selection هنگام صوت | نشست قدیمی بی‌اعتبار و excerpt revoked پنهان شود |
| مرورگر یا tab دوم | نشست دیگر مجوز مالکیت ایجاد نکند؛ دو اتصال یک session رد شوند |
برای هر نتیجه، نوع محیط/browser، نسخهٔ مشترک، حساب/نقش بدون رمز، سناریو، زمان و request IDهای امن ثبت شود. provider و hardware واقعی جدا از mock بررسی شوند. هیچ خانهٔ اجرا‌نشده به‌عنوان pass ثبت نشود.
## ۱۲. متن آماده برای واگذاری به عامل frontend
```text
Integrate the existing UI with the supplied backend handoff and client examples.
Read frontend-backend-connection-handoff.md and its linked current contracts.
Use a same-origin /api proxy supporting HTTP and WebSocket. Wire login/logout,
identity refresh, role-aware documents, upload and polling, human evidence review,
same-job retry, full-set knowledge selection, and owned voice-session lifecycle.
Serve the worklet from the UI origin with the correct asset URL. Preserve the
24 kHz mono PCM16LE contract, bounded audio queues, actual playback progress,
interruption behavior, generation ownership, and complete resource cleanup.
Preserve cookie/CSRF authentication, server-returned capabilities and permissions,
idempotency keys and immutable payloads across ambiguous failures, selection
revision recovery, and fresh-session reconciliation after media/context loss.
Gemini interruption can require ending the old session and starting a fresh one.
Provider selection and secrets remain on the backend. Implement only MVP routes.
Do not invent endpoints, approvals, sources, processing percentages or transcript
history. Adapt the examples to the existing UI framework without changing the
backend contract. Preserve unrelated UI work.
Use the supplied accounts and approved files. Execute the shared test matrix on
the running backend and actual browser, within the approved provider-call budget.
Report changed files, actual checks, safe correlation evidence and unrun cases.
If a prerequisite is missing, name it and continue independent integration work.
Do not claim real voice or browser acceptance from mocked responses.
```
Explicit uncalibrated connectivity testing: set `VOICE_TRANSPORT_TESTING=true`
and restart the API. Configure a compatible embedding adapter, credentials and
bounded request limits first. Pending/missing calibration then permits voice
reservation and provider streaming; create/recovery/poll report
`calibration_status: "uncalibrated"`. F01 also reports the policy and calibration
status. Treat this as connectivity testing: shared search still returns
`CALIBRATION_REQUIRED` with no sources. Disable the policy for strict admission;
existing reservations remain pinned and may require a new session after policy or
calibration changes. No automatic provider switch, calibration or paid call occurs
when enabling the policy. Existing client examples tolerate the additive metadata;
the actual developer UI should display the status.
@@ -1,7 +1,7 @@
# Authenticated Gemini voice integration
# Authenticated voice integration
Gemini Live is temporarily the sole voice provider because an OpenAI Realtime
voice key is unavailable. Extraction, embeddings, calibration and canonical
The backend selects Gemini Live or OpenAI Realtime with `VOICE_PROVIDER`. Gemini
is the temporary default while an OpenAI Realtime voice key is unavailable. Extraction, embeddings, calibration and canonical
search retain their existing providers and frozen profiles. The browser never
receives a provider credential, event, model selector or private call ID.
@@ -13,7 +13,8 @@ same origin. This is a developer example, not a production interface.
import {VoiceClient} from './voice-client.js';
const client = new VoiceClient(event => console.log(event.type));
await client.login(username, password); // supply credentials from your local form
await client.reserve(); // retain request IDs for identical retries/recovery
client.newCreationAttempt(); // exposes IDs before C01 and retains immutable payloads
await client.reserve(); // after an ambiguous response: await client.retryCreation()
await client.connect(); // call from a user gesture permitting AudioContext
// On explicit stop: await client.close(); await client.poll();
// On media loss: await client.recover(); await client.freshSession();
@@ -23,7 +24,7 @@ await client.connect(); // call from a user gesture permitting AudioContext
`GET /api/v1/me` refreshes actual expiry and CSRF. HTTP mutations use the opaque
cookie and CSRF; WebSocket upgrade uses that cookie plus the browser's Origin.
The API accepts no bearer or query token. Preserve the same normalized payload
and request ID after ambiguous creation; V03 recovers without opening Gemini.
and request ID after ambiguous creation; V03 recovers without opening a provider connection.
Connected/terminal recovery does not restore media/provider context. Close the
old reservation before requesting a fresh conversation and session.
@@ -36,9 +37,20 @@ and sources are retrieved/current-session information, not durable full history.
The client waits for `session_ready` before opening the microphone. It verifies
an actual 24 kHz AudioContext, which resamples device capture; the worklet mixes
channels and emits aligned mono PCM16LE 480-byte frames. Unsupported context
rates fail explicitly. Sending is bounded by WebSocket buffered bytes. Ordered
rates fail explicitly. Capture enforces dual capacity bounds of 96000 raw PCM bytes
AND 100 messages across capture handoff and outgoing WebSocket buffering. The worklet
tracks both pending messages and pending bytes (rejecting with overflow if either limit
would be exceeded). Capture handoff does not falsely imply network completion: the client
polls socket.bufferedAmount and delivers `{type: 'accepted', bytes}` to the worklet only
upon verified conservative buffer drain (`captureBytes - bufferedAmount >= packetBytes`).
Capacity is released exactly once on verified drain or terminal cleanup. Ordered
binary playback belongs to the last audio_started reference and is sealed by
audio_ended. The playback worklet bounds samples and reports the floor of actual
audio_ended. The client reserves playback capacity before PCM conversion and counts pending
MessagePort handoffs. The worklet independently enforces 96000 raw PCM bytes AND
100 messages across references, retaining a partially consumed packet in the
message count. Consumed-sample acknowledgements release byte reservations; only
completed/discarded packets release message reservations, exactly once. Admission
and flush acknowledgements never imply heard audio. The worklet reports the floor of actual
consumed samples / 24, never estimated elapsed time or generated samples.
Interruption flushes queued audio and reports each reference's final consumed
position. Explicit close stops capture and tracks, flushes actual final playback progress
@@ -71,3 +83,122 @@ Technical fake-wire/worklet checks, retrieval quality and real-browser speech
acceptance are separate. Real microphone/Persian audio/network behavior remains
unverified until explicit provider opt-in, approved corpus, measured compatible
calibration and budgets are supplied. See the [repair report](realtime-agent-phase2-repair.md).
## Creation attempts and recovery
`newCreationAttempt()` explicitly selects new C01 and V01 request IDs and retains
C01's immutable payload before either request. `creationAttempt`,
`conversationRequestID` and `requestID` are inspectable after failure. Once C01's
response supplies the owned conversation ID, V01's immutable payload is stored
before sending V01. `retryCreation()` (or `reserve()` with the existing attempt)
replays identical payloads and IDs after a committed response is lost. Calls with
changed IDs require an explicit new attempt; payload mutation is rejected locally,
and changed payloads at the backend retain IDEMPOTENCY_CONFLICT behavior.
`recover()` uses V03 and never connects automatically; a lost C01 response may
precede V01, so recovery can return SESSION_NOT_FOUND until identical C01/V01 retry.
`freshSession()` explicitly closes/reconciles the old reservation, creates a new
attempt and connects. Retain the attempt in application storage if page reload
recovery is required; this example retains it only in the current JS instance.
## Backend configuration and supported startup
Gemini deployment (no OpenAI voice key required):
```dotenv
VOICE_PROVIDER=gemini
GEMINI_API_KEY=<server-only-key>
GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede
# GEMINI_PROXY=https://trusted-proxy.example:443
```
OpenAI deployment (no Gemini key required):
```dotenv
VOICE_PROVIDER=openai
OPENAI_REALTIME_API_KEY=<server-only-voice-key>
OPENAI_REALTIME_MODEL=gpt-realtime-mini
OPENAI_REALTIME_VOICE=shimmer
# OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443
```
Existing `GEMINI_*` names and legacy `PROVIDER` remain valid. Matching provider
aliases are accepted; conflicting `VOICE_PROVIDER`/`PROVIDER` across environment
and dotenv configuration fail. Explicit constructor settings otherwise take
priority over environment, then dotenv. `OPENAI_API_KEY` is not a voice alias:
embedding and other provider configuration remain independent. A compatible
measured `SEARCH_CALIBRATION_REPORT` and the existing origin/host/cookie settings
are still required. Do not put secrets in browser configuration. Model defaults
are compatibility defaults, not claims of current live service availability.
Reservation snapshots pin selected provider/model/voice/native rates plus search
profile; stream admission rejects a changed configuration. Durable V01 replay
still returns the original reservation without reinterpreting it.
```sh
.venv/bin/python -m app.server --host 0.0.0.0 --port 8000
# Separate ingestion process:
.venv/bin/python -m app.worker
```
Docker Compose uses the same API entrypoint. Run exactly one API process and no
API reload/multiple workers: media admission and runtime registry are process-local,
not distributed ownership. The ingestion worker is a separate process. For
production use trusted same-origin HTTPS/cookie settings and bounded reverse proxy
configuration; a proxy cannot substitute for backend message reassembly limits.
The supported entrypoint explicitly selects `BoundedWebSocketProtocol` over the
installed Uvicorn legacy WebSocket implementation, configured with validated
`LIVE_*` `RuntimeSettings`. It performs bounded reassembly using finite scratch
storage (`bytearray`) and an incremental UTF-8 decoder without retaining an unbounded
list of continuation metadata (preventing long empty-continuation memory retention).
Cancellation and connection termination release all scratch and assembly resources.
The parser rejects binary messages above `max_binary_message_bytes` (default 9600 bytes)
and UTF-8 text above `max_client_control_bytes` (default 4096 bytes), including aggregate
fragments, from declared frame lengths before reading payload/decoding. Compression is not
negotiated; any RSV/compression bit is rejected from the first two header bytes.
Total receive capacity strictly accounts for assembling, queued, and delivered/in-flight
messages against `max_queued_audio_messages` and `max_queued_audio_bytes`. Delivering a
message to the ASGI application retains its reservation until the next `recv()` call,
preventing an unmonitored runtime audio backlog. Queue depth is configured as
`max(1, max_queued_audio_messages - 2)` when the budget exceeds two, or one for small
budgets, preventing zero-capacity deadlocks on message budgets of one and two while
retaining deterministic wire backpressure. TCP/StreamReader scratch and kernel
buffers are separate finite transport buffers, not playback or commitment evidence.
Application checks remain defense in depth. Generic `uvicorn app.main:app`, `ws=auto`
and alternate/sansio backends are outside this supported policy. The selected legacy
backend is deprecated upstream: rerun real loopback tests on dependency upgrades;
replacement needs equivalent pre-payload enforcement, not renamed flags alone.
Authority-check saturation, timeout and SQL failure stop the session with
SEARCH_SATURATED, SEARCH_TIMEOUT and DEPENDENCY_UNAVAILABLE respectively; unverified
content/continuation is withheld. Verified revocation uses CONTEXT_REVOKED. Technical
failures persist `failed` with matching close reason/error code; committed terminal
logout/V04/expiry outcomes remain intact. Persistence retries bounded admission
saturation, but a database outage can still prevent a durable write and is logged.
## Continuous idle input limitation
The example continuously sends microphone PCM after readiness, including silence.
The frozen input-since-commit budget is 480000 bytes (10 seconds at 24 kHz PCM16LE).
Without verified native commitment, exactly 480000 bytes are accepted; the next
sample fails LIVE_BUFFER_OVERFLOW and closes. Native input consumption/transport
send is not commitment. This behavior is deterministic for an idle Gemini fake
with no activity boundary and applies to uncommitted admission for either adapter.
Longer continuous idle operation remains a product/provider-contract decision.
This example does not gate silence, fabricate commitment or add browser activity
controls. Use explicit stop/close and a fresh eligible session after overflow;
do not assume uninterrupted idle capture or seamless Gemini barge-in is supported.
Automated fake-provider/loopback/worklet results prove technical boundaries only.
Real provider access, measured retrieval quality, Persian speech, microphone,
heard audio and browser/hardware acceptance require their separate explicit opt-ins
and prerequisites; frontend readiness is not certified.
## Document workflow integration
Use the [Phase 3 HTTP handoff](realtime-agent-phase3-handoff.md) and delivered
DocumentClient with this VoiceClient. F01 exposes current OCR policy; document
polling exposes its frozen policy and actual review state. Automatic OCR admission
does not imply human review, factual authority, readiness or activation. Read K01
before replacing selection; removal revokes active voice context.
@@ -0,0 +1,172 @@
# Ingestion and voice admission repair — 2026-10-09
This scoped implementation supersedes the relevant ingestion/admission blockers
in the [Phase 4 operational report](realtime-agent-phase4-acceptance.md).
It does not certify real provider quality, browser audio or public HTTPS/WSS,
and does not complete Phase 4. No paid calls were made during this repair.
## Observable behavior
Initial unstyled FAQ titles and introductory paragraphs are document-wide context.
Every included pair retains that context, its text and original locators, including
pairs under later formal headings. Explicit heading ancestry and exclusive pair
context remain; detached prose after pairs and unresolved relationships still fail.
Factual authority approval is independent of extraction and remains mandatory.
The original extraction is never shortened or rewritten to make ingestion pass.
Gemini/OpenRouter recognition complete=false or warnings preserve nonempty legible
blocks. Global diagnostics and an explicit incomplete-recognition marker are retained
as block metadata, never injected into source text. These force the existing exact
extraction review even if the job's frozen OCR supervisor policy is false. Pending
review publishes no chunks. Approval/rejection uses existing D06/D07, source/profile/
evidence digests, backend reviewer identity, checks and deduplication. Approved retry
resumes the same job/candidate without repeating vision. Human completeness approval
must be genuine: missing content is a reason to reject, not an invitation to guess.
Malformed/empty responses, native truncation/blocking, model/provenance/relationship
violations, unreadable source text and resource limits remain fatal. OpenRouter now
also rejects multiple choices and explicit non-stop finish reasons. Warning wording
alone, including uncertainty about a margin, is a review diagnostic. Source text
containing replacement characters or unresolved PDF font identifiers is still invalid.
`VOICE_TRANSPORT_TESTING=false` remains the deployment default. Explicit true permits
transport testing without finalized offline calibration. V01 constructs configured
embedding transport after replay recovery, validating identity, credentials and
request limits without inference. The existing session execution-profile JSON pins
embedding identity and `mode: transport_testing`, with no distance or calibration ID.
Create/recovery/poll expose `calibration_status: uncalibrated`; calibrated reservations
report calibrated, and legacy reservations without search metadata report unknown.
F01 exposes the status and testing policy, and does not advertise testing availability
with an invalid embedding request policy. The delivered example client accepts these
additive fields; actual developer UI integration remains pending.
Authenticated WebSocket admission still checks Origin, owner/auth session, expiry,
access epoch, provider/model/voice and exact frozen search profile before opening a
provider connection. Disabling testing rejects an uncalibrated stream before provider
invocation. Replays keep their original identity and diagnostic status. Calibration
or policy changes cannot silently turn an existing reservation into another mode.
Shared canonical search still returns error/CALIBRATION_REQUIRED with no sources;
no invented fallback threshold, calibration report or alternate retrieval is created.
Operators can test streaming and greetings without claiming document-grounded answers.
## Acceptance and reproduction
Regression sources:
- `tests/unit/test_ingestion_admission_repairs.py`: 100-pair title/condition retention,
independent factual approval, unstyled Word introduction, both native vision
adapters' incomplete/global/block diagnostics, fatal OpenRouter output, pending
cutoff policy and search-service construction without uncalibrated evidence.
- `tests/integration/test_ingestion_admission_repairs.py`: real isolated database,
zero publication before review, D07 replay, same-job D04 resume without a second
vision call, inactive ready publication, Word/text factual review, authenticated
Gemini/OpenAI synthetic streaming, reservation replay and policy-disable rejection,
safe F01 diagnostics and configured embedding availability.
- Existing vision/OCR/source tests were updated only where the requested contract
changes their expected behavior. Genuine corrupt source text remains terminal;
detached FAQ prose and all worker/tenant/replay/fencing coverage remain.
Commands from the repository root (synthetic provider tests, no paid work):
```sh
.venv/bin/python -m pytest tests/unit/test_ingestion_admission_repairs.py tests/unit/test_phase5_repairs.py tests/unit/test_gemini_vision.py tests/unit/test_ocr_policy.py tests/unit/test_phase3_repairs.py -q -p no:cacheprovider --tb=short
.venv/bin/python -m pytest -m 'not postgres' -q -p no:cacheprovider --tb=short
docker run --rm -d --name rag-admission-regression-test --tmpfs /var/lib/postgresql/data -e POSTGRES_PASSWORD=fixture -e POSTGRES_DB=rag_admission_test -p 127.0.0.1:55469:5432 pgvector/pgvector:pg16
export TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55469/rag_admission_test
.venv/bin/python -m pytest tests/integration/test_ingestion_admission_repairs.py --require-postgres -q -p no:cacheprovider --tb=short
.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Final regression run reuses the two unchanged large-review cases that passed above.
.venv/bin/python -m pytest -m postgres --require-postgres -q -k 'not test_large_eligible_review_persists_and_replays' -p no:cacheprovider --tb=short --junitxml=/tmp/admission-postgres-final.xml
docker stop rag-admission-regression-test
git diff --check
```
The approved original DOCX also passed an offline `PageBlockExtractor.extract_for_review`
and `factual_context_units` diagnostic: **201 blocks, 100 pairs, all 201 review blocks**,
and the initial block appears in every pair context. Original SHA-256:
`6ce416719802136d16c82e153bf0671af5bb87b441cc5fed144ebd253d647f23`.
No database connection, human approval, publication or provider invocation was made.
The diagnostic used an inert explicit database URL because the real `.env` lacks a
host-run database URL. This is structural repair evidence, not factual acceptance.
Initial provider-free regression attempts failed settings validation inside the
socket-restricted sandbox; permitted execution outside it resolved that prerequisite.
The first complete run then found old warning-only terminal assertions (including
its nested isolation-suite run). Two PostgreSQL warning-only assertions also described
the superseded contract. Revised tests require review for diagnostics and terminal
failure for genuinely corrupt text. Final results are recorded below.
## Remaining runtime acceptance
Real Gemini Live and OpenAI audio quality were not run. Neither adapter was switched
or removed; Gemini remains the temporary default. OpenAI still requires its dedicated
key. Recognition changes were tested with deterministic native response fixtures;
the prior paid infographic attempt was not repeated to spend credits. The developer's
actual frontend remains under development, and browser/hardware/public deployment
acceptance remains not_run. Pending real calibration, human decisions and unseen labels
remain explicit quality prerequisites even when transport testing is enabled.
The real `.env` still needs its compatible database/request-limit configuration before
its backend transport can operate; changing admission does not repair or fabricate
those settings. Set the explicit testing flag and restart only after configuring them.
Health routes never construct or invoke providers. Applied migrations 0001–0005,
original inputs, stored profiles, tenant isolation, atomic publication, request keys
and lease fencing are preserved; no database schema changes or dependencies added.
## Executed results
- Focused final unit command above: **124 passed**, 4.36 s. New repair source:
**16 passed**, 1.56 s; broader extraction plus new source: **56 passed**, 3.99 s.
- Final complete provider-free suite: **1767 passed**, two existing Windows-path
skips, 403 PostgreSQL cases deselected at collection, 25 existing warnings,
**168.38 s**. Its nested ambient-configuration isolation suite also passed.
- New final database repair source: **7 passed**, 16.72 s. Earlier six-scenario
version passed in 12.60 s; final six plus existing F01 checks passed **8**, 19.37 s.
Strengthened corrupt-text database regressions: **2 passed**, 1.94 s.
- Complete initial database run: **401 passed / 2 obsolete assertion failures**,
zero skips, 1763 deselected, four warnings, **680.43 s**. Both existing
`test_large_eligible_review_persists_and_replays[False/True]` cases passed in
this run. Final recheck excludes only those two already executed unchanged
cases, includes the updated terminal-text assertions and newly added F01 case,
and produces per-case durations in `/tmp/admission-postgres-final.xml`. This
reuse is explicit, not a claim of a single final all-cases green invocation.
Database prerequisites: PostgreSQL **16.15**, pgvector **0.8.7**, dedicated
`rag_admission_test` on task-owned tmpfs container, never the existing database.
AST parsing, local repair/handoff links and `git diff --check` passed. All ten
protected input/migration files match the prior SHA-256 baseline, including every
applied migration 0001–0005 and all four supplied originals. The 55-case restored
`tests/unit/test_phase3_repairs.py` remains byte-identical.
Affected runtime files: `app/modules/documents/chunking.py`,
`app/infrastructure/gemini_vision.py`, `app/infrastructure/openrouter_vision.py`,
`app/modules/documents/extraction.py`, `app/modules/documents/worker.py`,
`app/modules/voice/configuration.py`, `app/modules/voice/lifecycle.py`,
`app/api/v1/live.py`, `app/api/v1/dependencies.py`, `app/api/v1/knowledge.py`.
Configuration/docs: `.env.example`, API catalog, implementation guide, reference
map, frontend backend handoff, operations guide, Phase 4 report and this repair
report. Existing test changes are limited to `test_gemini_vision.py`,
`test_phase5_repairs.py`, `test_phase3.py`, `test_ocr_policy.py` and integration
`test_phase5.py`; the two new repair test sources are listed above. Unrelated
working-tree changes were retained.
Final database recheck: **402 passed**, **zero skips**, 1771 deselected (1769
non-PostgreSQL cases plus the two previously passed large-review cases), four
existing warnings, **357.63 s**. Combined with those two actual earlier passes,
all **404 current PostgreSQL scenarios** have executed passing evidence. The
complete initial run with two superseded assertions is retained above; this is
coverage across executions, not a claim that its exit status was successful.
Temporary logs: `/tmp/admission-provider-free-final.log`,
`/tmp/admission-targeted-unit-final.log`, `/tmp/admission-targeted-complete.log`,
`/tmp/admission-postgres.log`, `/tmp/admission-postgres-final.log`.
Cleanup inspection found zero remaining application test schemas, zero public
tables and zero additional test databases. The task-owned tmpfs database container
was then stopped/removed. Existing containers and prior acceptance volumes were
not modified. For container deployment, rebuild the application image to include
this source change before restarting the API with the explicit testing policy;
worker startup still requires an approved queue and spending bounds. The operator
`app.voice_smoke` remains a calibrated search/voice-quality diagnostic; this policy
amendment applies to authenticated V01/WebSocket connectivity testing.
+230 -5
View File
@@ -1,10 +1,11 @@
# Phase 2 repair and acceptance record
Initial repair checkpoint: 2026-10-09. The [remaining-defect repair](#remaining-defect-repair-2026-10-09)
below supersedes affected behavior and validation totals. Gemini Live is the temporary sole voice provider
because an OpenAI Realtime voice key is unavailable. This decision changes voice
only. Extraction, embeddings, frozen profiles, calibration inputs, the canonical
search pipeline and the shared bounded SearchToolRunner are preserved.
Current checkpoint: [transport defect repairs](#transport-defect-repairs-2026-10-09).
Gemini is the temporary default; backend configuration can select the preserved
OpenAI adapter. Earlier initial and remaining-defect records below retain their
historical results. The latest checkpoint supersedes their Gemini-only restriction
and affected behavior; extraction, embeddings, frozen profiles, calibration inputs
and canonical search remain preserved.
The implementation and technical acceptance below are distinct from real Gemini
access, retrieval quality and browser/Persian voice acceptance. This report does
@@ -315,3 +316,227 @@ interrupted fixture run and zero public application tables**. That residue was
confined to this disposable container and was removed with it; it is not claimed
as clean fixture teardown. Preexisting containers and shared databases were
untouched. Executed logs and preservation inventories remain under /tmp.
## Provider selection and transport repair (2026-10-09)
This checkpoint supersedes the Gemini-only restriction and affected behavior in
both earlier checkpoints. Gemini remains the temporary operational default;
`VOICE_PROVIDER=gemini|openai` selects the backend adapter. Both authenticated
Live and operator smoke now use the small [shared factory](../../app/infrastructure/voice_provider.py).
The existing OpenAI adapter and Gemini adapter remain byte-identical to the
preservation baseline. No real provider calls were made.
### Findings → fixes → executable evidence
| Reproduced finding | Repair | Regression evidence |
| --- | --- | --- |
| `VoiceSettings(provider='openai')` raised ValidationError; API and smoke constructed Gemini directly. | Backend selection, selected-only credentials, dedicated OPENAI_REALTIME_* settings, legacy PROVIDER/GEMINI_* compatibility with conflicting aliases rejected. Factory reuses the existing adapters/connections. V01/stream pin selected provider/model/voice/native audio/search profile; replay returns original identity. | `test_phase2_provider_selection.py`: both factory profiles, selected credentials/aliases, actual OpenAI runtime tool/audio/continuation/cancel/truncate. Existing native Gemini runtime tests. Both providers execute actual smoke construction; PostgreSQL API tests exercise readiness, native input, canonical ok/no_evidence/error tool dispatch and matching durable results/public refs. Changed-provider admission opens zero transports; replay retains reservation. |
| Installed Uvicorn defaults were 16777216-byte messages, 32 queued messages, compression enabled. | [Supported entrypoint](../../app/server.py) selects [BoundedWebSocketProtocol](../../app/infrastructure/voice_websocket.py). Pre-payload binary 9600 / text 4096 limits apply across fragments; RSV rejected before payload, compression disabled, queue eight. API retains delivered input capacity until native send completes, avoiding a second backlog. | `test_voice_websocket_transport.py`: ten real loopback cases for exact binary/UTF-8 boundaries, fragments, oversized messages, header-only rejection without mask/payload, compressed-bit rejection, negotiation and queue backpressure. Application validation remains active. |
| Authority helper returned False after SERVICE_BUSY; monitor treated infrastructure exceptions as revocation with inconsistent durable state. | Shared authority classification: SEARCH_SATURATED / SEARCH_TIMEOUT / DEPENDENCY_UNAVAILABLE for infrastructure; CONTEXT_REVOKED only for verified authority loss. Fail closed before release/delivery; first terminal code retained. Durable finish retries bounded pool admission; prior committed terminal outcomes remain immutable. | Unit startup/release/output cases and actual authority deadline. PostgreSQL monitor cases occupy all eight real blocking slots, raise a real SQL failure, exercise timeout classification and change actual DB authority; client errors match status/reason/error_code. Existing logout/disable/expiry/epoch/V04 race tests preserve committed terminal outcomes. |
| Executed delivered worklet admitted 101 tiny packets without overflow. | Both client and worklet enforce 96000 bytes AND 100 messages across refs, including partial packets and pending handoffs. Capacity reserved before PCM conversion. Cumulative consumed counters and completion/discard IDs make release idempotent; admission never advances played_ms. | `voice_phase2_repairs.mjs` executes delivered code: 100/101 tiny packets, exact byte capacity, multiple refs, partial consumption, duplicate consumption ack, interruption flush and cleanup. Existing worklet capture/progress and ASGI active-playback bridge remain exercised. |
| Committed/lost C01 response left creationAttempt and conversationRequestID undefined. | Expose attempt and both IDs before C01; retain frozen C01 and, before V01, frozen V01 payload. retryCreation/ordinary reserve replay identical attempt; newCreationAttempt/freshSession explicitly create new identity. V03 recovery does not connect. | Delivered JS simulates committed/lost C01 and V01 responses, checks identical retry payloads, immutable payload/conflicting IDs, V03 recovery, intentional freshSession ordering. Existing PostgreSQL identical/changed C01/V01 concurrency tests retain backend conflict guarantees. |
| Continuous uncommitted silence reaches the 10-second input cap. | Bound preserved; no commitment or transcript/activity binding invented. Frontend handoff now states the limitation and isolates longer idle operation as a product/provider-contract decision. | Actual Gemini adapter/runtime accepts exactly 480000 bytes of silent PCM without native activity commitment, then rejects the next sample with LIVE_BUFFER_OVERFLOW. No fake tool output/commitment. |
### Deployment and limits
The [frontend handoff](frontend-voice-integration-example.md#backend-configuration-and-supported-startup)
contains both backend configuration examples, aliases, selected-only secrets,
24 kHz browser/native audio behavior, reservation compatibility, explicit retry
and fresh-session APIs, and idle-input limitations. `.env.example` supplies both
provider-specific configurations. Embedding OPENAI_API_KEY/INGEST_* settings are
not voice aliases and were not changed.
Run `.venv/bin/python -m app.server --host 0.0.0.0 --port 8000`; Docker Compose uses
this same supported configuration. Run ingestion separately with
`.venv/bin/python -m app.worker`. Exactly one API process owns process-local
media guards and registry; multiple workers/reload/distributed ownership are not
supported. Browser controls and HTTP schemas remain frozen. Gemini safe-close
interruption does not alter OpenAI cancellation/truncation.
Inspected installed versions: Uvicorn 0.54.0 and websockets 16.1.1. The selected
legacy parser is explicitly named, rather than relying on `ws=auto`. Upstream
legacy deprecation warnings are expected and retained in test output; upgrades
require these loopback checks before changing parser/backend. The upstream
[legacy server reference](https://websockets.readthedocs.io/en/stable/reference/legacy/server.html)
describes compression disabling and message-queue backpressure; local installed
source inspection and executable tests prove the chosen implementation here.
TCP/read scratch and kernel buffers remain separate from admitted-message
budgets. Fake native acknowledgements/input consumption/context sync were not added.
### Executed checks and preservation
Commands run from the repository root using Linux `.venv/bin/python`.
PostgreSQL acceptance uses only the task-created `rag_phase2_selection_test`
database at loopback port 55439 and disposable application schemas, with pgvector
in `test_vector`. No existing application database was reused. Repeated schema
migration writes were unusually slow; only the disposable container was changed
to fsync=off and synchronous_commit=off for functional acceptance. These results
do not prove database crash durability or production throughput.
Executed command results (logs retained under `/tmp/phase2-selection-*.log`):
- Initial focused existing cases:
`.venv/bin/python -m pytest tests/unit/test_phase2_lifecycle.py tests/unit/test_gemini_live.py tests/unit/test_voice_client_example.py tests/unit/test_phase2_remaining.py -q`
— **65 passed**, 22.09 seconds.
- Provider/factory/native cancellation/smoke/browser/loopback focus:
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_websocket_transport.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py::test_operator_harness_actual_fake_transport_tool_correlation -q`
— **35 passed**, 8.43 seconds. Later three-file focus with `-p no:cacheprovider --tb=short`
— **33 passed**, 7.36 seconds. After explicit expiry/disablement cases,
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short`
— **25 passed**, 5.28 seconds.
- Affected PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— first **58 passed**, 483.11 seconds; expanded both-provider tool/result and real
authority coverage **61 passed**, zero skips, 331.67 seconds.
- Final full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1679 passed**, two existing Windows path-alias skips, 372 PostgreSQL cases
deselected, 12 expected legacy-backend warnings; 142.03 seconds. A preceding
complete run passed 1677 cases before two additional authority regressions;
its results are superseded by this final run.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **372 passed**, zero skips, 1681 provider-free cases deselected, two expected
legacy-backend warnings; 394.30 seconds.
- `env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1, **one prerequisite error**, zero database passes/skips.
- `node tests/support/voice_phase2_repairs.mjs` and
`node tests/support/voice_client_harness.mjs unit` — passed. Delivered worklet,
module/client and harness syntax passed (`node --check`, client via
`node --input-type=module --check < examples/voice-client.js`). Python compileall
for app and affected tests, scoped AST/UTF-8, unchanged pyproject TOML parsing,
CLI help for `app.server`/`app.voice_smoke`, and `git diff --check` passed.
- New local documentation links resolve. The initial whole-modified-doc link check
found two unchanged README links to an absent LICENSE, confirmed present in HEAD;
this unrelated existing defect was preserved and excluded from the added-link check.
Failed/interrupted checks are separate from acceptance. The first new focus had
19 passes and two failures: conflicting constructor aliases were silently dropped
by the settings source, and a new timeout fixture incorrectly used dataclasses.replace
on Pydantic settings. Alias validation and the fixture were corrected. A later
focus had 34 passes and one timeout because its fake cancellation omitted the
required native terminal acknowledgement before truncation; the fixture was
corrected, preserving the OpenAI adapter and its acknowledgement gate. The earlier
full provider-free attempt and tool/container launch inspection were interrupted
by the user; completion was not recovered as suite acceptance. The disposable
container was subsequently verified running and full checks rerun. No failed,
interrupted, missing-database or skipped run is counted as PostgreSQL acceptance.
Preparation captured a clean working tree at HEAD `9be4719` and SHA-256 hashes of
213 existing repository files before editing, retained in
`/tmp/phase2-provider-selection-baseline.json`. The changes are limited to voice
configuration/factory/runtime authority/Live transport, supported startup,
browser examples, related tests and handoff/contracts. Protected migrations
0001–0005, both existing voice adapters, extraction/embedding configuration and
modules, shared SearchService/StructuredTool/SearchToolRunner, calibration inputs,
proof scripts and original-document paths were not edited. No migration was
required or added. Unrelated changes were absent at the initial baseline. A final
hash comparison matched exactly the 21 scoped modified existing paths; 42 protected
baseline entries remained unchanged. OpenAI adapter SHA-256:
`c5906daa1fb619baca6bb35a676b7cfdee720be4a4d52331278039c6efe01206`;
Gemini adapter SHA-256:
`607cf142801b8bede48482b42bc997462f2010b555eaf051a707242f09b575ae`.
Added paths are the shared factory, authority classifier, server/parser and their
regression/harness files; no unrelated existing paths changed.
Remaining external acceptance: separately authorized Gemini/OpenAI service
access with valid selected voice key/model/voice; compatible measured retrieval
calibration and approved corpus; budgets; Persian speech; real browser microphone,
AudioContext/hardware and heard-audio testing. Fake-provider tests establish
technical behavior only. Frontend readiness, seamless Gemini interruption and
longer continuous uncommitted idle capture remain uncertified.
## Transport defect repairs (2026-10-09)
This checkpoint repairs three verified Phase 2 transport defects across backend
WebSocket protocol reassembly, browser capture buffering, and trusted wire limits.
Both Gemini and OpenAI adapters, credentials, pinned profiles, migrations 0001–0005,
frozen payload/queue/playback limits, and canonical retrieval remain preserved.
### Verified defects, repairs, and observable regressions
| Transport defect | Implemented repair | Acceptance evidence |
| --- | --- | --- |
| 1. Bound fragmented-message reassembly (`app/infrastructure/voice_websocket.py`, `app/server.py`) | Reassembly uses finite scratch storage (`bytearray`), incremental UTF-8 decoding, and bounded retained metadata. Empty continuations do not allocate or grow fragment lists (preventing probe memory growth across 20,001 empty frames). Aggregate byte limits (`max_binary_message_bytes`, `max_client_control_bytes`), pre-payload frame header checks (`Frame.read(max_size=bound)`), and compression rejection are enforced. Connection close, failure, and cancellation release assembly resources. Interleaved control frames (ping/pong) remain supported during fragmentation. | Loopback tests in `tests/unit/test_voice_websocket_transport.py`: `test_bounded_fragment_reassembly_long_empty_and_tiny_sequences` (20,001 empty continuation frames, exact 9600-byte binary and 4096-byte UTF-8 boundaries), `test_interleaved_protocol_controls_during_fragmentation` (ping/pong interleaved during reassembly), and `test_malformed_fragmentation_sequences_and_resource_cleanup` (opcode 0 without start rejected with 1002, interleaved data frame rejected with 1002, unfinished message cleaned up on disconnect). |
| 2. Bound outgoing microphone messages through completion (`examples/voice-client.js`, `examples/voice-audio-worklet.js`) | Capture handoff and outgoing socket buffering enforce both byte (96000) and message (100) capacity bounds. Worklet tracks `pending` messages and `pendingBytes`, rejecting with `overflow` when either bound would be exceeded. Conservative browser `socket.bufferedAmount` accounting delivers `{type: 'accepted', bytes}` to the worklet only after verified drain across the socket (`captureBytes - bufferedAmount >= packetBytes`). Worklet acceptance does not falsely imply network completion. Capacity is released exactly once on verified drain or terminal cleanup. | Regressions in `tests/support/voice_phase2_repairs.mjs` (executed by `tests/unit/test_voice_client_example.py`): standalone worklet 100/101 boundary, client+worklet stalled socket 100/101 boundary (48,000 bytes admitted, 101st overflows), partial drain conservative accounting (partial packet bytes do not trigger acceptance), delayed handoffs, terminal cleanup, and stale callbacks. |
| 3. Honor lower trusted runtime limits at the wire boundary (`app/server.py`, `app/infrastructure/voice_websocket.py`) | Validated `LIVE_*` `RuntimeSettings` are injected into `server_config()` and `BoundedWebSocketProtocol`. Pre-allocation message admission accounts for assembling, queued, and in-flight messages (`recv()` entry release). Queue depth is set to `max(1, max_queued_audio_messages - 2)` when $> 2$ or 1, avoiding zero-capacity deadlocks for message budgets of one and two while strictly bounding total capacity. Oversized declarations are rejected before mask/payload allocation. | Loopback tests in `tests/unit/test_voice_websocket_transport.py`: `test_lower_trusted_runtime_limits_and_prepayload_rejection` (1201 binary and 501 text rejected with 1009 before reading mask/payload; legal 1200 binary and 500 text accepted), `test_small_message_budgets_one_and_two_deadlock_free` (budget of 1 functions with in-flight backpressure and sequential drain without deadlock; budget of 2 bounds total capacity to 2). |
### Exact checks and outcomes
Commands run from repository root using `.venv/bin/python` (Python 3.13.7) and `node` (v22.23.1):
- Transport loopback regressions and voice client example tests:
`.venv/bin/python -m pytest tests/unit/test_voice_websocket_transport.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short`
— **18 passed**, 22 expected legacy-backend warnings in 7.60s.
- Node worklet and client repair regressions:
`node tests/support/voice_phase2_repairs.mjs`
— **passed**: playback bounds, consumed capacity, flush, cleanup, capture bounds, 100/101 stalled socket, drain, delayed handoffs.
- Node client harness unit test:
`node tests/support/voice_client_harness.mjs unit`
— **passed**: VoiceClient ownership, errors, logout, and close.
- Provider selection, lifecycle, and Gemini Live regressions:
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_phase2_lifecycle.py tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short`
— **44 passed** in 4.46s.
- Full provider-free test suite:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1684 passed**, 2 skipped (Windows path alias), 372 deselected, 22 expected warnings in 150.64s.
- Missing-configuration gate:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1, **one prerequisite error**: `TEST_DATABASE_URL is required for PostgreSQL acceptance`.
- PostgreSQL acceptance status:
No active PostgreSQL container or TEST_DATABASE_URL is configured in this Linux test environment. Prerequisite gate verified; full PostgreSQL acceptance is reported as unavailable pending environment setup.
- JavaScript syntax and formatting:
`node --check examples/voice-audio-worklet.js` and `node --input-type=module --check < examples/voice-client.js`
— **passed**.
- Code integrity and git checks:
`git diff --check`
— **passed** with zero whitespace/formatting defects.
### Material limitations and scope preservation
All repairs preserve:
- `VOICE_PROVIDER=gemini|openai`, Gemini default, OpenAI adapter, shared adapter factory, and credentials.
- Applied migrations 0001–0005, protected inputs, canonical retrieval, and ownership/replay/revocation rules.
- Frozen payload (9600 binary / 4096 control), queue (96000 bytes / 100 messages), playback, and 10-second uncommitted input limits. No limits were widened.
- No provider fallback, frontend provider selector, new browser control types, or deferred history features were introduced.
Automated simulations, Node worklet tests, and transport loopback tests establish technical wire boundaries only. They do not certify real-provider availability, live microphone hardware, heard-audio acoustics, or real-browser production readiness.
## Phase 3 integration: final two Phase 2 transport findings (2026-10-09)
Both requested findings are repaired without changing selected Gemini/OpenAI
adapters, voice/model configuration, browser mono PCM16LE 24 kHz, playback limits,
canonical retrieval or migrations 0001–0005.
- Receive-capacity cancellation: wait_for_capacity now propagates CancelledError.
The real installed-parser regression fills a valid one-message capacity budget,
fails the protocol with a nonresponsive peer, shields the termination assertions
from issuing another cancellation and verifies bounded transport teardown.
Existing one/two-message, fragmentation, compression and header-only limits remain.
- Invalid UTF-8 classification: the parser retains its 1007 rejection for ASGI;
Uvicorn otherwise can expose 1006 because a failed parser no longer reads the
peer close. Live maps 1007 to LIVE_PROTOCOL_ERROR. Complete and fragmented raw
invalid UTF-8 produce wire close 1007 and real PostgreSQL terminal polling reports
the protocol error. Ordinary loss remains LIVE_TRANSPORT_FAILED; existing loss
regressions remain in the affected/full acceptance suites.
Finding-to-test mapping:
`tests/unit/test_voice_websocket_transport.py::test_capacity_failure_terminates_receive_with_nonresponsive_peer`,
`test_invalid_utf8_retains_standard_1007_rejection`, and
`tests/integration/test_realtime_phase3_http.py::test_real_parser_invalid_utf8_persists_protocol_error`.
The latter executes the actual Live handler, installed server parser and durable
polling, with a deterministic provider transport. See the
[Phase 3 handoff](realtime-agent-phase3-handoff.md) for the complete exact validation
record and HTTP/voice integration checks. No real provider or browser microphone,
Persian speech, network latency or transcription-quality acceptance was performed.
Executed final integration checks: **323 affected unit tests passed**;
**1724 provider-free tests passed**, two existing Windows-only path skips;
**162 affected PostgreSQL tests passed**, zero skips, including both adapters and
the raw UTF-8 polling cases. A prior full PostgreSQL checkpoint passed **393**;
final refinement coverage and exact commands are distinguished in the Phase 3
handoff. The two-provider explicit revoked-excerpt regression passed **2** additional
cases. Missing TEST_DATABASE_URL failed with the required prerequisite error.
Compose, executable JavaScript, AST/TOML, diff and preservation checks passed.
Task-owned acceptance database cleanup verified zero application schemas/tables
before removal. No provider, adapter, frozen voice configuration or corpus rewrite.
@@ -0,0 +1,513 @@
# Phase 3 document and knowledge HTTP handoff
The modular API exposes D01-D04, D06 preview/D07, K01/K02 and read-only F01 under
`/api/v1`. It uses the existing immutable intake, fenced worker, exact-output
review and atomic selection services. It preserves selected Gemini/OpenAI voice
configuration and the Phase 2 repairs. Production UI, text chat, settings editing,
deletion and real-provider certification remain outside this delivery.
## Startup and development origin
Install the API extra (including the bounded multipart parser) and the worker's
configured embedding/vision extras using the repository manifest. Apply migrations
and provision an enabled administrator as described in
[foundation setup](ingestion-foundation-setup.md). Applied migrations 0001–0005
remain unchanged.
### Direct run vs. Docker Compose ports
For local development matching the Vite development proxy (`http://localhost:8080`) and Docker Compose port mapping:
- **Docker Compose**: The API container listens internally on port 8000 and exposes host port 8080 via `${API_PORT:-8080}:8000`. Start `docker compose up -d db migrations api`; start `worker` separately only for an approved ingestion queue and budget. See the [Phase 4 operational procedure](phase4-backend-operations.md).
- **Direct run**: Start the API process with:
`python -m app.server --host 0.0.0.0 --port 8080`
(or `--port 8000` if matching container-internal default or behind a reverse proxy mapping host 8080 to container 8000), and start a separate worker with:
`python -m app.worker`.
Docker Compose forwards the OCR setting to API and worker; both mount the same original and extraction directories. Use `.env.example` for actual embedding identity, dimensions and provider credentials; they remain server-side.
### Proxy and trusted Host/Origin configuration
Use the [same-origin Vite proxy example](../../examples/vite-proxy.config.js) in the frontend's existing configuration. The Vite dev server runs at `http://localhost:5173` and proxies `/api` to the backend at `http://localhost:8080`.
- **Vite proxy with `changeOrigin: false` (recommended for development)**:
The proxy preserves browser headers (`Host: localhost:5173` and `Origin: http://localhost:5173`) and forwards both HTTP and WebSocket paths (`ws: true` for `/api/v1/live`). Set:
`TRUSTED_HOSTS=["localhost:5173"]`, `TRUSTED_ORIGINS=["http://localhost:5173"]`, `COOKIE_SECURE=false` (for loopback HTTP development only).
- **Direct API access (no frontend proxy)**:
When accessing the API directly on port 8080 without a frontend proxy, set:
`TRUSTED_HOSTS=["localhost:8080"]`, `TRUSTED_ORIGINS=["http://localhost:8080"]`.
HTTPS production uses Secure cookies and explicit trusted endpoints. Never use wildcard credentialed CORS. Cross-origin configured clients can preflight PATCH and Idempotency-Key; correlation/replay headers are exposed.
## Executable browser sequence
Use [DocumentClient](../../examples/document-client.js) with the existing
[VoiceClient](../../examples/voice-client.js). Run in the frontend module context; `inspectEvidence` is the frontend developer’s
human review interaction, never an automatic approval helper:
```js
import {VoiceClient} from './voice-client.js';
import {DocumentClient} from './document-client.js';
const voice = new VoiceClient(event => console.log(event));
await voice.login(username, password);
const documents = new DocumentClient(voice);
const configuration = await documents.configuration();
const uploadKey = crypto.randomUUID(); // retain until the upload outcome is resolved
const uploaded = await documents.upload(fileInput.files[0], 'Policy', uploadKey);
async function waitForProcessing(id) {
for (;;) {
const current = await documents.poll(id);
if (!['queued', 'processing'].includes(current.status)) return current;
await new Promise(resolve => setTimeout(resolve, 2000));
}
}
let document = await waitForProcessing(uploaded.document_id);
while (document.review_required) {
const evidence = await documents.review(document.id);
for (const item of evidence.items) {
// Frontend-owned human inspection: show blocks and authenticated preview_path.
// This returns the person's decision, checked fields, note and whole-group exclusions.
const humanDecision = await inspectEvidence(item);
await documents.decide(document.id, {
...humanDecision, evidence_sha256: item.evidence_sha256
}, crypto.randomUUID()); // retain each decision/key if its outcome is ambiguous
}
document = await documents.poll(document.id);
if (document.review_required) continue; // fetch the next still-pending page
if (!document.job.can_retry) throw new Error(document.review_state);
await documents.retry(document.id, crypto.randomUUID()); // retain retry key
document = await waitForProcessing(document.id);
}
if (document.status !== 'ready') throw new Error(document.job.error?.code);
// Ready remains inactive and unsearchable until this explicit replacement.
const selection = await documents.selection();
await documents.replace(selection.revision, [...new Set([...selection.document_ids, document.id])]);
// Voice admission additionally requires configured credentials and measured calibration.
await voice.reserve();
await voice.connect();
```
The snippets use real server-returned UUIDs/digests. Branch on processing state;
do not execute review with an empty candidate list. Keep the exact File/title and
upload key on ambiguous timeout, then replay the same upload. Retain decision and
retry keys similarly; replay headers are `Idempotency-Replayed: true`. A changed
payload under an existing key returns `409 IDEMPOTENCY_CONFLICT`. New keys create
independent documents even when bytes match. Titles are normalized by intake.
Known replay retains its accepted byte bound even if the current new-upload
limit is lower; changed bytes/length still conflict. The helper leaves FormData
Content-Type/boundary to the browser. Upload has one
file and optional title; caller-supplied organizations, profiles or model selectors
are rejected. Retry accepts no body.
Lists return items, next_cursor and knowledge_revision. Document lists use limit
20 by default, max 100, stable descending created_at/id, and opaque cursors.
Review pagination defaults to 10, max 20; pass the returned evidence cursor unchanged.
Invalid/unknown cursors return 422. Detail never exposes private storage keys,
original paths, leases, raw provider messages or credential-bearing profiles.
Admin documents/review/selection are organization-scoped; hidden/deleted IDs are
404. Authenticated non-admin collection access is 403. F01 is available to both roles.
## OCR supervisor policy and truthful review state
`INGEST_OCR_REVIEW_REQUIRED=true` is a backend-only deployment setting, default
true. API enqueue freezes it as `processing_profile.extraction.ocr_review_required`
in the immutable one-document/one-job snapshot. Workers use that snapshot; a later
environment change affects only new uploads. Same-job retry preserves it. Existing
profiles lacking the field retain mandatory OCR review and their original digests.
No migration, backfill or profile rewrite is needed.
False admits OCR/vision transcription only after existing automatic validation
passes: identity/model, readable complete blocks, source relationships, byte/pixel/
page/character budgets, faithful normalization, original integrity and coverage.
Warning-bearing OCR still requires inspection; unreadable/invalid output fails.
Direct PDF and other non-OCR review requirements remain. Factual Q&A inclusion
requires its own retained-evidence human approval regardless of OCR policy.
Approvals never enqueue or activate. Publication is atomic, ready and inactive;
K02 is the only delivered activation route.
F01 capabilities.ocr_review_required reports the current deployment policy.
D03 ocr_review_required reports the document's frozen policy. D03 review_state is
not_evaluated, not_required, pending, approved or rejected and describes retained
required decisions. review_required means a current candidate lacks a decision;
rejection separately prevents retry. extraction_quality_decision is null before a
complete artifact, passed for automatic validation, reviewed when all extraction requiring inspection was actually inspected, or
partially_reviewed for mixed inspected pages and automatically admitted OCR. An automatically admitted extraction creates no
human approval annotation or audit event. approved factual review does not change
passed extraction into reviewed. Only inspected locators carry human annotations; automatic pages never do.
Factual candidates can remain pending independently of any extraction outcome.
D06 returns exact server-owned evidence and check lists; preview URLs require the
same admin cookie and return no-store validated image bytes. Preview cannot accept
a storage path. D07 requires a nonblank note and exact required checks for approval.
For factual candidates, exclusions are whole existing Q&A group IDs and cannot
include placeholders or leave no factual groups. Rejection stays failed with zero
chunks. Stale/removed evidence returns REVIEW_STALE; a new conflicting decision on
already-decided evidence returns REVIEW_ALREADY_DECIDED. Pending reviews prevent
retry even after changing the deployment default. Retry reuses the same failed job
and retained output rather than obtaining a new OCR response under an old approval.
## Selection, voice and errors
K02 replaces the full selected set using expected_revision; duplicate IDs return
422, unready IDs return DOCUMENT_NOT_READY with rejected IDs, and stale revision
returns REVISION_CONFLICT. After ambiguous timeout or conflict, read K01 before
constructing the next replacement. Additions increment revision without changing
epoch; no-op preserves both. Removal increments access_epoch, stales conversations,
closes older Live sessions, fails running tools and notifies the local runtime after
commit. Polling redacts revoked evidence. Stop ineligible output and create a fresh
conversation; never copy revoked context into recovery.
Cookie-only authentication, trusted Host/Origin and X-CSRF-Token apply to mutations.
Refresh the CSRF token through `/me`. Safe failures carry error.code, message,
request_id and retryable; X-Request-ID matches that correlation.
### Bounded request-body admission before parsing
D07 extraction-review decisions and K02 knowledge-selection authenticate BEFORE
consuming or accumulating request bodies:
- Unauthenticated requests are rejected immediately with 401 (or 403 for non-admins)
with zero bytes read from the network stream, preventing unauthenticated denial-of-service
via unbounded payload buffering.
- Finite receive-byte limits are enforced during streaming accumulation:
- `MAX_DECISION_BYTES = 60,151,072 bytes` for D07 decisions, accommodating
all supported DTO values: 10,000 exclusions and 16 checks of 500 characters,
a 2,000-character note, 12 bytes per character for escaped surrogate pairs,
three bytes per array entry for quotes/comma, and 1,024 bytes for fixed fields
and formatting. This finite cap admits raw UTF-8 and escaped JSON without
reducing semantic eligibility. Capacity is checked before buffer extension.
- `MAX_SELECTION_BYTES = 1 MiB` (1,048,576 bytes) for K02 selection, accommodating
up to 10,000 document UUID selections (~360 KiB).
- Actual received bytes are counted dynamically; absent or misleading `Content-Length`
headers cannot bypass bounds. Payloads exceeding limits return 413 `PAYLOAD_TOO_LARGE`.
- Finite receive-time deadline: 15 seconds (`JSON_RECEIVE_SECONDS = 15`). Stalled or
timed-out body receives return 503 `DEPENDENCY_UNAVAILABLE` and clean up.
- D04 retry enforces a finite 5-second deadline (`RETRY_RECEIVE_SECONDS = 5`) and rejects
any nonempty body with 422 `VALIDATION_ERROR`. Stalled streams, client disconnects, or cancellations release
request resources immediately and cannot invoke retry afterward.
### Upload admission and temporary spool separation
Upload intake decouples user-facing display filenames from filesystem temporary storage:
- Spooled upload bytes are written to a bounded, server-controlled temporary filename
(`payload`) in an isolated temporary directory (`UploadSpool(path, filename, title)`).
- The original validated display filename (up to 255 characters, valid extension, no
traversal) is preserved in `spool.filename` and passed explicitly to `import_document`.
- This eliminates Linux filesystem `NAME_MAX` (255 byte) collisions for long multibyte UTF-8
filenames (e.g. 128 Arabic characters `س` + `.md` = 259 bytes), which previously raised
`OSError: File name too long` (503 `DEPENDENCY_UNAVAILABLE`).
- Default normalized title derivation, replay hash idempotency semantics, CLI intake
compatibility, upload bounds, and temporary file cleanup on completion/cancellation
remain fully preserved.
- Upload admission uses request max = configured file bytes + 16 KiB, file max = configured bytes,
two parts, 4 KiB headers per part, 800 UTF-8 title bytes, a 60-second receive
deadline and four concurrent disk spools. Invalid/malformed input is INVALID_FILE (422),
too large is FILE_TOO_LARGE (413), unsupported format is 415, and capacity is RATE_LIMITED (429).
Stalled receive returns DEPENDENCY_UNAVAILABLE (503) after its deadline. Partial
multipart, rejection and disconnect clean temporary resources. Uncertain original
commits retain candidates for existing reconciliation rather than deleting evidence.
F01 voice/captions indicate configured credential/calibration prerequisites, not
verified provider/Persian quality. See the
[voice handoff](frontend-voice-integration-example.md) for mono PCM16LE 24 kHz,
application events, playback_progress, audio_ended, interruption and ten-second
uncommitted input behavior. Native UTF-8 rejection retains wire close 1007 and is
persisted as LIVE_PROTOCOL_ERROR; ordinary loss remains LIVE_TRANSPORT_FAILED.
Reconcile V03/poll, close the old reservation and use fresh IDs before reconnecting.
## Validation checkpoint
Executed checks and remaining external prerequisites are recorded below after
implementation validation. Deterministic providers, simulated browser requests and
local parser tests do not establish real provider quality or browser hardware readiness.
### Executed checks (2026-10-09)
- Repair regression test suite:
`.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_upload_boundary.py -q -p no:cacheprovider --tb=short`
— **23 passed** (9 repair tests in `test_phase3_repairs.py`, 14 in `test_upload_boundary.py`), 0.65 seconds.
- Bounded admission, upload spool, and document client unit tests:
`.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_upload_boundary.py tests/unit/test_intake.py tests/unit/test_document_client_example.py -q -p no:cacheprovider --tb=short`
— **36 passed**, 0.74 seconds.
- Provider-free regression suite:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1680 passed**, 2 skipped (Windows path alias semantics), 395 PostgreSQL tests deselected, 154.21 seconds. No real provider calls.
- PostgreSQL integration acceptance with isolated container (`rag-phase3-repair-acceptance` on loopback port 54930, tmpfs):
`.venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **23 passed**, zero skips, 55.79 seconds; includes `test_unicode_filename_upload_persistence_and_replay`.
- PostgreSQL acceptance suite with intake:
`.venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py tests/integration/test_intake.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **77 passed**, zero skips, 78.07 seconds.
- Required PostgreSQL acceptance configuration check:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_unicode_filename_upload_persistence_and_replay -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1 with **prerequisite error**: `TEST_DATABASE_URL is required for PostgreSQL acceptance`. Missing configuration fails acceptance rather than passing.
- Node syntax and contract checks:
`node --check examples/document-client.js examples/vite-proxy.config.js examples/voice-client.js examples/voice-audio-worklet.js`: passed.
- Formatting, git diff, and whitespace checks:
`git diff --check`: passed. Zero trailing whitespace or merge conflict markers.
### Acceptance coverage and focused integration review
| Area | Evidence |
| --- | --- |
| Auth and scope | Actual cookie login, admin/user roles, Host/Origin/CSRF checks, cross-organization 404 for detail/review/preview/retry/selection, safe shared correlation/error envelopes |
| Bounded request admission | D07 decisions (60,151,072-byte bound) and K02 selection (1 MiB bound) authenticate before body accumulation (0 bytes consumed unauthenticated); dynamic receive-byte counts prevent bypass via missing/misleading Content-Length; 15s receive deadline returns 503; D04 retry empty body deadline (5s) rejects nonempty payload and releases resources on timeout/cancellation without invoking retry |
| Upload intake & spools | Spooling writes to bounded server-controlled disk path (`payload`) decoupling Linux `NAME_MAX` (255 byte) limit from original display filename; 128 Arabic characters (`س` * 128 + `.md` = 259 bytes) accepted without filesystem error; display filename, extension validation, default normalized title derivation, exact replay hash idempotency, CLI intake, and cleanup on disconnect/finish preserved |
| Startup & proxy | Direct run on port 8080 (`python -m app.server --host 0.0.0.0 --port 8080`), Docker Compose port mapping (`${API_PORT:-8080}:8000`), and Vite proxy configuration (`http://localhost:8080`, `changeOrigin: false`, `ws: true`) reconciled and documented with corresponding trusted Host/Origin settings |
| Review/retry | Exact retained source previews, required checks and forged reviewer rejection, stale digest, approval/rejection and replay/conflict, approval alone leaves failed, same-job/generation replay, retained OCR reuse |
| Frozen OCR | True/false new profiles, legacy missing setting, deployment changes after enqueue, JPEG/PNG/scanned PDF, unreadable/model/placeholder/warning failures, independent factual inclusion, truthful passed/partially_reviewed outcomes, zero synthetic human records |
| Publication/selection | Ready but inactive after actual fenced publication, unready/duplicate/revision rejection, no-op and addition epoch rules, authenticated K02 removal closing both provider paths, revoked excerpts redacted, blocked actual runtime search cancelled without late sources/provider output |
| Transport | Filled capacity with a nonresponsive peer terminates without another cancel; complete and fragmented UTF-8 retain native 1007 and persist LIVE_PROTOCOL_ERROR through actual installed parser/Live handler |
Final integration review confirmed that all three Phase 3 findings are repaired without altering Phase 1 architecture, data migrations, provider abstractions, or unrelated working tree changes.
Preservation checks confirm:
- Existing Gemini and OpenAI Realtime adapters remain intact and configurable; Gemini remains the default provider without fallback.
- OCR supervisor policy defaults to true and remains frozen per job; legacy profiles retain mandatory review.
- Independent uploads, immutable originals, same-job retry, ready-but-inactive publication, explicit K02 selection, and shared retrieval are preserved.
- Database migrations 0001–0005 and protected corpus inputs are untouched.
- No production UI, public search endpoint, settings editor, background service, or extra external dependency was added.
Real OCR/transcription quality, funded provider calls, Persian voice, browser microphone/playback, production HTTPS/proxy deployment, and frontend UI acceptance remain explicitly unverified. Setting the OCR supervisor gate false is not quality certification.
Before cleanup, the temporary test database contained zero disposable application schemas and zero public application tables. The test container `rag-phase3-repair-acceptance` was stopped and automatically removed.
## Four verified findings repair (2026-10-09)
K02 submits its unchanged synchronous atomic service to the existing eight-slot
blocking pool. Exhaustion maps to 429 RATE_LIMITED; a six-second wait timeout maps
to 503 DEPENDENCY_UNAVAILABLE. A timed-out transaction can still commit, retaining
its slot until completion and issuing the existing post-commit notification.
Resolve ambiguous outcomes through K01 before submitting a new expected revision.
| Finding | Exact regression coverage |
| --- | --- |
| Selection blocking | `tests/unit/test_phase3_http_repairs.py::test_blocked_selection_keeps_event_loop_responsive`, `test_selection_blocking_safe_errors`; PostgreSQL `tests/integration/test_realtime_phase3_http.py::test_authenticated_selection_removal_closes_active_voice_and_redacts_polling` (Gemini and OpenAI), `test_http_selection_removal_cancels_running_runtime_tool`, `test_selection_addition_preserves_active_epoch_and_noop_revision` |
| Overwritten ingestion suite | `tests/unit/test_phase3_repairs.py` restored byte-for-byte from commit `9be4719`: all 55 DOCX fidelity, FAQ association, chunking, budgets and deadline regressions; the nine existing HTTP tests moved intact to `tests/unit/test_phase3_http_repairs.py` with cap-dependent fixtures updated |
| Decision admission budget | HTTP suite `test_decision_budget_covers_multibyte_and_escaped_identifiers`, `test_json_capacity_checked_before_buffer_extension`, `test_streamed_oversized_json_rejection`, `test_absent_and_misleading_content_length`, `test_slow_body_receive_timeout`, `test_unauthenticated_admission_zero_bytes_consumed`, `test_csrf_rejection_consumes_no_decision_body`; PostgreSQL `test_large_eligible_review_persists_and_replays` generates 9,000 retained blocks/4,500 groups, excludes 4,499 and resumes one eligible pair without repeated provider calls (ASCII and escaped Unicode variants) |
| D04 handoff | HTTP suite `test_retry_admission_and_cancellation`: nonempty body returns 422 VALIDATION_ERROR; stalled receive returns 503 and cancellation never invokes retry |
The new decision bound is 60,151,072 bytes. Existing semantic limits, review
eligibility, authentication/CSRF ordering and 15-second receive deadlines remain.
JSON with excessive formatting can exceed the finite admission budget even if
its parsed DTO would otherwise be valid; compact valid DTO encodings fit.
Executed repair checks (Linux `.venv/bin/python`; local socket access required):
```sh
.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_phase3_http_repairs.py -q -p no:cacheprovider --tb=short
# 71 passed in 5.55s: 55 restored ingestion + 16 HTTP cases.
.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
# 1740 passed, 2 failed, 2 existing Windows-path skips, 397 deselected in 209.23s.
.venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short
# 9 passed, 1 failed in 15.33s; same tool-response timeout reproduces alone.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_repairs_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'large_eligible or selection' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# 6 passed, 1 failed, 18 deselected in 644.49s; zero skips.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_repairs_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k large_eligible -m postgres --require-postgres -x -q -p no:cacheprovider --tb=short
# 2 passed, 23 deselected in 477.99s; zero skips.
env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_large_eligible_review_persists_and_replays -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Expected failure: 2 setup errors, TEST_DATABASE_URL required; zero skips.
git diff --check
# Passed; four affected Python AST parses and restored-suite byte comparison passed.
```
Full provider-free failures: unchanged
`test_native_tool_correlation_canonical_result_and_once_only_continuation[rows0-ok]`
times out waiting for Gemini toolResponse; `test_ordinary_suite_ignores_ambient_ingestion_configuration`
runs the suite in a subprocess and encounters that same failure. The independent
Gemini run reproduces it. No failing test or runtime was weakened or changed.
Focused PostgreSQL failure: `test_http_selection_removal_cancels_running_runtime_tool`
times out at `entered.wait(3)` before invoking K02. Both provider variants of
post-commit active-session closure/redaction passed, as did selection revision,
addition/no-op and large-decision persistence/replay/same-job resume.
A broader command with the same isolated URL,
`.venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`,
was interrupted after 498.32s: 19 passed, two unchanged
`test_real_parser_invalid_utf8_persists_protocol_error` timeout failures; it is
not a completed acceptance run. Initial sandboxed unit/database runs encountered
existing socket-based timeout-validator setup errors; the checks above ran with
local socket access. An earlier focused unit checkpoint passed 69 cases before
the final two admission tests were added.
This repair edits only knowledge transport, JSON admission, the restored/separate
unit suites, generated HTTP integration cases, this handoff and the reference map.
All unrelated working-tree edits are retained. Neither provider adapter, OCR
policy/profile semantics, immutable originals, migrations 0001–0005, protected
inputs, shared retrieval, Phase 2 implementation, manifest or Compose changed.
No production UI, executor abstraction, dependency or service was added.
Remaining prerequisites include investigation of the recorded unchanged voice/
parser failures and actual funded provider, Persian speech, browser hardware and
HTTPS deployment acceptance. These tests use generated evidence and mocked
providers and certify none of those external behaviors.
The task-owned `rag-four-findings-test` container used `pgvector/pgvector:pg16`,
loopback port 55439 and the isolated `rag_repairs_test` database. Final inspection
found zero public tables and two disposable schemas left by the interrupted run.
Stopping the `--rm` container removed the database and remaining schemas; no
existing database/container was modified.
## Large JSON responsiveness and completed acceptance repair (2026-10-09)
This record supersedes the incomplete acceptance above for the affected final
code. D07 retains its 60,151,072-byte budget and all supported DTO semantics;
K02, all 55 restored ingestion cases, D04's 422 VALIDATION_ERROR and the separate
HTTP regression suite remain intact.
`receive_json` admits at most two requests before allocating/consuming their
body. It checks actual remaining byte capacity before each chunk, copies at most
64 KiB per iteration and yields even for a stream that never suspends. Bodies
above 64 KiB spill to private temporary files instead of growing an API buffer.
UTF-8 decoding, standard-library json.loads and full DTO validation run in a
short-lived local child process, with a separate GIL. The parent receives only
trusted child-validated field batches (at most 256 KiB each), yielding between
batches, and constructs the already-validated DTO without repeating validation.
Client data never enters a pickle loader; only the application's local child
produces the internal result frames. No provider credentials leave the server.
No external service, dependency, custom JSON parser or executor pool was added.
The 15-second JSON deadline now covers receive, parsing and result reconstruction.
Authentication and CSRF still precede consumption. Capacity exhaustion maps to
429 RATE_LIMITED, a receive/processing timeout to 503 DEPENDENCY_UNAVAILABLE,
and malformed encoding/JSON/DTOs to 422 VALIDATION_ERROR through the existing
correlated error envelope. A cancelled/timed-out caller cancels the independent
owner; admission remains held until pending disk writes finish, any child
(including one still being created) is killed/reaped, and the spool is removed.
At most two capped input spools and two decoder children can coexist. Normalized
D07 DTOs also have a separate two-transaction bound; model serialization stays
with the database work. Caller cancellation cannot recall a committing decision:
its worker retains admission and DTO ownership until actual completion. Replay
with the same decision/key resolves that ambiguous outcome as before.
### Wait investigation and cause evidence
Temporary test-only timestamp/stack diagnostics, outside the repository, observed:
- Fresh Gemini suite: 10 passed; first create_search_tool took 484.81 ms,
subsequent construction 0.12 ms, and the canonical worker completed promptly.
- Isolated PostgreSQL parser/running-tool diagnostic: both parser tests passed,
but the running-tool test failed at entered.wait(3). At 2.5 seconds the API
thread stack was importing langchain_core callbacks/manager/stdout and utility
modules through StructuredTool. First tool construction took 3,366.14 ms;
the test thread's three-second provider-entry wait expired before the framework
coroutine entered the search worker. The worker ran only after the failed
fixture began teardown. This is cold initialization crossing the fixture's
synchronization deadline, not evidence of a blocked embedding provider or
selection transaction. The unit Gemini wait for toolResponse has the same
first-framework-invocation placement; its nested-suite failure simply reran
the failing unit case and was not a separate configuration defect.
- API startup now prepares the existing optional framework through the bounded
blocking pool before reconciliation/readiness, so cold imports precede voice
admission and tool execution. The shared voice unit fixture follows the same
ordering. No wait was lengthened, assertion weakened or test skipped. The
framework remains optional for document-only installations; broken installed
dependencies still fail startup rather than being silently ignored.
- The historical parser failures stalled at connected-state observation (one
case) and the server's shutdown wait (the other). They did not reproduce in
the diagnostic or completed acceptance runs. Their original cause remains
unresolved: the interrupted, concurrently loaded earlier run does not provide
sufficient evidence to classify them as runtime, fixture, leaked work or
environment failures. No parser/transport runtime or assertion was changed.
Passing repetitions do not certify an intermittent parser defect fixed.
### Actual processing measurements and regression mapping
The generated transport tests cover 4,499 and 10,000 unique 500-character IDs
including escaped surrogate pairs, plus a 2,000-character Unicode note. A 10 ms
heartbeat runs across the actual receive/spool/decode/loads/validate/transfer path;
its maximum gap must stay below 100 ms, well below the reproduced old stalls.
No sleeping parser mock is used for this responsiveness assertion.
| Finding/invariant | Exact test source |
| --- | --- |
| Decoder/GIL responsiveness for actual 26.8/59.5 MB valid bodies | `tests/unit/test_json_processing.py::test_real_large_escaped_json_keeps_concurrent_loop_active` (4,499/10,000 IDs) |
| Timeout/cancellation retains admission and spool ownership through actual disk completion | `test_admission_retained_until_cancelled_disk_work_and_spool_release` (cancel/timeout) |
| Cancellation during process creation reaps the eventual real child before release | `test_cancel_during_child_creation_reaps_child_before_releasing_admission` |
| Malformed large JSON, invalid UTF-8, invalid DTO | `test_large_malformed_or_invalid_dto_is_safe` (three cases) |
| Cancelled review transaction retains normalized DTO and admission until completion | `test_cancelled_decision_keeps_normalized_dto_admitted_until_transaction_finishes` |
| Cold framework preparation precedes live admission, outside the loop; optional dependency preserved | `tests/unit/test_phase3_acceptance_repairs.py::test_framework_prepared_off_loop_before_reconciliation_and_readiness`, `test_document_only_installation_keeps_framework_optional` |
| First real Gemini tool correlation and canonical result | Both variants of `tests/unit/test_gemini_live.py::test_native_tool_correlation_canonical_result_and_once_only_continuation`; complete ten-case Gemini suite |
| Real provider-entry/revocation synchronization, parser and large-review persistence | Complete `tests/integration/test_realtime_phase3_http.py` (25 cases), including `test_http_selection_removal_cancels_running_runtime_tool`, both `test_real_parser_invalid_utf8_persists_protocol_error` variants and both `test_large_eligible_review_persists_and_replays` variants |
| Prior repairs, streamed oversize/pre-extension rejection, zero unauthenticated/CSRF consumption, receive/retry timeouts | Unchanged cases in `tests/unit/test_phase3_http_repairs.py`; all 55 original `tests/unit/test_phase3_repairs.py` remain byte-identical to 9be4719 |
Observed baseline on this machine using the same actual JSON and ReviewDecision
validator: inline maximum heartbeat gaps 219.08/431.75 ms; a thread still produced
215.07/336.19 ms gaps. This directly supports using a separate GIL rather than
claiming that thread offload proves voice responsiveness. The final focused child
processing run measured 26,784,224 bytes in 1,069.90 ms (103 heartbeat ticks,
maximum gap 14.03 ms) and 59,504,172 bytes in 1,329.13 ms (130 ticks, maximum gap
11.64 ms). These are measured scheduler gaps and end-to-end processing latency,
not an SLA or real speech/hardware certification. Smaller intermediate focused
runs measured gaps of 10.71–13.42 ms; they are not substituted for the final run.
### Exact final commands and outcomes
All pytest commands used the existing Linux environment and local socket access;
there were no real provider calls. Final focused measurements above came from:
```sh
.venv/bin/python -m pytest tests/unit/test_json_processing.py tests/unit/test_phase3_acceptance_repairs.py tests/unit/test_phase3_http_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_gemini_live.py -q -s -p no:cacheprovider --tb=short
# 92 passed in 11.37s; includes all 55 restored ingestion cases and ten Gemini cases.
.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
# FINAL: 1753 passed, 2 existing Windows-path skips, 397 PostgreSQL cases deselected;
# 161.89s. Includes the nested full-suite ambient-configuration acceptance driver.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# FINAL completed run: 25 passed, zero skips, 369.84s.
env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_large_eligible_review_persists_and_replays -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Expected exit 1: two setup errors, TEST_DATABASE_URL required, 0.57s; zero skips.
git diff --check
# Passed. Eight affected Python AST parses and new-file whitespace checks passed.
```
Diagnostic/intermediate commands and outcomes are preserved rather than silently
replaced by final successes:
```sh
PYTHONPATH=/tmp:. .venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -s -p no:cacheprovider -p phase3_wait_diagnostics --tb=short
# Temporary timestamp/stack plugin: 10 passed in 1.82s; 484.81 ms cold construction.
.venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short
# Without diagnostic wrappers: 10 passed in 1.50s, before the repair.
PYTHONPATH=/tmp:. TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'running_runtime_tool or real_parser' -m postgres --require-postgres -q -s -p no:cacheprovider -p phase3_wait_diagnostics --tb=short
# Before framework preparation: 2 passed, 1 failed, 22 deselected in 30.47s;
# 3366.14 ms cold import with live stack evidence; no interruptions/skips.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'running_runtime_tool or real_parser' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# After preparation: 3 passed, 22 deselected, zero skips in 19.04s.
PYTHONPATH=. .venv/bin/python /tmp/phase3-thread-measure.py
# Temporary generated-body comparison: same decision_bytes(4499/10000) fixture,
# actual validate_json(raw, ReviewDecision), inline versus asyncio.to_thread,
# concurrent 10 ms monotonic heartbeat; measurements recorded above.
```
The temporary diagnostic plugin and comparison script live outside the repository.
An initial focused JSON run had 78 passes and one test-harness spawn error:
pytest's automatically generated name for 70,000 invalid bytes made
PYTEST_CURRENT_TEST exceed the OS environment-entry limit. Explicit short
parameter IDs corrected that harness error without changing payloads/assertions.
A 67-case HTTP/Gemini/startup checkpoint passed. Focused checkpoints passed 90 and
91 cases as lifetime and optional-framework regressions were added; complete
provider-free checkpoints passed 1,751 and 1,752 cases before the final 1,753-case
run. An earlier completed affected PostgreSQL run passed all 25 cases in 365.18s
before the final retained-DTO lifetime pass. No acceptance run in this follow-up
was interrupted or counted as success while unfinished.
At task start 238 repository files were hashed. Only seven baseline files changed:
`app/api/v1/dependencies.py`, `app/api/v1/documents.py`, `app/main.py`,
`app/modules/knowledge/langchain_tool.py`, `tests/unit/test_realtime_phase1.py`,
this handoff and the reference map. The other 231 remain byte-identical, including
all 55 restored ingestion regressions, both provider adapters/selection, OCR
profiles and independent factual approval, original/protected inputs, shared
retrieval and applied migrations 0001–0005. Three scoped files were added:
`app/infrastructure/json_processing.py`, `tests/unit/test_json_processing.py` and
`tests/unit/test_phase3_acceptance_repairs.py`. Unrelated prior working-tree edits
were retained. No production UI, dependency, external service, parser replacement
or unrelated refactor was introduced.
The only unresolved historical wait cause is the earlier parser connected-state/
shutdown stall; its origin is not inferred from later green runs. This follow-up
has completed affected acceptance, not real-provider quality certification.
Funded Gemini/OpenAI selected-model acceptance, Persian speech, browser
microphone/playback hardware, actual frontend UI and production HTTPS/proxy
acceptance remain unrun and require their respective credentials, opt-in,
approved corpus/calibration and deployment/hardware prerequisites.
Final database cleanup: `rag-phase3-json-test` was created with
`docker run --rm -d --name rag-phase3-json-test --tmpfs /var/lib/postgresql/data -e POSTGRES_PASSWORD=fixture -e POSTGRES_DB=rag_json_test -p 127.0.0.1:55439:5432 pgvector/pgvector:pg16`.
After completed acceptance, SQL inspection found **zero application test schemas**
(excluding the intended test_vector extension namespace) and **zero public tables**.
`docker stop rag-phase3-json-test` removed the container and its tmpfs database.
No existing database/container was modified.
+8
View File
@@ -300,3 +300,11 @@ See [integration validation and operator handoff](ingestion-operator-handoff.md)
for the consolidated command sequence, JSON heartbeat/stage/error reporting,
end-to-end PostgreSQL acceptance and opt-in app.ingestion_smoke command.
Existing chat remains on Chroma; scoped pgvector search/selection is next.
## OCR supervisor startup setting
Set `INGEST_OCR_REVIEW_REQUIRED=true` (default) or `false` in the API/worker
deployment environment. API enqueue freezes the setting; workers ignore their
current value for existing jobs. Legacy snapshots remain mandatory-review and
retry preserves the same job/profile. Factual/non-OCR review and inactive ready
publication remain required. See [Phase 3 handoff](realtime-agent-phase3-handoff.md).
+30 -10
View File
@@ -1,15 +1,18 @@
# OpenAI Realtime Agent — Fast MVP Implementation Plan
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).
## 1. Goal and implementation decisions
@@ -518,3 +521,20 @@ existing 50 ms test remain preserved. Historical results above remain distinct.
Real provider/speech/browser and isolated PostgreSQL acceptance remain unrun,
subject to authorization/calibrated actor/corpus prerequisites and fail-closed
calibration/cancellation classification. Scope remains Phase 1.
## Phase 3 implementation checkpoint (2026-10-09)
The authenticated document/review/retry/selection/read-only configuration surface
and frontend developer handoff are implemented. Existing intake, review/resume,
fenced publication and atomic selection are reused; there is no new migration,
worker replacement, public search/text route, settings editor or production UI.
The two remaining Phase 2 transport findings are repaired. See the
[Phase 3 handoff and validation](../guides/realtime-agent-phase3-handoff.md).
The additional authorized backend OCR supervisor setting defaults to true and is
frozen in new jobs. False admits only clean automatically validated OCR; legacy
profiles, factual authority, non-OCR review, integrity and explicit selection
remain protected. Mixed extraction uses partially_reviewed rather than claiming
human inspection of automatically admitted pages. Provider selection and all
other Phase 2 repairs remain unchanged. Backend contract acceptance does not
certify real-provider/Persian quality, frontend implementation or browser hardware.
@@ -287,3 +287,22 @@ resources. Storage retention/purge remains an owner decision.
Read the implementation guide for work packages, API/database contracts for
transport/persistence and the English scenario report for concrete walkthroughs.
The reference map/setup guide remain the evidence of existing component progress.
### 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).
+60 -17
View File
@@ -1,15 +1,18 @@
# RAG Assistant — Phase 1 API Catalog
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 contract; planned endpoints are not claimed operational.
@@ -93,7 +96,7 @@ No body. Same identity/CSRF/expiry shape as login. Missing/expired session retur
`multipart/form-data`: required `file`; optional `title`. Required `Idempotency-Key`. The server creates one independent document and ingestion job. New document is inactive.
Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport remains planned.
Current local intake validates configured PDF, UTF-8 Markdown, DOCX, JPEG and PNG with byte/signature/package/image bounds and correct MIME. D01 accepts new files without a repository filename/hash allowlist. The four examples are acceptance fixtures, not upload eligibility. Stream/spool within configured limits; do not buffer an unbounded request. These engineering defaults do not imply every layout is extractable or total corpus capacity is unlimited. D01 HTTP transport is implemented; see the Phase 3 handoff.
```json
{"document_id":"10000000-0000-4000-8000-000000000001","job_id":"40000000-0000-4000-8000-000000000001","status":"queued","is_active":false,"searchable":false}
@@ -111,7 +114,7 @@ Query: common pagination; optional `status=queued|processing|ready|failed`, `is_
{"id":"10000000-0000-4000-8000-000000000001","title":"Working Hours","filename":"working-hours.pdf","status":"ready","is_active":false,"searchable":false,"created_at":"2026-10-05T09:00:00Z","chunk_count":8,"job":{"id":"40000000-0000-4000-8000-000000000001","status":"succeeded","stage":"publish","attempt_count":1,"retry_generation":0,"can_retry":false,"error":null}}
```
`searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail may include `review_required:false` for other outcomes. D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
`searchable = ready AND active AND not deleted AND not content-purged`. A review-required failure is failed with a safe reason and `review_required:true`; it is not a new lifecycle state. Detail includes `review_required`, `review_state`, frozen `ocr_review_required` and `extraction_quality_decision` (null before complete extraction). D06 supplies retained review evidence only to admins. Poll while queued/processing; proposed interval 2 seconds, slow down when tab is hidden. Failed job exposes `{code,message,retryable}` without internal stack traces. `can_retry` means server allows retry of the unchanged original; corrupt input generally requires new upload. Return 404 for deleted/hidden ID.
### D04 — Retry failed processing
@@ -215,7 +218,7 @@ Duplicate IDs: 422. Any unready item: 409 `DOCUMENT_NOT_READY`, with rejected ID
### F01 — Read
```json
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":null}}
{"revision":1,"assistant_name":"Organization Assistant","instruction":"Reply concisely in Persian using authorized document evidence.","capabilities":{"text":false,"voice":true,"captions":true,"supported_upload_types":["<confirmed-MIME-type>"],"max_upload_bytes":20971520,"ocr_review_required":true}}
```
Runtime must replace illustrative capability placeholders with actual configuration; `max_upload_bytes` is a positive integer in deployed responses. Add configured `max_pdf_pages` and a bounded `supported_structure_notes` description. Voice/captions capabilities reflect validated provider support, not assumed availability; captions=true above is the intended release outcome. The browser must not advertise full text chat. No settings mutation UI is required. No model secrets or selectable model list. Non-admin may read presentation settings/capabilities.
@@ -276,15 +279,15 @@ Scope key `(conversation_id,client_request_id)`. Changed message under same key:
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — Gemini Live temporarily; frozen application audio/events
## 7. Voice contract — backend-selected provider; frozen application audio/events
The current provider is Gemini Live managed by the backend. Earlier OpenAI-specific
provider mechanisms below describe the retained Realtime adapter; the Gemini
The selected provider is backend-managed Gemini Live or OpenAI Realtime. The
OpenAI-specific mechanisms below describe the preserved Realtime adapter; the Gemini
adapter uses native setupComplete, voiceActivity, toolCall/toolResponse and
transcription. Missing verified input boundaries fail safely. Interruption
requiring unheard-audio context repair closes the session rather than inventing
a cancellation/truncation acknowledgement. The browser still uses 24 kHz mono
PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
PCM16LE; Gemini input conversion to 16 kHz occurs inside the adapter. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. Phase 0 freezes the application audio/event fields below. Technical implementation evidence and remaining live acceptance prerequisites are recorded in the Phase 2 repair report. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
### V01 — Create session (HTTP)
@@ -557,3 +560,43 @@ safe codes never return keys or native provider errors. HTTP authentication
failures normalize to `AUTH_REQUIRED`, CSRF to `CSRF_INVALID`, hidden resources
to `NOT_FOUND`, admission throttling to `RATE_LIMITED` with Retry-After, and
unexpected dependency failures to `DEPENDENCY_UNAVAILABLE`.
### 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 additive admission diagnostics (2026-10-09)
V01, by-request recovery and V03 polling expose calibration_status with values
calibrated, uncalibrated or unknown (legacy reservations without search metadata).
It is derived from the frozen server execution profile, never supplied by clients.
F01 capabilities additionally expose calibration_status and voice_transport_testing.
With explicit server VOICE_TRANSPORT_TESTING=true, missing/pending calibration
permits voice connectivity using configured embedding transport. This does not
change Section 7.2 evidence admission: search returns error/CALIBRATION_REQUIRED
without sources until measured calibration exists. Default false retains strict
admission. Origin/CSRF, ownership, epochs, deduplication and provider pinning remain.
Leading unstyled FAQ introductions appear in factual review and in each included
pair's source context. Recognition warnings or complete=false with legible blocks
produce extraction review candidates, including when frozen ocr_review_required is
false. D06/D07 and same-job D04 approval/retry semantics remain unchanged; no chunks
are published while review is pending. Approval attests to exact output, including
completeness; reject missing/inaccurate content rather than approve guesses. Fatal
format/provenance/readability failures still map to EXTRACTION_QUALITY_FAILED.
@@ -1,15 +1,18 @@
# RAG Assistant — Phase 1 Database Design
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 · Live document MVP persistence contract; proposed forward changes are not applied migrations.
@@ -385,7 +388,7 @@ Keep source identity rows as tombstones if allowed. `available` in API is comput
UNIQUE(owner_user_id,client_request_id). Partial UNIQUE(conversation_id) WHERE status IN ('creating','connecting','connected'). Scoped and chain-consistent FKs ensure owner/auth session belong to same organization and user; live conversation is owned by that user. CHECK terminal implies closed_at set. No SDP replay field is required for the OpenAI Realtime WSS flow. Store no raw audio. Provider credentials are server configuration, never database plaintext. Application stream path derives from session ID; it is not a bearer provider credential.
API instance owns the direct OpenAI Realtime WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
The single API process owns the selected direct Gemini Live/OpenAI Realtime WSS connection and audio relay in memory; DB stores mapping/state, not recoverable media. After API restart, mark nonterminal sessions failed and attempt cleanup. Reconnection uses a new session. Poll returns recent tool_calls, not a fabricated transcript. Available current-session provider transcripts are relayed to the UI with completion/interruption state; durable full voice message storage is deferred. Existing text messages/turns are not silently reused for voice.
### 6.2 audit_events
@@ -465,3 +468,22 @@ Text finalization/history/citation tests belong to the later text milestone.
## 10. Deliberately absent from Phase 1
No per-organization vector database, message broker tables, raw audio blobs, arbitrary tool schema registry, retention scheduler, multi-version assignment workflow or model catalogue. Full document bodies are in file storage/chunks; original files and recordings are not PostgreSQL byte arrays. Keep no production capacity or retention claim until stakeholders supply those requirements.
### 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).
@@ -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.
@@ -160,3 +160,22 @@ Rehearse browser upload -> review if needed -> ready -> activate -> real Persian
voice -> shared retrieval -> spoken answer/sources on target HTTPS/network.
Record actual errors/latency/provider usage and limits, not invented accuracy
percentages or unexecuted acceptance claims.
### 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).