# Knowledge Layer (v0.3 foundation)

## Purpose

The knowledge layer retrieves relevant site content for prompt augmentation (RAG).
It follows the Clean Architecture contracts in `02-system-architecture-prompt.md`
while reusing the existing embeddings stack through a legacy adapter.

## Current Scope

- Domain contract: `KnowledgeRetrieverInterface`
- Value object: `KnowledgeChunk` with optional source URL for citations
- Application use case: `RetrieveKnowledgeContext`
- Public widget grounding: `PublicKnowledgeGroundingPolicy` (sources-only when RAG enabled)
- Legacy adapter: `LegacyRagKnowledgeRetriever` -> `RagService`
- Used by legacy `ChatService` for public widget + agent `SendChatMessage` for admin (both return `sources`)
- Indexed content types: posts, pages, extra public CPT (`rag_indexable_post_types` / `teddy_indexable_post_types`), WooCommerce products, PDF/CSV media uploads
- Large catalogs: cursor option `teddy_rag_ingest_cursor` batches 25 items per cron tick; phases include `uploads`; filters `teddy_indexable_products`, `teddy_indexable_posts`, `teddy_indexable_upload_mimes`
- Enrichment: `KnowledgeContentEnricher` (ACF + Elementor) + `UploadDocumentExtractor` (PDF/CSV)
- Admin: Settings knowledge panel + REST `GET/POST /knowledge/status|reindex|ingest`; Settings UI upload for PDF/CSV
- SEO domain tools: `seo.meta.generate`, `seo.article.write`, `seo.article.audit`

## Feature Flag

- Setting key: `enable_rag`
- Default: `false`

When RAG is first enabled, a background reindex is scheduled (~15s). Admins can also click **Rebuild knowledge index now** on Settings.

## Main Classes

- `src/Domain/Knowledge/KnowledgeChunk.php`
- `src/Domain/Knowledge/KnowledgeRetrieverInterface.php`
- `src/Application/Knowledge/KnowledgePromptComposer.php`
- `src/Application/Knowledge/PublicKnowledgeGroundingPolicy.php`
- `src/Application/UseCase/RetrieveKnowledgeContext.php`
- `src/Infrastructure/Knowledge/LegacyRagKnowledgeRetriever.php`
- `src/Services/RagService.php` (`search()` + `augment()`)
- `src/REST/KnowledgeController.php`

## Verification

- Unit tests: `tests/Unit/KnowledgePromptComposerTest.php`, `tests/Unit/PublicKnowledgeGroundingPolicyTest.php`, `tests/Unit/MarkdownToHtmlTest.php`
- Integration: `tests/Integration/RagServiceCursorTest.php` (1000-product cursor simulation)
- E2E: `tests/e2e-rag.php`, `tests/e2e-rag-scale.php`
- Playwright admin smoke: `TEDDY_E2E_PASS=*** npm run test:e2e:playwright` (optional `TEDDY_E2E_USER`, default `vinhnx`)
- Static analysis: `composer phpstan`
