agent-workflow-kit-cli 1.3.1 → 1.3.3

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 (50) hide show
  1. package/dist/cli/commands/add.js +3 -1
  2. package/dist/cli/commands/doctor.js +8 -1
  3. package/dist/cli/commands/init.js +6 -0
  4. package/dist/cli/index.js +2 -2
  5. package/dist/core/analyzer.js +216 -1
  6. package/dist/core/awos/intelligence.js +30 -6
  7. package/dist/core/detector.js +54 -4
  8. package/package.json +1 -1
  9. package/templates/common/AGENTS.md.hbs +4 -0
  10. package/templates/common/GLOBAL_RULES.md +101 -0
  11. package/templates/dotnet/AGENTS.md.hbs +53 -0
  12. package/templates/dotnet/rules/api-structure.md +43 -0
  13. package/templates/dotnet/rules/csharp-style.md +33 -0
  14. package/templates/dotnet/rules/dependency-injection.md +54 -0
  15. package/templates/dotnet/rules/error-handling-validation.md +86 -0
  16. package/templates/dotnet/skills/dotnet-controller/SKILL.md +24 -0
  17. package/templates/express/AGENTS.md.hbs +41 -0
  18. package/templates/express/rules/error-handling.md +88 -0
  19. package/templates/express/rules/express-style.md +39 -0
  20. package/templates/express/rules/router-controller.md +27 -0
  21. package/templates/express/skills/express-endpoint/SKILL.md +24 -0
  22. package/templates/golang/AGENTS.md.hbs +36 -0
  23. package/templates/golang/rules/concurrency.md +71 -0
  24. package/templates/golang/rules/error-handling.md +42 -0
  25. package/templates/golang/rules/golang-style.md +24 -0
  26. package/templates/golang/rules/project-layout.md +39 -0
  27. package/templates/nestjs/AGENTS.md.hbs +38 -0
  28. package/templates/nestjs/rules/module-architecture.md +35 -0
  29. package/templates/nestjs/rules/nestjs-style.md +41 -0
  30. package/templates/nestjs/rules/validation-errors.md +46 -0
  31. package/templates/nestjs/skills/nestjs-module/SKILL.md +25 -0
  32. package/templates/next-js/AGENTS.md.hbs +41 -0
  33. package/templates/next-js/rules/data-fetching-mutations.md +36 -0
  34. package/templates/next-js/rules/next-style.md +32 -0
  35. package/templates/next-js/rules/seo-metadata.md +50 -0
  36. package/templates/next-js/rules/server-client-components.md +27 -0
  37. package/templates/next-js/skills/next-feature/SKILL.md +26 -0
  38. package/templates/react-ts/AGENTS.md.hbs +109 -32
  39. package/templates/react-ts/rules/data-fetching.md +45 -0
  40. package/templates/react-ts/rules/forms-validation.md +55 -0
  41. package/templates/react-ts/rules/premium-ui.md +45 -0
  42. package/templates/react-ts/rules/react-style.md +38 -26
  43. package/templates/react-ts/rules/routing-splitting.md +21 -0
  44. package/templates/react-ts/rules/seo-accessibility.md +34 -0
  45. package/templates/react-ts/skills/react-feature/SKILL.md +5 -5
  46. package/templates/rust/AGENTS.md.hbs +34 -0
  47. package/templates/rust/rules/error-handling.md +36 -0
  48. package/templates/rust/rules/memory-concurrency.md +47 -0
  49. package/templates/rust/rules/project-layout.md +49 -0
  50. package/templates/rust/rules/rust-style.md +26 -0
@@ -0,0 +1,43 @@
1
+ # Presentation Layer Structure (API Controllers)
2
+
3
+ This document defines the structure and responsibilities of API Controllers inside the Presentation layer of a .NET application.
4
+
5
+ ---
6
+
7
+ ## 🏛️ API Controller Responsibilities
8
+ An API Controller is responsible for:
9
+ 1. Receiving incoming HTTP requests from clients.
10
+ 2. Mapping URL parameters, query strings, or request bodies into target request DTOs.
11
+ 3. Delegating request processing to the Application layer (Services/Queries/Commands).
12
+ 4. Receiving results and responding to the client using appropriate HTTP status codes (e.g., `200 OK`, `201 Created`, `400 Bad Request`, `404 Not Found`).
13
+
14
+ ---
15
+
16
+ ## 🚦 Development Rules
17
+ - **Thin Controllers:** Controllers must not contain business logic, algorithmic calculations, or direct database queries. 100% of this logic must reside in the Application layer.
18
+ - **Do Not Inject DbContext into Controllers:** Keep `DbContext` encapsulated within the Infrastructure / Repository layers. The Presentation layer must never access `DbContext` directly.
19
+ - **Use DTOs Instead of Domain Entities:**
20
+ - Never accept raw Domain Entities as Controller input parameters.
21
+ - Never return raw Domain Entities directly to the client to prevent exposing the database schema or triggering cyclic reference errors. Always map records to DTO (Data Transfer Object) classes.
22
+ - **Explicit Route Declarations:** Use attribute routing to clearly declare HTTP methods and endpoints:
23
+ ```csharp
24
+ [ApiController]
25
+ [Route("api/v1/[controller]")]
26
+ public class CoursesController : ControllerBase
27
+ {
28
+ private readonly ICourseService _courseService;
29
+
30
+ public CoursesController(ICourseService courseService)
31
+ {
32
+ _courseService = courseService;
33
+ }
34
+
35
+ [HttpGet("{id}")]
36
+ public async Task<IActionResult> GetById(Guid id)
37
+ {
38
+ var course = await _courseService.GetByIdAsync(id);
39
+ if (course == null) return NotFound();
40
+ return Ok(course);
41
+ }
42
+ }
43
+ ```
@@ -0,0 +1,33 @@
1
+ # C# Coding Style & Conventions
2
+
3
+ This document specifies standard coding styles, naming patterns, and source file organization conventions in .NET projects.
4
+
5
+ ---
6
+
7
+ ## 🏷️ Naming Conventions
8
+
9
+ ### Class & Component Naming Rules
10
+ - **PascalCase:** Use for Classes, Structs, Records, Enums, Interfaces, Methods, and Public Properties.
11
+ - *Examples:* `UserService`, `GetActiveUsers()`, `CreatedDate`.
12
+ - **Interface Prefix:** Interface names must start with the uppercase letter `I`.
13
+ - *Examples:* `IUserService`, `IUserRepository`.
14
+ - **camelCase:** Use for method arguments and local variables.
15
+ - *Examples:* `userId`, `requestPayload`.
16
+ - **Private Fields Prefix:** Private fields inside classes must use `camelCase` and start with an underscore `_`.
17
+ - *Example:* `private readonly IUserRepository _userRepository;`.
18
+
19
+ ---
20
+
21
+ ## 📦 File Structure & Formatting
22
+ - **Namespaces:** Match namespaces with the physical directory structure to ensure easy discovery.
23
+ - *Example:* `ProjectName.Application.Services`.
24
+ - **File-Scoped Namespaces:** Use C# 10+ file-scoped namespaces to reduce unnecessary indentation levels:
25
+ ```csharp
26
+ namespace ProjectName.Application.Services;
27
+
28
+ public class UserService : IUserService
29
+ {
30
+ // ...
31
+ }
32
+ ```
33
+ - **Sorting Usings:** Organize `using` directives by placing system namespaces (`System.*`) first, followed by third-party packages, and internal project dependencies last.
@@ -0,0 +1,54 @@
1
+ # Dependency Injection (DI) Configurations
2
+
3
+ This document details guidelines for configuring and consuming dependency injection in .NET Core applications.
4
+
5
+ ---
6
+
7
+ ## 💉 Constructor Injection
8
+ - **Mandatory Rule:** Always resolve class dependencies using constructor parameters. Assign them to private readonly fields prefixed with an underscore `_`.
9
+ - Never use the Service Locator pattern (do not call `app.Services.GetService<T>()` or inject `IServiceProvider` to dynamically resolve services at runtime).
10
+
11
+ * **Invalid (❌ Prohibited):**
12
+ ```csharp
13
+ public class OrderService
14
+ {
15
+ private readonly IServiceProvider _serviceProvider;
16
+
17
+ public OrderService(IServiceProvider serviceProvider)
18
+ {
19
+ _serviceProvider = serviceProvider;
20
+ }
21
+
22
+ public void Process()
23
+ {
24
+ var repo = _serviceProvider.GetService<IOrderRepository>();
25
+ // ...
26
+ }
27
+ }
28
+ ```
29
+ * **Valid (✔️ Recommended):**
30
+ ```csharp
31
+ public class OrderService : IOrderService
32
+ {
33
+ private readonly IOrderRepository _orderRepository;
34
+
35
+ public OrderService(IOrderRepository orderRepository)
36
+ {
37
+ _orderRepository = orderRepository;
38
+ }
39
+
40
+ public void Process()
41
+ {
42
+ var orders = _orderRepository.GetAll();
43
+ // ...
44
+ }
45
+ }
46
+ ```
47
+
48
+ ---
49
+
50
+ ## ⚙️ Service Lifetimes Registration
51
+ Register dependencies with the appropriate lifetime scopes inside `Program.cs`:
52
+ 1. **Transient (`AddTransient<I, T>()`):** Instantiated every time they are requested. Use for lightweight, stateless services.
53
+ 2. **Scoped (`AddScoped<I, T>()`):** Instantiated once per HTTP request context. Recommended for repositories, database contexts (`DbContext`), and business services.
54
+ 3. **Singleton (`AddSingleton<I, T>()`):** Instantiated once and shared across the entire application lifetime. Use for in-memory caching, system configurations, and thread-safe helper services.
@@ -0,0 +1,86 @@
1
+ # Unified Exception Handling & Automated Validation (FluentValidation)
2
+
3
+ This document defines configurations for centralized exception handling using Middleware and incoming request validation using the FluentValidation library in .NET applications.
4
+
5
+ ---
6
+
7
+ ## 🛡️ Automated Validation with FluentValidation
8
+ - **Rule:** Every API request representing complex input data payloads must have a corresponding validator class inheriting from `AbstractValidator<T>` to declare validation rules.
9
+ - Configure FluentValidation to automatically intercept invalid requests and return an HTTP `400 Bad Request` payload to the client, preventing repetitive manual validation checks inside Controllers.
10
+
11
+ ```csharp
12
+ // Example of a Validator class
13
+ using FluentValidation;
14
+
15
+ public class CreateCourseRequestValidator : AbstractValidator<CreateCourseRequestDto>
16
+ {
17
+ public CreateCourseRequestValidator()
18
+ {
19
+ RuleFor(x => x.Title)
20
+ .NotEmpty().WithMessage("Course title cannot be empty.")
21
+ .MaximumLength(150).WithMessage("Title must not exceed 150 characters.");
22
+
23
+ RuleFor(x => x.Price)
24
+ .GreaterThanOrEqualTo(0).WithMessage("Course price cannot be less than 0.");
25
+ }
26
+ }
27
+ ```
28
+
29
+ ---
30
+
31
+ ## 🚨 Centralized Exception Handling (Global Exception Middleware)
32
+ - **Rule:** Never expose raw system exceptions (such as database faults, file system errors, or stack traces) directly to clients as HTTP 500 errors.
33
+ - Build a global middleware (`ExceptionHandlingMiddleware`) or implement `IExceptionHandler` in .NET 8+ to intercept all unhandled exceptions and format them into a standard JSON payload:
34
+
35
+ ```json
36
+ {
37
+ "success": false,
38
+ "statusCode": 500,
39
+ "timestamp": "2026-06-13T07:42:00.000Z",
40
+ "message": "An internal server error occurred. Please contact the administrator."
41
+ }
42
+ ```
43
+
44
+ ```csharp
45
+ // Standard Global Exception Handling Middleware
46
+ public class ExceptionHandlingMiddleware
47
+ {
48
+ private readonly RequestDelegate _next;
49
+ private readonly ILogger<ExceptionHandlingMiddleware> _logger;
50
+
51
+ public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
52
+ {
53
+ _next = next;
54
+ _logger = logger;
55
+ }
56
+
57
+ public async Task InvokeAsync(HttpContext context)
58
+ {
59
+ try
60
+ {
61
+ await _next(context);
62
+ }
63
+ catch (Exception ex)
64
+ {
65
+ _logger.LogError(ex, "An unhandled exception has occurred.");
66
+ await HandleExceptionAsync(context, ex);
67
+ }
68
+ }
69
+
70
+ private static Task HandleExceptionAsync(HttpContext context, Exception exception)
71
+ {
72
+ context.Response.ContentType = "application/json";
73
+ context.Response.StatusCode = StatusCodes.Status500InternalServerError;
74
+
75
+ var response = new
76
+ {
77
+ success = false,
78
+ statusCode = context.Response.StatusCode,
79
+ timestamp = DateTime.UtcNow,
80
+ message = "An internal server error occurred. Please contact the administrator."
81
+ };
82
+
83
+ return context.Response.WriteAsJsonAsync(response);
84
+ }
85
+ }
86
+ ```
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: dotnet-controller
3
+ description: Scaffold or extend an ASP.NET Core API Controller with corresponding DTOs, FluentValidation, and Service interfaces
4
+ ---
5
+
6
+ Follow this process to generate a new API Endpoint or Controller in .NET (C#).
7
+
8
+ Inputs:
9
+ - controllerName: Name of the Controller (e.g., `CoursesController`)
10
+ - routePath: HTTP route mapping (e.g., `api/v1/courses`)
11
+ - requestDtoName: Class name of the request DTO (e.g., `CreateCourseRequestDto`)
12
+ - functionality: Summary of the business requirements and methods to process
13
+
14
+ Steps:
15
+ 1. Declare the corresponding Request/Response DTO classes inside the Application layer (or the project's `DTOs` directory).
16
+ 2. Create a Validator class inheriting from FluentValidation's `AbstractValidator<T>` in the Application layer to define data constraints.
17
+ 3. Define the Service Interface (e.g., `ICourseService`) and its concrete implementation class (`CourseService`) in the Application layer to handle business logic.
18
+ 4. Register the new Service in the Dependency Injection container (using Scoped lifetime) inside the `Program.cs` configuration file.
19
+ 5. Create the Controller class inheriting from `ControllerBase`, decorated with `[ApiController]` and `[Route]` attributes.
20
+ 6. Use Constructor Injection to inject the Service Interface into the Controller, delegate request processing, and map responses to appropriate `IActionResult` objects (e.g., `Ok()`, `Created()`, `BadRequest()`).
21
+ 7. Write unit tests for the Service and Controller using xUnit and Moq.
22
+ 8. Execute compilation and testing:
23
+ - `dotnet build`
24
+ - `dotnet test`
@@ -0,0 +1,41 @@
1
+ ## 🗺️ Express.js Development Guide (Node.js Backend)
2
+
3
+ ### 🔄 Agent Development Lifecycle
4
+ The AI Agent must execute all Express.js tasks following this 5-step workflow:
5
+ 1. **Design & Implementation:** Organize code according to a clean 3-tier architecture. Spaghetti code is strictly prohibited.
6
+ 2. **Comprehensive Testing:** Write unit tests for Services using Jest, and test API integrations using Supertest.
7
+ 3. **Code Quality & Type Safety:** Run syntax check and type check commands:
8
+ - Linting: `{{runCommand}} lint`
9
+ - Type Checking: `{{runCommand}} typecheck`
10
+ - Testing: `{{runCommand}} test` (or `{{runCommand}} test -- --run` for CI/CD environments)
11
+ - Build Validation: `{{runCommand}} build`
12
+ 4. **Dependency Management:** Install new libraries using `{{packageManager}} add [library_name]`. Never modify the lockfile `{{lockFile}}` manually.
13
+
14
+ ---
15
+
16
+ ### 🏗️ Template Blueprint
17
+ Refer to the detailed rules below:
18
+ - Clean coding style and type safety using TypeScript in Express: `@express-style.md`
19
+ - Separation of concerns: Router mappings $\rightarrow$ Controller delegation $\rightarrow$ Service execution: `@router-controller.md`
20
+ - Async error catching strategies and centralized global error handling middleware: `@error-handling.md`
21
+ - Process to scaffold new API endpoints cleanly from Routers to Validators: `@SKILL.md`
22
+
23
+ ---
24
+
25
+ ### 🏛️ Strict Development Rules
26
+
27
+ #### 1. Strict Layer Separation
28
+ Strictly comply with the data flow chain:
29
+ $$\text{Client} \longrightarrow \text{Router} \longrightarrow \text{Middleware} \longrightarrow \text{Controller} \longrightarrow \text{Service} \longrightarrow \text{Model/Database}$$
30
+ - **Router:** Must not contain processing logic. Only maps HTTP methods + paths and registers auth/validation middlewares.
31
+ - **Controller:** Only extracts inputs from the request object (`req.body`, `req.query`, `req.params`), invokes the target Service, and returns the response using `res.status().json()`. Never execute database queries directly here.
32
+ - **Service:** Houses business logic, calculations, and database model interactions. Must not reference or depend on Express `req` or `res` objects to ensure testability.
33
+
34
+ #### 2. Async Error Handling
35
+ - **No Manual Try/Catch in Controllers:** Avoid wrapping every controller method in manual try/catch blocks.
36
+ - **Use Async Handlers:** Wrap all async controller functions with an automatic error-catching wrapper (such as `express-async-handler`) to forward exceptions to the `next()` function automatically.
37
+ - **Centralized Global Error Middleware:** Declare a 4-parameter error-handling middleware at the end of the server bootstrap chain (after all route registrations) to format error payloads.
38
+
39
+ #### 3. Request Validation with Zod Middleware
40
+ - **No Manual Conditional Validation:** Do not write scattered `if` blocks to check input parameters.
41
+ - **Zod Schema Middleware:** Implement a shared validation middleware that accepts a Zod schema to validate request segments (`body`, `query`, `params`) before they reach the Controller.
@@ -0,0 +1,88 @@
1
+ # Async Error Handling & Automated Validation (Zod Middleware)
2
+
3
+ This document defines standard practices for asynchronous error catching, centralized global error handling middleware, and automated schema validations using Zod.
4
+
5
+ ---
6
+
7
+ ## 🚨 Async Error Handling Architecture
8
+ - **No Manual Try/Catch in Controllers:** Wrapping every controller method in manual try/catch blocks is prohibited.
9
+ - **Use Async Handlers:** Wrap all async controller functions with an automatic error-catching wrapper (such as `asyncHandler`) to automatically forward exceptions to Express's `next()` function.
10
+
11
+ ```typescript
12
+ import { Request, Response, NextFunction } from 'express';
13
+
14
+ // Automated async error catcher wrapper
15
+ const asyncHandler = (fn: Function) => (req: Request, res: Response, next: NextFunction) => {
16
+ Promise.resolve(fn(req, res, next)).catch(next);
17
+ };
18
+
19
+ // Controller usage example
20
+ export const getUserProfile = asyncHandler(async (req: Request, res: Response) => {
21
+ const userId = req.user.id;
22
+ const profile = await userService.getProfile(userId); // Errors thrown inside the service are automatically caught
23
+ return res.status(200).json({ success: true, data: profile });
24
+ });
25
+ ```
26
+
27
+ ---
28
+
29
+ ## 🔌 Centralized Global Error Handler Middleware
30
+ - **Register Error Middleware:** You must register a 4-parameter error-handling middleware at the end of the server bootstrap chain (after all route registrations) to parse and return clean error responses.
31
+
32
+ ```typescript
33
+ // Inside app.ts or server.ts
34
+ app.use((err: any, req: Request, res: Response, next: NextFunction) => {
35
+ const statusCode = err.statusCode || 500;
36
+ const message = err.message || 'Internal Server Error';
37
+
38
+ res.status(statusCode).json({
39
+ success: false,
40
+ status: statusCode,
41
+ message: message,
42
+ stack: process.env.NODE_ENV === 'development' ? err.stack : undefined,
43
+ });
44
+ });
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 🛡️ Automated Validation with Zod Middleware
50
+ - **No Manual Conditional Checks:** Do not write scattered `if (!req.body.email)` conditionals inside controllers.
51
+ - **Zod Schema Middleware:** Implement a shared validation middleware that accepts a Zod schema to validate request segments (`body`, `query`, `params`) before they reach the Controller.
52
+
53
+ ```typescript
54
+ import { AnyZodObject, ZodError } from 'zod';
55
+ import { Request, Response, NextFunction } from 'express';
56
+
57
+ export const validateSchema = (schema: AnyZodObject) => {
58
+ return async (req: Request, res: Response, next: NextFunction): Promise<any> => {
59
+ try {
60
+ // Validate incoming request segments concurrently
61
+ const parsed = await schema.parseAsync({
62
+ body: req.body,
63
+ query: req.query,
64
+ params: req.params,
65
+ });
66
+
67
+ // Re-assign parsed and sanitized payloads
68
+ req.body = parsed.body;
69
+ req.query = parsed.query;
70
+ req.params = parsed.params;
71
+
72
+ return next();
73
+ } catch (error) {
74
+ if (error instanceof ZodError) {
75
+ return res.status(400).json({
76
+ success: false,
77
+ message: 'Invalid input payload parameters',
78
+ errors: error.errors.map((err) => ({
79
+ field: err.path.join('.'),
80
+ message: err.message,
81
+ })),
82
+ });
83
+ }
84
+ return next(error);
85
+ }
86
+ };
87
+ };
88
+ ```
@@ -0,0 +1,39 @@
1
+ # Express.js Naming Conventions & Coding Style
2
+
3
+ This document defines coding conventions, directory layout, and TypeScript configurations for Express.js applications.
4
+
5
+ ---
6
+
7
+ ## 🏷️ Naming Conventions
8
+
9
+ ### Directory Layout (3-Tier Architecture)
10
+ The codebase must be structured cleanly according to a 3-tier architecture layout:
11
+ ```bash
12
+ src/
13
+ ├── config/ # Environment configurations, DB initializations
14
+ ├── middlewares/ # Express middleware functions (Auth, Log, Validation)
15
+ ├── models/ # Database Schemas (Mongoose, Sequelize, or Prisma client)
16
+ ├── routes/ # HTTP Route definitions and input middleware binding
17
+ ├── controllers/ # Request parameter extraction, response formatting
18
+ ├── services/ # Houses 100% of business logic and computations
19
+ ├── utils/ # Standalone utility helper functions
20
+ └── app.ts # Express App setup and server bootstrapping
21
+ ```
22
+
23
+ ### Filename Notation
24
+ - **Consistency:** Use `kebab-case.ts` across all filenames in the repository.
25
+ - **Suffix Declarations:** Filenames must end with a suffix representing their architectural role:
26
+ - Controller: `user-controller.ts`
27
+ - Service: `user-service.ts`
28
+ - Route: `user-route.ts`
29
+ - Middleware: `auth-middleware.ts`, `validate-middleware.ts`
30
+ - Model: `user-model.ts`
31
+
32
+ ---
33
+
34
+ ## 📦 TypeScript & Type Declarations
35
+ - **Explicit Type Declarations:** Avoid implicit type inference. Always define types for `req`, `res`, and `next` parameters imported from `express`:
36
+ ```typescript
37
+ import { Request, Response, NextFunction } from 'express';
38
+ ```
39
+ - **Strictly Ban the `any` Keyword:** Declare interfaces or types for all request bodies and API response structures.
@@ -0,0 +1,27 @@
1
+ # Architectural Boundaries (Router vs Controller vs Service)
2
+
3
+ This document establishes boundaries and responsibilities for routers, controllers, and services in Express.js projects.
4
+
5
+ ---
6
+
7
+ ## 🏛️ Data Flow Chain
8
+ All features in the repository must comply with the standard 3-tier architecture data flow:
9
+ $$\text{Client} \longrightarrow \text{Router} \longrightarrow \text{Middleware} \longrightarrow \text{Controller} \longrightarrow \text{Service} \longrightarrow \text{Model/Database}$$
10
+
11
+ ---
12
+
13
+ ## 🚦 Layer Responsibilities
14
+
15
+ ### 1. Router Layer (`routes/`)
16
+ - **Role:** Exclusively responsible for mapping HTTP methods + paths and binding authentication or payload validation middlewares (e.g., Zod schemas).
17
+ - **Rule:** Under no circumstances should the Router layer house business calculations or database operations. It must only forward requests to the target Controller.
18
+
19
+ ### 2. Controller Layer (`controllers/`)
20
+ - **Role:** Responsible for extracting input payloads from the Express `req` object (`req.body`, `req.query`, `req.params`, `req.user`), forwarding these arguments to the Service layer, receiving outcomes, and responding to the client via `res.status().json()`.
21
+ - **Rules:**
22
+ - Never query database models or call ORM clients inside the Controller.
23
+ - Never write manual try/catch blocks (delegate errors to the global error handler using async wrappers).
24
+
25
+ ### 3. Service Layer (`services/`)
26
+ - **Role:** Houses 100% of the core business logic, coordinates data mutations, executes algorithms, and interacts with Database models.
27
+ - **Rule:** Never import, reference, or access Express-specific objects (`req`, `res`, or `next`) inside Services. The Service layer must remain completely decoupled from the web framework to maintain isolated testability.
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: express-endpoint
3
+ description: Scaffold or extend a secure Express.js + TypeScript API endpoint including Router, Controller, and Validator
4
+ ---
5
+
6
+ Follow this process to generate a new Express.js API Endpoint or extend an existing route.
7
+
8
+ Inputs:
9
+ - endpointName: Name of the API Endpoint to create (e.g., `user-profile`)
10
+ - routePath: HTTP route path of the API (e.g., `/api/v1/users/profile`)
11
+ - httpMethod: HTTP method (GET, POST, PUT, DELETE)
12
+ - targetPath: The destination path to place the code files
13
+
14
+ Steps:
15
+ 1. Define a Zod Validation Schema under the `middlewares/` directory or alongside the controller to validate input payloads.
16
+ 2. Implement the corresponding Service function under the `services/` directory to handle 100% of the business logic and ORM queries.
17
+ 3. Implement the Controller dispatcher in the `controllers/` directory using the `asyncHandler` wrapper to forward errors automatically, extract inputs, and send JSON responses.
18
+ 4. Register the Controller and mount the `validateSchema(zodSchema)` middleware on the target Route file under the `routes/` directory.
19
+ 5. Create unit test suites for the Service and integration test suites (E2E) using Supertest.
20
+ 6. Execute local validation:
21
+ - `{{runCommand}} lint`
22
+ - `{{runCommand}} typecheck`
23
+ - `{{runCommand}} test`
24
+ - `{{runCommand}} build`
@@ -0,0 +1,36 @@
1
+ ## 🗺️ Golang Development Guide (Go Backend)
2
+
3
+ ### 🔄 Agent Development Lifecycle
4
+ The AI Agent must execute all Golang tasks following this 4-step workflow:
5
+ 1. **Design & Implementation:** 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. Run tests with: `go test ./...`.
7
+ 3. **Code Quality & Formatting:** Ensure code compiles and meets formatting/linting rules:
8
+ - Formatting: `gofmt -w .`
9
+ - Linting: `golangci-lint run`
10
+ - Build Validation: `go build ./...`
11
+ 4. **Dependency Management:** Add new external libraries using `go get [library_name]`. Never manually edit the `go.sum` file.
12
+
13
+ ---
14
+
15
+ ### 🏗️ Template Blueprint
16
+ Refer to the detailed rules below:
17
+ - Go coding style, interface design, and naming conventions: `@golang-style.md`
18
+ - Directory organization and manual dependency injection: `@project-layout.md`
19
+ - Explicit error handling, wrapping, and custom API errors: `@error-handling.md`
20
+ - Concurrency, goroutine/channel lifecycle, and escape analysis: `@concurrency.md`
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.
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`.
@@ -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.