Files
rag-technical-docs-assistant/docs/agent-reference-map.md
T
11linear11 111710c47c feat(voice): support evidence reuse, 120s output capacity, and input ASR coalescing
- Add internal reuse_last_evidence tool for continuing existing topic without repeated retrieval
- Expand OpenAI output capacity to 120s / 5,760,000 bytes and add delivery fairness
- Coalesce adjacent user ASR transcript deltas to prevent client control queue overflow
- Add server-side OPENAI_REALTIME_SPEED configuration and update style to v4
- Add extensive unit and integration regressions for evidence reuse, capacity, and fairness
2026-10-12 17:57:27 -04:00

2202 lines
155 KiB
Markdown

# Phase 1 agent reference map
Live repair diagnostics (2026-10-12): see [numeric trace guide](guides/live-conversation-traces.md)
for the opt-in runtime timeline, frontend consumed/discarded sample accounting,
and the provider-free fixed worklet trace command. Current Linux checks use
`.venv/bin/python`; historical `.venv/Scripts/python` commands below refer to
the Windows environment. Traces and synthetic checks do not close live incidents.
Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
one backend adapter. Gemini remains the temporary default because an OpenAI
Realtime voice key is unavailable.** Reservation, authenticated stream and
operator smoke share the selected model/voice/profile. Only the selected voice
key is required; there is no fallback or frontend provider selector. Legacy
PROVIDER and existing GEMINI_* settings remain supported; conflicting provider
aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change
embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions.
Pinned reservations cannot switch providers on connection or replay. Gemini
interruption requiring unverified context truncation closes safely; OpenAI keeps
its existing native cancellation/truncation contract. Canonical search, original
documents, frozen profiles and owner/replay/revocation rules remain unchanged.
See [Phase 2 repair report](guides/realtime-agent-phase2-repair.md).
Use this index to select the governing contract and inspect the real implementation before changing, testing, or reviewing behavior. Paths are relative to this file. Current voice contract amended 2026-10-08 by Realtime Phase 0; English revision 1.3 remains the broader scope baseline. Historical component evidence below is preserved; the English revision 1.3 documentation checkpoint reran no application/provider/database tests; current repair acceptance is recorded at the end. Use the latest applicable recorded acceptance, not earlier unavailable-database reports. Dated component records below describe their historical checkpoint; absence-of-worker statements there are superseded by the current Phase 5/6 inventory and repair evidence.
## Authority and document resolution
Follow governing instructions and the user's current task. The plan sets Phase 1 scope; API and database specifications set contracts; the implementation guide sets workflows. The English MVP scenario report explains current walkthroughs; the Persian revision 1.2 report is historical. Architecture supplies context only. Code and README describe the prototype, not approval to override the Phase 1 contracts.
The six current English specifications live under `docs/specifications/`:
delivery plan, implementation guide, API catalog, database design, architecture
and `RAG-Phase1-MVP-Scenarios.md`. Revision 1.3 replaces the prior 7-10 day
text-and-voice milestone with a conditional four-day Live document MVP:
new browser uploads, the existing ingestion/embedding Phases 1-4, LangChain,
mandatory example/unseen-file acceptance. The scoped 2026-10-08 Phase 0 amendment selects OpenAI Realtime for voice and the conditional 3-5 day backend sequence in [Realtime MVP plan](plans/realtime-agent-mvp-plan.md); the earlier four-day sequence is historical.
Full text chat/history and settings editing are deferred.
The four supplied files are test examples, not upload eligibility or final
corpus size. Preserve independent immutable documents, direct IDs, technical
revisions/profiles and applied migrations. D06/D07 review/resume backend services are implemented, with authenticated HTTP
transport still awaiting identity/Origin/CSRF integration. Voice-only tool
persistence remains planned.
The older Persian report and historical evidence sections remain unchanged
apart from an English supersession notice. Do not turn pending decisions into approvals.
Section numbers and heading names below are verified against these files; no inferred fragment anchors are used.
| Requested document | Actual file | Authority and sections to consult |
| --- | --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
| `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract أ¢â‚¬â€‌ OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping |
| `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
| `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation |
| `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions |
Track remaining implementation in the [Live document MVP TODO](plans/live-document-mvp-todo.md); it is a progress checklist, not a governing contract or proof of completion.
## Reading by workflow
- `implement-feature`: Plan 3/8/9 for boundaries and acceptance; guide 3 and the affected workflow in 5-10; API endpoint and error sections; database affected tables plus 7/8. Use English MVP scenarios to clarify observable behavior and architecture 17 for migration context.
- `write-tests`: Plan 9/10; guide 12 and affected workflow; API replay/error/permission rules; database 7/9 for races and constraints; English MVP scenarios 2-12 for concrete cases. Consult architecture only for relevant context.
- `review-change`: Plan 3/9 to avoid roadmap findings; guide 5-10 for changed boundaries; exact API contracts and database 7/8/9. Use English MVP scenarios for trigger/impact and architecture dependency rules only where relevant.
## Actual implementation and commands
| Existing path | Observed responsibility |
| --- | --- |
| [Application entry point](../app/main.py) | FastAPI routes, CORS, static health response |
| [API directory](../app/api/v1/) and [schemas](../app/schemas/) | Prototype chat transport and DTOs |
| [Services](../app/services/) | Document loading/chunking and Chroma/FastEmbed retrieval |
| [Agent](../app/services/agent/) and [tools](../app/services/tools/) | LangGraph text loop, in-memory history, retrieval tool |
| [Configuration](../app/core/config.py) and [environment example](../.env.example) | Settings and provider configuration |
| [README](../README.md) | Prototype startup instructions; not Phase 1 implementation evidence |
| [Document processor](../app/services/doc_processor.py) | Recursively ingests Markdown under `data/documents/`, separate from project documentation |
Ingestion foundation now exists: [manifest](../pyproject.toml), [settings/types/ports](../app/modules/documents/), [database access](../app/infrastructure/database.py), [initial migration](../migrations/versions/0001_ingestion_foundation.py), [Alembic environment](../migrations/env.py), [trusted bootstrap](../app/bootstrap.py), and [tests](../tests/). Read [foundation setup](guides/ingestion-foundation-setup.md) before migration/bootstrap/database testing. Only the seven requested foundation tables are implemented; no auth sessions, conversation or Live tables. Phase 2 now adds the [intake CLI](../app/ingest.py), [intake service](../app/modules/documents/intake.py) and [local FileStore](../app/infrastructure/file_store.py). Phase 4 adds the [hosted embedding adapter](../app/infrastructure/openai_embeddings.py) and [bounded staging service](../app/modules/documents/embeddings.py). There is still no lockfile, CI or frontend. Phase 5 now adds [worker orchestration](../app/worker.py), [fenced persistence](../app/infrastructure/worker_repository.py), [application processing](../app/modules/documents/worker.py), a forward extraction_state migration and the retry CLI; see [worker operations](guides/worker-orchestration.md). Extended Phase 5 adds [review services](../app/infrastructure/review_repository.py), [immutable review storage](../app/infrastructure/review_candidates.py), [manifest preparation](../app/modules/documents/review.py) and forward audit revision 0003. Retained review/resume and factual inclusion are implemented; authenticated D06/D07 HTTP transport remains blocked on identity/Origin/CSRF integration. Redis/broker and an additional orchestration framework are unnecessary. LangChain is the selected RAG/tool framework; use existing services through a small integration boundary, not a replacement embedding pipeline.
| Command from repository root | Verification status |
| --- | --- |
| `git status --short` | Executed for working-tree inspection |
| `git diff --check` | Executed for tracked whitespace validation; untracked new files need separate inspection |
| `rg --files --hidden -g '!.git/**'` | Executed for file discovery |
| `python -m app.server --host 0.0.0.0 --port 8000` | Supported single-process entrypoint; selected legacy parser verified by real loopback boundary/fragment/compression/queue tests |
| `python -m app.services.agent.exec` | README example and CLI entry point verified statically; provider smoke harness, not automated regression tests; not run |
Prototype runtime prerequisites remain unverified: configured credentials, approved corpus, writable vector storage, and provider/model access. Importing the application creates settings/retrieval singletons and can load embeddings/index documents. Do not use imports as a supposedly network-free smoke test. README installation now uses pyproject.toml extras. Foundation imports are independent of those prototype prerequisites. Verified foundation commands are listed below; current worker commands and acceptance are in the Phase 5 section at the end of this map.
## Gaps and decisions
- Required document content is available under `specifications/`; no reference-dependent workflow is currently blocked by missing content. If a linked document later disappears, mark only dependent contract work blocked, report its exact path, and continue unrelated work without inventing it.
- Material implementation gap: prototype Chroma/local Markdown/in-memory chat does not search the uploaded-document pipeline. Worker/publication/retry are implemented; remaining work includes authenticated review transport, real-model search calibration, HTTP identity/upload, LangChain integration, native Live and UI. The Fast-Track Search Phase 1 core and operator selection/inspection CLIs now exist; see the checkpoint below. Full durable text turns/history are deferred; no component test certifies this integration.
- Open validations: exact format/size caps, funded model profiles/vector dimension, OpenAI Realtime WSS/tool/transcript and Persian speech proof, hosting/connectivity, account/session/retention policy, quality target and delivery date. Direct OpenAI Realtime, LangChain, new browser uploads, existing embedding reuse and all supplied example structures are confirmed MVP direction. See guide 13 and plan 2. Do not turn proposals into recorded approvals.
- The 2026-10-06 MVP supersedes provisional SDP/WebRTC with backend-managed direct OpenAI Realtime WSS; see API Section 7. Current-session provider answer transcripts/sources are displayed when available; durable full voice history remains deferred. Broader features do not authorize model selectors or CTI.
- Project documentation now lives under `docs/`; sample corpus files remain under `data/documents/`. A future default corpus rebuild excludes the moved specifications and reference map. Existing vector indexes are not rebuilt or cleaned by this reorganization and may retain previously indexed project documentation. Use an approved corpus for real-provider evaluation.
## Skill discovery
Skills are stored at repository-root `.agents/skills/<name>/SKILL.md`, the repository location documented in [official Codex skill guidance](https://learn.chatgpt.com/docs/build-skills). No equivalent project-owned skills or prior AGENTS.md files were found.
Use `$implement-feature`, `$write-tests`, or `$review-change` in Codex. Automatic discovery was verified on 2026-10-05: all three repository skills appeared in this session's available-skills catalog after creation. In another client/session where selection is unavailable, explicitly ask Codex to read the relevant SKILL.md by repository path and follow it. No global installation or optional UI metadata is required.
## Ingestion foundation commands and evidence (2026-10-05)
- python -m venv .venv and .venv/Scripts/python -m pip install -e ".[test]": executed successfully with Python 3.14.6.
- .venv/Scripts/python -m pytest -m "not postgres": 13 passed; no real providers.
- .venv/Scripts/alembic history: initial revision discovered successfully.
- .venv/Scripts/python -m pytest -m postgres: requires TEST_DATABASE_URL targeting a dedicated database ending in _test. PostgreSQL tests use disposable schemas and real independent connections. Ordinary-suite missing configuration skips them with a non-acceptance reason; add --require-postgres to the acceptance command so missing configuration fails.
- .venv/Scripts/alembic upgrade head: operator command, not yet executed against PostgreSQL. Requires explicit INGEST embedding identity/dimension; initial vector(D) and profile are frozen in the database. Equal dimensions with a different model fail compatibility.
- .venv/Scripts/python -m app.bootstrap: trusted initial organization/admin command; requires explicit display/settings arguments and an interactive password prompt or --password-stdin. No HTTP authentication is implemented.
- docker info --format '{{.ServerVersion}}': failed both inside and outside the sandbox because Docker Desktop WSL bootstrap could not start. PostgreSQL/pgvector acceptance is unverified in this environment.
- git diff --check: tracked whitespace validation only; newly added files also need separate inspection.
The [ingestion pipeline plan](plans/ingestion-pipeline-plan.md) is a tracked specification; its later phases are not implemented by foundation work. All seven tables use the database contract's direct document identities, scoped FKs, state constraints and uniqueness. The initial revision already exists and must be treated as potentially applied. Repair work does not assume it is unapplied: preserve it byte-for-byte and use forward revisions for any future persisted changes. Processing-profile snapshots contain character units and embedding identity without secrets. Compatibility and native vector registration are explicit functions; importing ingestion modules opens no database/provider connection or corpus.
- Final .venv/Scripts/python -m pytest: 13 passed, 31 PostgreSQL tests skipped because TEST_DATABASE_URL was absent. .venv/Scripts/python -m pip check: no broken requirements. Database migration/constraint/concurrency/bootstrap runtime remains unverified.
## Phase 1 repair evidence (2026-10-05)
Scope is foundation repair only. No intake, worker, HTTP authentication,
conversation/Live tables or chat behavior was added.
- Settings reject credential-bearing or unsupported endpoint URLs, preserving supported endpoint identity. Error strings and structured validation errors omit raw input values. Credentials remain separate SecretStr values. Every floating-point duration rejects NaN and both infinities in direct and environment construction.
- [PostgreSQL fixture support](../tests/support/postgres.py) keeps public out of disposable search paths. pgvector resides in the dedicated test_vector namespace; an existing extension elsewhere is refused, not relocated. Alembic explicitly scopes version_table_schema. Every foundation relation is checked before test connections are used and before migration/downgrade. [Isolation regressions](../tests/integration/test_isolation.py) create their own temporary database to prove public tables/data survive setup, mutation, downgrade/upgrade and teardown.
- Manifest support remains pgvector >=0.3.6,<1. Vector acceptance handles both NumPy (0.3.6) and Vector (0.5.0) results. The minimum was installed in .venv/minimum; package imports/provider-free checks are not real database adaptation proof.
- Initial revision SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567. No revision file or persisted schema was changed; no forward data migration was needed for these code/config/test repairs. Historical URL-secret cleanup is unresolved if an older deployment actually persisted such inputs.
- Provider-free commands .venv/Scripts/python -m pytest -m "not postgres" and .venv/minimum/Scripts/python -m pytest -m "not postgres": 88 passed in each environment (pgvector 0.5.0 and 0.3.6).
- Explicit PostgreSQL acceptance commands in both environments, -m postgres --require-postgres --tb=no, fail fixture setup when TEST_DATABASE_URL is absent. Docker info still fails inside and outside the sandbox with DockerDesktop/Wsl/ExecError and WSL bootstrap exit 0x40010004. No PostgreSQL migration/constraint/isolation/concurrency/vector evidence is claimed.
- README now agrees with requires-python >=3.11. Pipeline inventory and AGENTS.md point to the actual manifest, migrations and tests.
Final repair checks:
- .venv/Scripts/python -m pytest: 88 passed, 48 skipped. Skips are PostgreSQL cases with missing TEST_DATABASE_URL and do not count as acceptance.
- .venv/Scripts/python -m pytest -m postgres --require-postgres --tb=no -q and the same command using .venv/minimum/Scripts/python: 48 setup errors in each environment, zero PostgreSQL passes/skips; database configuration is absent. An earlier run before constraint coverage expansion had 34 setup errors.
- .venv/Scripts/python -m pip check and .venv/minimum/Scripts/python -m pip check: no broken requirements.
- .venv/Scripts/alembic history: unchanged initial revision discovered.
- git diff --check: passed; new-file syntax/whitespace inspection is separate.
## Final foundation acceptance evidence (2026-10-05)
Remaining settings defects were reproduced first: malformed port values leaked
dummy secrets into Pydantic output/context, malformed URL structure escaped as
SQLAlchemy ArgumentError, and valid ambient limit overrides broke baseline tests.
[Settings](../app/modules/documents/settings.py) now converts parser failures
to a generic validation error outside the parser handler and raises sanitized
ValidationError outside its handler, retaining no raw parser/input exception
chain. [Regressions](../tests/unit/test_database_urls.py) inspect str/repr/json,
errors and context/cause, exercise valid Psycopg URLs and rerun the ordinary suite
with external overrides. [Fixtures](../tests/conftest.py) clear ambient
INGEST_* variables per test without changing production loading or TEST_DATABASE_URL.
Docker became available. A dedicated temporary PostgreSQL/pgvector container,
rag-foundation-acceptance-7e382b6f, ran on localhost:54918 with the dedicated
rag_foundation_test database. The server was PostgreSQL 16.15; pgvector extension
0.8.7. Python adapter versions were 0.5.0 and minimum 0.3.6.
[Prerequisite check](../tests/postgres_prerequisites.py) verifies connectivity,
dedicated database configuration, CREATE/DROP DATABASE and extension privileges,
and the safe extension namespace before the suite. Both environments passed it.
No existing deployment/database or metadata was changed.
Final commands/results:
- .venv/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
- .venv/minimum/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected.
- .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected.
- .venv/Scripts/python -m pytest --require-postgres -q: 163 passed.
- .venv/Scripts/python -m tests.postgres_prerequisites and .venv/minimum/Scripts/python -m tests.postgres_prerequisites: passed.
- Both environments' python -m pip check: no broken requirements.
- .venv/Scripts/alembic history: initial revision discovered.
All final test runs had zero failures, setup errors or skips.
First real-DB run: 46 passed/2 failed in 0.5.0; first 0.3.6 run after initial test
repairs: 47 passed/1 failed. Repaired test SQL JSON binding, replaced
search-path-dependent deparsed constraint comparisons with complete stable
catalog comparisons, and used 0.3.6's supported NumPy native input. Assertions
continue to prove numeric vector values and unchanged public relations/data.
Public preservation, scoped downgrade/upgrade, constraints, profile checks and
concurrent bootstrap now have real PostgreSQL evidence.
The initial revision remains byte-for-byte unchanged with SHA-256
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
No persisted schema change or forward migration was needed. Historical credential
remediation is conditional on identifying an affected deployment and explicit
authorization; see setup instructions for rotation and targeted forward metadata
migration while preserving agreed embedding identity. No remediation is claimed.
Remaining limits: local acceptance does not prove production deployment,
real-provider compatibility/quality or any later ingestion phase. The standalone
operator migration/bootstrap commands remain separately documented; the suite
executes the real Alembic migration path and bootstrap database function.
Final cleanup/inspection: the dedicated database reported zero leftover disposable
schemas, zero generated foundation_*_test databases and zero public application
tables. The temporary acceptance container and its anonymous test volume were
removed; no other container was touched. git diff --check passed, syntax and
new-file whitespace checks passed, and the original migration hash was preserved.
Test organization: tests/unit contains provider-free configuration, endpoint,
database URL, import and test-environment cases. tests/integration contains
PostgreSQL migrations/profile, constraints, concurrency, vector and isolation
cases, with database-only fixtures and a directory-wide postgres marker.
tests/support contains reusable PostgreSQL and row helpers; tests never import
helpers from another test module. Shared settings fixtures remain in root
conftest.py. The tests.postgres_prerequisites command remains unchanged.
Organization validation: .venv/Scripts/python -m pytest --require-postgres -q:
163 passed. .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres
-q: 48 passed, 115 deselected. Both prerequisite commands passed on a temporary
dedicated PostgreSQL/pgvector container. Final runs had no failures/errors/skips.
The first moved-helper run exposed a repository-root path error, which was fixed
before these final checks. Initial migration hash, test syntax/whitespace and
git diff --check passed. See [test layout](../tests/README.md).
## Documentation organization (2026-10-05)
Project documentation is grouped in [the documentation index](README.md):
`specifications/`, `plans/`, `guides/` and `agent-guidance/`. The shared map
now lives at `docs/agent-reference-map.md`; repository instructions, skills,
setup and test navigation use its current location. The six governing
specifications retain their exact contents, and the initial migration is
unchanged. Documentation link checks exclude the pre-existing README link
to the absent LICENSE file. No runtime or database acceptance checks were
rerun for this documentation-only reorganization; the evidence above remains
the result of the previously recorded runs.
## Phase 2 intake acceptance evidence (2026-10-05)
Implemented [operator CLI](../app/ingest.py), [intake application service](../app/modules/documents/intake.py),
[local original store](../app/infrastructure/file_store.py), [provider-free tests](../tests/unit/test_intake.py)
and [PostgreSQL acceptance tests](../tests/integration/test_intake.py). The import
isolation regression now includes every new ingestion module. Setup commands and
storage/error/reconciliation semantics are in [the setup guide](guides/ingestion-foundation-setup.md).
Final executed commands:
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on dedicated
rag_intake_test in temporary container rag-intake-acceptance-20261005,
localhost:54919, PostgreSQL 16.15 and vector 0.8.7.
- `.venv/Scripts/python -m pytest -m "not postgres" -q`: 137 passed,
1 skipped, 65 deselected. The skip is actual filesystem symlink creation,
unavailable under this Windows account; it is not claimed as verified.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q`:
65 passed, 138 deselected, no failures/errors/skips. This includes 17 intake
cases and all 48 existing foundation cases, using disposable schemas and
independent connections; no real providers.
- Initial targeted PostgreSQL intake run: 14 passed. The first provider-free
run had four failures caused by new test fixture path/Unicode handling,
including the existing ordinary-suite recursion check; corrected before the
final results above.
Acceptance covers restart with a fresh store and disposed connection pool,
same-key concurrent replay, different-payload races and conflicts, independent
same-byte documents, inactive/zero-chunk intake, atomic job/audit rollback,
administrator revalidation and organization scoping, profile snapshot retention,
lost commit acknowledgment recovery, CLI JSON, failed finalization cleanup,
generated-key collisions, path escape rejection and report-only reconciliation.
Storage requires a trusted persistent local directory with hard-link support.
PDF intake validates signature only; extraction and worker remain later phases.
No applied migration, provider adapter, upload API, chat or Live behavior changed.
## Phase 2 intake repairs (2026-10-05)
The intake service now resolves committed organization-scoped upload keys before
new-document acceptance policy. Replay streams the accepted size plus at most one
byte using 64 KiB blocks, outside transactions. Same bytes/normalized title preserve
IDs, filename, profile and audit/job identities after lowering the size cap or
disabling the format. New keys retain current-policy validation; database uniqueness
continues to resolve concurrent first imports. Enabled-administrator validation and
embedding compatibility remain mandatory.
Known-unused candidate cleanup is best effort after a confirmed database outcome.
Failure emits a redacted diagnostic and leaves a reportable orphan, preserving
successful replay or IDEMPOTENCY_CONFLICT. Ambiguous commits never trigger candidate
deletion. CLI success JSON escapes Unicode for strict redirected output streams;
warning and error envelopes are separate JSON lines on stderr. See the updated
[setup guide](guides/ingestion-foundation-setup.md). No schema repair or later phase
implementation was required.
Executed repair validation:
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on PostgreSQL
16.15 / pgvector 0.8.7 in dedicated rag_intake_repair_test, temporary container
rag-intake-repair-20261005, localhost:54920.
- `.venv/Scripts/python -m pytest tests/unit/test_intake.py tests/unit/test_imports.py -q`:
26 passed, 1 skipped (Windows symlink privilege).
- `.venv/Scripts/python -m pytest tests/integration/test_intake.py --require-postgres -q`:
25 passed. One administrator-revalidation regression was added afterward.
- `.venv/Scripts/python -m pytest -m "not postgres" -q`: 140 passed,
1 skipped, 74 deselected. The filesystem symlink check remains unavailable;
that skip is not acceptance evidence.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q`:
74 passed, 141 deselected, no failures/errors/skips. Includes concurrent
first-import replay/conflict, ambiguous commit recovery, policy replay/new-key
enforcement, identity/profile guards and injected cleanup failures.
- `git diff --check`: passed. Untracked affected Python files were separately
inspected and checked for syntax/whitespace.
- The isolated database reported zero leftover disposable schemas, generated
foundation test databases or public tables.
No applied migration changed: initial SHA-256 remains
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
Strict ASCII/CP1252 tests exercise actual TextIOWrapper output with exact decoded
Persian, ZWNJ, CJK and emoji metadata. No real provider checks were run; these
repairs introduce no provider behavior. Original-store power-loss guarantees and
unavailable Windows symlink creation remain outside the verified evidence.
## Persian document and voice MVP documentation أ¢â‚¬â€‌ 2026-10-06
The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged.
[Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14أ¢â‚¬â€œ15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01أ¢â‚¬â€œP1-12, add P1-13أ¢â‚¬â€œP1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18أ¢â‚¬â€œ22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples.
All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run.
Code inspection confirms foundation/intake plus Markdown/Chroma text prototype, not a completed worker/authenticated RAG/Live system. The documentation update left PDF/Markdown settings, immutable originals and applied migration unchanged. The subsequent alignment below adds DOCX/image intake and extraction contracts; artifact storage, model adapters, pgvector chat search and WSS transport remain planned.
No separate requirements document or ADR directory was found; acceptance stays in the delivery plan and decisions in architecture Section 21. Account eligibility/quotas, funded embedding profile, approved factual content/numeric review and target-network/audio rehearsal remain dependent release gates. Documentation checking does not rerun or extend earlier application/database acceptance evidence.
## Page/block foundation and intake alignment ? 2026-10-06
Implemented explicit [format validation](../app/modules/documents/formats.py) for
PDF/Markdown/DOCX/JPEG/PNG, [transactional intake repository](../app/infrastructure/intake_repository.py),
[extraction envelope/types](../app/modules/documents/types.py), small extraction/vision
ports, schema-2 [settings snapshots](../app/modules/documents/settings.py), and
[pure artifact validation](../app/modules/documents/extraction_artifacts.py).
See [setup guide](guides/ingestion-foundation-setup.md) for limits, legacy dispatch,
preprocessing compatibility and the separate proposed extraction namespace.
Pillow/defusedxml are added to the existing manifest. There is no production
extractor/OCR/embedding/worker/retry/publication/HTTP upload implementation here.
New-format intake validity is not extractability or provider-quality evidence.
Provider-free regressions are in [formats](../tests/unit/test_formats.py) and
[extraction contracts](../tests/unit/test_extraction_contract.py); generated inputs
are shared through [format fixtures](../tests/support/formats.py). Import isolation
covers the added modules. PostgreSQL [intake tests](../tests/integration/test_intake.py)
cover new-format races, rollback, snapshots/legacy replay and administrator scope
revalidation. Initial migration hash and schema/embedding checks remain unchanged.
Final executed checks and actual results follow.
Final alignment validation (2026-10-06):
- `.venv/Scripts/python -m pytest -m "not postgres" -q`: **196 passed,
1 skipped, 92 deselected**. The skip is the existing Windows symlink-creation
privilege check; it is not acceptance evidence. Supplied DOCX/JPEG intake checks
passed. No providers, model downloads or prototype indexing ran.
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on dedicated
`rag_intake_formats_test`, temporary container
`rag-intake-formats-acceptance-20261006`, localhost:54921, PostgreSQL 16.15 /
pgvector 0.8.7 (Python adapter 0.5.0).
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q`:
**92 passed, 197 deselected**, zero failures/errors/skips. Includes all
existing embedding/schema/isolation checks plus new-format document/job/audit,
races, rollback, frozen profile and legacy replay cases.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `git diff --check`: passed. All 13 affected/new Python files also passed AST
syntax and trailing-whitespace inspection, including untracked files.
- Initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`;
no schema revision or embedding compatibility check changed.
- Database cleanup inspection found zero leftover disposable foundation schemas,
generated foundation test databases or public application tables. Only the
named temporary acceptance container/anonymous volume was removed afterward.
The initial alignment PostgreSQL run also passed 92 cases; final rerun followed
additional forged-central-directory and provenance/normalization guards. Earlier
provider-free runs passed 191 cases before those additional regressions. Docker
was initially stopped; checks failed before Docker Desktop was started from its
user-local installation. Final database evidence above supersedes that temporary
availability limitation. Existing unrelated containers were preserved.
Not validated: unavailable symlink privilege, production storage/power-loss behavior,
minimum pgvector 0.3.6 rerun for this change, OCR/provider transcription quality,
account/model access, deployment and later pipeline phases. Remaining decisions
include deployment format/resource budgets, funded model/QC policy and incompatible
Persian preprocessing migration/reindex design. Durable artifact attachment and
its persistence mechanism remain explicit Phase 5 implementation work, not an
implemented or accepted unfenced finalizer.
## Reviewed foundation/intake repairs - 2026-10-06
Repaired only the reviewed foundation/intake findings:
- [Format validation](../app/modules/documents/formats.py) now independently reads
bounded raw STORED/DEFLATED member streams, counts actual expansion, checks full
CRC/length/end-of-stream and physical boundaries, and validates ZIP32 signed or
unsigned data descriptors. Matching forged local/central prefix declarations
cannot bypass actual per-member/aggregate/ratio limits. No member extraction.
- [Artifact validation](../app/modules/documents/extraction_artifacts.py) now checks
recorded model/method provenance against the frozen profile; OCR/vision need
configured identity with exact requested/actual model equality. No aliases or
implicit routing are supported. Direct blocks carry no provider model.
- [Shared normalization](../app/modules/documents/normalization.py) validates/rederives
NFC plus LF-only v1 search text, preserving faithful evidence. Aggregate normalized
input budgets are enforced before inputs return. No Persian folding, profile
rewriting or embedding schema/preprocessing changes.
- [Settings](../app/modules/documents/settings.py) reject equal/nested canonical
original/artifact roots without creating storage. Relative/absolute and native
Windows case/extended-drive aliases are tested; real symlink checks are conditional.
- [Application intake](../app/modules/documents/intake.py) uses injected
`IntakeRepository` for all three operations. [CLI composition](../app/ingest.py)
constructs the SQL repository; output/error contracts are unchanged.
New regressions: [raw DOCX streams](../tests/unit/test_docx_streams.py),
[storage roots](../tests/unit/test_storage_roots.py), and
[SQL-free application ports](../tests/unit/test_intake_repository_port.py).
[Extraction contracts](../tests/unit/test_extraction_contract.py),
[shared fixtures](../tests/support/formats.py), import isolation and
[real PostgreSQL intake](../tests/integration/test_intake.py) were extended.
No production extraction/OCR, embedding, worker, artifact attachment, retry,
HTTP, chat or Live behavior was added. The [setup guide](guides/ingestion-foundation-setup.md)
defines actual guarantees and distinguishes metadata checks from provider quality.
The initial reproduction run (47 failures) showed that the earlier alignment tests
were insufficient evidence for these guarantees. Final checks follow below.
Final repair validation (2026-10-06):
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**285 passed, 3 skipped, 102 deselected**. Skips are the existing file-symlink
creation case and two new directory-symlink aliases; this Windows account denies
creation. Those cases are not claimed as verified. Native Windows case and
extended-drive alias tests passed. Supplied DOCX/JPEG and generated DOCX/JPEG/PNG
acceptance and import isolation passed; no provider calls or model downloads.
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on dedicated
`rag_intake_repair_test` in temporary container
`rag-intake-repair-acceptance-20261006`, localhost:54922, PostgreSQL 16.15 /
pgvector 0.8.7, Python adapter 0.5.0.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**102 passed, 288 deselected**, zero failures/errors/skips. Existing real
transaction/concurrency, SHARE-lock revalidation, scoped replay/conflict,
rollback, ambiguous commit, cleanup warning, policy-independent replay,
schema/vector and frozen legacy-profile assertions remain. Ten new cases cover
dishonest DOCX rejection before candidate/row creation and atomic descriptor-
based STORED/DEFLATED intake/replay. Application tests use SQL repository injection.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `git diff --check`: passed. AST syntax and trailing-whitespace inspection passed
for all 13 affected/new Python files, including untracked files. Local links and
whitespace in the three affected documents passed inspection.
- Initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
No persisted processing profile, migration or vector schema was changed.
- Cleanup inspection found zero leftover disposable schemas, generated foundation
test databases or public application tables. Only the named acceptance container
and its anonymous volume were removed; unrelated containers were retained.
The first repair run exposed one existing invalid partial-vision test fixture after
positive artifact fixtures were configured correctly. A later SQL-free port test
initially also blocked the existing configuration URL parser; its setup now validates
configuration first, clears cached SQL modules and forbids SQL infrastructure during
application import/execution. Both test issues were corrected before final acceptance.
These are separate from the original 47 reproduced product failures.
Limits: no real-provider/OCR quality, factual completeness, production deployment or
power-loss guarantee is established. Actual symlink alias validation remains unrun
under this account, and this repair did not rerun minimum pgvector 0.3.6 or non-Windows
platforms. Model aliases/implicit resolution are deliberately unsupported. Future
artifact writes/attachment still require a worker-fenced implementation; no such path,
worker, retry, embedding, HTTP, chat or Live behavior was added. Deployment budgets,
funded provider models and QC thresholds remain existing release decisions.
## Phase 3 extraction/QC/chunking implementation - 2026-10-06
This supersedes earlier inventory statements that no extractor/artifact writer
exists. [Extractor/QC](../app/modules/documents/extraction.py),
[chunk drafts](../app/modules/documents/chunking.py) and
[preparation](../app/modules/documents/processing.py) implement schema-2 extraction
without prototype imports. [Gemini vision](../app/infrastructure/gemini_vision.py)
is explicitly configured and opt-in. [Artifact candidates](../app/infrastructure/extraction_candidates.py)
are bounded immutable files in the separate extraction namespace; there is no
durable attachment/reuse authorization or unfenced finalizer. Phase 5 remains
responsible for worker ownership/lease fencing, lifecycle failure updates and
publication. No embedding adapter, worker, HTTP, chat or Live changes were made.
[Setup and QC composition](guides/ingestion-foundation-setup.md) documents the
immediate evidence-bound manual review gate, supported/rejected source structures,
normalization compatibility, semantic size failures and corpus-purpose separation.
Schema-2 processing snapshots and the applied initial revision are preserved.
[Generated fixture helpers](../tests/support/extraction.py),
[extraction acceptance](../tests/unit/test_phase3.py),
[REST adapter contracts](../tests/unit/test_gemini_vision.py) and
[PostgreSQL preparation isolation](../tests/integration/test_phase3.py) supply
provider-free evidence. The supplied DOCX's 100 pairs are extracted, including
the first pair split across adjacent tables; no factual approval is inferred.
Executed acceptance results are recorded below after the final checks.
Final executed Phase 3 checks (2026-10-06):
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on dedicated
`rag_phase3_test`, temporary `rag-phase3-acceptance-20261006` container,
localhost:54923, PostgreSQL 16.15 / pgvector 0.8.7.
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**344 passed, 3 skipped, 105 deselected**. The three skips are the existing
file/directory symlink privilege cases. No real providers or prototype indexing.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**105 passed, 341 deselected**, zero skips/failures/errors. This full run preceded
the final provider-order/error-category correction; no database code changed.
- After that correction,
`.venv/Scripts/python -m pytest tests/integration/test_phase3.py --require-postgres -q --tb=short`:
**3 passed**. The final ordinary suite above includes six additional REST cases.
- Earlier targeted
`.venv/Scripts/python -m pytest tests/unit/test_phase3.py tests/unit/test_gemini_vision.py tests/unit/test_imports.py -q --tb=short`:
**54 passed**, before those final six cases.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `git diff --check`: passed; syntax/whitespace/local-link inspection includes
all 16 affected files, including untracked files.
- Initial revision SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Cleanup inspection found zero disposable test schemas, generated foundation
databases or public application tables. The named temporary acceptance
container and its anonymous volume were removed; unrelated containers remain.
The first targeted run reported two failures (cross-table first FAQ pair and
adapter unreadable-region handling); both were fixed. A later collection run was
blocked by an unused incorrect test import; corrected before successful full
checks. Final inspection also added dependent-heading grouping, provider ordinal
validation and redacted transient/permanent provider errors. Timeouts/network/
408/429/5xx failures are retryable; ordinary HTTP rejections and QC failures are
permanent. The adapter itself never retries.
Not validated: funded real-provider extraction/transcription quality, real manual
PDF/image fidelity acceptance, unavailable symlink privileges, production storage/
power-loss behavior, minimum pgvector 0.3.6 rerun or non-Windows deployment.
Supplied DOCX structural extraction is verified; its factual authority is not.
Unsupported/blank PDF pages and unsupported DOCX structures fail instead of being
silently omitted. Worker, artifact attachment/reuse authorization, embeddings and
publication remain later phases.
## Confirmed Phase 3 repair inventory (2026-10-06)
[Scoped regression suite](../tests/unit/test_phase3_repairs.py) reproduces the
confirmed extraction, association, bounds, FAQ, deadline and separator defects.
[Extraction](../app/modules/documents/extraction.py) rejects unsupported DOCX
wrappers/numbering instead of silently losing content and preserves hyphen run
characters and readable-text FAQ groups. [Chunking](../app/modules/documents/chunking.py)
keeps supported dependent units across pages/methods/groups, fails ambiguous
associations and preserves exact block boundaries.
[Artifact helpers](../app/modules/documents/extraction_artifacts.py) preflight
bounded JSON assembly for extraction, preparation, chunking and candidate writes.
[Gemini](../app/infrastructure/gemini_vision.py) enforces an absolute caller deadline,
including late reads/EOF, without adapter retries.
See [setup repair behavior](guides/ingestion-foundation-setup.md) for the exact
supported/rejected DOCX structures, automatic numbering policy, heading/prose
recognition, source-group ambiguity and blocking-transport qualification.
The [pipeline plan](plans/ingestion-pipeline-plan.md) now reports Phase 3's actual
implementation status; its acceptance requirements and Phase 5 fencing are unchanged.
No real-provider or manual Persian fidelity acceptance is inferred from these tests.
Final executed repair evidence (2026-10-06):
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on dedicated
`rag_phase3_repairs_test`, temporary container `rag-phase3-repairs-20261006`,
localhost:54924, PostgreSQL 16.15 / pgvector 0.8.7.
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**399 passed, 3 skipped, 105 deselected**. Skips are the existing file/directory
symlink-creation privilege cases, not acceptance evidence. The supplied DOCX's
100 pairs, frozen provenance/normalization contracts and import isolation pass.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**105 passed, 402 deselected**, zero failures/errors/skips. Existing real
constraints, intake races, scoped rollback and Phase 3 preparation isolation pass.
- Last targeted run before final full suites:
`.venv/Scripts/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short`:
**114 passed**. The repair file contains 55 generated cases.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `git diff --check`: passed; all 11 affected files also passed AST (Python),
trailing-whitespace and local Markdown link inspection, including untracked files.
- Initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Database cleanup inspection found zero disposable schemas, generated foundation
databases and public application tables. The named temporary container and its
anonymous volume were removed; unrelated containers were preserved.
An intermediate full provider-free run reported one blocking-fixture failure:
the 50 ms deadline expired before its test thread entered the fake operation.
The fixture now allows a 300 ms deadline and a 3-second fake block, still requiring
return before 1.5 seconds; open/read/EOF cases pass in the final full suite.
The production absolute deadline was not relaxed. Earlier reproduced product
failures were corrected before final acceptance.
Affected files: extraction.py, chunking.py, extraction_artifacts.py, processing.py,
extraction_candidates.py, gemini_vision.py, test_phase3_repairs.py,
test_gemini_vision.py, this setup guide, the reference map and the pipeline plan.
No dependencies, schemas, originals, frozen profiles or unrelated files were changed.
No real-provider quality or manual Persian PDF/image fidelity acceptance was run.
Minimum pgvector 0.3.6, unavailable symlink creation, production transport/storage
and OS-level cancellation remain unverified. Phase 5 attachment/reuse fencing is
still required; these repairs provide no worker or unfenced finalizer.
## Six additional Phase 3 context/transport repairs (2026-10-06)
[Regression cases](../tests/unit/test_phase3_context_repairs.py) cover equations,
tracked moves, FAQ heading hierarchy, whole dependency references, independent
circulars/decisions and outstanding transport capacity, with positive controls.
[Extraction](../app/modules/documents/extraction.py) validates paragraph namespaces
and containers, rejects equations and move/property/cell revisions, and keeps
unambiguous nested FAQ answer subsections in their original Q&A group.
[Chunking](../app/modules/documents/chunking.py) validates complete dependency
units regardless of source groups, distinguishes explicit incidental citations
from applicability targets, and recognizes plain circular/decision boundaries.
[Gemini](../app/infrastructure/gemini_vision.py) shares a single process-wide
transport slot across calls and instances, retaining occupancy after deadline
expiry until blocking work exits. Capacity errors are redacted/retryable,
there are no retries, and late responses cannot be consumed.
See the [final supported/rejected behavior](guides/ingestion-foundation-setup.md)
for supported DOCX containers, conservative reference/citation grammar, FAQ
hierarchy and OS cancellation limitations. Prior normalization, immutable originals,
frozen provenance and Phase 5 attachment/reuse fencing requirements are unchanged.
Executed checks for the six additional repairs (2026-10-06):
- Before corrections: `.venv/Scripts/python -m pytest tests/unit/test_phase3_context_repairs.py -q --tb=short`
reproduced **28 failed, 8 passed**, covering all six defects. Additional
cross-adapter capacity and hidden-rule regressions subsequently reproduced
**2 failed, 36 passed** before their corrections. The final explicit-rule
conflict within FAQ context separately reproduced **1 failed** before correction.
- Final targeted check:
`.venv/Scripts/python -m pytest tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short`:
**153 passed**. The new regression file has 39 generated cases; existing tests
preserve the supplied DOCX's 100 FAQ pairs, including its cross-table pair.
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**438 passed, 3 skipped, 105 deselected**. Skips concern unavailable Windows
file/directory symlink privileges; they do not prove that behavior.
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed on isolated
`rag_phase3_context_repairs_test`, dedicated container
`rag-phase3-context-repairs-20261006`, localhost:54925,
PostgreSQL 16.15 / pgvector 0.8.7.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**105 passed, 441 deselected**, no failures/errors/skips. TEST_DATABASE_URL
pointed only to the isolated database above.
- `.venv/Scripts/python -m pip check`: **No broken requirements found**.
- `git diff --check`: passed (Git reports existing LF/CRLF conversion notices).
The six affected files also passed Python AST, trailing-whitespace and local
Markdown-link checks, including untracked files.
- Initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Database cleanup inspection returned zero disposable test schemas, public
application tables and generated foundation databases. Only the dedicated
temporary container and its anonymous volume were removed.
Real-provider quality and manual Persian fidelity acceptance were **not executed**.
Generated fixtures and fake transports are not evidence for either. OS cancellation
of blocking DNS/network operations remains unsupported: an operation may occupy the
single process-wide slot indefinitely until it returns; capacity failures remain
visible and retryable. No adapter retries or late-result consumption are added.
Attachment and runtime reuse still require Phase 5 durable current-claim fencing.
## Four Phase 3 visibility/scope/completion repairs (2026-10-06)
[New regression cases](../tests/unit/test_phase3_visibility_scope_repairs.py) cover
the four scoped repairs plus visible text, explicit disabled hiding, style toggles,
scope conflicts, faithful line endings and deterministic transport scheduling.
[Extraction](../app/modules/documents/extraction.py) rejects effective hidden DOCX
evidence from direct properties and used styles/defaults, and parses paragraph
boundaries across LF/CRLF/CR while retaining faithful bytes-as-text.
[Chunking](../app/modules/documents/chunking.py) permits multiple rules within an
indivisible FAQ using Markdown ancestry or within a visual group using explicit
parent links; conflicting and ambiguous dependencies still fail.
[Gemini](../app/infrastructure/gemini_vision.py) closes transport work and releases
shared capacity before publishing completion to the caller.
The [setup guide](guides/ingestion-foundation-setup.md) records precise
supported/rejected behavior, Word style-toggle semantics and remaining limitations.
The existing Phase 3 contracts and Phase 5 attachment/reuse fencing remain governing.
Executed evidence for these four repairs (2026-10-06):
- Initial `.venv/Scripts/python -m pytest tests/unit/test_phase3_visibility_scope_repairs.py -q --tb=short`:
**22 failed, 21 passed**, before implementation changes. All four defects
reproduced; visible/disabled-hiding and conflicting-scope controls were included.
- Combined Phase 3 regression run:
`.venv/Scripts/python -m pytest tests/unit/test_phase3_visibility_scope_repairs.py tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short`:
**196 passed**. After adding three style-toggle/mixed-ending controls,
`.venv/Scripts/python -m pytest tests/unit/test_phase3_visibility_scope_repairs.py -q --tb=short`
passed **46 cases**. The final full suite includes all of them.
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**484 passed, 3 skipped, 105 deselected**. The three existing skips concern
unavailable Windows file/directory symlink privileges. The supplied DOCX's
100 pairs, previous regression cases and import isolation pass.
- `.venv/Scripts/python -m tests.postgres_prerequisites`: the first attempt on the
newly started isolated instance failed. After `pg_isready` reported accepting
connections, the retry passed: PostgreSQL 16.15 / pgvector 0.8.7.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**105 passed, 487 deselected**, no failures/errors/skips, using isolated
TEST_DATABASE_URL for `rag_phase3_visibility_repairs_test` on localhost:54926
in dedicated container `rag-phase3-visibility-repairs-20261006`.
- `.venv/Scripts/python -m pip check`: **No broken requirements found**.
- `git diff --check`: passed with existing LF/CRLF conversion notices.
Separate checks of the six affected files passed Python AST, trailing whitespace
and local Markdown links, including untracked files.
- Initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Database cleanup inspection found zero disposable test schemas, public application
tables and generated foundation databases. Only the named temporary container and
its anonymous volume were removed; unrelated containers were preserved.
Real-provider extraction quality and manual Persian fidelity acceptance remain
**unverified**. Fake transports and generated sources provide regression evidence
only. OS-level cancellation remains unsupported: a blocking operation can retain
the one process-wide transport slot after caller timeout until cleanup finishes.
Attachment/runtime reuse still requires Phase 5 durable current-claim fencing.
## Phase 3 semantic evidence, identifiers, scopes and HTTP cleanup (2026-10-06)
[Semantic regressions](../tests/unit/test_phase3_semantic_repairs.py) cover effective
superscript/subscript and strikethrough, complete English/Persian identifiers,
single-rule FAQ/visual scopes and tracked HTTPError streams with blocked cleanup.
[Extraction](../app/modules/documents/extraction.py) now uses
`_reject_docx_semantic_formatting` for effective visibility/alignment/strike checks.
[Chunking](../app/modules/documents/chunking.py) validates full compact identifiers
and applies explicit structural scopes with one or multiple governing rules.
[Gemini](../app/infrastructure/gemini_vision.py) closes HTTPError-owned streams before
releasing process-wide capacity and publishing worker outcomes.
The [setup guide](guides/ingestion-foundation-setup.md) records the exact supported
identifier grammar, explicit semantic-format rejection/reset behavior, dated
metadata handling, scope controls and cleanup/deadline limitations. The governing
Phase 3 contracts and Phase 5 attachment/runtime-reuse fencing are unchanged.
Executed evidence for these four semantic repairs (2026-10-06):
- Before implementation changes:
`.venv/Scripts/python -m pytest tests/unit/test_phase3_semantic_repairs.py -q --tb=short`
reproduced **61 failed, 33 passed**, covering all four defects.
- Final inspection separately reproduced unsupported spaced identifiers:
`.venv/Scripts/python -m pytest tests/unit/test_phase3_semantic_repairs.py -k unsupported_spaced -q --tb=short`:
**3 failed, 94 deselected** before the narrow rejection was added.
- Final targeted command:
`.venv/Scripts/python -m pytest tests/unit/test_phase3_semantic_repairs.py tests/unit/test_phase3_visibility_scope_repairs.py tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short`:
**296 passed**. The new file contains 97 cases. The supplied DOCX's
**100 pairs** and all previous Phase 3 regressions pass.
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**581 passed, 3 skipped, 105 deselected**. The existing skips are Windows
file/directory symlink-creation privilege cases, not acceptance evidence.
- After `pg_isready` reported accepting connections,
`.venv/Scripts/python -m tests.postgres_prerequisites` passed on dedicated
`rag_phase3_semantic_repairs_test`, container
`rag-phase3-semantic-repairs-20261006`, localhost:54927:
PostgreSQL 16.15 / pgvector 0.8.7.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**105 passed, 584 deselected**, zero failures/errors/skips. TEST_DATABASE_URL
was configured only for the dedicated isolated instance above.
- `.venv/Scripts/python -m pip check`: **No broken requirements found**.
- `git diff --check`: passed, with existing LF/CRLF conversion notices.
Separate AST, trailing-whitespace and local Markdown-link checks passed for all
six affected files, including untracked files.
- A baseline hash comparison of existing tracked/untracked working-tree files
confirms that only extraction.py, chunking.py, gemini_vision.py and these two
documentation files changed; test_phase3_semantic_repairs.py is the only new file.
Originals, frozen-profile/normalization code and unrelated changes were preserved.
- The applied initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Cleanup inspection returned zero disposable test schemas, public application
tables and generated foundation databases. Only the dedicated test container
and its anonymous volume were removed; unrelated containers were preserved.
An intermediate corrected targeted run had one compatibility failure:
`Decision dated 1403/01/02` was being treated as an identifier. The final parser
recognizes the explicit dated/ط¸â€¦ط¸ث†ط·آ±ط·آ® metadata qualifier; the existing control passes.
Real-provider extraction quality and manual Persian fidelity acceptance remain
**unverified**. These generated fixtures and fake providers do not establish
either. OS-level cancellation remains unsupported: a blocked transport or cleanup
can outlive the caller and retain process-wide capacity until it finishes. No
adapter retries were added. Candidate attachment/runtime reuse remain gated on
Phase 5 durable current-claim fencing.
## Phase 3 closure repair evidence (2026-10-06)
The [setup guide's closure repair](guides/ingestion-foundation-setup.md) records
exact commands and supported/rejected boundaries. Current source:
[extraction](../app/modules/documents/extraction.py) rejects effective semantic
transformations, preserves DOCX FAQ outline ancestry and table continuations,
and enforces construction budgets; [chunking](../app/modules/documents/chunking.py)
validates full dependency lists/ranges and explicit DOCX parent scopes;
[artifact validation](../app/modules/documents/extraction_artifacts.py) counts
exact JSON bytes without serializing accumulated output.
[Closure regressions](../tests/unit/test_phase3_closure.py) contain **111 cases**.
The [prior adjacent-table test](../tests/unit/test_phase3.py) now keeps answer
continuations grouped rather than treating a table boundary as an answer end.
Executed final evidence: targeted files **388 passed**, including supplied
**100 pairs**; provider-free suite **692 passed, 3 Windows symlink privilege
skips, 105 deselected**; PostgreSQL `--require-postgres` acceptance **105 passed,
693 deselected** on isolated `rag_phase3_closure_test`, localhost:54928,
PostgreSQL 16.15/pgvector 0.8.7. Pip check, diff check and separate affected-file
AST/whitespace/local-link checks passed. Baseline hashes preserve unrelated
changes, immutable originals, frozen profiles, normalization and applied migration.
Active position/case/hiding semantics fail safely; resets, harmless formatting
and unused styles pass. Deeper DOCX answer headings/table continuations stay
atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and
Persian ط¸â€¦ط·آ§ط·آ¯ط¸â€،/ط¸â€¦ط¸ث†ط·آ§ط·آ¯ targets support explicit conjunction/comma lists and simple
integer ranges; unsupported malformed/complex identifiers fail. Incidental
citations and ordinary decision prose remain accepted. See the setup guide for
exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated;
real-provider quality/manual Persian fidelity are unverified, and OS cancellation
limitations remain. Style-read consolidation and additional grammar fixtures
remain minor backlog.
## Phase 4 source and acceptance (2026-10-06)
The [setup guide's Phase 4 section](guides/ingestion-foundation-setup.md) describes
explicit endpoint-specific limits, optional tokenizer setup, frozen request
metadata, staging lifecycle/budget accounting and transport limitations.
[Embedding tests](../tests/unit/test_phase4.py) use fake HTTP/counters only;
[database isolation](../tests/integration/test_phase4.py) exercises concurrent
failed final batches against real PostgreSQL with zero publication effects.
[Import isolation](../tests/unit/test_imports.py) covers both new modules.
No worker/fenced publisher is implemented; Phase 5 remains required.
Existing frozen profiles are preserved and fail safely when explicit embedding
limits are absent; no tokenizer/endpoint compatibility is guessed.
Executed Phase 4 checks (2026-10-06):
- Initial targeted command:
`.venv/Scripts/python -m pytest tests/unit/test_phase4.py tests/unit/test_imports.py -q --tb=short`:
**58 passed**. Five further controls were added before the final full suite.
- Final `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**754 passed, 3 skipped, 106 deselected**. Existing skips concern Windows
file/directory symlink privileges; no real providers were contacted.
- `.venv/Scripts/python -m tests.postgres_prerequisites`: passed after
`docker exec rag-phase4-20261006 pg_isready -U postgres -d rag_phase4_test`
reported accepting connections. Dedicated container `rag-phase4-20261006`,
database `rag_phase4_test`, localhost:54929, PostgreSQL 16.15 / pgvector 0.8.7.
- Final `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**106 passed, 757 deselected**, zero failures/errors/skips. TEST_DATABASE_URL
targeted only the isolated instance above. Existing database constraints/races
and the new concurrent final-batch failure/zero-chunk invariant pass.
- `.venv/Scripts/python -m pip check`: **No broken requirements found**.
- `git diff --check`: passed, with existing LF/CRLF notices.
Separate inspection of all **13 affected files**, including untracked files,
passed Python AST, trailing whitespace and local Markdown links.
- The applied initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Dedicated database cleanup inspection found **zero** disposable schemas,
public tables and generated foundation databases. The named temporary
container and its anonymous volume were removed; unrelated containers remain.
Affected files: openai_embeddings.py, embeddings.py, settings.py, types.py,
ports.py, test_phase4.py (unit and integration), test_imports.py, pyproject.toml,
.env.example, this setup guide, the reference map and the ingestion pipeline plan.
Unrelated existing changes/specifications and immutable original files were not
edited. No schema migration or persisted profile rewrite was introduced.
Real hosted-provider validation, production tokenizer/endpoint compatibility,
optional tiktoken installation and retrieval-quality evaluation were **not run**.
Worker claims, retry scheduling and atomic publication remain Phase 5 work.
Staging is bounded by payload bytes rather than total RSS; OS cancellation and
consumer-retained references have the limitations described above.
## Phase 4 reviewed repairs (2026-10-06)
[Repair regressions](../tests/unit/test_phase4_repairs.py) cover the four
reviewed defects and controls. The [embedding service](../app/modules/documents/embeddings.py)
and [hosted adapter](../app/infrastructure/openai_embeddings.py) now enforce:
- Float32 multiplication and accumulation for the squared cosine norm, matching
the operations relevant to pgvector cosine distance. Both [1e-30, 0, 0] and
[1e20, 0, 0] fail permanently, as does aggregate float32 norm overflow.
Accepted vectors retain their original float32 bytes; no scaling or
normalization is introduced. Real PostgreSQL tests validate all 49 ordered
pairs of seven accepted packed vectors, including self, opposite, orthogonal,
mixed and small/large magnitudes. The two reviewed extremes produce nonfinite
raw PostgreSQL cosine distances and are rejected by the application.
- Content-Length completion is checked at EOF using the HTTPResponse's initial
declared remaining length. Both truncated JSON and syntactically complete
prefixes of incomplete bodies fail transiently before decoding.
HTTP protocol/incomplete chunk failures are also transient. Tests construct
real http.client.HTTPResponse objects over local byte streams without sockets.
Response byte bounds, absolute deadlines, stream cleanup and the shared slot
remain enforced, with no retries or late-result consumption. A blocked cleanup
retains capacity after caller timeout until it exits.
- UTF-8 JSON (optional BOM) is limited to 64 object/array nesting levels before
decoding. Brackets inside quoted/escaped strings do not count. Excess depth
and decoder RecursionError failures become redacted permanent EmbeddingError
outcomes. Malformed or incomplete responses never return partial vectors.
- Staging validates required profile mappings, the pinned normalization policy,
raw strictly positive integer staging limits before batch-size capping, and
ChunkDraft/text/metadata types before use. Expected key/type/attribute/value/
recursion failures become redacted permanent EmbeddingError outcomes.
Already-classified provider errors retain their identity and retry category.
Consumer exceptions raised inside the context are propagated unchanged while
staging is released.
The existing shuffled indexes, complete-document publication boundary, exact
payload-budget limits, faithful chunk text, frozen identity/policy checks and
context cleanup are preserved. No document_chunks writes, retries, worker,
schema changes, persisted-profile rewriting, content versions or chat/Live
changes were added. Phase 5 publication fencing remains required.
Real-provider/tokenizer compatibility remains unverified. Generated vector
cosine tests are database arithmetic evidence, not semantic embedding quality.
The payload budget is not total RSS, and OS cancellation/consumer-retained view
limitations from the Phase 4 section remain unchanged.
Executed repair evidence (2026-10-06):
- Before production fixes,
`.venv/Scripts/python -m pytest tests/unit/test_phase4_repairs.py -q --tb=short`:
**36 failed, 25 passed**, reproducing all four reviewed defects. Five additional
cleanup/depth/request-limit controls were added after the fixes.
- Final targeted command,
`.venv/Scripts/python -m pytest tests/unit/test_phase4_repairs.py tests/unit/test_phase4.py tests/unit/test_imports.py -q --tb=short`:
**129 passed**. The new file contains 66 cases.
- Final `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**820 passed, 3 skipped, 109 deselected**. The three existing skips concern
Windows file/directory symlink privileges and provide no acceptance evidence.
- After `docker exec rag-phase4-repairs-20261006 pg_isready -U postgres -d rag_phase4_repairs_test`
reported accepting connections, `.venv/Scripts/python -m tests.postgres_prerequisites`:
passed, PostgreSQL **16.15** / pgvector **0.8.7**.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**109 passed, 818 deselected**, no errors/failures/skips. This run used only
TEST_DATABASE_URL for dedicated `rag_phase4_repairs_test`, container
`rag-phase4-repairs-20261006`, localhost:54930. It preceded the five final
provider-free controls; production code did not change afterward.
- `.venv/Scripts/python -m pip check`: **No broken requirements found**.
- `git diff --check`: passed with existing LF/CRLF notices. Separate checks of
all seven affected files passed Python AST, trailing whitespace and local
Markdown links, including the untracked repair test and specifications.
- Baseline hash comparison confirms exactly six intended existing files changed:
embeddings.py, openai_embeddings.py, integration/test_phase4.py, the setup guide,
reference map and pipeline plan. unit/test_phase4_repairs.py is the only new file.
All other tracked/untracked baseline files and immutable originals are unchanged.
- Applied initial migration SHA-256 remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Dedicated database cleanup inspection found zero disposable schemas, public
tables and generated foundation databases. Only the named temporary test
container and its anonymous volume were removed; unrelated containers remain.
No real-provider calls or production tokenizer compatibility checks were made.
PostgreSQL arithmetic and constraint evidence is separate from provider quality.
## Phase 4 closure (2026-10-07)
[Closure regressions](../tests/unit/test_phase4_closure.py) exercise fake providers
and local HTTP byte streams; [PostgreSQL checks](../tests/integration/test_phase4.py)
provide separate database evidence. The embedding service and hosted adapter now:
- Capture provider identity and request policy before consuming drafts or counting
tokens. Account using the captured dimension, and recheck before requests,
after responses/result consumption, and before yielding complete staging.
Preparation-time drift fails permanently without provider calls.
- Reject NUL and invalid UTF-8 in retained text/location strings before embedding,
including section metadata passed through a vision extraction envelope,
artifact validation and chunking. Evidence is never stripped or rewritten.
Persian, ZWNJ and newline controls retain their original text/location values.
- Inspect only complete, bounded 429 error bodies: at most the smaller of the
configured response limit and 64 KiB, with 64 structural nesting levels.
Official OpenAI codes credit_balance_exhausted, organization_spend_limit_exceeded,
project_spend_limit_exceeded and organization_usage_limit_exceeded, plus the
broader insufficient_quota category, are permanent. Temporary rate limits and
unknown, empty, malformed, oversized or incomplete bodies retain the status
fallback (429 transient). Messages are never used to infer billing status or
exposed in errors. See [official error codes](https://developers.openai.com/api/docs/guides/error-codes).
- Validate direct constructor/configuration types, profile/endpoint values,
counter shape/identity, UTF-8 inputs and visible-ASCII authorization keys
before transport. Expected validation failures are redacted permanent errors;
classified provider errors keep their category. Unrelated programming failures
propagate. Inputs require a bounded sequence; iteration is also capped so a
dishonest reported length cannot bypass the batch limit.
- Reject duplicate JSON fields/nonstandard numbers and dishonest vector-result
cardinality. Counter identity is rechecked after counting; actual token counts
must fit PostgreSQL's positive integer range. Invalid tokenizer identities,
raw transport exception context and error-stream cleanup failures are handled
safely. Each batch still makes exactly one request with no adapter retries.
The full review retained input/batch unit limits, shuffled-index mapping,
model/dimension checks, float32 cosine safety, complete HTTP framing, absolute
transport deadlines, payload/depth bounds, shared capacity, cleanup after failure
or context exit, faithful evidence and exact staging-budget boundaries.
No document_chunks writes, original changes, applied-migration edits, persisted
profile rewrites, worker/Phase 5 implementation, content versions or chat/Live
changes were introduced. CLI initialization remains independent of the prototype.
Executed checks:
- Before fixes, `.venv/Scripts/python -m pytest tests/unit/test_phase4_closure.py -q --tb=short`:
**63 failed, 31 passed**, reproducing the four requested defects.
Subsequent full-contract regressions first produced **5 failed, 110 passed**,
then the five selected counter/sequence/integer/identity cases produced
**5 failed, 115 deselected**, before their respective fixes.
- Final targeted command:
`.venv/Scripts/python -m pytest tests/unit/test_phase4_closure.py tests/unit/test_phase4_repairs.py tests/unit/test_phase4.py tests/unit/test_imports.py -q --tb=short`:
**249 passed** (120 closure cases).
- `.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short`:
**940 passed, 3 skipped, 113 deselected**. The existing Windows symlink privilege
skips provide no database acceptance evidence.
- `docker exec rag-phase4-closure-20261007 pg_isready -U postgres -d rag_phase4_closure_test`:
accepting connections.
`.venv/Scripts/python -m tests.postgres_prerequisites`: passed, PostgreSQL
**16.15**, pgvector **0.8.7**.
- `.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short`:
**113 passed, 943 deselected**, no failures/errors/skips. Only the isolated
TEST_DATABASE_URL for rag_phase4_closure_test in dedicated container
rag-phase4-closure-20261007 (127.0.0.1:54931) was used. New checks prove JSONB
rejects NUL, valid Unicode round-trips faithfully and out-of-range token counts
fail before provider work. Existing accepted-vector cosine pairs, unsafe norms,
concurrency and failed-final-batch zero-publication checks remain included.
- `.venv/Scripts/python -m pip check`: **No broken requirements found**.
Real-provider/production-tokenizer compatibility and semantic quality were not
tested. Fake-provider tests and PostgreSQL arithmetic do not establish them.
No remaining concrete defect was identified in the reviewed Phase 4 paths.
The staging budget measures payload bytes, not total RSS; consumer-retained
references and OS-level cancellation/blocking cleanup retain the previously
documented limitations. Phase 5 lease fencing and atomic publication remain
necessary before a worker can publish staging.
Final preservation/cleanup checks:
- `git diff --check` passed (existing LF/CRLF conversion notices only).
Separate AST, trailing-whitespace and local Markdown-link checks passed for
all seven affected files, including the untracked closure tests.
- Baseline SHA-256 comparison confirmed exactly six existing files changed:
embeddings.py, openai_embeddings.py, integration/test_phase4.py, this setup
guide, reference map and pipeline plan. unit/test_phase4_closure.py is the
only new file. All other tracked/untracked baseline files, specifications and
originals are unchanged. The applied initial migration hash remains
`9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Dedicated database inspection found zero disposable schemas, public tables
and generated foundation databases. Only rag-phase4-closure-20261007 and its
anonymous volume were removed. The three unrelated containers remain.
## Phase 4 vector validation, float32 cosine safety, timeout and hostname repairs (2026-10-07)
[New regression suite](../tests/unit/test_phase4_vector_timeout_repairs.py) reproduces and validates
the four scoped findings together; [PostgreSQL tests](../tests/integration/test_phase4.py) provide real
pgvector distance and reference evidence. Source modules [embeddings](../app/modules/documents/embeddings.py),
[settings](../app/modules/documents/settings.py), and [adapter](../app/infrastructure/openai_embeddings.py) now:
- Consume no more than D+1 elements when validating and packing vectors; never trust `__len__` alone.
Captured elements are validated and packed exactly once into float32 array requiring actual dimension D
and storage exactly 4*D bytes. Dishonest sequences, changing elements across traversals, and endless
sequences cannot bypass dimension validation or the staging budget. Clean up partial staging on failed final batches.
- Reject float32 cosine distortion without rescaling: pgvector accumulates products and squared norms in float32.
Vectors like `[1e-21] * 16000` have a normal accumulated sum of squares but subnormal precision on every term,
and `[3e-23, 0, 0]` suffers ~20% cosine distortion against `[1, 0, 0]`. Precision-safety rule requires accumulated
float32 squared norm is normal (`FLT_MIN = 2**-126 ~ 1.175e-38`) AND `max_i(v_i**2) >= FLT_MIN` (`max_i(|v_i|) >= 2**-63`).
Safe mixed-scale vectors like `[1e-30, 1, 0]` are preserved unscaled. Real PostgreSQL tests validate multi-dimensional
comparisons against high-precision references across boundary magnitudes, dimensions (1D, 2D, 4D), signs, and directions.
- Preflight runtime synchronization and socket timeout representation limits (`(2**31 - 1) / 1000.0` seconds / 32-bit timeval).
`timeout_seconds=1e20` and unrepresentable values are rejected as permanent `EmbeddingError` (`retryable=False`)
directly and via `from_settings` without starting a thread, request, or acquiring `_CAPACITY`. Ordinary deadlines and
capacity cleanup are preserved. Frozen profiles are never silently clamped.
- Validate runtime hostname syntax and IDNA encoding without DNS or network calls. Empty interior DNS labels (`example..com`),
leading/trailing dots, labels > 63 characters, label-boundary hyphens, and malformed IP spellings are rejected.
Valid DNS names, IPv4, IPv6 (`[::1]`, `[2001:db8::1]`), ports, paths, and exact frozen profile identity are preserved.
Redacted permanent errors are returned; unrelated programming failures propagate without a blanket handler.
Executed validation:
- Targeted repair tests: **50 passed** (`test_phase4_vector_timeout_repairs.py`).
- Combined Phase 4 suite: **299 passed** (all four Phase 4 unit suites + `test_imports.py`).
- Provider-free full suite: **990 passed, 3 skipped, 117 deselected**. The three skips are Windows symlink privilege checks.
- Dedicated PostgreSQL acceptance: **117 passed, 993 deselected**, zero failures/errors/skips on isolated container
`rag-phase4-repairs-20261007` (localhost:54932, PostgreSQL 16.15 / pgvector 0.8.7).
- `python -m pip check` passed. `git diff --check` passed.
- Initial migration SHA-256 remains `9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567`.
- Cleaned up temporary container and anonymous volume; 3 unrelated containers preserved.
## English Live document MVP baseline - 2026-10-07
Scope/contracts now use revision 1.3. Start with delivery plan Sections 2/3/8/9
and implementation guide work packages WP1-WP6. The first implementation work
continues the existing embedding pipeline into a fenced worker while provider
audio/tool proof is checked early. There is no wholesale LangChain refactor.
API inventory explicitly labels current/deferred routes. D06/D07 add exact
retained review, authenticated preview, factual FAQ inclusion and decision replay.
Database design keeps the applied foundation and proposes forward review state,
identity, owned voice contexts/sessions and voice-only tool_calls. Deferred text
tables are not a voice dependency.
The English scenarios replace the Persian report as the current reading route.
All four examples and unseen new supported uploads are required; corpus size and
capacity are unknown and bounded by declared deployment choices. Retained output
review/resume, real provider/Persian quality, quotas/network and release timing
remain implementation/release gates.
This documentation update changes no application code, migrations, embedding
profile or indexed content. Preserve historical setup/reference test evidence;
it is not evidence that the current worker/review/Live integrations have passed.
## Phase 5 worker orchestration and atomic publication (2026-10-07)
The requested worker/publication scope is implemented in [worker CLI](../app/worker.py),
[application orchestration](../app/modules/documents/worker.py) and
[fenced PostgreSQL persistence](../app/infrastructure/worker_repository.py).
[Forward revision](../migrations/versions/0002_worker_artifact.py) adds
extraction_state.complete_artifact; the applied foundation revision is unchanged.
[Operations guide](guides/worker-orchestration.md) documents continuous/once polling,
frozen-profile dispatch, heartbeats, claim fencing, artifact validation/reuse,
atomic publication, uncertain commit recovery, retry and report-only inventory.
Executed acceptance:
- Provider-free full suite: **1004 passed, 3 skipped, 160 deselected**. The three
existing skips concern Windows symlink privileges; no real providers were called.
- Full PostgreSQL suite: **160 passed, 1003 deselected**, zero failures/errors/skips.
Final artifact-pointer guard rerun: **43 worker database tests passed**.
- Dedicated rag_phase5_test in container rag-phase5-20261007, localhost:54933,
PostgreSQL **16.15**, pgvector **0.8.7**. Tests use disposable schemas;
inspection found zero leftover disposable schemas and zero public tables.
- Dependency check and tracked diff whitespace check passed. Separate Python AST
and whitespace inspection covered the new worker/migration/tests and updated
ingestion/storage/import files.
- Initial migration SHA-256 remains
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
This is database/worker acceptance, not real-provider or complete Live MVP evidence.
Partial review-candidate retention, D06/D07 decisions/resume and factual inclusion
remain separate implementation work. Existing review/FAQ gates remain enabled;
review-required attempts fail terminally without publication or automatic retry.
## Extended Phase 5 backend repair acceptance (2026-10-07)
Implemented durable partial review retention, current-claim attachment and progress,
failed ownership release, trusted administrator read/preview/decide services,
evidence-bound atomic audit decisions/replay, exact approved-output restart/resume,
and whole-group factual authority/inclusion. Worker staging and publication use
one validated preparation boundary. Standalone extraction/chunking protections,
immutable complete artifacts, original files, atomic publication and ambiguous
commit recovery remain enabled. Vision now constructs lazily from frozen profile
identity/policy with independently checked current server credentials. Operational
poll/heartbeat/lease/retry durations reject runtime/SQL-unrepresentable values.
Affected application sources: app/worker.py; modules/documents/{worker,extraction,
chunking,settings,review,operational_limits}.py; infrastructure/{database,
worker_repository,extraction_candidates,review_candidates,review_repository}.py.
New forward migration: migrations/versions/0003_extraction_review.py. Tests:
unit/test_phase5_review.py, integration/test_phase5.py and unit/test_imports.py.
Current README, worker guide, plan and reference-map inventory describe these changes.
Exact final checks:
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
**1050 passed, 3 skipped, 186 deselected**. Skips are existing Windows symlink
privilege cases. No real providers were called.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
**186 passed, 1053 deselected**, no failures/errors/skips. This includes all
**69 worker/review database cases**, compared with the previous 43 worker cases.
- Dedicated container rag-phase5-review-20261007; database rag_phase5_review_test;
localhost:54934; PostgreSQL **16.15**, pgvector **0.8.7**. Only disposable test
schemas were migrated/written. No production database was migrated or modified.
- .venv/Scripts/python -m pip check: no broken requirements.
- git diff --check and separate AST/whitespace checks for all 16 affected Python
files passed. Applied revision 0001 SHA-256 remains
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567;
applied revision 0002 SHA-256 remains
0BFFBA5014A136E3FD251DB8870395FAA056A6277B317506CCF91812C6748ECE.
D06/D07 HTTP transport and authenticated preview still depend on the absent
administrator/session/organization/Origin/CSRF boundary. No unsafe route trusting
a request administrator ID was introduced. Full extended Phase 5 is **not complete**
until that integration exists. Real providers, Persian OCR quality, semantic factual
authority, browser integration and Live release acceptance were not validated.
## Phase 5 governing context, review annotations and attachment replay repair
The [repair regressions](../tests/unit/test_phase5_repairs.py), expanded real
[worker database tests](../tests/integration/test_phase5.py), and
[operations guide](guides/worker-orchestration.md) record the three reproduced
backend repairs: deterministic governing context before FAQ inclusion, bounded
review metadata separate from machine warnings, and fenced identical complete
attachment replay. Immutable legacy review candidates remain compatible.
Verified checks for this repair:
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
**1064 passed, 3 skipped, 196 deselected** (52.49 seconds).
The three existing skips are Windows symlink privilege checks.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
**196 passed, 1067 deselected**, zero failures/errors/skips (128.54 seconds).
Includes 79 worker/review cases and 10 new database regressions.
- Dedicated rag-phase5-context-20261007 container, rag_phase5_context_test
database on 127.0.0.1:54935; PostgreSQL 16.15 / pgvector 0.8.7.
Only disposable isolated test schemas were written; no production DB access.
- pip check, git diff --check, and AST/whitespace checks of the nine affected
Python files passed. No broken requirements.
- All three applied migrations and unrelated baseline files remain unchanged.
Affected sources: app/modules/documents/{chunking,extraction,review,types}.py;
app/infrastructure/{review_candidates,review_repository,worker_repository}.py;
tests/unit/test_phase5_repairs.py and tests/integration/test_phase5.py.
The workflow/API/database contracts and operations/reference/plan docs describe
the context-preserving review/preparation boundary and metadata distinction.
No real providers, Persian OCR quality, HTTP/browser or Live acceptance was run.
D06/D07 transport still requires trusted admin/session/organization, Origin and
CSRF integration and remains outside this repair.
## Phase 6 integration validation and operator handoff (2026-10-07)
[Operator handoff](guides/ingestion-operator-handoff.md) consolidates setup, head
migration, bootstrap, import/status/retry, once/continuous worker and report-only
reconciliation commands. [End-to-end tests](../tests/integration/test_phase6.py)
use disposable PostgreSQL schemas, temporary originals/extractions, real Markdown/
DOCX extraction and [deterministic embeddings](../tests/support/embedding.py).
They observe incomplete batches, exact atomic publication and crash/retry/deletion
boundaries. Existing Phase 5 tests remain the lock/race/review acceptance boundary.
[Worker](../app/modules/documents/worker.py) reports redacted document/job IDs,
stages, heartbeat renewal and error categories; [CLI](../app/worker.py) emits
JSON diagnostics on stderr. [Opt-in smoke](../app/ingestion_smoke.py) requires
explicit corpus files, --allow-provider-calls and provider environment settings;
it runs outside pytest and reports provider compatibility separately from
extraction checks/manual semantic quality. [Provider-free tests](../tests/unit/test_phase6.py)
verify opt-in enforcement, configuration gates, report separation and redaction.
The existing chat retriever still uses Chroma/FastEmbed. Scoped pgvector search
and authorized knowledge selection are the next milestone. No uploaded-document
search, activation, HTTP authentication, Live acceptance, real-provider/Persian
quality proof or schema migration is introduced by Phase 6.
## Executed Phase 6 acceptance (2026-10-07)
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
**1076 passed, 3 skipped, 204 deselected**. The three skips are existing
Windows symlink-privilege checks. No real providers were called.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
**204 passed, 1077 deselected**, no failures/errors/skips.
- Final worker/publication rerun:
.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py -q --require-postgres --tb=short:
**87 passed**. This verifies the final exact row/source assertions and reporting
changes after the full database run.
- Isolated container rag-phase6-20261007, database rag_phase6_test,
127.0.0.1:54936; prerequisite command passed on PostgreSQL **16.15** /
pgvector **0.8.7**. Only disposable test schemas were migrated/written.
- pip check passed. git diff --check passed; separate AST/whitespace checks
covered all seven affected Python files and the new handoff guide, whose local
links passed. Inherited README whitespace was preserved.
- Applied 0001/0002 SHA-256 values remain
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567 and
0BFFBA5014A136E3FD251DB8870395FAA056A6277B317506CCF91812C6748ECE.
No migration was changed.
- Post-test inspection found zero leftover disposable schemas and zero public
tables. The verified Phase 6 container and its anonymous volume were removed;
the three pre-existing containers were preserved.
Real-provider smoke, production model/tokenizer compatibility, Persian
extraction/semantic quality, HTTP/browser and Live acceptance were not run.
The separate opt-in command is available; successful deterministic/database
acceptance does not certify those gates.
## Phase 6 findings repair acceptance (2026-10-07)
The current repair changes app/ingestion_smoke.py, tests/unit/test_phase6.py and
tests/integration/test_phase6.py, plus current status/operator documentation.
Production publication code, all applied migrations, immutable originals,
frozen profiles and unrelated mixed working-tree changes are unchanged.
The harmless compatibility probe uses a bounded set of one-byte ASCII candidates
and measures the actual frozen input/batch policy with the compatible token
counter. Restrictive byte/token policies and one-input batches now succeed;
the one-byte regression reaches the hosted adapter's fake HTTP request boundary.
Local probe/counter/staging failures are reported as not_run/probe_validation_failed,
separately from adapter/provider failures and invalid returned vectors. No real
provider is contacted by any ordinary test.
Independent literal Markdown/DOCX evidence expects exactly three rows and their
original paragraph locators. Exact text, ordinals, vector correspondence, profile,
ready/succeeded state and inactivity are checked together. Critical evidence
includes 25 bar, 60 C, 40 liters per minute, 30 days, 15 Nm, conditions, negation
and exceptions. A shared-chunker 25-to-26 bar mutation is detected for both formats,
even though implementation-derived expected and actual drafts otherwise agree.
The originals are not changed by this mutation test.
Deterministic event barriers pause production publication after all chunk
inserts and after both completion updates, before commit. An independent
PostgreSQL connection observes rows/count and document/job state in one SQL
snapshot at both barriers: zero visible rows and no ready/succeeded state.
After commit the entire expected publication is visible in one snapshot.
All event/future waits are bounded; cleanup releases both barriers and removes
the listener. There are no sleep-based assertions in the new visibility tests.
The existing Phase 5 rollback, claim/lease fencing and ambiguous-commit coverage
still passes; no production publication defect was exposed.
Reproduction before fixes:
~~~powershell
.venv/Scripts/python -m pytest tests/unit/test_phase6.py -k "restrictive or one_byte or local_probe or bad_provider_vectors" -q --tb=short
# 9 failed, 12 deselected: restrictive-policy rejection and insufficient error categories.
.venv/Scripts/python -m pytest tests/integration/test_phase6.py -k shared_chunker -q --require-postgres --tb=short
# 2 failed, 10 deselected: the shared-chunker numeric mutation was not detected.
~~~
Final executed checks from the repository root:
~~~powershell
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:repair-test-only@127.0.0.1:54937/rag_phase6_repair_test"
.venv/Scripts/python -m pytest tests/unit/test_phase6.py tests/integration/test_phase6.py -q --require-postgres --tb=short
# 34 passed.
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
# 1086 passed, 3 skipped, 208 deselected.
.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py -q --require-postgres --tb=short
# 91 passed.
.venv/Scripts/python -m tests.postgres_prerequisites
# Passed: PostgreSQL 16.15, pgvector 0.8.7.
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
# 208 passed, 1089 deselected; no failures/errors/skips.
.venv/Scripts/python -m pip check
# No broken requirements found.
git diff --check
# Passed (existing LF/CRLF notices only).
~~~
The three ordinary-suite skips are existing Windows symlink-privilege checks.
Database acceptance used only the fresh rag-phase6-repair-20261007 container and
rag_phase6_repair_test database, disposable scoped schemas and temporary file
directories. Missing PostgreSQL configuration is not acceptance. Separate
Python AST/whitespace and documentation local-link checks covered affected
untracked files. Baseline SHA-256 comparisons confirm preservation of unrelated
files and applied migrations; publication code was not changed.
Earlier exact validation records above remain historical evidence. Phase 5
worker/review/resume backend services and Phase 6 validation/handoff are
implemented. Authenticated D06/D07 transport still requires trusted
identity/organization/Origin/CSRF integration. Chroma still serves existing chat;
scoped pgvector search and authorized selection are next. Real-provider smoke,
funded production model/tokenizer compatibility, Persian extraction/semantic
quality, browser integration and Live acceptance were not run or certified.
Repair cleanup: inspection found zero leftover disposable schemas and zero public
tables. Only the verified rag-phase6-repair-20261007 container and its anonymous
volume were removed; all three pre-existing containers were preserved.
Affected repair files (all other baseline files are unchanged):
- app/ingestion_smoke.py
- docs/README.md
- docs/agent-reference-map.md
- docs/guides/ingestion-foundation-setup.md
- docs/guides/ingestion-operator-handoff.md
- docs/plans/ingestion-pipeline-plan.md
- docs/plans/live-document-mvp-todo.md
- docs/specifications/RAG-AI-Phase1-Delivery-Plan.md
- docs/specifications/RAG-Phase1-Database-Design.md
- docs/specifications/RAG-Phase1-Implementation-Guide.md
- tests/integration/test_phase6.py
- tests/unit/test_phase6.py
## Fast-Track Search Phase 1 first-result checkpoint (2026-10-07)
Current inventory supersedes historical statements that scoped search and
selection are still entirely absent. [Shared selection/search core](../app/modules/knowledge/service.py),
[selection CLI](../app/knowledge.py), [inspection CLI](../app/search.py),
[targeted PostgreSQL tests](../tests/integration/test_scoped_search.py),
[input/CLI tests](../tests/unit/test_scoped_search.py), and
[provider-free demonstration](../tests/search_demo.py) now exist.
See the [operator checkpoint guide](guides/scoped-search-checkpoint.md)
for setup, commands, exact observed source IDs/text and limitations.
Implemented: persisted enabled actor/organization resolution; full-set selection
with expected knowledge revision, settings-first document locks in UUID order,
no-op counter preservation, knowledge revision increments, removal epochs and
atomic change audit; compatible bounded one-input query embeddings outside
transactions; exact pgvector cosine eligibility joins; actor/epoch revalidation;
whole-chunk diagnostic results (five chunks, 12000 text characters).
No migration, dependency, prototype retriever, HTTP search or framework was added.
The inspection format is uncalibrated_candidates, not the model-tool contract.
Actual checks:
- PostgreSQL prerequisite probe passed: PostgreSQL 16.15 / pgvector 0.8.7 in a
fresh dedicated container/database on 127.0.0.1:54938.
- `.venv/Scripts/python -m pytest tests/unit/test_scoped_search.py tests/integration/test_scoped_search.py --require-postgres -q --tb=short`:
**37 passed** (14 unit, 23 PostgreSQL), zero skips, 28.46 seconds.
- `.venv/Scripts/python -m tests.search_demo` with isolated TEST_DATABASE_URL:
inactive=0 candidates; after legitimate selection revision=2/epoch=1,
one faithful pump-limit candidate with document/chunk IDs and actual locator.
- Selection/search CLI help verified; tracked and new-file whitespace passed;
all applied migration files compared byte-for-byte with HEAD and preserved.
The available operator URL was rejected by the isolated-test guard because its
database name was not suffixed _test; it was not used for test writes.
The deployment ingestion database connection failed with OperationalError.
Credentials/configuration were present but no hosted call was attempted;
approved ready real-document/provider demonstration remains pending a reachable
compatible ingestion database. This is provider-free database validation, not
semantic-quality acceptance. Full regressions/calibration/LangChain/UI/Live/ANN
were not run or built; Fast-Track phases 2-4 remain pending.
## Fast-Track Search Phase 2 technical acceptance (2026-10-08)
Current inventory supersedes the Phase 1 checkpoint's pending exact-matching and
canonical-outcome statements. [Shared core](../app/modules/knowledge/service.py)
now uses [comparison-only lexical normalization](../app/modules/knowledge/lexical.py),
[bounded merge/admission and execution references](../app/modules/knowledge/evidence.py),
[cutoff selection](../app/modules/knowledge/calibration.py) and an
[opt-in calibration CLI](../app/calibrate_search.py). The existing inspection CLI,
selection service, embedding preprocessing/provider adapter, publication path,
dependencies and all applied migrations remain preserved.
See [Phase 2 operator guide](guides/scoped-search-phase2.md) for the actual
commands, boundaries, [ten independent annotations](calibration/phase2-cases.json),
[original fixture](../data/calibration/phase2-source.md) and
[pending real-model status](calibration/phase2-status.json).
Exact candidates cannot bypass calibrated admission. Canonical search refuses
an absent measured cutoff rather than inventing a universal threshold.
One SearchExecution pins actor/access epoch across calls and owns stable S
references. Remote embedding work holds no database connection. Every matching
branch applies all eligibility predicates before ranking/limits.
Actual checks, with no real providers:
- Affected [unit](../tests/unit/test_search_phase2.py) and
[PostgreSQL](../tests/integration/test_search_phase2.py) tests plus the Phase 1
scoped-search tests: **93 passed** (35 unit / 58 PostgreSQL), zero skips.
- Full provider-free suite: **1121 passed, 3 skipped, 266 deselected**.
Existing Windows symlink privilege cases account for the skips.
- Affected ingestion/publication PostgreSQL suites (test_phase5/test_phase6):
**91 passed**, zero skips.
- PostgreSQL **16.15** / pgvector **0.8.7**, existing isolated
rag-scoped-search-20261007 container, rag_scoped_search_test database,
127.0.0.1:54938. Only disposable schemas were written.
- Dependency check, inspection/calibration CLI help, tracked diff and separate
AST/new-file whitespace/local-link inspection passed. All three migration
files compare byte-for-byte with HEAD.
Bounded provider barriers prove removal and actor disablement suppress results.
Real Markdown/DOCX ingestion-to-search tests assert independent literal numbers,
conditions, negation, exceptions and actual locators. Publication barriers and
a failed final batch remain invisible/unselectable/unsearchable. Calibration
runner/bindings, actual ten-call bounds, complete-group coverage, zero unsupported
false positives and stricter-cutoff tie selection are covered provider-free.
Phase 2 technical implementation is complete; its real-model calibration gate
is **pending**. No provider-call authorization or approved original/document
bindings were available. The configured Ollama bge-m3 / 1024 / v1 profile was
observed without invoking it. No cutoff or semantic-quality certification is
claimed. Phases 3/4, LangChain, full PostgreSQL regression and held-out quality
acceptance remain separate.
## Current Phase 2 repair acceptance (2026-10-08)
[Repair report](guides/scoped-search-phase2-repairs.md) supersedes the earlier
Phase 2 counts for current acceptance. Canonical service handoff now guards
admission and staged reference allocation at transaction commit; provider work
remains outside transactions. Terminal punctuation exact matching, retained
calibration finalization failures and explicit SQL retryability are repaired.
[Unit regressions](../tests/unit/test_search_phase2_repairs.py) and
[PostgreSQL regressions](../tests/integration/test_search_phase2_repairs.py) include
bounded candidate/admission barriers and exact recovery beyond 50 semantic rows.
Actual results: 75 affected unit tests; 97 affected isolated PostgreSQL tests
with --require-postgres, zero skips; 1161 provider-free tests, three existing
Windows symlink skips and 305 deselected. pip check, both CLI help commands,
whitespace/new-file checks and migration byte-preservation passed. Unrelated
changes were preserved. No real provider calls or production cutoff: approved
bindings, explicit call authorization and real compatibility remain pending.
Future transport delivery and Phases 3/4 are outside this acceptance.
## Current remaining Phase 2 repair acceptance (2026-10-08)
[Current repair report](guides/scoped-search-phase2-repairs.md#remaining-two-repairs-current-acceptance-2026-10-08)
supersedes earlier test counts. Literal frozen-annotation matching rejects
numeric/date/identifier extensions while retaining whole-group and bound-document
checks. Confirmed SQLSTATE-less DBAPI connection invalidation is retryable;
permanent and unknown errors retain safe nonretryable classifications. No
automatic retries were added.
[Unit regressions](../tests/unit/test_search_phase2_remaining.py) and
[real PostgreSQL disconnect regressions](../tests/integration/test_search_phase2_remaining.py)
cover candidate retrieval, canonical handoff and retained calibration failure
reports. Actual acceptance: 107 affected unit tests; 100 affected PostgreSQL
tests with --require-postgres and zero skips; 1193 provider-free tests, three
existing symlink skips and 308 deselected. pip check, CLI help, whitespace,
AST/local links, migration byte comparisons and unrelated/frozen baseline
preservation passed. The four earlier repairs and Phase 1 inspection path remain
intact. No real model calls or production cutoff; calibration prerequisites
and Phases 3/4 remain pending.
## Fast-Track Search Phase 3 technical acceptance (2026-10-08)
[Lazy LangChain adapter](../app/modules/knowledge/langchain_tool.py) delegates
directly to the canonical Phase 2 service. The dedicated `search` extra declares
only `langchain-core>=1,<2`; actual acceptance installed 1.6.7.
[Operator guide](guides/scoped-search-phase3.md) records schema, trusted context,
invocation, cancellation/deadline semantics and exact executed commands.
Only query and optional context are model inputs, using the existing strict
SearchInput schema. ToolContext captures backend-owned execution/reference
state, absolute monotonic deadline and cancellation; persisted actor/epoch
capture/revalidation runs in the worker, outside model input. One shared runner
allows four running/eight waiting calls with a 75-second total deadline.
Queue waiting consumes the deadline; async waiting uses no executor thread.
Running work holds its slot until actual completion after timeout/cancellation.
Saturation/deadline/cancellation remain canonical technical errors.
No new retrieval, provider pipeline, text agent, Live dispatch or schema
migration was introduced; the diagnostic CLI remains uncalibrated.
Executed checks:
- Search extra installation and pip check passed.
- [41 new unit tests](../tests/unit/test_search_phase3.py) plus affected search
unit regressions: **148 passed**, zero skips.
- [Three new PostgreSQL tests](../tests/integration/test_search_phase3.py) plus
affected scoped/Phase 2/repair acceptance: **103 passed**, zero skips,
with --require-postgres.
- Fresh isolated rag-search-phase3-20261008 container, rag_phase3_test database,
127.0.0.1:54939; prerequisite probe: PostgreSQL **16.15**, pgvector **0.8.7**.
Only disposable test schemas were written.
- Sync/async actual StructuredTool invocation produced the same faithful pump
evidence/document/chunk/locator and stable S1 as the shared canonical service;
inspection candidate identities agreed. Foreign hints granted no scope;
persisted selection removal revoked subsequent pinned-execution calls.
- Event-loop responsiveness, default four/eight saturation, queued/running
timeout/cancellation, retained running slots, strict forged/unknown fields,
canonical results and framework-blocked fresh-process lazy imports passed.
- Tracked diff, new-file AST/whitespace, local guide links and applied-migration
byte-preservation checks passed; unrelated work was preserved.
No real providers were called. Phase 3 technical integration is complete.
Phase 2 real-model calibration and Phase 4 frozen Persian held-out quality
acceptance remain pending approved bindings/access/explicit call authorization.
Full provider-free and mandatory isolated PostgreSQL regression acceptance
remains part of the final Phase 4 checkpoint, not a Phase 3 readiness claim.
## Phase 3 runner shutdown repair acceptance (2026-10-08)
This checkpoint supersedes the initial Phase 3 shutdown behavior only.
[Runner](../app/modules/knowledge/langchain_tool.py) now recognizes permanent
closure in stop checks and after rejected admissions, returning existing
canonical SEARCH_CANCELLED with empty sources and retryable:false.
[Operator guide](guides/scoped-search-phase3.md#shutdown-repair-acceptance-2026-10-08)
documents shutdown priority, races and the blocking close lifecycle.
Closure/admission/submission share a condition lock. Closure prevents queued
submission; already submitted work owns its running/admission slots until the
actual completion callback releases them. Queued callers promptly cancel and
release their own admissions once. After executor join, close waits for queued
admissions to drain; it returns with active/admitted zero and is safe to repeat,
including concurrently. A submitted worker observing closure before I/O starts
performs no provider/database work. Previously delivered results cannot be
recalled; final delivery checks suppress results when closure wins.
Call blocking close from a control thread outside active event loops and this
runner's worker pool, keeping queued callers schedulable until they drain.
[Fourteen event-barrier regressions](../tests/unit/test_search_phase3_shutdown.py)
cover sync/async queued shutdown, post-close/expired invocations, concurrent
repeat close, admission/submission and completion/callback races, exact releases,
no queued I/O and retention of actual running work. All waits are bounded;
there are no sleep-based ordering assertions in the new tests.
Actual checks:
- Before repair, six selected reproduction cases failed (six deselected in
the initial test set): queued calls stayed pending and closed calls returned
SEARCH_SATURATED/SEARCH_TIMEOUT.
- Actual LangChain tests with installed declared extra (1.6.7): **55 passed**,
zero skips. Existing cancellation/deadline/lazy import/schema/delegation
acceptance remains intact.
- Affected search unit regressions: **162 passed**, zero skips.
- Affected search PostgreSQL acceptance with --require-postgres:
**103 passed**, zero skips.
- Fresh rag-phase3-shutdown-20261008 container, rag_shutdown_test database,
127.0.0.1:54939; prerequisite probe passed PostgreSQL **16.15** /
pgvector **0.8.7**. Only disposable schemas were written.
- pip check, tracked/new-file whitespace, AST, local documentation links and
byte-for-byte comparison of all applied migrations passed.
- Unrelated changes were left untouched. Baseline comparison observed a
concurrent change to scripts/live_voice_server.py; this repair did not edit it.
Only runner shutdown, its new unit tests, the operator guide, this reference
record and the plan were changed by the repair. No real providers, calibration,
Phase 4, Live or HTTP work was performed. Blocking shutdown still waits for
actual blocking work and needs active queued caller loops to progress.
Full repository regressions and real-model/held-out quality gates remain
separate unrun acceptance.
Shutdown test cleanup: zero disposable schemas and zero public tables remained.
The verified rag-phase3-shutdown-20261008 container and its anonymous volume
were removed; all pre-existing containers were preserved.
## Historical Fast-Track Search Phase 4 preparatory acceptance (2026-10-08)
[Phase 4 operator guide](guides/scoped-search-phase4.md) and
[status](calibration/phase4-status.json) retain the historical preparatory technical
regressions: 1258 provider-free tests passed, three existing Windows symlink
skips, and 311 isolated PostgreSQL tests passed with --require-postgres and zero
skips. The fresh rag-phase4-acceptance-20261008 container used rag_phase4_test on
127.0.0.1:54940, PostgreSQL 16.15 / pgvector 0.8.7. No deployment database writes.
pip check, tracked/new-file whitespace, AST/JSON and byte-preservation of all
three applied migrations passed.
[Draft independent annotations](calibration/phase4-cases.draft.json) cover both
original PDFs, the visually inspected infographic and factual DOCX candidates:
16 answerable, six unsupported, and four unseen slots without invented evidence.
Approval, DOCX human inclusion and actual hash/document bindings are pending.
The [opt-in evaluator](../tests/evaluate_search.py) is outside pytest and
delegates to the existing canonical service with a measured Phase 2 cutoff,
bounded calls, checked bindings/sources, flushed per-case records and the exact
18/20 + all-critical + 6/6-unsupported gate.
[Ten deterministic regressions](../tests/unit/test_search_phase4_gate.py) test
scoring/preflight/budget safety only; they do not establish model quality.
Real evaluation: zero cases, zero provider calls. The local Phase 2 cutoff is
still null; funded-profile approval, explicit call opt-in/budget, unseen
originals, required human review and actual eligible bindings are unavailable.
Quality acceptance remains not run. No production defects were silently fixed.
No retrieval, generated-answer or Live readiness is certified.
Cleanup confirmed zero disposable schemas and zero public tables. The created
Phase 4 test container and its anonymous volume were removed; existing containers
were preserved. Temporary original-page renderings were removed. Baseline
comparison found a concurrent change to scripts/live_voice_server.py, which this
evaluation did not edit. All other unrelated baseline files were unchanged.
## Current Phase 4 annotation/independence repair checks (2026-10-08)
[Repair guide](guides/scoped-search-phase4.md) and
[current status](calibration/phase4-status.json) supersede the preparatory
checkpoint for current repair validation. All 22 populated draft annotations
(16 answerable / six unsupported) were reconstructed from actual originals,
persisted as UTF-8, strictly read back and synchronized with status expected
records. Zero unresolved annotations. Hashes, approvals, null bindings and four
empty unseen slots remain unchanged.
[Evaluator](../tests/evaluate_search.py) now checks question separation using
[comparison-only validation](../tests/phase4_gate.py) against the supplied full
Phase 2 calibration annotations before settings/database/provider setup.
Missing/malformed annotations and exact/Unicode-formatting-equivalent overlap
fail closed with safe actionable diagnostics. Different questions may share
documents; evidence literals/retrieval preprocessing and all gate thresholds
remain unchanged.
[Repair regressions](../tests/unit/test_search_phase4_repairs.py) include original
DOCX literal/source checks, persisted corruption detection, legitimate punctuation,
exact/equivalent overlaps, distinct shared-source questions and setup barriers.
Executed: **52 targeted passed**, zero skips; **1300 provider-free passed**,
three existing Windows symlink skips, 311 deselected; pip check, whitespace,
AST/JSON, UTF-8 read-back and all three applied migration comparisons passed.
Mandatory isolated PostgreSQL **not run** because TEST_DATABASE_URL is absent;
previous database acceptance remains historical. No providers were run.
Phase 4 quality acceptance is still not_run. Measured cutoff, approved funded
profile/call budget, approved original/FAQ decisions, actual eligible bindings
and four unseen annotations remain pending. No retrieval, generated-answer or
Live readiness is claimed.
Final preservation inspection observed a change to scripts/live_voice_server.py
outside this repair. It was left untouched; all other unrelated baseline files
were unchanged. All three applied migrations match HEAD byte-for-byte. Local
documentation links and new-file inspection passed. Existing intentional Markdown
hard breaks were preserved. Temporary original-image inspection files were removed.
## OpenAI Realtime Phase 0 (2026-10-08)
Voice provider selection now follows the [Realtime MVP plan](plans/realtime-agent-mvp-plan.md); the scoped [Phase 0 report](guides/realtime-agent-phase0.md) records the frozen application contract, configuration and calibration prerequisites. Historical component/provider records above remain historical. Proof is isolated/hardcoded; canonical search and LangChain adapter are reused, not rebuilt. Runtime, real calibration and voice acceptance remain pending.
Phase 0 executed: 162 targeted provider-free search/calibration/LangChain tests passed, zero skips; CLI help and tracked whitespace checks passed. Persisted-profile connection probe failed (OperationalError); real providers and PostgreSQL acceptance were not run. Concurrent untracked scripts/mock_stream_server.py was preserved. See the report for remaining calibration prerequisites.
Phase 0 documentation repair (2026-10-08) supersedes incomplete progress/bounds preparation: API 7.1.1-7.1.4 defines reference lifecycle, floor/sample coordinates, final reports, acknowledged cleanup barrier, frame/queue caps and six walkthroughs. Report includes official model/transcription retirement and executable read-only profile/binding preflight. Earlier 162-test results were not rerun; this repair makes no provider, runtime, quality or PostgreSQL acceptance claim. Verification results are recorded in the repair report.
Repair checks: six CLI help commands and six PowerShell example parses passed; local original hash, Python example AST, UTF-8/local links/whitespace and proof/migration/frozen-input preservation passed. Eight documentation files changed; 168 other baseline files unchanged, with a concurrent external mock-server edit observed and preserved separately. No pytest/database/provider/runtime checks run for this documentation repair. Exact commands/results are in the Phase 0 report.
Remaining-four-findings Phase 0 repair (2026-10-08): API 7.1.5 separates bounded generated backlog from paced transport/playback, and 7.1.6 governs delayed user ASR, normal completion and committed current-turn release/supersession. API 7.1.2 selects backend cancellation ownership with both VAD flags false and narrowly correlated no-active-response races. Plan Phase 1/2 prompts and current guide/report/progress align; twelve walkthroughs are documented. Official-source verification is separate from unrun provider/runtime/database acceptance; exact checks are recorded in the latest Phase 0 report checkpoint. CALIBRATION_REQUIRED remains closed.
Latest four-findings repair checks: Git whitespace, strict UTF-8/local links, two Python AST parses and six PowerShell syntax parses passed. Eight documents changed; 169 other repair-start files are byte-identical, including the proof, existing mock-server changes, migrations and frozen calibration records. Recorded original hash verified. No CLI help commands, database/provider workflows or runtime tests were run in this repair; embedded examples were parsed only. See the latest report checkpoint for exact boundaries.
Playback-stall/cleanup timeout repair (2026-10-08): API 7.1.1/7.1.2/7.1.5 excludes finalizing/interrupted/retired refs from stall detection, atomically invalidates timer identities at cleanup ownership, rechecks queued callbacks, and initializes each eligible interval independently. Retirement releases credit once without changing evidence or bypassing response gates. Four additional walkthroughs (sixteen total), plan/guide/config summaries align; documentation-only checks and unchanged external gates are recorded in the latest Phase 0 report. CALIBRATION_REQUIRED remains.
Timeout-repair checks passed: tracked whitespace, strict UTF-8/local links, two Python AST parses, 39 JSON examples, six PowerShell syntax parses and manual timer/credit/barrier consistency. Eight documents changed; 169 other baseline files unchanged, including proof/mock scripts, applied migrations and frozen calibration inputs. Original hash verified. No database/provider/runtime workflows or tests were run; exact outcomes are in the latest report checkpoint.
## OpenAI Realtime Phase 1 runtime checkpoint (2026-10-08)
[Operator/runtime guide](guides/realtime-agent-phase1.md) documents the private
[Realtime adapter](../app/infrastructure/realtime.py),
[voice runtime](../app/modules/voice/runtime.py),
[operator command](../app/voice_smoke.py) and
[fake-provider regressions](../tests/unit/test_realtime_phase1.py).
The voice optional extra in pyproject.toml uses LangChain core and websockets;
no new agent framework, retrieval implementation, API route or migration is added.
Runtime receives setup acknowledgement with both VAD auto-response/cancel flags
false. Backend SearchExecution/reference state is shared per voice turn, with
actual StructuredTool async dispatch through one caller-owned SearchToolRunner.
Persisted authority checks, retrieval and socket sends remain off serialized
provider reception. Input-item/response/output-item/call/intent correlation,
strict query/context validation, canonical result serialization, terminal
call-set verification and once-only continuations are session-local and bounded.
Client tool references are backend-generated; private provider IDs appear only
in the operator diagnostic correlation report.
Generated reservoir, paced progress credits, successful-send accounting, eligible
stall timer identities, final-progress/terminal/truncation deadlines, acknowledged
retirement and latest committed-turn release gates implement API 7.1.2/7.1.5/7.1.6.
Normal tails preserve completion; delayed authorized user ASR keeps its original
turn; superseded assistant/tool work is suppressed. The narrowly correlated
no-active race classifier fails closed by default pending selected-profile proof.
Actual checks:
- 59 new voice regressions plus actual LangChain/runner/shutdown checks:
114 passed, zero skips, via .venv/Scripts/python -m pytest
tests/unit/test_realtime_phase1.py tests/unit/test_search_phase3.py
tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider.
- Final .venv/Scripts/python -m pytest -m "not postgres" -p no:cacheprovider -q:
1359 passed, three existing Windows symlink skips, 311 PostgreSQL deselected.
- One preceding full run failed inside its nested environment rerun in the
unchanged test_running_timeout_retains_slot_and_suppresses_late_result[False].
Selecting that existing 50 ms case alone also failed before worker entry:
its deadline includes cold LangChain import/tool construction. The entire
unchanged test_search_phase3.py file reran with 41 passed; final full rerun
passed. Neither the runner nor this existing test was changed. This timing
sensitivity is reported rather than silently widening its deadline.
- CLI help, pip check, AST/manifest parsing, tracked and new-file whitespace,
guide links and proof/all applied migration byte comparison against HEAD passed.
- Actual fake-wire operator smoke used the canonical service/StructuredTool:
provider call real-fake-c belongs to real-fake-r1, output matches its call ID;
continuation real-fake-r2 supplies the final transcript. Fixture evidence
retains document UUID(int=100), chunk UUID(int=1) and S1. Empty fixture evidence
remains no_evidence; technical results remain distinct canonical errors.
No fixture identity is presented as a production corpus identity.
No real provider calls were authorized or executed; no measured calibrated
approved actor/corpus bindings were supplied. TEST_DATABASE_URL is absent:
isolated PostgreSQL acceptance was not run and deselection is not DB evidence.
No real Persian speech/browser playback or Phase 1 grounded-provider exit
criterion is claimed. Harness playback is explicitly unverified and never
fabricates progress. Selected-model acknowledgements/cancellation classification,
real truncation/layouts, transport send/playback behavior, allocator/global
capacity and Phase 2 identity/durable lifecycle remain separate acceptance.
The original proof, existing mock script, applied migrations, frozen calibration
inputs and unrelated working-tree changes were not edited by this task.
## OpenAI Realtime Phase 1 repair checkpoint (2026-10-08)
The [repaired operator guide](guides/realtime-agent-phase1.md) supersedes the
initial Phase 1 validation totals above. Current inventory adds
[validated runtime settings](../app/modules/voice/settings.py),
[bounded serialization](../app/modules/voice/serialization.py), and
[67 repair regressions](../tests/unit/test_realtime_repairs.py).
Repairs reject new audio after terminal generation while preserving legitimate
delayed transcripts; correlate assistant response/item/output/content identities
and string payloads, including provider-announced items; require healthy current
turn, completed final response, delivered transcript and confirmed matching tool
outputs/continuation chain for smoke success. Input reserves raw queued/in-flight
bytes and counts before encoding and retains forwarded input until correlated
prefix commitment. Output controls reserve encoded bytes/count through send,
preserve entire fields and retain terminal-error capacity.
Serialized event decisions reject expired setup/input/response/cancel/truncate
acknowledgements before ticker execution. Dispatch deadlines start at actual
dispatch with independent queue/send bounds. Cleanup failure keeps the affected
old turn; provider protocol/availability, transport and context-sync failures are
distinct and private IDs never enter client errors. Close is bounded/coalesced,
input/control reservations release once, and cancellation remains backend-owned.
LIVE_ configuration implements the Phase 0 defaults (including 30-second setup)
and rejects inconsistent bounds before provider connection. No model/voice,
ingestion/search, migration, route or framework change was introduced.
Executed repair checks (2026-10-08):
- `.venv/Scripts/python -m pytest tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`: 181 passed (59 existing voice + 67 repair + 55 runner/shutdown), no skips.
- `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: 1426 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `.venv/Scripts/python -m app.voice_smoke --help`: passed; required actor, provider opt-in and bounded seconds/call options remain.
- Seven affected Python AST parses, TOML manifest parse, strict UTF-8/local links, new-file whitespace and `git diff --check`: passed.
- Baseline SHA-256 preservation: only the seven intended existing implementation/test/documentation files changed; the other 176 baseline files remain byte-identical, including proof/mock scripts, applied migrations, original documents, shared search/runner and frozen calibration/evaluation inputs. Three scoped files were added: runtime settings, bounded serialization and repair tests.
The earlier cold-construction 50 ms runner timing failure is recorded in the
reference map's initial checkpoint. This repair did not change that test or
runner; the targeted and full repair runs passed without that timing failure.
These fake-provider results establish state/correlation behavior, including
real-fake-c -> real-fake-r1 -> real-fake-r2 and delivered final transcript,
not real provider/corpus quality or heard audio.
TEST_DATABASE_URL is not configured. No isolated PostgreSQL or real provider
call was executed; no real voice opt-in or approved calibrated actor/corpus
binding was supplied. Selected-model acknowledgement shapes, cancellation-race
classifier, Persian speech, actual truncation/latency, browser progress/transport
fragment admission and allocator/global-session capacity remain unverified.
The classifier and missing calibration remain fail-closed. Blocking search can
retain a shared runner slot until actual completion and make final shutdown
outlast the bounded smoke interaction. Phase 2 endpoints/authentication/durable
lifecycle remain outside this repair.
## Five remaining Phase 1 defects repair (2026-10-08)
The current runtime adds independently bounded/coalesced provider cleanup,
one-to-one function item/call bindings, exact immutable adapter-wire reservations,
common nested call-ID validation and completed zero-sample audio retirement.
[48 new regression cases](../tests/unit/test_realtime_remaining.py) use fake
transport barriers and the actual async StructuredTool/shared runner for dispatch.
See the [operator checkpoint and exact checks](guides/realtime-agent-phase1.md#five-remaining-defects-repair-2026-10-08).
This checkpoint: 229 targeted tests passed; full provider-free suite 1474 passed,
three existing Windows symlink skips and 311 PostgreSQL tests deselected.
Dependency, AST/TOML, whitespace, local-link and baseline preservation checks passed.
Seven intended baseline files changed, 179 stayed byte-identical, one test file
was added; protected files, shared search and the unrelated 50 ms runner test
were preserved. Earlier checkpoint results above remain historical.
No real provider or isolated PostgreSQL acceptance was run; approved actor/corpus,
explicit opt-in, compatible database/profile access and measured calibration remain
required. Existing runtime/real-browser limits in the operator guide still apply.
## Readiness and Unicode Phase 1 repair (2026-10-08)
The runtime now distinguishes private provider configuration acknowledgement from
successful application session_ready delivery; pending readiness admits no client
audio/control payload. Malformed Unicode function arguments receive canonical
INVALID_TOOL_ARGUMENTS with bounded safe hashing and zero retrieval. Provider
framing/correlation remains strict.
See [operator checkpoint and exact checks](guides/realtime-agent-phase1.md#readiness-and-unicode-repair-2026-10-08)
and [52 added regression cases](../tests/unit/test_realtime_remaining.py).
Executed for this checkpoint: 281 targeted voice/runner/shutdown tests passed;
1526 provider-free tests passed, three existing Windows symlink skips and 311
PostgreSQL tests deselected. Dependencies, eight Python AST parses, TOML,
whitespace, local documentation links and preservation checks passed. Seven
intended baseline files changed; 180 remain byte-identical; no files added/removed.
Shared search/runner, protected files and the existing 50 ms runner test remain
unchanged. Earlier results above are historical. Real provider/browser/Persian
speech and isolated PostgreSQL acceptance remain unrun with prerequisites and
fail-closed calibration/cancellation limits recorded in the operator guide.
## Provider replay and user ASR Phase 1 repair (2026-10-08)
Provider replay hashing now streams bounded canonical UTF-8 after depth/scalar/work
validation; actual provider wire-byte admission remains at RealtimeAdapter.receive.
Completed user-ASR is coalesced per mapped input/content index, while conflicting
completions fail and repeated partial text remains incremental.
See [operator behavior, exact checks and failure/rerun record](guides/realtime-agent-phase1.md#provider-replay-and-user-asr-repair-2026-10-08)
and [37 added regressions](../tests/unit/test_realtime_remaining.py).
Final targeted voice/runner/shutdown result: 318 passed. Full provider-free:
1563 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected.
Dependency, eight Python AST parses, TOML, whitespace, documentation-link and
SHA-256 preservation checks passed. Six intended baseline files changed; 181
remain byte-identical; no files added/removed. Shared search/runner, protected
inputs and the unrelated 50 ms runner test remain unchanged. Initial reproduction
and fixture-correction reruns are recorded separately in the guide.
Real provider, browser playback/Persian speech and isolated PostgreSQL acceptance
remain unrun. Existing authorization, actor/corpus/profile/calibration gates and
fail-closed cancellation classification still apply; no Phase 2 work was added.
## Current Phase 2 repair inventory (2026-10-09)
- Deployment configuration: `app/modules/voice/configuration.py`; finite limits
remain in `app/modules/voice/settings.py`.
- Cookie auth and C01/V01-V04/WSS: `app/api/v1/auth.py`, `dependencies.py`,
`conversations.py`, `live.py`; bounded blocking work in
`app/infrastructure/blocking.py`; application lifecycle in `app/main.py`.
- Durable admission/completion: `app/modules/voice/lifecycle.py`,
`durable_tools.py`; post-commit loop notifications in `registry.py`.
- Forward owner-chain repair: `migrations/versions/0005_live_owner_chain.py`.
Revisions 0001-0004 are preserved.
- Gemini adapter: `app/infrastructure/gemini_live.py`; shared canonical search,
StructuredTool and SearchToolRunner are retained.
- Exercised developer audio example: `examples/voice-client.js`,
`examples/voice-audio-worklet.js`; guide linked in the repair report.
- This Linux environment uses `.venv/bin/python`, not the historical Windows
`.venv/Scripts/python`. Existing timeout validation creates a local socket;
sandbox denial must be distinguished from an application validation defect.
Exact executed checks, remaining provider limitations and preservation evidence
are recorded in the [Phase 2 repair report](guides/realtime-agent-phase2-repair.md).
## Remaining Phase 2 defects checkpoint (2026-10-09)
The [current repair record](guides/realtime-agent-phase2-repair.md#remaining-defect-repair-2026-10-09)
supersedes affected initial Phase 2 behavior. Native pending generations retain
their input identity; ambiguous overlapping speech closes safely. Gemini PCM
admission uses packed bounded slabs separately from controls and shares the
runtime aggregate backlog. Durable canonical technical errors coalesce/replay
with fresh eligibility checks. Legacy creation hashes are verified against
persisted payload/configuration before atomic normalization; migrations 0001-0005
remain immutable. The delivered VoiceClient now owns resources by connection
generation, coordinates V04 before transport teardown, and attempts logout
independently of close failure. Partial application startup always cleans up.
Regression sources add `tests/unit/test_phase2_remaining.py` and executable
`tests/support/voice_client_harness.mjs`. Actual client/ASGI/PostgreSQL close
acceptance uses a local transport bridge; Node executes the delivered client and
worklet. Exact results and unrun real-provider/browser prerequisites are in the
repair record. No selected-model multi-turn or frontend readiness claim is made.
## Phase 2 provider selection and transport repair (2026-10-09)
Current locations: [selected provider factory](../app/infrastructure/voice_provider.py),
[voice settings](../app/modules/voice/configuration.py),
[authority classification](../app/modules/voice/authority.py),
[supported single-process server](../app/server.py),
[pre-payload WebSocket parser](../app/infrastructure/voice_websocket.py).
API and operator smoke share construction; unchanged Gemini/OpenAI adapters keep
their separate native capabilities. Browser PCM remains 24 kHz; reservations pin
provider/model/voice/profile and cannot switch on replay/connection. Legacy
PROVIDER/GEMINI_* remain supported; conflicting provider aliases fail. Dedicated
OPENAI_REALTIME_* keys do not change embedding configuration.
See the [current repair checkpoint](guides/realtime-agent-phase2-repair.md#provider-selection-and-transport-repair-2026-10-09)
for finding/fix/test mapping, exact checks and preservation evidence, and the
[frontend guide](guides/frontend-voice-integration-example.md) for configuration,
startup, retained creation attempts, dual playback bounds and the 10-second
uncommitted idle-input limitation. Real loopback tests execute the explicitly
selected installed parser; generic Uvicorn defaults are not supported admission.
Exactly one API process owns media guards; ingestion runs separately. Fake tests
are not real provider/Persian speech/browser hardware or frontend readiness proof.
Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
أ¢â‚¬â€‌ **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
أ¢â‚¬â€‌ **372 passed**, zero skips, using only the isolated task-created test database.
Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the
required prerequisite failure. Executable JS, syntax/compile, diff and baseline
preservation checks passed. See the report for exact durations, failed/interrupted
runs, isolated-database settings and remaining external prerequisites.
## Current Phase 3 HTTP and OCR policy inventory (2026-10-09)
D01-D04/D06 preview/D07, K01/K02 and read-only F01 are now implemented in
[document routes](../app/api/v1/documents.py) and
[knowledge/configuration routes](../app/api/v1/knowledge.py). These use existing
intake/review/worker/selection services, with bounded streaming
[multipart admission](../app/api/v1/uploads.py) and safe scoped
[polling queries](../app/infrastructure/document_queries.py). This supersedes
prior pending-HTTP statements above. The standalone frontend developer handoff is
[Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable
DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet,
Gemini/OpenAI selection, canonical search and migrations 0001أ¢â‚¬â€œ0005 are preserved.
`INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job
profiles; false admits only automatically validated OCR. Legacy profiles retain
mandatory review without rewriting their digests. Non-OCR and factual approval
remain separate. Mixed automatic/inspected PDFs report partially_reviewed;
only actually inspected locators receive human annotations. Publication remains
ready and inactive until K02. F01 reports configured safe policy/capabilities,
while document polling reports the frozen policy and actual retained review state.
The two remaining Phase 2 findings are repaired: cancellation propagates out of
receive-capacity waits, and the parser preserves its native UTF-8 rejection for
durable LIVE_PROTOCOL_ERROR classification even when Uvicorn would report 1006.
See the [Phase 2 checkpoint](guides/realtime-agent-phase2-repair.md) and
[Phase 3 validation record](guides/realtime-agent-phase3-handoff.md) for exact
checks, actual failures/corrections and remaining real-provider/browser prerequisites.
Final Phase 3 checks: **1724 provider-free passed**, two existing Windows path
skips; **162 affected PostgreSQL passed**, zero skips; **323 affected unit passed**;
**22 final HTTP acceptance cases passed** and **2 explicit two-provider redaction
cases passed**. Prior broader PostgreSQL checkpoint: **393 passed**, zero skips;
see the handoff for its timing relative to the final mixed-PDF refinement.
Missing TEST_DATABASE_URL produced the required failure. Compose, Node execution/
syntax, AST/TOML, diff and preservation checks passed. **200 task-start files remain
byte-identical**, 26 intended existing files changed, 11 added, none removed.
The isolated task-owned test container was removed after zero-schema/table checks.
## Four verified Phase 3 findings repair (2026-10-09)
The ingestion regression source `tests/unit/test_phase3_repairs.py` is restored
byte-for-byte from `9be4719` (55 cases). HTTP admission/filename/proxy regressions
now live in `tests/unit/test_phase3_http_repairs.py`. K02 uses the existing bounded
blocking pool; D07's DTO-derived finite body budget is 60,151,072 bytes with
pre-extension capacity checks. D04 nonempty bodies remain 422 VALIDATION_ERROR.
See the [current handoff repair record](guides/realtime-agent-phase3-handoff.md)
for exact finding-to-test mappings, executed results and open validation failures.
Earlier Phase 3 counts above are historical and do not establish restored coverage.
## Phase 3 JSON responsiveness and acceptance follow-up (2026-10-09)
Large D07/K02 JSON handling now uses two admitted requests, 64 KiB cooperative
spooling and local child-process UTF-8/JSON/DTO validation in
`app/infrastructure/json_processing.py`, with bounded result frames and owned
cancellation/cleanup. D07 also bounds retained normalized DTOs to two review
transactions. Existing finite byte budgets and safe error/correlation mappings
remain. `app/modules/knowledge/langchain_tool.py::prepare_search_tools` runs
through the existing blocking pool during API startup, before readiness, to move
observed cold framework loading outside first-tool waits; document-only optional
framework behavior remains supported. No dependency or external service added.
New regressions: `tests/unit/test_json_processing.py` (actual large escaped JSON
responsiveness and lifetime/admission checks),
`tests/unit/test_phase3_acceptance_repairs.py` (startup order/off-loop preparation
and optional framework). Existing correlation, HTTP, all 55 restored ingestion
and isolated PostgreSQL acceptance sources remain intact. See the
[current handoff record](guides/realtime-agent-phase3-handoff.md) for measured
GIL comparisons, diagnostic stacks/wait locations, exact completed commands and
remaining unresolved historical parser-stall cause. Real providers, Persian
speech, browser hardware and production deployment remain unverified.
Final follow-up acceptance: **92 focused unit passed**, **1753 provider-free
passed** (two existing Windows-path skips; 397 PostgreSQL cases deselected),
**25 affected isolated PostgreSQL passed**, zero acceptance skips. Missing
TEST_DATABASE_URL failed as required. Actual 26.8/59.5 MB escaped JSON heartbeat
maximum gaps: **14.03/11.64 ms**, versus **215.07/336.19 ms** in a thread.
Seven scoped baseline files changed, **231 stayed byte-identical**, three added.
The historical parser-stall cause remains explicitly unresolved; no real-provider,
Persian speech or browser hardware claim is made. Exact commands/results,
intermediate failures and database cleanup are in the handoff.
## Realtime MVP Phase 4 acceptance checkpoint (2026-10-09)
The [Phase 4 acceptance report](guides/realtime-agent-phase4-acceptance.md)
records current baseline verification, per-scenario outcomes, JSON heartbeat
observations, guarded provider-free health correlation IDs, isolated database
checks, spending prerequisites and startup/recovery commands. This is the
Realtime MVP phase, separate from the older scoped-search Phase 4 report.
Current checks: **92 focused passed**, **1753 provider-free passed** (two existing
Windows-path skips), **397 isolated PostgreSQL passed**, zero acceptance skips.
Actual large-JSON maximum heartbeat gaps were **13.06/16.21 ms**. Health made
zero provider calls; missing TEST_DATABASE_URL failed explicitly. Disposable
database cleanup/removal and dependency/Compose/whitespace checks passed.
The developer confirms the actual frontend is still in development. Funded
Gemini and OpenAI acceptance, independent held-out retrieval quality, real UI/
hardware and HTTPS/WSS deployment remain `not_run` with exact prerequisites.
The configured calibration remains pending with null cutoff. No completion,
provider quality or operational readiness claim follows from technical tests.
Existing provider adapters/selection, frozen OCR/factual policies, shared
retrieval, protected inputs and applied migrations were retained.
## Phase 4 executed operational follow-up (2026-10-09)
The latest [acceptance report](guides/realtime-agent-phase4-acceptance.md) and
[startup/recovery guide](guides/phase4-backend-operations.md) supersede the
technical-only operational checkpoint above. Actual built Docker API/worker,
accounts and HTTP, publication/selection, provider-free health, persistent service
recreation, interrupted-worker lease recovery, synthetic review/retry and graceful
shutdown passed **eight scenarios** with zero real-provider calls. Correlations,
timing definitions and observations are in
[operational evidence](calibration/realtime-phase4-operations.json).
Final suites: **1755 provider-free passed** (two existing Windows-path skips),
**397 isolated PostgreSQL passed**, zero database acceptance skips. Missing database
configuration failed explicitly. Task containers/networks were removed; unrelated
containers and named acceptance volumes were preserved.
The user's bounded permission for four originals/APIs resulted in **one** real
OpenRouter vision HTTP attempt; all native Gemini/OpenAI voice, calibration,
evaluation and paid embedding call counts remained zero. Actual bindings and
failures are in [bounded intake evidence](calibration/realtime-phase4-bounded-intake.json).
The original DOCX failed ambiguous factual association; the infographic failed
extraction quality; both PDFs remain queued without paid extraction. No human
approval or unseen label was manufactured. Real embedding request limits and
container endpoint reachability, approved calibration/review/labels and finalized
retrieval gate remain non-UI prerequisites. Gemini Live preflight returned 503
CALIBRATION_REQUIRED; OpenAI additionally lacks its dedicated key. Actual frontend
and hardware, provider quality, and public HTTPS/WSS remain separately not_run.
Phase 4 is incomplete. Docker dependency/startup configuration and demonstrated
worker SIGTERM cleanup were repaired; protected inputs and frozen contracts remain.
## Ingestion and voice transport admission amendment (2026-10-09)
The [scoped repair report](guides/ingestion-voice-admission-repair.md) supersedes
prior claims that initial FAQ preambles or recognition diagnostics must terminate
intake, and documents the explicit `VOICE_TRANSPORT_TESTING` policy (default false).
Initial unheaded source introductions accompany all approved FAQ pairs; detached
post-pair prose still fails. Gemini/OpenRouter incomplete recognition and warnings
retain legible candidates and require exact human extraction review even with a
frozen false OCR policy. Fatal native format/provenance/readability remains enforced.
Independent factual approval, same-job retry and explicit selection remain intact.
Explicit transport testing admits owned voice reservations/streams without measured
cutoff and exposes frozen calibration_status in create/recovery/poll and F01.
Shared search still admits no uncalibrated evidence: CALIBRATION_REQUIRED remains its
canonical result. Provider selection/adapters, authorization before provider opening,
replay identities, epochs and stream profile matching remain. No migrations or
external dependencies added. Actual provider quality/UI/hardware/public HTTPS/WSS
remain separately unverified. Full commands, outcomes, intermediate obsolete contract
assertions and protected-input checks are recorded in the scoped report.
Executed scoped repair checks: **124 focused unit passed**, **1767 full provider-free
passed** (two existing Windows-path skips), **7 new PostgreSQL repair scenarios
passed**. Initial full database run: 401 passed and two superseded warning-only
assertion failures; strengthened corrupt-text cases passed. Final database recheck:
**402 passed**, zero skips, with only the two unchanged large-review cases already
passed in the initial full run deselected. All 404 current database scenarios have
passing executed evidence across these runs. Protected inputs/migrations and the
restored 55-case source remained byte-identical. Exact timings, reproduction,
intermediate failures, JUnit path and cleanup are in the scoped repair report.
## Browser voice termination repair (2026-10-10)
The [incident repair and frontend handoff](guides/voice-session-termination-repair.md)
records the confirmed OpenAI output-item normalization, terminal-close race and
manual-stop notification fixes, safe diagnostic fields, shared bounded shutdown
ownership, regression checks and deployment/browser acceptance steps. Source
locations: `app/modules/voice/diagnostics.py`, existing runtime/lifecycle/registry,
`app/infrastructure/realtime.py`, and `app/api/v1/live.py`. New regression sources:
`tests/unit/test_voice_session_incident.py` and
`tests/integration/test_voice_session_incident.py`. Historical incident attribution,
actual Angular cleanup and funded provider/browser acceptance remain unverified.
No applied migration or public error envelope changed. See the report for exact
completed checks; earlier checkpoints do not establish this repair's acceptance.
## OpenAI cancellation/context synchronization repair (2026-10-10)
The [scoped repair and acceptance report](guides/live-context-sync-repair.md)
records one explicitly authorized OpenAI probe (two short responses), the captured
gpt-realtime-mini/shimmer structured no-active cancellation error, its pre-fix
synthetic failure and the profile-restricted adapter correction. Terminal and
heard-position truncation barriers remain mandatory. Runtime diagnostics now
distinguish every synchronization failure branch with bounded numeric state.
Final checks: 1827 provider-free passed (three Windows symlink skips) and 11
isolated PostgreSQL incident tests passed (zero skips). Applied migrations,
public contracts, provider/model configuration and unrelated changes remain.
Historical incident attribution, corrected live application/browser acceptance
and deployment are unverified; the currently inspected API selected Gemini.
## Continuous microphone input accounting repair (2026-10-10)
The [scoped repair report](guides/voice-input-accounting-repair.md) supersedes the historical 10-second silence overflow requirement. API 7.1.3 now bounds detected uncommitted speech independently of queued/in-flight transport; absolute positions and commitment fencing remain. Fixed speech-stop and existing commit/send deadlines protect missing events. Stable overflow diagnostics distinguish input, output, playback and control branches. Verification: 1834 provider-free passed (three existing Windows symlink skips); final adapter/diagnostic follow-up 80 passed. No database behavior or migration changed; no deployment or paid provider calls. Real-provider/browser acceptance remains unverified. See the report for exact commands, intermediate failures, counter definitions and provider evidence.
## OpenAI Persian speech Phase 1 foundation (2026-10-11)
The [scoped implementation/frontend handoff](guides/openai-persian-speech-phase1.md)
and [baseline/check report](evaluation/openai-persian-speech-baseline.json) track
Phase 1 of the Persian quality plan only. OpenAI input ASR/VAD/noise settings
flow through existing configuration/factory/adapter paths and freeze in
execution_profile.audio_input. Existing replay/stream admission rejects missing
or mismatched snapshots without rewriting them; Gemini/public contracts remain.
User transcription now rejects malformed types/post-completion deltas.
New offline command: .venv/Scripts/python -m app.score_speech --help.
The scorer, 30-slot manifest, blank human annotation/observation templates and
runnable examples/voice-transcripts.js are preparation, not real quality evidence.
Actual live comparisons, human speech/critical facts, natural pauses and actual
frontend/browser reconciliation remain not_run; Phase 1 is not closed.
Read-only rag-api inspection selected OpenAI gpt-realtime-mini/shimmer,
transport testing true and no calibration report. No rebuild/restart or provider
evaluation was performed. Final checks are recorded in the linked report.
Phase 1 affected checks: 361 provider-free regressions and 82 isolated PostgreSQL
cases passed, no database skips. Broader database acceptance is incomplete after
a reported failure and stalled progress; ordinary-suite attempts have timing
failures. See the report for all attempts and final outcomes. No assertions were
weakened, no operational containers were restarted, and test storage was removed.
Final full provider-free run: 1874 passed, three Windows symlink skips, one
existing GeminiVision extraction deadline failure; isolated retest 2 passed.
The full suite remains non-green. Phase 1 live/frontend acceptance remains not_run.
## OpenAI Persian delivery Phase 2 ? 2026-10-11
Fixed OpenAI-only style and instruction digest now reuse the existing execution
profile; shared POLICY/Gemini instructions and cancellation classifier are unchanged.
See [Phase 2 handoff](guides/openai-persian-delivery-phase2.md),
[comparison manifest](evaluation/openai-persian-delivery-comparison.json), and
[style source](../app/modules/voice/openai_style.py). Human examples/listening and
real candidate interruption acceptance remain pending; Phase 2 is not closed.
Phase 2 actual checks: 338 focused checks and 10 isolated PostgreSQL profile cases
passed. Broad provider-free run excluding the duplicate-suite driver: 1880 passed,
3 symlink skips, 1 unchanged JSON responsiveness failure; isolated JSON rerun also
failed its timing bound (different parameter). See the handoff for exact commands
and outcomes. No clean full-suite or real-speech acceptance claim.
## Persian quality Phase 3 (2026-10-11)
[Phase 3 report](guides/openai-persian-understanding-phase3.md) and
[comparison status](evaluation/openai-persian-understanding-comparison.json)
record optional OpenAI low/medium reasoning through existing configuration,
factory and adapter, frozen private execution profiles and acknowledgment/replay
regressions. Gemini and canonical search remain unchanged. Real retrieval/model
acceptance is blocked by approval/bindings, measured calibration, selected speech
profile, human scenarios and explicit bounded authorization. No provider calls or
candidate promotion. Consult the report for actual checks and unresolved failures.
## Measured calibration activation (2026-10-11)
[Operational handoff](guides/search-calibration-activation-2026-10-11.md) records
actual approved sample intake, six ready chunks, selection revision 9 with existing
documents preserved, and ten local bge-m3 query embedding calls. Measured support
is 6/6, unsupported false positives 0/4. The successful environment-specific
report is mounted read-only into rag-api; SEARCH_CALIBRATION_REPORT selects it
and VOICE_TRANSPORT_TESTING is false. Read-only capability checks report calibrated;
HTTP readiness and localhost:4200 CORS preflight passed. No OpenAI voice calls.
Independent 26-case evaluation, real speech/delivery and candidate interruption
acceptance remain unrun; Phase 3 is still open. Earlier no-call checkpoints above
are historical and precede this separately approved operational workflow.
## OpenAI bounded voice generation repair (2026-10-12)
The [scoped implementation and frontend handoff](guides/openai-output-limit-repair.md)
records OPENAI_REALTIME_MAX_OUTPUT_TOKENS (default 256), acknowledged session
generation limits and pinned profiles/instruction revision. Validated audio-only
max_output_tokens terminal responses remain incomplete/limited, drain exact
existing credits, and preserve interruption, truncation and next-turn gates.
Incomplete tools fail safely; OpenAI tool execution waits for successful terminal
validation. Gemini setup/policy and all existing audio bounds remain unchanged.
New application answer_limited and assistant transcript status limited are
documented with the example consumer. Old incompatible reservations are replayed
without rewriting but fail stream admission. Per-report VOICE_PLAYBACK logging
was removed; bounded failure diagnostics remain.
Final checks: 385 focused passed plus 40 final limit/authority checks; 1932 full
provider-free passed (three existing Windows symlink skips); 32 profile/incident
and eight existing two-provider ASGI isolated PostgreSQL cases passed, zero
database skips. Missing database configuration failed explicitly. Disposable
schemas/containers/volumes were removed and operational services were untouched.
See the handoff for exact commands, intermediate failures and scoped file list.
No provider calls, actual Angular/browser validation, measured audio-duration
guarantee, deployment or speech-quality acceptance is claimed.