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.
- package/dist/cli/commands/add.js +3 -1
- package/dist/cli/commands/doctor.js +145 -47
- package/dist/cli/commands/init.js +6 -0
- package/dist/core/analyzer.js +70 -0
- package/dist/core/detector.js +22 -0
- package/package.json +1 -1
- package/templates/common/AGENTS.md.hbs +4 -0
- package/templates/common/GLOBAL_RULES.md +101 -0
- package/templates/devops/AGENTS.md.hbs +32 -0
- package/templates/devops/skills/devops/SKILL.md +477 -0
- package/templates/diagram/AGENTS.md.hbs +30 -0
- package/templates/diagram/skills/drawio-diagram/SKILL.md +427 -0
- package/templates/dotnet/AGENTS.md.hbs +38 -34
- package/templates/dotnet/rules/api-structure.md +15 -15
- package/templates/dotnet/rules/csharp-style.md +17 -17
- package/templates/dotnet/rules/dependency-injection.md +12 -12
- package/templates/dotnet/rules/error-handling-validation.md +15 -15
- package/templates/dotnet/skills/dotnet-controller/SKILL.md +16 -16
- package/templates/express/AGENTS.md.hbs +37 -33
- package/templates/express/rules/error-handling.md +18 -18
- package/templates/express/rules/express-style.md +19 -19
- package/templates/express/rules/router-controller.md +16 -16
- package/templates/express/skills/express-endpoint/SKILL.md +14 -14
- package/templates/fastapi/AGENTS.md.hbs +25 -3
- package/templates/fastapi/rules/api-testing.md +24 -0
- package/templates/fastapi/rules/database-async.md +26 -0
- package/templates/golang/AGENTS.md.hbs +42 -0
- package/templates/golang/rules/concurrency.md +71 -0
- package/templates/golang/rules/error-handling.md +42 -0
- package/templates/golang/rules/golang-style.md +24 -0
- package/templates/golang/rules/project-layout.md +39 -0
- package/templates/golang/skills/golang-db/SKILL.md +27 -0
- package/templates/golang/skills/golang-feature/SKILL.md +42 -0
- package/templates/nestjs/AGENTS.md.hbs +33 -29
- package/templates/nestjs/rules/module-architecture.md +14 -14
- package/templates/nestjs/rules/nestjs-style.md +12 -12
- package/templates/nestjs/rules/validation-errors.md +15 -15
- package/templates/nestjs/skills/nestjs-module/SKILL.md +15 -15
- package/templates/next-js/AGENTS.md.hbs +39 -35
- package/templates/next-js/rules/data-fetching-mutations.md +17 -17
- package/templates/next-js/rules/next-style.md +17 -17
- package/templates/next-js/rules/seo-metadata.md +18 -18
- package/templates/next-js/rules/server-client-components.md +17 -17
- package/templates/next-js/skills/next-feature/SKILL.md +16 -16
- package/templates/rust/AGENTS.md.hbs +41 -0
- package/templates/rust/rules/error-handling.md +36 -0
- package/templates/rust/rules/memory-concurrency.md +47 -0
- package/templates/rust/rules/project-layout.md +49 -0
- package/templates/rust/rules/rust-style.md +26 -0
- package/templates/rust/skills/rust-db/SKILL.md +27 -0
- 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
|
|
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
|
-
## 🗺️
|
|
2
|
-
|
|
3
|
-
### 🔄
|
|
4
|
-
|
|
5
|
-
1. **
|
|
6
|
-
2. **
|
|
7
|
-
3. **
|
|
8
|
-
|
|
9
|
-
|
|
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
|
-
### 🏗️
|
|
17
|
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
20
|
-
-
|
|
21
|
-
-
|
|
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
|
-
### 🏛️
|
|
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
|
-
####
|
|
28
|
-
- **
|
|
29
|
-
- **
|
|
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
|
-
####
|
|
32
|
-
-
|
|
33
|
-
- **
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
- **
|
|
38
|
-
- **
|
|
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
|
-
#
|
|
1
|
+
# Modular Architecture & Dependency Injection (DI)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
This document defines module boundaries, code isolation (encapsulation), and dependency injection standards in NestJS.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
7
|
-
## 💉
|
|
8
|
-
- **
|
|
9
|
-
- **
|
|
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
|
-
* **
|
|
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
|
-
* **
|
|
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
|
-
## 🏗️
|
|
30
|
-
- **
|
|
31
|
-
- **
|
|
32
|
-
1.
|
|
33
|
-
2.
|
|
34
|
-
*
|
|
35
|
-
- **
|
|
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
|
-
#
|
|
1
|
+
# NestJS Naming Conventions & Coding Style
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
## 🏷️
|
|
7
|
+
## 🏷️ Naming Conventions
|
|
8
8
|
|
|
9
|
-
###
|
|
10
|
-
|
|
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
|
-
#
|
|
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
|
-
###
|
|
30
|
-
|
|
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 &
|
|
39
|
-
- **
|
|
40
|
-
- **
|
|
41
|
-
- **
|
|
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.
|