add brain

This commit is contained in:
2026-03-12 15:17:52 +07:00
parent fd9f558fa1
commit e7821a7a9d
355 changed files with 93784 additions and 24 deletions

View File

@@ -0,0 +1,126 @@
---
name: GenerateGitHubActions
description: Guide to generating a CI/CD pipeline automating Build, Test, Docker Build & Deploy using GitHub Actions.
---
# GenerateGitHubActions Skill
When a user requests the creation of CI/CD Pipelines (e.g., GitHub Actions, or its equivalent for GitLab CI / Azure DevOps), you must generate an automation workflow file following standard steps below.
## Purpose
- Automate the source code testing (CI) and deployment (CD) process.
- Ensure any code pushed to the `main` branch always functions correctly and is ready for production.
## Configuration Guide (GitHub Actions)
Create a Workflow file for GitHub Actions.
### 1. File Path and Name
- **Path**: `.github/workflows/ci-cd.yml`
- (Or corresponding platform format: `.gitlab-ci.yml` for GitLab, `azure-pipelines.yml` for Azure DevOps).
### 2. Mandatory Configuration Steps in the YAML File
The workflow needs to progress through these main flows (example below is for GitHub Actions):
#### Phase 1: Build & Test (CI)
- **Triggers**: Listen for `push` or `pull_request` events on the `main` branch.
- **Environment Setup**:
- Checkout source code (e.g., using `actions/checkout@v4`).
- Install the .NET SDK matching the project (e.g., `actions/setup-dotnet@v4` for .NET 8.0). **Note: Enable Nuget cache to speed up the build.**
- **Run Tests**:
- Execute `dotnet restore`, `dotnet build --no-restore`.
- Most critically: Run `dotnet test --no-build --verbosity normal`. (Only if Tests go Green (Passed) should subsequent steps proceed).
#### Phase 2: Docker Build & Push (Start of CD)
- **Prerequisite**: Only run if the Build & Test Job was successful (`needs: build`).
- **Log into Container Registry**:
- Login to Docker Hub or Azure Container Registry (ACR) using System Secrets (e.g., `DOCKER_USERNAME` and `DOCKER_PASSWORD`).
- **Build & Push Image**:
- Build the Image from the Dockerfile (ensure it points to the root directory containing the main project so `docker build` can access the multiple layers of Clean Architecture).
- Tag the Image (e.g., `latest` or via Commit SHA/version).
- Push the Image to the Registry.
#### Phase 3: Deploy to Server (CD - Webhook / SSH)
- Use the `appleboy/ssh-action` library (or similar) to SSH into the target Server.
- Instruct the server to pull the latest Image file from the Registry.
- **Important:** Prioritize using `docker compose` to deploy (pull and up) if the user's project structure includes a `docker-compose.yml` file. This helps restart the entire stack (API, DB, Redis, etc.) rather than just running a standalone `docker run`.
## Default Template File (`ci-cd.yml`)
Below is the template framework you need to base your designs on when generating files for users:
```yaml
name: CI/CD Pipeline
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
cache: true # Enable Nuget cache; subsequent builds will be twice as fast
cache-dependency-path: '**/packages.lock.json'
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal
docker-build-push:
needs: build-and-test
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- uses: actions/checkout@v4
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
tags: ${{ secrets.DOCKER_USERNAME }}/detailed-project-name-lowercase:latest
deploy:
needs: docker-build-push
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy via SSH
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USER }}
key: ${{ secrets.SERVER_SSH_KEY }}
script: |
cd /path/to/your/project/on/server # Point to the directory containing docker-compose.yml
docker compose pull # Pull the newest image (based on the compose file)
docker compose up -d --build # Restart any services with modifications
```
## Reminders for the AI Agent
- When a User asks to generate a pipeline, ensure you ask the User to confirm their Docker Hub account name, Server Credentials, and remind them to fully configure `Secrets` on GitHub after the file is generated.
- **Automatically replace the project name string (`detailed-project-name-lowercase` in the template) with the true name of the Project / Repository the User is working on. Convert everything to lowercase when naming the Docker Image to prevent Docker formatting errors.**
- **If the user utilizes `docker-compose`, prioritize generating the `docker compose up -d` command over bare `docker run` commands.**

View File

@@ -0,0 +1,34 @@
---
name: GenerateCQRSFeature
description: Guide to generating a CQRS-based feature using MediatR (including Entity, Command/Query, Handler, and Controller).
---
# GenerateCQRSFeature Skill
When a user requests to create a feature using the **CQRS** pattern, providing the **Feature Name** (e.g., `Order`) and **Action** (e.g., `Create`), you **MUST** follow these steps to generate the corresponding code and files:
## 1. Directory and File Outputs
Based on the {FeatureName} and {Action}, create the following files (if the action is Read/Get, change 'Commands' to 'Queries'):
1. **Domain Entity**
- **Path**: `Domain/Entities/{FeatureName}.cs`
- **Content**: A basic Entity class defining the properties.
2. **Command / Query**
- **Path**: `Application/Features/{FeatureName}s/Commands/{Action}{FeatureName}/{Action}{FeatureName}Command.cs`
- **Content**: An input model that implements MediatR's `IRequest<TResponse>`.
3. **Command / Query Handler**
- **Path**: `Application/Features/{FeatureName}s/Commands/{Action}{FeatureName}/{Action}{FeatureName}CommandHandler.cs`
- **Content**: Business logic processor that implements `IRequestHandler<{Action}{FeatureName}Command, TResponse>`. Inject any needed Repository or service here.
4. **WebAPI Controller**
- **Path**: `WebAPI/Controllers/{FeatureName}sController.cs` (Remember to pluralize the Controller name if applicable).
- **Content**: REST API endpoints. **Requirement:** Must receive `IMediator` via Dependency Injection in the constructor to dispatch requests (e.g., `await _mediator.Send(command)`).
## 2. Dependency Injection Configuration (NOT REQUIRED)
⚠️ **Note:** As per project standards, the CQRS flow **DOES NOT REQUIRE** updating Dependency Injection configuration files.
The MediatR library automatically scans and registers all Handlers inheriting from `IRequestHandler`. Therefore, you **ABSOLUTELY MUST SKIP** updating the DI config files for Handlers.

View File

@@ -0,0 +1,40 @@
---
name: GenerateNTierFeature
description: Guide to generating an N-Tier architecture feature (including Entity, Interface, Service, Controller, and Dependency Injection configuration).
---
# GenerateNTierFeature Skill
When a user requests to create a feature using the **N-Tier** flow, providing the **Feature Name** (e.g., `Category`), you **MUST** follow these steps to generate the corresponding code and files:
## 1. Directory and File Outputs
Create the following files with appropriate content for the {FeatureName}:
1. **Domain Entity**
- **Path**: `Domain/Entities/{FeatureName}.cs`
- **Content**: A basic Entity class defining the properties.
2. **Service Interface**
- **Path**: `Application/Interfaces/I{FeatureName}Service.cs`
- **Content**: Interfaces defining the method contracts for {FeatureName}.
3. **Service Implementation**
- **Path**: `Application/Services/{FeatureName}Service.cs`
- **Content**: A class that inherits from `I{FeatureName}Service`. **Requirement:** Use constructor Dependency Injection (DI) to receive instances (e.g., `IRepository<{FeatureName}>`).
4. **WebAPI Controller**
- **Path**: `WebAPI/Controllers/{FeatureName}sController.cs` (Remember to pluralize the Controller name).
- **Content**: The Controller class. **Requirement:** Must receive `I{FeatureName}Service` via constructor DI and define the corresponding endpoints.
## 2. Dependency Injection Configuration (MANDATORY STEP)
⚠️ **Important:** Unlike CQRS with MediatR mentioned above, the N-Tier flow **REQUIRES** you to manually register the newly created service into the IoC Container.
You **MUST** use the appropriate tool to open the project's DI configuration file (could be `DependencyInjection.cs` or `ServiceCollectionExtensions.cs` depending on the directory structure) and inject the following code block into the relevant service configuration method:
```csharp
services.AddScoped<I{FeatureName}Service, {FeatureName}Service>();
```
Make sure to use an accurate file editing tool (`replace_file_content` or `multi_replace_file_content`) to avoid breaking the DI file's syntax.

View File

@@ -0,0 +1,49 @@
---
name: GenerateArchitectureTest
description: Guide to creating an Architecture Test using NetArchTest.Rules to protect the Clean Architecture structure.
---
# GenerateArchitectureTest Skill
When a user requests to verify or create an **Architecture Test**, you must use the `NetArchTest.Rules` library to generate tests that strictly protect the project's "Clean Architecture" boundaries.
## Purpose
- Prevent developers from writing sloppy code by incorrectly importing libraries/modules across layers.
- If a violation occurs (e.g., importing Entity Framework into the Domain layer), this test will immediately turn RED during the build process. It acts as solid proof to ensure the architecture is fully protected!
## Writing Test Rules Guide
You need to write test methods (using `[Fact]` with xUnit or NUnit) that utilize the Fluent API of `NetArchTest.Rules`. Below are the mandatory common rules:
1. **Domain Layer Rules:**
- The Domain must not depend on anything from Infrastructure, Application, or WebAPI.
```csharp
[Fact]
public void DomainLayer_ShouldNot_HaveDependencyOn_OtherLayers()
{
var result = Types.InAssembly(DomainAssembly)
.ShouldNot()
.HaveDependencyOnAny(
"MyNewProjectName.Application",
"MyNewProjectName.Infrastructure",
"MyNewProjectName.WebAPI"
)
.GetResult();
Assert.True(result.IsSuccessful);
}
```
2. **Application Layer Rules:**
- The Application Layer is only allowed to communicate with the Domain. It MUST NOT have dependencies on `Infrastructure` or `WebAPI`.
3. **Controller Rules (Naming/API Location):**
- Controllers must inherit from the BaseAPIController class and have the suffix "Controller".
- Direct database queries from the Controller are strictly prohibited (prevent the injection of `DbContext` or `IRepository` into the Controller; verify Constructor dependencies).
4. **Handler Rules (CQRS):**
- Business logic Handlers must implement the `IRequestHandler` interface and end with `CommandHandler` or `QueryHandler`. They must solely reside in the Application Layer.
## Output File Format
- **Path:** Placed within the test project, e.g., `tests/MyNewProjectName.ArchitectureTests/`.
- **File Name:** Usually named after the test scope, such as `LayerTests.cs`, `DesignConventionTests.cs`, `NamingRulesTests.cs`, etc.

View File

@@ -0,0 +1,34 @@
---
name: GenerateIntegrationTest
description: Guide to creating Integration Tests (end-to-end) using WebApplicationFactory and Testcontainers.
---
# GenerateIntegrationTest Skill
When a user requests to create an **Integration Test** to verify API endpoints from start to finish, you need to generate the code according to the following guidelines:
## Purpose
- Test whether the assembled components work correctly together.
- Flow: Client calls API -> Middleware -> Controller -> CQRS Handler/Service -> Read/Write to a real Database.
## Implementation Guide
1. **Setup WebApplicationFactory:**
- Automatically setup `WebApplicationFactory<Program>` (to create an in-memory test server in .NET).
- Override application configurations if necessary (e.g., changing the ConnectionString to point to a test container).
2. **Setup Testcontainers (Real Database):**
- Use the `Testcontainers` library (or similar configuration) to automatically spin up a Docker container containing a real Database (e.g., PostgreSQL, SQL Server).
- Ensure this database container starts before the tests run and is automatically disposed of after the tests complete. Avoid using in-memory SQLite because it often causes minor bugs and does not accurately mimic a production database.
3. **Write API Test Scenarios (Arrange - Act - Assert):**
- Create an `HttpClient` object from `WebApplicationFactory.CreateClient()`.
- **Arrange:** Prepare payload data as JSON objects or prepopulate database records for GET/PUT/DELETE APIs.
- **Act:** Call the corresponding API endpoint directly via code. E.g.: `await client.PostAsJsonAsync("/api/v1/samples", payload);`.
- **Assert:** Verify the returned results:
- Check HTTP Status: is it `200 OK` or `400 Bad Request`?
- Deserialize the response body to check the exact object data.
- (Optional) Query the database container directly to confirm the record was actually created/updated.
## Output File Format
- **Path:** Placed in the corresponding test project, such as `tests/MyNewProjectName.IntegrationTests/Controllers/...`.
- **File Name:** `[ControllerName]Tests.cs` (e.g., `OrdersControllerTests.cs`).

View File

@@ -0,0 +1,32 @@
---
name: GenerateUnitTest
description: Guide to creating isolated Unit Tests (high speed) using Mocking (Moq or NSubstitute).
---
# GenerateUnitTest Skill
When a user requests a **Unit Test** for a class/method, you must adhere to the following principles to generate the test code:
## Purpose
- Test solely one class/method in isolation.
- Completely ignore real Databases, Redis, or HTTP calls.
- Extremely fast execution speed.
## 1. For CQRS Handlers or Services
- **Identify Dependencies:** Automatically identify the Interfaces (e.g., `IRepository`, `IUnitOfWork`, `ILogger`, `IMediator`) injected into the constructor.
- **Create Mock Objects:** Use a Mocking library (like `Moq` or `NSubstitute`) to create fake instances of these Interfaces.
- **Test Scenario (Arrange - Act - Assert):**
- **Arrange:** Provide fake data (Mock data) for the Interface methods.
- **Act:** Call the method being executed (e.g., `Handle()` in CQRS or Service methods).
- **Assert:** Check the returned result, OR verify if a Mock object's method was called the correct number of times (e.g., checking if `_repository.AddAsync()` was called), OR verify if it throws a `ValidationException` given invalid input.
## 2. For Domain Entities
- **Goal:** Verify internal business logic and calculations of the Entity.
- **Scenario:**
- Initialize the Entity with specific states.
- Call a method that alters the state or performs a calculation (e.g., `Order.CalculateTotal()`).
- Verify if the modified value adheres to business rules (e.g., `Total` must equal `Price * Quantity`).
## Output File Format
- **Path:** Placed in the `tests/MyNewProjectName.UnitTests/...` project (corresponding to the tested class's root directory).
- **File Name:** `[ClassName]Tests.cs` (e.g., `CreateOrderCommandHandlerTests.cs`).