agent-workflow-kit-cli 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/cli/commands/add.js +3 -1
  2. package/dist/cli/commands/doctor.js +145 -47
  3. package/dist/cli/commands/init.js +6 -0
  4. package/dist/core/analyzer.js +70 -0
  5. package/dist/core/detector.js +22 -0
  6. package/package.json +1 -1
  7. package/templates/common/AGENTS.md.hbs +4 -0
  8. package/templates/common/GLOBAL_RULES.md +101 -0
  9. package/templates/devops/AGENTS.md.hbs +32 -0
  10. package/templates/devops/skills/devops/SKILL.md +477 -0
  11. package/templates/diagram/AGENTS.md.hbs +30 -0
  12. package/templates/diagram/skills/drawio-diagram/SKILL.md +427 -0
  13. package/templates/dotnet/AGENTS.md.hbs +38 -34
  14. package/templates/dotnet/rules/api-structure.md +15 -15
  15. package/templates/dotnet/rules/csharp-style.md +17 -17
  16. package/templates/dotnet/rules/dependency-injection.md +12 -12
  17. package/templates/dotnet/rules/error-handling-validation.md +15 -15
  18. package/templates/dotnet/skills/dotnet-controller/SKILL.md +16 -16
  19. package/templates/express/AGENTS.md.hbs +37 -33
  20. package/templates/express/rules/error-handling.md +18 -18
  21. package/templates/express/rules/express-style.md +19 -19
  22. package/templates/express/rules/router-controller.md +16 -16
  23. package/templates/express/skills/express-endpoint/SKILL.md +14 -14
  24. package/templates/fastapi/AGENTS.md.hbs +25 -3
  25. package/templates/fastapi/rules/api-testing.md +24 -0
  26. package/templates/fastapi/rules/database-async.md +26 -0
  27. package/templates/golang/AGENTS.md.hbs +42 -0
  28. package/templates/golang/rules/concurrency.md +71 -0
  29. package/templates/golang/rules/error-handling.md +42 -0
  30. package/templates/golang/rules/golang-style.md +24 -0
  31. package/templates/golang/rules/project-layout.md +39 -0
  32. package/templates/golang/skills/golang-db/SKILL.md +27 -0
  33. package/templates/golang/skills/golang-feature/SKILL.md +42 -0
  34. package/templates/nestjs/AGENTS.md.hbs +33 -29
  35. package/templates/nestjs/rules/module-architecture.md +14 -14
  36. package/templates/nestjs/rules/nestjs-style.md +12 -12
  37. package/templates/nestjs/rules/validation-errors.md +15 -15
  38. package/templates/nestjs/skills/nestjs-module/SKILL.md +15 -15
  39. package/templates/next-js/AGENTS.md.hbs +39 -35
  40. package/templates/next-js/rules/data-fetching-mutations.md +17 -17
  41. package/templates/next-js/rules/next-style.md +17 -17
  42. package/templates/next-js/rules/seo-metadata.md +18 -18
  43. package/templates/next-js/rules/server-client-components.md +17 -17
  44. package/templates/next-js/skills/next-feature/SKILL.md +16 -16
  45. package/templates/rust/AGENTS.md.hbs +41 -0
  46. package/templates/rust/rules/error-handling.md +36 -0
  47. package/templates/rust/rules/memory-concurrency.md +47 -0
  48. package/templates/rust/rules/project-layout.md +49 -0
  49. package/templates/rust/rules/rust-style.md +26 -0
  50. package/templates/rust/skills/rust-db/SKILL.md +27 -0
  51. package/templates/rust/skills/rust-feature/SKILL.md +34 -0
@@ -1,11 +1,19 @@
1
1
  ## 🐍 Python FastAPI Guidelines
2
2
 
3
+ ### 🔄 End-to-End Agent Development Lifecycle
4
+ AI Agents must execute all Python FastAPI tasks following this structured 5-stage lifecycle:
5
+ 1. **Design & Code:** Implement layers following the structure guidelines below. Keep routes thin and business logic inside Services/CRUD.
6
+ 2. **Comprehensive Testing:** Write API test cases using pytest and `httpx.AsyncClient`. Mock all external dependencies. Review the testing guidelines in `@api-testing.md`.
7
+ 3. **Troubleshooting & Debugging:** When debugging database or connection errors, follow async context managers and mock session structures.
8
+ 4. **Code Quality & Review:** Perform self-review using `@python-style.md` to check type hinting, Pydantic validations, and parameter annotations.
9
+ 5. **Database Integrity:** Ensure all structural changes have matching Alembic migrations. Conform to async session guidelines in `@database-async.md`.
10
+
3
11
  ### 🏗️ Architecture & Router-Service-Repository Conventions
4
- Follow a clean layering architecture. Separate HTTP routing, business logic, and database operations:
12
+ Follow a feature-first or modular layered architecture. Separate HTTP routing, business logic, and database operations:
5
13
 
6
14
  ```text
7
15
  app/
8
- core/ # Config, database setup
16
+ core/ # Config, database setup, exceptions
9
17
  models/ # SQLAlchemy or SQLModel entities
10
18
  schemas/ # Pydantic validation models
11
19
  crud/ # Database repositories/CRUD operations
@@ -16,10 +24,24 @@ app/
16
24
  ```
17
25
 
18
26
  ### ⚙️ Coding Guidelines
19
- - **Dependency Injection:** Use FastAPI's `Depends` explicitly for injecting database sessions, security credentials, and custom services.
27
+ - **Dependency Injection:** Use FastAPI's `Depends` explicitly for injecting database sessions, security credentials, and custom services. Avoid manual imports of DB connections.
20
28
  - **Strict Typing:** Always annotate function arguments and return types. Use Pydantic's `response_model` or type hints to enforce validation.
21
29
  - **Asynchronous Handlers:** Prefer `async def` for I/O bound endpoints.
22
30
 
31
+ ### 🏛️ Strict Development Rules
32
+
33
+ #### 1. Input/Output Validation with Pydantic
34
+ - Validate all incoming request payloads using Pydantic models.
35
+ - Design distinct schemas for read, create, and update actions (e.g. `UserRead`, `UserCreate`, `UserUpdate`) to prevent exposing sensitive fields or auto-incrementing ID fields.
36
+
37
+ #### 2. Async Database Session Lifecycle
38
+ - Always use `AsyncSession` from `sqlalchemy.ext.asyncio` for operations.
39
+ - Bind the database session lifetime using dependency yield. Review the rules in `@database-async.md`.
40
+
41
+ #### 3. Error Handling
42
+ - Never throw raw python exceptions directly from routers.
43
+ - Map business logic errors (e.g., entity not found, duplicate emails) to FastAPI's built-in `HTTPException` class with specific status codes (e.g., `404 Not Found`, `400 Bad Request`).
44
+
23
45
  ### 🧪 Testing & Verification
24
46
  Before completing a task, run the following verification pipeline locally:
25
47
  ```bash
@@ -0,0 +1,24 @@
1
+ # API Testing Rules (FastAPI & Pytest)
2
+
3
+ Testing guidelines for endpoints, services, and mocks:
4
+
5
+ ## Test Setup and Client
6
+ - Use `pytest` for running test suites.
7
+ - Use `httpx.AsyncClient` or `FastAPI.testclient.TestClient` for HTTP testing. If endpoints are asynchronous (`async def`), prefer `httpx.AsyncClient` with `pytest-asyncio` markers:
8
+ ```python
9
+ @pytest.mark.asyncio
10
+ async def test_read_items(client: AsyncClient):
11
+ response = await client.get("/items/")
12
+ assert response.status_code == 200
13
+ ```
14
+
15
+ ## Fixtures and DB Mocking
16
+ - **Database isolation:** Create a clean database session for each test run. Do not use the production database; use an in-memory SQLite (`sqlite+aiosqlite:///:memory:`) or a dedicated PostgreSQL test container/database.
17
+ - **Fixture overrides:** Override the `get_db` dependency in the app:
18
+ ```python
19
+ app.dependency_overrides[get_db] = override_get_db
20
+ ```
21
+
22
+ ## Mocking External Dependencies
23
+ - Use `pytest-mock` (via the `mocker` fixture) to intercept external HTTP calls (such as third-party APIs or email dispatch services).
24
+ - Never make actual outbound network calls during tests.
@@ -0,0 +1,26 @@
1
+ # Async Database Rules (FastAPI & SQLAlchemy)
2
+
3
+ Guidelines for database access, connection pooling, and async operations:
4
+
5
+ ## Async Sessions and Depends
6
+ - **Async Database Connection:** Always use `AsyncSession` from `sqlalchemy.ext.asyncio`.
7
+ - **Session Lifecycle:** Inject the database session using `Depends(get_db)`. Ensure the dependency closes the session cleanly using a context manager or yield:
8
+ ```python
9
+ async def get_db() -> AsyncIterator[AsyncSession]:
10
+ async with AsyncSessionLocal() as session:
11
+ yield session
12
+ ```
13
+
14
+ ## Querying and Transactions
15
+ - **Async Queries:** Never use synchronous execution APIs. Always execute queries asynchronously using `session.execute(select(...))` or similar.
16
+ - **Explicit Transactions:** Use `async with session.begin():` blocks for operations modifying multiple entities to ensure atomic commits and rollbacks.
17
+ - **Relationship Loading:** Avoid implicit lazy loading since it raises errors in async contexts. Explicitly specify loading strategies like `selectinload` or `joinedload`:
18
+ ```python
19
+ stmt = select(User).options(selectinload(User.items))
20
+ ```
21
+
22
+ ## Migrations (Alembic)
23
+ - Every schema change must have a corresponding Alembic migration.
24
+ - Auto-generate migrations using:
25
+ `alembic revision --autogenerate -m "description"`
26
+ - Always inspect the generated migration script for accuracy before applying.
@@ -0,0 +1,42 @@
1
+ ## 🗺️ Golang Development Guide (Go Backend)
2
+
3
+ ### 🔄 Agent Development Lifecycle
4
+ The AI Agent must execute all Golang tasks following this structured 5-stage lifecycle:
5
+ 1. **Design & Code:** Implement business logic adhering to the Standard Go Project Layout. Keep entrypoints in `cmd/`, core business logic in `internal/`, and standalone shared libraries in `pkg/`.
6
+ 2. **Comprehensive Testing:** Write unit tests using the table-driven testing pattern and Go's built-in `testing` library. Mock database layers or third-party connections.
7
+ 3. **Troubleshooting & Debugging:** When debugging goroutines or database locks, use context cancellation and trace log output.
8
+ 4. **Code Quality & Review:** Verify code quality against `@golang-style.md` to check interface boundaries, error wrapping, and naming.
9
+ 5. **Acyclic Design:** Ensure there are no circular imports. Encapsulate domain packages cleanly under `@project-layout.md` and manage concurrent access via `@concurrency.md`.
10
+
11
+ ---
12
+
13
+ ### 🏗️ Template Blueprint
14
+ Refer to the detailed rules below:
15
+ - Go coding style, interface design, and naming conventions: `@golang-style.md`
16
+ - Directory organization and manual dependency injection: `@project-layout.md`
17
+ - Explicit error handling, wrapping, and custom API errors: `@error-handling.md`
18
+ - Concurrency, goroutine/channel lifecycle, and escape analysis: `@concurrency.md`
19
+ - Scaffolding a business feature (Handler, Service interface, tests): `@golang-feature`
20
+ - Scaffolding repository database operations and models: `@golang-db`
21
+
22
+ ---
23
+
24
+ ### 🏛️ Strict Development Rules
25
+
26
+ #### 1. Package Boundaries & Encapsulation
27
+ - **No Circular Dependencies:** Design packages around domains/components rather than tech layers (e.g., separate folders for `course`, `billing` instead of `controllers`, `models`) to avoid circular imports.
28
+ - **Internal Directory:** Keep 100% of core application logic inside `/internal` to enforce encapsulation and leverage Go compiler protections.
29
+
30
+ #### 2. Explicit Error Handling
31
+ - **Check Every Error:** Never ignore returned errors. Write `if err != nil` checks immediately after calling fallible functions.
32
+ - **Wrap Errors:** Use `fmt.Errorf("failed to...: %w", err)` when propagating errors to preserve runtime context. Review details in `@error-handling.md`.
33
+
34
+ #### 3. Safe Concurrency
35
+ - **Context Propagation:** Pass `ctx context.Context` as the first argument to all functions executing I/O.
36
+ - **Prevent Race Conditions:** Protect shared memory access across goroutines using `sync.Mutex` or `sync/atomic`.
37
+
38
+ ### 🧪 Verification & Testing
39
+ Before completing a task, run the following verification pipeline locally:
40
+ - **Build Validation:** `go build ./...`
41
+ - **Testing:** `go test ./...`
42
+ - **Formatting:** `gofmt -w .`
@@ -0,0 +1,71 @@
1
+ # Golang Concurrency & Memory Allocation
2
+
3
+ This document outlines standard guidelines for goroutines, context propagation, race conditions, and heap allocation optimizations.
4
+
5
+ ---
6
+
7
+ ## 🧠 Escape Analysis & Allocations
8
+ The Go compiler determines if a variable should live on the Stack (fast, auto-allocated/deallocated) or Heap (garbage-collected).
9
+ - **Pointer Rule (*):** Return pointers only for large structs where value copying is expensive, or when you must modify the receiver's state directly.
10
+ - **Value Types for Small Structs:** For small configuration values or short-lived structs (under 64-128 bytes), return value types to keep allocations on the Stack.
11
+ ```go
12
+ // ❌ Forces heap allocation (Bad)
13
+ func NewConfig() *Config {
14
+ return &Config{Timeout: 30}
15
+ }
16
+
17
+ // ✔️ Keeps allocation on the Stack (Good)
18
+ func NewConfig() Config {
19
+ return Config{Timeout: 30}
20
+ }
21
+ ```
22
+ - **sync.Pool Usage:** For high-frequency, repetitive operations like JSON encoding/decoding or byte buffer allocation (`[]byte`), use `sync.Pool` to reuse memory, minimizing GC pressure.
23
+ ```go
24
+ var bufferPool = sync.Pool{
25
+ New: func() any {
26
+ return make([]byte, 1024)
27
+ },
28
+ }
29
+ ```
30
+
31
+ ---
32
+
33
+ ## 🚦 Prevent Goroutine Leaks
34
+ - **Rule:** When writing data to a channel inside an independent goroutine, ensure the channel has a buffer or is monitored with timeouts/contexts to prevent permanent blocking.
35
+ ```go
36
+ // ❌ Leaks goroutine if no reader reads from ch (Bad)
37
+ func FetchData() string {
38
+ ch := make(chan string) // Unbuffered channel
39
+ go func() {
40
+ ch <- doHeavyWork() // Blocks indefinitely if parent exits early
41
+ }()
42
+ return <-ch
43
+ }
44
+
45
+ // ✔️ Safe with Buffer and Context (Good)
46
+ func FetchData(ctx context.Context) (string, error) {
47
+ ch := make(chan string, 1) // Buffered channel avoids blocking
48
+ go func() {
49
+ ch <- doHeavyWork()
50
+ }()
51
+
52
+ select {
53
+ case res := <-ch:
54
+ return res, nil
55
+ case <-ctx.Done():
56
+ return "", ctx.Err() // Exits safely on timeout/cancel
57
+ }
58
+ }
59
+ ```
60
+
61
+ ---
62
+
63
+ ## 🧭 Context Propagation
64
+ - Pass `ctx context.Context` as the first argument to any functions handling network or filesystem operations.
65
+ - Never store Context inside a struct; pass it explicitly down the call chain.
66
+
67
+ ---
68
+
69
+ ## ⚡ Prevent Race Conditions
70
+ Protect shared variables accessed concurrently across multiple goroutines using `sync.Mutex`, `sync.RWMutex`, or `sync/atomic`.
71
+ - Run race detection during testing: `go test -race ./...`.
@@ -0,0 +1,42 @@
1
+ # Golang Error Handling Standards
2
+
3
+ This document defines strict guidelines for error checking, error wrapping, and structuring standard API errors.
4
+
5
+ ---
6
+
7
+ ## 🔄 Error Wrapping
8
+ - **Rule:** When passing errors up the stack (e.g., from Repository to UseCase), never return the raw error or create a new error that discards the trace.
9
+ - **Solution:** Use `%w` in `fmt.Errorf` to wrap the underlying error with contextual information:
10
+ ```go
11
+ if err != nil {
12
+ return fmt.Errorf("failed to fetch user from db (id: %d): %w", id, err)
13
+ }
14
+ ```
15
+ - **Checking Errors:** Use `errors.Is()` for comparing sentinel errors and `errors.As()` to extract custom error structures:
16
+ ```go
17
+ if errors.Is(err, sql.ErrNoRows) {
18
+ // Handle record not found
19
+ }
20
+ ```
21
+
22
+ ---
23
+
24
+ ## 🏛️ Standard Custom Errors
25
+ To return uniform error responses to Frontend clients or API Gateways, define a standard struct:
26
+ ```go
27
+ type AppError struct {
28
+ Code string `json:"code"`
29
+ Message string `json:"message"`
30
+ Details map[string]string `json:"details,omitempty"`
31
+ }
32
+
33
+ func (e *AppError) Error() string {
34
+ return fmt.Sprintf("[%s] %s", e.Code, e.Message)
35
+ }
36
+ ```
37
+
38
+ ---
39
+
40
+ ## 🚫 Avoid Panics
41
+ - **Strict Rule:** Never use `panic` and `recover` for normal business flow control or expected failures.
42
+ - **Exception:** Only use `panic` during application startup if a fatal dependency fails (e.g., cannot connect to the primary database, or port is already in use).
@@ -0,0 +1,24 @@
1
+ # Golang Coding Style Rules
2
+
3
+ This document defines naming conventions, interface designs, and code style rules for Golang projects.
4
+
5
+ ---
6
+
7
+ ## 🏷️ Naming Conventions
8
+ - **Package Names:** Must be short, single-word, lowercase names (e.g., `user`, `config`, `db`, `auth`). Never use `camelCase`, `snake_case`, or hyphens.
9
+ - **Private Symbols (Variables & Functions):** Use `camelCase` (e.g., `userID`, `fetchData`).
10
+ - **Public Symbols (Exported):** Use `PascalCase` to export variables, functions, and structs (e.g., `UserID`, `FetchData`).
11
+ - **Acronyms:** Keep acronyms consistent in casing (e.g., `userID` instead of `userId`, `httpServer` instead of `httpServer`).
12
+
13
+ ---
14
+
15
+ ## 🔌 Interface Design
16
+ - **Rule:** *"Accept interfaces, return structs"*. This optimizes escape analysis and maintains clean API boundaries.
17
+ - **Minimality:** Design interfaces to be small, ideally declaring only 1 or 2 methods (e.g., `io.Reader`, `io.Writer`).
18
+ - **Naming:** End interface names with the `-er` suffix if they declare a single method (e.g., `Reader`, `Writer`, `Validator`).
19
+
20
+ ---
21
+
22
+ ## 🚫 Avoid Global Variables
23
+ - **No Global Mutable State:** Do not instantiate global variables for connections, logs, or caches.
24
+ - **Solution:** Pass dependencies explicitly through struct constructors (Dependency Injection) instead of accessing global instances.
@@ -0,0 +1,39 @@
1
+ # Golang Project Architecture & Layout
2
+
3
+ This document defines the Standard Go Project Layout and Clean Architecture conventions.
4
+
5
+ ---
6
+
7
+ ## 🏗️ Standard Directory Structure
8
+ Adhere to the following layout guidelines:
9
+ - **/cmd:** Contains only the entrypoints of the application (e.g., `cmd/api/main.go`). Code here must only parse configs, initialize the DI container, and start the server. Do not write business logic here.
10
+ - **/internal:** Contains all core application code. The Go compiler enforces that external packages cannot import code from this directory. Write 100% of business logic here.
11
+ - **/pkg:** Contains standalone utility libraries that can be shared with other projects (e.g., `pkg/logger`, `pkg/crypto`). Code in `/pkg` must never import packages from `/internal`.
12
+ - **/api:** Contains API contract definitions (OpenAPI/Swagger schemas, gRPC proto files).
13
+
14
+ ---
15
+
16
+ ## 🏛️ Clean Architecture Layers
17
+ Organize code inside `/internal/app` or `/internal/<domain>` into 3 distinct layers:
18
+ 1. **Entities (Domain Models):** Pure Go structs and core business rules. They must be free of external dependencies.
19
+ 2. **Use Cases (Services):** Coordinates business logic. Interacts only with interfaces representing external components.
20
+ 3. **Adapters (Controllers / Repositories):** Manages external communications (e.g., database operations using GORM, API routes using Fiber/Echo, gRPC handlers).
21
+
22
+ ---
23
+
24
+ ## 💉 Manual Dependency Injection (DI)
25
+ - **Constructor Injection:** Pass dependencies to structs (UseCases or Repositories) via `New[StructName]` constructors. Dependencies must be passed as interfaces.
26
+ - **Example:**
27
+ ```go
28
+ type UserRepository interface {
29
+ GetByID(ctx context.Context, id int64) (*domain.User, error)
30
+ }
31
+
32
+ type UserUseCase struct {
33
+ repo UserRepository // Access via interface
34
+ }
35
+
36
+ func NewUserUseCase(r UserRepository) *UserUseCase {
37
+ return &UserUseCase{repo: r}
38
+ }
39
+ ```
@@ -0,0 +1,27 @@
1
+ ---
2
+ name: golang-db
3
+ description: Scaffold a Go database repository layer using SQLx, GORM, or raw SQL queries
4
+ ---
5
+
6
+ Follow this process to add or extend database entities and repository queries.
7
+
8
+ Inputs:
9
+ - structName: Model entity struct name (e.g., `User`)
10
+ - tableName: Database table name (e.g., `users`)
11
+ - repositoryName: Interface name (e.g., `UserRepository`)
12
+
13
+ Steps:
14
+ 1. Declare the entity model struct with json and db (or gorm) tags:
15
+ ```go
16
+ type User struct {
17
+ ID int64 `json:"id" db:"id" gorm:"primaryKey"`
18
+ Email string `json:"email" db:"email"`
19
+ CreatedAt time.Time `json:"created_at" db:"created_at"`
20
+ }
21
+ ```
22
+ 2. Define the repository interface (e.g., `UserRepository`) containing standard SQL actions (`FindByID`, `Save`).
23
+ 3. Implement the interface concrete struct wrapping the database handle (e.g., `*sql.DB`, `*sqlx.DB`, or `*gorm.DB`).
24
+ 4. Wire the repository implementation to the service layer using constructor injection.
25
+ 5. Create SQL schema files under the `/migrations` or `/db` directories if schema changes are required.
26
+ 6. Verify code correctness using:
27
+ - `go build ./...`
@@ -0,0 +1,42 @@
1
+ ---
2
+ name: golang-feature
3
+ description: Scaffold a Go package slice including Handler, Service interfaces, and table-driven unit tests
4
+ ---
5
+
6
+ Follow this process to generate a new Go business feature slice.
7
+
8
+ Inputs:
9
+ - packageName: Name of the package (e.g., `billing`)
10
+ - structName: Primary model struct name (e.g., `Invoice`)
11
+ - functionality: Summary of the business requirements and API paths
12
+
13
+ Steps:
14
+ 1. Create a directory inside `internal/` named `<packageName>/` (e.g., `internal/billing`).
15
+ 2. Declare structs and interfaces in `<packageName>.go` or `types.go` (e.g., `BillingService` interface and `Invoice` struct).
16
+ 3. Implement the concrete service class (e.g., `service.go` containing `type service struct { ... }` implementing `BillingService`).
17
+ 4. Implement HTTP handlers in `handler.go` wrapping inputs/outputs via JSON bindings.
18
+ 5. Register routers/handlers in the application bootloader (e.g., in `cmd/server/main.go`).
19
+ 6. Write unit tests in `service_test.go` using table-driven tests:
20
+ ```go
21
+ func TestBillingService(t *testing.T) {
22
+ tests := []struct {
23
+ name string
24
+ input string
25
+ wantErr bool
26
+ }{
27
+ {
28
+ name: "Valid input case",
29
+ input: "valid",
30
+ wantErr: false,
31
+ },
32
+ }
33
+ for _, tt := range tests {
34
+ t.Run(tt.name, func(t *testing.T) {
35
+ // Implement test validation
36
+ })
37
+ }
38
+ }
39
+ ```
40
+ 7. Run validation commands:
41
+ - `go build ./...`
42
+ - `go test ./...`
@@ -1,38 +1,42 @@
1
- ## 🗺️ Hướng Dẫn Phát Triển NestJS (Node.js Backend)
2
-
3
- ### 🔄 Vòng Đời Phát Triển Tác Nhân (Agent Development Lifecycle)
4
- Tác nhân AI phải thực hiện tất cả các nhiệm vụ NestJS theo quy trình 5 bước sau:
5
- 1. **Thiết kế & Lập trình:** Triển khai các lớp nghiệp vụ tuân thủ cấu trúc Module-driven. Giữ Controller mỏng, đặt 100% logic nghiệp vụ trong Service.
6
- 2. **Kiểm thử Toàn diện:** Viết unit test cho các Service sử dụng Jest Mocking (`.spec.ts`) viết kiểm thử tích hợp đầu cuối (E2E) sử dụng Supertest.
7
- 3. **Chất lượng Mã nguồn:** Chạy các lệnh kiểm tra lỗi pháp kiểu dữ liệu:
8
- - Kiểm tra Lint: `{{runCommand}} lint`
9
- - Kiểm tra Kiểu dữ liệu: `{{runCommand}} typecheck`
10
- - Chạy Kiểm thử: `{{runCommand}} test` (hoặc `{{runCommand}} test -- --run` cho môi trường CI/CD)
11
- - Chạy Build thử nghiệm: `{{runCommand}} build`
12
- 4. **Quản lý Thư viện:** Cài đặt các thư viện mới bằng lệnh: `{{packageManager}} add [tên_thư_viện]`. Tuyệt đối cấm sửa thủ công file lock `{{lockFile}}`.
1
+ ## 🗺️ NestJS Development Guide (Node.js Backend)
2
+
3
+ ### 🔄 Agent Development Lifecycle
4
+ The AI Agent must execute all NestJS tasks following this structured 5-stage lifecycle:
5
+ 1. **Design & Code:** Implement business logic adhering to the Module-driven architecture. Keep Controllers thin; place 100% of business logic within Services. Encapsulate components cleanly as outlined in `@module-architecture.md`.
6
+ 2. **Comprehensive Testing:** Write unit tests for Services using Jest Mocking (`.spec.ts`) and end-to-end (E2E) integration tests using Supertest.
7
+ 3. **Troubleshooting & Debugging:** When debugging request validations or database mappings, inspect class-validator metadata and database query logs.
8
+ 4. **Code Quality & Review:** Perform self-review using `@validation-errors.md` to ensure constraints are enforced and exceptions are mapped correctly. Check formatting conventions in `@nestjs-style.md`.
9
+ 5. **Production Readiness:** Verify compilation and lint errors are resolved before completion.
13
10
 
14
11
  ---
15
12
 
16
- ### 🏗️ Kiến Trúc Hệ Thống Bản Mẫu (Template Blueprint)
17
- Vui lòng tham khảo các tài liệu quy tắc chi tiết dưới đây:
18
- - Hướng dẫn coding style chuẩn TypeScript, quy tắc căn lề, sắp xếp decorator tổ chức nguồn sạch: `@nestjs-style.md`
19
- - Quy định chặt chẽ về ranh giới Module, cơ chế cô lập mã nguồn, Encapsulation chia sẻ tài nguyên: `@module-architecture.md`
20
- - Cấu hình Class Validator, chuyển đổi dữ liệu thông qua ValidationPipe xử lỗi tập trung bằng Exceptions Filters: `@validation-errors.md`
21
- - Quy trình tự động sinh trọn bộ cấu phần gồm Module, Controller, Service, DTO, Entity theo đúng chuẩn hệ thống: `@SKILL.md`
13
+ ### 🏗️ Template Blueprint
14
+ Refer to the detailed rules below:
15
+ - TypeScript coding style, indentation, decorator sorting, and clean code conventions: `@nestjs-style.md`
16
+ - Strict module boundaries, encapsulation, and resource sharing rules: `@module-architecture.md`
17
+ - Class Validator setups, ValidationPipe data transformations, and Exception Filters: `@validation-errors.md`
18
+ - Process to scaffold modular components (Module, Controller, Service, DTO, Entity): `@nestjs-module`
22
19
 
23
20
  ---
24
21
 
25
- ### 🏛️ Quy Tắc Phát Triển Nghiêm Ngặt
22
+ ### 🏛️ Strict Development Rules
23
+
24
+ #### 1. Dependency Injection (DI)
25
+ - **No Property Injection:** Never use the `@Inject()` decorator directly on class properties unless injecting Custom Tokens. Property injection limits test mocking capabilities.
26
+ - **Constructor Injection Required:** Leverage NestJS's auto-dependency resolution via constructor parameters using `private readonly`.
26
27
 
27
- #### 1. Tiêm Phụ Thuộc (Dependency Injection)
28
- - **Cấm tiêm thuộc tính (Property Injection):** Tuyệt đối không dùng `@Inject()` trực tiếp trên thuộc tính của Class trừ trường hợp tiêm các token tùy biến (Custom Tokens).
29
- - **Bắt buộc tiêm qua Hàm Khởi Tạo (Constructor Injection):** Sử dụng chế tự động phân giải phụ thuộc của NestJS qua từ khóa `private readonly`.
28
+ #### 2. Input Validation & Transformation
29
+ - **Strict DTO Definitions:** All incoming HTTP request parameters (`@Body()`, `@Query()`, `@Param()`) must be mapped to DTO classes decorated with `class-validator` rules.
30
+ - **Global Validation Pipe:** Configure a global `ValidationPipe` in `main.ts` to strip non-whitelisted properties and automatically transform types.
30
31
 
31
- #### 2. Kiểm Thử Dữ Liệu Đầu Vào (Validation & Transformation)
32
- - **Định hình DTO nghiêm ngặt:** Toàn bộ dữ liệu đầu vào của HTTP Request (`@Body()`, `@Query()`, `@Param()`) phải được đặc tả qua các lớp DTO sử dụng decorator từ `class-validator`.
33
- - **Kích hoạt ống lọc toàn cục (Global Validation Pipe):** Khai báo tại file `main.ts` để tự động lọc bỏ các thuộc tính không nằm trong danh sách trắng (whitelist) tự động ép kiểu dữ liệu (transform).
32
+ #### 3. Unified Exception Handling
33
+ - **No Raw Server Errors:** Never expose raw database or system exceptions (HTTP 500) to clients.
34
+ - **Built-in HttpExceptions:** Handle try/catch flows inside Services and map errors to explicit NestJS HttpExceptions (e.g., `NotFoundException`, `BadRequestException`, `ForbiddenException`).
35
+ - **Global Exception Filter:** Expose a global Exception Filter to format all error responses consistently in JSON format.
34
36
 
35
- #### 3. Quản Ngoại Lệ Toàn Cục (Unified Exception Handling)
36
- - **Cấm trả về lỗi hệ thống thô:** Tuyệt đối không để lộ lỗi thô (chẳng hạn như lỗi từ DB) ra ngoài client với mã lỗi 500.
37
- - **Sử dụng HttpExceptions tích hợp:** Bắt buộc phải bắt lỗi (try/catch) ở tầng Service và ánh xạ sang các Http Exception tường minh của NestJS (`NotFoundException`, `BadRequestException`, `ForbiddenException`).
38
- - **Tập trung hóa bằng Exception Filter:** Xây dựng một Filter toàn cục để cấu trúc lại định dạng JSON trả về cho Client một cách đồng nhất.
37
+ ### 🧪 Verification & Testing
38
+ Before completing a task, run the following verification pipeline:
39
+ - **Linting:** `{{runCommand}} lint`
40
+ - **Type Checking:** `{{runCommand}} typecheck`
41
+ - **Testing:** `{{runCommand}} test`
42
+ - **Build Validation:** `{{runCommand}} build`
@@ -1,14 +1,14 @@
1
- # Kiến Trúc Mô-đun & Chế Tiêm Phụ Thuộc (DI)
1
+ # Modular Architecture & Dependency Injection (DI)
2
2
 
3
- Tài liệu này quy định ranh giới Module, chế cô lập mã nguồn, Encapsulation cách tiêm phụ thuộc chuẩn trong NestJS.
3
+ This document defines module boundaries, code isolation (encapsulation), and dependency injection standards in NestJS.
4
4
 
5
5
  ---
6
6
 
7
- ## 💉 Tiêm Phụ Thuộc (Dependency Injection)
8
- - **Cấm tiêm thuộc tính (Property Injection):** Tuyệt đối không dùng `@Inject()` trực tiếp trên thuộc tính của Class trừ trường hợp tiêm các token tùy biến (Custom Tokens). Việc tiêm thuộc tính làm giảm khả năng kiểm thử (mocking) và làm loãng mã nguồn.
9
- - **Bắt buộc tiêm qua Hàm Khởi Tạo (Constructor Injection):** Sử dụng chế tự động phân giải phụ thuộc của NestJS qua từ khóa `private readonly` trong constructor.
7
+ ## 💉 Dependency Injection (DI)
8
+ - **No Property Injection:** Never use the `@Inject()` decorator directly on class properties unless injecting Custom Tokens. Property injection degrades mock testing and litters class definitions.
9
+ - **Constructor Injection Required:** Use constructor parameter injection with the `private readonly` modifier to leverage NestJS's dependency resolution.
10
10
 
11
- * **Không hợp lệ (❌ Cấm viết):**
11
+ * **Invalid (❌ Prohibited):**
12
12
  ```typescript
13
13
  @Injectable()
14
14
  export class AuthService {
@@ -16,7 +16,7 @@ Tài liệu này quy định ranh giới Module, cơ chế cô lập mã nguồn
16
16
  private readonly usersService: UsersService;
17
17
  }
18
18
  ```
19
- * **Hợp lệ (✔️ Khuyến khích):**
19
+ * **Valid (✔️ Recommended):**
20
20
  ```typescript
21
21
  @Injectable()
22
22
  export class AuthService {
@@ -26,10 +26,10 @@ Tài liệu này quy định ranh giới Module, cơ chế cô lập mã nguồn
26
26
 
27
27
  ---
28
28
 
29
- ## 🏗️ Ranh Giới Mô-đun & Encapsulation
30
- - ** lập theo mặc định (Encapsulation by Default):** Các Provider (Services, Repositories) bên trong một Module mặc định private. Các module khác không thể truy cập nếu không được export công khai.
31
- - **Chia sẻ tài nguyên qua Module:** Khi Module B muốn sử dụng Service của Module A:
32
- 1. Thêm Service đó vào mảng `exports` trong `@Module()` của Module A.
33
- 2. Import Module A vào mảng `imports` của Module B.
34
- * Nghiêm cấm import trực tiếp Service của Module A vào danh sách `providers` của Module B.
35
- - **Mô-đun Toàn cục (Global Modules):** Hạn chế sử dụng `@Global()` ngoại trừ các mô-đun hạ tầng chung cực kỳ ổn định (như sở dữ liệu hoặc cấu hình hệ thống).
29
+ ## 🏗️ Module Boundaries & Encapsulation
30
+ - **Encapsulated by Default:** Providers (Services, Repositories) inside a Module are private by default. Other modules cannot access them unless they are explicitly exported.
31
+ - **Sharing Resources:** When Module B needs to use a Service declared in Module A:
32
+ 1. Add that Service to the `exports` array in Module A's `@Module()` decorator.
33
+ 2. Add Module A to the `imports` array in Module B's `@Module()` decorator.
34
+ * **Strict Rule:** Never import a Service of Module A directly into the `providers` array of Module B.
35
+ - **Global Modules:** Avoid using `@Global()` unless configuring highly stable infrastructure modules (e.g., Database connections or Config systems).
@@ -1,16 +1,16 @@
1
- # Quy Ước Đặt Tên & Coding Style cho NestJS
1
+ # NestJS Naming Conventions & Coding Style
2
2
 
3
- Tài liệu này hướng dẫn coding style chuẩn TypeScript, quy tắc đặt tên tệp tin lớp trong NestJS.
3
+ This document outlines standard guidelines for TypeScript coding styles, filename notations, and class naming conventions in NestJS.
4
4
 
5
5
  ---
6
6
 
7
- ## 🏷️ Quy Ước Đặt Tên (Naming Conventions)
7
+ ## 🏷️ Naming Conventions
8
8
 
9
- ### Kỹ thuật Đặt Tên Tệp (Dot Notation)
10
- Tất cả các tệp tin trong NestJS phải tuân thủ nghiêm ngặt định dạng cấu trúc: `<tên-đối-tượng>.<loại-cấu-phần>.ts`.
9
+ ### Filename Notation (Dot Notation)
10
+ All filenames in NestJS must strictly comply with the following format: `<name>.<type>.ts`.
11
11
 
12
12
  ```bash
13
- # Thư mục module luôn dùng số nhiều hoặc số ít đồng nhất ( dụ: auth, users, products)
13
+ # Module directories should use consistent singular or plural names (e.g., auth, users, products)
14
14
  src/users/
15
15
  ├── users.module.ts
16
16
  ├── users.controller.ts
@@ -26,8 +26,8 @@ src/users/
26
26
  └── logging.interceptor.ts
27
27
  ```
28
28
 
29
- ### Quy ước đặt tên Lớp (Class Naming)
30
- Tên lớp phải được viết theo định dạng PascalCase kết thúc bằng tên cụ thể của loại cấu phần đó:
29
+ ### Class Naming
30
+ Class names must use `PascalCase` and end with the specific component suffix representing their role:
31
31
  - **Controller:** `src/auth/auth.controller.ts` $\rightarrow$ `export class AuthController {}`
32
32
  - **Service:** `src/auth/auth.service.ts` $\rightarrow$ `export class AuthService {}`
33
33
  - **Module:** `src/auth/auth.module.ts` $\rightarrow$ `export class AuthModule {}`
@@ -35,7 +35,7 @@ Tên lớp phải được viết theo định dạng PascalCase và kết thúc
35
35
 
36
36
  ---
37
37
 
38
- ## 📦 TypeScript & Sắp Xếp Decorator
39
- - **Sắp xếp Decorator:** Nhóm sắp xếp các decorator một cách khoa học. Các decorator định nghĩa phương thức HTTP (`@Get()`, `@Post()`) nằm trên cùng, tiếp theo cấu hình bảo mật hoặc kiểm duyệt đầu vào (`@UseGuards()`, `@UseInterceptors()`).
40
- - **Kiểu trả về tường minh:** Khai báo kiểu trả về ràng cho tất cả các phương thức trong Controller Service để bảo đảm tính chặt chẽ của kiểu dữ liệu.
41
- - **Nghiêm cấm kiểu dữ liệu `any`:** Luôn khai báo class hoặc interface tương ứng cho các tham số kết quả xử lý.
38
+ ## 📦 TypeScript & Decorator Sorting
39
+ - **Decorator Sorting:** Group and organize decorator annotations systematically. Place HTTP methods (`@Get()`, `@Post()`) on top, followed by guards or interceptors (`@UseGuards()`, `@UseInterceptors()`).
40
+ - **Explicit Return Types:** Always define clear return types for all Controller and Service methods to guarantee type safety.
41
+ - **Strictly Ban the `any` Type:** Avoid generic `any` keywords. Create proper classes, interfaces, or types for all arguments and responses.