diff --git a/.windsurfrules b/.windsurfrules index 6afa499..2714f62 100644 --- a/.windsurfrules +++ b/.windsurfrules @@ -1,6 +1,6 @@ # NAP-DMS Project Context & Rules - - For: Windsurf Cascade (and compatible: Codex CLI, opencode, Amp, Amazon Q, AGENTS.md tools) -- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-04-04 +- For: Windsurf Cascade +- Version: 1.8.6 | Last synced from repo: 2026-04-10 - Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3) --- @@ -24,6 +24,51 @@ Every response must be **precise**, **spec-compliant**, and **production-ready** --- +## 🧩 Thought & Planning Protocol (Powered by Everything-Claude-Code) + +Before writing any code or taking any action in Tier 1 and Tier 2, the AI must demonstrate the following thinking process: + +### 1. Analysis Phase (Explore & Analyze) + +Problem Understanding: Restate what the user wants in clear, unambiguous terms. +Context Search: Identify the relevant Spec files or ADRs from the "Key Spec Files" table that must be read before starting. +Constraints Identification: Identify key constraints (e.g. Security rules, UUID patterns, or Domain terminology). + +### 2. Planning Phase (Plan) + +Alternative Exploration: Present at least 2 solution approaches (where possible) with pros/cons analysis. +Step-by-Step Roadmap: Write a file-by-file plan of changes before executing. +Verification Plan: Specify how to verify the work is complete (e.g. "which unit tests to write" or "which file to check the schema in"). + +### 3. Execution & Refinement (Execute & Refine) + +Follow the plan step by step, and pause to ask if any uncertainty arises. +If significant logic changes are made, summarize what was done for the user after completion. + +--- + +## ⚙️ DMS Workflow Engine Protocol + +กฎนี้ใช้คุมการเขียน Logic ส่วนการไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกันปัญหา Race Condition และรักษาความถูกต้องของสถานะเอกสาร: + +- **State Management:** ทุกการเปลี่ยนสถานะของ Workflow ต้องตรวจสอบสถานะปัจจุบันจากฐานข้อมูลก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดูตัวอย่างใน `05-06-code-snippets.md` `[workflow-transition]`) +- **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 + +--- + +## 🛡️ Security & Integrity Audit Protocol + +กฎนี้จะช่วยให้ 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-018) +- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่านการตรวจสอบแบบ **Two-Phase** (Temp → Commit) และต้องสแกนด้วย **ClamAV** ก่อนย้ายเข้า Permanent Storage (ADR-016) + +--- + ## 🧭 Rule Enforcement Tiers ### 🔴 Tier 1 — CRITICAL (CI BLOCKER) @@ -61,24 +106,30 @@ Best practice — follow when possible: Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others -| Document | Path | Use When | -| ----------------------- | ----------------------------------------------------------------- | ------------------------------- | -| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology | -| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | -| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | -| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | -| **ADR-007 Error Handling** | `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` | Error patterns & recovery | -| **ADR-018 AI Boundary** | `specs/06-Decision-Records/ADR-018-ai-boundary.md` | AI isolation rules | -| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | -| **ADR-020 AI Integration** | `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` | AI architecture patterns | -| **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 | -| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | -| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | Commit/branch naming | -| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | Reusable patterns | -| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | Localization rules | -| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | Before deploy/hotfix | -| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | Feature completeness | +| Document | Path | Status | Use When | +| --------------------------- | -------------------------------------------------------------------- | ----------- | ------------------------------------ | +| **Glossary** | `specs/00-overview/00-02-glossary.md` | — | Verify domain terminology | +| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | — | Before writing any query | +| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | — | Field meanings + business rules | +| **RBAC Matrix** | `specs/01-requirements/01-02-business-rules/01-02-01-rbac-matrix.md` | — | Permission levels + roles | +| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | — | Prevent bugs in flows | +| **ADR-001 Workflow Engine** | `specs/06-Decision-Records/ADR-001-unified-workflow-engine.md` | ✅ Active | DSL-based workflow implementation | +| **ADR-002 Doc Numbering** | `specs/06-Decision-Records/ADR-002-document-numbering-strategy.md` | ✅ Active | Document number generation + locking | +| **ADR-007 Error Handling** | `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` | ✅ Active | Error patterns & recovery | +| **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-018 AI Boundary** | `specs/06-Decision-Records/ADR-018-ai-boundary.md` | ✅ Active | AI isolation rules | +| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | ✅ Active | UUID-related work | +| **ADR-020 AI Integration** | `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` | 🔄 Proposed | AI architecture patterns | +| **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 | +| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | — | Coverage goals | +| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | — | Commit/branch naming | +| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | — | Reusable patterns | +| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | — | Localization rules | +| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | — | Before deploy/hotfix | +| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | — | Feature completeness | --- @@ -174,21 +225,42 @@ Full glossary: `specs/00-overview/00-02-glossary.md` ## 🚫 Forbidden Actions -| ❌ Forbidden | ✅ Correct Approach | -| ----------------------------------------------- | --------------------------------------------- | -| SQL Triggers for business logic | NestJS Service methods | -| `.env` files in production | `docker-compose.yml` environment section | -| TypeORM migration files | Edit schema SQL directly (ADR-009) | -| Inventing table/column names | Verify against `schema-02-tables.sql` | -| `any` TypeScript type | Proper types / generics | -| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | -| `req: any` in controllers | `RequestWithUser` typed interface | -| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | -| Exposing INT PK in API responses | UUIDv7 (ADR-019) | -| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | -| Direct file operations bypassing StorageService | `StorageService` for all file moves | -| Inline email/notification sending | BullMQ queue job | -| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | +| ❌ Forbidden | ✅ Correct Approach | ⚠️ Why | +| ----------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------- | +| SQL Triggers for business logic | NestJS Service methods | Untestable; bypasses audit log | +| `.env` files in production | `docker-compose.yml` environment section | Secrets exposed in version control | +| TypeORM migration files | Edit schema SQL directly (ADR-009) | Migration drift risk; schema managed via SQL delta | +| Inventing table/column names | Verify against `schema-02-tables.sql` | Schema mismatch causes silent runtime errors | +| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors | +| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage | +| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable | +| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"019505…"` parsed to integer `19` — silently wrong | +| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks | +| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | Bypasses RBAC, audit trail, and validation layer | +| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail | +| Inline email/notification sending | BullMQ queue job (ADR-008) | Blocks request thread; no retry on transient failure | +| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | Unverified deploy risks data loss in production | +| AI direct cloud API calls | On-premises Ollama only (ADR-018) | Data privacy violation; no audit control | +| AI outputs without human validation | Human-in-the-loop validation required (ADR-020) | Unvalidated AI metadata corrupts document records | + +--- + +## 🚧 Out of Scope — Never Do Without Explicit Approval + +The following actions MUST NOT be performed autonomously. **Stop and ask for confirmation** before proceeding: + +| ❌ 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 | --- @@ -208,15 +280,33 @@ Full glossary: `specs/00-overview/00-02-glossary.md` ### 🟡 Normal Work — UI / Feature / Integration -- Follow existing patterns in codebase -- Check spec for relevant module only -- No need to read all specs +**Steps:** + +1. Follow existing patterns in codebase +2. Check spec for relevant module only +3. Verify no forbidden patterns (`any`, `console.log`, UUID misuse) + +**Expected output:** + +- Functional component or updated service method +- At least 1 unit/snapshot test added or updated +- No new TypeScript errors or ESLint warnings +- PR description reflects the change ### 🟢 Quick Fix — Bug Fix / Typo / Style -- Fix directly -- Add minimal test if logic changed -- Check forbidden patterns before commit +**Steps:** + +1. Identify root cause before changing code +2. Apply minimal, targeted fix +3. Add regression test if logic changed +4. Verify no forbidden patterns introduced + +**Expected output:** + +- Single focused commit: `fix(scope): description` +- All existing tests still pass (no regressions) +- If logic changed: at least 1 regression test added --- @@ -224,18 +314,25 @@ Full glossary: `specs/00-overview/00-02-glossary.md` When user asks about... check these files: -| Request | Files to Check | Expected Response | -| -------------------- | ------------------------------------------------------- | --------------------------------------------------- | -| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | -| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments | -| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `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" | `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-018`, `ADR-020` | AI boundary + unified pipeline | -| "Error handling" | `ADR-007` | Layered error classification + recovery | +| Request | Files to Check | Expected Response | +| ----------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | +| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments | +| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `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" | `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-018`, `ADR-020` | AI boundary + unified pipeline | +| "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.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร | +| "Audit ความปลอดภัย" | `ADR-016`, `ADR-018`, `ADR-019` | ตรวจสอบ UUID pattern, CASL Guard และ AI Boundary | --- @@ -244,7 +341,7 @@ When user asks about... check these files: - [ ] UUID pattern verified (no parseInt on UUID) - [ ] No `any` types in TypeScript - [ ] No `console.log` in committed code -- [ ] Comments in Thai +- [ ] Business logic comments in Thai (human devs), technical/library comments in English (AI tools) - [ ] Code identifiers in English - [ ] Schema changes via SQL directly (not migration) - [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) @@ -272,15 +369,16 @@ This file is a **quick reference**. For detailed information: ## 🔄 Change Log -| Version | Date | Changes | Updated By | -| ------- | ---------- | ------------------------------------------------------------------- | -------------- | -| 1.8.5 | 2026-04-04 | Added ADR-007 error handling, ADR-020 AI integration, updated security rules | Windsurf AI | -| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | -| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | -| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | -| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet | -| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev | -| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro | +| Version | Date | Changes | Updated By | +| ------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | +| 1.8.6 | 2026-04-10 | + DMS Workflow Engine Protocol, + Security & Integrity Audit Protocol, + 2 Context-Aware Triggers, ADR Status column, Forbidden Why column | Human Dev | +| 1.8.5 | 2026-04-04 | Added ADR-007 error handling, ADR-020 AI integration, updated security rules | Windsurf AI | +| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | +| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | +| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | +| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet | +| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev | +| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro | --- diff --git a/AGENTS.md b/AGENTS.md index a9cfbca..7162354 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # NAP-DMS Project Context & Rules - For: Windsurf Cascade (and compatible: Codex CLI, opencode, Amp, Antigravity, AGENTS.md tools) -- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-04-04 +- Version: 1.8.6 | Last synced from repo: 2026-04-10 - Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3) --- @@ -25,6 +25,51 @@ Every response must be **precise**, **spec-compliant**, and **production-ready** --- +## 🧩 Thought & Planning Protocol (Powered by Everything-Claude-Code) + +Before writing any code or taking any action in Tier 1 and Tier 2, the AI must demonstrate the following thinking process: + +### 1. Analysis Phase (Explore & Analyze) + +Problem Understanding: Restate what the user wants in clear, unambiguous terms. +Context Search: Identify the relevant Spec files or ADRs from the "Key Spec Files" table that must be read before starting. +Constraints Identification: Identify key constraints (e.g. Security rules, UUID patterns, or Domain terminology). + +### 2. Planning Phase (Plan) + +Alternative Exploration: Present at least 2 solution approaches (where possible) with pros/cons analysis. +Step-by-Step Roadmap: Write a file-by-file plan of changes before executing. +Verification Plan: Specify how to verify the work is complete (e.g. "which unit tests to write" or "which file to check the schema in"). + +### 3. Execution & Refinement (Execute & Refine) + +Follow the plan step by step, and pause to ask if any uncertainty arises. +If significant logic changes are made, summarize what was done for the user after completion. + +--- + +## ⚙️ DMS Workflow Engine Protocol + +กฎนี้ใช้คุมการเขียน Logic ส่วนการไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกันปัญหา Race Condition และรักษาความถูกต้องของสถานะเอกสาร: + +- **State Management:** ทุกการเปลี่ยนสถานะของ Workflow ต้องตรวจสอบสถานะปัจจุบันจากฐานข้อมูลก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดูตัวอย่างใน `05-06-code-snippets.md` `[workflow-transition]`) +- **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 + +--- + +## 🛡️ Security & Integrity Audit Protocol + +กฎนี้จะช่วยให้ 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-018) +- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่านการตรวจสอบแบบ **Two-Phase** (Temp → Commit) และต้องสแกนด้วย **ClamAV** ก่อนย้ายเข้า Permanent Storage (ADR-016) + +--- + ## 🧭 Rule Enforcement Tiers ### 🔴 Tier 1 — CRITICAL (CI BLOCKER) @@ -62,24 +107,30 @@ Best practice — follow when possible: Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others -| Document | Path | Use When | -| -------------------------- | ------------------------------------------------------------------ | ------------------------------- | -| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology | -| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | -| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | -| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | -| **ADR-007 Error Handling** | `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` | Error patterns & recovery | -| **ADR-018 AI Boundary** | `specs/06-Decision-Records/ADR-018-ai-boundary.md` | AI isolation rules | -| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | -| **ADR-020 AI Integration** | `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` | AI architecture patterns | -| **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 | -| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | -| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | Commit/branch naming | -| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | Reusable patterns | -| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | Localization rules | -| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | Before deploy/hotfix | -| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | Feature completeness | +| Document | Path | Status | Use When | +| --------------------------- | -------------------------------------------------------------------- | ----------- | ------------------------------------ | +| **Glossary** | `specs/00-overview/00-02-glossary.md` | — | Verify domain terminology | +| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | — | Before writing any query | +| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | — | Field meanings + business rules | +| **RBAC Matrix** | `specs/01-requirements/01-02-business-rules/01-02-01-rbac-matrix.md` | — | Permission levels + roles | +| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | — | Prevent bugs in flows | +| **ADR-001 Workflow Engine** | `specs/06-Decision-Records/ADR-001-unified-workflow-engine.md` | ✅ Active | DSL-based workflow implementation | +| **ADR-002 Doc Numbering** | `specs/06-Decision-Records/ADR-002-document-numbering-strategy.md` | ✅ Active | Document number generation + locking | +| **ADR-007 Error Handling** | `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` | ✅ Active | Error patterns & recovery | +| **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-018 AI Boundary** | `specs/06-Decision-Records/ADR-018-ai-boundary.md` | ✅ Active | AI isolation rules | +| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | ✅ Active | UUID-related work | +| **ADR-020 AI Integration** | `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` | 🔄 Proposed | AI architecture patterns | +| **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 | +| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | — | Coverage goals | +| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | — | Commit/branch naming | +| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | — | Reusable patterns | +| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | — | Localization rules | +| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | — | Before deploy/hotfix | +| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | — | Feature completeness | --- @@ -175,21 +226,42 @@ Full glossary: `specs/00-overview/00-02-glossary.md` ## 🚫 Forbidden Actions -| ❌ Forbidden | ✅ Correct Approach | -| ----------------------------------------------- | --------------------------------------------- | -| SQL Triggers for business logic | NestJS Service methods | -| `.env` files in production | `docker-compose.yml` environment section | -| TypeORM migration files | Edit schema SQL directly (ADR-009) | -| Inventing table/column names | Verify against `schema-02-tables.sql` | -| `any` TypeScript type | Proper types / generics | -| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | -| `req: any` in controllers | `RequestWithUser` typed interface | -| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | -| Exposing INT PK in API responses | UUIDv7 (ADR-019) | -| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | -| Direct file operations bypassing StorageService | `StorageService` for all file moves | -| Inline email/notification sending | BullMQ queue job | -| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | +| ❌ Forbidden | ✅ Correct Approach | ⚠️ Why | +| ----------------------------------------------- | ----------------------------------------------- | ---------------------------------------------------- | +| SQL Triggers for business logic | NestJS Service methods | Untestable; bypasses audit log | +| `.env` files in production | `docker-compose.yml` environment section | Secrets exposed in version control | +| TypeORM migration files | Edit schema SQL directly (ADR-009) | Migration drift risk; schema managed via SQL delta | +| Inventing table/column names | Verify against `schema-02-tables.sql` | Schema mismatch causes silent runtime errors | +| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors | +| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage | +| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable | +| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"019505…"` parsed to integer `19` — silently wrong | +| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks | +| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | Bypasses RBAC, audit trail, and validation layer | +| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail | +| Inline email/notification sending | BullMQ queue job (ADR-008) | Blocks request thread; no retry on transient failure | +| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | Unverified deploy risks data loss in production | +| AI direct cloud API calls | On-premises Ollama only (ADR-018) | Data privacy violation; no audit control | +| AI outputs without human validation | Human-in-the-loop validation required (ADR-020) | Unvalidated AI metadata corrupts document records | + +--- + +## 🚧 Out of Scope — Never Do Without Explicit Approval + +The following actions MUST NOT be performed autonomously. **Stop and ask for confirmation** before proceeding: + +| ❌ 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 | --- @@ -209,15 +281,33 @@ Full glossary: `specs/00-overview/00-02-glossary.md` ### 🟡 Normal Work — UI / Feature / Integration -- Follow existing patterns in codebase -- Check spec for relevant module only -- No need to read all specs +**Steps:** + +1. Follow existing patterns in codebase +2. Check spec for relevant module only +3. Verify no forbidden patterns (`any`, `console.log`, UUID misuse) + +**Expected output:** + +- Functional component or updated service method +- At least 1 unit/snapshot test added or updated +- No new TypeScript errors or ESLint warnings +- PR description reflects the change ### 🟢 Quick Fix — Bug Fix / Typo / Style -- Fix directly -- Add minimal test if logic changed -- Check forbidden patterns before commit +**Steps:** + +1. Identify root cause before changing code +2. Apply minimal, targeted fix +3. Add regression test if logic changed +4. Verify no forbidden patterns introduced + +**Expected output:** + +- Single focused commit: `fix(scope): description` +- All existing tests still pass (no regressions) +- If logic changed: at least 1 regression test added --- @@ -225,18 +315,25 @@ Full glossary: `specs/00-overview/00-02-glossary.md` When user asks about... check these files: -| Request | Files to Check | Expected Response | -| -------------------- | ------------------------------------------------------- | --------------------------------------------------- | -| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | -| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments | -| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `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" | `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-018`, `ADR-020` | AI boundary + unified pipeline | -| "Error handling" | `ADR-007` | Layered error classification + recovery | +| Request | Files to Check | Expected Response | +| ----------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------- | +| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | +| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments | +| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `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" | `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-018`, `ADR-020` | AI boundary + unified pipeline | +| "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.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร | +| "Audit ความปลอดภัย" | `ADR-016`, `ADR-018`, `ADR-019` | ตรวจสอบ UUID pattern, CASL Guard และ AI Boundary | --- @@ -245,7 +342,7 @@ When user asks about... check these files: - [ ] UUID pattern verified (no parseInt on UUID) - [ ] No `any` types in TypeScript - [ ] No `console.log` in committed code -- [ ] Comments in Thai +- [ ] Business logic comments in Thai (human devs), technical/library comments in English (AI tools) - [ ] Code identifiers in English - [ ] Schema changes via SQL directly (not migration) - [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) @@ -273,15 +370,16 @@ This file is a **quick reference**. For detailed information: ## 🔄 Change Log -| Version | Date | Changes | Updated By | -| ------- | ---------- | ---------------------------------------------------------------------------- | -------------- | -| 1.8.5 | 2026-04-04 | Added ADR-007 error handling, ADR-020 AI integration, updated security rules | Windsurf AI | -| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | -| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | -| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | -| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet | -| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev | -| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro | +| Version | Date | Changes | Updated By | +| ------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------- | +| 1.8.6 | 2026-04-10 | + DMS Workflow Engine Protocol, + Security & Integrity Audit Protocol, + 2 Context-Aware Triggers, ADR Status column, Forbidden Why column | Human Dev | +| 1.8.5 | 2026-04-04 | Added ADR-007 error handling, ADR-020 AI integration, updated security rules | Windsurf AI | +| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | +| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | +| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | +| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet | +| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev | +| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro | --- diff --git a/CHANGELOG.md b/CHANGELOG.md index cce5d4a..34345e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,16 @@ # Version History -## [Unreleased] +## 1.8.5 (2026-04-10) + +### Specification & ADR Documentation + +#### 📋 **ADR Registry Update** (2026-04-10) + +- **Added**: ADR-003 (API Design Strategy) to `06-Decision-Records/README.md` — Hybrid REST + Action Strategy สำหรับ Resource และ Workflow Operations +- **Added**: ADR-004 (Database Schema Design Strategy) to `06-Decision-Records/README.md` — Selective Normalization + Standard Patterns (UUID, Soft Delete, Audit) +- **Added**: ADR-007 (Error Handling & Recovery Strategy) to `06-Decision-Records/README.md` — Layered Classification (Validation / Business / System) + Recovery Actions +- **Updated**: `06-Decision-Records/README.md` version 1.8.2 → 1.8.5 +- **Total ADRs**: 21 (ADR-001 to ADR-020 + ADR-017B) ### Correspondence Module — Phase 7 Complete (2026-03-24) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c3d56a3..d304550 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,12 +75,20 @@ specs/ │ ├── 05-03-frontend-guidelines.md │ └── 05-04-testing-strategy.md │ -├── 06-Decision-Records/ # Architecture Decision Records (17+1 ADRs) +├── 06-Decision-Records/ # Architecture Decision Records (21 ADRs) │ ├── README.md -│ ├── ADR-001-unified-workflow.md -│ ├── ADR-002-document-numbering.md -│ ├── ... (ADR-003 to ADR-017) -│ └── ADR-018-ai-boundary.md # AI Isolation Policy [★ Patch 1.8.1] +│ ├── ADR-001-unified-workflow-engine.md +│ ├── ADR-002-document-numbering-strategy.md +│ ├── ADR-003-api-design-strategy.md # Hybrid REST + Action [★ v1.8.5] +│ ├── ADR-004-database-schema-design-strategy.md # Selective Normalization [★ v1.8.5] +│ ├── ... (ADR-005 to ADR-006) +│ ├── ADR-007-error-handling-strategy.md # Layered Error Handling [★ v1.8.5] +│ ├── ... (ADR-008 to ADR-016) +│ ├── ADR-017-ollama-data-migration.md +│ ├── ADR-017B-ai-document-classification.md +│ ├── ADR-018-ai-boundary.md # AI Isolation Policy [★ Patch 1.8.1] +│ ├── ADR-019-hybrid-identifier-strategy.md +│ └── ADR-020-ai-intelligence-integration.md │ └── 99-archives/ # ประวัติการทำงานและ Tasks เก่า ├── history/ @@ -90,16 +98,16 @@ specs/ ### 📋 หมวดหมู่เอกสาร -| หมวด | วัตถุประสงค์ | ไฟล์สำคัญ | ผู้ดูแล | -| ----------------------------- | -------------------------------------- | ------------ | ----------------------- | -| **00-Overview** | ภาพรวม, Product Vision, KPI, Training | Gap 1/5/6/9 | Project Manager / PO | -| **01-Requirements** | User Stories, UAT, UI, Edge Cases | Gap 2/3/4/10 | Business Analyst + PO | -| **02-Architecture** | สถาปัตยกรรมและการออกแบบ | — | Tech Lead + Architects | -| **03-Data-and-Storage** | Schema v1.8.0, Migration Scope | Gap 7 | Backend Lead + DBA | -| **04-Infrastructure-OPS** | Deployment, Operations, Release Policy | Gap 8 | DevOps Team | -| **05-Engineering-Guidelines** | แผนการพัฒนาและ Implementation | — | Development Team Leads | -| **06-Decision-Records** | Architecture Decision Records (17+1) | ADR-018 | Tech Lead + Senior Devs | -| **99-archives** | Archived / Tasks | — | All Team Members | +| หมวด | วัตถุประสงค์ | ไฟล์สำคัญ | ผู้ดูแล | +| ----------------------------- | -------------------------------------- | --------------- | ----------------------- | +| **00-Overview** | ภาพรวม, Product Vision, KPI, Training | Gap 1/5/6/9 | Project Manager / PO | +| **01-Requirements** | User Stories, UAT, UI, Edge Cases | Gap 2/3/4/10 | Business Analyst + PO | +| **02-Architecture** | สถาปัตยกรรมและการออกแบบ | — | Tech Lead + Architects | +| **03-Data-and-Storage** | Schema v1.8.0, Migration Scope | Gap 7 | Backend Lead + DBA | +| **04-Infrastructure-OPS** | Deployment, Operations, Release Policy | Gap 8 | DevOps Team | +| **05-Engineering-Guidelines** | แผนการพัฒนาและ Implementation | — | Development Team Leads | +| **06-Decision-Records** | Architecture Decision Records (21) | ADR-018/019/020 | Tech Lead + Senior Devs | +| **99-archives** | Archived / Tasks | — | All Team Members | --- @@ -536,16 +544,17 @@ graph LR **Document History**: -| Version | Date | Author | Changes | -| ------- | ---------- | ---------- | ------------------------------------------------------- | -| 1.0.0 | 2025-01-15 | John Doe | Initial version | -| 1.1.0 | 2025-02-20 | Jane Smith | Add CC support | -| 1.2.0 | 2025-03-10 | John Doe | Update workflow | -| 1.8.1 | 2026-03-21 | Tech Lead | Security hardening, numbering fixes, dependency updates | +| Version | Date | Author | Changes | +| ------- | ---------- | ---------- | ----------------------------------------------------------- | +| 1.0.0 | 2025-01-15 | John Doe | Initial version | +| 1.1.0 | 2025-02-20 | Jane Smith | Add CC support | +| 1.2.0 | 2025-03-10 | John Doe | Update workflow | +| 1.8.1 | 2026-03-21 | Tech Lead | Security hardening, numbering fixes, dependency updates | +| 1.8.5 | 2026-04-10 | Tech Lead | ADR registry complete (21 ADRs), spec documentation updates | -**Current Version**: 1.8.1 +**Current Version**: 1.8.5 **Status**: Approved -**Last Updated**: 2026-03-21 +**Last Updated**: 2026-04-10 **Security**: 0 vulnerabilities (backend) ``` diff --git a/README.md b/README.md index 6a794a7..8dd073c 100644 --- a/README.md +++ b/README.md @@ -3,16 +3,16 @@ > **Laem Chabang Port Phase 3 - Document Management System** > ระบบบริหารจัดการเอกสารโครงการแบบครบวงจร สำหรับโครงการก่อสร้างท่าเรือแหลมฉบังระยะที่ 3 -[![Version](https://img.shields.io/badge/version-1.8.1-blue.svg)](./CHANGELOG.md) +[![Version](https://img.shields.io/badge/version-1.8.5-blue.svg)](./CHANGELOG.md) [![License](https://img.shields.io/badge/license-Internal-red.svg)]() [![Status](https://img.shields.io/badge/status-UAT%20Ready-brightgreen.svg)]() [![Docs](https://img.shields.io/badge/docs-10%2F10%20Gaps%20Closed-success.svg)](./specs/00-Overview/README.md) --- -## 📈 Current Status (As of 2026-03-21) +## 📈 Current Status (As of 2026-04-10) -**Version 1.8.1 (Patch) — UAT Ready, Security Hardened** +**Version 1.8.5 — UAT Ready, ADR Documentation Complete (21 ADRs)** | Area | Status | หมายเหตุ | | -------------------- | ------------------------ | ---------------------------------------- | @@ -292,7 +292,7 @@ lcbp3-dms/ │ ├── 03-Data-and-Storage/ # Schema v1.8.0 (split 3 files) + 03-06-migration-business-scope.md │ ├── 04-Infrastructure-OPS/ # Ops: Deploy, Monitoring, Security + 04-08-release-management-policy.md │ ├── 05-Engineering-Guidelines/ # มาตรฐานการพัฒนา Backend/Frontend -│ ├── 06-Decision-Records/ # 17+1 ADRs รวม ADR-018-ai-boundary +│ ├── 06-Decision-Records/ # 21 ADRs (ADR-001~020 + ADR-017B) │ └── 99-archives/ # ประวัติการทำงานและ Tasks เก่า │ ├── docs/ # 📚 Legacy documentation @@ -313,21 +313,21 @@ lcbp3-dms/ ### เอกสารหลัก (specs/ folder) -| เอกสาร | คำอธิบาย | Gap | ไฟล์หลัก | -| ----------------------- | -------------------------------------------- | --------- | --------------------------------------- | -| **Product Vision** | Vision, Strategic Pillars, Guardrails | Gap 1 ✅ | `00-03-product-vision.md` | -| **User Stories** | 27 Stories, 8 Epics, MoSCoW | Gap 2 ✅ | `01-04-user-stories.md` | -| **Acceptance Criteria** | UAT Criteria, Sign-off Process | Gap 3 ✅ | `01-05-acceptance-criteria.md` | -| **UI/UX Wireframes** | 26 Screens, ASCII Wireframes, Design System | Gap 4 ✅ | `01-07-ui-wireframes.md` | -| **Stakeholder & Risk** | Sign-off, Risk Register, Change Control | Gap 5 ✅ | `00-04-stakeholder-signoff-and-risk.md` | -| **KPI Baseline** | 14 KPIs, SQL Queries, Grafana Specs | Gap 6 ✅ | `00-05-kpi-baseline.md` | -| **Migration Scope** | 20K Docs, 3 Tiers, Go/No-Go Gates | Gap 7 ✅ | `03-06-migration-business-scope.md` | -| **Release Policy** | SemVer, 5 Gates, Hotfix, Rollback | Gap 8 ✅ | `04-08-release-management-policy.md` | -| **Training Plan** | Curriculum per Role, UAT Training | Gap 9 ✅ | `00-06-training-plan.md` | -| **Edge Cases & Rules** | 37 Edge Cases, Business Logic Guards | Gap 10 ✅ | `01-06-edge-cases-and-rules.md` | -| **Schema v1.8.0** | Tables, Views, Indexes (3-file split) | — | `lcbp3-v1.8.0-schema-*.sql` | -| **Data Dictionary** | Field Meanings, Business Rules | — | `03-01-data-dictionary.md` | -| **ADRs (17+2)** | All Architecture Decisions incl. ADR-018/019 | — | `06-Decision-Records/` | +| เอกสาร | คำอธิบาย | Gap | ไฟล์หลัก | +| ----------------------- | ------------------------------------------------------------ | --------- | --------------------------------------- | +| **Product Vision** | Vision, Strategic Pillars, Guardrails | Gap 1 ✅ | `00-03-product-vision.md` | +| **User Stories** | 27 Stories, 8 Epics, MoSCoW | Gap 2 ✅ | `01-04-user-stories.md` | +| **Acceptance Criteria** | UAT Criteria, Sign-off Process | Gap 3 ✅ | `01-05-acceptance-criteria.md` | +| **UI/UX Wireframes** | 26 Screens, ASCII Wireframes, Design System | Gap 4 ✅ | `01-07-ui-wireframes.md` | +| **Stakeholder & Risk** | Sign-off, Risk Register, Change Control | Gap 5 ✅ | `00-04-stakeholder-signoff-and-risk.md` | +| **KPI Baseline** | 14 KPIs, SQL Queries, Grafana Specs | Gap 6 ✅ | `00-05-kpi-baseline.md` | +| **Migration Scope** | 20K Docs, 3 Tiers, Go/No-Go Gates | Gap 7 ✅ | `03-06-migration-business-scope.md` | +| **Release Policy** | SemVer, 5 Gates, Hotfix, Rollback | Gap 8 ✅ | `04-08-release-management-policy.md` | +| **Training Plan** | Curriculum per Role, UAT Training | Gap 9 ✅ | `00-06-training-plan.md` | +| **Edge Cases & Rules** | 37 Edge Cases, Business Logic Guards | Gap 10 ✅ | `01-06-edge-cases-and-rules.md` | +| **Schema v1.8.0** | Tables, Views, Indexes (3-file split) | — | `lcbp3-v1.8.0-schema-*.sql` | +| **Data Dictionary** | Field Meanings, Business Rules | — | `03-01-data-dictionary.md` | +| **ADRs (21)** | All Architecture Decisions incl. ADR-003/004/007/018/019/020 | — | `06-Decision-Records/` | ### Schema & Seed Data (v1.8.0) @@ -554,6 +554,14 @@ This project is **Internal Use Only** - ลิขสิทธิ์เป็น ## 🗺️ Roadmap +### ✅ Version 1.8.5 (Apr 2026) — ADR Documentation Complete + +- ✅ ADR-003 (API Design Strategy) — Hybrid REST + Action Pattern registered +- ✅ ADR-004 (Database Schema Design Strategy) — Selective Normalization registered +- ✅ ADR-007 (Error Handling & Recovery) — Layered Classification registered +- ✅ ADR-020 (AI Intelligence Integration) — Unified AI Pipeline proposed +- ✅ **Total: 21 ADRs** ครอบคลุมทุก Architectural Decision (ADR-001~020 + ADR-017B) + ### ✅ Version 1.8.0 (Feb 2026) — Schema & Type Safety - ✅ Schema v1.8.0 (3-file split + ADR-009 No-Migration Policy) diff --git a/specs/05-Engineering-Guidelines/05-06-code-snippets.md b/specs/05-Engineering-Guidelines/05-06-code-snippets.md index 5b1b69a..f1b117e 100644 --- a/specs/05-Engineering-Guidelines/05-06-code-snippets.md +++ b/specs/05-Engineering-Guidelines/05-06-code-snippets.md @@ -1,7 +1,7 @@ # Code Snippets -**Version:** 1.8.4 -**Last Updated:** 2026-03-24 +**Version:** 1.8.6 +**Last Updated:** 2026-04-10 **Location:** `specs/05-Engineering-Guidelines/05-06-code-snippets.md` --- @@ -92,6 +92,68 @@ return entity; --- +## Workflow Transition Pattern + +```typescript +// [workflow-transition] → Pattern สำหรับการเปลี่ยนสถานะเอกสารอย่างปลอดภัย +// ใช้ใน: WorkflowEngineService + +async transitionStatus( + publicId: string, // รับ UUIDv7 เท่านั้น (ADR-019) + targetStatus: DocumentStatus, + actor: RequestWithUser +): Promise { + // 1. ค้นหา Entity ด้วย publicId และตรวจสอบการมีอยู่ + const document = await this.repo.findOne({ + where: { publicId }, + relations: ['currentAssignee'], + }); + + if (!document) { + this.logger.warn(`ไม่พบเอกสาร UUID: ${publicId}`, 'WorkflowService'); + throw new NotFoundException(ErrorCode.DOC_NOT_FOUND); + } + + // 2. ตรวจสอบว่า transition นี้ถูกต้องตาม DSL (ADR-001) + await this.workflowEngine.validateTransition(document.workflowState, targetStatus); + + // 3. Business Logic Validation: ตรวจสอบสิทธิ์ผู้รับผิดชอบ + if (document.currentAssignee?.publicId !== actor.user.publicId) { + throw new ForbiddenException(ErrorCode.UNAUTHORIZED_TRANSITION); + } + + // 4. ปรับปรุงสถานะและใช้ @VersionColumn ใน Entity เพื่อทำ Optimistic Locking + try { + document.status = targetStatus; + document.updatedBy = actor.user.publicId; + + const savedDoc = await this.repo.save(document); + + // 5. บันทึก Audit Log + this.logger.log( + `เอกสาร ${publicId} เปลี่ยนสถานะเป็น ${targetStatus} โดย ${actor.user.publicId}` + ); + + // 6. ส่งงานเข้า Queue (BullMQ) สำหรับการส่ง Notification/Email (ADR-008) + await this.notificationQueue.add('status-change', { + docId: savedDoc.publicId, + status: targetStatus, + recipientPublicId: savedDoc.creatorPublicId, // ใช้ publicId ตาม ADR-019 + }); + + return savedDoc; + } catch (error) { + if (error instanceof OptimisticLockVersionMismatchError) { + // ป้องกันการแก้ไขซ้ำซ้อนในเวลาเดียวกัน (Race Condition) + throw new ConflictException('ข้อมูลถูกแก้ไขโดยผู้อื่นไปก่อนหน้าแล้ว กรุณารีเฟรชหน้าจอ'); + } + throw error; + } +} +``` + +--- + ## Reference - [Backend Guidelines](05-02-backend-guidelines.md) diff --git a/specs/05-Engineering-Guidelines/README.md b/specs/05-Engineering-Guidelines/README.md index 8483412..00a348f 100644 --- a/specs/05-Engineering-Guidelines/README.md +++ b/specs/05-Engineering-Guidelines/README.md @@ -10,9 +10,9 @@ | Attribute | Value | | ------------------ | -------------------------------- | -| **Version** | 1.8.1 | +| **Version** | 1.8.6 | | **Status** | Active | -| **Last Updated** | 2026-03-16 | +| **Last Updated** | 2026-04-10 | | **Owner** | Nattanin Peancharoen | | **Classification** | Internal Technical Documentation | @@ -29,6 +29,10 @@ - [2. Backend Guidelines](#2-backend-guidelines) - [3. Frontend Guidelines](#3-frontend-guidelines) - [4. Document Numbering System](#4-document-numbering-system) + - [5. Git Conventions](#5-git-conventions) + - [6. Code Snippets](#6-code-snippets) + - [7. UUID Implementation Plan](#7-uuid-implementation-plan) + - [8. i18n Guidelines](#8-i18n-guidelines) - [🧪 Testing Strategy](#-testing-strategy) - [🛠️ Technology Stack Recap](#️-technology-stack-recap) - [🔗 Related Documents](#-related-documents) @@ -79,7 +83,7 @@ - React Hook Form + Zod for Client Validation - API Client Interceptors (Auth & Idempotency) -### 4. [Document Numbering System](../01-Requirements/business-rules/01-02-02-doc-numbering-rules.md) +### 4. [Document Numbering System](../01-Requirements/01-02-business-rules/01-02-02-doc-numbering-rules.md) **รายละเอียดการนำระบบออกเลขที่เอกสารไปใช้งาน** @@ -88,6 +92,45 @@ - Reservation Flow (Phase 1: Reserve, Phase 2: Confirm) - API Specs for Numbering Management +### 5. [Git Conventions](./05-05-git-conventions.md) + +**มาตรฐานการใช้ Git และ Commit Messages** + +- Branch Naming (feature/, fix/, hotfix/) +- Commit Message Format (Conventional Commits) +- PR/Merge กระบวนการ +- [Git Cheatsheet](./05-05-git-cheatsheet.md) — คำสั่งที่ใช้บ่อย + +### 6. [Code Snippets](./05-06-code-snippets.md) + +**ตัวอย่างโค้ดที่ใช้ซ้ำบ่อย (Reusable Patterns)** + +- Backend DTO Pattern with `@IsUUID()` +- Frontend RHF + Zod Form Pattern +- UUID Safe Pattern +- Backend Error Handling Pattern +- Workflow Transition Pattern +- Redis Cache Pattern +- Frontend TanStack Query Pattern + +### 7. [UUID Implementation Plan](./05-07-hybrid-uuid-implementation-plan.md) + +**แผนการ Implement Hybrid Identifier (ADR-019)** + +- Migration Strategy (INT → UUIDv7) +- Backend: `UuidBaseEntity` Pattern +- Frontend: `publicId` Usage Guidelines +- API Response Standardization + +### 8. [i18n Guidelines](./05-08-i18n-guidelines.md) + +**แนวทางการทำ Localization** + +- i18n Key Structure (Thai/English) +- Error Message Keys vs Hardcoded Text +- Frontend Locale Organization +- Comments Language Policy (Thai for business, English for technical) + --- ## 🧪 Testing Strategy @@ -123,9 +166,9 @@
-**LCBP3-DMS Implementation Specification v1.8.1** +**LCBP3-DMS Implementation Specification v1.8.6** -[FullStack](./05-01-fullstack-js-guidelines.md) • [Backend](./05-02-backend-guidelines.md) • [Frontend](./05-03-frontend-guidelines.md) • [Testing](./05-04-testing-strategy.md) +[FullStack](./05-01-fullstack-js-guidelines.md) • [Backend](./05-02-backend-guidelines.md) • [Frontend](./05-03-frontend-guidelines.md) • [Testing](./05-04-testing-strategy.md) • [Git](./05-05-git-conventions.md) • [Snippets](./05-06-code-snippets.md) • [UUID](./05-07-hybrid-uuid-implementation-plan.md) • [i18n](./05-08-i18n-guidelines.md) [Main README](../../README.md) • [Architecture](../02-Architecture/README.md) • [Requirements](../01-Requirements/README.md) diff --git a/specs/06-Decision-Records/README.md b/specs/06-Decision-Records/README.md index adffcd4..ea7f4c3 100644 --- a/specs/06-Decision-Records/README.md +++ b/specs/06-Decision-Records/README.md @@ -1,7 +1,7 @@ # Architecture Decision Records (ADRs) -**Version:** 1.8.2 -**Last Updated:** 2026-04-04 +**Version:** 1.8.5 +**Last Updated:** 2026-04-10 **Project:** LCBP3-DMS (Laem Chabang Port Phase 3 - Document Management System) --- @@ -50,6 +50,7 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ | ADR | Title | Status | Date | Summary | | --------------------------------------------------- | ------------------------------------ | --------------------- | ---------- | --------------------------------------------------------------- | +| [ADR-004](./ADR-004-database-schema-design-strategy.md) | Database Schema Design Strategy | ✅ Accepted | 2026-04-04 | Selective Normalization + Standard Patterns (UUID, Soft Delete, Audit) | | [ADR-005](./ADR-005-technology-stack.md) | Technology Stack Selection | ✅ Accepted | 2026-02-24 | Full Stack TypeScript: NestJS 11 + Next.js 16 + MariaDB + Redis | | [ADR-006](./ADR-006-redis-caching-strategy.md) | Redis Usage & Caching Strategy | ✅ Accepted | 2026-02-24 | Redis สำหรับ Distributed Lock, Cache, Queue, และ Rate Limiting | | [ADR-009](./ADR-009-database-migration-strategy.md) | Database Migration & Deployment | ✅ Accepted (Pending) | 2026-02-24 | TypeORM Migrations พร้อม Blue-Green Deployment | @@ -59,6 +60,8 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ | ADR | Title | Status | Date | Summary | | --------------------------------------------------- | ----------------------------- | ---------------------------- | ---------- | ----------------------------------------------------------------------------- | +| [ADR-003](./ADR-003-api-design-strategy.md) | API Design Strategy | ✅ Accepted | 2026-04-04 | Hybrid REST + Action Strategy สำหรับ Resource และ Workflow Operations | +| [ADR-007](./ADR-007-error-handling-strategy.md) | Error Handling & Recovery | ✅ Accepted | 2026-04-04 | Layered Error Classification พร้อม User-friendly Messages และ Recovery Actions | | [ADR-008](./ADR-008-email-notification-strategy.md) | Email & Notification Strategy | ✅ Accepted (Pending Review) | 2026-02-24 | BullMQ + Redis Queue สำหรับ Multi-channel Notifications (Email, LINE, In-app) | ### Observability @@ -113,12 +116,15 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ ### 4. Infrastructure & Performance +- **ADR-004:** Database Schema Design - Selective Normalization + Standard Patterns - **ADR-005:** Technology Stack - TypeScript ecosystem (NestJS 11, Next.js 16) - **ADR-006:** Redis - Caching และ Distributed coordination - **ADR-015:** Deployment - Docker Compose with Blue-Green Deployment ### 5. API & Integration +- **ADR-003:** API Design - Hybrid REST + Action Strategy สำหรับ Resource และ Workflow Operations +- **ADR-007:** Error Handling - Layered Classification (Validation / Business / System) พร้อม Recovery Actions - **ADR-008:** Notification - BullMQ Queue สำหรับ Multi-channel notifications ### 6. Observability & Monitoring @@ -369,9 +375,9 @@ graph TB --- -**Version:** 1.8.2 (Enhanced Template + Review Process) -**Last Review:** 2026-04-04 -**Next Review:** 2026-10-04 +**Version:** 1.8.5 (Added ADR-003, ADR-004, ADR-007) +**Last Review:** 2026-04-10 +**Next Review:** 2026-10-10 ---