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
+11
View File
@@ -2278,3 +2278,14 @@ Source order, text and locations are preserved; strict mode remains unchanged.
This mode does not guarantee complete legal context within each chunk. This mode does not guarantee complete legal context within each chunk.
117 focused regression checks passed, including malformed legal identifiers 117 focused regression checks passed, including malformed legal identifiers
and bounded splitting. and bounded splitting.
## Planned local speech-to-speech provider (2026-10-15)
The [phased plan](plans/local-s2s-adapter-plan.md),
[execution ledger](plans/local-s2s-adapter-progress.md) and
[copy-ready prompts](plans/local-s2s-adapter-prompts/README.md) describe local_s2s
alongside OpenAI/Gemini, with initially remote OpenRouter STT/LLM/TTS stages.
All eight phases are not_started. OpenAI preservation, actual context-repair
proof, shared RAG authority, isolated acceptance and rollback are hard gates.
This planning record does not weaken existing browser/OpenAI contracts or claim
implementation, live validation or deployment.
+458
View File
@@ -0,0 +1,458 @@
# Local speech-to-speech adapter: phased implementation plan
Date: 2026-10-15. Status: **planned; implementation and live acceptance not started**.
## 1. Outcome and scope
Add `local_s2s` alongside OpenAI and Gemini. Keep the OpenAI implementation usable,
preserve its behavior, and retain the original operational API container/image for
rollback. Initially run orchestration/VAD locally and obtain STT, a tool-capable
text LLM and TTS through OpenRouter. Local orchestration is not offline inference.
Replacing individual stages with local models is a later independent optimization.
This is a plan, not authorization to switch the running application, download
weights or perform unbounded paid evaluation. Each phase has a tangible demo,
acceptance criteria, evidence and a copy-ready English prompt. No phase has run.
## 2. Target architecture
```mermaid
flowchart LR
Browser[Existing Angular browser] <-->|Application PCM and JSON| API[FastAPI and VoiceRuntime]
API --> Tools[Existing tools and SearchService]
Tools --> Data[(Authorized knowledge)]
API --> Boundary[Small internal provider boundary]
Boundary <--> OA[Existing OpenAI adapter]
Boundary <--> GE[Existing Gemini adapter]
Boundary <--> LA[New local_s2s adapter]
LA <--> Engine[Pinned speech-to-speech service]
Engine --> VAD[Local VAD]
Engine --> STT[OpenRouter STT]
Engine --> LLM[OpenRouter text LLM]
Engine --> TTS[OpenRouter TTS]
```
The engine emits tool requests; our backend executes them. It receives no separate
database authority. Browser clients continue to use our API, never a public engine
endpoint or an OpenRouter key.
| Concern | Owner |
| --- | --- |
| Identity, organization, permissions and revisions | Existing application services |
| Turn ownership, deadlines, playback credits, evidence lifetime, next-turn release | VoiceRuntime |
| Native wire events/requests, error classification and configuration proof | Provider adapter |
| Actual local cancellation/history mutation and authoritative receipt | Pinned engine plus a minimal versioned extension when necessary |
| Recognition, text generation and synthesis | OpenRouter initially |
| Search/reuse, document eligibility and used-source validation | Existing knowledge services and DurableTools |
| Browser PCM and JSON contract | Existing application API contract |
### Boundary design
Normalize semantic events/operations actually required by runtime: effective
setup, consumed input, speech boundaries, generation identity, audio/transcript,
tool request and terminal outcome. Preserve native identity/provenance and replay
fingerprints. Do not turn an arbitrary transcript into a fake input-commit ack.
Interruption has separate generation-stop and history-repair progress. Runtime
supplies the response/item, session generation and final played coordinates; the
adapter establishes the actual result and runtime retains authority to release
the next turn. The receipt must identify the operation and applied state revision.
A boolean success flag, elapsed timer or sent request is insufficient proof.
Keep OpenAI's cancel/terminal/truncate/ack behavior intact behind this boundary.
Gemini's unsupported repair remains fail-closed. Prefer a small protocol/data model
to a plugin registry, event bus or wholesale state-machine rewrite.
## 3. Upstream evidence and hard compatibility gaps
Upstream documents a cascade and a core Realtime interface, not full OpenAI API
equivalence. Its documented conversation.item.truncate is a no-op without an ack.
Pin a commit and inspect its actual implementation/tests; changing the endpoint
URL alone cannot meet our cleanup contract. Sources:
[repository](https://github.com/huggingface/speech-to-speech),
[Realtime contract](https://github.com/huggingface/speech-to-speech/blob/main/src/speech_to_speech/api/openai_realtime/README.md).
HTTP STT progressive updates can repeatedly upload cumulative utterances. Remote
TTS cancellation can stop local publication without proving remote compute stopped.
These affect cost and late-result handling. Sources:
[STT backend](https://github.com/huggingface/speech-to-speech/blob/main/docs/openai-compatible-stt.md),
[TTS backend](https://github.com/huggingface/speech-to-speech/blob/main/docs/openai-compatible-tts.md).
OpenRouter documents separate STT/TTS endpoints and LLM tool calling. Model IDs,
voices, Persian behavior, supported parameters and rates require actual checks:
[STT](https://openrouter.ai/docs/guides/overview/multimodal/stt),
[TTS](https://openrouter.ai/docs/guides/overview/multimodal/tts),
[tools](https://openrouter.ai/docs/guides/features/tool-calling).
### Critical case: completed generation, unplayed audio
A model can finish text/audio while the browser has heard only the beginning.
Cancel may then do nothing, leaving unheard assistant prose in engine history.
Test the actual next LLM request, not only audio queue state or terminal flags.
Closing HTTP, clearing playback and returning response.done do not establish repair.
Do not infer a text prefix from audio-duration ratios or character counts. If
reliable heard-prefix alignment is unavailable, keep the gate open. Dropping an
entire interrupted assistant turn or retaining only fully played segments is a
weaker alternative policy requiring explicit acceptance and documentation; never
silently present it as exact heard-prefix preservation.
## 4. Invariants
1. OpenAI remains available. No automatic cross-provider fallback, new UI provider
selector or mid-session provider switch. Freeze effective configuration.
2. Keep original API containers/images and unrelated changes. No database reset,
pruning, compose down, rewriting old snapshots or document-content versioning.
3. Keep browser PCM16LE mono 24 kHz in both directions and existing public events.
4. One canonical search implementation, calibrated cutoff, document/chunk identity,
ready/active/authorized/undeleted filtering and final delivery revalidation.
5. Used-source membership validation is not full factual-entailment verification.
6. Generation completion differs from playback completion. Retained searches have
a lifetime independent of speech cancellation and retain their original deadline.
7. Bound queues, bytes, concurrency, deadlines and retry counts across all stages.
Do not stack automatic retries at multiple layers or conceal latency with buffers.
8. Secrets stay server-side. Default logs contain fixed categories/numeric state,
not complete provider payloads or real speech/document text.
9. Separate offline tests, isolated PostgreSQL acceptance, provider smokes and human
listening. Mock success or skipped checks do not prove live acceptance.
10. Never start a second API against the operational database. app/main.py invokes
lifecycle.reconcile_startup, which reconciles active sessions globally. A
different HTTP port alone is not isolation.
## 5. Phase overview
| Phase | Visible result | Operational effect |
| --- | --- | --- |
| 0 | Baseline and protocol compatibility report | None |
| 1 | Existing OpenAI interruption replay still passes through the new boundary | None; refactor only |
| 2 | Independent Persian audio -> text -> response -> playable audio demo | Isolated engine only |
| 3 | Existing browser greets and closes through local_s2s | Isolated test API/database only |
| 4 | Real interruption and coherent continuation; verified repaired history | No promotion until proof |
| 5 | Document answers, retained search and correct source subset | Isolated end-to-end RAG |
| 6 | Paired OpenAI/local quality, latency and cost scorecard | Promotion decision evidence |
| 7 | Authorized deployment switch and demonstrated OpenAI rollback | Controlled opt-in switch |
Phases run in order. Phase 2 engine preparation may proceed independently of Phase
1 when it does not depend on application changes. Never accept a later gate merely
because code exists. Do not combine the OpenAI refactor and operational switch.
## 6. Phase 0 - Baseline and immutable upstream audit
**Visible outcome:** Open a report showing OpenAI baseline, upstream support,
required changes and proof tests side by side. Replay an existing offline trace.
**Work:**
- Read applicable instructions, reference map and governing API/database/workflow
sections. Inspect current source and deployment; historical defaults are stale.
- Record active/preserved container IDs, image digests, selected profile, ports and
storage mounts without keys/full environment dumps. Do not recreate containers.
- Pin an upstream SHA and build inputs; record license and patch policy.
- Audit effective session config, input acceptance, VAD/commit boundaries, manual
response control, metadata/identity, tools, audio rates, terminal states,
transcripts, cancellation and history repair against actual source/tests.
- Run focused baseline tests; distinguish existing failures from new defects.
- Prepare Persian fixture questions and expected answers against an authorized
frozen test corpus. Record outstanding product/implementation decisions.
**Accept when:** baseline/rollback identities exist; each required behavior is
verified, requires a specified patch, or is explicitly unverified; every live
prerequisite is visible. No runtime/data changes occurred.
**Stop/narrow:** unknown upstream behavior remains unknown. Missing credentials
block live checks, not read-only inspection or deterministic preparation.
**Prompt:** [Phase 0](local-s2s-adapter-prompts/phase-00.md).
## 7. Phase 1 - Small provider boundary, OpenAI preserved
**Visible outcome:** Replay the same interruption before/after extraction: old
output stops, the same played position is respected and exactly one next response
is released. OpenAI remains the selected provider.
**Work:**
- Implement minimal typed operations/events; runtime keeps turn/authority/release,
playback bounds and evidence state. Adapters own provider wire interpretation.
- Move OpenAI native cancel/terminal/truncate mechanics behind the boundary without
changing semantics. Do not lose raw event fingerprints/correlation on normalization.
- Represent interruption with an operation ID, response/item/session identity,
generation-stop and applied-history progress, and finite deadlines.
- Do not introduce capability switches that waive cleanup. Unsupported capabilities
reject admission or fail safely. Preserve Gemini's conservative behavior.
- Add controlled-clock replay and regression tests. Document the internal contract
amendment; browser wire contracts remain unchanged.
**Accept when:** existing OpenAI tests retain assertions and pass; terminal/error
orderings, missing/wrong acknowledgements, duplicates, late events, incomplete
responses and bounds remain covered. Shared control has no model/voice branches.
Run isolated PostgreSQL cases if persisted profiles/lifecycle behavior is touched.
**Stop/narrow:** no full runtime rewrite or blanket provider-error suppression.
**Prompt:** [Phase 1](local-s2s-adapter-prompts/phase-01.md).
## 8. Phase 2 - Isolated engine with OpenRouter stages
**Visible outcome:** Submit a Persian recording to the independent smoke, inspect
its explicitly requested test transcript, hear a WAV response and see stage usage
and timing. The application remains untouched.
**Work:**
- Build the pinned engine in a separate image/environment with local VAD, HTTP
STT, Chat Completions LLM and HTTP TTS. No default local model downloads.
- Discover/pin available models/voices and validate Persian hints, tool support,
endpoint fields, rates and audio formats. Models are independently configurable.
- Keep the key inside the engine. Custom endpoints must not accidentally receive
another provider's credentials. Keep engine access behind the application boundary.
- Start with final-utterance STT, not cumulative HTTP retranscription.
- Verify actual multipart/JSON STT and TTS stream_format/PCM compatibility; add only
a narrow observed-mismatch shim if necessary.
- Bound and meter startup probes, generation, response sizes, retries/concurrency
and close. Provide deterministic stubs and an opt-in bounded live smoke.
**Accept when:** with live prerequisites all stages complete and audio is valid;
otherwise mark live-pending. Bad key/model/voice/rate fails setup accurately. Save
sanitized timing/usage and consented fixture outputs, not secrets or raw user logs.
**Stop/narrow:** do not install every optional model/GPU dependency. Credential or
model availability gaps do not authorize fabricated success.
**Prompt:** [Phase 2](local-s2s-adapter-prompts/phase-02.md).
## 9. Phase 3 - Local adapter and normal browser session
**Visible outcome:** In an isolated test app, open the existing browser, say hello,
hear a Persian answer, see a transcript, and close cleanly. Show a local_s2s pinned
profile. This milestone is development-only, not production parity.
**Work:**
- Add local_s2s configuration/factory selection while keeping openai/gemini.
- Freeze engine/patch revision, internal protocol revision, STT/LLM/TTS identities,
voice, input policy, rates and effective instruction/config digest. No secrets
or credential-derived hashes belong in database execution profiles.
- Define the expected configuration and compare to authoritative engine state.
A reachable socket or echoed request is insufficient setup proof.
- Map actual consumed input, manual response identity/metadata, audio/transcript,
terminal and tool events. No invented native commits/acknowledgements.
- Preserve browser 24 kHz PCM; use stateful bounded conversion where required,
including correct playback-position units.
- Preserve owner/Origin/cookie/CSRF/replay/epoch checks. Inspect schema/DTO/provider
constraints; use a new migration only if necessary, never edit an applied one.
- Use disposable database/storage and isolated test browser identity/origin.
Until Phase 4, unsupported interruption must fail safely and be labelled as such.
**Accept when:** ready/audio/transcript/close work; bad configuration, wrong owner,
old epoch, mismatched profile, malformed terminal and disconnect cannot pass
silently. Existing profiles are not rewritten; a new session pins new settings.
**Stop/narrow:** a second port with the same operational DB is prohibited. No
promotion or hidden fallback before interruption and RAG gates.
**Prompt:** [Phase 3](local-s2s-adapter-prompts/phase-03.md).
## 10. Phase 4 - Verified interruption and history repair
**Visible outcome:** Interrupt a long answer, ask a follow-up, and get a coherent
reply without stale audio. In a controlled test, show the actual next LLM input
contains no unheard sentinel that was generated later in the interrupted answer.
**Work:**
- Implement a real correlated engine operation/extension if the pinned version
cannot repair history. Keep a reproducible versioned patch with independent tests.
- Cover active generation AND completed generation with unplayed buffered audio.
- Track item/response/segment/session identities, final consumed position and
reliable assistant text/audio alignment. Never use character/duration ratios.
- Keep valid prior turns/user/tool state; remove unheard assistant continuation
from future generation input. Expose applied history revision/digest as proof.
- If exact repair is unavailable, stop this acceptance gate. Conservative whole-turn
rollback or fully-played-segment-only history needs explicit policy acceptance.
- Admit a receipt only after mutation; reject stale, conflicting, wrong-identity
or missing receipts. Runtime retains deadlines and final authority to continue.
- Suppress late STT/LLM/TTS results even if remote computation cannot be cancelled.
Keep latest backend retrieval independent from speech cancellation.
- Repeat OpenAI regressions; the new local proof must not weaken native OpenAI gates.
**Accept when:** no next turn before generation stop, real repair and playback gates;
active and completed-unplayed cases pass; late work cannot reach another turn;
missing/wrong proof fails safely. No fake conversation.item.truncated event.
**Stop/narrow:** this is the highest-risk phase. Audio stopping or a stock-SDK
compatibility claim does not prove our context semantics. Keep promotion blocked.
**Prompt:** [Phase 4](local-s2s-adapter-prompts/phase-04.md).
## 11. Phase 5 - Existing RAG tools and used sources
**Visible outcome:** Ask hours/Thursday, the planning deputy in the specific letter,
and the incentive percentage/dates/exclusions. Interrupt a pending search and
repeat the question; show one retrieval plus revalidation and relevant UI sources.
**Work:**
- Expose search_knowledge, reuse_last_evidence and report_used_sources to the new
LLM. Execute through existing dispatch/ToolContext/DurableTools/SearchService.
- Preserve backend identity, calibrated retrieval, document/chunk references and
handoff/delivery eligibility. Engine gets no independent retrieval path.
- Validate streamed arguments after successful terminal validation; correlate
response/item/call identities and deduplicate repeats/replays.
- Reuse same-topic pending results within original deadline, revalidate, and discard
changed-topic results. Never use earlier assistant prose as document evidence.
- Validate current-turn source labels and correct invalid reports privately. Do
not show every candidate or persist metadata reports as extra retrievals.
- Exercise ok/no_evidence/error, token-limited tools, interrupted delivery,
revocation/deactivation and all known Mini factual failure cases.
**Accept when:** all three tools retain existing authority; no stale evidence or
extra retrieval on same-topic reuse; used subset has original document/chunk
identity. Correct citation membership is not claimed as full factual verification.
**Stop/narrow:** no weakened cutoff/filter or second search implementation to hide
model-quality problems.
**Prompt:** [Phase 5](local-s2s-adapter-prompts/phase-05.md).
## 12. Phase 6 - Persian quality, latency, cost and resilience
**Visible outcome:** A paired OpenAI/local scorecard and audio samples show the
actual trade-off. Demonstrate a controlled provider failure without contamination.
**Work:**
- Evaluate the same authorized frozen corpus and paired Persian audio/question
fixtures. Keep exact baseline/candidate component profiles and sample counts.
- Cover names/roles, numbers/dates, natural pauses, noise, self-correction,
ambiguity, continuation, topic switch, no evidence and document conflicts.
- Measure speech-end-to-first-audible-sample, tool time, first text/audio,
interruption-to-stop, underruns, duplicates, disconnects and task completion.
- Count cached/input/output usage when available, STT duration, TTS billed units,
startup probes, failures and abandoned work. Missing usage stays unknown. Compare
cost per successful task, not only successful API requests.
- Fault-inject slow/down providers, quotas, stream loss, restart and saturation.
Prove bounded queues, late-result suppression and no stacked retry storms.
- Change one component at a time. Human listening is separate from transport tests;
do not claim that a better LLM repairs bad transcription.
**Accept when:** all critical factual fixture assertions pass with zero invented
names/numbers/dates/conditions; all intended interruption cases pass or fail safely
as specified; results assess predeclared targets and expose all failures.
Provisional goals, to accept or revise explicitly BEFORE evaluation: p95 first
audible response <= baseline + 1 second, no persistent underruns, and cost per
successful task <= 70% of baseline for a cost-saving promotion. These are targets,
not measurements or universal guarantees. If quality/cost goals fail, keep OpenAI.
**Stop/narrow:** missing actual provider/human evidence leaves the gate open. Do
not broaden prompts/buffers or silently change thresholds after seeing results.
**Prompt:** [Phase 6](local-s2s-adapter-prompts/phase-06.md).
## 13. Phase 7 - Controlled switch and demonstrated rollback
**Visible outcome:** Demonstrate a local document interaction, then stop the
candidate, start the preserved OpenAI API without rebuild, and repeat the question.
Leave the selected provider in the final state explicitly requested by the user.
**Work:**
- Finalize opt-in Compose and .env.example; OpenAI stays default until an explicit
operational switch. No automatic fallback or UI provider selector.
- Verify original container/image/config retention. Candidate gets separate tags;
never prune, remove, overwrite or rebuild the original rollback target.
- Check effective setup, health, secrets, bounds and database compatibility before
switching. An incompatible migration blocks simple old-container rollback.
- Drain/close current sessions, stop the existing API, then start the candidate on
the operational DB. Never two application APIs against that DB simultaneously.
- Test a fresh browser session: greeting, RAG, used sources, interruption and close.
- Actually exercise rollback and verify readiness plus a fresh OpenAI session.
Container rollback is not database/filesystem rollback or media-session resume.
- Record commands, identities, fingerprints, checks, final state and limitations.
**Accept when:** preserved OpenAI restoration succeeds; user/ingestion data is
preserved; one API owns the operational lifecycle at a time; session profiles stay
pinned. Health readiness alone is not speech/RAG acceptance.
**Stop/narrow:** prepare all reviewable work first. Without the operational switch
authorization, compatibility or live evidence, stop before changing the service.
**Prompt:** [Phase 7](local-s2s-adapter-prompts/phase-07.md).
## 14. Configuration, data and deployment contract
Proposed names below must be finalized before implementation and documented with
units/defaults. Do not create unvalidated option bags or leak credentials to LLMs.
| Scope | Proposed configuration |
| --- | --- |
| Selection | VOICE_PROVIDER=openai / gemini / local_s2s |
| Engine access | LOCAL_S2S_ENDPOINT and optional server-to-server credential |
| Identity | LOCAL_S2S_ENGINE_REVISION, adapter contract revision, effective config digest |
| Models | LOCAL_S2S_STT_MODEL, LOCAL_S2S_LLM_MODEL, LOCAL_S2S_TTS_MODEL, LOCAL_S2S_TTS_VOICE |
| Policy | STT language/final-only mode, LLM limits, TTS rate/format and verified options |
| Credentials | OpenRouter key only in engine component clients; never in database profile |
| Bounds | Connect/request/repair/close deadlines, queue bytes/items/concurrency |
Start with fixed component identities per engine configuration. Reservation
expectations must match authoritative engine state; never silently mutate shared
global models on every session.update. Later multi-profile concurrency requires a
separate isolation design.
Candidate API acceptance uses an isolated PostgreSQL/pgvector database and storage.
Cookies are not port-isolated: use a dedicated test hostname/browser profile and
credentials with matching trusted Origin. Do not copy production auth sessions
into a parallel test browser. Operational switching runs only one application API.
No schema migration is assumed. Inspect provider constraints/DTOs/profile replay
in Phases 0/3; use a new migration only if required and verify rollback image
compatibility. Do not add document_versions/version_id/version_no.
## 15. Validation commands and evidence
Verify paths and side effects at execution time. Focused baseline command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py -q
```
Broaden when shared behavior changes justify it:
```powershell
.venv/Scripts/python -m pytest -m "not postgres"
git diff --check
```
Only with a verified disposable TEST_DATABASE_URL:
```powershell
.venv/Scripts/python -m pytest -m postgres --require-postgres
```
Existing timing/Windows failures must be recorded, not hidden by weakening tests.
Ordinary-suite skips do not establish PostgreSQL acceptance. Future local smoke
and conformance commands are phase deliverables, not existing verified commands.
Each phase produces docs/evaluation/local-s2s/phase-NN.md with scoped diff/commits,
exact commands, results, counts, fingerprints, visible demo, actual vs simulated
observations, not-run checks, blockers and rollback relevance. No keys/raw real
conversation logs. Save audio/transcripts only as explicitly consented evaluation
artifacts. Upstream CI success is not our runtime compatibility evidence.
Progress ledger: [local-s2s-adapter-progress.md](local-s2s-adapter-progress.md).
Prompt index: [local-s2s-adapter-prompts/README.md](local-s2s-adapter-prompts/README.md).
States: not_started, in_progress, offline_complete_live_pending, blocked, accepted.
Only accepted closes a required gate. Missing paid authorization blocks dependent
live work, not independent preparation. Reuse existing bounded authorization; do
not ask the user to approve the same action repeatedly.
## 16. Decisions to resolve and definition of done
- Upstream SHA, dependency/build lock and maintained patch provenance: Phase 0.
- Effective profile/config attestation and concurrent engine isolation: Phase 3.
- Real heard-prefix mapping/receipt: Phase 4 hard gate; weaker policy requires an
explicit product decision and intentional API/workflow documentation.
- Available OpenRouter models/voices, Persian quality, hardware footprint and
latency/cost: measure, do not infer from default local-model examples.
- Any future local weight licensing is checked for the chosen model separately.
- Candidate promotion follows evidence, not an assumption that local is cheaper.
Done means independently selectable local_s2s, working OpenAI, unchanged trusted
RAG authority, browser compatibility, real correlated history repair, bounded
failure handling and recorded Persian quality/latency/cost acceptance. Restoring
the compatible preserved OpenAI container has actually worked. Missing real or
human acceptance remains a blocker, not a completed implementation.
+36
View File
@@ -0,0 +1,36 @@
# Local S2S adapter progress
Created: 2026-10-15. This ledger records execution, not a completion claim.
Plan/prompts are written; implementation, paid calls, downloads and operational
switches have NOT been performed as part of this planning task.
[Plan](local-s2s-adapter-plan.md) | [Prompts](local-s2s-adapter-prompts/README.md)
| Phase | Status | Evidence | Visible demo | Blockers |
| --- | --- | --- | --- | --- |
| 0 - Baseline and immutable upstream audit | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 1 - Small provider boundary with OpenAI preserved | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 2 - Isolated S2S engine with OpenRouter stages | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 3 - Local provider and normal browser session | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 4 - Verified interruption and history synchronization | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 5 - Shared RAG and declared-source integration | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 6 - Persian quality, latency, cost and resilience | not_started | Not run | Not demonstrated | Resolve prerequisites |
| 7 - Controlled switch and verified rollback | not_started | Not run | Not demonstrated | Resolve prerequisites |
## Phase evidence template
- Phase/status and prerequisite evidence:
- Reviewed diff/implementation commit:
- Preserved operational and rollback identities:
- Pinned upstream and patch revision:
- Candidate effective profile without credentials:
- Exact commands, counts and results:
- Actual / simulated / unverified observations:
- Visible demo and outcome:
- Bounded paid-call authorization/usage when applicable:
- Decisions, blockers, not-run checks and risks:
- Acceptance verdict / next allowed phase:
States: not_started, in_progress, offline_complete_live_pending, blocked, accepted.
Only accepted closes a mandatory gate. Inspect current deployment before each
operational action; historical notes do not establish current provider selection.
@@ -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.
```