690517:1449 204 and 302 refactor #03
CI / CD Pipeline / build (push) Failing after 42s
CI / CD Pipeline / deploy (push) Has been skipped

This commit is contained in:
2026-05-17 14:49:45 +07:00
parent 544bb30277
commit 50bffdf38a
53 changed files with 4026 additions and 617 deletions
+1 -1
View File
@@ -63,7 +63,7 @@ Best practice — follow when possible:
---
## 📐 TypeScript Rules & Coding Standards (v1.9.0)
## 📐 TypeScript Rules & Coding Standards (v1.9.3)
### 📝 Core Standards
+3 -1
View File
@@ -30,7 +30,9 @@ trigger: always_on
- [ ] No SQL injection vulnerabilities
- [ ] File upload validation (whitelist + ClamAV)
- [ ] Rate limiting applied to auth endpoints
- [ ] AI boundary enforcement (ADR-018) - no direct DB/storage access
- [ ] AI boundary enforcement (ADR-023) - no direct DB/storage access
- [ ] AI audit logging implemented for AI interactions
- [ ] AI outputs validated before use (human-in-the-loop)
- [ ] Error handling follows ADR-007 layered classification
- [ ] Cache invalidation when data modified
- [ ] OWASP Top 10 review passed
+9 -1
View File
@@ -1,4 +1,4 @@
# TypeScript Rules (v1.9.0)
# TypeScript Rules (v1.9.3)
## Core Standards
@@ -13,10 +13,18 @@
## File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- Use **absolute path** from project root (e.g., `// File: backend/src/modules/correspondence/correspondence.service.ts`)
- Do NOT use relative path (e.g., `// File: src/example.service.ts`)
- **Change Log** — include `// Change Log` at the top of the file.
- **Single Export** — export **only one main symbol** per file.
- **Function Style** — avoid unnecessary blank lines inside functions.
## i18n Guidelines
- **No Hardcoded Text:** Use i18n keys for all user-facing text
- **Reference:** `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md`
- **Pattern:** Use `t('key.path')` from i18n hook instead of hardcoded strings
## Patterns
```typescript
+2 -1
View File
@@ -29,10 +29,11 @@ Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > oth
| 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 |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.9.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-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **ADR-023 AI** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | AI integration work |
| **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 |
+20 -18
View File
@@ -6,28 +6,30 @@ trigger: always_on
## ❌ Never Do This
| ❌ 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` |
| AI direct cloud API calls | On-premises Ollama only (ADR-018) |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-020) |
| ❌ 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 `lcbp3-v1.9.0-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-023) |
| 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` |
| AI direct cloud API calls | On-premises Ollama only (ADR-023) |
| AI outputs without human validation | Human-in-the-loop validation required (ADR-023) |
| n8n calling Ollama/Qdrant directly | n8n → DMS API → BullMQ → Ollama/Qdrant (ADR-023A) |
| Qdrant query without projectPublicId filter | QdrantService.search(projectPublicId: string) required (ADR-023A) |
## Schema Changes (ADR-009)
- **NO TypeORM migrations** — edit SQL schema directly
- Always check `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` before writing queries
- Always check `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` before writing queries
- Update Data Dictionary when changing fields
## UUID Handling
+7 -7
View File
@@ -1,10 +1,10 @@
---
trigger: glob
globs:
- "backend/**/*.service.ts"
- "backend/**/*.controller.ts"
- "backend/**/*.dto.ts"
- "backend/**/*.entity.ts"
- 'backend/**/*.service.ts'
- 'backend/**/*.controller.ts'
- 'backend/**/*.dto.ts'
- 'backend/**/*.entity.ts'
---
# Backend Patterns (NestJS)
@@ -25,7 +25,7 @@ async create(@Body() dto: CreateCorrespondenceDto) {
// Resolve UUID to internal ID
const contract = await this.contractService.findOneByUuid(dto.contractUuid);
const contractId = contract.id; // Internal INT for DB queries
return this.service.create(dto, contractId);
}
@@ -48,8 +48,8 @@ async create(dto: CreateCorrespondenceDto, contractId: number) {
class Contract extends UuidBaseEntity {
@Column({ type: 'uuid' })
publicId: string;
@PrimaryKey()
@PrimaryGeneratedColumn()
@Exclude()
id: number;
}
+12 -12
View File
@@ -10,7 +10,7 @@ trigger: always_on
1. **Glossary check** — verify domain terms in `00-02-glossary.md`
2. **Read the spec** — select from Key Spec Files table
3. **Check schema** — verify table/column in `schema-02-tables.sql`
3. **Check schema** — verify table/column in `lcbp3-v1.9.0-schema-02-tables.sql`
4. **Check data dictionary** — confirm field meanings + business rules
5. **Scan edge cases**`01-06-edge-cases-and-rules.md`
6. **Check ADRs** — verify decisions align (ADR-009, ADR-018, ADR-019)
@@ -20,7 +20,7 @@ trigger: always_on
- Follow existing patterns in codebase.
- Check spec for relevant module only.
- **Hybrid Specs Organization:**
- **Hybrid Specs Organization:**
- Place new Infrastructure tasks in `specs/100-Infrastructures/`
- Place new Feature/Workflow tasks in `specs/200-fullstacks/`
- Place Documentation/Research in `specs/300-others/`
@@ -34,13 +34,13 @@ trigger: always_on
## Context-Aware Triggers
| 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 |
| 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.md` | RHF+Zod + TanStack Query + Thai comments |
| "เพิ่ม field ใหม่" | `ADR-009`, `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" | `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 |
+69 -25
View File
@@ -2,32 +2,37 @@
trigger: always_on
---
# ADR-020 AI Integration Architecture
# ADR-023/023A AI Integration Architecture
## CRITICAL RULES
- **ALWAYS** follow ADR-018 AI boundary policy (isolation on Admin Desktop)
- **ALWAYS** use RFA-First approach for AI implementation
- **ALWAYS** follow ADR-023 AI boundary policy (isolation on Admin Desktop)
- **ALWAYS** use ADR-023A 2-model stack (gemma4:e4b Q8_0 + nomic-embed-text)
- **ALWAYS** use BullMQ 2-queue (ai-realtime + ai-batch) for GPU overload prevention
- **NEVER** allow AI direct database/storage access
- **ALWAYS** implement human-in-the-loop validation
- **NEVER** send sensitive data to cloud AI services
- **ALWAYS** enforce Qdrant projectPublicId filter (compile-time enforcement)
- **NEVER** allow n8n to call Ollama/Qdrant directly (must go through DMS API → BullMQ)
## AI Integration Patterns
### Architecture Overview
```
Frontend → AI Gateway API → Admin Desktop (Ollama) → Backend Validation
Frontend → AI Gateway API → BullMQ → Admin Desktop (Ollama) → Backend Validation
n8n (Migration) → DMS API → BullMQ → Admin Desktop (Ollama) → Backend Validation
```
### Key Components
| Component | Location | Purpose |
|-----------|----------|---------|
| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging |
| **Ollama Engine** | Admin Desktop (Desk-5439) | LLM inference (Gemma 4) |
| **OCR Engine** | Admin Desktop (Desk-5439) | Thai/English text extraction |
| **Orchestrator** | QNAP NAS (n8n) | Workflow management |
| Component | Location | Purpose |
| ----------------- | ------------------------- | ------------------------------------------------------------------------ |
| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging |
| **BullMQ Queues** | Backend (NestJS) | ai-realtime (RAG/Suggest), ai-batch (OCR/Extract/Embed) |
| **Ollama Engine** | Admin Desktop (Desk-5439) | gemma4:e4b Q8_0 (LLM) + nomic-embed-text (Embedding) |
| **OCR Engine** | Admin Desktop (Desk-5439) | PaddleOCR + PyThaiNLP (Thai/English text extraction) |
| **Orchestrator** | QNAP NAS (n8n) | Migration Phase orchestrator only (calls DMS API, never Ollama directly) |
## Backend Implementation (NestJS)
@@ -35,24 +40,50 @@ Frontend → AI Gateway API → Admin Desktop (Ollama) → Backend Validation
// AI Module with boundary enforcement
@Module({
controllers: [AiController],
providers: [AiService, AiGateway],
providers: [AiService, AiGateway, QdrantService],
exports: [AiService],
})
export class AiModule {
constructor() {
// Enforce ADR-018 boundaries
// Enforce ADR-023 boundaries
}
}
// QdrantService with compile-time projectPublicId enforcement
@Injectable()
export class QdrantService {
async search(
projectPublicId: string, // required — compile-time enforcement
vector: number[],
topK: number = 5,
): Promise<QdrantSearchResult[]> {
return this.client.search('documents', {
vector,
limit: topK,
filter: {
must: [{ key: 'project_public_id', match: { value: projectPublicId } }],
},
});
}
async upsert(
projectPublicId: string, // required
chunks: DocumentChunk[],
): Promise<void> { ... }
// ❌ NEVER expose rawSearch() or method without projectPublicId filter
}
// AI Service with validation
@Injectable()
export class AiService {
async extractMetadata(documentId: string): Promise<AIMetadata> {
// 1. Validate permissions
// 2. Send to Admin Desktop AI
// 3. Validate AI response
// 4. Log audit trail
// 5. Return validated results
// 2. Queue job to BullMQ (ai-batch or ai-realtime)
// 3. Worker sends to Admin Desktop AI (gemma4:e4b Q8_0)
// 4. Validate AI response
// 5. Log audit trail to ai_audit_logs
// 6. Return validated results
}
}
```
@@ -77,24 +108,37 @@ const DocumentReviewForm = ({ document, aiSuggestions }) => {
## Security Requirements
- **AI Isolation:** All AI processing on Admin Desktop only
- **AI Isolation:** All AI processing on Admin Desktop only (Desk-5439)
- **Data Privacy:** No cloud AI services, on-premises only
- **Audit Trail:** Log all AI interactions and human validations
- **Audit Trail:** Log all AI interactions and human validations to ai_audit_logs
- **Rate Limiting:** Prevent AI abuse and resource exhaustion
- **Validation:** All AI outputs must be validated before use
- **Multi-tenant Isolation:** Qdrant queries MUST include projectPublicId filter (compile-time enforcement)
- **n8n Boundary:** n8n MUST call DMS API → BullMQ, NEVER Ollama/Qdrant directly
- **GPU Overload Prevention:** BullMQ 2-queue (ai-realtime + ai-batch) with concurrency=1
## ADR-023A Specific Rules
- **2-Model Stack:** gemma4:e4b Q8_0 (~4.0GB) + nomic-embed-text (~0.3GB) = ~4.3GB VRAM peak
- **PDF 3-Page Limit:** Classification/Tagging uses first 3 pages only (NOT RAG embedding)
- **RAG Embedding:** Full document chunked at 512 tokens/64 tokens overlap
- **OCR Auto-Detect:** PyMuPDF chars > 100 → Fast path, else PaddleOCR
- **Embed Auto-Trigger:** AUTO after commit (parallel), gap covered by DB search
- **Threshold Recalibration:** After 100-500 docs, based on ai_audit_logs analysis
## Required Implementation
- [ ] AiModule with ADR-018 boundary enforcement
- [ ] AiModule with ADR-023 boundary enforcement
- [ ] AI Gateway API endpoints with validation
- [ ] BullMQ 2-queue setup (ai-realtime + ai-batch)
- [ ] QdrantService with projectPublicId enforcement
- [ ] DocumentReviewForm reusable component
- [ ] Admin Desktop Ollama + PaddleOCR setup
- [ ] n8n workflow orchestration
- [ ] AI audit logging and monitoring
- [ ] Admin Desktop Ollama (gemma4:e4b Q8_0 + nomic-embed-text) + PaddleOCR setup
- [ ] n8n workflow orchestration (Migration Phase only)
- [ ] AI audit logging and monitoring (ai_audit_logs)
- [ ] Human-in-the-loop validation workflows
## Related Documents
- `specs/06-Decision-Records/ADR-018-ai-boundary.md`
- `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md`
- `specs/06-Decision-Records/ADR-017-ollama-data-migration.md`
- `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` (Base architecture)
- `specs/06-Decision-Records/ADR-023A-unified-ai-architecture.md` (Model revision - current)
+115
View File
@@ -0,0 +1,115 @@
# LCBP3 Agent Rules
Critical rules and guidelines for AI agents working on LCBP3-DMS.
## Version
- **Current:** v1.9.3
- **Last Updated:** 2026-05-15
- **Synced with:** `AGENTS.md` (v1.9.3)
## Purpose
This directory contains rule files that define:
- Project context and role expectations
- Critical Tier 1 rules (CI blockers)
- Coding standards and patterns
- Domain terminology and glossary
- Development workflows
- Security requirements
- AI integration architecture (ADR-023/023A)
## Rule Enforcement Tiers
### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Build fails immediately if violated:
- Security (Auth, RBAC, Validation)
- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID
- Database correctness — verify schema before writing queries
- File upload security (ClamAV + whitelist)
- AI validation boundary (ADR-023)
- Error handling strategy (ADR-007)
- Forbidden patterns: `any`, `console.log`, UUID misuse, `id ?? ''` fallback
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
Must fix before merge:
- Architecture patterns (thin controller, business logic in service)
- Test coverage (80%+ business logic, 70%+ backend overall)
- Cache invalidation
- Naming conventions
- TypeScript Standards: Missing JSDoc, explicit types, or file headers
### 🟢 Tier 3 — GUIDELINES
Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
## Rule Files
### Core Rules (Tier 1 - CRITICAL)
| File | Purpose |
|------|---------|
| `00-project-context.md` | Project context, role & persona, tier classification, specs folder organization |
| `01-adr-019-uuid.md` | UUID handling strategy — no parseInt, use publicId only |
| `02-security.md` | Security requirements, checklist, ADR-023/023A AI boundaries |
### Coding Standards
| File | Purpose |
|------|---------|
| `03-typescript.md` | TypeScript rules, file headers, i18n guidelines |
| `06-backend-patterns.md` | NestJS patterns, UUID resolution, API response patterns |
| `07-frontend-patterns.md` | Next.js patterns, RHF+Zod+TanStack Query, UUID handling |
### Domain & Workflow
| File | Purpose |
|------|---------|
| `04-domain-terminology.md` | DMS glossary, key spec files priority table |
| `08-development-flow.md` | Development workflow by work type (Critical/Normal/Quick Fix) |
### Compliance & Architecture
| File | Purpose |
|------|---------|
| `05-forbidden-actions.md` | Actions that must never be done, schema changes, UUID handling |
| `09-commit-checklist.md` | Pre-commit verification, commit message format |
| `10-error-handling.md` | ADR-007 error handling strategy, layered classification |
| `11-ai-integration.md` | ADR-023/023A AI architecture, 2-model stack, BullMQ 2-queue |
## Key Spec Files Priority
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.9.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-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work |
| **ADR-023 AI** | `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md` | AI integration work |
| **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 |
## Maintenance
When updating rules:
1. **Check AGENTS.md version** — Ensure rule files are synced
2. **Update version numbers** — Bump version in `00-project-context.md` and `03-typescript.md`
3. **Review ADR references** — Ensure all ADR references are current (ADR-023, ADR-023A, etc.)
4. **Add new forbidden actions** — When new patterns are identified as violations
5. **Update key spec files table** — When new ADRs or guidelines are added
## Related Documents
- `AGENTS.md` — Master agent configuration and context
- `specs/06-Decision-Records/` — All Architecture Decision Records
- `specs/05-Engineering-Guidelines/` — Backend, frontend, and testing guidelines