===============================================================================
 Commit Message - xSaherelmWorkspace
 تاریخ: ۱۴۰۵/۰۸/۰۷ (2026-10-29)
 نسخه مستند: v01
 گزارش کامل: Documents/Docs/ChangeLogs/1405-08-07-v01.html
===============================================================================

هدف: رفع موانع پیش از Production در xAiApi (Scope واقعی RAG، حذف
ProxyController، ترتیب Middleware، قالب SSE) و اصلاح باگ‌های منطقی xAiModels.

ترتیب Commit: [1] xHttpService -> [2] xAiModels -> [3] xAiApi -> [4] Root

[1] Modules/xHttpService
Add Shared Server-Sent Events Helpers
- Add XSseExtensions: PrepareSseResponse, WriteSseEventAsync, WriteSseRawAsync,
  WriteSseDoneAsync, WriteSseErrorAsync, IsClientCancellation;
- Spec-compliant "data:" framing, multi-line split, "event: done" / "event: error";
- Add Microsoft.AspNetCore.Http.Features 2.3.13 reference.
Files: A Extensions/XSseExtensions.cs; M xHttpService.csproj

[2] Modules/xAiModels
Move Knowledge Constants and Fix Inverted Ownership Filters
- Add XAiKnowledgeScope enum (Conversation=0, Project=1, Global=2, User=3) with StringValue prefixes;
- Add Knowledge constants, scope prefixes, metadata keys and XAiErrorRoute to XAiModelsConstants;
- Fix inverted ownerId condition in QueryProjects / QueryConversations / QueryMessages
  (ownership filter was skipped for real owners -> cross-user data exposure);
- Fix inverted HasChild() validation in HasDefaultProject / HasDefaultConversation;
- LoadConversations: ignore soft-deleted conversations;
- CreateProject / CreateConversation: set isDefaultLanguageHandled = true;
- GetDefaultConversation: use projectId instead of unloaded project.Id.
Files: A Constants/XAiKnowledgeScope.cs; M Constants/XAiModelsConstants.cs;
       M Extensions/XAiModelsExtensions.cs; M Providers/XAiDataProvider.cs

[3] xAiApi
Implement RAG Scopes, Remove ProxyController, Fix Pipeline Order and SSE Format
- RAG: real scopes with identifiers conversation/{id}/, project/{id}/, user/{ownerId}/, global/;
- RAG: ownership checks via GetProject/GetConversation; Global write requires admin role;
- RAG: tiered retrieval Conversation -> Project -> User -> Global (single embedding, dedup, TopK fill);
- RAG: apply Type filter, sanitize file names, enforce MaxFilesPerIngest/MaxFileSizeBytes/MaxDocumentsPerScope;
- RAG: store scope/scopeId/type/ownerId metadata; return it in documents and sources;
- RAG: add MigrateLegacyVectorsAsync + POST /Knowledge/MigrateLegacy ({ownerId}/... -> user/{ownerId}/...);
- Knowledge API: scope/scopeId on Ingest, Documents, DELETE Documents;
- Remove ProxyController (root route "{modelName}/{path}" + AllowAnonymous hijacked all 2-segment paths);
- Startup: ExceptionHandler("/error") + HSTS outside Development; Swagger only in Development;
  static files before routing; CORS before model proxy; add /error endpoint;
- SSE: all stream endpoints use xHttpService XSseExtensions; validate before streaming;
  pre-stream errors return proper HTTP status; remove "Connection: keep-alive";
- Use xAiModels.Constants for XAiKnowledgeScope / Knowledge constants / XOpenAINoKey;
- Register XAiVectorEntityRegisterar in XAiApiDbContext;
- XCodeFileContentExtractor: actually read stream content; drop hard-coded "book.epub".
BREAKING: AskTextStream emits data: {"text":"..."}; AskStream emits data: {json}; both end with event: done.
Files: D Controllers/ProxyController.cs; D Constants/XAiKnowledgeScope.cs;
       M Constants/XAiApiConstants.cs; M Controllers/ChatWithDocumentsController.cs;
       M Controllers/KnowledgeController.cs; M Controllers/StartupController.cs;
       M Controllers/XAiServiceControllerBase.cs; M Database/XAiApiDbContext.cs;
       M Extensions/XModelsExtensions.cs; M Interfaces/IXAiRAGService.cs;
       M Models/XAiKnowledgeModels.cs; M Providers/Extractors/XCodeFileContentExtractor.cs;
       M Providers/XAiEmbeddingServiceBase.cs; M Providers/XAiRAGService.cs; M Startup.cs

[4] Workspace (root)
- Update submodule pointers: xAiApi, Modules/xAiModels, Modules/xHttpService;
- Add Documents/Docs/Developer/xAiApi-14050807-Overview.html and -Overview-1.html (review reports);
- Add Documents/GeneratedContext/*-20261029_145645.txt (xAiApi, xAiModels, xAiService);
- Add Documents/Docs/ChangeLogs/1405-08-07-v01.html and this commit message file.

Validation:
- dotnet build xAiApi/xAiApi.csproj --nologo -v q -> 0 Error(s), 392 pre-existing warnings (MSB3277/NU1900);
- Runtime smoke (Development, anonymous): GET / 200; GET /Knowledge/Ask 405 (no longer proxied);
  GET /foo/bar 404; GET /error 500 JSON; /ai-model/NotExists 404 (middleware); protected endpoints 401;
- Authenticated end-to-end tests (Ingest/Ask/AskStream with real embedding/LLM) still pending.

Follow-ups:
- Frontend must migrate to the new SSE format;
- Call POST /Knowledge/MigrateLegacy for users with legacy vectors;
- Review UseHsts behind TLS-terminating reverse proxy;
- Review anonymous access to wwwroot/Storage/Uploads.

Suggested root commit title:
Implement RAG Scopes, Remove ProxyController, Fix Pipeline and SSE, Fix xAiModels Ownership Filters (۱۴۰۵/۰۸/۰۷ v01)

For additional documentation use v02:
1405-08-07-v02.html
CommitMessage-1405-08-07-v02.txt
===============================================================================
