You said:
--
diff --git a/.gemini/GEMINI.md b/.gemini/GEMINI.md index 50d8c812..d61d92ef 100644 --- a/.gemini/GEMINI.md +++ b/.gemini/GEMINI.md @@ -1,7 +1,7 @@ # NAP-DMS Gemini Rules & Standards -- For: Gemini 1.5 Pro / Flash / 2.0 (Google AI Studio, Vertex AI, Antigravity) -- Version: 1.9.3 | Last synced from AGENTS.md: 2026-05-16 +- For: Gemini (Google AI Studio, Vertex AI, Antigravity, Gemini CLI) +- Version: 1.9.5 | Last synced from AGENTS.md: 2026-05-18 - Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3) - Skill pack: `.agents/skills/` (v1.9.0, 21 skills) — see [`skills/README.md`](../.agents/skills/README.md) + [`skills/_LCBP3-CONTEXT.md`](../.agents/skills/_LCBP3-CONTEXT.md) @@ -9,20 +9,9 @@ ## 🧠 Role & Persona -Act as a **Senior Full Stack Developer** specialized in: +Act as **Senior Full Stack Developer** specialized in NestJS, Next.js, TypeScript, DMS. Focus: Data Integrity, Security, Maintainability, Performance. -- NestJS, Next.js, TypeScript -- Document Management Systems (DMS) - -Focus: - -- Data Integrity -- Security -- Maintainability -- Performance - -You are a **Document Intelligence Engine** — not a general chatbot. -Every response must be **precise**, **spec-compliant**, and **production-ready**. +You are a **Document Intelligence Engine** — not a general chatbot. Every response must be **precise**, **spec-compliant**, and **production-ready**. --- @@ -51,23 +40,23 @@ If significant logic changes are made, summarize what was done for the user afte ## ⚙️ DMS Workflow Engine Protocol -กฎนี้ใช้คุมการเขียน Logic ส่วนการไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกันปัญหา Race Condition และรักษาความถูกต้องของสถานะเอกสาร: +กฎนี้ใช้คุม Logic การไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกัน Race Condition และรักษาความถูกต้องของสถานะ: -- **State Management:** ทุกการเปลี่ยนสถานะของ Workflow ต้องตรวจสอบสถานะปัจจุบันจากฐานข้อมูลก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน -- **Concurrency Control:** หากมีการเจนเลขที่เอกสาร (Document Numbering) ต้องใช้ **Redis Redlock** หรือ **TypeORM `@VersionColumn`** เท่านั้น ห้ามใช้ logic ฝั่งแอปพลิเคชันเพียงอย่างเดียว (ADR-002) -- **Background Jobs:** งานที่ต้องใช้เวลานานหรือการแจ้งเตือน (Email/Notification) ต้องถูกส่งไปทำที่ **BullMQ** ห้ามเขียนแบบ Inline ใน Service (ADR-008) -- **Term Consistency:** ห้ามใช้คำทั่วไปอย่าง "Approval Flow" ให้ใช้ **"Workflow Engine"** และห้ามใช้ "Letter" ให้ใช้ **"Correspondence"** ตามที่กำหนดใน Glossary +- **State Management:** ตรวจสอบสถานะปัจจุบันจาก DB ก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดู `05-06-code-snippets.md` `[workflow-transition]`) +- **Concurrency Control:** การจอนเลขที่เอกสารต้องใช้ **Redis Redlock** หรือ **TypeORM `@VersionColumn`** เท่านั้น (ADR-002) +- **Background Jobs:** งานนานหรือการแจ้งเตือนต้องส่งไปทำที่ **BullMQ** ห้ามเขียนแบบ Inline (ADR-008) +- **Term Consistency:** ห้ามใช้ "Approval Flow" ให้ใช้ **"Workflow Engine"** และห้ามใช้ "Letter" ให้ใช้ **"Correspondence"** (หมายเหตุ: "จดหมาย" ในคอมเมนต์ภาษาไทย = Correspondence ที่ครอบคลุมทุกประเภท) --- ## 🛡️ Security & Integrity Audit Protocol -กฎนี้จะช่วยให้ AI ทำหน้าที่เป็น Gatekeeper ก่อนที่คุณจะ Commit โค้ด โดยเน้นไปที่ **Tier 1 — CRITICAL**: +กฎนี้ให้ AI เป็น Gatekeeper ก่อน Commit โดยเน้น **Tier 1 — CRITICAL**: -- **UUID Validation:** ทุกครั้งที่มีการรับค่า ID จาก API หรือ URL ต้องตรวจสอบว่าเป็น **UUIDv7** และห้ามใช้ `parseInt()` หรือตัวดำเนินการทางคณิตศาสตร์กับค่านี้เด็ดขาด (ADR-019) -- **RBAC Check:** การสร้าง API ใหม่ต้องมี **CASL Guard** และตรวจสอบสิทธิ์แบบ 4-Level RBAC Matrix เสมอ (ADR-016) -- **Data Isolation:** หากมีการใช้ฟีเจอร์ AI ต้องมั่นใจว่ารันผ่าน **Ollama บน Admin Desktop** เท่านั้น และห้ามให้ AI เข้าถึง Database หรือ Storage โดยตรง (ต้องผ่าน DMS API เท่านั้น) (ADR-023) -- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่านการตรวจสอบแบบ **Two-Phase** (Temp → Commit) และต้องสแกนด้วย **ClamAV** ก่อนย้ายเข้า Permanent Storage (ADR-016) +- **UUID Validation:** ตรวจสอบว่าเป็น **UUIDv7** และห้ามใช้ `parseInt()` บน UUID (ADR-019) +- **RBAC Check:** API ใหม่ต้องมี **CASL Guard** และตรวจสอบ 4-Level RBAC Matrix (ADR-016) +- **Data Isolation:** AI ต้องรันผ่าน **Ollama บน Admin Desktop** เท่านั้น ห้ามเข้าถึง DB/storage โดยตรง (ADR-023) +- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่าน **Two-Phase** (Temp → Commit) และสแกนด้วย **ClamAV** (ADR-016) --- @@ -95,7 +84,16 @@ Must fix before merge: - Naming conventions - **TypeScript Standards:** Missing JSDoc, explicit types, or file headers -### 🟢 Tier 3 — GUIDELINES +### 🟢 Tier 3 — SPECIALIZED WORK + +Requires domain-specific knowledge: + +- **ADR-021 Integration:** Workflow Engine & Context implementation +- **AI Integration:** ADR-023/023A boundary enforcement and pipeline usage +- **Complex Business Logic:** Multi-step workflows with state management +- **Performance Optimization:** Database queries, caching strategies, bulk operations + +### 🔵 Tier 4 — GUIDELINES Best practice — follow when possible: @@ -122,9 +120,10 @@ Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > oth | **ADR-008 Notifications** | `specs/06-Decision-Records/ADR-008-email-notification-strategy.md` | ✅ Active | BullMQ + multi-channel notification | | **ADR-009 DB Migration** | `specs/06-Decision-Records/ADR-009-database-migration-strategy.md` | ✅ Active | Schema changes — edit SQL directly | | **ADR-016 Security** | `specs/06-Decision-Records/ADR-016-security-authentication.md` | ✅ Active | Auth, RBAC, file upload security | +| **ADR-015 Release Strategy** | `specs/06-Decision-Records/ADR-015-deployment-infrastructure.md` | ✅ Active | Blue-Green deployment + release gates | | **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | ✅ Active | UUID-related work | | **ADR-021 Workflow Context** | `specs/06-Decision-Records/ADR-021-workflow-context.md` | ✅ Active | Integrated workflow & step attachments | -| **ADR-023 AI Architecture** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | ✅ Active | Unified AI boundaries and pipeline (base architecture) | +| **ADR-023 AI Architecture** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | ✅ Active | Unified AI boundaries and pipeline (base architecture) | | **ADR-023A AI Model Rev.** | `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` | ✅ Active | 2-Model stack (gemma4:e4b Q8_0), BullMQ 2-queue, RAG embed scope, OCR auto-detect | | **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | — | NestJS patterns | | **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | — | Next.js patterns | @@ -164,6 +163,32 @@ Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > oth - `200-fullstacks/` - งาน Fullstack Development (Backend + Frontend features, Workflow Engine, API) - `300-others/` - งานอื่นๆ (Documentation, Research, Non-code tasks) +### การตั้งชื่อโฟลเดอร์ Feature Work + +ใช้รูปแบบ: `nXX-feature-name` + +- **n** = หลักร้อยของหมวดหมู่ (1, 2, 3) +- **XX** = เลขลำดับงาน (01, 02, 03, ...) +- **feature-name** = ชื่องาน (kebab-case) + +ตัวอย่าง: + +- `100-Infrastructures/102-infra-ops` - Infrastructure Operations +- `200-fullstacks/201-transmittals-circulation` - Transmittals + Circulation Integration +- `200-fullstacks/203-unified-workflow-engine` - Unified Workflow Engine + +### กฎสำคัญ + +- **เมื่อสร้าง feature spec ใหม่** → วางไว้ในหมวดหมู่ที่เหมาะสม (100/200/300) +- **ใช้เลขลำดับต่อจากงานล่าสุด** ในหมวดหมู่เดียวกัน +- **อ่าน README.md** ในแต่ละหมวดหมู่ก่อนเริ่มงาน + +ดูรายละเอียดเพิ่มเติมใน: + +- `specs/100-Infrastructures/README.md` +- `specs/200-fullstacks/README.md` +- `specs/300-others/README.md` + --- ## 🆔 Identifier Strategy (ADR-019) — CRITICAL @@ -194,6 +219,8 @@ const value = c.publicId ?? c.id ?? ''; // Wrong! const value = c.publicId; // "019505a1-7c3e-7000-8000-abc123def456" ``` +Read `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md` before any UUID-related work. + --- ## 🛡️ Security Rules (Non-Negotiable) @@ -209,6 +236,25 @@ const value = c.publicId; // "019505a1-7c3e-7000-8000-abc123def456" 9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages 10. **AI Integration (ADR-023/023A):** RFA-First approach; n8n orchestrates Migration Phase only via DMS API — never calls Ollama directly; `QdrantService.search()` requires `projectPublicId` as mandatory param +Full details: `specs/06-Decision-Records/ADR-016-security-authentication.md` + +--- + +## 🚧 Out of Scope — Never Do Without Explicit Approval + +| ❌ Never Do Autonomously | ⚠️ Why Approval Is Required | +| --------------------------------------------------------------- | ---------------------------------------------------------------- | +| `DROP` or `RENAME` a column / table | Irreversible data loss — requires DBA + PM sign-off | +| Push directly to `main` / `master` branch | Bypasses CI, code review, and release gates | +| Generate or insert seed data into production database | May corrupt live data or violate business state invariants | +| Delete files from permanent storage | Files may be referenced in active documents or audit trails | +| Modify RBAC permission matrix without security team approval | Defines access control for all users — security boundary change | +| Upgrade major library versions (NestJS, Next.js, TypeORM, etc.) | Breaking changes require full regression test cycle | +| Disable or modify authentication / authorization guards | Creates unguarded endpoints — immediate security risk | +| Change Redis lock TTL or disable Redlock | Risk of document number race condition (ADR-002) | +| Create or supersede an ADR unilaterally | Architecture decisions require team consensus and review process | +| Add new columns to production tables without schema review | Must update Data Dictionary + downstream queries simultaneously | + --- ## 📐 TypeScript Rules & Coding Standards @@ -304,36 +350,197 @@ const value = c.publicId; // "019505a1-7c3e-7000-8000-abc123def456" 3. Add regression test if logic changed 4. Verify no forbidden patterns introduced +### 🟣 Specialized Work — ADR-021, AI Integration, Complex Logic + +**MUST complete:** + +1. **Domain Knowledge Check** - Read relevant ADRs (ADR-021, ADR-023/023A) +2. **Pattern Verification** - Check existing implementations in codebase +3. **Specialized Requirements** - Follow domain-specific patterns +4. **Complex Logic Testing** - Multi-scenario test coverage +5. **Performance Validation** - Load testing if applicable + +**For ADR-021 Integration:** + +- Read ADR-021 - Integrated workflow & step attachments +- Check ADR-001 - Unified workflow engine patterns +- Verify WorkflowEngineService - Polymorphic instance handling +- Add workflow fields - Expose workflowInstanceId, workflowState, availableActions +- Include IntegratedBanner - Frontend workflow lifecycle display +- Test workflow transitions - State changes and action validation + +**For AI Integration (ADR-023/023A):** + +- Verify AI boundary enforcement - No direct DB/storage access +- Check BullMQ 2-queue setup - ai-realtime + ai-batch +- Validate Qdrant multi-tenancy - projectPublicId filter required +- Test human-in-the-loop validation workflows +- Audit AI interaction logging + +**Expected output:** + +- Backend services expose specialized context fields +- Frontend components use domain-specific patterns +- Complex state management with proper validation +- Performance metrics within acceptable thresholds +- Comprehensive test coverage for edge cases + --- ## 🎯 Context-Aware Triggers When user asks about... check these files: -| Request | Files to Check | Expected Response | -| ----------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------- | -| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | -| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases-and-rules.md` | RHF+Zod + TanStack Query + Thai comments | -| "เพิ่ม field ใหม่" | `ADR-009`, `03-01-data-dictionary.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity | -| "ตรวจสอบ UUID" | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor | -| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow | -| "ตรวจสอบ permission" | `lcbp3-v1.9.0-seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix | -| "deploy production" | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy | -| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns | -| "AI integration" | `ADR-023`, `ADR-023A` | AI boundary + 2-model stack + BullMQ queue policy | -| "Error handling" | `ADR-007` | Layered error classification + recovery | -| "File upload" | `ADR-016`, `05-02-backend-guidelines.md`, `03-Data-and-Storage/03-03-file-storage.md` | Two-phase upload → temp → commit; ClamAV + whitelist | -| "Notifications / Queue" | `ADR-008`, `05-02-backend-guidelines.md` | BullMQ job — never inline; check retry + dead-letter | -| "Add i18n / translate" | `05-08-i18n-guidelines.md` | i18n keys only — no hardcoded text | -| "Workflow / DSL" | `ADR-001`, `01-03-modules/01-03-06-unified-workflow.md` | DSL state machine + WorkflowEngineService | -| "Document numbering" | `ADR-002`, `01-02-business-rules/01-02-02-doc-numbering-rules.md` | Redis Redlock + DB optimistic lock (double-lock) | +| Request | Status | Files to Check | Expected Response | +| --------------------------- | ------ | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| "สร้าง API ใหม่" | ✅ | `05-02-backend-guidelines.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | +| "แก้ฟอร์ม frontend" | ✅ | `05-03-frontend-guidelines.md`, `01-06-edge-cases-and-rules.md` | RHF+Zod + TanStack Query + Thai comments | +| "เพิ่ม field ใหม่" | ✅ | `ADR-009`, `03-01-data-dictionary.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity | +| "ตรวจสอบ UUID" | ✅ | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor | +| "สร้าง migration" | ✅ | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow | +| "ตรวจสอบ permission" | ✅ | `lcbp3-v1.9.0-seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix | +| "deploy production" | ✅ | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy | +| "เพิ่ม test" | ✅ | `05-04-testing-strategy.md` | Coverage goals + test patterns | +| "AI integration" | ✅ | `ADR-023`, `ADR-023A` | AI boundary + 2-model stack + BullMQ queue policy | +| "Error handling" | ✅ | `ADR-007` | Layered error classification + recovery | +| "File upload" | ✅ | `ADR-016`, `05-02-backend-guidelines.md`, `03-Data-and-Storage/03-03-file-storage.md` | Two-phase upload → temp → commit; ClamAV + whitelist | +| "Notifications / Queue" | ✅ | `ADR-008`, `05-02-backend-guidelines.md` | BullMQ job — never inline; check retry + dead-letter | +| "Add i18n / translate" | ✅ | `05-08-i18n-guidelines.md` | i18n keys only — no hardcoded text | +| "Workflow / DSL" | ✅ | `ADR-001`, `01-03-modules/01-03-06-unified-workflow.md` | DSL state machine + WorkflowEngineService | +| "Document numbering" | ✅ | `ADR-002`, `01-02-business-rules/01-02-02-doc-numbering-rules.md` | Redis Redlock + DB optimistic lock (double-lock) | +| "ตรวจสอบ Workflow" | ✅ | `01-06-edge-cases-and-rules.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร | +| "Transmittal submit" | 📋 | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | submit() with EC-RFA-004 validation | +| "Circulation reassign" | 📋 | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | reassignRouting() with EC-CIRC-001 | +| "สร้าง workflow ใหม่" | 📋 | `ADR-001`, `ADR-021`, `specs/200-fullstacks/203-unified-workflow-engine/` | DSL workflow definition + WorkflowEngineService setup | +| "ตรวจสอบ AI boundary" | ✅ | `ADR-023`, `ADR-023A` | Verify Ollama isolation + BullMQ queues + Qdrant projectPublicId filter | +| "จัดการ document numbering" | ✅ | `ADR-002`, `specs/03-Data-and-Storage/03-04-document-numbering.md` | Redis Redlock + template system + preview/override workflows | +| "Audit ความปลอดภัย" | ✅ | `ADR-016`, `ADR-019`, `ADR-023`, `ADR-023A` | ตรวจสอบ UUID pattern, CASL Guard, AI Boundary และ Qdrant multi-tenancy | +| "แก้ bug / bugfix" | ✅ | `.agents/workflows/bugfix.md`, `error-catalog.md` | ใช้ bugfix workflow สำหรับเคสที่สาเหตุชัดเจน | +| "ตรวจแอปจริง" | ✅ | `.windsurf/workflows/check-real-app.md` | ตรวจ endpoint/UI/console หลัง build pass — No Fake Evidence | +| "งานค้าง / resume" | ✅ | `.windsurf/workflows/resume-pending-work.md` | อ่าน checkpoint เดิม → ตรวจ build → วางแผนต่อโดยไม่ทำงานซ้ำ | + +**Status Legend:** + +- ✅ Implemented and verified +- 📋 Spec exists, implementation in progress +- 🔄 In development +- ❌ Not yet started + +## 🛠️ Final Checklists + +### 🔴 Tier 1 — CRITICAL (CI BLOCKER) + +**Security & Data Integrity:** + +- [ ] **UUID Strategy:** Use `publicId` only, no `parseInt()` on UUID values (ADR-019) +- [ ] **RBAC Guards:** CASL guards on all endpoints, 4-level matrix checked (ADR-016) +- [ ] **AI Boundary:** Ollama isolation, no direct DB/storage access (ADR-023/023A) +- [ ] **Input Validation:** Zod (frontend) + class-validator (backend DTO) +- [ ] **File Upload:** Two-phase (Temp → Commit), ClamAV scan, whitelist enforced +- [ ] **Idempotency:** `Idempotency-Key` header validated on critical POST/PUT/PATCH +- [ ] **Error Handling:** Layered classification (Validation, Business, System) with user-friendly messages (ADR-007) + +**Code Quality:** + +- [ ] No `any` types in TypeScript (use interfaces/types) +- [ ] No `console.log` in committed code (use NestJS Logger) +- [ ] Database schema verified before writing queries +- [ ] SQL injection prevention checked + +### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) + +**Architecture & Standards:** + +- [ ] **File header `// File: path/filename` present** +- [ ] **`// Change Log` section included at top** +- [ ] **JSDoc present for public classes and methods** +- [ ] **One main export per file** +- [ ] Business logic in services, thin controllers pattern +- [ ] Schema changes via SQL directly (ADR-009) +- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) +- [ ] Cache invalidation when data modified +- [ ] Naming conventions followed + +**Localization & Comments:** + +- [ ] Business logic comments in Thai, technical comments in English +- [ ] Code identifiers in English +- [ ] i18n keys used instead of hardcode text + +### 🟢 Tier 3 — SPECIALIZED WORK + +**Workflow Integration (ADR-021):** + +- [ ] WorkflowEngineService polymorphic handling verified +- [ ] Workflow fields exposed (workflowInstanceId, workflowState, availableActions) +- [ ] IntegratedBanner + WorkflowLifecycle components used +- [ ] Workflow transitions tested with state validation +- [ ] RBAC guards on workflow actions + +**AI Integration (ADR-023/023A):** + +- [ ] **BullMQ Usage:** Background jobs via BullMQ, no inline processing +- [ ] **Qdrant Multi-tenancy:** `projectPublicId` filter enforced +- [ ] **Human-in-the-loop:** AI outputs validated before use +- [ ] **Audit Logging:** All AI interactions logged to `ai_audit_logs` +- [ ] **2-Model Stack:** gemma4:e4b Q8_0 + nomic-embed-text verified + +**Performance & Complex Logic:** + +- [ ] Performance metrics within targets (P95 ≤ 5s for ≤10MB uploads) +- [ ] Multi-scenario test coverage for edge cases +- [ ] Load testing completed if applicable +- [ ] Complex state management properly validated + +### 🔵 Tier 4 — GUIDELINES + +**Code Style:** + +- [ ] Code formatting follows Prettier rules +- [ ] Comment completeness where helpful +- [ ] Minor optimizations considered but not required + +--- + +## Agent skills + +### Issue tracker + +Issues live in the self-hosted Gitea repo at git.np-dms.work:2222. See `docs/agents/issue-tracker.md`. + +### Triage labels + +Default label vocabulary (no custom mapping). See `docs/agents/triage-labels.md`. + +### Domain docs + +Single-context repo with domain documentation in `specs/`. See `docs/agents/domain.md`. + +--- + +## 📚 Full Documentation + +This file is a **quick reference**. For detailed information: + +- **Architecture:** `specs/02-architecture/` +- **Requirements:** `specs/01-requirements/` +- **Data & Storage:** `specs/03-Data-and-Storage/` (canonical schema + `deltas/` incremental SQL per ADR-009) +- **Engineering Guidelines:** `specs/05-Engineering-Guidelines/` +- **Decision Records:** `specs/06-Decision-Records/` +- **Infrastructure:** `specs/04-Infrastructure-OPS/` +- **Agent Skill Pack:** `.agents/skills/` (NestJS/Next.js rules + 21 Speckit & Utility skills) +- **Helper Scripts:** `.agents/scripts/{bash,powershell}/` (audit, validate, prerequisites, setup-plan) --- ## 🔄 Change Log -| Version | Date | Changes | Updated By | -| ------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | -| 1.9.3 | 2026-05-16 | Sync with AGENTS.md v1.9.3 — ADR-023A updates, schema v1.9.0 path corrections, CaslModule import fix for DelegationModule, console.log → Logger migration | Windsurf AI | -| 1.9.0 | 2026-05-13 | Sync with AGENTS.md v1.9.0 — TS Standards, Hybrid Specs organization | Windsurf AI | -| 1.8.5 | 2026-04-22 | Legacy version | Human Dev | +| Version | Date | Changes | Updated By | +| ------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | +| 1.9.5 | 2026-05-18 | **Grill-with-Docs Session:** Domain terminology clarified (Correspondence = all doc types), Tier 3: SPECIALIZED WORK added, Context-Aware Triggers with Status column, Tier-specific Final Checklists | Windsurf AI | +| 1.9.4 | 2026-05-16 | Added ADR-015 Release Strategy to Key Spec Files table (Blue-Green deployment + release gates) | Human Dev | +| 1.9.3 | 2026-05-15 | ADR-023A: Model revision — gemma4:9b+Typhoon→gemma4:e4b Q8_0 (2-model stack), BullMQ 2-queue split, RAG full-doc embed, OCR auto-detect, n8n→DMS API boundary, QdrantService multi-tenancy contract | Windsurf AI | +| 1.9.2 | 2026-05-14 | Consolidated legacy AI ADRs (017, 017B, 018, 020, 022) into master ADR-023: Unified AI Architecture | Antigravity AI | +| 1.9.1 | 2026-05-13 | Added `bugfix` workflow and skill (migrated and improved from `docs/bugfix.md`) | Windsurf AI | +| 1.9.0 | 2026-05-03 | Integrated Global TypeScript Coding Standards (Headers, JSDoc, Thai comments, Single Export, No blank lines) | Windsurf AI | +| 1.8.5 | 2026-04-22 | Legacy version | Human Dev | diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 00000000..c923a0fa --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,147 @@ +# LCBP3 / NAP-DMS Context + +ระบบจัดการเอกสารงานก่อสร้าง (DMS) สำหรับโครงการ LCBP3 — เน้นการควบคุม Correspondence, RFA, Transmittal, Drawing พร้อมผู้ช่วย AI แบบ on-premises ที่ทำงานภายใต้ Workflow Engine กลางและขอบเขต AI ที่เข้มงวด (ADR-023A) + +## Language + +### Documents + +**Correspondence**: +ซองจดหมาย/เอกสารทุกประเภทที่หมุนเวียนในโครงการ เป็น parent ของ RFA / Transmittal / Memo +_Avoid_: Letter, Communication, Document (generic) + +**RFA** (Request For Approval): +Correspondence ประเภทขออนุมัติ มี revision และอ้างอิง Drawing Revision ผ่าน `rfa_items` +_Avoid_: Approval Request, Submit for Approval + +**Transmittal**: +Correspondence ที่ใช้ส่งมอบเอกสาร/แบบ ไม่ใช่จดหมายปะหน้า +_Avoid_: Delivery Note, Cover Letter + +**Shop Drawing**: +แบบที่ผู้รับเหมาจัดทำเพื่อขออนุมัติก่อนก่อสร้าง +_Avoid_: Construction Drawing + +**Contract Drawing**: +แบบต้นฉบับตามสัญญา ไม่ใช่ Shop Drawing +_Avoid_: Design Drawing, Blueprint + +### Workflow + +**Workflow Engine**: +State machine กลาง DSL-based (ADR-001) — authority เดียวของการเปลี่ยน state ของทุก Correspondence +_Avoid_: Approval Flow, Process Engine, RFA status flow (เป็นเพียง definition หนึ่ง) + +**Workflow Definition**: +Row ใน `workflow_definitions` ระบุ DSL ของ flow เช่น `RFA_FLOW_V1`, `CORRESPONDENCE_FLOW_V1` +_Avoid_: Approval logic, Hardcoded flow + +**Workflow Instance**: +Row ใน `workflow_instances` = สถานะปัจจุบันของเอกสารหนึ่งฉบับ — source of truth ของ state +_Avoid_: Status, Stage (ใช้ภายใน DSL ได้แต่ห้ามแทน instance) + +**Workflow Transition**: +การเปลี่ยน state ที่บันทึกใน `workflow_histories` พร้อม `actor_user_id` (มนุษย์เท่านั้น) +_Avoid_: Auto-execute, AI-driven approval + +### AI + +**AI Document Assistant**: +ผู้ช่วยที่ให้ Insight + Suggest + Notify โดยไม่เปลี่ยน state ของเอกสารเอง (ADR-023A) +_Avoid_: AI Document Controller, AI Agent, Autonomous Agent + +**AI Gateway**: +NestJS module ที่เป็นจุดเข้าเดียวของทุกคำขอ AI — enforce CASL + tenant scope ก่อนส่งงานเข้า BullMQ +_Avoid_: AI Service (generic), Tool Layer + +**Server-side Intent**: +Enum ของคำขอที่ AI Gateway รองรับ (เช่น `RAG_QUERY`, `CLASSIFY_DOCUMENT`, `EXTRACT_METADATA`) — แทนที่ LLM function-calling +_Avoid_: Tool, LLM tool, LangChain tool + +**Document Chunk**: +Row ใน `ai_document_chunks` (MariaDB) เก็บ chunk text + metadata, ground truth สำหรับ re-embed +_Avoid_: ai_embeddings, embedding row + +**Vector Point**: +Point ใน Qdrant — เก็บแค่ `chunk_public_id`, vector, และ payload `{ project_public_id, document_public_id, chunk_index }` +_Avoid_: Embedding (ambiguous), Vector record + +**RAG Query**: +Pipeline: embed query → `QdrantService.search(projectPublicId, vector)` → ดึง `chunk_text` จาก MariaDB → ส่งเข้า LLM พร้อม context +_Avoid_: Semantic search (overloaded), Vector search (incomplete) + +**OCR Service**: +Container สำเร็จรูป (opaque black box) เปิด HTTP API ให้ NestJS เรียก — ไม่มีโค้ด Python ใน repo, ทีมไม่ maintain runtime ภายใน +_Avoid_: Python sidecar, OCR microservice (ที่เรา maintain เอง) + +**Human-in-the-loop**: +ทุก AI suggestion ต้องผ่านการ accept/reject โดย user ก่อนกลายเป็น state change — บันทึกใน `ai_audit_logs` +_Avoid_: Auto-apply, AI auto-execute + +## Relationships + +- A **Correspondence** has a 1:1 specialization to **RFA** / **Transmittal** / etc. (table inheritance) +- A **RFA** has 1:N **RFA Revisions**, each linking to one or more **Shop Drawing Revisions** via `rfa_items` +- A **Workflow Instance** governs exactly one **Correspondence**; its current state is projected into entity columns (e.g. `rfa_revisions.rfa_status_code_id`) but **`workflow_instances` is the source of truth** +- A **Document Chunk** (MariaDB) has a 1:1 **Vector Point** in Qdrant via shared `chunk_public_id` (UUIDv7) +- An **AI Document Assistant** suggestion produces an `ai_audit_logs` row; if user accepts, it triggers a normal **Workflow Transition** (AI never writes the transition itself) +- **Qdrant queries MUST be filtered by `project_public_id`** — enforced at compile time by `QdrantService` signature + +## AI authority scope (resolved) + +| Scope | Allowed? | Mechanism | +|-------|----------|-----------| +| Read-only insight (summarise, explain) | ✅ | AI Gateway → service → CASL-guarded query | +| Suggest action (UI shows button) | ✅ | Response shape `{ suggestedAction, confidence, reasoning }` | +| Auto-trigger side-effects (notify, alert, comment) | ✅ | BullMQ job (ADR-008); MUST NOT change workflow state | +| Auto-execute workflow transition | ❌ | Forbidden Tier 1 — every transition needs human `actor_user_id` | + +## Upload pipeline (resolved) + +| Stage | Mode | Queue | Notes | +|-------|------|-------|-------| +| 1. Upload → **temp** + return `tempUploadId` | Sync | — | <1s | +| 2. ClamAV scan + MIME whitelist | Sync | — | block ก่อน commit (ADR-016) | +| 3. User commit (metadata + ย้าย permanent) | Sync | — | สร้าง `documents` row, ใช้ `Idempotency-Key` | +| 4. **Classification/Tagging** (3 pages แรก) | Async | `ai-realtime` | suggest metadata; user accept/reject (human-in-the-loop) | +| 5. **RAG Embedding** (full doc; OCR ถ้า text-layer < 100 chars/page) | Async | `ai-batch` | trigger AUTO หลัง commit, parallel กับ stage 4 | +| 6. Qdrant upsert + `ai_document_chunks.embedded_at = NOW()` | Async | (worker) | gap = DB full-text fallback | + +**กฎ:** +- ❌ ห้าม OCR/embed ใน HTTP request handler +- ✅ BullMQ `jobId = chunk_public_id` (UUIDv7) กัน duplicate +- ✅ Embed fail → graceful degrade (เอกสารยังใช้งานได้, AI feature ลด) +- ✅ Revision ใหม่ → chunks เก่า mark `superseded_at`, **ไม่ลบ** vector +- ✅ Frontend ใช้ `AiStatusBanner` แสดง progress + +## Example dialogue + +> **Dev:** "AI สรุป **RFA** revision นี้ให้หน่อย แล้วเปลี่ยน status เป็น approved เลย" +> **Domain expert:** "ไม่ได้ — AI สรุปได้ (read-only insight) และเสนอ 'ควร approve เพราะ…' ได้ (suggest action) แต่การเปลี่ยน state ต้องผ่าน user กดปุ่มเอง ระบบจะเรียก `WorkflowService.transition()` ซึ่งบันทึก `actor_user_id` เป็นมนุษย์ใน `workflow_histories`" + +> **Dev:** "งั้น **Tool Layer** ใน plan เก่าที่ให้ LLM เรียก `get_rfa(id)` ใช้ได้ไหม" +> **Domain expert:** "ไม่ใช่ tool ของ LLM — เป็น **Server-side Intent** ที่ AI Gateway แปลงเป็น service call ภายใต้ CASL + `projectPublicId` scope LLM แค่รับ context ที่ pre-fetched มาแล้ว" + +## Identifier rules (ADR-019, AI subsystem) + +| Boundary | Identifier ที่ใช้ | +|----------|-------------------| +| API (FE ↔ AI Gateway) | `publicId` (UUIDv7 string) เท่านั้น; INT `id` มี `@Exclude()` | +| Server-side Intent payload | `*PublicId` strings; service แปลงเป็น INT FK ภายใน | +| LLM context (prompt) | `publicId` + business code (`rfa_number`, `drawing_code`) ห้ามเห็น INT | +| Qdrant payload | `project_public_id`, `document_public_id`, `chunk_public_id` | +| `ai_document_chunks` internals | INT FK ใช้ได้ภายใน DB; identity ที่ expose = `chunk_public_id BINARY(16)` | +| Business codes (e.g. `drawing_code = "A-101"`) | รับเป็น input ได้ แต่ resolve → `publicId` ก่อน query | + +**Forbidden (Tier 1 CI blocker):** +- `parseInt(<*PublicId>)`, `Number(<*PublicId>)`, `+<*PublicId>` +- `publicId ?? id ?? ''` fallback chain +- DTO ที่มีทั้ง `{ id, uuid, publicId }` + +## Flagged ambiguities + +- **"approval logic"** ในเอกสารเก่าใช้คาบเกี่ยวระหว่าง `rfa_approve_codes` (business outcome เช่น 1A/1B) กับ `workflow_definitions` (state transition rules) — resolved: เป็นคนละสิ่ง +- **"ai_embeddings"** vs **"ai_document_chunks"** — resolved: ใช้ `ai_document_chunks` (metadata + text) + Qdrant (vector only); ห้ามเก็บ vector ใน MariaDB +- **"Tool Layer"** ในเอกสาร AI — resolved: ไม่ใช่ LLM-callable tools, เป็น **Server-side Intents** ที่ NestJS controlใน AI Gateway +- **"AI = Document Controller"** — resolved: ใช้ **AI Document Assistant** (Suggest + Insight) แทน เพื่อกัน scope creep ไปทาง autonomous agent +- **OpenRAG vs ADR-023A** — `specs/03-Data-and-Storage/03-07-OpenRAG.md` ระบุ Elasticsearch + dense_vector ซึ่งขัดกับ ADR-023A (Qdrant + nomic-embed-text) — **ยังไม่ resolve**, ต้องตัดสินใจในรอบถัดไป diff --git a/docs/AI Specs/Quizzes.md b/docs/AI Specs/Quizzes.md new file mode 100644 index 00000000..73e9b0c8 --- /dev/null +++ b/docs/AI Specs/Quizzes.md @@ -0,0 +1,421 @@ +🧠 🎯 เป้าหมาย: AI DMS (Document Management System อัจฉริยะ) + +> จาก “เก็บเอกสาร” → กลายเป็น “ผู้ช่วยควบคุมเอกสาร” + +--- + +🏗️ 1. Architecture ภาพรวม + +[User] +↓ +(Web UI / Chat UI) +↓ +AI Agent Layer ← (หัวใจ) +↓ + +| RAG Engine (ค้นหาเอกสาร) +| Workflow Engine (RFA logic) +| Tool Layer (DB / File / API) + +↓ +[Database + File Storage] + +--- + +🔥 2. Core Components (ต้องมี) + +2.1 AI Agent (สมอง) + +ใช้แนวคิดจาก: + +LangChain / OpenClaw / CrewAI + +💡 ทำอะไร: + +เข้าใจคำถาม user + +ตัดสินใจว่าจะ: + +query DB + +search document + +run workflow + + +--- + +2.2 RAG System (ค้นหาเอกสาร) + +💡 ใช้: + +vector DB (เช่น Qdrant / Chroma) + +💡 ทำอะไร: + +search PDF / Drawing / Spec + +ตอบคำถามจาก content + +👉 use case: + +“Drawing A-101 revision ล่าสุดคืออะไร” + +“RFA นี้เกี่ยวข้องกับ drawing ไหน” + + +--- + +2.3 Tool Layer (สำคัญมาก) + +AI จะไม่เก่งถ้าไม่มี tools + +tools ที่ต้องมี: + +get_rfa(id) + +get_drawings_by_rfa(rfa_id) + +get_latest_revision(drawing_code) + +search_documents(query) + +get_transmittal_history() + +👉 ตรงนี้ = bridge ระหว่าง AI กับ DB จริงของคุณ + + +--- + +2.4 Workflow Engine (logic ธุรกิจ) + +💡 ไม่ให้ AI มั่ว + +เช่น: + +RFA status flow + +approval logic + +revision control + +👉 AI = “ช่วยคิด” +👉 workflow = “ของจริง” + + +--- + +2.5 File Storage + +เก็บไฟล์จริง (PDF, DWG) + +version control + +naming convention + +👉 ตรงกับ backlog คุณข้อ 9 พอดี + + +--- + +⚙️ 3. Database Design (ต่อยอดของเดิมคุณ) + +คุณมีอยู่แล้ว: + +RFAs + +Drawings + +Revisions + +👉 เพิ่ม: + +🧩 ai_embeddings + +document_id + +chunk_text + +vector + +🧩 ai_logs + +user_query + +agent_decision + +tool_used + +🧩 ai_tasks (optional) + +background job + +document indexing + + +--- + +🤖 4. AI Use Cases (ของจริงที่ควรทำ) + +🔎 1. Smart Search + +> “ขอ drawing structural ล่าสุดของ zone B” + + + +AI: + +เข้าใจ intent + +query DB + RAG + + +--- + +📄 2. Document QA + +> “สรุป spec นี้” + + + +AI: + +อ่าน PDF + +summarize + + +--- + +🔗 3. Relationship Mapping + +> “RFA นี้เกี่ยวกับ drawing อะไร” + + + +AI: + +join: + +rfa → drawing → revision + + +--- + +📊 4. Timeline Analysis + +> “RFA นี้ delay เพราะอะไร” + + + +AI: + +วิเคราะห์ revision timeline + + +--- + +🧠 5. Auto Classification + +upload file → AI tag: + +type + +discipline + +revision + + +--- + +⚠️ 6. Alert / Assistant + +“Drawing นี้ outdated” + +“RFA ใกล้ deadline” + + +--- + +🧩 5. UI Design (สำคัญมาก) + +5.1 Hybrid UI + +Table (DataTables) + +Chat (AI assistant) + +[ Table RFAs ] | [ AI Chat ] +| > RFA ล่าสุดคืออะไร +| > Drawing ไหนยังไม่ approve + +👉 best of both worlds + + +--- + +5.2 Drawing Page (โคตรสำคัญ) + +แสดง: + +revision history + +related RFAs + +AI summary + + +--- + +⚡ 6. Tech Stack (แนะนำตรงๆ) + +Backend + +PHP (ของเดิมคุณ) + +Python (AI service) + +AI Layer + +LangChain หรือ custom agent + +Ollama (local) หรือ OpenAI + +Vector DB + +Qdrant (แนะนำ) + +Frontend + +DataTables (ตาม backlog) + +Chat UI + + +--- + +🔥 7. Flow การทำงานจริง + +📥 Upload Drawing + +1. user upload PDF + + +2. system: + + + +extract text (OCR) + +chunk + +embed → vector DB + +3. AI tag metadata + + + + +--- + +🔎 Query + +user: + +> “drawing ล่าสุดของ contract นี้” + + + +AI: + +1. เข้าใจ intent + + +2. call tool: + + + +get_drawings(contract_id) + +3. filter revision ล่าสุด + + +4. ตอบ + + + + +--- + +🧠 8. Insight สำคัญ (อย่าพลาด) + +❌ อย่าทำแบบนี้ + +ให้ AI query DB ตรงๆ + +ให้ AI ตัดสินใจ workflow + +✅ ต้องทำแบบนี้ + +AI → call function (tool) + +system → validate logic + + +--- + +🚀 9. Roadmap (ทำจริง) + +Phase 1 (2–4 สัปดาห์) + +AI chat + query DB + +basic tools + +Phase 2 + +RAG (search document) + +embedding + +Phase 3 + +automation + +alert + +classification + + +--- + +🎯 10. ถ้าจะทำให้ “โหดจริง” + +👉 ultimate version: + +AI = Document Controller + +auto check: + +revision mismatch + +missing approval + +outdated drawing + + +--- + +💡 สรุปสั้น + +AI DMS = + +> “AI + Workflow + Document + Database” + + +ไม่ใช่แค่ chatbot + + +--- + +จากเนื้อหาข้างบน เทียบกับ repo ของผม ขอสรุป แบบละเฮียกทีละข้อ diff --git a/docs/AI Specs/deepseek-answer.md b/docs/AI Specs/deepseek-answer.md new file mode 100644 index 00000000..08974c3e --- /dev/null +++ b/docs/AI Specs/deepseek-answer.md @@ -0,0 +1,189 @@ +จากการวิเคราะห์ repo `lcbp3` อย่างละเอียด เทียบกับ blueprint AI DMS ของคุณแบบข้อต่อข้อ: + +--- + +## 🔍 สรุปเทียบ Blueprint AI DMS กับ Repo `lcbp3` + +--- + +### 🏗️ 1. Architecture ภาพรวม + +| Blueprint | Repo `lcbp3` | สถานะ | +|---|---|---| +| Web UI / Chat UI | ✅ Next.js 16.2.0 + shadcn/ui + `RagChatWidget.tsx` | **มีแล้ว** | +| AI Agent Layer | ✅ `AiService` + `AiRagService` + `AiQueueService` — ใช้ **n8n + Ollama** pipeline ตาม ADR-023 | **มีแล้ว** (คนละ approach) | +| RAG Engine | ✅ `AiRagService` + `AiQdrantService` (Qdrant vector DB, project-isolated) | **มีแล้ว** | +| Workflow Engine | ✅ ADR-021 Unified Workflow Engine (DSL-based สำหรับ Correspondences, RFAs, Circulations) | **มีแล้ว** | +| Tool Layer | ⚠️ มี AI services (embedding, OCR, Ollama, Qdrant, migration) แต่ไม่มี tool functions ที่ blueprint ระบุ (เช่น `get_rfa(id)`, `get_drawings_by_rfa(rfa_id)`) ใน AI module | **บางส่วน** | +| DB + File Storage | ✅ MariaDB 11.8 + Two-Phase File Storage (Multer + ClamAV) | **มีแล้ว** | + +**💡 ความเห็น:** โครงสร้างพื้นฐานตรงตาม blueprint ~85% แต่ AI Agent Layer ใช้ n8n+Ollama แทน LangChain/CrewAI ที่ blueprint แนะนำ ซึ่งเป็น architectural decision ที่ **ถูกต้องแล้ว** สำหรับบริบทของคุณ (local deployment บน QNAP, เน้น privacy, no external API) — ADR-023 รวม ADR-017, 017B, 018, 020, 022 เข้าด้วยกันเป็น Unified AI Architecture + +--- + +### 🔥 2. Core Components (ต้องมี) + +#### 2.1 AI Agent (สมอง) +| Blueprint แนะนำ | Repo จริง | หมายเหตุ | +|---|---|---| +| LangChain / OpenClaw / CrewAI | **n8n + Ollama** | ADR-023 เลือก n8n workflow orchestration + Ollama local LLM inference — pragmatic choice สำหรับ QNAP NAS ที่มี RAM 32GB | + +**💡 ความเห็น:** n8n เป็น low-code workflow automation ที่ stable กว่า LangChain สำหรับ production use case นี้ และ Ollama รองรับการรัน local LLM บน CPU ได้ดี จุดที่ยังขาดคือ **agentic decision-making** — ตอนนี้ AI ยังไม่สามารถ "ตัดสินใจว่าจะ query DB / search document / run workflow" ได้เอง ต้องต่อยอดจาก n8n workflow + AI services ที่มีอยู่ + +#### 2.2 RAG System (ค้นหาเอกสาร) +| Blueprint | Repo | สถานะ | +|---|---|---| +| Vector DB (Qdrant/Chroma) | ✅ **Qdrant** — `AiQdrantService` ใช้ `@qdrant/js-client-rest`, collection `lcbp3_vectors`, 768-dim vectors, Cosine distance, **project-isolated** payload filter | **ครบ** | +| Search PDF/Drawing/Spec | ✅ `AiRagService` — query ผ่าน Ollama + Qdrant, BullMQ-backed async pipeline, Redis caching, TTL 5 นาที, FR-009 (1 active job per user) | **ครบ** | +| Embedding | ✅ `embedding.service.ts` + Ollama embed model (`nomic-embed-text`) | **มีแล้ว** | +| Chunking | ⚠️ มี `ai-ingest.service.ts` สำหรับ document ingestion แต่ไม่เห็น chunking strategy ชัดเจน | **ต้องตรวจสอบ** | +| Use case: "Drawing A-101 revision ล่าสุด" | ❌ ยังไม่เห็น integration ระหว่าง RAG search ↔ drawing module โดยตรง | **ยังไม่มี** | + +#### 2.3 Tool Layer +| Blueprint Tool | Repo | สถานะ | +|---|---|---| +| `get_rfa(id)` | ❌ ไม่มีใน AI module (มีใน RFA module แต่ AI เรียกตรงไม่ได้) | **ต้องพัฒนา** | +| `get_drawings_by_rfa(rfa_id)` | ❌ ไม่มี cross-module tool | **ต้องพัฒนา** | +| `get_latest_revision(drawing_code)` | ❌ ไม่มีใน AI module | **ต้องพัฒนา** | +| `search_documents(query)` | ✅ มีผ่าน RAG + Elasticsearch | **มีแล้ว** | +| `get_transmittal_history()` | ❌ ไม่มี | **ต้องพัฒนา** | + +**💡 Insight:** ตรงนี้คือ **gap สำคัญที่สุด** — blueprint บอกว่า tool layer คือ "bridge ระหว่าง AI กับ DB จริง" แต่ repo ตอนนี้ AI module แยกขาดจาก business modules (RFA, Drawing, Transmittal) ตาม ADR-018 AI Boundary Policy (ต่อมาถูกรวมเข้า ADR-023) ที่กำหนดว่า **"Ollama Isolation มี No Direct DB/Storage Access"** — นี่คือ security boundary ที่ดี แต่ต้องสร้าง tool functions เป็น bridge จริงๆ + +#### 2.4 Workflow Engine +| Blueprint | Repo | สถานะ | +|---|---|---| +| RFA status flow | ✅ `workflow-engine` module + `rfas` components | **มีแล้ว** | +| Approval logic | ✅ ADR-021 Integrated Context Workflow | **มีแล้ว** | +| Revision control | ✅ Drawing module มี revision tracking | **มีแล้ว** | + +#### 2.5 File Storage +| Blueprint | Repo | สถานะ | +|---|---|---| +| เก็บไฟล์จริง (PDF, DWG) | ✅ Two-Phase File Storage, Multer + ClamAV virus scanning | **มีแล้ว** | +| Version control | ✅ Schema v1.8.0 รองรับ | **มีแล้ว** | +| Naming convention | ✅ Document Numbering (ADR-002, Double-lock mechanism) | **มีแล้ว** | + +--- + +### ⚙️ 3. Database Design + +| Blueprint Suggestion | Repo | สถานะ | +|---|---|---| +| `ai_embeddings` (document_id, chunk_text, vector) | ✅ Qdrant เก็บ vectors แยกจาก MariaDB, collection `lcbp3_vectors` พร้อม payload (project_public_id, public_id) | **มีแล้ว** (คนละ implementation) | +| `ai_logs` (user_query, agent_decision, tool_used) | ✅ `ai-audit-log.entity.ts` + `AuditLog` entity — บันทึก AI jobs, callbacks, results | **มีแล้ว** | +| `ai_tasks` (background job, indexing) | ✅ BullMQ queues (`ai-realtime`, `ai-batch`) + `MigrationLog` entity | **มีแล้ว** | +| RFAs, Drawings, Revisions | ✅ มีครบทุก module | **มีแล้ว** | + +--- + +### 🤖 4. AI Use Cases (ของจริง) + +| Use Case | สถานะใน Repo | +|---|---| +| **1. Smart Search** — "ขอ drawing structural ล่าสุดของ zone B" | ⚠️ RAG search มีแล้ว + Elasticsearch แต่ยังไม่รวม intent understanding + cross-module query | +| **2. Document QA** — "สรุป spec นี้" | ⚠️ `AiRagService` รองรับ Q&A บน document content ผ่าน Ollama — มีพื้นฐานแล้ว | +| **3. Relationship Mapping** — "RFA นี้เกี่ยวกับ drawing อะไร" | ❌ ยังไม่มี cross-module relationship query | +| **4. Timeline Analysis** — "RFA นี้ delay เพราะอะไร" | ❌ ยังไม่มี | +| **5. Auto Classification** — upload file → AI tag | ✅ `ai-ingest.service.ts` + metadata extraction + AI Suggestion (`POST /ai/suggest`) | +| **6. Alert / Assistant** — "Drawing นี้ outdated", "RFA ใกล้ deadline" | ⚠️ มี `reminder` module + BullMQ queues แต่ยังไม่ integrated กับ AI | + +--- + +### 🧩 5. UI Design + +| Blueprint | Repo | สถานะ | +|---|---|---| +| Hybrid UI (Table + Chat) | ✅ DataTables-style + `RagChatWidget.tsx` + `rag-search-bar.tsx` + `rag-result-card.tsx` | **มีแล้ว** | +| Drawing Page (revision history, related RFAs, AI summary) | ✅ Drawing module + revision tracking + AI components (`document-comparison-view.tsx`) | **มีแล้ว** | +| AI Status Banner | ✅ `AiStatusBanner.tsx` | **มีแล้ว** | + +--- + +### ⚡ 6. Tech Stack + +| Blueprint แนะนำ | Repo จริง | หมายเหตุ | +|---|---|---| +| **PHP** (ของเดิมคุณ) | **NestJS 11 (TypeScript)** | คุณเปลี่ยน stack ไปแล้ว — repo เป็น TypeScript 87.5% | +| **Python** (AI service) | **TypeScript + n8n + Ollama** | ไม่มี Python service แยก — AI logic อยู่ใน NestJS module + n8n workflows | +| **LangChain** | **n8n + custom services** | Architectural decision ที่ pragmatic — n8n เสถียรกว่า LangChain สำหรับ production | +| **Qdrant** | ✅ `@qdrant/js-client-rest` | ตรงตาม blueprint | +| **Ollama** | ✅ Ollama บน QNAP NAS | ตรงตาม blueprint | +| **DataTables + Chat UI** | ✅ shadcn/ui + RagChatWidget | ตรงตาม blueprint | + +--- + +### 🔥 7. Flow การทำงานจริง + +**📥 Upload Drawing Flow:** +``` +User upload → Multer + ClamAV scan → Two-Phase File Storage → +ai-ingest.service (extract text, OCR, embed) → Qdrant upsert → AI tag metadata +``` +✅ มีครบตาม blueprint + +**🔎 Query Flow:** +``` +User: "drawing ล่าสุดของ contract นี้" → +RagChatWidget → AiRagService → Qdrant search → Ollama generate answer → +แสดงผลพร้อม citations +``` +⚠️ มี RAG search แต่ยังขาด tool call ไปยัง drawing/contract modules + +--- + +### 🧠 8. Insight สำคัญ — สิ่งที่ทำถูกแล้วและที่ต้องระวัง + +| หลักการ | Repo | คะแนน | +|---|---|---| +| ❌ อย่าให้ AI query DB ตรงๆ | ✅ ADR-023: Ollama Isolation, No Direct DB Access | **ดีมาก** | +| ❌ อย่าให้ AI ตัดสินใจ workflow | ✅ Workflow Engine (ADR-021) แยกจาก AI | **ดีมาก** | +| ✅ AI → call function (tool) | ⚠️ ยังไม่มี tool function layer เชื่อม AI ↔ business modules | **ต้องพัฒนา** | +| ✅ System → validate logic | ✅ Validation services, RBAC guards, Business Logic Guards (37 edge cases) | **ดีมาก** | + +--- + +### 🚀 9. Roadmap — สถานะเทียบ Blueprint + +| Blueprint Phase | Repo Status | +|---|---| +| **Phase 1:** AI chat + query DB + basic tools | ✅ v1.9.0 — `RagChatWidget` + RAG search + AI Suggestion endpoints | +| **Phase 2:** RAG + embedding | ✅ v1.9.2 — Qdrant collection, embedding service, RAG pipeline | +| **Phase 3:** Automation, alert, classification | 🔄 กำลังพัฒนา — AI Suggest, reminder module, n8n workflows | + +--- + +### 🎯 10. Ultimate Version — "AI = Document Controller" + +| ความสามารถ | สถานะ | +|---|---| +| Auto check revision mismatch | ❌ ยังไม่มี | +| Missing approval detection | ❌ ยังไม่มี | +| Outdated drawing alert | ❌ ยังไม่มี | + +--- + +## 💡 สรุปภาพรวม + +**repo `lcbp3` v1.9.2 ของคุณทำไปแล้ว ~70-80% ของ blueprint AI DMS** + +### ✅ สิ่งที่มีแล้ว (แข็งแรงมาก): +- **RAG System** — Qdrant + Ollama + BullMQ pipeline, project-isolated, production-ready +- **AI Chat UI** — `RagChatWidget` + search bar + result cards +- **Workflow Engine** — DSL-based, รองรับ RFA, Correspondence, Circulation +- **File Storage** — Two-phase + virus scanning + version control +- **AI Boundary** — Security isolation ที่ดี (Ollama ไม่แตะ DB โดยตรง) +- **Infrastructure** — Docker Compose hardened, Blue-Green Deploy, 0 vulnerabilities +- **Documentation** — 10/10 Gaps Closed, 23 ADRs, specs ครอบคลุมทุกมิติ + +### ❌ สิ่งที่ยังขาด (ตาม blueprint): +1. **Tool Layer** — ยังไม่มี tool functions เชื่อม AI กับ business modules (`get_rfa`, `get_drawings_by_rfa`, `get_latest_revision` ฯลฯ) — **นี่คือ gap ใหญ่สุด** +2. **Agentic Decision-Making** — AI ยังตอบได้เฉพาะ RAG search ยังตัดสินใจเองไม่ได้ว่าจะเรียก tool ไหน +3. **Cross-Module Relationship Mapping** — ยังไม่มี RFA ↔ Drawing ↔ Revision linkage ใน AI context +4. **Auto Document Controller** — ยังไม่ถึงขั้น AI ตรวจสอบ revision mismatch, missing approval อัตโนมัติ + +### 🎯 สิ่งที่ควรทำต่อ (Priority): +1. **สร้าง Tool Functions** ใน AI module ที่เป็น bridge ไปยัง RFA, Drawing, Transmittal modules — โดยคง security boundary ไว้ +2. **เพิ่ม Intent Routing** — ให้ AI รู้ว่าคำถามแบบไหนควรเรียก tool ไหน (ต่อยอดจาก n8n workflow ที่มี) +3. **Cross-Module Context** — inject RFA-Drawing-Revision relationships เข้า RAG context +4. **Alert Engine** — ต่อยอด reminder module + AI classification เพื่อแจ้งเตือนอัจฉริยะ diff --git a/docs/AI Specs/qwen-answer.md b/docs/AI Specs/qwen-answer.md new file mode 100644 index 00000000..a61068b7 --- /dev/null +++ b/docs/AI Specs/qwen-answer.md @@ -0,0 +1,294 @@ +# 🔍 เปรียบเทียบ: AI DMS Architecture Proposal vs. Repo จริง (lcbp3) + +> จากแผน "อยากได้" → เทียบกับ "ที่มีอยู่จริง" แบบละเฮียกทีละข้อ 🎯 + +--- + +## 🏗️ 1. Architecture ภาพรวม + +| ส่วนที่เสนอ | สถานะใน Repo | Gap / ข้อสังเกต | +|------------|-------------|---------------| +| **User → Web UI / Chat UI** | ✅ มี Next.js 16 + App Router | ✅ ตรงตามแผน แต่ยังไม่มี "Chat UI" แบบ Dedicated (มีแต่ Table + Form) | +| **AI Agent Layer** | 🟡 มี `.agents/` + `AGENTS.md` + n8n | ⚠️ เป็น "Agent Toolkit" สำหรับ Dev AI ช่วยเขียนโค้ด **ไม่ใช่** AI Agent ที่รันใน Production สำหรับ User | +| **RAG Engine** | ✅ มี ADR-022 (Superseded) → ADR-023 | ✅ มีสถาปัตยกรรม RAG แล้ว แต่ยังเป็น "แผน" ในเอกสาร ต้องดูการ Implement จริง | +| **Workflow Engine** | ✅ มี `workflow-engine/` module + ADR-001/021 | ✅ ตรงตามแผน 100% — DSL-based workflow + Integrated Context | +| **Tool Layer** | 🟡 มี Services ใน NestJS modules | ⚠️ Tools ยังเป็น "Internal API" ไม่ใช่ "Function Calling Interface" สำหรับ AI โดยตรง | +| **Database + Storage** | ✅ MariaDB 11.8 + Two-Phase File Storage | ✅ ตรงตามแผน + มี ClamAV + Redis Locking | + +👉 **สรุป**: โครงสร้างพื้นฐาน (Infrastructure) พร้อมมาก แต่ "AI Agent Layer" ที่ User คุยด้วยยังต้องพัฒนาเพิ่ม + +--- + +## 🔥 2. Core Components (ต้องมี) + +### 2.1 AI Agent (สมอง) + +| ที่เสนอ | ที่มีอยู่ | Gap | +|--------|----------|-----| +| LangChain / CrewAI | 🟡 ใช้ n8n + Ollama (ADR-023) | ⚠️ n8n เป็น Workflow Orchestrator **ไม่ใช่** Agent Framework แบบ LangChain | +| เข้าใจคำถาม → ตัดสินใจ → Call Tool | 🟡 มี "AI Boundary" (ADR-023) | ⚠️ ยังไม่มี "Intent Recognition Layer" ที่แยก Query → Tool Routing ชัดเจน | + +💡 **แนะนำ**: ถ้าอยากได้ Agent แบบ "ตัดสินใจเอง" อาจต้องเพิ่ม `ai-agent/` module ที่ใช้ LangGraph หรือ Custom Agent Loop + +--- + +### 2.2 RAG System (ค้นหาเอกสาร) + +| ที่เสนอ | ที่มีอยู่ | Gap | +|--------|----------|-----| +| Vector DB: Qdrant / Chroma | 🟡 มี ADR-023A ระบุใช้ `Qdrant` | ✅ มีในสถาปัตยกรรม แต่ต้องตรวจสอบว่า Deploy แล้วหรือยัง | +| Search PDF / Drawing / Spec | 🟡 มี Elasticsearch 9.3.4 | ⚠️ Elasticsearch เป็น **Keyword Search** ไม่ใช่ **Vector Search** — ต้องแยกกัน | +| Use case: "Drawing A-101 revision ล่าสุด" | 🟡 มี `drawing/` module + revision tracking | ✅ Data Model พร้อม แต่ต้องเพิ่ม "Natural Language → Query Translation" | + +💡 **จุดสำคัญ**: ต้องแยกให้ชัดระหว่าง: +- `Elasticsearch` → Full-text search (keyword) +- `Qdrant` → Vector search (semantic/RAG) + +--- + +### 2.3 Tool Layer (สำคัญมาก) ⭐ + +| Tool ที่เสนอ | ที่มีอยู่ (NestJS Service) | Gap | +|-------------|--------------------------|-----| +| `get_rfa(id)` | ✅ `RfaService.findOne()` | ✅ พร้อม แต่ต้องสร้าง "AI Tool Wrapper" | +| `get_drawings_by_rfa(rfa_id)` | 🟡 มี Relation ใน Schema | ⚠️ ต้องเขียน Service Method แยกสำหรับ AI Call | +| `get_latest_revision(drawing_code)` | ✅ มี `DrawingService.getLatestRevision()` | ✅ พร้อม | +| `search_documents(query)` | ✅ มี `SearchModule` (Elasticsearch) | ⚠️ ต้องเพิ่ม "Vector Search" endpoint สำหรับ RAG | +| `get_transmittal_history()` | ✅ มี `TransmittalService` | ✅ พร้อม | + +💡 **สิ่งที่ต้องทำเพิ่ม**: สร้าง `AiToolsService` ที่: +```typescript +// ตัวอย่าง: AI Tool Wrapper +@Injectable() +export class AiToolsService { + @Tool({ name: 'get_rfa', description: 'Get RFA by ID' }) + async getRfa(id: string) { + return this.rfaService.findOne({ publicId: id }); + } + // ...อื่นๆ +} +``` + +--- + +### 2.4 Workflow Engine (logic ธุรกิจ) + +| ที่เสนอ | ที่มีอยู่ | Gap | +|--------|----------|-----| +| RFA status flow | ✅ มี `workflow-engine/` + DSL | ✅ ตรงตามแผน 100% | +| Approval logic | ✅ มี CASL Guards + State Machine | ✅ พร้อม | +| Revision control | ✅ มี `revisions` table + locking | ✅ พร้อม | +| "AI = ช่วยคิด, Workflow = ของจริง" | ✅ มี ADR-023 "AI Boundary" | ✅ ตรงตามหลักการ | + +👉 **จุดแข็ง**: ส่วนนี้ทำไว้ดีมากแล้ว — AI ไม่สามารถ "มั่ว" Workflow ได้ เพราะต้องผ่าน DSL Engine + +--- + +### 2.5 File Storage + +| ที่เสนอ | ที่มีอยู่ | Gap | +|--------|----------|-----| +| เก็บไฟล์จริง (PDF, DWG) | ✅ Two-Phase Storage + ClamAV | ✅ ตรงตามแผน | +| Version control | ✅ มี `revisions` table + naming convention | ✅ พร้อม | +| Naming convention | ✅ มี `document-numbering/` module (ADR-002) | ✅ พร้อม | + +--- + +## ⚙️ 3. Database Design + +| Table ที่เสนอ | ที่มีอยู่ | Gap | +|--------------|----------|-----| +| `ai_embeddings` | 🟡 มีใน ADR-023A (Qdrant) | ⚠️ ต้องสร้าง Collection ใน Qdrant + Sync Job | +| `ai_logs` | 🟡 มี `monitoring/` module | ⚠️ ต้องเพิ่ม `ai_audit_logs` table สำหรับ tracking AI decisions | +| `ai_tasks` | 🟡 มี BullMQ (ADR-008) | ✅ สามารถใช้ `ai-batch` queue สำหรับ background jobs | + +💡 **แนะนำ**: สร้าง migration script สำหรับ: +```sql +-- ตัวอย่าง: ai_audit_logs table +CREATE TABLE ai_audit_logs ( + id INT AUTO_INCREMENT PRIMARY KEY, + user_public_id BINARY(16), + query_text TEXT, + agent_decision JSON, + tools_used JSON, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); +``` + +--- + +## 🤖 4. AI Use Cases (ของจริงที่ควรทำ) + +| Use Case | สถานะใน Repo | ความยาก | +|----------|-------------|---------| +| 🔎 Smart Search | 🟡 มี Elasticsearch + ADR-023 RAG | ⭐⭐ ต้องเพิ่ม NL→Query translator | +| 📄 Document QA | 🟡 มี OCR + Text extraction ในแผน | ⭐⭐⭐ ต้องเพิ่ม PDF parsing + chunking pipeline | +| 🔗 Relationship Mapping | ✅ มี Relations ใน Schema + Services | ⭐⭐ ต้องเพิ่ม "Graph Query" layer สำหรับ AI | +| 📊 Timeline Analysis | 🟡 มี `revisions.created_at` | ⭐⭐⭐ ต้องเพิ่ม "Temporal Query" logic | +| 🧠 Auto Classification | 🟡 มี ADR-017B (Superseded) | ⭐⭐⭐⭐ ต้องฝึก Model หรือใช้ Prompt Engineering | +| ⚠️ Alert / Assistant | 🟡 มี `notification/` module | ⭐⭐ ต้องเพิ่ม "Rule Engine" สำหรับ trigger alerts | + +--- + +## 🧩 5. UI Design + +| ส่วนที่เสนอ | ที่มีอยู่ | Gap | +|------------|----------|-----| +| Hybrid UI: Table + Chat | 🟡 มี DataTables + Forms | ⚠️ ยังไม่มี "Chat Panel" แบบ Side-by-side | +| Drawing Page: revision + RFAs + AI summary | ✅ มี `drawing/` module + relations | ⚠️ ต้องเพิ่ม "AI Summary" component ที่เรียก RAG | + +💡 **Quick Win**: เพิ่ม Chat Panel แบบง่ายๆ ใน `app/(dashboard)/drawings/[id]/page.tsx`: +```tsx +// ตัวอย่าง: Chat Panel ใน Drawing Page + +``` + +--- + +## ⚡ 6. Tech Stack + +| ส่วนที่เสนอ | ที่มีอยู่ | ตรงกัน? | +|------------|----------|---------| +| Backend: PHP → Python | ❌ ใช้ NestJS (TypeScript) ทั้งระบบ | ⚠️ ไม่ตรง — แต่ TypeScript + NestJS ดีกว่า PHP สำหรับ AI Integration | +| AI Layer: LangChain / Ollama | 🟡 ใช้ Ollama + n8n (ADR-023) | ✅ ตรงบางส่วน — ขาด LangChain/LlamaIndex | +| Vector DB: Qdrant | ✅ มีใน ADR-023A | ✅ ตรง | +| Frontend: DataTables + Chat UI | 🟡 มี DataTables (shadcn/ui) | ⚠️ ขาด Chat UI component | + +💡 **ข้อดีของ Stack ปัจจุบัน**: +- Full TypeScript → Type-safe AI Tool definitions +- NestJS Modules → Easy to add `ai-agent/` module +- BullMQ → Ready for async AI jobs + +--- + +## 🔥 7. Flow การทำงานจริง + +### 📥 Upload Drawing + +| ขั้นตอนที่เสนอ | ที่มีอยู่ | Gap | +|--------------|----------|-----| +| 1. User upload PDF | ✅ มี Two-Phase Upload | ✅ พร้อม | +| 2. Extract text (OCR) | 🟡 มีแผนใน ADR-023A | ⚠️ ต้องเพิ่ม OCR service (Tesseract / PaddleOCR) | +| 3. Chunk + Embed → Vector DB | 🟡 มี Qdrant ในแผน | ⚠️ ต้องเขียน `DocumentIndexingService` | +| 4. AI tag metadata | 🟡 มี ADR-017B (Superseded) | ⚠️ ต้อง implement classification pipeline | + +### 🔎 Query + +| ขั้นตอนที่เสนอ | ที่มีอยู่ | Gap | +|--------------|----------|-----| +| 1. เข้าใจ intent | 🟡 ไม่มี NLU layer | ⭐⭐⭐ ต้องเพิ่ม Intent Classifier | +| 2. Call tool: `get_drawings()` | ✅ มี `DrawingService` | ✅ พร้อม (แต่ต้อง wrap เป็น AI Tool) | +| 3. Filter revision ล่าสุด | ✅ มี `getLatestRevision()` | ✅ พร้อม | +| 4. ตอบ | 🟡 มี API Response | ⚠️ ต้องเพิ่ม "Natural Language Generation" layer | + +--- + +## 🧠 8. Insight สำคัญ (อย่าพลาด) + +| ข้อควรระวัง | สถานะใน Repo | ผ่าน? | +|------------|-------------|-------| +| ❌ อย่าให้ AI query DB ตรงๆ | ✅ มี ADR-023 "AI Boundary" | ✅ ผ่าน | +| ❌ อย่าให้ AI ตัดสินใจ workflow | ✅ มี Workflow Engine แยก | ✅ ผ่าน | +| ✅ AI → call function (tool) | 🟡 มี Services แต่ไม่มี Tool Interface | ⚠️ ต้องเพิ่ม `@Tool()` decorator pattern | +| ✅ System → validate logic | ✅ มี CASL Guards + Validation | ✅ ผ่าน | + +👉 **คุณทำถูกแล้ว**: การแยก "AI Intelligence" ออกจาก "Business Logic" เป็นหัวใจของระบบที่ปลอดภัย + +--- + +## 🚀 9. Roadmap (ทำจริง) + +### Phase 1 (2–4 สัปดาห์) — AI Chat + Query DB + +| Task | สถานะ | ความยาก | +|------|--------|---------| +| สร้าง `AiAgentModule` ใน NestJS | ❌ ยังไม่มี | ⭐⭐ | +| สร้าง `AiToolsService` wrapper | ❌ ยังไม่มี | ⭐⭐ | +| เพิ่ม Chat UI component ใน Frontend | ❌ ยังไม่มี | ⭐⭐ | +| ทดสอบ: "RFA ล่าสุดคืออะไร" | ❌ ยังไม่มี | ⭐⭐ | + +### Phase 2 — RAG + Embedding + +| Task | สถานะ | ความยาก | +|------|--------|---------| +| Deploy Qdrant ใน Docker | 🟡 มีในแผน | ⭐⭐ | +| สร้าง `DocumentIndexingService` (OCR + Chunk + Embed) | ❌ ยังไม่มี | ⭐⭐⭐ | +| สร้าง `QdrantService` สำหรับ vector search | ❌ ยังไม่มี | ⭐⭐ | +| ทดสอบ: "สรุป spec นี้" | ❌ ยังไม่มี | ⭐⭐⭐ | + +### Phase 3 — Automation + Alert + +| Task | สถานะ | ความยาก | +|------|--------|---------| +| สร้าง `AiAlertService` สำหรับ rule-based alerts | ❌ ยังไม่มี | ⭐⭐⭐ | +| สร้าง `ClassificationPipeline` สำหรับ auto-tagging | ❌ ยังไม่มี | ⭐⭐⭐⭐ | +| Integrateกับ Notification Module | ✅ มี `notification/` module | ⭐⭐ | + +--- + +## 🎯 10. ถ้าจะทำให้ "โหดจริง" + +### Ultimate Version: AI = Document Controller + +| ฟีเจอร์ | สิ่งที่ต้องเพิ่ม | ความยาก | +|--------|----------------|---------| +| 🔍 Auto check: revision mismatch | สร้าง `RevisionConsistencyChecker` | ⭐⭐⭐ | +| 🔍 Auto check: missing approval | สร้าง `ApprovalGapDetector` | ⭐⭐⭐ | +| 🔍 Auto check: outdated drawing | สร้าง `DrawingFreshnessMonitor` | ⭐⭐⭐ | +| 🤖 Proactive alert: "Drawing นี้ outdated" | Integrateกับ `notification/` module | ⭐⭐ | + +--- + +## 💡 สรุปสั้นๆ (แบบเฮียก) + +### ✅ สิ่งที่ "มีแล้ว" และ "ทำดีแล้ว" +1. **สถาปัตยกรรมพื้นฐาน** — NestJS + Next.js + MariaDB + Redis + Elasticsearch → Solid +2. **Workflow Engine** — DSL-based + ADR-001/021 → ตรงตามแผน 100% +3. **Security & RBAC** — CASL + 4-Level + JWT → พร้อมสำหรับ Enterprise +4. **File Storage** — Two-Phase + ClamAV + Versioning → ดีมาก +5. **AI Boundary** — ADR-023 กำหนดขอบเขตชัดเจน → ป้องกัน AI มั่ว + +### ⚠️ สิ่งที่ "ต้องเพิ่ม" เพื่อให้เป็น AI DMS จริง +1. **AI Agent Runtime** — สร้าง `ai-agent/` module ที่รันใน Production (ไม่ใช่แค่ `.agents/` สำหรับ Dev) +2. **Tool Calling Interface** — Wrap Services เป็น `@Tool()` decorators สำหรับ AI Call +3. **Vector Search Pipeline** — Deploy Qdrant + สร้าง `DocumentIndexingService` +4. **Chat UI Component** — เพิ่ม Side Panel Chat ใน Drawing/RFA Pages +5. **Intent Recognition** — เพิ่ม NL→Query translator สำหรับ Smart Search + +### 🎯 Quick Win (ทำใน 1 สัปดาห์) +```bash +# 1. สร้าง AI Agent Module +nest g module ai-agent +nest g service ai-agent/ai-tools +nest g controller ai-agent/chat + +# 2. เพิ่ม Tool Wrapper +# src/ai-agent/ai-tools.service.ts +@Injectable() +export class AiToolsService { + @Tool({ name: 'get_rfa', description: 'Get RFA by publicId' }) + async getRfa(@Arg('publicId') publicId: string) { + return this.rfaService.findOne({ where: { publicId } }); + } +} + +# 3. เพิ่ม Chat Endpoint +# src/ai-agent/chat.controller.ts +@Post('chat') +async chat(@Body() dto: ChatDto) { + // 1. Parse intent + // 2. Route to tools + // 3. Generate response +} +``` + +--- + +> 🎯 **Bottom Line**: Repo คุณ "พร้อม 80%" สำหรับ AI DMS — ขาดแค่ "AI Runtime Layer" ที่เชื่อม Agent → Tools → UI +> ถ้าเพิ่ม `ai-agent/` module + Tool Interface + Chat UI → จะได้ระบบที่ "โหดจริง" ตามที่วางแผนไว้ 🔥 + diff --git a/docs/จัดการตำแหน่ง Node n8n.html b/docs/จัดการตำแหน่ง Node n8n.html deleted file mode 100644 index 5054b278..00000000 --- a/docs/จัดการตำแหน่ง Node n8n.html +++ /dev/null @@ -1,8670 +0,0 @@ - - - -
- - - - -