690517:1449 204 and 302 refactor #03
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
+14
-11
@@ -1,6 +1,6 @@
|
||||
# `.agents/skills/` — LCBP3 Agent Skill Pack
|
||||
|
||||
**Version:** 1.8.9 | **Last Updated:** 2026-04-22 | **Total Skills:** 20
|
||||
**Version:** 1.9.0 | **Last Updated:** 2026-05-17 | **Total Skills:** 23
|
||||
|
||||
Agent skills for AI-assisted development in **Windsurf IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
|
||||
|
||||
@@ -16,12 +16,15 @@ Agent skills for AI-assisted development in **Windsurf IDE** (and compatible age
|
||||
├── README.md # (this file)
|
||||
├── nestjs-best-practices/ # Backend rules (40 rules across 10 categories)
|
||||
├── next-best-practices/ # Frontend rules (Next.js 15+)
|
||||
├── e2e-testing/ # Playwright E2E testing patterns (POM, flaky tests, CI/CD)
|
||||
├── verification-loop/ # Comprehensive verification (build, typecheck, lint, test, security)
|
||||
├── security-review/ # OWASP Top 10 + ADR compliance checklist
|
||||
└── speckit-*/ # 18 workflow skills (spec → plan → tasks → implement → …)
|
||||
```
|
||||
|
||||
Each skill directory contains:
|
||||
|
||||
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.8.9`, `scope`, `depends-on`, `handoffs`) + instructions
|
||||
- `SKILL.md` — frontmatter (`name`, `description`, `version: 1.9.0`, `scope`, `depends-on`, `handoffs`) + instructions
|
||||
- `templates/` _(optional)_ — artifact templates (spec/plan/tasks/checklist)
|
||||
- `rules/` _(nestjs only)_ — individual rule files grouped by prefix (`arch-`, `security-`, `db-`, etc.)
|
||||
|
||||
@@ -62,14 +65,14 @@ Use `/00-speckit.all` to run specify → clarify → plan → tasks → analyze
|
||||
|
||||
From repo root:
|
||||
|
||||
| Script | Purpose |
|
||||
| --- | --- |
|
||||
| `./.agents/scripts/bash/check-prerequisites.sh --json` | Emit `FEATURE_DIR` + `AVAILABLE_DOCS` for a feature branch |
|
||||
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
|
||||
| `./.agents/scripts/bash/update-agent-context.sh windsurf` | Append tech entries to `AGENTS.md` |
|
||||
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
|
||||
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
|
||||
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.windsurf/workflows/*.md` wrapper |
|
||||
| Script | Purpose |
|
||||
| --------------------------------------------------------- | ----------------------------------------------------------- |
|
||||
| `./.agents/scripts/bash/check-prerequisites.sh --json` | Emit `FEATURE_DIR` + `AVAILABLE_DOCS` for a feature branch |
|
||||
| `./.agents/scripts/bash/setup-plan.sh --json` | Emit `FEATURE_SPEC`, `IMPL_PLAN`, `SPECS_DIR`, `BRANCH` |
|
||||
| `./.agents/scripts/bash/update-agent-context.sh windsurf` | Append tech entries to `AGENTS.md` |
|
||||
| `./.agents/scripts/bash/audit-skills.sh` | Validate all `SKILL.md` frontmatter + presence |
|
||||
| `./.agents/scripts/bash/validate-versions.sh` | Version consistency check |
|
||||
| `./.agents/scripts/bash/sync-workflows.sh` | Verify every skill has a `.windsurf/workflows/*.md` wrapper |
|
||||
|
||||
All scripts mirror to `.agents/scripts/powershell/*.ps1` for Windows.
|
||||
|
||||
@@ -92,7 +95,7 @@ See [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md) for the complete list.
|
||||
|
||||
To add a new skill:
|
||||
|
||||
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.8.9`, `scope`, `depends-on`.
|
||||
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.9.0`, `scope`, `depends-on`.
|
||||
2. Append an LCBP3 context reference pointing to `_LCBP3-CONTEXT.md`.
|
||||
3. Wrap with `.windsurf/workflows/NAME.md` so it becomes a slash command.
|
||||
4. Update [`skills.md`](./skills.md) dependency matrix.
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
## 🔴 Tier 1 Non-Negotiables
|
||||
|
||||
- **ADR-019 UUID:** `publicId: string` exposed directly — **no** `@Expose({ name: 'id' })` rename; **no** `parseInt`/`Number`/`+` on UUID; **no** `id ?? ''` fallback in frontend.
|
||||
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
|
||||
- **ADR-009:** No TypeORM migrations — edit `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` or add a `deltas/*.sql` file.
|
||||
- **ADR-016 Security:** JWT + CASL 4-Level RBAC; `@UseGuards(JwtAuthGuard, CaslAbilityGuard)` on every mutation controller; `ThrottlerGuard` on auth; bcrypt 12 rounds; `Idempotency-Key` required on POST/PUT/PATCH.
|
||||
- **ADR-002 Document Numbering:** Redis Redlock + TypeORM `@VersionColumn` (double-lock). Never use application-side counter alone.
|
||||
- **ADR-008 Notifications:** BullMQ queue — never inline email/notification in a request thread.
|
||||
@@ -59,7 +59,7 @@
|
||||
| A plan | `.agents/skills/speckit-plan/templates/plan-template.md` + relevant ADRs |
|
||||
| Task breakdown | `.agents/skills/speckit-tasks/templates/tasks-template.md` + existing patterns in `specs/08-Tasks/` |
|
||||
| Acceptance criteria / UAT | `specs/01-Requirements/01-05-acceptance-criteria.md` |
|
||||
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
|
||||
| Schema / table definition | `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql` + `03-01-data-dictionary.md` |
|
||||
| RBAC / permissions | `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-permissions.sql` + `01-02-01-rbac-matrix.md` |
|
||||
| Release / hotfix | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` |
|
||||
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
---
|
||||
name: e2e-testing
|
||||
description: Playwright E2E testing patterns, Page Object Model, configuration, CI/CD integration, artifact management, and flaky test strategies for LCBP3-DMS.
|
||||
version: 1.9.0
|
||||
scope: testing
|
||||
depends-on: []
|
||||
handoffs-to: [speckit-tester]
|
||||
user-invocable: true
|
||||
---
|
||||
|
||||
# E2E Testing Skill
|
||||
|
||||
Playwright E2E testing patterns adapted for LCBP3-DMS (NestJS + Next.js + MariaDB stack).
|
||||
|
||||
## LCBP3 Context
|
||||
|
||||
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific testing requirements:
|
||||
- Backend: Jest (Unit + Integration + E2E)
|
||||
- Frontend: Vitest (Unit) + Playwright (E2E)
|
||||
- E2E test location: `frontend/e2e/workflow-adr021.spec.ts`
|
||||
- Coverage goals: Backend 70%+, Business Logic 80%+
|
||||
|
||||
## When to Use
|
||||
|
||||
Invoke this skill when:
|
||||
- Creating new E2E tests for frontend features
|
||||
- Debugging flaky Playwright tests
|
||||
- Setting up CI/CD integration for E2E tests
|
||||
- Optimizing test performance and reliability
|
||||
- Implementing Page Object Model (POM) patterns
|
||||
|
||||
## Test File Organization
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── e2e/
|
||||
│ ├── auth/
|
||||
│ │ ├── login.spec.ts
|
||||
│ │ └── logout.spec.ts
|
||||
│ ├── correspondence/
|
||||
│ │ ├── create.spec.ts
|
||||
│ │ └── workflow.spec.ts
|
||||
│ ├── transmittals/
|
||||
│ │ ├── create.spec.ts
|
||||
│ │ └── submit.spec.ts
|
||||
│ ├── circulation/
|
||||
│ │ ├── routing.spec.ts
|
||||
│ │ └── approval.spec.ts
|
||||
│ └── workflow-adr021.spec.ts # Existing ADR-021 integration test
|
||||
├── playwright.config.ts
|
||||
└── tests/
|
||||
└── fixtures/
|
||||
├── auth.ts
|
||||
└── data.ts
|
||||
```
|
||||
|
||||
## Page Object Model (POM)
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/pages/CorrespondencePage.ts
|
||||
import { Page, Locator } from '@playwright/test'
|
||||
|
||||
export class CorrespondencePage {
|
||||
readonly page: Page
|
||||
readonly createButton: Locator
|
||||
readonly subjectInput: Locator
|
||||
readonly recipientSelect: Locator
|
||||
readonly submitButton: Locator
|
||||
readonly successMessage: Locator
|
||||
|
||||
constructor(page: Page) {
|
||||
this.page = page
|
||||
this.createButton = page.getByTestId('create-correspondence')
|
||||
this.subjectInput = page.getByTestId('subject-input')
|
||||
this.recipientSelect = page.getByTestId('recipient-select')
|
||||
this.submitButton = page.getByTestId('submit-button')
|
||||
this.successMessage = page.getByTestId('success-message')
|
||||
}
|
||||
|
||||
async goto() {
|
||||
await this.page.goto('/admin/doc-control/correspondences')
|
||||
await this.page.waitForLoadState('networkidle')
|
||||
}
|
||||
|
||||
async createCorrespondence(data: {
|
||||
subject: string
|
||||
recipientId: string
|
||||
}) {
|
||||
await this.createButton.click()
|
||||
await this.subjectInput.fill(data.subject)
|
||||
await this.recipientSelect.selectOption(data.recipientId)
|
||||
await this.submitButton.click()
|
||||
}
|
||||
|
||||
async verifySuccess() {
|
||||
await expect(this.successMessage).toBeVisible()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Test Structure
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/correspondence/create.spec.ts
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { CorrespondencePage } from '../pages/CorrespondencePage'
|
||||
|
||||
test.describe('Correspondence Creation', () => {
|
||||
let correspondencePage: CorrespondencePage
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
correspondencePage = new CorrespondencePage(page)
|
||||
await correspondencePage.goto()
|
||||
})
|
||||
|
||||
test('should create correspondence successfully', async ({ page }) => {
|
||||
await correspondencePage.createCorrespondence({
|
||||
subject: 'Test Correspondence',
|
||||
recipientId: 'test-recipient-id'
|
||||
})
|
||||
|
||||
await correspondencePage.verifySuccess()
|
||||
await page.screenshot({ path: 'artifacts/correspondence-created.png' })
|
||||
})
|
||||
|
||||
test('should validate required fields', async ({ page }) => {
|
||||
await correspondencePage.createButton.click()
|
||||
await correspondencePage.submitButton.click()
|
||||
|
||||
await expect(page.getByTestId('subject-error')).toBeVisible()
|
||||
await expect(page.getByTestId('recipient-error')).toBeVisible()
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Playwright Configuration
|
||||
|
||||
```typescript
|
||||
// frontend/playwright.config.ts
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
reporter: [
|
||||
['html', { outputFolder: 'playwright-report' }],
|
||||
['junit', { outputFile: 'playwright-results.xml' }],
|
||||
['json', { outputFile: 'playwright-results.json' }]
|
||||
],
|
||||
use: {
|
||||
baseURL: process.env.BASE_URL || 'http://localhost:3000',
|
||||
trace: 'on-first-retry',
|
||||
screenshot: 'only-on-failure',
|
||||
video: 'retain-on-failure',
|
||||
actionTimeout: 10000,
|
||||
navigationTimeout: 30000,
|
||||
},
|
||||
projects: [
|
||||
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
|
||||
],
|
||||
webServer: {
|
||||
command: 'pnpm dev',
|
||||
url: 'http://localhost:3000',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120000,
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## Flaky Test Patterns
|
||||
|
||||
### Quarantine
|
||||
|
||||
```typescript
|
||||
test('flaky: complex workflow', async ({ page }) => {
|
||||
test.fixme(true, 'Flaky - Issue #123')
|
||||
// test code...
|
||||
})
|
||||
|
||||
test('conditional skip', async ({ page }) => {
|
||||
test.skip(process.env.CI, 'Flaky in CI - Issue #123')
|
||||
// test code...
|
||||
})
|
||||
```
|
||||
|
||||
### Identify Flakiness
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npx playwright test e2e/correspondence/create.spec.ts --repeat-each=10
|
||||
npx playwright test e2e/correspondence/create.spec.ts --retries=3
|
||||
```
|
||||
|
||||
### Common Causes & Fixes
|
||||
|
||||
**Race conditions:**
|
||||
```typescript
|
||||
// Bad: assumes element is ready
|
||||
await page.click('[data-testid="submit-button"]')
|
||||
|
||||
// Good: auto-wait locator
|
||||
await page.locator('[data-testid="submit-button"]').click()
|
||||
```
|
||||
|
||||
**Network timing:**
|
||||
```typescript
|
||||
// Bad: arbitrary timeout
|
||||
await page.waitForTimeout(5000)
|
||||
|
||||
// Good: wait for specific condition
|
||||
await page.waitForResponse(resp =>
|
||||
resp.url().includes('/api/correspondences') && resp.status() === 201
|
||||
)
|
||||
```
|
||||
|
||||
**Animation timing:**
|
||||
```typescript
|
||||
// Bad: click during animation
|
||||
await page.click('[data-testid="menu-item"]')
|
||||
|
||||
// Good: wait for stability
|
||||
await page.locator('[data-testid="menu-item"]').waitFor({ state: 'visible' })
|
||||
await page.waitForLoadState('networkidle')
|
||||
await page.locator('[data-testid="menu-item"]').click()
|
||||
```
|
||||
|
||||
## Artifact Management
|
||||
|
||||
### Screenshots
|
||||
|
||||
```typescript
|
||||
await page.screenshot({ path: 'artifacts/after-login.png' })
|
||||
await page.screenshot({ path: 'artifacts/full-page.png', fullPage: true })
|
||||
await page.locator('[data-testid="workflow-banner"]').screenshot({
|
||||
path: 'artifacts/workflow-banner.png'
|
||||
})
|
||||
```
|
||||
|
||||
### Traces
|
||||
|
||||
```typescript
|
||||
// In playwright.config.ts
|
||||
use: {
|
||||
trace: 'on-first-retry'
|
||||
}
|
||||
|
||||
// View trace
|
||||
npx playwright show-trace trace.zip
|
||||
```
|
||||
|
||||
### Video
|
||||
|
||||
```typescript
|
||||
// In playwright.config.ts
|
||||
use: {
|
||||
video: 'retain-on-failure',
|
||||
videosPath: 'artifacts/videos/'
|
||||
}
|
||||
```
|
||||
|
||||
## CI/CD Integration
|
||||
|
||||
```yaml
|
||||
# .github/workflows/e2e.yml
|
||||
name: E2E Tests
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
- run: pnpm install
|
||||
- run: cd frontend && npx playwright install --with-deps
|
||||
- run: cd frontend && npx playwright test
|
||||
env:
|
||||
BASE_URL: ${{ vars.STAGING_URL }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: frontend/playwright-report/
|
||||
retention-days: 30
|
||||
```
|
||||
|
||||
## Test Report Template
|
||||
|
||||
```markdown
|
||||
# E2E Test Report
|
||||
|
||||
**Date:** YYYY-MM-DD HH:MM
|
||||
**Duration:** Xm Ys
|
||||
**Status:** PASSING / FAILING
|
||||
|
||||
## Summary
|
||||
- Total: X | Passed: Y (Z%) | Failed: A | Flaky: B | Skipped: C
|
||||
|
||||
## Failed Tests
|
||||
|
||||
### correspondence-create
|
||||
**File:** `frontend/e2e/correspondence/create.spec.ts:45`
|
||||
**Error:** Expected element to be visible
|
||||
**Screenshot:** artifacts/failed.png
|
||||
**Recommended Fix:** Add waitForLoadState after form submission
|
||||
|
||||
## Artifacts
|
||||
- HTML Report: frontend/playwright-report/index.html
|
||||
- Screenshots: frontend/artifacts/*.png
|
||||
- Videos: frontend/artifacts/videos/*.webm
|
||||
- Traces: frontend/artifacts/*.zip
|
||||
```
|
||||
|
||||
## Critical Flow Testing
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/workflow/adr021.spec.ts
|
||||
test('workflow: correspondence → rfa → approval', async ({ page }) => {
|
||||
// Create correspondence
|
||||
await createCorrespondence(page)
|
||||
await expect(page.getByTestId('correspondence-created')).toBeVisible()
|
||||
|
||||
// Submit for RFA
|
||||
await page.getByTestId('submit-rfa').click()
|
||||
await expect(page.getByTestId('rfa-submitted')).toBeVisible()
|
||||
|
||||
// Approve RFA
|
||||
await page.goto('/admin/doc-control/rfa/123')
|
||||
await page.getByTestId('approve-button').click()
|
||||
await expect(page.getByTestId('approval-success')).toBeVisible()
|
||||
|
||||
// Verify workflow state
|
||||
await expect(page.getByTestId('workflow-state')).toContainText('APPROVED')
|
||||
})
|
||||
```
|
||||
|
||||
## LCBP3-Specific Considerations
|
||||
|
||||
- **UUID Handling:** Use `publicId` (string UUID) in E2E tests, never `parseInt()` (ADR-019)
|
||||
- **Authentication:** Mock auth tokens for E2E tests to avoid real auth flows
|
||||
- **Workflow States:** Test ADR-021 workflow transitions (DRAFT → PENDING → APPROVED)
|
||||
- **i18n:** Test with Thai language to verify i18n key resolution
|
||||
- **RBAC:** Test different user roles (admin, user, reviewer) for permission checks
|
||||
|
||||
## References
|
||||
|
||||
- LCBP3 Testing Strategy: `specs/05-Engineering-Guidelines/05-04-testing-strategy.md`
|
||||
- ADR-021 Workflow Context: `specs/06-Decision-Records/ADR-021-workflow-context.md`
|
||||
- Existing E2E test: `frontend/e2e/workflow-adr021.spec.ts`
|
||||
@@ -126,7 +126,7 @@ These rules override general NestJS best practices for the NAP-DMS project:
|
||||
### ADR-009: No TypeORM Migrations
|
||||
|
||||
- **ห้ามสร้างไฟล์ migration ของ TypeORM**
|
||||
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
|
||||
- แก้ไข schema โดยตรงที่: `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
|
||||
- ใช้ n8n workflow สำหรับ data migration ถ้าจำเป็น
|
||||
|
||||
### ADR-019: Hybrid Identifier Strategy (CRITICAL — March 2026 Pattern)
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
---
|
||||
name: security-review
|
||||
description: Comprehensive security review for LCBP3-DMS with OWASP Top 10 checklist, ADR compliance, and automated security testing patterns.
|
||||
version: 1.9.0
|
||||
scope: security
|
||||
depends-on: []
|
||||
handoffs-to: [speckit-reviewer, speckit-security-audit]
|
||||
user-invocable: true
|
||||
---
|
||||
|
||||
# Security Review Skill
|
||||
|
||||
Comprehensive security review for LCBP3-DMS ensuring all code follows security best practices and identifies potential vulnerabilities.
|
||||
|
||||
## LCBP3 Context
|
||||
|
||||
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific security requirements:
|
||||
- **ADR-016**: Security & Authentication (JWT, CASL, RBAC, file upload)
|
||||
- **ADR-018**: AI Boundary (Ollama on Admin Desktop only, no direct DB/storage access)
|
||||
- **ADR-019**: UUID Strategy (no parseInt/Number/+ on UUID)
|
||||
- **ADR-023**: Unified AI Architecture (AI via DMS API only)
|
||||
- **ADR-007**: Error Handling (layered error classification)
|
||||
|
||||
## When to Activate
|
||||
|
||||
Invoke this skill:
|
||||
- Implementing authentication or authorization
|
||||
- Handling user input or file uploads
|
||||
- Creating new API endpoints
|
||||
- Working with secrets or credentials
|
||||
- Integrating AI features (Ollama/Qdrant)
|
||||
- Storing or transmitting sensitive data
|
||||
- Integrating third-party APIs
|
||||
|
||||
## Security Checklist
|
||||
|
||||
### 1. Secrets Management
|
||||
|
||||
#### FAIL: NEVER Do This
|
||||
```typescript
|
||||
const apiKey = "sk-proj-xxxxx" // Hardcoded secret
|
||||
const dbPassword = "password123" // In source code
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Do This
|
||||
```typescript
|
||||
const apiKey = process.env.OPENAI_API_KEY
|
||||
const dbUrl = process.env.DATABASE_URL
|
||||
|
||||
// Verify secrets exist
|
||||
if (!apiKey) {
|
||||
throw new Error('OPENAI_API_KEY not configured')
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] No hardcoded API keys, tokens, or passwords
|
||||
- [ ] All secrets in environment variables
|
||||
- [ ] `.env.local` in .gitignore
|
||||
- [ ] No secrets in git history
|
||||
- [ ] Production secrets in QNAP docker-compose environment section (not .env files)
|
||||
|
||||
### 2. Input Validation
|
||||
|
||||
#### Always Validate User Input
|
||||
```typescript
|
||||
import { z } from 'zod'
|
||||
|
||||
// Define validation schema
|
||||
const CreateCorrespondenceSchema = z.object({
|
||||
subject: z.string().min(1).max(500),
|
||||
recipientId: z.string().uuid(),
|
||||
typeCode: z.string().min(1).max(50)
|
||||
})
|
||||
|
||||
// Validate before processing
|
||||
export async function createCorrespondence(input: unknown) {
|
||||
try {
|
||||
const validated = CreateCorrespondenceSchema.parse(input)
|
||||
return await correspondenceService.create(validated)
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
throw new BadRequestException(error.errors)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### File Upload Validation (ADR-016)
|
||||
```typescript
|
||||
function validateFileUpload(file: Express.Multer.File) {
|
||||
// Size check (50MB max per ADR-016)
|
||||
const maxSize = 50 * 1024 * 1024
|
||||
if (file.size > maxSize) {
|
||||
throw new BadRequestException('File too large (max 50MB)')
|
||||
}
|
||||
|
||||
// Type check (whitelist: PDF, DWG, DOCX, XLSX, ZIP)
|
||||
const allowedTypes = [
|
||||
'application/pdf',
|
||||
'application/vnd.dwg',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/zip'
|
||||
]
|
||||
if (!allowedTypes.includes(file.mimetype)) {
|
||||
throw new BadRequestException('Invalid file type')
|
||||
}
|
||||
|
||||
// Extension check
|
||||
const allowedExtensions = ['.pdf', '.dwg', '.docx', '.xlsx', '.zip']
|
||||
const extension = path.extname(file.originalname).toLowerCase()
|
||||
if (!allowedExtensions.includes(extension)) {
|
||||
throw new BadRequestException('Invalid file extension')
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] All user inputs validated with Zod (frontend) + class-validator (backend)
|
||||
- [ ] File uploads restricted (50MB max, whitelist types)
|
||||
- [ ] No direct use of user input in queries
|
||||
- [ ] Whitelist validation (not blacklist)
|
||||
- [ ] Error messages don't leak sensitive info
|
||||
|
||||
### 3. SQL Injection Prevention
|
||||
|
||||
#### FAIL: NEVER Concatenate SQL
|
||||
```typescript
|
||||
// DANGEROUS - SQL Injection vulnerability
|
||||
const query = `SELECT * FROM correspondences WHERE uuid = '${correspondenceUuid}'`
|
||||
await this.connection.query(query)
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Use TypeORM Parameterized Queries
|
||||
```typescript
|
||||
// Safe - TypeORM parameterized query
|
||||
const correspondence = await this.correspondenceRepository.findOne({
|
||||
where: { publicId: correspondenceUuid }
|
||||
})
|
||||
|
||||
// Or with QueryBuilder
|
||||
const result = await this.correspondenceRepository
|
||||
.createQueryBuilder('c')
|
||||
.where('c.publicId = :uuid', { uuid: correspondenceUuid })
|
||||
.getOne()
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] All database queries use TypeORM parameterized queries
|
||||
- [ ] No string concatenation in SQL
|
||||
- [ ] TypeORM query builder used correctly
|
||||
- [ ] Schema verified before writing queries (ADR-009)
|
||||
|
||||
### 4. Authentication & Authorization (ADR-016)
|
||||
|
||||
#### JWT Token Handling
|
||||
```typescript
|
||||
// FAIL: WRONG: localStorage (vulnerable to XSS)
|
||||
localStorage.setItem('token', token)
|
||||
|
||||
// PASS: CORRECT: httpOnly cookies
|
||||
response.setHeader('Set-Cookie',
|
||||
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`
|
||||
)
|
||||
```
|
||||
|
||||
#### Authorization Checks (CASL)
|
||||
```typescript
|
||||
// Controller with CASL guard
|
||||
@Post()
|
||||
@UseGuards(JwtAuthGuard, RolesGuard, AbilitiesGuard)
|
||||
@CheckAbilities({ action: 'create', subject: 'Correspondence' })
|
||||
async create(@Body() dto: CreateCorrespondenceDto, @Request() req) {
|
||||
// Service logic
|
||||
}
|
||||
```
|
||||
|
||||
#### RBAC Matrix (ADR-016)
|
||||
- [ ] 4-Level RBAC matrix implemented (Admin, Manager, User, Viewer)
|
||||
- [ ] CASL AbilityFactory configured with correct permissions
|
||||
- [ ] JwtAuthGuard on all protected routes
|
||||
- [ ] RolesGuard for role-based access
|
||||
- [ ] AuditLogInterceptor on all mutation endpoints
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] Tokens stored in httpOnly cookies (not localStorage)
|
||||
- [ ] Authorization checks before sensitive operations
|
||||
- [ ] CASL abilities configured correctly
|
||||
- [ ] Role-based access control implemented
|
||||
- [ ] Session management secure
|
||||
|
||||
### 5. XSS Prevention
|
||||
|
||||
#### Sanitize HTML
|
||||
```typescript
|
||||
import DOMPurify from 'isomorphic-dompurify'
|
||||
|
||||
// ALWAYS sanitize user-provided HTML
|
||||
function renderUserContent(html: string) {
|
||||
const clean = DOMPurify.sanitize(html, {
|
||||
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
|
||||
ALLOWED_ATTR: []
|
||||
})
|
||||
return <div dangerouslySetInnerHTML={{ __html: clean }} />
|
||||
}
|
||||
```
|
||||
|
||||
#### Content Security Policy (Next.js)
|
||||
```typescript
|
||||
// next.config.js
|
||||
const securityHeaders = [
|
||||
{
|
||||
key: 'Content-Security-Policy',
|
||||
value: `
|
||||
default-src 'self';
|
||||
script-src 'self' 'unsafe-eval' 'unsafe-inline';
|
||||
style-src 'self' 'unsafe-inline';
|
||||
img-src 'self' data: https:;
|
||||
font-src 'self';
|
||||
connect-src 'self' http://localhost:3001 https://192.168.10.8;
|
||||
`.replace(/\s{2,}/g, ' ').trim()
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] User-provided HTML sanitized
|
||||
- [ ] CSP headers configured
|
||||
- [ ] No unvalidated dynamic content rendering
|
||||
- [ ] React's built-in XSS protection used
|
||||
|
||||
### 6. CSRF Protection
|
||||
|
||||
#### CSRF Tokens
|
||||
```typescript
|
||||
import { csrf } from '@/lib/csrf'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const token = request.headers.get('X-CSRF-Token')
|
||||
|
||||
if (!csrf.verify(token)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid CSRF token' },
|
||||
{ status: 403 }
|
||||
)
|
||||
}
|
||||
|
||||
// Process request
|
||||
}
|
||||
```
|
||||
|
||||
#### SameSite Cookies
|
||||
```typescript
|
||||
response.setHeader('Set-Cookie',
|
||||
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`
|
||||
)
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] CSRF tokens on state-changing operations
|
||||
- [ ] SameSite=Strict on all cookies
|
||||
- [ ] Double-submit cookie pattern implemented
|
||||
|
||||
### 7. Rate Limiting (ADR-016)
|
||||
|
||||
#### API Rate Limiting
|
||||
```typescript
|
||||
import { ThrottlerGuard } from '@nestjs/throttler'
|
||||
|
||||
// Apply to auth endpoints
|
||||
@UseGuards(ThrottlerGuard)
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
async login(@Body() dto: LoginDto) {
|
||||
// Login logic
|
||||
}
|
||||
```
|
||||
|
||||
#### Expensive Operations
|
||||
```typescript
|
||||
// Aggressive rate limiting for AI endpoints
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
async extractMetadata(@Body() dto: ExtractMetadataDto) {
|
||||
// AI extraction logic
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] Rate limiting on all auth endpoints (ADR-016)
|
||||
- [ ] Rate limiting on AI endpoints (ADR-018/023)
|
||||
- [ ] IP-based rate limiting
|
||||
- [ ] User-based rate limiting (authenticated)
|
||||
|
||||
### 8. Sensitive Data Exposure
|
||||
|
||||
#### Logging
|
||||
```typescript
|
||||
// FAIL: WRONG: Logging sensitive data
|
||||
this.logger.log('User login:', { email, password })
|
||||
this.logger.log('Payment:', { cardNumber, cvv })
|
||||
|
||||
// PASS: CORRECT: Redact sensitive data
|
||||
this.logger.log('User login:', { email, userId })
|
||||
this.logger.log('Payment:', { last4: card.last4, userId })
|
||||
```
|
||||
|
||||
#### Error Messages (ADR-007)
|
||||
```typescript
|
||||
// FAIL: WRONG: Exposing internal details
|
||||
catch (error) {
|
||||
return { error: error.message, stack: error.stack }
|
||||
}
|
||||
|
||||
// PASS: CORRECT: Generic error messages
|
||||
catch (error) {
|
||||
this.logger.error('Internal error:', error)
|
||||
throw new BadRequestException('An error occurred. Please try again.')
|
||||
}
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] No passwords, tokens, or secrets in logs
|
||||
- [ ] Error messages generic for users
|
||||
- [ ] Detailed errors only in server logs
|
||||
- [ ] No stack traces exposed to users
|
||||
|
||||
### 9. AI Boundary Enforcement (ADR-018/023)
|
||||
|
||||
#### FAIL: NEVER Do This
|
||||
```typescript
|
||||
// Direct AI access - FORBIDDEN
|
||||
import ollama from 'ollama'
|
||||
const response = await ollama.chat({ model: 'gemma4', messages })
|
||||
|
||||
// Direct Qdrant access - FORBIDDEN
|
||||
import { QdrantClient } from '@qdrant/js-client-rest'
|
||||
const client = new QdrantClient({ url: 'http://localhost:6333' })
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Do This
|
||||
```typescript
|
||||
// AI via DMS API only
|
||||
const response = await fetch('http://localhost:3001/api/ai/extract-metadata', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ documentId })
|
||||
})
|
||||
|
||||
// Qdrant via DMS API only
|
||||
const response = await fetch('http://localhost:3001/api/ai/search', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ query, projectPublicId })
|
||||
})
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] AI processing on Admin Desktop only (Desk-5439)
|
||||
- [ ] No direct Ollama calls from backend/frontend
|
||||
- [ ] No direct Qdrant calls from backend/frontend
|
||||
- [ ] All AI interactions via DMS API endpoints
|
||||
- [ ] AI audit logging implemented (ADR-020)
|
||||
- [ ] Human-in-the-loop validation for AI outputs
|
||||
|
||||
### 10. UUID Handling (ADR-019)
|
||||
|
||||
#### FAIL: NEVER Do This
|
||||
```typescript
|
||||
// parseInt on UUID - FORBIDDEN
|
||||
const projectId = parseInt(projectUuid) // "0195..." → 19 (WRONG!)
|
||||
|
||||
// Number on UUID - FORBIDDEN
|
||||
const projectId = Number(projectUuid)
|
||||
|
||||
// + operator on UUID - FORBIDDEN
|
||||
const projectId = +projectUuid
|
||||
|
||||
// id ?? '' fallback - FORBIDDEN
|
||||
const value = c.publicId ?? c.id ?? ''
|
||||
```
|
||||
|
||||
#### PASS: ALWAYS Do This
|
||||
```typescript
|
||||
// Use UUID string directly
|
||||
const projectId = projectUuid // "019505a1-7c3e-7000-8000-abc123def456"
|
||||
|
||||
// Backend: findOneByUuid returns entity with publicId
|
||||
const project = await this.projectService.findOneByUuid(projectUuid)
|
||||
const projectId = project.id // Internal INT for DB operations
|
||||
|
||||
// Frontend: use publicId only
|
||||
interface ProjectOption {
|
||||
publicId?: string; // No uuid fallback
|
||||
projectName?: string;
|
||||
}
|
||||
const value = c.publicId // "019505a1-7c3e-7000-8000-abc123def456"
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] No `parseInt()` on UUID values
|
||||
- [ ] No `Number()` on UUID values
|
||||
- [ ] No `+` operator on UUID values
|
||||
- [ ] No `id ?? ''` fallback patterns
|
||||
- [ ] Use `publicId` (string UUID) in API responses
|
||||
- [ ] Internal INT `id` marked with `@Exclude()` in entities
|
||||
|
||||
### 11. Dependency Security
|
||||
|
||||
#### Regular Updates
|
||||
```bash
|
||||
# Check for vulnerabilities
|
||||
pnpm audit
|
||||
|
||||
# Fix automatically fixable issues
|
||||
pnpm audit fix
|
||||
|
||||
# Update dependencies
|
||||
pnpm update
|
||||
|
||||
# Check for outdated packages
|
||||
pnpm outdated
|
||||
```
|
||||
|
||||
#### Lock Files
|
||||
```bash
|
||||
# ALWAYS commit lock files
|
||||
git add pnpm-lock.yaml
|
||||
|
||||
# Use in CI/CD for reproducible builds
|
||||
pnpm install --frozen-lockfile
|
||||
```
|
||||
|
||||
#### Verification Steps
|
||||
- [ ] Dependencies up to date
|
||||
- [ ] No known vulnerabilities (pnpm audit clean)
|
||||
- [ ] Lock files committed
|
||||
- [ ] Regular security updates
|
||||
|
||||
## Security Testing
|
||||
|
||||
### Automated Security Tests
|
||||
|
||||
```typescript
|
||||
// Test authentication
|
||||
test('requires authentication', async () => {
|
||||
const response = await fetch('/api/correspondences')
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
// Test authorization
|
||||
test('requires admin role', async () => {
|
||||
const response = await fetch('/api/admin/users', {
|
||||
headers: { Authorization: `Bearer ${userToken}` }
|
||||
})
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
// Test input validation
|
||||
test('rejects invalid input', async () => {
|
||||
const response = await fetch('/api/correspondences', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ subject: '', recipientId: 'invalid' })
|
||||
})
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
// Test rate limiting
|
||||
test('enforces rate limits', async () => {
|
||||
const requests = Array(11).fill(null).map(() =>
|
||||
fetch('/api/auth/login', { method: 'POST' })
|
||||
)
|
||||
|
||||
const responses = await Promise.all(requests)
|
||||
const tooManyRequests = responses.filter(r => r.status === 429)
|
||||
|
||||
expect(tooManyRequests.length).toBeGreaterThan(0)
|
||||
})
|
||||
```
|
||||
|
||||
## Pre-Deployment Security Checklist
|
||||
|
||||
Before ANY production deployment:
|
||||
|
||||
- [ ] **Secrets**: No hardcoded secrets, all in env vars
|
||||
- [ ] **Input Validation**: All user inputs validated (Zod + class-validator)
|
||||
- [ ] **SQL Injection**: All queries parameterized (TypeORM)
|
||||
- [ ] **XSS**: User content sanitized
|
||||
- [ ] **CSRF**: Protection enabled
|
||||
- [ ] **Authentication**: Proper token handling (httpOnly cookies)
|
||||
- [ ] **Authorization**: RBAC + CASL checks in place
|
||||
- [ ] **Rate Limiting**: Enabled on auth and AI endpoints
|
||||
- [ ] **HTTPS**: Enforced in production
|
||||
- [ ] **Security Headers**: CSP, X-Frame-Options configured
|
||||
- [ ] **Error Handling**: No sensitive data in errors (ADR-007)
|
||||
- [ ] **Logging**: No sensitive data logged
|
||||
- [ ] **Dependencies**: Up to date, no vulnerabilities
|
||||
- [ ] **UUID Handling**: No parseInt/Number/+ on UUID (ADR-019)
|
||||
- [ ] **AI Boundary**: AI via DMS API only (ADR-018/023)
|
||||
- [ ] **File Uploads**: Validated (50MB max, whitelist types)
|
||||
- [ ] **AI Audit**: All AI interactions logged (ADR-020)
|
||||
|
||||
## Resources
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [NestJS Security](https://docs.nestjs.com/security)
|
||||
- [Next.js Security](https://nextjs.org/docs/security)
|
||||
- [ADR-016 Security Authentication](../../specs/06-Decision-Records/ADR-016-security-authentication.md)
|
||||
- [ADR-018 AI Boundary](../../specs/06-Decision-Records/ADR-018-ai-boundary.md)
|
||||
- [ADR-019 UUID Strategy](../../specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md)
|
||||
- [ADR-023 AI Architecture](../../specs/06-Decision-Records/ADR-023-unified-ai-architecture.md)
|
||||
|
||||
---
|
||||
|
||||
**Remember**: Security is not optional. One vulnerability can compromise the entire platform. When in doubt, err on the side of caution.
|
||||
+30
-27
@@ -1,8 +1,8 @@
|
||||
# 🧠 NAP-DMS Agent Skills (v1.8.9)
|
||||
# 🧠 NAP-DMS Agent Skills (v1.9.0)
|
||||
|
||||
ไฟล์นี้กำหนดทักษะและความสามารถเฉพาะทางของ Document Intelligence Engine สำหรับโครงการ LCBP3 v1.8.9 เพื่อรักษามาตรฐานสูงสุดด้าน Security และ Data Integrity
|
||||
ไฟล์นี้กำหนดทักษะและความสามารถเฉพาะทางของ Document Intelligence Engine สำหรับโครงการ LCBP3 v1.9.0 เพื่อรักษามาตรฐานสูงสุดด้าน Security และ Data Integrity
|
||||
|
||||
**Status**: Production Ready | **Last Updated**: 2026-04-22 | **Total Skills**: 20
|
||||
**Status**: Production Ready | **Last Updated**: 2026-05-17 | **Total Skills**: 23
|
||||
|
||||
> 📌 Shared context for all speckit-\* skills: see [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md).
|
||||
|
||||
@@ -57,28 +57,31 @@
|
||||
|
||||
## 🔄 Skill Dependency Matrix
|
||||
|
||||
| Skill | Dependencies | Handoffs To | Notes |
|
||||
| -------------------------- | -------------------- | -------------------------------- | ----------------------------- |
|
||||
| **speckit-constitution** | None | speckit-specify | Project governance foundation |
|
||||
| **speckit-specify** | speckit-constitution | speckit-clarify | Feature specification |
|
||||
| **speckit-clarify** | speckit-specify | speckit-plan | Resolve ambiguities |
|
||||
| **speckit-plan** | speckit-clarify | speckit-tasks, speckit-checklist | Technical design |
|
||||
| **speckit-tasks** | speckit-plan | speckit-implement | Task breakdown |
|
||||
| **speckit-implement** | speckit-tasks | speckit-checker | Code implementation |
|
||||
| **speckit-checker** | speckit-implement | speckit-tester | Static analysis |
|
||||
| **speckit-tester** | speckit-checker | speckit-reviewer | Test execution |
|
||||
| **speckit-reviewer** | speckit-tester | speckit-validate | Code review |
|
||||
| **speckit-validate** | speckit-reviewer | None | Requirements validation |
|
||||
| **speckit-analyze** | speckit-tasks | None | Cross-artifact consistency |
|
||||
| **speckit-migrate** | None | speckit-plan | Legacy code import |
|
||||
| **speckit-quizme** | speckit-specify | speckit-plan | Logic validation |
|
||||
| **speckit-diff** | None | speckit-plan | Version comparison |
|
||||
| **speckit-status** | None | None | Progress tracking |
|
||||
| **speckit-taskstoissues** | speckit-tasks | None | Issue sync |
|
||||
| **speckit-checklist** | speckit-plan | None | Requirements validation |
|
||||
| **nestjs-best-practices** | None | speckit-implement | Backend patterns |
|
||||
| **next-best-practices** | None | speckit-implement | Frontend patterns |
|
||||
| **speckit-security-audit** | None | speckit-reviewer | Security validation |
|
||||
| Skill | Dependencies | Handoffs To | Notes |
|
||||
| -------------------------- | -------------------- | ---------------------------------------- | ----------------------------- |
|
||||
| **speckit-constitution** | None | speckit-specify | Project governance foundation |
|
||||
| **speckit-specify** | speckit-constitution | speckit-clarify | Feature specification |
|
||||
| **speckit-clarify** | speckit-specify | speckit-plan | Resolve ambiguities |
|
||||
| **speckit-plan** | speckit-clarify | speckit-tasks, speckit-checklist | Technical design |
|
||||
| **speckit-tasks** | speckit-plan | speckit-implement | Task breakdown |
|
||||
| **speckit-implement** | speckit-tasks | speckit-checker | Code implementation |
|
||||
| **speckit-checker** | speckit-implement | speckit-tester | Static analysis |
|
||||
| **speckit-tester** | speckit-checker | speckit-reviewer | Test execution |
|
||||
| **speckit-reviewer** | speckit-tester | speckit-validate | Code review |
|
||||
| **speckit-validate** | speckit-reviewer | None | Requirements validation |
|
||||
| **speckit-analyze** | speckit-tasks | None | Cross-artifact consistency |
|
||||
| **speckit-migrate** | None | speckit-plan | Legacy code import |
|
||||
| **speckit-quizme** | speckit-specify | speckit-plan | Logic validation |
|
||||
| **speckit-diff** | None | speckit-plan | Version comparison |
|
||||
| **speckit-status** | None | None | Progress tracking |
|
||||
| **speckit-taskstoissues** | speckit-tasks | None | Issue sync |
|
||||
| **speckit-checklist** | speckit-plan | None | Requirements validation |
|
||||
| **nestjs-best-practices** | None | speckit-implement | Backend patterns |
|
||||
| **next-best-practices** | None | speckit-implement | Frontend patterns |
|
||||
| **speckit-security-audit** | None | speckit-reviewer | Security validation |
|
||||
| **e2e-testing** | None | speckit-tester | Playwright E2E patterns |
|
||||
| **verification-loop** | None | speckit-checker, speckit-tester | Comprehensive verification |
|
||||
| **security-review** | None | speckit-reviewer, speckit-security-audit | OWASP Top 10 + ADR compliance |
|
||||
|
||||
---
|
||||
|
||||
@@ -96,8 +99,8 @@
|
||||
|
||||
### Health Metrics
|
||||
|
||||
- **Total Skills**: 20 implemented
|
||||
- **Version Alignment**: v1.8.9 across all skills
|
||||
- **Total Skills**: 23 implemented
|
||||
- **Version Alignment**: v1.9.0 across all skills
|
||||
- **Template Coverage**: 100% for skills requiring templates
|
||||
- **Documentation**: Complete front matter + shared `_LCBP3-CONTEXT.md` appendix
|
||||
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: verification-loop
|
||||
description: A comprehensive verification system for LCBP3-DMS development sessions with build, type check, lint, test, security scan, and diff review phases.
|
||||
version: 1.9.0
|
||||
scope: verification
|
||||
depends-on: []
|
||||
handoffs-to: [speckit-checker, speckit-tester]
|
||||
user-invocable: true
|
||||
---
|
||||
|
||||
# Verification Loop Skill
|
||||
|
||||
A comprehensive verification system for LCBP3-DMS development sessions.
|
||||
|
||||
## LCBP3 Context
|
||||
|
||||
See [`_LCBP3-CONTEXT.md`](../_LCBP3-CONTEXT.md) for project-specific verification requirements:
|
||||
- Backend: NestJS with TypeScript strict mode
|
||||
- Frontend: Next.js with TypeScript strict mode
|
||||
- Package manager: pnpm
|
||||
- Coverage goals: Backend 70%+, Business Logic 80%+
|
||||
- Security: ADR-016, ADR-018, ADR-019, ADR-023 compliance
|
||||
|
||||
## When to Use
|
||||
|
||||
Invoke this skill:
|
||||
- After completing a feature or significant code change
|
||||
- Before creating a PR
|
||||
- When you want to ensure quality gates pass
|
||||
- After refactoring
|
||||
- Before deploying to staging/production
|
||||
|
||||
## Verification Phases
|
||||
|
||||
### Phase 1: Build Verification
|
||||
|
||||
```bash
|
||||
# Backend build
|
||||
cd backend
|
||||
pnpm build 2>&1 | tail -20
|
||||
|
||||
# Frontend build
|
||||
cd frontend
|
||||
pnpm build 2>&1 | tail -20
|
||||
```
|
||||
|
||||
If build fails, STOP and fix before continuing.
|
||||
|
||||
### Phase 2: Type Check
|
||||
|
||||
```bash
|
||||
# Backend TypeScript
|
||||
cd backend
|
||||
pnpm typecheck 2>&1 | head -30
|
||||
|
||||
# Frontend TypeScript
|
||||
cd frontend
|
||||
pnpm typecheck 2>&1 | head -30
|
||||
```
|
||||
|
||||
Report all type errors. Fix critical ones before continuing.
|
||||
|
||||
### Phase 3: Lint Check
|
||||
|
||||
```bash
|
||||
# Backend lint
|
||||
cd backend
|
||||
pnpm lint 2>&1 | head -30
|
||||
|
||||
# Frontend lint
|
||||
cd frontend
|
||||
pnpm lint 2>&1 | head -30
|
||||
```
|
||||
|
||||
### Phase 4: Test Suite
|
||||
|
||||
```bash
|
||||
# Backend tests with coverage
|
||||
cd backend
|
||||
pnpm test -- --coverage 2>&1 | tail -50
|
||||
|
||||
# Frontend unit tests
|
||||
cd frontend
|
||||
pnpm test 2>&1 | tail -50
|
||||
|
||||
# Frontend E2E tests (if applicable)
|
||||
cd frontend
|
||||
npx playwright test 2>&1 | tail -50
|
||||
```
|
||||
|
||||
Report:
|
||||
- Total tests: X
|
||||
- Passed: X
|
||||
- Failed: X
|
||||
- Coverage: X%
|
||||
|
||||
### Phase 5: Security Scan
|
||||
|
||||
```bash
|
||||
# Check for hardcoded secrets
|
||||
grep -rn "sk-" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
|
||||
grep -rn "api_key" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
|
||||
grep -rn "password" --include="*.ts" --include="*.tsx" . 2>/dev/null | head -10
|
||||
|
||||
# Check for console.log (forbidden in committed code)
|
||||
grep -rn "console.log" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for any types (forbidden)
|
||||
grep -rn ": any" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for parseInt on UUID (ADR-019 violation)
|
||||
grep -rn "parseInt(" --include="*.ts" --include="*.tsx" backend/src/ frontend/src/ 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
### Phase 6: ADR Compliance Check
|
||||
|
||||
```bash
|
||||
# Check for id ?? '' fallback (ADR-019 violation)
|
||||
grep -rn "id ?? ''" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for Number() on UUID (ADR-019 violation)
|
||||
grep -rn "Number(" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
|
||||
|
||||
# Check for + operator on UUID (ADR-019 violation)
|
||||
grep -rn "+ publicId\|+ id" --include="*.ts" --include="*.tsx" frontend/src/ 2>/dev/null | head -10
|
||||
```
|
||||
|
||||
### Phase 7: Diff Review
|
||||
|
||||
```bash
|
||||
# Show what changed
|
||||
git diff --stat
|
||||
git diff HEAD~1 --name-only
|
||||
|
||||
# Show detailed changes
|
||||
git diff
|
||||
```
|
||||
|
||||
Review each changed file for:
|
||||
- Unintended changes
|
||||
- Missing error handling (ADR-007)
|
||||
- Potential edge cases
|
||||
- UUID handling (ADR-019)
|
||||
- Security vulnerabilities (ADR-016)
|
||||
- AI boundary violations (ADR-018/023)
|
||||
|
||||
## Output Format
|
||||
|
||||
After running all phases, produce a verification report:
|
||||
|
||||
```
|
||||
VERIFICATION REPORT
|
||||
==================
|
||||
|
||||
Build: [PASS/FAIL]
|
||||
Types: [PASS/FAIL] (X errors)
|
||||
Lint: [PASS/FAIL] (X warnings)
|
||||
Tests: [PASS/FAIL] (X/Y passed, Z% coverage)
|
||||
Security: [PASS/FAIL] (X issues)
|
||||
ADR: [PASS/FAIL] (X violations)
|
||||
Diff: [X files changed]
|
||||
|
||||
Overall: [READY/NOT READY] for PR
|
||||
|
||||
Issues to Fix:
|
||||
1. ...
|
||||
2. ...
|
||||
```
|
||||
|
||||
## Continuous Mode
|
||||
|
||||
For long sessions, run verification every 15 minutes or after major changes:
|
||||
|
||||
```markdown
|
||||
Set a mental checkpoint:
|
||||
- After completing each function
|
||||
- After finishing a component
|
||||
- Before moving to next task
|
||||
|
||||
Run: /verify
|
||||
```
|
||||
|
||||
## Integration with LCBP3 Skills
|
||||
|
||||
This skill complements:
|
||||
- **speckit-checker**: Runs static analysis (lint, typecheck)
|
||||
- **speckit-tester**: Runs tests with coverage verification
|
||||
- **speckit-security-audit**: Performs security review against OWASP Top 10
|
||||
|
||||
This skill provides a unified verification loop that combines all checks into a single report.
|
||||
|
||||
## LCBP3-Specific Checks
|
||||
|
||||
### Tier 1 — CRITICAL (CI BLOCKER)
|
||||
|
||||
- [ ] **Security**: Auth, RBAC, Validation implemented
|
||||
- [ ] **UUID Strategy (ADR-019)**: No `parseInt` / `Number` / `+` on UUID
|
||||
- [ ] **Database correctness**: Schema verified before writing queries
|
||||
- [ ] **File upload security**: ClamAV + whitelist implemented
|
||||
- [ ] **AI validation boundary (ADR-018/023)**: AI via DMS API only
|
||||
- [ ] **Error handling (ADR-007)**: Layered error classification
|
||||
- [ ] **Forbidden patterns**: Zero `any`, zero `console.log`, UUID misuse
|
||||
|
||||
### Tier 2 — IMPORTANT (CODE REVIEW)
|
||||
|
||||
- [ ] **Architecture patterns**: Thin controller, business logic in service
|
||||
- [ ] **Test coverage**: 80%+ business logic, 70%+ backend overall
|
||||
- [ ] **Cache invalidation**: Implemented when data modified
|
||||
- [ ] **Naming conventions**: Follow domain terminology
|
||||
|
||||
### Tier 3 — GUIDELINES
|
||||
|
||||
- [ ] **Code style**: Prettier formatting
|
||||
- [ ] **Comment completeness**: Thai comments, JSDoc on public methods
|
||||
- [ ] **Minor optimizations**: Performance improvements where applicable
|
||||
|
||||
## References
|
||||
|
||||
- LCBP3 AGENTS.md: `AGENTS.md` (repo root)
|
||||
- ADR-007 Error Handling: `specs/06-Decision-Records/ADR-007-error-handling-strategy.md`
|
||||
- ADR-016 Security: `specs/06-Decision-Records/ADR-016-security-authentication.md`
|
||||
- ADR-019 UUID: `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md`
|
||||
- ADR-018 AI Boundary: `specs/06-Decision-Records/ADR-018-ai-boundary.md`
|
||||
- ADR-023 AI Architecture: `specs/06-Decision-Records/ADR-023-unified-ai-architecture.md`
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
auto_execution_mode: 0
|
||||
description: Playwright E2E testing patterns, Page Object Model, configuration, CI/CD integration, artifact management, and flaky test strategies for LCBP3-DMS
|
||||
---
|
||||
|
||||
This workflow invokes the e2e-testing skill to help with Playwright E2E testing patterns for LCBP3-DMS.
|
||||
|
||||
Invoke the e2e-testing skill when:
|
||||
- Creating new E2E tests for frontend features
|
||||
- Debugging flaky Playwright tests
|
||||
- Setting up CI/CD integration for E2E tests
|
||||
- Optimizing test performance and reliability
|
||||
- Implementing Page Object Model (POM) patterns
|
||||
@@ -40,7 +40,7 @@ The following are **CI-blocking issues** that must be caught in code review. The
|
||||
|
||||
- **❌ NO SQL Triggers for business logic** — use NestJS Service methods instead
|
||||
- **❌ NO `.env` files in production** — use Docker environment variables
|
||||
- **❌ NO direct table/column name invention** — verify against `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
|
||||
- **❌ NO direct table/column name invention** — verify against `specs/03-Data-and-Storage/lcbp3-v1.9.0-schema-02-tables.sql`
|
||||
|
||||
### Security (ADR-016)
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
auto_execution_mode: 0
|
||||
description: Comprehensive security review for LCBP3-DMS with OWASP Top 10 checklist, ADR compliance, and automated security testing patterns
|
||||
---
|
||||
|
||||
This workflow invokes the security-review skill to perform comprehensive security review of LCBP3-DMS code changes.
|
||||
|
||||
Invoke the security-review skill when:
|
||||
- Implementing authentication or authorization
|
||||
- Handling user input or file uploads
|
||||
- Creating new API endpoints
|
||||
- Working with secrets or credentials
|
||||
- Integrating AI features (Ollama/Qdrant)
|
||||
- Storing or transmitting sensitive data
|
||||
- Integrating third-party APIs
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
auto_execution_mode: 0
|
||||
description: A comprehensive verification system for LCBP3-DMS development sessions with build, type check, lint, test, security scan, and diff review phases
|
||||
---
|
||||
|
||||
This workflow invokes the verification-loop skill to perform comprehensive verification of LCBP3-DMS code changes.
|
||||
|
||||
Invoke the verification-loop skill when:
|
||||
- After completing a feature or significant code change
|
||||
- Before creating a PR
|
||||
- When you want to ensure quality gates pass
|
||||
- After refactoring
|
||||
- Before deploying to staging/production
|
||||
Reference in New Issue
Block a user