docs(voice): plan phased local S2S adapter with execution prompts

This commit is contained in:
amirhosein mazaheri
2026-10-15 09:21:54 +03:30
parent 5a4786d0fe
commit 22f29b8d58
12 changed files with 981 additions and 0 deletions
@@ -0,0 +1,12 @@
# Local S2S phase prompts
Read [the complete plan](../local-s2s-adapter-plan.md) and [progress ledger](../local-s2s-adapter-progress.md). Each file contains one copy-ready English prompt. Run one phase at a time; never assume prerequisites passed.
- [Phase 0 - Baseline and immutable upstream audit](phase-00.md)
- [Phase 1 - Small provider boundary with OpenAI preserved](phase-01.md)
- [Phase 2 - Isolated S2S engine with OpenRouter stages](phase-02.md)
- [Phase 3 - Local provider and normal browser session](phase-03.md)
- [Phase 4 - Verified interruption and history synchronization](phase-04.md)
- [Phase 5 - Shared RAG and declared-source integration](phase-05.md)
- [Phase 6 - Persian quality, latency, cost and resilience](phase-06.md)
- [Phase 7 - Controlled switch and verified rollback](phase-07.md)
@@ -0,0 +1,57 @@
# Phase 0 - Baseline and immutable upstream audit
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 0 only: Baseline and immutable upstream audit.
Prerequisite:
No implementation prerequisite. The current deployment must remain unchanged.
Required visible outcome:
Produce a compatibility matrix and baseline evidence that a user can inspect before any adapter changes.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Capture baseline selected profile, preserved container IDs/image digests, ports and mounts without credentials; do not recreate containers.
2. Resolve an immutable speech-to-speech commit and dependency/build inputs. Inspect actual implementation/tests for setup, consumed input, manual turn control, identities, tools, audio, terminals, cancellation and history mutation.
3. Map each required operation to supported / patch-required / unverified. Explicitly flag no-op truncate and completed-but-unplayed assistant history.
4. Run focused current regressions and classify any pre-existing failures without changing assertions. Prepare an authorized frozen Persian fixture corpus and expected critical facts.
5. Record exact heard-prefix policy, profile attestation design, missing live prerequisites and decision owners. Propose alternatives without silently accepting weaker history behavior.
Acceptance criteria:
- Baseline and rollback identities are recorded; no service/data changes occurred.
- Upstream is pinned and every required semantic has a proof test or explicit gap.
- Existing test failures, missing credentials and live-unverified items are visible.
- No unsupported acknowledgement is accepted by inference.
Relevant paths (verify actual locations before editing):
app/modules/voice/, app/infrastructure/realtime.py, voice_provider.py, gemini_live.py, app/api/v1/live.py, app/main.py, current tests and pinned upstream sources.
Validation:
Use current selected-provider/context-sync/search-reuse/sources/output-limit/style tests; inspect lifecycle/profile and schema constraints. No paid calls.
Visible demonstration:
Open the compatibility matrix and replay one existing offline interruption trace. The user sees what works and what needs a patch.
Explicit stop/narrow condition:
Unknown semantics stay unverified. Do not start refactoring or downloading models in this phase.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-00.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,57 @@
# Phase 1 - Small provider boundary with OpenAI preserved
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 1 only: Small provider boundary with OpenAI preserved.
Prerequisite:
Phase 0 audit, scoped contract proposal and baseline evidence exist.
Required visible outcome:
OpenAI still produces the same command/ack behavior through a provider boundary; show a deterministic before/after replay.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Implement minimal internal typed operations/events for actual runtime needs, preserving raw provider replay fingerprints and identities.
2. Keep turn ownership, authorization, evidence, deadlines, audio credits, final played positions and next-turn release in runtime. Move native encoding/parsing and confirmation interpretation into adapters.
3. Define interruption progress with operation/response/item/session identities and separate generation-stop/history-repair proof. Capability declarations must not waive cleanup.
4. Adapt OpenAI using existing cancel/terminal/truncate semantics unchanged. Preserve Gemini conservative failure. No model/voice branches in shared control.
5. Add controlled-clock regression/replay tests and document the internal responsibility amendment while keeping browser wire behavior fixed.
Acceptance criteria:
- Existing OpenAI assertions remain and affected tests pass, with prior failures reported honestly.
- Before/after trace releases exactly one next response after matching cleanup.
- Wrong/missing/late/duplicate-conflicting events, limited tools and timeouts fail safely.
- No deployment/default change or unnecessary persistence migration.
Relevant paths (verify actual locations before editing):
runtime.py, a minimal internal provider-contract module if justified, realtime.py, Gemini adapter only where needed, diagnostics and focused tests.
Validation:
Provider-free adapter/runtime conformance plus existing races, final playback, output limits and evidence tests. Isolated PostgreSQL only if persistence behavior changed.
Visible demonstration:
Replay a fixture: interrupted old output stops, matching final played position is confirmed, and one new response begins.
Explicit stop/narrow condition:
No wholesale state-machine rewrite or generic provider-error suppression.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-01.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,57 @@
# Phase 2 - Isolated S2S engine with OpenRouter stages
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 2 only: Isolated S2S engine with OpenRouter stages.
Prerequisite:
Pinned engine/build design from Phase 0; independent of Phase 1 where no application integration is used.
Required visible outcome:
A Persian recording independently becomes a transcript, LLM response and playable WAV with stage timings and actual usage.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Build a separate pinned engine image/environment. Use local VAD and independently configured remote STT, Chat Completions LLM and TTS.
2. Discover/pin supported model IDs/voices/parameters and test Persian language behavior. Choose a tool-capable text LLM, not an assumed universal audio endpoint.
3. Verify explicit credential forwarding, multipart/JSON STT, TTS stream fields, raw PCM rate/endianness and startup probes. Add a narrow shim only for an observed mismatch.
4. Use final-utterance STT initially. Bound retries, requests, response sizes, concurrency and cleanup; include startup probes in cost.
5. Provide deterministic stub mode and opt-in live smoke with bounded requests/time/cost. Save only consented evaluation outputs; do not connect to production DB/API.
Acceptance criteria:
- With authorized live prerequisites, all three stages succeed and output audio is valid; otherwise mark live-pending.
- Invalid key/model/voice/rate cannot produce false readiness.
- Models remain independently replaceable and keys remain server-side.
- Existing app, worker, database and rollback container are untouched.
Relevant paths (verify actual locations before editing):
An opt-in engine build/service directory, isolated Compose configuration, smoke command and evaluation fixtures. Do not vendor all upstream code into app/.
Validation:
Pinned upstream relevant tests and HTTP fixtures; optional bounded actual-provider requests. Ordinary tests require no keys or weights.
Visible demonstration:
Run the isolated Persian smoke, inspect its requested test transcript, hear the WAV and view per-stage timing/usage.
Explicit stop/narrow condition:
Missing keys/availability blocks live proof only. Do not install unrelated local-model/GPU extras.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-02.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,59 @@
# Phase 3 - Local provider and normal browser session
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 3 only: Local provider and normal browser session.
Prerequisite:
Phases 1 and 2 have accepted prerequisite evidence. Candidate app has disposable DB/storage.
Required visible outcome:
The existing browser opens a local_s2s session, greets in Persian, displays transcript and closes cleanly in isolation.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Add local_s2s to validated selection/factory/settings/readiness without removing openai/gemini or adding a UI selector.
2. Freeze engine/patch/contract revisions, effective component models, voice, speech policy, rates and instruction/config digest. Do not store secrets or secret hashes.
3. Compare reservation expectations with authoritative effective engine setup; do not rely on connection reachability or echoing desired values.
4. Map real input acceptance, response intent/identity, tool frames, terminal states and audio/transcript. Do not synthesize native commit acknowledgements from timing.
5. Keep browser PCM16LE mono24k and public events. Bound resampling and convert playback coordinates correctly.
6. Preserve owner/Origin/cookie/CSRF/replay/epoch checks and old profiles. Audit DB/DTO constraints; new migration only if necessary.
7. Use isolated DB/storage and separate test browser credentials/origin. Unsupported interruption fails closed until Phase 4.
Acceptance criteria:
- Ready/audio/transcript/close work end to end in the isolated app.
- Incorrect profile, configuration, ownership or epoch is rejected; no snapshot rewrites.
- Malformed terminals/disconnects cannot cause false success.
- This remains development-only, not operational parity or a default switch.
Relevant paths (verify actual locations before editing):
configuration.py, settings.py, voice_provider.py, new local adapter, live admission/lifecycle only where required, .env.example and isolated deployment config.
Validation:
Provider-free adapter contract tests, isolated PostgreSQL admission/replay/profile/revocation, then bounded browser live smoke.
Visible demonstration:
Use the existing browser to greet and close. Show the local pinned profile and separate OpenAI conformance results.
Explicit stop/narrow condition:
Never use a second port with the operational DB. No promotion before interruption/RAG acceptance.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-03.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,59 @@
# Phase 4 - Verified interruption and history synchronization
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 4 only: Verified interruption and history synchronization.
Prerequisite:
Phase 3 works in isolation. Upstream history/turn ownership and required patch are understood.
Required visible outcome:
The user interrupts a long answer and continues coherently; inspect the next model request to prove unheard sentinel text is absent.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Add an actual correlated engine repair operation/extension if needed. Pin the patch and test it independently; do not monkey-patch installed packages as the deployment strategy.
2. Handle both active generation and completed generation with audio still queued at the browser. Closing TTS HTTP or getting response.done does not prove history repair.
3. Track response/item/segment/session identities, final consumed position and reliable text/audio mapping; no proportional text slicing.
4. Preserve valid earlier user/assistant/tool state and remove unheard assistant continuation from subsequent LLM input. Verify applied history revision/digest.
5. If exact heard-prefix repair cannot be proven, keep this gate open. Whole-turn rollback or fully-played-segment-only retention needs explicit policy acceptance and contract changes.
6. Validate real applied receipts against operation identity; reject stale/missing/conflicting receipts with bounded safe failure. Runtime owns final release.
7. Suppress late STT/LLM/TTS work and preserve same-topic backend search independently. Re-run all affected OpenAI interruption tests.
Acceptance criteria:
- Generation stop, real context repair and application playback gates all precede next response.
- Active and completed-unplayed cases pass controlled history inspection and actual microphone testing.
- Wrong/missing receipts fail safely; late output cannot contaminate another turn/session.
- No fabricated conversation.item.truncated or weakened OpenAI checks; unapproved weaker policies block promotion.
Relevant paths (verify actual locations before editing):
Internal interruption contract, local adapter, pinned engine extension/patch, runtime barrier integration, diagnostics and regression tests.
Validation:
Controlled clocks, ordering, races, receipt replay, mid-segment interruption, teardown/reuse, terminal-completed/unplayed audio, plus actual bounded live interruption.
Visible demonstration:
Generate an answer with a late sentinel, interrupt before hearing it, inspect the following LLM context, then demonstrate real barge-in and continuation.
Explicit stop/narrow condition:
This is the highest-risk gate. Stopped playback or upstream SDK compatibility does not prove the required semantics.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-04.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,58 @@
# Phase 5 - Shared RAG and declared-source integration
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 5 only: Shared RAG and declared-source integration.
Prerequisite:
Phase 4 context safety accepted. Existing shared search and evidence policy remain authoritative.
Required visible outcome:
Document questions work with valid used sources, and a repeated interrupted question reuses one original retrieval.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Expose search_knowledge, reuse_last_evidence and report_used_sources schemas to the LLM. Execute through current dispatch, ToolContext, DurableTools and SearchService.
2. Preserve backend identity, eligibility, calibration, references, handoff/delivery revisions and access checks; no engine DB credentials or independent retrieval.
3. Validate streamed tool arguments after successful terminal validation; correlate call/item/response identities and deduplicate replays.
4. Preserve pending same-topic search with original deadline; revalidate reuse, discard changed-topic results, never use old assistant prose as evidence.
5. Validate current-turn source reports and repair invalid metadata privately. Only used sources reach UI; metadata reports create no retrieval row.
6. Exercise no_evidence versus technical error, limited tools, revocation/deactivation, interrupted source delivery and known name/percentage/date mistakes.
Acceptance criteria:
- All three tools use existing authority and canonical retrieval.
- No stale/inactive/deleted/revoked evidence is emitted, including reuse/delivery races.
- Repeated same-topic continuation causes no duplicate search; labels map to original document/chunk IDs.
- Evaluation checks actual answer facts, not only valid citation membership.
Relevant paths (verify actual locations before editing):
Local tool mapping, current runtime dispatch, durable_tools.py and shared knowledge services only as needed for a demonstrated integration change.
Validation:
Existing sources and retained-search tests extended to local, isolated PostgreSQL evidence/revocation acceptance and bounded live RAG fixtures.
Visible demonstration:
Ask hours/Thursday, the named deputy in the letter and incentive conditions; interrupt a search and repeat it while showing one retrieval and revalidation.
Explicit stop/narrow condition:
Do not loosen cutoff/authorization filters or introduce another search service to hide model failures.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-05.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,58 @@
# Phase 6 - Persian quality, latency, cost and resilience
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 6 only: Persian quality, latency, cost and resilience.
Prerequisite:
Phases 3-5 accepted; exact model/profile choices and frozen evaluation corpus recorded.
Required visible outcome:
A paired OpenAI/local scorecard and audio samples demonstrate measured accuracy, latency, failure behavior and cost per successful task.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Use identical authorized corpus/questions/audio fixtures for baseline and candidate; record exact profiles/sample counts.
2. Cover names/roles, numbers/dates, pauses/noise, correction/ambiguity, follow-up/topic switch, no evidence and conflicts.
3. Measure first audible response after speech end, first text/audio, tool time, interruption stop, underruns, duplicates, disconnects and completion rate.
4. Count actual returned input/output/cache usage, STT duration, TTS billed units, failed/abandoned work and startup probes; unknown costs stay unknown.
5. Fault-test slow/down providers, quota, partial stream loss, engine restart, saturation and teardown; no late contamination, unbounded queues or retry storms.
6. Change one component at a time. Predeclare thresholds and keep human Persian listening separate from transport checks. Do not tune thresholds after observing failures.
Acceptance criteria:
- Zero incorrect critical names/numbers/dates/conditions in the agreed fixture set; no fabricated unsupported answers.
- Interruption scenarios complete or fail safely as specified; no persistent underruns.
- Assess predeclared targets with counts and failures. Provisional p95 first-audible latency <= baseline + 1 second; cost/task <= 70% baseline for cost-saving promotion.
- If quality/cost targets fail, classify honestly and keep OpenAI. Missing live/human checks leave the gate open.
Relevant paths (verify actual locations before editing):
Evaluation harness, consented fixtures/annotations, content-free usage/timing diagnostics and only demonstrated bounded resource/error fixes.
Validation:
Focused regressions, isolated DB acceptance, controlled transport faults, authorized bounded paired provider evaluation and human listening.
Visible demonstration:
Play paired name/number/date clips; open the scorecard and demonstrate a controlled provider failure without cross-session output.
Explicit stop/narrow condition:
No blanket prompt/buffer expansion, selected anecdotes or mocked quality claims. Targets are provisional goals, not achieved measurements.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-06.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```
@@ -0,0 +1,59 @@
# Phase 7 - Controlled switch and verified rollback
Paste the following into a fresh implementation session in this repository.
```text
Implement Phase 7 only: Controlled switch and verified rollback.
Prerequisite:
All mandatory prior gates accepted; candidate configuration, evidence and rollback procedure are reviewable.
Required visible outcome:
Switch to local_s2s only when authorized, demonstrate a document interaction, then restore preserved OpenAI without rebuilding it.
Execution rules:
- Read docs/plans/local-s2s-adapter-plan.md and docs/plans/local-s2s-adapter-progress.md first. Read applicable AGENTS.md, repository skills and governing API/database/workflow sections. Inspect current code; historical defaults are not current evidence.
- Implement only this phase. Check actual prerequisite artifacts, not just the existence of code. State observed, simulated, unverified and blocked outcomes separately.
- Preserve OpenAI/Gemini behavior, original operational/rollback containers/images, frozen old profiles and unrelated working-tree changes. No database reset, compose down, pruning or implicit provider switch.
- Keep existing browser PCM24k/application events, backend-derived identity, one canonical search implementation, document/chunk references and authorization/revision checks.
- Make the smallest scoped change. No plugin framework, full runtime rewrite, new broker or unrelated refactor. Update intentional contracts and affected consumers coherently; never edit applied migrations.
- Ordinary tests are provider-free. DB acceptance requires a verified disposable TEST_DATABASE_URL and --require-postgres; never production. Do not run a parallel application API against the operational database.
- Reuse explicit authorization already present. Paid requests, downloads and operational switching need the applicable bounded authorization. Without it, finish independent offline preparation, identify the exact missing prerequisite and keep dependent live acceptance open.
- Do not print keys/full environments/raw provider payloads or real user speech. Consent-controlled fixture artifacts are separate from default logs.
- Never fake provider events, terminal success or history acknowledgements. Unsupported capabilities fail safely. Do not introduce automatic cross-provider fallback.
- Before finishing: inspect diff, run meaningful checks, record exact commands/results and demo steps, update the progress ledger and list all not-run checks. Do not accept a phase with required live/human checks unrun. Do not begin the next phase.
Required work:
1. Finalize opt-in Compose and .env.example; OpenAI remains default until explicit switching. No UI provider selector or automatic cross-provider fallback.
2. Verify original OpenAI container/image/config remain intact. Build separate candidate tags; never remove/prune/rebuild the original rollback target.
3. Check authoritative profile, readiness, credentials, rates/bounds and DB compatibility. An old-image-incompatible migration blocks simple rollback.
4. Drain/close current sessions, stop the current API, then start candidate on operational DB. Never run both against that DB simultaneously.
5. Use fresh sessions for greeting, Persian audio, tools, sources, barge-in and close; old reservations are not repinned.
6. Actually stop candidate/start preserved OpenAI and verify health plus a fresh real session. Container rollback is not DB/filesystem rollback or seamless media resume.
7. Leave provider state as explicitly requested and record exact commands, IDs, digests, validation and limitations.
Acceptance criteria:
- Original OpenAI image/container remain intact and restoration has actually succeeded.
- One API owns operational lifecycle at a time; users/documents/ingestion data preserved.
- Fresh-session admission and profile pinning hold; no credentials exposed.
- Final provider and live check results recorded; health alone is not speech/RAG acceptance.
Relevant paths (verify actual locations before editing):
Opt-in Compose overrides, .env.example, operator runbook and progress/evaluation evidence; app changes only for confirmed deployment defects.
Validation:
Config/image inspection, authorized controlled switch/rollback, health and actual fresh-session smoke.
Visible demonstration:
Show local RAG, execute documented OpenAI rollback without rebuilding, and repeat the same question in a fresh session.
Explicit stop/narrow condition:
Complete preparation first; missing explicit switch authorization, compatibility or acceptance blocks operational switching.
Deliver:
1. Scoped code/configuration and necessary tests/contracts where this phase requires implementation; Phase 0 remains an audit.
2. docs/evaluation/local-s2s/phase-07.md with exact commands, results, actual/simulated/unverified evidence, fingerprints, not-run checks and risks.
3. Updated docs/plans/local-s2s-adapter-progress.md with a candid acceptance verdict.
4. Exact demo instructions and rollback relevance. Preserve the operational provider unless this phase explicitly authorizes switching and session authorization exists.
Do not implement the next phase. Do not mark acceptance complete with mandatory live or human checks unrun.
```