feat(voice): add authenticated Phase 2 live lifecycle

Add cookie authentication, owned conversations, durable Live reservations,
tool completion/replay fencing, revocation, and startup reconciliation.
Introduce forward lifecycle/owner-chain migrations and the temporary Gemini
adapter while preserving the existing OpenAI Realtime adapter.

Include the executable audio client, regression coverage, configuration,
API/database documentation, and recorded acceptance evidence.

Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript
syntax, and whitespace checks passed. Full PostgreSQL/provider-free results
are recorded in the repair report; real-provider/browser acceptance is unrun.

Follow-up work remains for configurable OpenAI/Gemini selection, transport
admission, authority diagnostics, playback message bounds, and client replay
identity after ambiguous creation responses.
This commit is contained in:
11linear11
2026-10-09 07:59:02 -04:00
parent 07245cd5ca
commit 996435d2ae
42 changed files with 4551 additions and 88 deletions
+53
View File
@@ -1,5 +1,16 @@
# Phase 1 agent reference map
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).
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Current voice contract amended 2026-10-08 by Realtime Phase 0; English revision 1.3 remains the broader scope baseline. Historical component evidence below is preserved; the English revision 1.3 documentation checkpoint reran no application/provider/database tests; current repair acceptance is recorded at the end. Use the latest applicable recorded acceptance, not earlier unavailable-database reports. Dated component records below describe their historical checkpoint; absence-of-worker statements there are superseded by the current Phase 5/6 inventory and repair evidence.
## Authority and document resolution
@@ -1818,3 +1829,45 @@ and fixture-correction reruns are recorded separately in the guide.
Real provider, browser playback/Persian speech and isolated PostgreSQL acceptance
remain unrun. Existing authorization, actor/corpus/profile/calibration gates and
fail-closed cancellation classification still apply; no Phase 2 work was added.
## Current Phase 2 repair inventory (2026-10-09)
- Deployment configuration: `app/modules/voice/configuration.py`; finite limits
remain in `app/modules/voice/settings.py`.
- Cookie auth and C01/V01-V04/WSS: `app/api/v1/auth.py`, `dependencies.py`,
`conversations.py`, `live.py`; bounded blocking work in
`app/infrastructure/blocking.py`; application lifecycle in `app/main.py`.
- Durable admission/completion: `app/modules/voice/lifecycle.py`,
`durable_tools.py`; post-commit loop notifications in `registry.py`.
- Forward owner-chain repair: `migrations/versions/0005_live_owner_chain.py`.
Revisions 0001-0004 are preserved.
- Gemini adapter: `app/infrastructure/gemini_live.py`; shared canonical search,
StructuredTool and SearchToolRunner are retained.
- Exercised developer audio example: `examples/voice-client.js`,
`examples/voice-audio-worklet.js`; guide linked in the repair report.
- This Linux environment uses `.venv/bin/python`, not the historical Windows
`.venv/Scripts/python`. Existing timeout validation creates a local socket;
sandbox denial must be distinguished from an application validation defect.
Exact executed checks, remaining provider limitations and preservation evidence
are recorded in the [Phase 2 repair report](guides/realtime-agent-phase2-repair.md).
## Remaining Phase 2 defects checkpoint (2026-10-09)
The [current repair record](guides/realtime-agent-phase2-repair.md#remaining-defect-repair-2026-10-09)
supersedes affected initial Phase 2 behavior. Native pending generations retain
their input identity; ambiguous overlapping speech closes safely. Gemini PCM
admission uses packed bounded slabs separately from controls and shares the
runtime aggregate backlog. Durable canonical technical errors coalesce/replay
with fresh eligibility checks. Legacy creation hashes are verified against
persisted payload/configuration before atomic normalization; migrations 0001-0005
remain immutable. The delivered VoiceClient now owns resources by connection
generation, coordinates V04 before transport teardown, and attempts logout
independently of close failure. Partial application startup always cleans up.
Regression sources add `tests/unit/test_phase2_remaining.py` and executable
`tests/support/voice_client_harness.mjs`. Actual client/ASGI/PostgreSQL close
acceptance uses a local transport bridge; Node executes the delivered client and
worklet. Exact results and unrun real-provider/browser prerequisites are in the
repair record. No selected-model multi-turn or frontend readiness claim is made.
@@ -0,0 +1,73 @@
# Authenticated Gemini voice integration
Gemini Live is temporarily the sole voice provider because 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.
Use the [client module](../../examples/voice-client.js) and
[audio worklet](../../examples/voice-audio-worklet.js), served on the configured
same origin. This is a developer example, not a production interface.
```js
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
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();
// On logout: await client.logout();
```
`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.
Connected/terminal recovery does not restore media/provider context. Close the
old reservation before requesting a fresh conversation and session.
The exercised schemas are `session_ready`, `transcript` (role user/assistant,
status partial/completed), `sources`, `user_speech_started`, `audio_started`,
`audio_ended`, `turn_interrupted`, `error`, and the sole client control
`playback_progress` with `audio_ref` and cumulative `played_ms`. Transcripts
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
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
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
while the socket is usable, commits HTTP V04, and then closes transport/audio.
Requests wait at most five seconds each, flush at most 250 ms and AudioContext
close at most one second; a genuine transport loss stays a failure.
Connection generations own their audio, tracks and callbacks. Late permission
results are stopped immediately, cleanup is coalesced, and callbacks from an old
socket cannot close a newer session. Logout always attempts A02 even if identity
refresh or V04 fails, then clears local resources and identity. Valid sessions
retain CSRF enforcement; expired/repeated logout still validates Origin.
Canonical search errors for an eligible turn are displayed while its authorized
spoken explanation and later interaction continue. Setup/transport/overflow,
authority and context synchronization failures stop resources. Error fatality is
not inferred from retryable alone. The client does not retry tool execution.
Identical durable technical results replay only after fresh backend eligibility
checks; cancelled/revoked/stale-parent results cannot continue.
Gemini setup readiness requires native setupComplete, not an echoed requested
configuration. This profile requires native voiceActivity with usable offsets;
missing boundaries fail safely. Input transcripts without offsets become
ambiguous after more than one input; that fails rather than rebinding delayed
speech. Output transcripts use outputTranscription. There is no verified
sample-level Gemini context truncation: interruption/context cleanup closes the
session and requires freshSession. Seamless barge-in is not certified. Diagnostic text smoke uses native clientContent; first correlated model/tool
output proves input consumption. It never fabricates an item acknowledgement.
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).
+11
View File
@@ -1,5 +1,16 @@
# Realtime Phase 1 operator/runtime integration
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](realtime-agent-phase2-repair.md).
Phase 1 adds the private [wire adapter](../../app/infrastructure/realtime.py),
[application runtime](../../app/modules/voice/runtime.py),
[operator smoke command](../../app/voice_smoke.py) and
+317
View File
@@ -0,0 +1,317 @@
# 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.
The implementation and technical acceptance below are distinct from real Gemini
access, retrieval quality and browser/Persian voice acceptance. This report does
not certify frontend readiness or seamless interruption.
## Findings → fixes → regressions
| Finding / work package | Implemented repair | Acceptance evidence |
| --- | --- | --- |
| Credentials/model read from RuntimeSettings; hardcoded calibration status path (1) | Validated VoiceSettings supplies Gemini credentials, configured model/voice/proxy, exact origins/hosts, explicit cookie security, lifetimes and measured report path. RuntimeSettings retains finite bounds. Reservation snapshots actual voice, calibration and embedding metadata and revisions. No OpenAI voice key is required. | Configuration rejection/selection tests in test_phase2_lifecycle; actual configured Gemini operator test in test_gemini_live; real reservation/stream in test_phase2_postgres. |
| Synthetic configuration and tool terminal acknowledgements; missing correlation (2) | Native setupComplete confirms setup without copying requested settings. Native voiceActivity offsets identify inputs; first correlated native output proves consumption. Native tool requests produce a private waiting_tools phase, not a fabricated terminal event. Matching toolResponse IDs carry complete canonical results once, with bounded translation and duplicate admission. Native outputTranscription supplies assistant transcripts. | Actual Gemini adapter + VoiceRuntime + canonical SearchService + StructuredTool/shared runner unit cases; actual ASGI/durable tool cases for ok/no_evidence/error. |
| Audio format mismatch and unsafe interruption (2/7) | Browser PCM16LE mono remains 24 kHz. Bounded streaming 2/3 FIR conversion supplies 16 kHz Gemini input; output MIME/rate/alignment are verified. Unsupported cancellation/truncation closes context safely and suppresses late output. Provider loss independently wakes and closes reception. | Resampler partition/count tests; provider-loss/frame/queue/context-error tests; blocked-browser cleanup and setup-loss PostgreSQL/ASGI cases. |
| Permissive auth/CORS/token transports and malformed CSRF (3) | Cookie-only opaque sessions store hashes; constant-time bounded CSRF checks; exact configured Host/Origin; restricted credentialed CORS; explicit Secure/HttpOnly/SameSite policy. Canonical /me returns real expiry. Valid logout needs CSRF; missing/expired/repeated logout clears cookies after Origin. Bounded global login/provider admission. Strict DTOs and safe correlated HTTP envelopes. | Malformed token/CSRF/Origin/DTO unit tests; actual login/me/logout/replay/security/expiry and query-token rejection against PostgreSQL. |
| Missing owner chain and concurrent creation/expiry races (4) | Forward 0005 adds conversation/auth owner-chain constraints and distinct public tool references. Settings-first serialization rechecks enabled actor/auth/owner/epoch/expiry inside admission. Same normalized creation replays; changed payload conflicts; competing reservations are busy. Expired rows/calls terminalize before replacement. V03 is owner-only and never opens a provider. | Independent connections and start barriers for identical/changed C01/V01, competing reservations and tool admission; actual wrong-owner/auth FK rejection, expiry replacement and V03 replay tests. |
| Persistence inferred from sources and ON CONFLICT-only dispatch (5) | DurableTools wraps actual validated StructuredTool invocation. Insert owns execution; running duplicates poll shared durable completion; completed duplicates replay only after fresh checks; conflicts never retrieve. Full canonical results/revisions/epochs are persisted. Completion is fenced against call/parent/auth/expiry/epoch and cancellation. Result/source/continuation delivery rechecks eligibility. | Real duplicate completion with one invocation; conflicting arguments; cancellation/close/logout/restart/selection late completion tests; actual ASGI persistence and matching private/public identities. |
| Saved evidence exposed without redaction (6) | Poll returns at most 20 rows ordered deterministically by timestamp/id, chronological, with public UUID references and normalized diagnostics. Current document/chunk scope and ready/active/undeleted availability govern excerpts; unavailable identities remain, excerpts are redacted. | Real revoked-source redaction and public-reference test. |
| Snapshot-only authority, blocked receive, stranded media guard and readiness races (7) | Persisted session and per-turn SearchExecution authority is captured/rechecked. One media guard covers acceptance/setup/stream/cleanup. Independent cleanup survives ASGI cancellation. Browser/provider/runtime/expiry/revocation/shutdown are supervised. connected_at follows native setup plus successful application readiness delivery. Immediate post-ready PCM waits for the verified readiness transition. | Real authenticated ASGI first-frame/tool cases; provider loss while browser blocks; HTTP close/logout/disablement/auth and Live expiry/epoch/shutdown; duplicate media before setup; failed acceptance and setup-loss tests. |
| Thread-unsafe notifications and swallowed startup reconciliation (8) | Logout/selection transactionally terminalize running calls; selection stales old conversations. Post-commit notifications marshal to owning loops and filter pinned epochs. Persisted checks also cover separate maintenance processes. Startup requires 0005/reconciliation and never advertises readiness on failure. DB/password work is off audio reception through bounded blocking admission; shutdown bounds waits and disposes resources. | Notification thread/epoch unit test; actual selection/completion race, restart/logout and dropped-table startup failure; actual shutdown cleanup. |
| Incomplete/mismatched frontend example and cross-org provisioning (9) | Executable client/audio worklet implements aligned capture, bounded sending/playback, actual consumed-sample progress, final flush and cleanup, login/expiry/CSRF, replay/poll/recovery and fresh-session behavior. Provisioning refuses an existing username in another organization before any password/role/enablement update. | Node executes capture/playback/flush accounting; JS syntax checks; frozen schemas exercised by actual ASGI tests; real cross-org account preservation test. |
| Invalid PostgreSQL fixtures and sequential “concurrency” claims (10) | Phase 2 fixtures use actual accounts/password hashes/auth rows/settings and deterministically published ready documents/chunks. Independent SQLAlchemy connections and synchronization barriers test real constraints and races. Remote Gemini/embedding transports are deterministic; the lifecycle/runtime/tool/search boundaries are real. | Mandatory isolated PostgreSQL/pgvector suite and targeted provider-free suite below. |
## Files and boundaries
- Configuration/auth: [.env.example](../../.env.example),
[configuration.py](../../app/modules/voice/configuration.py),
[auth service](../../app/modules/auth/service.py),
[auth routes](../../app/api/v1/auth.py),
[dependencies](../../app/api/v1/dependencies.py),
[provisioning](../../app/provision.py).
- Lifecycle/transport: [forward migration](../../migrations/versions/0005_live_owner_chain.py),
[database compatibility](../../app/infrastructure/database.py),
[lifecycle](../../app/modules/voice/lifecycle.py),
[durable tools](../../app/modules/voice/durable_tools.py),
[registry](../../app/modules/voice/registry.py),
[blocking execution](../../app/infrastructure/blocking.py),
[conversation routes](../../app/api/v1/conversations.py),
[Live routes](../../app/api/v1/live.py), [application](../../app/main.py).
- Provider/runtime: [Gemini adapter](../../app/infrastructure/gemini_live.py),
[runtime](../../app/modules/voice/runtime.py), [operator smoke](../../app/voice_smoke.py).
The existing [search service](../../app/modules/knowledge/service.py) changes
only selection invalidation; retrieval remains the same.
- Handoff: [frontend guide](frontend-voice-integration-example.md),
[client](../../examples/voice-client.js), [worklet](../../examples/voice-audio-worklet.js).
Narrow current-provider notices update the reference map, plan, current operator
guide and API/database/implementation specifications; historical evidence remains.
- Regressions: test_gemini_live.py, test_phase2_auth.py,
test_phase2_lifecycle.py, test_voice_client_example.py and
tests/integration/test_phase2_postgres.py. Existing operator tests in
test_realtime_phase1.py/test_realtime_repairs.py inject the private adapter
factory, preserving their provider-neutral runtime assertions.
No deferred text/history tables, production UI, provider selector, Redis, new
agent framework, retrieval replacement or document-content versioning is added.
## Exact checks and outcomes
Commands run from the repository root. This Linux environment has
`.venv/bin/python`; the historical Windows `.venv/Scripts/python` does not exist.
Tests require normal local socket creation for the existing timeout validation
probe, so they ran outside the network-restricted shell sandbox. No remote AI
calls were made.
- Targeted final provider-free command:
`.venv/bin/python -m pytest tests/unit/test_gemini_live.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_lifecycle.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`
— **358 passed**, zero skips.
- Final targeted PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **41 passed**, zero skips, isolated database with pgvector.
- Full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1604 passed**, two existing Windows path-alias skips,
352 PostgreSQL cases deselected.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **352 passed**, zero skips, 1606 provider-free cases deselected.
The final affected PostgreSQL rerun also passed all **41** cases after the
bounded duplicate-wait and authority-diagnostic refinements.
- 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=no`
— expected exit 1 / one fixture error. This is prerequisite evidence only.
- `.venv/bin/python -m pip check` — unavailable: this environment has no pip.
Fallback `UV_CACHE_DIR=/tmp/phase2-uv-cache uv pip check --python .venv/bin/python`
— **61 packages checked; all compatible**.
- `.venv/bin/python -m app.voice_smoke --help` — passed, explicit provider opt-in
and bounded call/time arguments retained. No real smoke call was authorized.
- `node --input-type=module --check < examples/voice-client.js` and
`node --check examples/voice-audio-worklet.js` — passed.
- `git diff --check`, scoped new-file whitespace/UTF-8, Python ASTs (UTF-8-sig
for existing BOM files), TOML, links and SHA-256 preservation — **passed**. Final inspection covers all scoped tracked and new files:
27 intended baseline changes, nine new files and 175 byte-identical baseline files.
CLI help for app.provision and safe missing-Gemini-key/calibration capability
preflight also passed.
Initial checks exposed and corrected actual readiness/cleanup races. Other
failed runs were kept separate: sandbox denied the existing socket-timeout
probe; early ASGI fixtures used TestClient's untrusted default WebSocket host;
login admission persisted across test lifespans; a no-evidence fixture changed
its cutoff without updating the pinned snapshot. Fixtures now use explicit
trusted WebSocket URLs, isolated limiter state, valid measured-fixture snapshots
and cleanup barriers. None of these fixture repairs weakens production policy.
## Preservation and environment
Before editing, SHA-256 inventory captured **202 existing repository files**;
**27 intended baseline files changed, 175 remained byte-identical**. The manifest
is `/tmp/phase2-preservation.json`. Protected migrations 0001-0004 are unchanged;
0001-0003 also match HEAD. Revision 0004 was initially untracked and is treated
as potentially applied. Only forward 0005 repairs persisted ownership.
The initially modified pyproject.toml and test_migrations.py remain byte-identical
to the start-of-task baseline. The shared runner, RealtimeAdapter, RuntimeSettings,
proof scripts, frozen calibration/evaluation inputs and captured original documents
are unchanged. Unrelated working-tree edits are retained. No real ingestion,
calibration, embedding or voice calls were executed. Ignored external originals
and credentials were not edited; the manifest does not claim hashes for files
excluded from its initial repository inventory.
The system filesystem filled during implementation and prevented sandbox mounts.
Disposable repository/venv bytecode was removed; the venv temporarily moved to
/tmp and was restored at its original path. The user explicitly approved removal
of regenerable pip/uv caches outside the repository. Source and document content
were preserved. Acceptance uses a task-created PostgreSQL container/database with
application schemas isolated from public; final cleanup is recorded below.
## Remaining Gemini capabilities and external prerequisites
The existing intended configured Gemini model is preserved, including environment
overrides. Model availability and its actual native event layouts have **not**
been proven by live access. SetupComplete proves setup completion; it does not
return an echoed configuration. Native voiceActivity must contain usable audio
coordinates; absent/unsupported boundaries fail safely before tool/output release.
Input transcripts with offsets can retain their original turn; after multiple
inputs, missing coordinates are ambiguous and close rather than guess a binding.
Partial user transcription is supported without inventing a final ASR ack.
Mixed audio/tool phases without a safe layout also fail closed.
Google documents native [Live messages, activity, setup and tools](https://ai.google.dev/api/live)
and [audio formats/capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
These provide no verified sample-level unheard-audio context truncation for this
selected profile. Cancellation/truncation or native interruption therefore closes
and requires a fresh session. No synthetic terminal/cancel/truncate/input-commit
acknowledgement or seamless continuation claim is made.
Real calibrated retrieval quality, selected-model tool/transcription/event
behavior, Persian speech, latency, microphone/playback/hardware timing and full
browser acceptance are **unrun**. They require explicit real-provider opt-ins,
approved inputs/corpus, a measured profile-compatible calibration report and
budgets. The Node worklet test proves accounting/capture code, not heard audio;
ASGI tests prove application wiring with deterministic remotes, not Google service
availability. Final API shutdown waits are bounded; already-running synchronous
search work retains its runner slot until its actual bounded provider/database
work completes. Threads are not forcibly terminated or reported as erased.
Deploy forward 0005 before admission. It refuses preexisting inconsistent owner
chains rather than silently reassigning them. Configure production HTTPS trusted
origins/hosts, Secure cookies, Gemini access and the measured report. HTTP local
development requires explicit loopback-only COOKIE_SECURE=false. Health never
calls an AI provider. No production deployment was performed.
## Final cleanup
Acceptance used `pgvector/pgvector:pg17` in the task-created
`rag-phase2-acceptance` container, a loopback-only port and tmpfs database data.
TEST_DATABASE_URL pointed only to `rag_phase2_test`, with disposable application
schemas isolated from public. Before removal, queries confirmed **zero disposable
application schemas and zero public application tables**. The task-created
container/volumes were removed; preexisting containers were preserved. Temporary
logs and preservation inventories remain under /tmp for this session. No shared
or production database was migrated, reconciled or altered.
## Remaining-defect repair (2026-10-09)
This checkpoint supersedes the affected initial behavior above. Gemini remains
selected; model, voice, native interruption safe-close policy, browser 24 kHz
mono PCM16LE, public events/HTTP schemas and canonical search outcomes are
unchanged. No new migration or dependency is necessary.
### Verified findings, repairs and regressions
| Requested finding | Repair and observable coverage |
| --- | --- |
| 1. Pending input/generation rebound | A second distinct activity start while the first input/generation remains unfinished fails `LIVE_CONTEXT_SYNC_FAILED` before replacing its identity or releasing old output. Native completion allows ordinary sequential turns in deterministic tests. Runtime dispatch/result/transcript gates recheck turn eligibility; normally completed delayed transcripts remain eligible under the frozen contract. Delayed user transcription with coordinates retains its original input; ambiguous optional offsets still fail closed. `test_pending_input_cannot_be_replaced_before_first_output`, `test_actual_runtime_suppresses_delayed_first_output_after_new_speech`, and `test_sequential_native_turns_and_delayed_transcript_keep_original_identity`. |
| 2. Audio charged to controls | Adapter audio uses decoded, packed <=9600-byte slabs, with the existing aggregate 1440000-byte backlog, 512-slab and 65536-byte metadata bounds. A transfer reservation connects adapter backlog with runtime G/T/R; controls retain their independent count/byte admission and native FIFO order. Scratch bounds apply before decoding. Tiny adjacent deltas coalesce; capacity failure normalizes to `LIVE_BUFFER_OVERFLOW`. Tests admit a five-second burst, 120000 two-byte deltas, exact aggregate boundary, interleaved controls, slow consumption and actual runtime pacing. |
| 3. Client asynchronous ownership | Each connection generation owns its AudioContext, nodes, socket, callbacks, readiness and tracks. Cancellation checks follow preparation/readiness/acquisition; stale returned tracks stop immediately. Cleanup coalesces and remains idempotent; old callbacks cannot mutate a newer session. Executable VoiceClient scenarios cover pending permission, resolution during flush, acquisition rejection, preparation cancellation, concurrent cleanup, stale callbacks and a stalled AudioContext close promise. |
| 4. Canonical technical-error replay | A failed row containing a recognized canonical technical error with matching saved error code is eligible for coalesced/replayed completion after fresh authority, epoch, parent and source checks. Cancellation/revocation/abandonment never becomes eligible through a saved error. PostgreSQL barrier tests prove one invocation and equivalent original, running-duplicate and completed-duplicate results for `SEARCH_TIMEOUT`, `SEARCH_FAILED` and `PROVIDER_UNAVAILABLE`; logout and saved cancellation remain ineligible. Existing late-completion/source revocation regressions continue to run. |
| 5. Duplicate activity drops content | Duplicate START/END suppresses only boundary handling; accompanying native transcription, audio, tool requests and completion still run. Conflicting coordinates fail safely. Eight combined-message cases plus conflicting-coordinate coverage exercise the actual adapter. |
| 6. Nonterminal client errors | Eligible canonical search failures are displayed while authorized explanation and subsequent interaction continue. Setup, transport, overflow, authority and synchronization failures stop resources; socket close is independently terminal. Classification uses known contract codes and turn/readiness context, not `retryable` alone. Executable VoiceClient scenarios prove speech continuation and fatal cleanup. |
| 7. Logout depends on close | A02 is attempted independently when identity refresh or V04 fails. Local identity/resources clear afterward. Valid CSRF/Origin enforcement is unchanged. Executable client tests cover expired/revoked identities, close failure, valid and repeated logout; actual HTTP expired/repeated/valid logout acceptance remains in the PostgreSQL suite. |
| 8. Explicit close races transport | Capture stops and playback flushes actual final progress before V04; intentional socket teardown follows the HTTP operation. HTTP waits are bounded at five seconds each, flush at 250 ms, AudioContext-close waiting at one second. Actual Node VoiceClient/ASGI/PostgreSQL cases cover silent and active-playback close. The active case executes the delivered playback worklet, consumes 120 samples and sends its actual 5 ms progress. Both preserve `closed/user_requested`; existing genuine transport-loss/terminal-state tests remain. Hardware and Google transport are deterministic doubles. |
| 9. Blanket revocation diagnostics | Execution and delivery classify authority loss, cancellation, changed arguments, technical timeout, busy admission and SQL availability separately. No unverified result or continuation is released. Delivery mismatch is a context synchronization failure. Real SQL fault injection through ASGI proves `DEPENDENCY_UNAVAILABLE`, a durably failed session and zero toolResponse; runtime execution/delivery cases assert normalized failures rather than false revocation. |
| 10. Repair-upgrade replay | Verified original creation hashes are accepted only if the original persisted payload/pinned configuration also matches. Under the existing settings lock they normalize atomically to the current format. Representative rows at revision 0004 upgrade through immutable 0005 and replay with the same IDs, including null, empty, Unicode and original whitespace titles. Changed payloads, null/empty collisions and unknown hashes still conflict. No ownership, provider/model snapshot or row is reassigned/discarded. |
| 11. Partial lifespan leaks | Engine acquisition, lifecycle construction and reconciliation are inside cleanup ownership. Startup failure/cancellation leaves readiness false, disposes acquired engine, closes runner, clears service globals and shuts down blocking admission. Independent cleanup preserves the original startup error even if disposal also fails. Tests cover failure, cancellation, normal shutdown and subsequent startup, including an actual running bounded worker that retains its slot until completion. No thread is claimed forcibly terminated. |
Regression sources are [native/runtime/startup tests](../../tests/unit/test_phase2_remaining.py),
[executed client/worklet tests](../../tests/unit/test_voice_client_example.py),
[client harness](../../tests/support/voice_client_harness.mjs), and
[PostgreSQL/ASGI acceptance](../../tests/integration/test_phase2_postgres.py).
The harness loads the delivered [VoiceClient](../../examples/voice-client.js)
and [worklet](../../examples/voice-audio-worklet.js); it does not replace the
client implementation with a test-only imitation.
### Original hash evidence and upgrade limits
The earlier-session tool inspection at `2026-10-09T09:04:03.658Z` retained the
original lifecycle source. Its algorithm is SHA-256 over sorted compact JSON,
`ensure_ascii=False`, encoded as UTF-8. Original C01 fields were
`{user, request, mode, title: title or ""}`; original V01 fields were
`{owner, conversation_id, client_request_id, provider, model}`. Current C01
hashes normalized mode/title; current V01 hashes conversation identity only.
Compatibility reconstructs only those verified formats. C01 also compares the
original stored title exactly, preventing null/empty hash collisions from
weakening conflict detection. V01 uses the persisted provider/model, not current
configuration. Unknown hashes still fail. The tests upgrade isolated schemas;
no shared database or migration file was changed. Normal startup reconciliation
still terminalizes old media: compatible request identity is not recoverable
provider context.
Official Google [Live schema](https://ai.google.dev/api/live) was consulted for
activity accompanying native content, completion semantics and independently
ordered transcription with optional coordinates. The [capabilities guide](https://ai.google.dev/gemini-api/docs/live-api/capabilities)
was also consulted. These references do not prove the configured model's actual
ordinary multi-turn layout. Deterministic multi-turn tests are technical evidence
only; real model capability and ambiguity handling remain external acceptance.
### Executed checks
Final full-suite results below supersede preceding failed/interrupted runs.
Commands use `.venv/bin/python` in this Linux environment, `-p no:cacheprovider`,
and no real AI providers. PostgreSQL commands use only the task-created
`rag_phase2_test` database and independently disposable application schemas.
- Targeted runtime/auth/client/shared-runner command:
`.venv/bin/python -m pytest tests/unit/test_gemini_live.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_lifecycle.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`
— **400 passed**, zero skips. The client harness additionally reran after its
bounded AudioContext-close case was added and passed.
- Final affected PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **52 passed**, zero skips.
- Full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1646 passed**, two existing Windows path-alias skips, 363 PostgreSQL
cases deselected; 147.64 seconds.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **363 passed**, zero skips, 1648 provider-free cases deselected;
314.26 seconds.
- `env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_concurrent_and_completed_technical_errors_replay_one_invocation -m postgres --require-postgres -q -p no:cacheprovider --tb=no`
— expected exit 1, **three prerequisite errors**, zero database passes/skips.
- `node tests/support/voice_client_harness.mjs unit`, client/worklet/harness
JavaScript syntax checks, and
`UV_CACHE_DIR=/tmp/phase2-remaining-uv-cache uv pip check --python .venv/bin/python`
— passed; **61 installed packages compatible**. CLI help for app.voice_smoke
and app.provision, git diff --check, scoped Python AST/UTF-8, TOML, local
documentation links and protected-file hashes also passed.
Failed/interrupted runs remain separate from acceptance. The initial sandboxed
check had 19 passes and three existing socket-timeout validation setup errors;
normal local socket access resolved those. A subsequent sandboxed startup test
run was interrupted rather than claimed successful. One targeted run had 393
passes and one failure after an overly strict newly added guard suppressed a
normally completed delayed transcript; the guard was corrected and the 400-test
run passed. A full provider-free run was interrupted during that correction
(344 passes are not full acceptance).
The first active-playback bridge fixture lacked its base64 import and did not
close the outstanding test WebSocket on fixture failure: one case timed out;
the 48 passing cases were not called full acceptance. Both fixture issues were
fixed and silent/active cases reran with two passes. The first full PostgreSQL
run had 359 passes and one readiness-state assertion race: a delivered buffered
session_ready frame could be received before its documented subsequent durable
connected commit. The affected fixture now waits on that actual transition,
keeping the same connected assertion and existing three-second test barrier;
no production ordering or unrelated timing test was weakened.
### Preservation and remaining acceptance
The start-of-task inventory `/tmp/phase2-remaining-baseline.json` covers **211
existing repository files**. Final hashes show **13 intended baseline files
changed and 198 byte-identical**, with two scoped new regression files. All
migrations 0001-0005, extraction/embedding configuration, shared SearchService,
StructuredTool/SearchToolRunner, RuntimeSettings, RealtimeAdapter, original/proof
files and frozen inputs in that inventory are unchanged. Ignored credentials and
originals were not edited; inventory hashes are not claimed for excluded files.
Inherited working-tree edits are retained.
Changed baseline paths: Gemini adapter, VoiceRuntime, Live lifecycle, DurableTools,
Live routes, application lifespan, VoiceClient, its unit test and PostgreSQL
acceptance, frontend guide, this report, the plan and reference map. New paths:
`tests/unit/test_phase2_remaining.py` and
`tests/support/voice_client_harness.mjs`. No dependency, migration, production UI,
public chat/history, Redis, retrieval replacement or new agent framework is added.
Real selected-Gemini-model audio/tool/transcription/multi-turn layouts,
microphone/playback hardware, Persian speech, retrieval quality, latency and
full browser acceptance remain **unrun**. They require explicit provider opt-ins,
Gemini/model access, an approved eligible actor/corpus, a measured compatible
calibration report, approved inputs and call/time budgets. No real provider calls
or production deployment were made. Safe-close interruption remains disclosed;
this checkpoint does not certify frontend readiness.
Final cleanup for this remaining-defect checkpoint: the task-created
`rag-phase2-remaining-acceptance` container and its disposable data/volumes were
removed. Before removal, queries found **one disposable schema left by the
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.
+15
View File
@@ -1,5 +1,16 @@
# 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).
## 1. Goal and implementation decisions
Deliver a working backend for this browser workflow:
@@ -217,6 +228,10 @@ Do not add a new agent framework or rebuild ingestion/search.
### Phase 2 — Add trusted identity and durable Live lifecycle
Remaining-defect implementation and executed acceptance are recorded in the
[updated repair report](../guides/realtime-agent-phase2-repair.md#remaining-defect-repair-2026-10-09).
Real selected-model multi-turn behavior and frontend readiness remain unverified.
**Purpose:** Make the working runtime safely callable by the frontend.
**Implementation:**
+28 -2
View File
@@ -1,5 +1,16 @@
# 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).
Version 1.3 · 2026-10-07 · Current Live document MVP contract; planned endpoints are not claimed operational.
Companions: `RAG-Phase1-Implementation-Guide.md`, `RAG-Phase1-Database-Design.md`, `RAG-Phase1-MVP-Scenarios.md`. Scope follows `RAG-AI-Phase1-Delivery-Plan.md`. No document versioning is implemented: every upload is a new document; there is no version-upload route, model selector, mixed conversation or SSE in Phase 1.
@@ -265,9 +276,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 — OpenAI Realtime; frozen application audio/events
## 7. Voice contract — Gemini Live temporarily; frozen application audio/events
The initial provider is direct OpenAI Realtime managed by the backend. 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.
The current provider is Gemini Live managed by the backend. Earlier OpenAI-specific
provider mechanisms below describe the retained 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.
### V01 — Create session (HTTP)
@@ -531,3 +548,12 @@ Inside persisted jobs/sessions/tool calls, normalized codes include PROVIDER_TIM
Prove real native audio/tools early. Build A01/A03, bounded upload/polling, D06/D07 review and D04 resume, selection, C01 voice creation, V01-V04/WSS and read-only F01 capabilities. Full T01/T02/messages and settings editing are deferred. Display request progress and state rather than a fake percentage. Disable selection on non-ready documents. On stale conversation explain that sources changed and offer New Conversation. Do not automatically copy revoked context.
Out of scope: file-version API, raw downloads for ordinary users, document text editing, search HTTP endpoint, model selector, raw audio recording, streamed chat, mixed-mode history, full event replay. Sources needed by normal users are supplied in authorized message/session responses.
Current temporary Gemini capability failures before reservation are 503
`LIVE_PROVIDER_UNAVAILABLE` for missing voice credentials/profile access and
`CALIBRATION_REQUIRED` for a missing/invalid/incompatible measured report.
A configured profile is a prerequisite, not proof of provider access. These
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`.
@@ -1,5 +1,16 @@
# 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).
Version 1.3 · 2026-10-07 · Live document MVP persistence contract; proposed forward changes are not applied migrations.
Companions: `RAG-Phase1-Implementation-Guide.md` and `RAG-Phase1-API-Catalog.md`. Scope: PostgreSQL + pgvector, one organization, existing ingestion foundation, retained review decisions and owned voice/session/tool metadata. Durable text turns/messages/citations are deferred. No deployed database was queried; the repository foundation migration was inspected statically for this documentation update. Only seven foundation tables are currently implemented; compare this complete proposal with actual migrations before applying it. Live tables/SDP fields are not applied foundation schema.
@@ -1,5 +1,16 @@
# 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).
Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.
Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The [Realtime MVP plan](../plans/realtime-agent-mvp-plan.md) supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See [Phase 0 prerequisites and results](../guides/realtime-agent-phase0.md). Extraction/embeddings and HTTP/search contracts are unchanged.