Files
rag-technical-docs-assistant/docs/plans/scoped-search-implementation-plan.md
T
amirhosein mazaheri ca8833dd2f docs: restructure documentation hierarchy and update agent reference map
- Organize architecture, specifications, plans, and guides into dedicated subdirectories under docs/
- Remove legacy and duplicate documents from data/documents/
- Update AGENTS.md, README.md, and agent skills to target canonical docs paths
2026-10-07 16:19:24 +03:30

18 KiB

Fast-Track Search MVP - Implementation Plan

Date: 2026-10-07
Target file: docs/plans/scoped-search-implementation-plan.md
Status: Approved planning direction; implementation and acceptance remain pending. This four-phase plan replaces the earlier seven-phase proposal.

1. Delivery Strategy

The first phase must deliver a visible search result. Selection, compatible query embeddings, pgvector retrieval, and a minimal inspection CLI are implemented together.

There are four phases:

Phase Deliverable Observable checkpoint
1 Working vertical slice Ask a question and see actual uploaded-document chunks and sources
2 Retrieval correctness Exact identifiers, bounded evidence, calibrated outcomes, and revocation tests
3 LangChain integration The model-facing tool invokes the same search service
4 Quality gate and handoff Real Persian evaluation passes and operator instructions are complete

Do not postpone the first result until all adapters, evaluation infrastructure, or documentation are finished. Run targeted checks while building; run full regression acceptance at the final checkpoint.

The first result depends on a working PostgreSQL/pgvector database, one approved processed document, and compatible funded embedding credentials. If credentials are unavailable, deterministic database evidence can prove the connection, but must be labeled as provider-free validation.

No fixed completion time is promised before these prerequisites are checked. The first-result checkpoint is the end of Phase 1.

2. Shared Contracts and Scope

Read AGENTS.md, the reference map, and the applicable sections of the implementation guide, API catalog, database design, and MVP scenarios. The delivery plan governs Phase 1 scope.

This plan uses milestone phases 1-4; these labels do not replace the existing ingestion phase numbering or the product's Phase 1 contracts.

Preserve these requirements from the beginning:

  • Reuse existing ingestion, embeddings, worker, review, and publication.
  • Resolve organization and role from the persisted enabled actor.
  • Search only authorized, ready, active, undeleted, unpurged documents.
  • Activate through an atomic selection service, never direct SQL shortcuts.
  • Preserve selection revisions, access epochs, and audit behavior.
  • Keep provider calls outside database transactions.
  • Verify full embedding identity, input limits, normalization, and float32 vectors.
  • Return faithful text, document/chunk IDs, and actual locators.
  • Preserve applied migrations and unrelated working-tree changes.
  • Technical failures remain errors, never "no evidence."
  • Keep one retrieval implementation for inspection, LangChain, and later Live.
  • Do not introduce document-content versioning or overwrite original uploads.

Backend defaults are five returned chunks and 12,000 evidence-text characters. Return whole chunks; skip a chunk that cannot fit rather than removing its conditions or exceptions.

Public HTTP search, browser authentication, UI, text/history, Live transport, persistent tool dispatch, reranking, and ANN are outside this milestone.

The inspection CLI may show uncalibrated retrieval candidates, clearly labeled as such. This is an operator diagnostic format, not the model-tool contract or a quality claim. It uses the same retrieval core and eligibility rules.

The final tool accepts only required query and optional context, each bounded by the existing API contract: query is 1-2000 characters; context is at most 2000 characters. Reject unknown fields and whitespace-only queries. Context is an untrusted retrieval hint, not evidence or authority. Authority, profile, limits, execution IDs, and source-reference allocation remain backend-owned.

The operator CLI follows the existing trusted intake model. An operator-supplied user UUID is not HTTP authentication and must never become an unauthenticated web identity mechanism. Enabled administrators manage selection; enabled administrators and normal users may execute authorized search.

Search captures and rechecks access epoch and enabled actor around remote work. No conversation or Live tables are required here. Future sessions must integrate with the same epoch boundary; this milestone does not claim to close sessions that do not yet exist.

All phases must inspect Git status, preserve unrelated tracked and untracked files, and report actual checks. Do not delegate to sub-agents. Missing infrastructure is an unrun prerequisite, not successful acceptance. Keep ordinary tests deterministic and provider-free.

3. Implementation Phases and Exact Prompts

Phase 1 - First Search Result

Build only what is needed to exercise one complete path:

  1. Read this saved plan and inspect the baseline.
  2. Implement trusted actor resolution and selection get/replace.
  3. Add compatible one-input query embedding and scoped cosine retrieval.
  4. Add a single-query inspection CLI.
  5. Demonstrate retrieval from one approved uploaded document.

Selection uses the existing K01/K02 semantics: full-set replacement, expected revision, atomic validation, unchanged counters for no-op, knowledge revision for changes, access epoch for removals, and an audit event for successful changes. Lock settings before affected documents, using stable document-ID order. Reject duplicate IDs, hidden/deleted/purged IDs, unready documents, and stale revisions without a partial update. Preserve configuration revision.

Use existing provider and validation utilities. Add no dependency for this phase.

Planned commands

.venv/Scripts/python -m app.knowledge selection get --administrator-id <admin-id>

.venv/Scripts/python -m app.knowledge selection replace `
  --administrator-id <admin-id> `
  --expected-revision <revision> `
  --document-id <document-id>

.venv/Scripts/python -m app.search `
  --inspect `
  --user-id <user-id> `
  --query "<Persian question>" `
  --allow-provider-calls

Document IDs are repeatable; explicit --clear replaces the selection with an empty set and is mutually exclusive with document IDs. Result JSON goes to stdout; safe diagnostics go to stderr.

Acceptance: an inactive document yields no candidates; after legitimate selection, a query returns actual chunk text and source identities. Foreign and ineligible documents remain excluded.

Execution prompt

Use $implement-feature to implement Phase 1 of the Fast-Track Search MVP.

Read docs/plans/scoped-search-implementation-plan.md, AGENTS.md, the
reference map, and governing selection/search/database contracts.
Inspect Git status and preserve all unrelated tracked and untracked
changes. Preserve applied migrations.

Deliver a working vertical slice in this phase:
persisted enabled-actor resolution -> atomic knowledge selection ->
compatible query embedding -> scoped pgvector cosine retrieval ->
single-query inspection CLI.

Reuse existing ingestion, embedding adapter, preprocessing, input-limit,
tokenizer, float32-vector, and database compatibility utilities.
Do not import the prototype Chroma retriever.

Implement full-set selection with expected revision, documented
counter behavior, settings-first locking, and atomic audit updates.
Search derives organization from the actor and applies every eligibility
filter. Revalidate actor and access epoch before delivering results.
Keep remote calls outside transactions and use finite provider/SQL
timeouts.

Inspection output must identify results as uncalibrated candidates and
include faithful text, title, document_id, chunk_id, and location.
Require explicit provider-call opt-in. This diagnostic output is not
a model-tool response or semantic-quality certification.

Add targeted tests for selection/counters, organization isolation,
eligibility, profile mismatch, invalid vectors, and inactive-to-active
retrieval using real PostgreSQL.

As soon as targeted checks pass, demonstrate one approved real document
and query if prerequisites are available. Otherwise demonstrate the
provider-free database path and identify the missing prerequisite.

Stop at the first-result checkpoint. Do not build LangChain, UI,
evaluation infrastructure, ANN, or unrelated abstractions.
Report the exact demonstration command and observed result.

Phase 2 - Make Retrieval Reliable

Add:

  • Normalized exact identifier/date/article matching alongside cosine candidates.
  • Deterministic merge and deduplication.
  • Whole-chunk evidence budgeting and source references.
  • Canonical ok, no_evidence, and error results.
  • Profile-specific cutoff calibrated from ten separate cases.
  • Revocation, publication-boundary, and failure tests.

Lexical comparison handles Persian/Arabic digit equivalence, kaf/yeh equivalence, NFC, case, and whitespace. Preserve dates, separators, source text, and embedding preprocessing. Use boundary-aware matching; arbitrary isolated numbers are not identifiers.

Each semantic/exact branch retrieves at most 50 eligible candidates. Deduplicate by chunk ID; rank exact matches first, then cosine distance and stable chunk ID. Exact matching cannot bypass evidence admission.

Successful sources follow API Section 7.2: source_ref, document_id, chunk_id, title, faithful text, and location.page/section. Preserve nullable locators; do not invent pagination. Allocate source references consistently across searches in one execution. No evidence means completed retrieval with insufficient support; provider, SQL, profile, timeout, and revoked-context failures are normalized errors.

Calibrate on six answerable and four unsupported questions. Select the cutoff maximizing complete-support coverage with zero unsupported false positives; choose the stricter cutoff on ties. If none works, report the measured failure and repair the baseline. Do not change the pinned embedding profile or weaken expected evidence to obtain a pass.

Execution prompt

Use $implement-feature to implement Phase 2 only.

Read the plan and governing contracts. Preserve unrelated changes,
applied migrations, and the Phase 1 working path.

Extend the SAME retrieval core with parameterized normalized exact
identifier/date/article matching. Apply all eligibility predicates
before ranking and limits in every branch. Preserve evidence and
embedding preprocessing.

Implement bounded candidate merge, deterministic ordering, deduplication,
whole-chunk budgeting, actual locators, and execution-wide source
references. Enforce five chunks and 12000 evidence-text characters.

Add canonical tool-result outcomes. Provider, SQL, timeout, compatibility,
and revoked-context failures remain normalized technical errors.

Create ten independently annotated calibration cases: six answerable,
four unsupported. Use the configured compatible real model only with
explicit provider-call authorization. Calibrate and record the cutoff
using the plan's selection rule; do not invent a universal threshold.

Capture and recheck access epoch and enabled actor around provider work.
Use short settings-locked retrieval transactions. Add bounded barrier
tests for removal and actor disablement during execution.

Add real PostgreSQL integration coverage from ingestion/publication
through selection/search, including independent literal expected
numbers, conditions, negation, and exceptions. Verify partial publication
and failed batches never become searchable.

Run affected unit and database tests. Keep the inspection CLI available.
If calibration prerequisites are missing, finish independent technical
work and report model-quality acceptance as pending.

Phase 3 - Thin LangChain Tool

Add only the framework boundary required by the MVP.

  • Dedicated search extra: langchain-core>=1,<2.
  • Strict search_knowledge arguments: query, optional context.
  • Trusted execution context captured outside model arguments.
  • Synchronous and asynchronous calls to the same service.
  • Lazy framework imports and bounded blocking execution.

Use a thin StructuredTool adapter with an explicit argument schema and synchronous/asynchronous entrypoints; see the official LangChain API reference.

Default execution limits: four running calls, eight waiting calls, and a 75-second total deadline. SQL statement/lock timeouts are five/two seconds. Validate configuration; retain the explicit provider timeout policy.

Cancellation suppresses late results. A running blocking call holds its slot until it exits, even if its caller times out. Queue waiting consumes the deadline. Saturation and timeout return normalized technical errors. Do not create unbounded executor queues or internal provider retries.

Execution prompt

Use $implement-feature to implement Phase 3 only.

Follow AGENTS.md, the plan, and the canonical internal tool contract.

Add the minimal search dependency extra and a lazy LangChain
search_knowledge adapter. Expose only query and optional context with
strict validation. Capture persisted backend authority, deadline,
epoch, cancellation, and source-reference context outside model input.

Delegate directly to the Phase 2 service. Do not build another retriever,
vector store, embedding pipeline, text agent, or Live dispatcher.

Provide sync and async entrypoints. Run blocking provider/database work
off the event loop with the plan's bounded concurrency and admission
limits. Queue waiting consumes the deadline. Suppress cancelled or late
results, retaining running-work slots until actual completion.

Test CLI/tool equivalence, forged-scope and unknown-field rejection,
canonical results, event-loop responsiveness, saturation, timeout,
cancellation, and lazy imports.

Keep core search and ingestion usable without LangChain. Run actual
adapter tests with the declared extra installed; missing dependencies
do not count as skipped acceptance.

Report the tool schema, verified invocation, and remaining final
quality gate.

Phase 4 - Persian Quality Gate and Minimal Handoff

Use the four required example structures and additional unseen documents.

Held-out evaluation:

  • Twenty answerable Persian questions, including at least four about unseen documents.
  • Six unsupported questions.
  • Original-source annotations created independently of retrieval output.
  • Explicit bindings between original hashes and database document IDs.
  • Frozen profile, cutoff, labels, and search settings before evaluation.

An answerable case passes when its first five chunks collectively contain every required evidence group. Matching a title or one number is insufficient.

Required gate:

  • At least 18 of 20 answerable cases pass.
  • Every critical number/condition/negation/exception case passes.
  • All six unsupported cases return no_evidence.
  • No unauthorized or ineligible evidence appears.
  • Technical errors are failures, not unsupported-question successes.

Do not tune against the held-out cases or remove failures from reports. Calibration and held-out questions remain separate. Failure requires a measured repair and a valid reevaluation; do not claim practical retrieval readiness from technical tests alone.

Execution prompt

Use $write-tests for final evaluation and acceptance.

Read the plan and current implementation. This phase does not silently
fix production defects; report failures with their responsible phase.

Prepare twenty independently annotated answerable Persian questions
and six unsupported questions. Cover both supplied PDFs, the infographic,
approved factual DOCX content, and at least four unseen-document
questions. Annotate evidence from originals, including qualifiers.
Do not generate expected facts from search results or indexed FAQs alone.

Bind approved original hashes to actual document IDs. Use existing
intake, worker, review, and selection services. Do not force readiness,
activate with raw SQL, or automatically approve human review decisions.

Run the same search service with the pinned funded model and the
Phase 2 frozen cutoff. Require explicit provider-call opt-in and a
bounded call budget. Keep real evaluation outside ordinary pytest.

Apply the exact 18-of-20, all-critical, all-unsupported gate. Record
per-case evidence, sources, outcomes, latency, provider calls, and
available usage. Mark unavailable billing information as unavailable.

Classify failures by extraction/review, chunking, publication, selection,
compatibility, retrieval/ranking, evidence budgeting, or technical
provider/database errors. Preserve every failed case.

Run the full provider-free and mandatory isolated PostgreSQL suites,
pip check, whitespace/new-file inspection, and migration preservation
checks.

Write a short operator guide with actual setup, selection, query,
evaluation, troubleshooting, and results. Update plan/reference status.
Claim retrieval readiness only if both technical and quality gates pass.
Do not claim generated-answer or Live readiness.

4. Verification and Completion

Run targeted checks before the first-result demonstration. Run full acceptance at Phase 4:

.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short

.venv/Scripts/python -m tests.postgres_prerequisites

.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short

.venv/Scripts/python -m pip check

git diff --check

Use an isolated TEST_DATABASE_URL; missing configuration must fail PostgreSQL acceptance. Inspect untracked files separately and verify the preservation of applied migrations.

Each phase reports its working command, observed output, actual checks, and remaining prerequisites. Documentation stays proportional to the work. Record technical acceptance and real-provider quality acceptance separately. Historical test results are not checks performed by this plan.

No latency or concurrent-user service-level target has been approved. Measure timings and enforce the stated execution bounds without claiming an unapproved performance target. Actual provider runs require explicit opt-in, compatible credentials, approved inputs, and a bounded operator call budget.

Speed rule: finish and demonstrate each usable checkpoint before expanding it. Optimize only a reproduced quality or latency problem. The MVP search milestone remains incomplete until the confirmed real-quality gate passes.