690513:0920 Refactor Workflow module: Lint error #01
CI / CD Pipeline / build (push) Failing after 10m44s
CI / CD Pipeline / deploy (push) Has been skipped

This commit is contained in:
2026-05-13 09:20:49 +07:00
parent e218fc826c
commit 5537d20152
299 changed files with 27326 additions and 2501 deletions
+19 -14
View File
@@ -2,7 +2,11 @@
> **The Event Horizon of Software Quality.**
> _Adapted for Google Antigravity IDE from [github/spec-kit](https://github.com/github/spec-kit)._
> _Version: 1.8.6 — LCBP3-DMS Edition (v1.8.6 Production Ready)_
> # Speckit Agent Infrastructure (v1.9.0)
>
> - Version: 1.9.0
> - Last Updated: 2026-05-13
> - Core Principle: **Sync with AGENTS.md v1.9.0**
---
@@ -78,8 +82,19 @@ The toolkit is organized into modular components that provide both the logic (Sc
│ ├── speckit-tester/ # Test Runner & Coverage
│ └── speckit-validate/ # Implementation Validator
├── workflows/ # / Slash Commands (Orchestration)
│ ├── 00-speckit.all.md # Full Pipeline (10 steps: Specify → Validate)
│ ├── 0111-speckit-*.md # Individual phase workflows
│ ├── speckit-prepare.md # Prep Pipeline (5 steps: Specify → Analyze)
│ ├── schema-change.md # DB Schema Change (ADR-009)
│ ├── create-backend-module.md # NestJS Module Scaffolding
│ ├── create-frontend-page.md # Next.js Page Scaffolding
│ ├── deploy.md # Deployment via Gitea CI/CD
│ ├── review.md # Code Review Workflow
│ └── util-speckit-*.md # Utilities (checklist, diff, migrate, etc.)
├── rules/ # Project Context & Validation Rules
│ ├── 00-project-context.md # Role, Persona, Rule Tiers
│ ├── 00-project-context.md # Role, Persona, Rule Tiers (v1.9.0)
│ ├── 01-adr-019-uuid.md # UUID Strategy (Critical)
│ ├── 02-security.md # Security Requirements
│ ├── 03-typescript.md # TypeScript Standards
@@ -98,16 +113,6 @@ The toolkit is organized into modular components that provide both the logic (Sc
├── fix_links.py # Spec link fixer
├── verify_links.py # Spec link verifier
└── start-mcp.js # MCP server launcher
.windsurf/workflows/ # / Slash Commands (Orchestration)
├── 00-speckit.all.md # Full Pipeline (10 steps: Specify → Validate)
├── 0111-speckit-*.md # Individual phase workflows
├── speckit-prepare.md # Prep Pipeline (5 steps: Specify → Analyze)
├── schema-change.md # DB Schema Change (ADR-009)
├── create-backend-module.md # NestJS Module Scaffolding
├── create-frontend-page.md # Next.js Page Scaffolding
├── deploy.md # Deployment via Gitea CI/CD
├── review.md # Code Review Workflow
└── util-speckit-*.md # Utilities (checklist, diff, migrate, etc.)
```
@@ -259,7 +264,7 @@ If you change your mind mid-project:
---
## 🏗️ LCBP3-DMS Project Notes (v1.8.6)
## 🏗️ LCBP3-DMS Project Notes (v1.9.0)
### 📊 Current Status: Production Ready (2026-04-14)
@@ -319,7 +324,7 @@ If you change your mind mid-project:
# Run version validation
./scripts/bash/validate-versions.sh
# Fix by updating all files to v1.8.6
# Fix by updating all files to v1.9.0
# Then re-run validation to confirm
```
@@ -2,6 +2,7 @@
name: setup-matt-pocock-skills
description: Sets up an `## Agent skills` block in AGENTS.md/CLAUDE.md and `docs/agents/` so the engineering skills know this repo's issue tracker (GitHub or local markdown), triage label vocabulary, and domain doc layout. Run before first use of `to-issues`, `to-prd`, `triage`, `diagnose`, `tdd`, `improve-codebase-architecture`, or `zoom-out` — or if those skills appear to be missing context about the issue tracker, triage labels, or domain docs.
disable-model-invocation: true
version: 1.9.0
---
# Setup Matt Pocock's Skills
+55
View File
@@ -0,0 +1,55 @@
# NAP-DMS Project Context & Core Rules
- Version: 1.9.0
- Last Updated: 2026-05-13
- Status: Production Ready
- Canonical Source: AGENTS.md
## 🎭 Role & Persona
Act as a **Senior Full Stack Developer** specialized in NestJS, Next.js, and TypeScript.
Focus on **Data Integrity, Security, Maintainability, and Performance**.
You are a **Document Intelligence Engine** — every response must be precise, spec-compliant, and production-ready.
---
## 🔴 Tier 1 — CRITICAL (CI BLOCKER)
1. **Identifier Strategy (ADR-019)**
- ห้ามใช้ `parseInt()` บน UUID
- ใช้ `publicId` (string) สำหรับการติดต่อภายนอก (API/URL) เท่านั้น
2. **Database Management (ADR-009)**
- ห้ามใช้ TypeORM Migrations หรือ `synchronize: true`
- การแก้ Schema ต้องแก้ที่ SQL files ใน `specs/03-Data-and-Storage/` เท่านั้น
3. **Security (ADR-016)**
- ทุก API ต้องมี `CASL Guard` และตรวจสอบสิทธิ์ผ่าน RBAC Matrix
- การอัปโหลดไฟล์ต้องเป็น Two-Phase (Temp → Commit) และต้องสแกน ClamAV
4. **AI Boundary (ADR-018)**
- AI Agent ต้องทำงานผ่าน DMS API เท่านั้น ห้ามเขียนลง Database หรือ Storage โดยตรง
---
## 📐 TypeScript Rules & Coding Standards (v1.9.0)
- **File Header:** ทุกไฟล์ต้องขึ้นต้นด้วย `// File: path/filename`
- **Change Log:** ต้องมีส่วน `// Change Log` ที่หัวไฟล์
- **Language:** ตัวแปร/Logic เป็น English, Comment/JSDoc เป็น **Thai**
- **Explicit Typing:** กำหนด Type ให้ชัดเจนเสมอ ห้ามใช้ `any`
- **Cleanliness:** ห้ามมีบรรทัดว่างในฟังก์ชัน, Export ได้เพียง 1 symbol หลักต่อไฟล์
---
## 📁 Specs Folder Organization (Hybrid Model)
- **Core (00-06):** ข้อมูลอ้างอิงถาวร (Permanent Source of Truth)
- **Feature (100-300):** สำหรับงาน Implementation ใหม่
- `100-Infrastructures/`
- `200-fullstacks/`
- `300-others/`
---
## 🔄 Workflow Engine (ADR-001/021)
- ใช้ DSL-based state machine
- การเปลี่ยนสถานะต้องตรวจสอบสถานะปัจจุบันจาก DB ก่อนเสมอ
- งานที่ใช้เวลานานต้องส่งไปที่ **BullMQ** เท่านั้น
+68
View File
@@ -0,0 +1,68 @@
# ADR-019 UUID Strategy
## CRITICAL RULES
- **NEVER** use `parseInt()` on UUID values
- **NEVER** use `Number()` on UUID values
- **NEVER** use `+` operator on UUID values
- **ALWAYS** use `publicId` (string UUID) for API responses
- **NEVER** expose internal INT `id` in API responses (use `@Exclude()`)
## Identifier Types
| Context | Type | Notes |
| ---------------- | ------------------------- | ------------------------------------------- |
| Internal / DB FK | `INT AUTO_INCREMENT` | Never exposed in API |
| Public API / URL | `UUIDv7` (MariaDB native) | Stored as BINARY(16), no transformer needed |
| Entity Property | `publicId: string` | Exposed directly in API (no transformation) |
| API Response | `publicId: string` (UUID) | INT `id` has `@Exclude()` — never appears |
## Backend Pattern (NestJS/TypeORM)
```typescript
// Entity
@Entity()
class Project extends UuidBaseEntity {
@Column({ type: 'uuid' })
publicId: string; // UUID string, no transformation needed
@PrimaryKey()
@Exclude()
id: number; // Internal INT, never exposed
}
// API Response → { id: "019505a1-7c3e-7000-8000-abc123def456" }
// Uses publicId directly, no @Expose({ name: 'id' }) needed
```
## Frontend Pattern (Next.js)
```typescript
// ✅ CORRECT — Use publicId only
type ProjectOption = {
publicId?: string; // No uuid, no id fallback
projectName?: string;
};
// ❌ WRONG — Multiple identifiers cause confusion
type ProjectOption = {
publicId?: string;
uuid?: string; // Don't do this
id?: number; // Don't do this
};
// ❌ NEVER use parseInt on UUID
parseInt(projectId); // "0195..." → 19 (WRONG!)
// ❌ NEVER use id ?? '' fallback
const value = c.publicId ?? c.id ?? ''; // Wrong!
// ✅ CORRECT — Use publicId only
const value = c.publicId; // "019505a1-7c3e-7000-8000-abc123def456"
```
## Related Documents
- `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md`
- `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md`
+33
View File
@@ -0,0 +1,33 @@
# Security Rules (Non-Negotiable)
## Mandatory Security Requirements
1. **Idempotency:** All critical `POST`/`PUT`/`PATCH` MUST validate `Idempotency-Key` header
2. **Two-Phase File Upload:** Upload → Temp → Commit → Permanent
3. **Race Conditions:** Redis Redlock + TypeORM `@VersionColumn` for Document Numbering
4. **Validation:** Zod (frontend) + class-validator (backend DTO)
5. **Password:** bcrypt 12 salt rounds, min 8 chars, rotate every 90 days
6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints
7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan
8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access
9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages
10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture
11. **AI Audit Trail:** Log all AI interactions and human validations
12. **Rate Limiting:** Apply to AI endpoints to prevent abuse
## Full Documentation
`specs/06-Decision-Records/ADR-016-security-authentication.md`
## Security Checklist (Before Every Commit)
- [ ] Input validation implemented (Zod/class-validator)
- [ ] RBAC/CASL permissions checked
- [ ] 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 audit logging implemented for AI interactions
- [ ] Error handling follows ADR-007 layered classification
- [ ] OWASP Top 10 review passed
+36
View File
@@ -0,0 +1,36 @@
# TypeScript Rules (v1.9.0)
## Core Standards
- **Strict Mode** — all strict checks enforced.
- **ZERO `any` types** — use proper types or `unknown` + narrowing.
- **ZERO `console.log`** — use NestJS `Logger` (backend) or remove before commit (frontend).
- **English for Code** — use English for all code identifiers, variables, and logic.
- **Thai for Comments** — use Thai for comments, documentation, and JSDoc.
- **Explicit Typing** — explicitly define types for all variables, parameters, and return values.
- **JSDoc** — use JSDoc for all public classes and methods (in **Thai**).
## File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- **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.
## Patterns
```typescript
// ✅ CORRECT
// File: src/example.service.ts
// Change Log:
// - 2026-05-13: Initial creation
/**
* บริการตัวอย่างสำหรับ LCBP3
*/
export class ExampleService {
public doSomething(data: string): boolean {
return data.length > 0;
}
}
```
+35
View File
@@ -0,0 +1,35 @@
# Domain Terminology
## DMS Glossary
| ✅ Use | ❌ Don't Use |
| ------------------ | ------------------------------------- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
| RBAC | Permission System (generic) |
## Full Glossary
`specs/00-overview/00-02-glossary.md`
## 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.8.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related 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 |
+38
View File
@@ -0,0 +1,38 @@
# Forbidden Actions
## ❌ 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) |
## 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
- Update Data Dictionary when changing fields
## UUID Handling
See `01-adr-019-uuid.md` for complete UUID rules.
Quick reminder:
-`parseInt(uuid)` → NEVER
-`Number(uuid)` → NEVER
- ✅ Use UUID string directly
+55
View File
@@ -0,0 +1,55 @@
# Backend Patterns (NestJS)
## Architecture
- **Thin Controller** — business logic in Service layer
- **DTO Validation** — class-validator + class-transformer
- **RBAC** — CASL for authorization
- **Error Handling** — Logger + HttpException
## UUID Resolution Pattern
```typescript
// Controller - accept UUID in DTO
@Post()
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);
}
// Service - use internal ID for DB operations
async create(dto: CreateCorrespondenceDto, contractId: number) {
// Use contractId (INT) for database queries
const correspondence = this.repo.create({
contractId, // FK is INT
// ... other fields
});
return this.repo.save(correspondence);
}
```
## API Response Pattern
```typescript
// Entity
@Entity()
class Contract extends UuidBaseEntity {
@Column({ type: 'uuid' })
publicId: string;
@PrimaryKey()
@Exclude()
id: number;
}
// Response automatically includes publicId as 'id'
// { id: "019505a1-7c3e-7000-8000-abc123def456", ... }
```
## Full Guidelines
`specs/05-Engineering-Guidelines/05-02-backend-guidelines.md`
+47
View File
@@ -0,0 +1,47 @@
# Frontend Patterns (Next.js)
## Form Handling
- **RHF** (React Hook Form) for form management
- **Zod** for validation schema
- **TanStack Query** for server state
## UUID Handling
```typescript
// ✅ CORRECT - Use publicId only
interface ProjectOption {
publicId?: string;
projectName?: string;
}
// Select options
const options = contracts.map(c => ({
label: `${c.contractName} (${c.contractCode})`,
value: c.publicId!, // Use publicId, no fallback to id
}));
// ❌ WRONG - Never use these patterns
const value = c.publicId ?? c.id ?? ''; // Wrong!
const id = parseInt(projectId); // Wrong - parseInt on UUID!
```
## API Client Pattern
```typescript
// Use publicId directly in API calls
const contract = await contractService.getById(publicId);
// Form submission with UUID
const onSubmit = async (data: FormData) => {
await correspondenceService.create({
contractUuid: selectedContract.publicId!, // UUID string
// ... other fields
});
};
```
## Full Guidelines
`specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md`
+43
View File
@@ -0,0 +1,43 @@
# Development Flow
## 🔴 Critical Work — DB / API / Security / Workflow Engine
**MUST complete all steps:**
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`
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)
7. **Write code** — TypeScript strict, no `any`, no `console.log`
## 🟡 Normal Work — UI / Feature / Integration
- Follow existing patterns in codebase.
- Check spec for relevant module only.
- **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/`
- Ensure no forbidden patterns (`any`, `console.log`, UUID misuse) are introduced.
## 🟢 Quick Fix — Bug Fix / Typo / Style
- Fix directly
- Add minimal test if logic changed
- Check forbidden patterns before commit
## 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 |
+33
View File
@@ -0,0 +1,33 @@
# Commit Checklist
## Pre-Commit Verification
- [ ] UUID pattern verified (no parseInt on UUID)
- [ ] No `any` types in TypeScript
- [ ] No `console.log` in committed code
- [ ] Comments in Thai
- [ ] Code identifiers in English
- [ ] Schema changes via SQL directly (not migration)
- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+)
- [ ] Relevant ADRs checked (ADR-009, ADR-018, ADR-019)
- [ ] Glossary terms used correctly
- [ ] Error handling complete (Logger + HttpException)
- [ ] i18n keys used instead of hardcode text
- [ ] Cache invalidation when data modified
- [ ] Security checklist passed (OWASP Top 10)
## Commit Message Format
```
type(scope): description
[optional body]
```
Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`
Examples:
- `feat(correspondence): add originator organization validation`
- `fix(uuid): correct parseInt usage to string comparison`
- `spec(agents): bump to v1.8.5 - refactor structure`
+75
View File
@@ -0,0 +1,75 @@
# ADR-007 Error Handling Strategy
## CRITICAL RULES
- **ALWAYS** use layered error classification (Validation, Business, System)
- **NEVER** expose technical details to end users
- **ALWAYS** provide user-friendly error messages with recovery guidance
- **ALWAYS** log technical details for debugging
- **NEVER** use generic error messages without context
## Error Classification
| Error Type | Description | User Message | Technical Log |
|------------|-------------|--------------|---------------|
| **Validation** | Input validation failures | Clear field-level errors | Full validation details |
| **Business** | Business rule violations | Actionable guidance | Business context + user ID |
| **System** | Infrastructure failures | Generic "try again" | Full stack trace + metrics |
## Backend Pattern (NestJS)
```typescript
// Custom Exception Hierarchy
export class BusinessException extends HttpException {
constructor(
message: string,
userMessage: string,
recoveryAction?: string,
errorCode?: string
) {
super({ message, userMessage, recoveryAction, errorCode }, 400);
}
}
// Global Exception Filter
@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// Classify error and provide appropriate response
// Log technical details
// Return user-friendly message
}
}
```
## Frontend Pattern (Next.js)
```typescript
// Error Display Component
const ErrorDisplay = ({ error, onRetry }) => {
const userMessage = error.userMessage || 'เกิดข้อผิดพลาด';
const recoveryAction = error.recoveryAction;
return (
<div>
<p>{userMessage}</p>
{recoveryAction && <p>{recoveryAction}</p>}
{onRetry && <button onClick={onRetry}></button>}
</div>
);
};
```
## Required Implementation
- [ ] Global Exception Filter with layered classification
- [ ] Custom exception hierarchy (Validation, Business, System)
- [ ] Standardized error response DTOs
- [ ] Frontend error display components
- [ ] Error recovery mechanisms where applicable
## Related Documents
- `specs/06-Decision-Records/ADR-007-error-handling-strategy.md`
- `specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md`
+97
View File
@@ -0,0 +1,97 @@
# ADR-020 AI Integration Architecture
## CRITICAL RULES
- **ALWAYS** follow ADR-018 AI boundary policy (isolation on Admin Desktop)
- **ALWAYS** use RFA-First approach for AI implementation
- **NEVER** allow AI direct database/storage access
- **ALWAYS** implement human-in-the-loop validation
- **NEVER** send sensitive data to cloud AI services
## AI Integration Patterns
### Architecture Overview
```
Frontend → AI Gateway API → 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 |
## Backend Implementation (NestJS)
```typescript
// AI Module with boundary enforcement
@Module({
controllers: [AiController],
providers: [AiService, AiGateway],
exports: [AiService],
})
export class AiModule {
constructor() {
// Enforce ADR-018 boundaries
}
}
// 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
}
}
```
## Frontend Pattern (Next.js)
```typescript
// Document Review Form (reusable component)
const DocumentReviewForm = ({ document, aiSuggestions }) => {
return (
<form>
<Field label="Document Type" suggestions={aiSuggestions.documentType} />
<Field label="Project Code" suggestions={aiSuggestions.projectCode} />
<Field label="Discipline" suggestions={aiSuggestions.discipline} />
<ConfidenceScore score={aiSuggestions.confidence} />
<HumanValidationActions />
</form>
);
};
```
## Security Requirements
- **AI Isolation:** All AI processing on Admin Desktop only
- **Data Privacy:** No cloud AI services, on-premises only
- **Audit Trail:** Log all AI interactions and human validations
- **Rate Limiting:** Prevent AI abuse and resource exhaustion
- **Validation:** All AI outputs must be validated before use
## Required Implementation
- [ ] AiModule with ADR-018 boundary enforcement
- [ ] AI Gateway API endpoints with validation
- [ ] DocumentReviewForm reusable component
- [ ] Admin Desktop Ollama + PaddleOCR setup
- [ ] n8n workflow orchestration
- [ ] AI audit logging and monitoring
- [ ] 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`
+52 -1
View File
@@ -20,6 +20,8 @@ SKILLS_DIR="$AGENTS_DIR/skills"
echo "=== Skills Health Audit ==="
echo "Base directory: $BASE_DIR"
echo "Agents directory: $AGENTS_DIR"
echo "Specs directory: $BASE_DIR/specs"
echo
# Function to check if skill has required files
@@ -178,8 +180,57 @@ fi
echo
# Specs Integrity Audit (New for v1.9.0)
echo "=== Specs Integrity Audit ==="
echo "---------------------------"
SPECS_DIR="$BASE_DIR/specs"
CATEGORIES=("100-Infrastructures" "200-fullstacks" "300-others")
SPEC_ISSUES=0
if [[ -d "$SPECS_DIR" ]]; then
# 1. Check for core categories
for cat in "${CATEGORIES[@]}"; do
if [[ -d "$SPECS_DIR/$cat" ]]; then
echo -e "${GREEN} FOUND${NC}: category $cat"
# Check features within category
features=$(find "$SPECS_DIR/$cat" -maxdepth 1 -type d -not -path "$SPECS_DIR/$cat" | wc -l)
echo " -> Contains $features feature(s)"
# Check each feature for spec.md
while IFS= read -r f_dir; do
if [[ -n "$f_dir" ]]; then
f_name=$(basename "$f_dir")
if [[ ! -f "$f_dir/spec.md" ]]; then
echo -e " ${RED} MISSING${NC}: $f_name/spec.md"
((SPEC_ISSUES++))
fi
fi
done < <(find "$SPECS_DIR/$cat" -maxdepth 1 -type d -not -path "$SPECS_DIR/$cat")
else
echo -e "${YELLOW} MISSING${NC}: category $cat"
((SPEC_ISSUES++))
fi
done
# 2. Check for misplaced files in specs root
misplaced=$(find "$SPECS_DIR" -maxdepth 1 -type f -name "*.md" | wc -l)
if [[ $misplaced -gt 1 ]]; then # Ignore README.md
echo -e "${YELLOW} WARNING${NC}: Found $misplaced misplaced files in specs root (should be in 100/200/300)"
((SPEC_ISSUES++))
fi
else
echo -e "${RED}ERROR: Specs directory not found${NC}"
((SPEC_ISSUES++))
fi
echo
# Overall health
if [[ $TOTAL_ISSUES -eq 0 ]]; then
TOTAL_HEALTH_ISSUES=$((TOTAL_ISSUES + SPEC_ISSUES))
if [[ $TOTAL_HEALTH_ISSUES -eq 0 ]]; then
echo -e "${GREEN}=== SUCCESS: All skills healthy ===${NC}"
echo "Total skills: ${#SKILL_DIRS[@]}"
exit 0
+1 -33
View File
@@ -1,33 +1 @@
# Speckit Skills Version
version: 1.8.9
release_date: 2026-04-22
## Changelog
### 1.8.9 (2026-04-22)
- Full LCBP3-native rebuild of `.agents/skills/`
- Fixed ADR-019 drift (removed `@Expose({ name: 'id' })` and `id ?? ''` fallback patterns)
- Replaced all dead references (`GEMINI.md` → `AGENTS.md`, v1.7.0 → v1.8.0 schema, `.specify/memory/` → `AGENTS.md`)
- Added real helper scripts under `.agents/scripts/bash/` and `.agents/scripts/powershell/`
- Added ADR-007/008/020/021 coverage
- New rules: workflow-engine, file-two-phase-upload, ai-boundary, i18n, file-upload, workflow-banner
- Standardized frontmatter across all 20 skills (`version: 1.8.9`)
### 1.8.6 (2026-04-14)
- Version alignment with LCBP3-DMS v1.8.6
- Complete skill implementations for all 20 skills
- Enhanced security and audit capabilities
- Production-ready deployment status
### 1.1.0 (2026-01-24)
- New QA skills: tester, reviewer, checker
- tester: Execute tests, measure coverage, report results
- reviewer: Code review with severity levels and suggestions
- checker: Static analysis aggregation (lint, types, security)
### 1.0.0 (2026-01-24)
- Initial versioned release
- Core skills: specify, clarify, plan, tasks, implement, analyze, checklist, constitution, quizme, taskstoissues
- New skills: diff, validate, migrate, status
- All workflows enhanced with error handling and relative paths
version: 1.9.0
+43
View File
@@ -0,0 +1,43 @@
// File: .agents/skills/bugfix/SKILL.md
// Change Log: 2026-05-13 - Initial version improved from docs/bugfix.md
---
name: bugfix
description: Quick bugfix workflow with minimal impact. Focused on surgical fixes without unrelated refactoring.
version: 1.0.0
---
# Bugfix
ใช้สำหรับแก้ไข Bug ที่ระบุสาเหตุได้ชัดเจน โดยเน้นที่การแก้ไขที่ตรงจุด (Surgical Fix) และมีผลกระทบน้อยที่สุด (Minimal Impact)
## Phase 1 — Analysis (การวิเคราะห์)
1. **Read Logs & Context**: อ่าน Error Logs หรือรายละเอียดที่ User แจ้งมาให้ครบถ้วน
2. **Identify Root Cause**: ค้นหาสาเหตุที่แท้จริง (Root Cause) ไม่ใช่แค่การแก้ที่ปลายเหตุ
3. **Check Error Catalog**: ตรวจสอบ `docs/error-catalog.md` เพื่อดูว่ามี Error Code หรือ Pattern ที่เกี่ยวข้องหรือไม่
4. **Locate Code**: ระบุไฟล์และบรรทัดที่เกิดปัญหาให้ชัดเจน
## Phase 2 — Planning (การวางแผน)
1. **Create Fix Plan**: ร่างแผนการแก้ไขที่เน้น **Minimal Change**
- ห้าม Refactor โค้ดที่ไม่เกี่ยวข้อง
- หลีกเลี่ยงการเปลี่ยนแปลงที่จะส่งผลกระทบต่อส่วนอื่น (No Side Effects)
2. **Verify Standards**: ตรวจสอบว่าแผนการแก้ไขไม่ขัดกับ Tier 1 (Security, UUID, DB) และ Tier 2 (Architecture) ใน `AGENTS.md`
3. **Save to fix.md**: (Optional) บันทึกรายละเอียดการแก้ไขลงในไฟล์ `fix.md` เพื่อใช้ตรวจสอบก่อนลงมือจริง
## Phase 3 — Execution (การดำเนินการ)
1. **Apply Fix**: ลงมือแก้ไขโค้ดตามแผน
2. **Verify Fix**:
- จำลองสถานการณ์เพื่อยืนยันว่า Bug หายไปจริง
- ตรวจสอบว่าไม่มี Forbidden Patterns (`any`, `console.log`, UUID misuse)
3. **Regression Check**: ตรวจสอบส่วนที่เกี่ยวข้องว่ายังทำงานได้ปกติ
## Phase 4 — Finalization (การสรุปผล)
1. **Report**: สรุปผลการแก้ไขให้ User ทราบ
- Root cause (สาเหตุ)
- Fix detail (รายละเอียดการแก้)
- Affected files (ไฟล์ที่เกี่ยวข้อง)
2. **Cleanup**: ลบไฟล์ `fix.md` หรือ Debug logs ที่สร้างขึ้น
+1
View File
@@ -1,6 +1,7 @@
---
name: diagnose
description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test. Use when user says "diagnose this" / "debug this", reports a bug, says something is broken/throwing/failing, or describes a performance regression.
version: 1.9.0
---
# Diagnose
+1
View File
@@ -1,6 +1,7 @@
---
name: grill-with-docs
description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.
version: 1.9.0
---
<what-to-do>
@@ -1,7 +1,7 @@
---
name: nestjs-best-practices
description: NestJS best practices and architecture patterns for building production-ready LCBP3-DMS backend code. Enforces ADR-009 (no TypeORM migrations), ADR-019 (hybrid UUID), ADR-016 (security), ADR-007 (error handling), ADR-008 (BullMQ), ADR-001/002 (workflow + numbering), ADR-018/020 (AI boundary), and ADR-021 (workflow context).
version: 1.8.9
version: 1.9.0
scope: backend
user-invocable: false
license: MIT
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: next-best-practices
description: Next.js best practices for LCBP3-DMS frontend. Enforces ADR-019 (publicId only, no parseInt/id fallback), TanStack Query + RHF + Zod, shadcn/ui, i18n, ADR-007 error UX, ADR-021 IntegratedBanner/WorkflowLifecycle, two-phase file upload.
version: 1.8.9
version: 1.9.0
scope: frontend
user-invocable: false
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-analyze
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-tasks
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-checker
description: Run static analysis tools and aggregate results.
version: 1.8.9
version: 1.9.0
depends-on: []
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-checklist
description: Generate a custom checklist for the current feature based on user requirements.
version: 1.8.9
version: 1.9.0
---
## Checklist Purpose: "Unit Tests for English"
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-clarify
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-specify
handoffs:
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-constitution
description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync.
version: 1.8.9
version: 1.9.0
handoffs:
- label: Build Specification
agent: speckit-specify
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-diff
description: Compare two versions of a spec or plan to highlight changes.
version: 1.8.9
version: 1.9.0
depends-on: []
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-implement
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md (with Ironclad Anti-Regression Protocols)
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-tasks
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-migrate
description: Migrate existing projects into the speckit structure by generating spec.md, plan.md, and tasks.md from existing code.
version: 1.8.9
version: 1.9.0
depends-on: []
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-plan
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-specify
handoffs:
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-quizme
description: Challenge the specification with Socratic questioning to identify logical gaps, unhandled edge cases, and robustness issues.
version: 1.8.9
version: 1.9.0
handoffs:
- label: Clarify Spec Requirements
agent: speckit-clarify
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-reviewer
description: Perform code review with actionable feedback and suggestions.
version: 1.8.9
version: 1.9.0
depends-on: []
---
@@ -1,7 +1,7 @@
---
name: speckit-security-audit
description: Perform a security-focused audit of the codebase against OWASP Top 10, CASL authorization, and LCBP3-DMS security requirements.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-checker
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-specify
description: Create or update the feature specification from a natural language feature description.
version: 1.8.9
version: 1.9.0
handoffs:
- label: Build Technical Plan
agent: speckit-plan
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-status
description: Display a dashboard showing feature status, completion percentage, and blockers.
version: 1.8.9
version: 1.9.0
depends-on: []
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-tasks
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-plan
handoffs:
@@ -1,7 +1,7 @@
---
name: speckit-taskstoissues
description: Convert existing tasks into actionable, dependency-ordered issues for the feature based on available design artifacts.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-tasks
tools: ['github/github-mcp-server/issue_write']
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-tester
description: Execute tests, measure coverage, and report results.
version: 1.8.9
version: 1.9.0
depends-on: []
---
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: speckit-validate
description: Validate that implementation matches specification requirements.
version: 1.8.9
version: 1.9.0
depends-on:
- speckit-implement
---
+86
View File
@@ -0,0 +1,86 @@
---
auto_execution_mode: 0
description: Run the full speckit pipeline from specification to analysis in one command.
---
# Workflow: speckit.all
This meta-workflow orchestrates the **complete development lifecycle**, from specification through implementation and validation. For the preparation-only pipeline (steps 1-5), use `/speckit.prepare` instead.
## Preparation Phase (Steps 1-5)
1. **Specify** (`/speckit.specify`):
- Use the `view_file` tool to read: `.agents/skills/speckit-specify/SKILL.md`
- Execute with user's feature description
- Creates: `spec.md`
2. **Clarify** (`/speckit.clarify`):
- Use the `view_file` tool to read: `.agents/skills/speckit-clarify/SKILL.md`
- Execute to resolve ambiguities
- Updates: `spec.md`
3. **Plan** (`/speckit.plan`):
- Use the `view_file` tool to read: `.agents/skills/speckit-plan/SKILL.md`
- Execute to create technical design
- Creates: `plan.md`
4. **Tasks** (`/speckit.tasks`):
- Use the `view_file` tool to read: `.agents/skills/speckit-tasks/SKILL.md`
- Execute to generate task breakdown
- Creates: `tasks.md`
5. **Analyze** (`/speckit.analyze`):
- Use the `view_file` tool to read: `.agents/skills/speckit-analyze/SKILL.md`
- Execute to validate consistency across spec, plan, and tasks
- Output: Analysis report
- **Gate**: If critical issues found, stop and fix before proceeding
## Implementation Phase (Steps 6-7)
6. **Implement** (`/speckit.implement`):
- Use the `view_file` tool to read: `.agents/skills/speckit-implement/SKILL.md`
- Execute all tasks from `tasks.md` with anti-regression protocols
- Output: Working implementation
7. **Check** (`/speckit.checker`):
- Use the `view_file` tool to read: `.agents/skills/speckit-checker/SKILL.md`
- Run static analysis (linters, type checkers, security scanners)
- Output: Checker report
## Verification Phase (Steps 8-10)
8. **Test** (`/speckit.tester`):
- Use the `view_file` tool to read: `.agents/skills/speckit-tester/SKILL.md`
- Run tests with coverage
- Output: Test + coverage report
9. **Review** (`/speckit.reviewer`):
- Use the `view_file` tool to read: `.agents/skills/speckit-reviewer/SKILL.md`
- Perform code review
- Output: Review report with findings
10. **Validate** (`/speckit.validate`):
- Use the `view_file` tool to read: `.agents/skills/speckit-validate/SKILL.md`
- Verify implementation matches spec requirements
- Output: Validation report (pass/fail)
## Usage
```
/speckit.all "Build a user authentication system with OAuth2 support"
```
## Pipeline Comparison
| Pipeline | Steps | Use When |
| ------------------ | ------------------------- | -------------------------------------- |
| `/speckit.prepare` | 1-5 (Specify → Analyze) | Planning only — you'll implement later |
| `/speckit.all` | 1-10 (Specify → Validate) | Full lifecycle in one pass |
## On Error
If any step fails, stop the pipeline and report:
- Which step failed
- The error message
- Suggested remediation (e.g., "Run `/speckit.clarify` to resolve ambiguities before continuing")
+28
View File
@@ -0,0 +1,28 @@
---
auto_execution_mode: 0
description: Execute the full preparation pipeline (Specify -> Clarify -> Plan -> Tasks -> Analyze) in sequence.
---
# Workflow: speckit.prepare
This workflow orchestrates the sequential execution of the Speckit preparation phase skills (02-06).
1. **Step 1: Specify (Skill 02)**
- Goal: Create or update the `spec.md` based on user input.
- Action: Read and execute `.agents/skills/speckit-specify/SKILL.md`.
2. **Step 2: Clarify (Skill 03)**
- Goal: Refine the `spec.md` by identifying and resolving ambiguities.
- Action: Read and execute `.agents/skills/speckit-clarify/SKILL.md`.
3. **Step 3: Plan (Skill 04)**
- Goal: Generate `plan.md` from the finalized spec.
- Action: Read and execute `.agents/skills/speckit-plan/SKILL.md`.
4. **Step 4: Tasks (Skill 05)**
- Goal: Generate actionable `tasks.md` from the plan.
- Action: Read and execute `.agents/skills/speckit-tasks/SKILL.md`.
5. **Step 5: Analyze (Skill 06)**
- Goal: Validate consistency across all design artifacts (spec, plan, tasks).
- Action: Read and execute `.agents/skills/speckit-analyze/SKILL.md`.
@@ -0,0 +1,19 @@
---
auto_execution_mode: 0
description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync.
---
# Workflow: speckit.constitution
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-constitution/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `.specify/` directory doesn't exist: Initialize the speckit structure first
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Create or update the feature specification from a natural language feature description.
---
# Workflow: speckit.specify
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
- This is typically the starting point of a new feature.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-specify/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the feature description for the skill's logic.
4. **On Error**:
- If no feature description provided: Ask the user to describe the feature they want to specify
+19
View File
@@ -0,0 +1,19 @@
---
auto_execution_mode: 0
description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec.
---
# Workflow: speckit.clarify
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-clarify/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `spec.md` is missing: Run `/speckit.specify` first to create the feature specification
+19
View File
@@ -0,0 +1,19 @@
---
auto_execution_mode: 0
description: Execute the implementation planning workflow using the plan template to generate design artifacts.
---
# Workflow: speckit.plan
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-plan/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `spec.md` is missing: Run `/speckit.specify` first to create the feature specification
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts.
---
# Workflow: speckit.tasks
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-tasks/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `plan.md` is missing: Run `/speckit.plan` first
- If `spec.md` is missing: Run `/speckit.specify` first
+23
View File
@@ -0,0 +1,23 @@
---
auto_execution_mode: 0
description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation.
---
// turbo-all
# Workflow: speckit.analyze
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-analyze/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `spec.md` is missing: Run `/speckit.specify` first
- If `plan.md` is missing: Run `/speckit.plan` first
- If `tasks.md` is missing: Run `/speckit.tasks` first
@@ -0,0 +1,21 @@
---
auto_execution_mode: 0
description: Execute the implementation plan by processing and executing all tasks defined in tasks.md
---
# Workflow: speckit.implement
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-implement/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `tasks.md` is missing: Run `/speckit.tasks` first
- If `plan.md` is missing: Run `/speckit.plan` first
- If `spec.md` is missing: Run `/speckit.specify` first
+22
View File
@@ -0,0 +1,22 @@
---
auto_execution_mode: 0
description: Run static analysis tools and aggregate results.
---
// turbo-all
# Workflow: speckit.checker
1. **Context Analysis**:
- The user may specify paths to check or run on entire project.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-checker/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If no linting tools available: Report which tools to install based on project type
- If tools fail: Show raw error and suggest config fixes
+22
View File
@@ -0,0 +1,22 @@
---
auto_execution_mode: 0
description: Execute tests, measure coverage, and report results.
---
// turbo-all
# Workflow: speckit.tester
1. **Context Analysis**:
- The user may specify test paths, options, or just run all tests.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-tester/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If no test framework detected: Report "No test framework found. Install Jest, Vitest, Pytest, or similar."
- If tests fail: Show failure details and suggest fixes
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Perform code review with actionable feedback and suggestions.
---
# Workflow: speckit.reviewer
1. **Context Analysis**:
- The user may specify files to review, "staged" for git staged changes, or "branch" for branch diff.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-reviewer/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If no files to review: Ask user to stage changes or specify file paths
- If not a git repo: Review current directory files instead
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Validate that implementation matches specification requirements.
---
# Workflow: speckit.validate
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-validate/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `tasks.md` is missing: Run `/speckit.tasks` first
- If implementation not started: Run `/speckit.implement` first
@@ -0,0 +1,22 @@
---
auto_execution_mode: 0
description: Perform a security-focused audit of the codebase against OWASP Top 10, CASL authorization, and LCBP3-DMS security requirements.
---
# Workflow: speckit.security-audit
1. **Context Analysis**:
- The user may pass a scope hint: `backend`, `frontend`, `both`, or specific module paths (defaults to `both`).
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-security-audit/SKILL.md`
- Also load `.agents/skills/_LCBP3-CONTEXT.md` for project-specific rules.
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- This is READ-ONLY — never modify code during the audit.
- Output a structured report with Critical / High / Medium / Low severity.
4. **On Error**:
- If scope unclear: Default to `both` (backend + frontend)
- If `specs/06-Decision-Records/ADR-016-security-authentication.md` missing: Warn and proceed with OWASP Top 10 + CASL checks only
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Quick bugfix workflow with minimal impact. Focused on surgical fixes without unrelated refactoring.
---
# Workflow: bugfix
1. **Context Analysis**:
- The user has reported a bug. Treat the bug description or logs as the primary input.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/bugfix/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Phases: Analysis → Planning → Execution → Finalization
4. **Safety Check**:
- Always ensure Tier 1 rules (Security, UUID v7, DB Schema) are NOT violated.
- Refer to `AGENTS.md` for the full list of forbidden patterns.
@@ -0,0 +1,52 @@
---
auto_execution_mode: 0
description: Create a new NestJS backend feature module following project standards
---
# Create NestJS Backend Module
Use this workflow when creating a new feature module in `backend/src/modules/`.
Follows `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` and ADR-005.
## Steps
// turbo
1. **Verify requirements exist** — confirm the feature is in `specs/01-Requirements/` before starting
// turbo 2. **Check schema** — read `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema.sql` for relevant tables
3. **Scaffold module folder**
```
backend/src/modules/<module-name>/
├── <module-name>.module.ts
├── <module-name>.controller.ts
├── <module-name>.service.ts
├── dto/
│ ├── create-<module-name>.dto.ts
│ └── update-<module-name>.dto.ts
├── entities/
│ └── <module-name>.entity.ts
└── <module-name>.controller.spec.ts
```
// turbo 4. **Create Entity** — map ONLY columns defined in the schema SQL. Use TypeORM decorators. Add `@VersionColumn()` if the entity needs optimistic locking.
// turbo 5. **Create DTOs** — use `class-validator` decorators. Never use `any`. Validate all inputs.
// turbo 6. **Create Service** — inject repository via constructor DI. Use transactions for multi-step writes. Add `Idempotency-Key` guard for POST/PUT/PATCH operations.
// turbo 7. **Create Controller** — apply `@UseGuards(JwtAuthGuard, CaslAbilityGuard)`. Use proper HTTP status codes. Document with `@ApiTags` and `@ApiOperation`.
// turbo 8. **Register in Module** — add to `imports`, `providers`, `controllers`, `exports` as needed.
// turbo 9. **Register in AppModule** — import the new module in `app.module.ts`.
// turbo 10. **Write unit test** — cover service methods with Jest mocks. Run:
```bash
pnpm test:watch
```
// turbo 11. **Citation** — confirm implementation references `specs/01-Requirements/` and `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md`
+65
View File
@@ -0,0 +1,65 @@
---
auto_execution_mode: 0
description: Create a new Next.js App Router page following project standards
---
# Create Next.js Frontend Page
Use this workflow when creating a new page in `frontend/app/`.
Follows `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md`, ADR-011, ADR-012, ADR-013, ADR-014.
## Steps
1. **Determine route** — decide the route path, e.g. `app/(dashboard)/documents/page.tsx`
2. **Classify components** — decide what is Server Component (default) vs Client Component (`'use client'`)
- Server Component: initial data load, static content, SEO
- Client Component: interactivity, forms, TanStack Query hooks, Zustand
3. **Create page file** — Server Component by default:
```typescript
// app/(dashboard)/<route>/page.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
title: '<Page Title> | LCBP3-DMS',
};
export default async function <PageName>Page() {
return (
<div>
{/* Page content */}
</div>
);
}
```
4. **Create API hook** (if client-side data needed) — add to `hooks/use-<feature>.ts`:
```typescript
'use client';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
export function use<Feature>() {
return useQuery({
queryKey: ['<feature>'],
queryFn: () => apiClient.get('<endpoint>'),
});
}
```
5. **Build UI components** — use Shadcn/UI primitives. Place reusable components in `components/<feature>/`.
6. **Handle forms** — use React Hook Form + Zod schema validation. Never access form values without validation.
7. **Handle errors** — add `error.tsx` alongside `page.tsx` for route-level error boundaries.
8. **Add loading state** — add `loading.tsx` for Suspense fallback if page does async work.
9. **Add to navigation** — update sidebar/nav config if the page should appear in the menu.
10. **Access control** — ensure page checks CASL permissions. Redirect unauthorized users via middleware or `notFound()`.
11. **Citation** — confirm implementation references `specs/01-Requirements/` and `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md`
+72
View File
@@ -0,0 +1,72 @@
---
auto_execution_mode: 0
description: Deploy the application via Gitea Actions to QNAP Container Station
---
# Deploy to Production
Use this workflow to deploy updated backend and/or frontend to QNAP via Gitea Actions CI/CD.
Follows `specs/04-Infrastructure-OPS/` and ADR-015.
## Pre-deployment Checklist
- [ ] All tests pass locally (`pnpm test:watch`)
- [ ] No TypeScript errors (`tsc --noEmit`)
- [ ] No `any` types introduced
- [ ] Schema changes applied to `specs/03-Data-and-Storage/lcbp3-v1.7.0-schema.sql`
- [ ] Environment variables documented (NOT in `.env` files)
## Steps
1. **Commit and push to Gitea**
```bash
git status
git add .
git commit -m "feat(<scope>): <description>"
git push origin main
```
2. **Monitor Gitea Actions** — open Gitea web UI → Actions tab → verify pipeline starts
3. **Pipeline stages (automatic)**
- `build-backend` → Docker image build + push to registry
- `build-frontend` → Docker image build + push to registry
- `deploy` → SSH to QNAP → `docker compose pull` + `docker compose up -d`
4. **Verify backend health**
```bash
curl http://<QNAP_IP>:3000/health
# Expected: { "status": "ok" }
```
5. **Verify frontend**
```bash
curl -I http://<QNAP_IP>:3001
# Expected: HTTP 200
```
6. **Check logs in Grafana** — navigate to Grafana → Loki → filter by container name
- Backend: `container_name="lcbp3-backend"`
- Frontend: `container_name="lcbp3-frontend"`
7. **Verify database** — confirm schema changes are reflected (if any)
8. **Rollback (if needed)**
```bash
# SSH into QNAP
docker compose pull <service>=<previous-image-tag>
docker compose up -d <service>
```
## Common Issues
| Symptom | Cause | Fix |
| ----------------- | --------------------- | ----------------------------------- |
| Backend unhealthy | DB connection failed | Check MariaDB container + env vars |
| Frontend blank | Build error | Check Next.js build logs in Grafana |
| 502 Bad Gateway | Container not started | `docker compose ps` to check status |
| Pipeline stuck | Gitea runner offline | Restart runner on QNAP |
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test.
---
# Workflow: diagnose
1. **Context Analysis**:
- The user has provided a bug report or performance regression. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/diagnose/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Execute phases: Build feedback loop → Reproduce → Hypothesise → Instrument → Fix → Regression test → Cleanup
4. **On Error**:
- If cannot build a feedback loop: Ask user for environment access, captured artifacts, or production instrumentation
- If no correct seam for regression test: Flag architectural issues to improve-codebase-architecture
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise.
---
# Workflow: grill-with-docs
1. **Context Analysis**:
- The user has provided a plan to stress-test. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/grill-with-docs/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Ask questions one at a time, waiting for feedback before continuing.
- Update CONTEXT.md and ADRs inline as terms are resolved.
4. **On Error**:
- If CONTEXT.md or docs/adr/ don't exist: Create them lazily when first term is resolved
+62
View File
@@ -0,0 +1,62 @@
---
auto_execution_mode: 0
description: Review code changes for bugs, security issues, and improvements
---
You are a senior software engineer performing a thorough code review to identify potential bugs.
Your task is to find all potential bugs and code improvements in the code changes. Focus on:
1. Logic errors and incorrect behavior
2. Edge cases that aren't handled
3. Null/undefined reference issues
4. Race conditions or concurrency issues
5. Security vulnerabilities
6. Improper resource management or resource leaks
7. API contract violations
8. Incorrect caching behavior, including cache staleness issues, cache key-related bugs, incorrect cache invalidation, and ineffective caching
9. Violations of existing code patterns or conventions
## 🔴 Tier 1 Critical Rules (CI Blockers)
The following are **CI-blocking issues** that must be caught in code review. These align with project specs in `specs/05-Engineering-Guidelines/` and `specs/06-Decision-Records/`:
### ADR-019: UUID Handling
- **❌ NEVER use `parseInt()`, `Number()`, or `+` operator on UUID values**
- Example of violation: `parseInt(projectId)` where `projectId` is UUID string
- ✅ Correct: Use UUID string directly without conversion
- **❌ NEVER expose internal INT PK in API responses**
- API must expose only `publicId` (transformed to `id` via `@Expose()`)
- Verify DTOs have `@Exclude()` on `id: number` field
### TypeScript Strict Rules
- **❌ ZERO `any` types allowed** — use proper types or `unknown` + narrowing
- **❌ ZERO `console.log`** — must use NestJS `Logger` (backend) or remove (frontend)
- **❌ NO `req: any` in controllers** — use `RequestWithUser` typed interface
### Database & Architecture
- **❌ 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`
### Security (ADR-016)
- Idempotency validation for critical `POST`/`PUT`/`PATCH` endpoints
- Two-phase file upload pattern (Upload → Temp → Commit → Permanent)
- Input validation with class-validator (backend) and Zod (frontend)
### Test Coverage Requirements
- **Backend Services:** 80% minimum
- **Backend Overall:** 70% minimum
- **Business Logic:** 80% minimum
Make sure to:
1. If exploring the codebase, call multiple tools in parallel for increased efficiency. Do not spend too much time exploring.
2. If you find any pre-existing bugs in the code, you should also report those since it's important for us to maintain general code quality for the user.
3. Do NOT report issues that are speculative or low-confidence. All your conclusions should be based on a complete understanding of the codebase.
4. Remember that if you were given a specific git commit, it may not be checked out and local code states may be different.
+109
View File
@@ -0,0 +1,109 @@
---
auto_execution_mode: 0
description: Manage database schema changes following ADR-009 (no migrations, modify SQL directly)
---
# Schema Change Workflow
Use this workflow when modifying database schema for LCBP3-DMS.
Follows `specs/06-Decision-Records/ADR-009-database-strategy.md`**NO TypeORM migrations**.
## Pre-Change Checklist
- [ ] Change is required by a spec in `specs/01-Requirements/`
- [ ] Existing data impact has been assessed
- [ ] No SQL triggers are being added (business logic in NestJS only)
## Steps
1. **Read current schema** — load the full schema file:
```
specs/03-Data-and-Storage/lcbp3-v1.8.0-schema.sql
```
2. **Read data dictionary** — understand current field definitions:
```
specs/03-Data-and-Storage/03-01-data-dictionary.md
```
// turbo 3. **Identify impact scope** — determine which tables, columns, indexes, or constraints are affected. List:
- Tables being modified/created
- Columns being added/renamed/dropped
- Foreign key relationships affected
- Indexes being added/modified
- Seed data impact (if any)
4. **Modify schema SQL** — edit `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema.sql`:
- Add/modify table definitions
- Maintain consistent formatting (uppercase SQL keywords, lowercase identifiers)
- Add inline comments for new columns explaining purpose
- Ensure `DEFAULT` values and `NOT NULL` constraints are correct
- Add `version` column with `@VersionColumn()` marker comment if optimistic locking is needed
> [!CAUTION]
> **NEVER use SQL Triggers.** All business logic must live in NestJS services.
5. **Update data dictionary** — edit `specs/03-Data-and-Storage/03-01-data-dictionary.md`:
- Add new tables/columns with descriptions
- Update data types and constraints
- Document business rules for new fields
- Add enum value definitions if applicable
6. **Update seed data** (if applicable):
- `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-basic.sql` — for reference/lookup data
- `specs/03-Data-and-Storage/lcbp3-v1.8.0-seed-permissions.sql` — for new CASL permissions
7. **Update TypeORM entity** — modify corresponding `backend/src/modules/<module>/entities/*.entity.ts`:
- Map ONLY columns defined in schema SQL
- Use correct TypeORM decorators (`@Column`, `@PrimaryGeneratedColumn`, `@ManyToOne`, etc.)
- Add `@VersionColumn()` if optimistic locking is needed
8. **Update DTOs** — if new columns are exposed via API:
- Add fields to `create-*.dto.ts` and/or `update-*.dto.ts`
- Add `class-validator` decorators for all new fields
- Never use `any` type
// turbo 9. **Run type check** — verify no TypeScript errors:
```bash
cd backend && npx tsc --noEmit
```
10. **Generate SQL diff** — create a summary of changes for the user to apply manually:
```
-- Schema Change Summary
-- Date: <current date>
-- Feature: <feature name>
-- Tables affected: <list>
--
-- ⚠️ Apply this SQL to the live database manually:
ALTER TABLE ...;
-- or
CREATE TABLE ...;
```
11. **Notify user** — present the SQL diff and remind them:
- Apply the SQL change to the live database manually
- Verify the change doesn't break existing data
- Run `pnpm test` after applying to confirm entity mappings work
## Common Patterns
| Change Type | Template |
| ----------- | -------------------------------------------------------------- |
| Add column | `ALTER TABLE \`table\` ADD COLUMN \`col\` TYPE DEFAULT value;` |
| Add table | Full `CREATE TABLE` with constraints and indexes |
| Add index | `CREATE INDEX \`idx_table_col\` ON \`table\` (\`col\`);` |
| Add FK | `ALTER TABLE \`child\` ADD CONSTRAINT ... FOREIGN KEY ...` |
| Add enum | Add to data dictionary + `ENUM('val1','val2')` in column def |
## On Error
- If schema SQL has syntax errors → fix and re-validate with `tsc --noEmit`
- If entity mapping doesn't match schema → compare column-by-column against SQL
- If seed data conflicts → check unique constraints and foreign keys
+21
View File
@@ -0,0 +1,21 @@
---
auto_execution_mode: 0
description: Test-driven development with red-green-refactor loop. Use when user wants to build features or fix bugs using TDD, mentions red-green-refactor, wants integration tests, or asks for test-first development.
---
# Workflow: tdd
1. **Context Analysis**:
- The user wants to build features or fix bugs using TDD. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/tdd/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Plan → Tracer Bullet → Incremental Loop → Refactor
- One test at a time, only enough code to pass current test.
4. **On Error**:
- If interface changes are needed: Confirm with user first
- If unsure which behaviors to test: Ask user to prioritize
+21
View File
@@ -0,0 +1,21 @@
---
auto_execution_mode: 0
description: Break a plan, spec, or PRD into independently-grabbable issues on the project issue tracker using tracer-bullet vertical slices.
---
# Workflow: to-issues
1. **Context Analysis**:
- The user wants to convert a plan into issues. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/to-issues/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Draft vertical slices (HITL or AFK) → Quiz user → Publish to issue tracker.
- Each slice delivers a narrow but complete path through every layer.
4. **On Error**:
- If issue tracker not configured: Run `/setup-matt-pocock-skills` first
- If user wants different granularity: Iterate on slice sizes
+21
View File
@@ -0,0 +1,21 @@
---
auto_execution_mode: 0
description: Turn the current conversation context into a PRD and publish it to the project issue tracker.
---
# Workflow: to-prd
1. **Context Analysis**:
- The user wants to create a PRD from the current context. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/to-prd/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Synthesize current conversation and codebase understanding into a PRD.
- Do NOT interview the user - use existing knowledge.
4. **On Error**:
- If issue tracker not configured: Run `/setup-matt-pocock-skills` first
- If user expectations unclear: Confirm major modules with user
+22
View File
@@ -0,0 +1,22 @@
---
auto_execution_mode: 0
description: Triage issues through a state machine driven by triage roles. Use when user wants to create an issue, triage issues, review incoming bugs or feature requests, prepare issues for an AFK agent, or manage issue workflow.
---
# Workflow: triage
1. **Context Analysis**:
- The user wants to triage issues. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/triage/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Show what needs attention OR Triage specific issue OR Quick state override.
- Apply triage roles: bug/enhancement + needs-triage/needs-info/ready-for-agent/ready-for-human/wontfix.
4. **On Error**:
- If issue tracker not configured: Run `/setup-matt-pocock-skills` first
- If state roles conflict: Flag and ask maintainer before proceeding
- If no reproduction possible: Mark as `needs-info`
@@ -0,0 +1,19 @@
---
auto_execution_mode: 0
description: Generate a custom checklist for the current feature based on user requirements.
---
# Workflow: speckit.checklist
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-checklist/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If `spec.md` is missing: Run `/speckit.specify` first to create the feature specification
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Compare two versions of a spec or plan to highlight changes.
---
# Workflow: speckit.diff
1. **Context Analysis**:
- The user has provided an input prompt (optional file paths or version references).
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-diff/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If no files to compare: Use current feature's `spec.md` vs git HEAD
- If `spec.md` doesn't exist: Run `/speckit.specify` first
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Migrate existing projects into the speckit structure by generating spec.md, plan.md, and tasks.md from existing code.
---
# Workflow: speckit.migrate
1. **Context Analysis**:
- The user has provided an input prompt (path to analyze, feature name).
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-migrate/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If path doesn't exist: Ask user to provide valid directory path
- If no code found: Report that no analyzable code was detected
+21
View File
@@ -0,0 +1,21 @@
---
auto_execution_mode: 0
description: Challenge the specification with Socratic questioning to identify logical gaps, unhandled edge cases, and robustness issues.
---
// turbo-all
# Workflow: speckit.quizme
1. **Context Analysis**:
- The user has provided an input prompt. Treat this as the primary input for the skill.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-quizme/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If required files don't exist, inform the user which prerequisite workflow to run first (e.g., `/speckit.specify` to create `spec.md`).
+21
View File
@@ -0,0 +1,21 @@
---
auto_execution_mode: 0
description: Display a dashboard showing feature status, completion percentage, and blockers.
---
// turbo-all
# Workflow: speckit.status
1. **Context Analysis**:
- The user may optionally specify a feature to focus on.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-status/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Apply the user's prompt as the input arguments/context for the skill's logic.
4. **On Error**:
- If no features exist: Report "No features found. Run `/speckit.specify` to create your first feature."
@@ -0,0 +1,23 @@
---
auto_execution_mode: 0
description: Convert existing tasks into actionable, dependency-ordered issues on Gitea for the current feature.
---
# Workflow: speckit.taskstoissues
1. **Context Analysis**:
- The user may pass filters (e.g., phase, priority). Default: convert all pending tasks.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/speckit-taskstoissues/SKILL.md`
- Also load `.agents/skills/_LCBP3-CONTEXT.md` for project conventions (labels, commit format).
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Use Gitea API (not GitHub) — target `git.np-dms.work/np-dms/lcbp3`.
- Apply LCBP3 labels: `spec`, `adr`, `security`, `ux`, `backend`, `frontend`, `schema`, etc.
- Use commit-format-compatible issue titles (per `specs/05-Engineering-Guidelines/05-05-git-conventions.md`).
4. **On Error**:
- If `tasks.md` missing: Run `/05-speckit.tasks` first
- If Gitea credentials missing: Report to user and provide manual issue-creation template
+20
View File
@@ -0,0 +1,20 @@
---
auto_execution_mode: 0
description: Tell the agent to zoom out and give broader context or a higher-level perspective. Use when you're unfamiliar with a section of code or need to understand how it fits into the bigger picture.
---
# Workflow: zoom-out
1. **Context Analysis**:
- The user is unfamiliar with a section of code or needs broader context. Treat this as the primary input.
2. **Load Skill**:
- Use the `view_file` tool to read the skill file at: `.agents/skills/zoom-out/SKILL.md`
3. **Execute**:
- Follow the instructions in the `SKILL.md` exactly.
- Go up a layer of abstraction and give a map of all relevant modules and callers.
- Use the project's domain glossary vocabulary.
4. **On Error**:
- No specific error handling - this is an exploratory skill.
+42 -254
View File
@@ -1,288 +1,76 @@
---
trigger: always_on
---
# NAP-DMS Project Context & Rules
# NAP-DMS Gemini Rules & Standards
- For: Gemeni CLI and Gemini.
- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-03-27
- Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3)
- For: Gemini 1.5 Pro / Flash / 2.0 (Google AI Studio, Vertex AI, Antigravity)
- Version: 1.9.0 | Last synced from AGENTS.md: 2026-05-13
- Project: LCBP3-DMS
---
## 🧠 Role & Persona
Act as a **Senior Full Stack Developer** specialized in:
- NestJS, Next.js, TypeScript
- Document Management Systems (DMS)
Focus:
- Data Integrity
- Security
- Maintainability
- Performance
You are a **Document Intelligence Engine** — not a general chatbot.
Every response must be **precise**, **spec-compliant**, and **production-ready**.
Act as a **Senior Full Stack Developer** (NestJS, Next.js, TypeScript).
You are a **Document Intelligence Engine** — focus on Data Integrity, Security, and Production-ready code.
---
## 🧭 Rule Enforcement Tiers
## 🧩 Thinking Protocol (Tier 1 & 2)
### 🔴 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-018)
- Forbidden patterns: `any`, `console.log`, UUID misuse
### 🟡 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
### 🟢 Tier 3 — GUIDELINES
Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
Before any code changes:
1. **Analyze**: Problem understanding + Context Search (Specs/ADRs) + Constraints.
2. **Plan**: 2 Alternatives + Roadmap + Verification Plan (Tests).
3. **Execute**: Follow roadmap + Summary of logic changes.
---
## 🗂️ Key Spec Files (Always Check Before Writing Code)
## 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others
| Document | Path | Use When |
| ----------------------- | ----------------------------------------------------------------- | ------------------------------- |
| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology |
| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query |
| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules |
| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows |
| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related 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 |
| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | Commit/branch naming |
| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | Reusable patterns |
| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | Localization rules |
| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | Before deploy/hotfix |
| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | Feature completeness |
1. **UUID (ADR-019):** No `parseInt` on UUID. Use `publicId` (string) only.
2. **Database (ADR-009):** No TypeORM migrations. Edit `schema-02-tables.sql` directly.
3. **Security (ADR-016):** CASL Guard for all APIs. Whitelist file uploads + ClamAV.
4. **AI Boundary (ADR-018):** AI → DMS API → DB. No direct DB access.
5. **Types:** ZERO `any`. ZERO `console.log`.
---
## 🆔 Identifier Strategy (ADR-019) — CRITICAL
## 📐 TypeScript Standards (v1.9.0)
| Context | Type | Notes |
| ---------------- | ------------------------- | ------------------------------------------- |
| Internal / DB FK | `INT AUTO_INCREMENT` | Never exposed in API |
| Public API / URL | `UUIDv7` (MariaDB native) | Stored as BINARY(16), no transformer needed |
| Entity Property | `publicId: string` | Exposed directly in API (no transformation) |
| API Response | `publicId: string` (UUID) | INT `id` has `@Exclude()` — never appears |
### ✅ Updated Pattern (March 2026)
**Backend:** `UuidBaseEntity` exposes `publicId` directly — no `@Expose({ name: 'id' })` transformation
**Frontend:** Use `publicId` only — no `uuid` or `id` fallbacks:
```typescript
// ✅ CORRECT — Use publicId only
type ProjectOption = {
publicId?: string; // No uuid, no id fallback
projectName?: string;
};
// ❌ WRONG — Multiple identifiers cause confusion
type ProjectOption = {
publicId?: string;
uuid?: string; // Don't do this
id?: number; // Don't do this
};
```
### ❌ Forbidden UUID Patterns
```typescript
// ❌ NEVER use parseInt on UUID
parseInt(projectId); // "0195..." → 19 (WRONG!)
// ❌ NEVER use id ?? '' fallback
const value = c.publicId ?? c.id ?? ''; // Wrong!
// ✅ CORRECT — Use publicId only
const value = c.publicId; // "019505a1-7c3e-7000-8000-abc123def456"
```
Read `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md` before any UUID-related work.
- **File Header:** First line MUST be `// File: path/filename`.
- **Change Log:** Include `// Change Log` at the top.
- **Language:** Code in English, Comments/JSDoc in **Thai**.
- **Compactness:** No blank lines inside functions.
- **Export:** Single main symbol per file.
- **Typing:** Explicit types for variables, parameters, and returns.
---
## 🛡️ Security Rules (Non-Negotiable)
## 📁 Specs Organization (Hybrid Model)
1. **Idempotency:** All critical `POST`/`PUT`/`PATCH` MUST validate `Idempotency-Key` header
2. **Two-Phase File Upload:** Upload → Temp → Commit → Permanent
3. **Race Conditions:** Redis Redlock + TypeORM `@VersionColumn` for Document Numbering
4. **Validation:** Zod (frontend) + class-validator (backend DTO)
5. **Password:** bcrypt 12 salt rounds, min 8 chars, rotate every 90 days
6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints
7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan
8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access
Full details: `specs/06-Decision-Records/ADR-016-security-authentication.md`
- **Core (00-06):** Source of Truth (Overview, Req, Arch, Data, Ops, Guidelines, ADRs).
- **Feature (100, 200, 300):** Implementation Work (100: Infra, 200: Fullstack, 300: Others).
---
## 📐 TypeScript Rules
## 🛡️ Security & Workflow (Non-Negotiable)
- **Strict Mode** — all strict checks enforced
- **ZERO `any` types** — use proper types or `unknown` + narrowing
- **ZERO `console.log`** — NestJS `Logger` (backend); remove before commit (frontend)
- **Workflow (ADR-001/021):** DSL-based engine. Integrated context in UI.
- **Numbering (ADR-002):** Redis Redlock + Optimistic Lock.
- **Notifications (ADR-008):** BullMQ jobs (never inline).
- **Error (ADR-007):** Layered classification + User-friendly messages.
---
## 🏷 Domain Terminology
## 🗂 Key References
| ✅ Use | ❌ Don't Use |
| ------------------ | ------------------------------------- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
| RBAC | Permission System (generic) |
Full glossary: `specs/00-overview/00-02-glossary.md`
---
## 🚫 Forbidden Actions
| ❌ Forbidden | ✅ Correct Approach |
| ----------------------------------------------- | --------------------------------------------- |
| SQL Triggers for business logic | NestJS Service methods |
| `.env` files in production | `docker-compose.yml` environment section |
| TypeORM migration files | Edit schema SQL directly (ADR-009) |
| Inventing table/column names | Verify against `schema-02-tables.sql` |
| `any` TypeScript type | Proper types / generics |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) |
| `req: any` in controllers | `RequestWithUser` typed interface |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) |
| Exposing INT PK in API responses | UUIDv7 (ADR-019) |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) |
| Direct file operations bypassing StorageService | `StorageService` for all file moves |
| Inline email/notification sending | BullMQ queue job |
| Deploying without Release Gates | Complete `04-08-release-management-policy.md` |
---
## 🔄 Development Flow (Tiered)
### 🔴 Critical Work — DB / API / Security / Workflow Engine
**MUST complete all steps:**
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`
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)
7. **Write code** — TypeScript strict, no `any`, no `console.log`
### 🟡 Normal Work — UI / Feature / Integration
- Follow existing patterns in codebase
- Check spec for relevant module only
- No need to read all specs
### 🟢 Quick Fix — Bug Fix / Typo / Style
- Fix directly
- Add minimal test if logic changed
- Check forbidden patterns before commit
---
## 🎯 Context-Aware Triggers
When user asks about... check these files:
| Request | Files to Check | Expected Response |
| -------------------- | ------------------------------------------------------- | --------------------------------------------------- |
| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard |
| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments |
| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity |
| "ตรวจสอบ UUID" | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor |
| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow |
| "ตรวจสอบ permission" | `seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix |
| "deploy production" | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy |
| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns |
---
## ✅ Quick Reference Checklist (Before Every Commit)
- [ ] UUID pattern verified (no parseInt on UUID)
- [ ] No `any` types in TypeScript
- [ ] No `console.log` in committed code
- [ ] Comments in Thai
- [ ] Code identifiers in English
- [ ] Schema changes via SQL directly (not migration)
- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+)
- [ ] Relevant ADRs checked (ADR-009, ADR-018, ADR-019)
- [ ] Glossary terms used correctly
- [ ] Error handling complete (Logger + HttpException)
- [ ] i18n keys used instead of hardcode text
- [ ] Cache invalidation when data modified
- [ ] Security checklist passed (OWASP Top 10)
---
## 📚 Full Documentation
This file is a **quick reference**. For detailed information:
- **Architecture:** `specs/02-architecture/`
- **Requirements:** `specs/01-requirements/`
- **Data & Storage:** `specs/03-Data-and-Storage/`
- **Engineering Guidelines:** `specs/05-Engineering-Guidelines/`
- **Decision Records:** `specs/06-Decision-Records/`
- **Infrastructure:** `specs/04-Infrastructure-OPS/`
| Area | Key File |
| --- | --- |
| Glossary | `specs/00-overview/00-02-glossary.md` |
| Schema | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` |
| RBAC | `specs/01-requirements/01-02-business-rules/01-02-01-rbac-matrix.md` |
| API | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` |
| UI | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` |
---
## 🔄 Change Log
| Version | Date | Changes | Updated By |
| ------- | ---------- | ------------------------------------------------------------------- | -------------- |
| 1.8.5 | 2026-03-27 | Refactored — moved detailed content to specs/, now quick reference | Windsurf AI |
| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI |
| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI |
| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI |
| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet |
| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev |
| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro |
---
**To update this file:**
1. Edit relevant sections
2. Update Change Log above
3. Bump version number in header
4. Commit: `spec(agents): bump to vX.X.X - <brief description>`
- 1.9.0: Sync with AGENTS.md v1.9.0 (TS Standards, Hybrid Specs).
- 1.8.5: Legacy version.
+1
View File
@@ -0,0 +1 @@
24.15.0
+8 -3
View File
@@ -1,7 +1,11 @@
// File: specs/[100/200/300]-category/feature-name/plan.md
// Change Log:
// - [DATE]: Initial implementation plan for [FEATURE]
# Implementation Plan: [FEATURE]
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
**Input**: Feature specification from `/specs/[100/200/300]-category/feature-name/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
@@ -38,13 +42,14 @@ _GATE: Must pass before Phase 0 research. Re-check after Phase 1 design._
### Documentation (this feature)
```text
specs/[###-feature]/
specs/[100/200/300]-category/[feature-name]/
├── spec.md # Feature specification
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
└── tasks.md # Phase 2 output (/speckit.tasks command)
```
### Source Code (repository root)
+5
View File
@@ -1,8 +1,13 @@
// File: specs/[100/200/300]-category/feature-name/spec.md
// Change Log:
// - [DATE]: Initial specification for [FEATURE NAME]
# Feature Specification: [FEATURE NAME]
**Feature Branch**: `[###-feature-name]`
**Created**: [DATE]
**Status**: Draft
**Category**: [100-Infrastructures | 200-fullstacks | 300-others]
**Input**: User description: "$ARGUMENTS"
## User Scenarios & Testing _(mandatory)_
+9 -9
View File
@@ -1,10 +1,10 @@
---
description: 'Task list template for feature implementation'
---
// File: specs/[100/200/300]-category/feature-name/tasks.md
// Change Log:
// - [DATE]: Initial task list for [FEATURE NAME]
# Tasks: [FEATURE NAME]
**Input**: Design documents from `/specs/[###-feature-name]/`
**Input**: Design documents from `/specs/[100/200/300]-category/feature-name/`
**Prerequisites**: plan.md (required), spec.md (required for user stories), research.md, data-model.md, contracts/
**Tests**: The examples below include test tasks. Tests are OPTIONAL - only include them if explicitly requested in the feature specification.
@@ -17,12 +17,12 @@ description: 'Task list template for feature implementation'
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions
## Path Conventions
## Path Conventions (v1.9.0)
- **Single project**: `src/`, `tests/` at repository root
- **Web app**: `backend/src/`, `frontend/src/`
- **Mobile**: `api/src/`, `ios/src/` or `android/src/`
- Paths shown below assume single project - adjust based on plan.md structure
- **Backend (NestJS)**: `backend/src/`
- **Frontend (Next.js)**: `frontend/src/`
- **Specs (Hybrid)**: `specs/[100/200/300]-category/`
- Paths shown below assume standard LCBP3 mono-repo structure.
<!--
============================================================================
+24 -1
View File
@@ -24,7 +24,9 @@ Every response must be **precise**, **spec-compliant**, and **production-ready**
## Project Information
- **Project:** NAP-DMS (LCBP3)
- **Version:** 1.8.6
- Version: 1.9.0
- Last Updated: 2026-05-13
- Canonical Source: AGENTS.md
- **Stack:** NestJS + Next.js + TypeScript + MariaDB + Ollama (AI)
- **Repo:** https://git.np-dms.work/np-dms/lcbp3
@@ -58,3 +60,24 @@ Best practice — follow when possible:
- Code style / formatting (Prettier handles)
- Comment completeness
- Minor optimizations
---
## 📐 TypeScript Rules & Coding Standards (v1.9.0)
### 📝 Core Standards
- **Strict Mode** — all strict checks enforced.
- **ZERO `any` types** — use proper types or `unknown` + narrowing.
- **ZERO `console.log`** — use NestJS `Logger` (backend) or remove before commit (frontend).
- **English for Code** — use English for all code identifiers, variables, and logic.
- **Thai for Comments** — use Thai for comments, documentation, and JSDoc.
- **Explicit Typing** — explicitly define types for all variables, parameters, and return values.
- **JSDoc** — use JSDoc for all public classes and methods.
### 🏗️ File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- **Change Log** — include `// Change Log` at the top of the file to track modifications.
- **Single Export** — export **only one main symbol** per file.
- **Function Style** — avoid unnecessary blank lines inside functions.
+27 -23
View File
@@ -1,32 +1,36 @@
---
trigger: always_on
---
# TypeScript Rules (v1.9.0)
# TypeScript Rules
## Core Standards
## Strict Requirements
- **Strict Mode** — all strict checks enforced.
- **ZERO `any` types** — use proper types or `unknown` + narrowing.
- **ZERO `console.log`** — use NestJS `Logger` (backend) or remove before commit (frontend).
- **English for Code** — use English for all code identifiers, variables, and logic.
- **Thai for Comments** — use Thai for comments, documentation, and JSDoc.
- **Explicit Typing** — explicitly define types for all variables, parameters, and return values.
- **JSDoc** — use JSDoc for all public classes and methods (in **Thai**).
- **Strict Mode** — all strict checks enforced
- **ZERO `any` types** — use proper types or `unknown` + narrowing
- **ZERO `console.log`** — NestJS `Logger` (backend); remove before commit (frontend)
## File & Function Structure
## Comment Language Policy
- **File Headers** — every file MUST start with `// File: path/filename` on the first line.
- **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.
- **Comments:** Thai (เข้าใจง่ายสำหรับทีมไทย)
- **Code Identifiers:** English (variables, functions, classes)
## Error Handling Pattern
## Patterns
```typescript
// Backend (NestJS)
import { Logger } from '@nestjs/common';
const logger = new Logger('ServiceName');
// ✅ CORRECT
// File: src/example.service.ts
// Change Log:
// - 2026-05-13: Initial creation
// Use logger instead of console.log
logger.error('Error message', error.stack);
throw new HttpException('Message', HttpStatus.BAD_REQUEST);
// Frontend (Next.js)
// Remove all console.log before commit
// Use proper error boundaries and toast notifications
/**
* บริการตัวอย่างสำหรับ LCBP3
*/
export class ExampleService {
public doSomething(data: string): boolean {
return data.length > 0;
}
}
```
+7 -3
View File
@@ -18,9 +18,13 @@ trigger: always_on
## 🟡 Normal Work — UI / Feature / Integration
- Follow existing patterns in codebase
- Check spec for relevant module only
- No need to read all specs
- Follow existing patterns in codebase.
- Check spec for relevant module only.
- **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/`
- Ensure no forbidden patterns (`any`, `console.log`, UUID misuse) are introduced.
## 🟢 Quick Fix — Bug Fix / Typo / Style
+109
View File
@@ -0,0 +1,109 @@
# `.agents/skills/` — LCBP3 Agent Skill Pack
**Version:** 1.8.9 | **Last Updated:** 2026-04-22 | **Total Skills:** 20
Agent skills for AI-assisted development in **Windsurf IDE** (and compatible agents: Codex CLI, opencode, Amp, Antigravity, AGENTS.md-aware tools).
---
## 📂 Layout
```
.agents/skills/
├── VERSION # Single source of truth for skill-pack version
├── skills.md # Overview + dependency matrix + health monitoring
├── _LCBP3-CONTEXT.md # Shared LCBP3 context injected into every speckit-* skill
├── README.md # (this file)
├── nestjs-best-practices/ # Backend rules (40 rules across 10 categories)
├── next-best-practices/ # Frontend rules (Next.js 15+)
└── 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
- `templates/` _(optional)_ — artifact templates (spec/plan/tasks/checklist)
- `rules/` _(nestjs only)_ — individual rule files grouped by prefix (`arch-`, `security-`, `db-`, etc.)
---
## 🚀 How Windsurf Invokes These Skills
Windsurf exposes two entry points:
1. **Skill tool** — Windsurf discovers skills by scanning `.agents/skills/*/SKILL.md` frontmatter. Skills marked `user-invocable: false` are used silently by Cascade.
2. **Slash commands**`.windsurf/workflows/*.md` wraps each skill as a slash command (e.g. `/04-speckit.plan`). The workflow file is short; the heavy lifting is delegated to the skill via `skill` tool.
Both paths end up executing the same `SKILL.md` instructions.
---
## 🧭 Typical Flow
```
/01-speckit.constitution → AGENTS.md / product vision
/02-speckit.specify → specs/feat-XXX/spec.md
/03-speckit.clarify → updates spec.md (up to 5 targeted questions)
/04-speckit.plan → specs/feat-XXX/plan.md + data-model.md + contracts/
/05-speckit.tasks → specs/feat-XXX/tasks.md
/06-speckit.analyze → cross-artifact consistency report (read-only)
/07-speckit.implement → executes tasks with Ironclad Protocols (Blast Radius + Strangler + TDD)
/08-speckit.checker → pnpm lint / typecheck / markdown-lint
/09-speckit.tester → pnpm test + coverage gates (Backend 70%+, Business Logic 80%+)
/10-speckit.reviewer → code review with Tier 1/2/3 classification
/11-speckit.validate → UAT / acceptance-criteria.md
```
Use `/00-speckit.all` to run specify → clarify → plan → tasks → analyze in one go.
---
## 🛠️ Helper Scripts
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 |
All scripts mirror to `.agents/scripts/powershell/*.ps1` for Windows.
---
## ⚠️ Tier 1 Non-Negotiables (auto-enforced)
- ADR-019 — `publicId` exposed directly; no `parseInt` / `Number` / `+` on UUID; no `id ?? ''` fallback
- ADR-009 — edit SQL schema directly, no TypeORM migrations
- ADR-016 — JWT + CASL on every mutation; `Idempotency-Key` required; ClamAV two-phase upload
- ADR-018 — AI via DMS API only (Ollama on Admin Desktop; no direct DB/storage)
- ADR-007 — layered error classification (Validation / Business / System)
- Zero `any`, zero `console.log` (use `Logger`)
See [`_LCBP3-CONTEXT.md`](./_LCBP3-CONTEXT.md) for the complete list.
---
## 🤝 Extending
To add a new skill:
1. Create `NAME/SKILL.md` with frontmatter: `name`, `description`, `version: 1.8.9`, `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.
5. Run `./.agents/scripts/bash/audit-skills.sh` → must pass.
---
## 📚 References
- **Canonical rules:** `AGENTS.md` (repo root)
- **Product vision:** `specs/00-Overview/00-03-product-vision.md`
- **ADRs:** `specs/06-Decision-Records/`
- **Engineering guidelines:** `specs/05-Engineering-Guidelines/`
- **Contributing:** `CONTRIBUTING.md`
+1
View File
@@ -0,0 +1 @@
version: 1.9.0
+91
View File
@@ -0,0 +1,91 @@
# 🧭 LCBP3-DMS Context Appendix (Shared)
> This file is included/referenced by every Speckit skill as the authoritative project context.
> Skills **must** load it (or the files it links to) before generating any artifact.
**Project:** NAP-DMS (LCBP3) — Laem Chabang Port Phase 3 Document Management System
**Stack:** NestJS 11 + Next.js 16 + TypeScript + MariaDB 11.8 + Redis + BullMQ + Elasticsearch + Ollama (on-prem AI)
**Version:** 1.8.9 (2026-04-18)
---
## 📌 Canonical Rule Sources (read in this order)
1. **`AGENTS.md`** (repo root) — primary rule file for AI agents; supersedes legacy `GEMINI.md`.
2. **`specs/06-Decision-Records/`** — architectural decisions (22 ADRs); ADR priority > Engineering Guidelines.
3. **`specs/05-Engineering-Guidelines/`** — backend/frontend/testing/i18n/git patterns.
4. **`specs/00-Overview/00-02-glossary.md`** — domain terminology (Correspondence / RFA / Transmittal / Circulation).
5. **`specs/00-Overview/00-03-product-vision.md`** — project constitution (Vision, Strategic Pillars, Guardrails).
6. **`CONTRIBUTING.md`** — spec writing standards, PR template, review levels.
7. **`README.md`** — technology stack + getting started.
---
## 🔴 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-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.
- **ADR-018 AI Boundary:** Ollama on Admin Desktop only; AI → DMS API → DB (never direct DB/storage). Human-in-the-loop validation required.
- **ADR-007 Error Handling:** Layered (Validation / Business / System); `BusinessException` hierarchy; user-friendly `userMessage` + `recoveryAction`; technical stack only in logs.
- **TypeScript Strict:** Zero `any`, zero `console.log` (use NestJS `Logger`).
- **i18n:** No hardcoded Thai/English strings in components — use i18n keys (see `05-08-i18n-guidelines.md`).
- **File Upload:** Two-phase (Temp → ClamAV → Permanent), whitelist `PDF/DWG/DOCX/XLSX/ZIP`, max 50MB, `StorageService` only.
---
## 🏷️ Domain Glossary (reject generic terms)
| ✅ Use | ❌ Don't Use |
| --- | --- |
| Correspondence | Letter, Communication, Document |
| RFA | Approval Request, Submit for Approval |
| Transmittal | Delivery Note, Cover Letter |
| Circulation | Distribution, Routing |
| Shop Drawing | Construction Drawing |
| Contract Drawing | Design Drawing, Blueprint |
| Workflow Engine | Approval Flow, Process Engine |
| Document Numbering | Document ID, Auto Number |
---
## 📁 Key Files for Generating / Validating Artifacts
| When you need... | Read |
| --- | --- |
| A new feature spec | `.agents/skills/speckit-specify/templates/spec-template.md` + `specs/01-Requirements/01-06-edge-cases-and-rules.md` |
| 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` |
| 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` |
---
## 🛠️ Helper Scripts (real paths in this repo)
- `./.agents/scripts/bash/check-prerequisites.sh` / `powershell/*.ps1`
- `./.agents/scripts/bash/setup-plan.sh`
- `./.agents/scripts/bash/update-agent-context.sh windsurf`
- `./.agents/scripts/bash/audit-skills.sh`
- `./.agents/scripts/bash/validate-versions.sh`
- `./.agents/scripts/bash/sync-workflows.sh`
---
## ✅ Commit Checklist (applied automatically by speckit-implement)
- [ ] UUID pattern verified (no `parseInt` / `Number` / `+` on UUID, no `id ?? ''` fallback)
- [ ] No `any`, no `console.log` in committed code
- [ ] Business comments in Thai, code identifiers in English
- [ ] Schema changes via SQL directly (not migration)
- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+)
- [ ] Relevant ADRs referenced (007/008/009/016/018/019/020/021)
- [ ] Domain glossary terms used correctly
- [ ] Error handling: `Logger` + `HttpException` / `BusinessException`
- [ ] i18n keys used (no hardcode text)
- [ ] Cache invalidation when data mutated
- [ ] OWASP Top 10 review passed
+43
View File
@@ -0,0 +1,43 @@
// File: .agents/skills/bugfix/SKILL.md
// Change Log: 2026-05-13 - Initial version improved from docs/bugfix.md
---
name: bugfix
description: Quick bugfix workflow with minimal impact. Focused on surgical fixes without unrelated refactoring.
version: 1.0.0
---
# Bugfix
ใช้สำหรับแก้ไข Bug ที่ระบุสาเหตุได้ชัดเจน โดยเน้นที่การแก้ไขที่ตรงจุด (Surgical Fix) และมีผลกระทบน้อยที่สุด (Minimal Impact)
## Phase 1 — Analysis (การวิเคราะห์)
1. **Read Logs & Context**: อ่าน Error Logs หรือรายละเอียดที่ User แจ้งมาให้ครบถ้วน
2. **Identify Root Cause**: ค้นหาสาเหตุที่แท้จริง (Root Cause) ไม่ใช่แค่การแก้ที่ปลายเหตุ
3. **Check Error Catalog**: ตรวจสอบ `docs/error-catalog.md` เพื่อดูว่ามี Error Code หรือ Pattern ที่เกี่ยวข้องหรือไม่
4. **Locate Code**: ระบุไฟล์และบรรทัดที่เกิดปัญหาให้ชัดเจน
## Phase 2 — Planning (การวางแผน)
1. **Create Fix Plan**: ร่างแผนการแก้ไขที่เน้น **Minimal Change**
- ห้าม Refactor โค้ดที่ไม่เกี่ยวข้อง
- หลีกเลี่ยงการเปลี่ยนแปลงที่จะส่งผลกระทบต่อส่วนอื่น (No Side Effects)
2. **Verify Standards**: ตรวจสอบว่าแผนการแก้ไขไม่ขัดกับ Tier 1 (Security, UUID, DB) และ Tier 2 (Architecture) ใน `AGENTS.md`
3. **Save to fix.md**: (Optional) บันทึกรายละเอียดการแก้ไขลงในไฟล์ `fix.md` เพื่อใช้ตรวจสอบก่อนลงมือจริง
## Phase 3 — Execution (การดำเนินการ)
1. **Apply Fix**: ลงมือแก้ไขโค้ดตามแผน
2. **Verify Fix**:
- จำลองสถานการณ์เพื่อยืนยันว่า Bug หายไปจริง
- ตรวจสอบว่าไม่มี Forbidden Patterns (`any`, `console.log`, UUID misuse)
3. **Regression Check**: ตรวจสอบส่วนที่เกี่ยวข้องว่ายังทำงานได้ปกติ
## Phase 4 — Finalization (การสรุปผล)
1. **Report**: สรุปผลการแก้ไขให้ User ทราบ
- Root cause (สาเหตุ)
- Fix detail (รายละเอียดการแก้)
- Affected files (ไฟล์ที่เกี่ยวข้อง)
2. **Cleanup**: ลบไฟล์ `fix.md` หรือ Debug logs ที่สร้างขึ้น
+1
View File
@@ -1,6 +1,7 @@
---
name: diagnose
description: Disciplined diagnosis loop for hard bugs and performance regressions. Reproduce → minimise → hypothesise → instrument → fix → regression-test. Use when user says "diagnose this" / "debug this", reports a bug, says something is broken/throwing/failing, or describes a performance regression.
version: 1.9.0
---
# Diagnose
@@ -1,6 +1,7 @@
---
name: grill-with-docs
description: Grilling session that challenges your plan against the existing domain model, sharpens terminology, and updates documentation (CONTEXT.md, ADRs) inline as decisions crystallise. Use when user wants to stress-test a plan against their project's language and documented decisions.
version: 1.9.0
---
<what-to-do>
@@ -1,37 +0,0 @@
# Deepening
How to deepen a cluster of shallow modules safely, given its dependencies. Assumes the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**.
## Dependency categories
When assessing a candidate for deepening, classify its dependencies. The category determines how the deepened module is tested across its seam.
### 1. In-process
Pure computation, in-memory state, no I/O. Always deepenable — merge the modules and test through the new interface directly. No adapter needed.
### 2. Local-substitutable
Dependencies that have local test stand-ins (PGLite for Postgres, in-memory filesystem). Deepenable if the stand-in exists. The deepened module is tested with the stand-in running in the test suite. The seam is internal; no port at the module's external interface.
### 3. Remote but owned (Ports & Adapters)
Your own services across a network boundary (microservices, internal APIs). Define a **port** (interface) at the seam. The deep module owns the logic; the transport is injected as an **adapter**. Tests use an in-memory adapter. Production uses an HTTP/gRPC/queue adapter.
Recommendation shape: *"Define a port at the seam, implement an HTTP adapter for production and an in-memory adapter for testing, so the logic sits in one deep module even though it's deployed across a network."*
### 4. True external (Mock)
Third-party services (Stripe, Twilio, etc.) you don't control. The deepened module takes the external dependency as an injected port; tests provide a mock adapter.
## Seam discipline
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a port unless at least two adapters are justified (typically production + test). A single-adapter seam is just indirection.
- **Internal seams vs external seams.** A deep module can have internal seams (private to its implementation, used by its own tests) as well as the external seam at its interface. Don't expose internal seams through the interface just because tests use them.
## Testing strategy: replace, don't layer
- Old unit tests on shallow modules become waste once tests at the deepened module's interface exist — delete them.
- Write new tests at the deepened module's interface. The **interface is the test surface**.
- Tests assert on observable outcomes through the interface, not internal state.
- Tests should survive internal refactors — they describe behaviour, not implementation. If a test has to change when the implementation changes, it's testing past the interface.
@@ -1,44 +0,0 @@
# Interface Design
When the user wants to explore alternative interfaces for a chosen deepening candidate, use this parallel sub-agent pattern. Based on "Design It Twice" (Ousterhout) — your first idea is unlikely to be the best.
Uses the vocabulary in [LANGUAGE.md](LANGUAGE.md) — **module**, **interface**, **seam**, **adapter**, **leverage**.
## Process
### 1. Frame the problem space
Before spawning sub-agents, write a user-facing explanation of the problem space for the chosen candidate:
- The constraints any new interface would need to satisfy
- The dependencies it would rely on, and which category they fall into (see [DEEPENING.md](DEEPENING.md))
- A rough illustrative code sketch to ground the constraints — not a proposal, just a way to make the constraints concrete
Show this to the user, then immediately proceed to Step 2. The user reads and thinks while the sub-agents work in parallel.
### 2. Spawn sub-agents
Spawn 3+ sub-agents in parallel using the Agent tool. Each must produce a **radically different** interface for the deepened module.
Prompt each sub-agent with a separate technical brief (file paths, coupling details, dependency category from [DEEPENING.md](DEEPENING.md), what sits behind the seam). The brief is independent of the user-facing problem-space explanation in Step 1. Give each agent a different design constraint:
- Agent 1: "Minimize the interface — aim for 13 entry points max. Maximise leverage per entry point."
- Agent 2: "Maximise flexibility — support many use cases and extension."
- Agent 3: "Optimise for the most common caller — make the default case trivial."
- Agent 4 (if applicable): "Design around ports & adapters for cross-seam dependencies."
Include both [LANGUAGE.md](LANGUAGE.md) vocabulary and CONTEXT.md vocabulary in the brief so each sub-agent names things consistently with the architecture language and the project's domain language.
Each sub-agent outputs:
1. Interface (types, methods, params — plus invariants, ordering, error modes)
2. Usage example showing how callers use it
3. What the implementation hides behind the seam
4. Dependency strategy and adapters (see [DEEPENING.md](DEEPENING.md))
5. Trade-offs — where leverage is high, where it's thin
### 3. Present and compare
Present designs sequentially so the user can absorb each one, then compare them in prose. Contrast by **depth** (leverage at the interface), **locality** (where change concentrates), and **seam placement**.
After comparing, give your own recommendation: which design you think is strongest and why. If elements from different designs would combine well, propose a hybrid. Be opinionated — the user wants a strong read, not a menu.
@@ -1,53 +0,0 @@
# Language
Shared vocabulary for every suggestion this skill makes. Use these terms exactly — don't substitute "component," "service," "API," or "boundary." Consistent language is the whole point.
## Terms
**Module**
Anything with an interface and an implementation. Deliberately scale-agnostic — applies equally to a function, class, package, or tier-spanning slice.
_Avoid_: unit, component, service.
**Interface**
Everything a caller must know to use the module correctly. Includes the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics.
_Avoid_: API, signature (too narrow — those refer only to the type-level surface).
**Implementation**
What's inside a module — its body of code. Distinct from **Adapter**: a thing can be a small adapter with a large implementation (a Postgres repo) or a large adapter with a small implementation (an in-memory fake). Reach for "adapter" when the seam is the topic; "implementation" otherwise.
**Depth**
Leverage at the interface — the amount of behaviour a caller (or test) can exercise per unit of interface they have to learn. A module is **deep** when a large amount of behaviour sits behind a small interface. A module is **shallow** when the interface is nearly as complex as the implementation.
**Seam** _(from Michael Feathers)_
A place where you can alter behaviour without editing in that place. The *location* at which a module's interface lives. Choosing where to put the seam is its own design decision, distinct from what goes behind it.
_Avoid_: boundary (overloaded with DDD's bounded context).
**Adapter**
A concrete thing that satisfies an interface at a seam. Describes *role* (what slot it fills), not substance (what's inside).
**Leverage**
What callers get from depth. More capability per unit of interface they have to learn. One implementation pays back across N call sites and M tests.
**Locality**
What maintainers get from depth. Change, bugs, knowledge, and verification concentrate at one place rather than spreading across callers. Fix once, fixed everywhere.
## Principles
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable, swappable parts — they just aren't part of the interface. A module can have **internal seams** (private to its implementation, used by its own tests) as well as the **external seam** at its interface.
- **The deletion test.** Imagine deleting the module. If complexity vanishes, the module wasn't hiding anything (it was a pass-through). If complexity reappears across N callers, the module was earning its keep.
- **The interface is the test surface.** Callers and tests cross the same seam. If you want to test *past* the interface, the module is probably the wrong shape.
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it.
## Relationships
- A **Module** has exactly one **Interface** (the surface it presents to callers and tests).
- **Depth** is a property of a **Module**, measured against its **Interface**.
- A **Seam** is where a **Module**'s **Interface** lives.
- An **Adapter** sits at a **Seam** and satisfies the **Interface**.
- **Depth** produces **Leverage** for callers and **Locality** for maintainers.
## Rejected framings
- **Depth as ratio of implementation-lines to interface-lines** (Ousterhout): rewards padding the implementation. We use depth-as-leverage instead.
- **"Interface" as the TypeScript `interface` keyword or a class's public methods**: too narrow — interface here includes every fact a caller must know.
- **"Boundary"**: overloaded with DDD's bounded context. Say **seam** or **interface**.
@@ -1,71 +0,0 @@
---
name: improve-codebase-architecture
description: Find deepening opportunities in a codebase, informed by the domain language in CONTEXT.md and the decisions in docs/adr/. Use when the user wants to improve architecture, find refactoring opportunities, consolidate tightly-coupled modules, or make a codebase more testable and AI-navigable.
---
# Improve Codebase Architecture
Surface architectural friction and propose **deepening opportunities** — refactors that turn shallow modules into deep ones. The aim is testability and AI-navigability.
## Glossary
Use these terms exactly in every suggestion. Consistent language is the point — don't drift into "component," "service," "API," or "boundary." Full definitions in [LANGUAGE.md](LANGUAGE.md).
- **Module** — anything with an interface and an implementation (function, class, package, slice).
- **Interface** — everything a caller must know to use the module: types, invariants, error modes, ordering, config. Not just the type signature.
- **Implementation** — the code inside.
- **Depth** — leverage at the interface: a lot of behaviour behind a small interface. **Deep** = high leverage. **Shallow** = interface nearly as complex as the implementation.
- **Seam** — where an interface lives; a place behaviour can be altered without editing in place. (Use this, not "boundary.")
- **Adapter** — a concrete thing satisfying an interface at a seam.
- **Leverage** — what callers get from depth.
- **Locality** — what maintainers get from depth: change, bugs, knowledge concentrated in one place.
Key principles (see [LANGUAGE.md](LANGUAGE.md) for the full list):
- **Deletion test**: imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep.
- **The interface is the test surface.**
- **One adapter = hypothetical seam. Two adapters = real seam.**
This skill is _informed_ by the project's domain model. The domain language gives names to good seams; ADRs record decisions the skill should not re-litigate.
## Process
### 1. Explore
Read the project's domain glossary and any ADRs in the area you're touching first.
Then use the Agent tool with `subagent_type=Explore` to walk the codebase. Don't follow rigid heuristics — explore organically and note where you experience friction:
- Where does understanding one concept require bouncing between many small modules?
- Where are modules **shallow** — interface nearly as complex as the implementation?
- Where have pure functions been extracted just for testability, but the real bugs hide in how they're called (no **locality**)?
- Where do tightly-coupled modules leak across their seams?
- Which parts of the codebase are untested, or hard to test through their current interface?
Apply the **deletion test** to anything you suspect is shallow: would deleting it concentrate complexity, or just move it? A "yes, concentrates" is the signal you want.
### 2. Present candidates
Present a numbered list of deepening opportunities. For each candidate:
- **Files** — which files/modules are involved
- **Problem** — why the current architecture is causing friction
- **Solution** — plain English description of what would change
- **Benefits** — explained in terms of locality and leverage, and also in how tests would improve
**Use CONTEXT.md vocabulary for the domain, and [LANGUAGE.md](LANGUAGE.md) vocabulary for the architecture.** If `CONTEXT.md` defines "Order," talk about "the Order intake module" — not "the FooBarHandler," and not "the Order service."
**ADR conflicts**: if a candidate contradicts an existing ADR, only surface it when the friction is real enough to warrant revisiting the ADR. Mark it clearly (e.g. _"contradicts ADR-0007 — but worth reopening because…"_). Don't list every theoretical refactor an ADR forbids.
Do NOT propose interfaces yet. Ask the user: "Which of these would you like to explore?"
### 3. Grilling loop
Once the user picks a candidate, drop into a grilling conversation. Walk the design tree with them — constraints, dependencies, the shape of the deepened module, what sits behind the seam, what tests survive.
Side effects happen inline as decisions crystallize:
- **Naming a deepened module after a concept not in `CONTEXT.md`?** Add the term to `CONTEXT.md` — same discipline as `/grill-with-docs` (see [CONTEXT-FORMAT.md](../grill-with-docs/CONTEXT-FORMAT.md)). Create the file lazily if it doesn't exist.
- **Sharpening a fuzzy term during the conversation?** Update `CONTEXT.md` right there.
- **User rejects the candidate with a load-bearing reason?** Offer an ADR, framed as: _"Want me to record this as an ADR so future architecture reviews don't re-suggest it?"_ Only offer when the reason would actually be needed by a future explorer to avoid re-suggesting the same thing — skip ephemeral reasons ("not worth it right now") and self-evident ones. See [ADR-FORMAT.md](../grill-with-docs/ADR-FORMAT.md).
- **Want to explore alternative interfaces for the deepened module?** See [INTERFACE-DESIGN.md](INTERFACE-DESIGN.md).
@@ -0,0 +1,24 @@
name: Branch Protection
on:
pull_request:
branches: [main]
jobs:
check-branch:
runs-on: ubuntu-latest
steps:
- name: Block docs branch merge to main
if: github.head_ref == 'docs'
run: |
echo "::error::Merging 'docs' branch into 'main' is not allowed."
echo ""
echo "The 'docs' branch contains the documentation website which should"
echo "remain separate from the main skill files to keep installations lightweight."
echo ""
echo "If you need to sync changes, cherry-pick specific commits instead."
exit 1
- name: Branch check passed
if: github.head_ref != 'docs'
run: echo "Branch check passed - not merging from docs branch"
@@ -0,0 +1,61 @@
name: Deploy to GitHub Pages
on:
push:
branches: [docs]
paths:
- 'website/**'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: website/package-lock.json
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Install dependencies
run: npm ci
working-directory: website
- name: Build
run: npm run build
working-directory: website
- name: Copy index.html to 404.html for SPA routing
run: cp website/dist/index.html website/dist/404.html
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: website/dist
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
@@ -0,0 +1,29 @@
# Dependencies
node_modules/
# Website (lives on docs branch)
website/
# Build outputs
dist/
*.js
*.d.ts
*.js.map
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Logs
*.log
npm-debug.log*
# Environment
.env
.env.local
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More