@polymorphism-tech/morph-spec 7.0.0 → 7.1.1

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 (89) hide show
  1. package/README.md +368 -368
  2. package/claude-plugin.json +14 -14
  3. package/docs/CHEATSHEET.md +199 -199
  4. package/docs/QUICKSTART.md +200 -200
  5. package/framework/CLAUDE.md +1 -1
  6. package/framework/MORPH.md +4 -1
  7. package/framework/agents.json +132 -127
  8. package/framework/rubrics/backend.json +41 -36
  9. package/framework/rules/ai-agents-standards.md +45 -15
  10. package/framework/rules/neon-standards.md +25 -26
  11. package/framework/skills/core/morph-brainstorming/SKILL.md +1 -1
  12. package/framework/skills/core/morph-plan/SKILL.md +3 -1
  13. package/framework/skills/core/morph-stack-scan/SKILL.md +3 -3
  14. package/framework/standards/STANDARDS.json +1729 -1133
  15. package/framework/standards/ai-agents/agent-session.md +160 -0
  16. package/framework/standards/ai-agents/batching.md +193 -0
  17. package/framework/standards/ai-agents/context-providers.md +188 -0
  18. package/framework/standards/ai-agents/mcp-server.md +250 -0
  19. package/framework/standards/ai-agents/mcp-tools.md +197 -0
  20. package/framework/standards/ai-agents/middleware-patterns.md +207 -0
  21. package/framework/standards/ai-agents/modalities-image-gen.md +173 -0
  22. package/framework/standards/ai-agents/modalities-speech-to-text.md +171 -0
  23. package/framework/standards/ai-agents/modalities-text-to-speech.md +181 -0
  24. package/framework/standards/ai-agents/modalities-vision.md +201 -0
  25. package/framework/standards/ai-agents/multi-agent-patterns.md +155 -0
  26. package/framework/standards/ai-agents/production.md +114 -258
  27. package/framework/standards/ai-agents/prompts-in-db.md +214 -0
  28. package/framework/standards/ai-agents/providers/model-registry.md +158 -0
  29. package/framework/standards/ai-agents/rag-custom-pgvector.md +243 -0
  30. package/framework/standards/ai-agents/service-tier-flex.md +135 -0
  31. package/framework/standards/ai-agents/setup.md +142 -316
  32. package/framework/standards/ai-agents/structured-output.md +249 -0
  33. package/framework/standards/ai-agents/sweet-spot.md +109 -0
  34. package/framework/standards/ai-agents/workflows.md +114 -284
  35. package/framework/standards/architecture/vertical-slice/vertical-slice.md +439 -429
  36. package/framework/standards/backend/api/validation.md +92 -88
  37. package/framework/standards/backend/database/postgresql/database.md +336 -332
  38. package/framework/standards/backend/database/vector-search-rag.md +599 -541
  39. package/framework/standards/backend/dotnet/fluent-validation-vsa.md +4 -0
  40. package/framework/standards/backend/dotnet/result-pattern.md +4 -0
  41. package/framework/standards/backend/dotnet/scalar-ui.md +176 -172
  42. package/framework/standards/backend/dotnet/scrutor.md +4 -0
  43. package/framework/standards/backend/dotnet/vsa-handler-patterns.md +310 -274
  44. package/framework/standards/backend/integrations/asaas/asaas-api.md +260 -216
  45. package/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +354 -350
  46. package/framework/standards/backend/integrations/neon-auth/neon-auth.md +30 -19
  47. package/framework/standards/backend/integrations/resend/resend-email.md +400 -385
  48. package/framework/standards/data/nosql/cache/redis.md +106 -97
  49. package/framework/standards/data/nosql/cosmos-db.md +127 -118
  50. package/framework/standards/data/vector-search/rag-chunking.md +113 -104
  51. package/framework/standards/frontend/design-system/ai-image-generation.md +4 -0
  52. package/framework/standards/frontend/design-system/animations.md +164 -160
  53. package/framework/standards/frontend/design-system/naming.md +68 -64
  54. package/framework/standards/frontend/gsap/gsap-core.md +14 -8
  55. package/framework/standards/frontend/gsap/gsap-plugins.md +26 -21
  56. package/framework/standards/frontend/gsap/gsap-scrolltrigger.md +9 -7
  57. package/framework/standards/frontend/nextjs/app-router.md +127 -123
  58. package/framework/standards/frontend/nextjs/components.md +136 -132
  59. package/framework/standards/frontend/nextjs/data-fetching.md +130 -126
  60. package/framework/standards/frontend/nextjs/forms.md +134 -128
  61. package/framework/standards/frontend/nextjs/motion-patterns.md +328 -322
  62. package/framework/standards/frontend/nextjs/naming-conventions.md +71 -67
  63. package/framework/standards/frontend/nextjs/nextjs-patterns.md +229 -225
  64. package/framework/standards/frontend/nextjs/project-structure.md +106 -102
  65. package/framework/standards/frontend/nextjs/state-management.md +76 -72
  66. package/framework/standards/frontend/nextjs/testing.md +115 -111
  67. package/framework/standards/infrastructure/docker/easypanel-deploy.md +196 -192
  68. package/framework/standards/infrastructure/neon/neon-pgrag.md +6 -2
  69. package/framework/standards/infrastructure/neon/neon-pgvector.md +4 -0
  70. package/framework/standards/infrastructure/neon/neon-setup.md +5 -1
  71. package/framework/standards/integration/mcp/mcp-tools.md +471 -462
  72. package/framework/templates/CLAUDE.md.core.template +1 -1
  73. package/framework/templates/REGISTRY.json +1745 -1239
  74. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +39 -0
  75. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +68 -0
  76. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +117 -0
  77. package/framework/templates/code/dotnet/ai-agents/PromptRepository.cs.template +95 -0
  78. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +61 -0
  79. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +107 -0
  80. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +58 -0
  81. package/framework/templates/code/dotnet/backend/repository.cs +3 -10
  82. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +58 -0
  83. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +91 -0
  84. package/package.json +89 -83
  85. package/src/core/templates/template-registry.js +289 -256
  86. package/src/lib/generators/context-generator.js +516 -518
  87. package/src/lib/generators/scaffold-generator.js +23 -26
  88. package/framework/standards/infrastructure/neon/neon-semantic-kernel.md +0 -310
  89. package/framework/templates/integrations/semantic-kernel-neon.cs +0 -125
@@ -1,274 +1,310 @@
1
- # VSA Handler Patterns — Complete Feature Slice Guide
2
-
3
- > **Scope:** dotnet-vsa
4
- > **Layer:** 0 (always load)
5
- > **Keywords:** vsa, handler, feature-slice, vertical-slice, minimal-api, endpoint
6
- > **Load When:** dotnet VSA projects
7
-
8
- ## Overview
9
-
10
- Each feature in VSA is a self-contained slice with 5 files in a feature folder. Handlers implement `IHandler<TRequest, TResponse>` (not MediatR). Dependencies use primary constructors. The data path is `Handler -> Repository -> UnitOfWork` with no service layer in between.
11
-
12
- ---
13
-
14
- ## IHandler\<TRequest, TResponse\>
15
-
16
- A single-method interface — intentionally minimal:
17
-
18
- ```csharp
19
- public interface IHandler<in TRequest, TResponse>
20
- {
21
- Task<TResponse> HandleAsync(TRequest command, CancellationToken cancellationToken);
22
- }
23
- ```
24
-
25
- **Why not MediatR:** No `IRequest`/`INotification` marker interfaces, no `Send()` indirection, no service locator. Handlers are resolved directly from DI by their interface type. Decorators (validation, logging) are applied via Scrutor, not MediatR pipeline behaviors.
26
-
27
- ---
28
-
29
- ## Feature Folder Structure (5 Files Per Slice)
30
-
31
- ```
32
- Features/
33
- BookFeature/
34
- CreateBook/
35
- CreateBookRequest.cs (sealed record — can be inline in handler)
36
- CreateBookResponse.cs (sealed record — can be inline in handler)
37
- CreateBookHandler.cs (business logic)
38
- CreateBookValidator.cs (FluentValidation)
39
- CreateBookEndpoint.cs (minimal API mapping)
40
- GetBookById/
41
- ...
42
- UpdateBook/
43
- ...
44
- DeleteBook/
45
- ...
46
- BookErrors.cs (shared error factory for the feature)
47
- ```
48
-
49
- Request/Response DTOs can be defined inline in the handler file for simple slices:
50
-
51
- ```csharp
52
- namespace ProjectName.Features.BookFeature.CreateBook;
53
-
54
- // Sealed records for DTOs — immutable, structural equality
55
- public sealed record CreateBookRequest(
56
- string Title, string Author, string ISBN, decimal Price, int PublishedYear);
57
-
58
- public sealed record CreateBookResponse(
59
- Guid Id, string Title, string Author, string ISBN, decimal Price, int PublishedYear);
60
- ```
61
-
62
- ---
63
-
64
- ## Complete Handler Example
65
-
66
- ```csharp
67
- namespace ProjectName.Features.BookFeature.CreateBook;
68
-
69
- using ProjectName.Abstractions;
70
- using ProjectName.Entities;
71
- using ProjectName.Repository;
72
-
73
- public sealed record CreateBookRequest(
74
- string Title, string Author, string ISBN, decimal Price, int PublishedYear);
75
-
76
- public sealed record CreateBookResponse(
77
- Guid Id, string Title, string Author, string ISBN, decimal Price, int PublishedYear);
78
-
79
- // Primary constructor for DI — no field declarations needed
80
- public sealed class CreateBookHandler(
81
- IRepository<Book> bookRepo,
82
- IUnitOfWork unitOfWork) : IHandler<CreateBookRequest, Result<CreateBookResponse>>
83
- {
84
- public async Task<Result<CreateBookResponse>> HandleAsync(
85
- CreateBookRequest command, CancellationToken cancellationToken)
86
- {
87
- var book = new Book
88
- {
89
- Id = Guid.CreateVersion7(), // .NET 9+ — time-sortable UUID
90
- Title = command.Title,
91
- Author = command.Author,
92
- ISBN = command.ISBN,
93
- Price = command.Price,
94
- PublishedYear = command.PublishedYear
95
- };
96
-
97
- await bookRepo.AddAsync(book, cancellationToken);
98
- await unitOfWork.CommitAsync(cancellationToken);
99
-
100
- return Result.Success(new CreateBookResponse(
101
- book.Id, book.Title, book.Author, book.ISBN, book.Price, book.PublishedYear));
102
- }
103
- }
104
- ```
105
-
106
- ### Key Patterns
107
-
108
- - **`sealed class`** — handlers are never inherited
109
- - **`sealed record`** — DTOs are immutable value types
110
- - **Primary constructors** — `(IRepository<Book> bookRepo, IUnitOfWork unitOfWork)` replaces field + constructor boilerplate
111
- - **`Guid.CreateVersion7()`** — time-sortable, index-friendly UUID (not `Guid.NewGuid()`)
112
- - **`CancellationToken`** — passed through every async call
113
- - **`Result<T>` return** — never throw for expected failures
114
-
115
- ---
116
-
117
- ## Complete Endpoint Example
118
-
119
- ```csharp
120
- namespace ProjectName.Features.BookFeature.CreateBook;
121
-
122
- using ProjectName.Abstractions;
123
- using ProjectName.Constants;
124
- using ProjectName.Extensions;
125
-
126
- internal sealed class CreateBookEndpoint : IApiEndpoint
127
- {
128
- public void MapEndpoint(IEndpointRouteBuilder app)
129
- {
130
- app.MapPost("books", async (
131
- IHandler<CreateBookRequest, Result<CreateBookResponse>> handler,
132
- CreateBookRequest command,
133
- CancellationToken cancellationToken) =>
134
- {
135
- var result = await handler.HandleAsync(command, cancellationToken);
136
- return result.Match(
137
- onSuccess: () => Results.Ok(result.Value),
138
- onFailure: error => Results.BadRequest(error));
139
- })
140
- .WithTags(ApiTags.Books)
141
- .Produces<CreateBookResponse>(StatusCodes.Status200OK)
142
- .Produces(StatusCodes.Status400BadRequest);
143
- }
144
- }
145
- ```
146
-
147
- ### Endpoint Conventions
148
-
149
- - **`internal sealed`** — endpoints are not public API
150
- - **`IApiEndpoint`** — single interface for auto-discovery
151
- - **Handler injected via DI** — resolved as `IHandler<TReq, TRes>` parameter
152
- - **`Match()` for responses** — never access `.Value` directly
153
- - **`.WithTags()`** — always tag for Scalar API docs
154
- - **`.Produces<T>()`** — always document response types
155
-
156
- ---
157
-
158
- ## IApiEndpoint Interface
159
-
160
- ```csharp
161
- public interface IApiEndpoint
162
- {
163
- void MapEndpoint(IEndpointRouteBuilder app);
164
- }
165
- ```
166
-
167
- All endpoint classes implementing this interface are auto-discovered and mapped via `MapApiEndpoints()` in Program.cs.
168
-
169
- ---
170
-
171
- ## Repository + UnitOfWork (No Service Layer)
172
-
173
- Handlers call repositories directly. There is no service/manager layer:
174
-
175
- ```csharp
176
- public interface IRepository<T> where T : class
177
- {
178
- Task<IEnumerable<T>> GetAllAsync(CancellationToken cancellationToken = default);
179
- Task<T?> GetByIdAsync(object id, CancellationToken cancellationToken = default);
180
- Task<T> AddAsync(T entity, CancellationToken cancellationToken = default);
181
- Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
182
- Task DeleteAsync(T entity, CancellationToken cancellationToken = default);
183
- Task AddRangeAsync(IEnumerable<T> entities, CancellationToken cancellationToken = default);
184
- void RemoveRange(IEnumerable<T> entities);
185
- }
186
-
187
- public interface IUnitOfWork
188
- {
189
- Task<int> CommitAsync(CancellationToken cancellationToken);
190
- Task RollbackAsync(CancellationToken cancellationToken = default);
191
- }
192
- ```
193
-
194
- **Pattern:** `Repository.AddAsync()` -> `UnitOfWork.CommitAsync()` — always commit explicitly.
195
-
196
- ---
197
-
198
- ## Feature Error Factory
199
-
200
- Each feature defines its own error constants:
201
-
202
- ```csharp
203
- // Features/BookFeature/BookErrors.cs
204
- public static class BookErrors
205
- {
206
- public static Error NotFound(Guid bookId) =>
207
- Error.NotFound("Book.NotFound", $"Book with ID '{bookId}' was not found.");
208
-
209
- public static Error DuplicateIsbn(string isbn) =>
210
- Error.Conflict("Book.DuplicateIsbn", $"A book with ISBN '{isbn}' already exists.");
211
-
212
- public static readonly Error InvalidPrice =
213
- Error.Failure("Book.InvalidPrice", "Book price must be greater than zero.");
214
- }
215
- ```
216
-
217
- Usage in handler:
218
-
219
- ```csharp
220
- var existing = await bookRepo.GetByIdAsync(command.BookId, cancellationToken);
221
- if (existing is null)
222
- return BookErrors.NotFound(command.BookId); // implicit conversion to Result<T>
223
- ```
224
-
225
- ---
226
-
227
- ## Program.cs DI Registration Order
228
-
229
- ```csharp
230
- // 1. OpenAPI
231
- builder.Services.AddOpenApi();
232
-
233
- // 2. Infrastructure (Repository, UnitOfWork, DbContext)
234
- builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
235
- builder.Services.AddScoped(typeof(IUnitOfWork), typeof(UnitOfWork));
236
- builder.Services.AddSQLDatabaseConfiguration(builder.Configuration);
237
-
238
- // 3. Endpoint auto-discovery
239
- builder.Services.RegisterApiEndpointsFromAssembly(Assembly.GetExecutingAssembly());
240
-
241
- // 4. Health checks
242
- builder.Services.AddHealthChecksConfiguration();
243
-
244
- // 5. Validators (MUST be before handlers)
245
- builder.Services.AddValidatorsFromAssembly(typeof(CreateBookValidator).Assembly);
246
-
247
- // 6. Handlers + Decorators (Scrutor auto-discovery)
248
- builder.Services.AddHandlersFromAssembly(typeof(Program).Assembly);
249
-
250
- // 7. Exception handling
251
- builder.Services.AddExceptionHandler<CustomExceptionHandler>()
252
- .AddProblemDetails();
253
- ```
254
-
255
- ---
256
-
257
- ## Anti-Patterns
258
-
259
- | Do NOT | Do Instead |
260
- |--------|------------|
261
- | Use MediatR `IRequest`/`Send()` | Use `IHandler<TReq, TRes>` resolved directly from DI |
262
- | Create a service/manager layer | Handler calls Repository + UnitOfWork directly |
263
- | Use `Guid.NewGuid()` | Use `Guid.CreateVersion7()` for time-sortable IDs |
264
- | Make handler classes non-sealed | Always `sealed class` |
265
- | Use mutable DTOs (class with setters) | Always `sealed record` with positional parameters |
266
- | Omit `CancellationToken` from async methods | Pass `CancellationToken` through every async call |
267
- | Put business logic in endpoints | Endpoints only map HTTP and call `Match()` |
268
- | Share handlers across features | Each feature has its own handler, even if similar |
269
- | Use constructor + field for DI | Use primary constructors: `class Handler(IDep dep)` |
270
- | Group by technical concern (Controllers/, Services/) | Group by feature: `Features/BookFeature/CreateBook/` |
271
-
272
- ---
273
-
274
- *MORPH-SPEC by Polymorphism Tech*
1
+ # VSA Handler Patterns — Complete Feature Slice Guide
2
+
3
+ > **Scope:** dotnet-vsa
4
+ > **Layer:** 0 (always load)
5
+ > **Keywords:** vsa, handler, feature-slice, vertical-slice, minimal-api, endpoint
6
+ > **Load When:** dotnet VSA projects
7
+
8
+ **Verified against:** .NET 10 (minimal APIs, primary constructors, `Guid.CreateVersion7()`). Last-verified: 2026-05-20.
9
+
10
+ ---
11
+
12
+ ## Overview
13
+
14
+ Each feature in VSA is a self-contained slice with 5 files in a feature folder. Handlers implement `IHandler<TRequest, TResponse>` (not MediatR). Dependencies use primary constructors. The data path is `Handler -> Repository -> UnitOfWork` with no service layer in between.
15
+
16
+ ---
17
+
18
+ ## IHandler\<TRequest, TResponse\>
19
+
20
+ A single-method interface — intentionally minimal:
21
+
22
+ ```csharp
23
+ public interface IHandler<in TRequest, TResponse>
24
+ {
25
+ Task<TResponse> HandleAsync(TRequest command, CancellationToken cancellationToken);
26
+ }
27
+ ```
28
+
29
+ **Why not MediatR:** No `IRequest`/`INotification` marker interfaces, no `Send()` indirection, no service locator. Handlers are resolved directly from DI by their interface type. Decorators (validation, logging) are applied via Scrutor, not MediatR pipeline behaviors.
30
+
31
+ ---
32
+
33
+ ## Feature Folder Structure (5 Files Per Slice)
34
+
35
+ ```
36
+ Features/
37
+ BookFeature/
38
+ CreateBook/
39
+ CreateBookRequest.cs (sealed record — can be inline in handler)
40
+ CreateBookResponse.cs (sealed record — can be inline in handler)
41
+ CreateBookHandler.cs (business logic)
42
+ CreateBookValidator.cs (FluentValidation)
43
+ CreateBookEndpoint.cs (minimal API mapping)
44
+ GetBookById/
45
+ ...
46
+ UpdateBook/
47
+ ...
48
+ DeleteBook/
49
+ ...
50
+ BookErrors.cs (shared error factory for the feature)
51
+ ```
52
+
53
+ Request/Response DTOs can be defined inline in the handler file for simple slices:
54
+
55
+ ```csharp
56
+ namespace ProjectName.Features.BookFeature.CreateBook;
57
+
58
+ // Sealed records for DTOs — immutable, structural equality
59
+ public sealed record CreateBookRequest(
60
+ string Title, string Author, string ISBN, decimal Price, int PublishedYear);
61
+
62
+ public sealed record CreateBookResponse(
63
+ Guid Id, string Title, string Author, string ISBN, decimal Price, int PublishedYear);
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Complete Handler Example
69
+
70
+ ```csharp
71
+ namespace ProjectName.Features.BookFeature.CreateBook;
72
+
73
+ using ProjectName.Abstractions;
74
+ using ProjectName.Entities;
75
+ using ProjectName.Repository;
76
+
77
+ public sealed record CreateBookRequest(
78
+ string Title, string Author, string ISBN, decimal Price, int PublishedYear);
79
+
80
+ public sealed record CreateBookResponse(
81
+ Guid Id, string Title, string Author, string ISBN, decimal Price, int PublishedYear);
82
+
83
+ // Primary constructor for DI — no field declarations needed
84
+ public sealed class CreateBookHandler(
85
+ IRepository<Book> bookRepo,
86
+ IUnitOfWork unitOfWork) : IHandler<CreateBookRequest, Result<CreateBookResponse>>
87
+ {
88
+ public async Task<Result<CreateBookResponse>> HandleAsync(
89
+ CreateBookRequest command, CancellationToken cancellationToken)
90
+ {
91
+ var book = new Book
92
+ {
93
+ Id = Guid.CreateVersion7(), // .NET 9+ — time-sortable UUID
94
+ Title = command.Title,
95
+ Author = command.Author,
96
+ ISBN = command.ISBN,
97
+ Price = command.Price,
98
+ PublishedYear = command.PublishedYear
99
+ };
100
+
101
+ await bookRepo.AddAsync(book, cancellationToken);
102
+ await unitOfWork.CommitAsync(cancellationToken);
103
+
104
+ return Result.Success(new CreateBookResponse(
105
+ book.Id, book.Title, book.Author, book.ISBN, book.Price, book.PublishedYear));
106
+ }
107
+ }
108
+ ```
109
+
110
+ ### Key Patterns
111
+
112
+ - **`sealed class`** — handlers are never inherited
113
+ - **`sealed record`** — DTOs are immutable value types
114
+ - **Primary constructors** — `(IRepository<Book> bookRepo, IUnitOfWork unitOfWork)` replaces field + constructor boilerplate
115
+ - **`Guid.CreateVersion7()`** — time-sortable, index-friendly UUID (not `Guid.NewGuid()`)
116
+ - **`CancellationToken`** — passed through every async call
117
+ - **`Result<T>` return** — never throw for expected failures
118
+
119
+ ---
120
+
121
+ ## Complete Endpoint Example
122
+
123
+ ```csharp
124
+ namespace ProjectName.Features.BookFeature.CreateBook;
125
+
126
+ using ProjectName.Abstractions;
127
+ using ProjectName.Constants;
128
+ using ProjectName.Extensions;
129
+
130
+ internal sealed class CreateBookEndpoint : IApiEndpoint
131
+ {
132
+ public void MapEndpoint(IEndpointRouteBuilder app)
133
+ {
134
+ app.MapPost("books", async (
135
+ IHandler<CreateBookRequest, Result<CreateBookResponse>> handler,
136
+ CreateBookRequest command,
137
+ CancellationToken cancellationToken) =>
138
+ {
139
+ var result = await handler.HandleAsync(command, cancellationToken);
140
+ return result.Match(
141
+ onSuccess: () => Results.Ok(result.Value),
142
+ onFailure: error => Results.BadRequest(error));
143
+ })
144
+ .WithTags(ApiTags.Books)
145
+ .Produces<CreateBookResponse>(StatusCodes.Status200OK)
146
+ .Produces(StatusCodes.Status400BadRequest);
147
+ }
148
+ }
149
+ ```
150
+
151
+ ### Endpoint Conventions
152
+
153
+ - **`internal sealed`** — endpoints are not public API
154
+ - **`IApiEndpoint`** — single interface for auto-discovery
155
+ - **Handler injected via DI** — resolved as `IHandler<TReq, TRes>` parameter
156
+ - **`Match()` for responses** — never access `.Value` directly
157
+ - **`.WithTags()`** — always tag for Scalar API docs
158
+ - **`.Produces<T>()`** — always document response types
159
+
160
+ ---
161
+
162
+ ## IApiEndpoint Interface
163
+
164
+ ```csharp
165
+ public interface IApiEndpoint
166
+ {
167
+ void MapEndpoint(IEndpointRouteBuilder app);
168
+ }
169
+ ```
170
+
171
+ All endpoint classes implementing this interface are auto-discovered and mapped via `MapApiEndpoints()` in Program.cs.
172
+
173
+ ---
174
+
175
+ ## Repository + UnitOfWork (No Service Layer)
176
+
177
+ Handlers call repositories directly. There is no service/manager layer:
178
+
179
+ ```csharp
180
+ public interface IRepository<T> where T : class
181
+ {
182
+ Task<IEnumerable<T>> GetAllAsync(CancellationToken cancellationToken = default);
183
+ Task<T?> GetByIdAsync(object id, CancellationToken cancellationToken = default);
184
+ Task<T> AddAsync(T entity, CancellationToken cancellationToken = default);
185
+ Task UpdateAsync(T entity, CancellationToken cancellationToken = default);
186
+ Task DeleteAsync(T entity, CancellationToken cancellationToken = default);
187
+ Task AddRangeAsync(IEnumerable<T> entities, CancellationToken cancellationToken = default);
188
+ void RemoveRange(IEnumerable<T> entities);
189
+ }
190
+
191
+ public interface IUnitOfWork
192
+ {
193
+ Task<int> CommitAsync(CancellationToken cancellationToken);
194
+ Task RollbackAsync(CancellationToken cancellationToken = default);
195
+ }
196
+ ```
197
+
198
+ **Pattern:** `Repository.AddAsync()` -> `UnitOfWork.CommitAsync()` — always commit explicitly.
199
+
200
+ ### When to Use DbContext Directly Instead
201
+
202
+ `IRepository<T>` is the right tool for CRUD by key. It is **not** the right tool for
203
+ slice-specific queries — joins, projections, pagination, composite filters. For those,
204
+ inject `ApplicationDbContext` directly into the handler and write the LINQ in the slice:
205
+
206
+ ```csharp
207
+ public sealed class SearchBooksHandler(
208
+ ApplicationDbContext db) : IHandler<SearchBooksRequest, Result<IReadOnlyList<BookDto>>>
209
+ {
210
+ public async Task<Result<IReadOnlyList<BookDto>>> HandleAsync(
211
+ SearchBooksRequest query, CancellationToken cancellationToken)
212
+ {
213
+ var books = await db.Books
214
+ .Where(b => b.Author.Contains(query.Author))
215
+ .OrderBy(b => b.Title)
216
+ .Skip(query.Skip).Take(query.Take)
217
+ .Select(b => new BookDto(b.Id, b.Title, b.Author))
218
+ .ToListAsync(cancellationToken);
219
+
220
+ return Result.Success<IReadOnlyList<BookDto>>(books);
221
+ }
222
+ }
223
+ ```
224
+
225
+ **Rule of thumb:** CRUD by key → `IRepository<T>` + `IUnitOfWork`. Anything that needs a
226
+ custom query shape → `ApplicationDbContext` in the slice. Never reach for raw SQL
227
+ (`FromSqlRaw`) unless a query genuinely cannot be expressed in LINQ — and document that
228
+ in `decisions.md`.
229
+
230
+ ---
231
+
232
+ ## Feature Error Factory
233
+
234
+ Each feature defines its own error constants:
235
+
236
+ ```csharp
237
+ // Features/BookFeature/BookErrors.cs
238
+ public static class BookErrors
239
+ {
240
+ public static Error NotFound(Guid bookId) =>
241
+ Error.NotFound("Book.NotFound", $"Book with ID '{bookId}' was not found.");
242
+
243
+ public static Error DuplicateIsbn(string isbn) =>
244
+ Error.Conflict("Book.DuplicateIsbn", $"A book with ISBN '{isbn}' already exists.");
245
+
246
+ public static readonly Error InvalidPrice =
247
+ Error.Failure("Book.InvalidPrice", "Book price must be greater than zero.");
248
+ }
249
+ ```
250
+
251
+ Usage in handler:
252
+
253
+ ```csharp
254
+ var existing = await bookRepo.GetByIdAsync(command.BookId, cancellationToken);
255
+ if (existing is null)
256
+ return BookErrors.NotFound(command.BookId); // implicit conversion to Result<T>
257
+ ```
258
+
259
+ ---
260
+
261
+ ## Program.cs DI Registration Order
262
+
263
+ ```csharp
264
+ // 1. OpenAPI
265
+ builder.Services.AddOpenApi();
266
+
267
+ // 2. Infrastructure (Repository, UnitOfWork, DbContext)
268
+ builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
269
+ builder.Services.AddScoped(typeof(IUnitOfWork), typeof(UnitOfWork));
270
+ builder.Services.AddSQLDatabaseConfiguration(builder.Configuration);
271
+
272
+ // 3. Endpoint auto-discovery
273
+ builder.Services.RegisterApiEndpointsFromAssembly(Assembly.GetExecutingAssembly());
274
+
275
+ // 4. Health checks
276
+ builder.Services.AddHealthChecksConfiguration();
277
+
278
+ // 5. Validators (MUST be before handlers)
279
+ builder.Services.AddValidatorsFromAssembly(typeof(CreateBookValidator).Assembly);
280
+
281
+ // 6. Handlers + Decorators (Scrutor auto-discovery)
282
+ builder.Services.AddHandlersFromAssembly(typeof(Program).Assembly);
283
+
284
+ // 7. Exception handling
285
+ builder.Services.AddExceptionHandler<CustomExceptionHandler>()
286
+ .AddProblemDetails();
287
+ ```
288
+
289
+ ---
290
+
291
+ ## Anti-Patterns
292
+
293
+ | Do NOT | Do Instead |
294
+ |--------|------------|
295
+ | Use MediatR `IRequest`/`Send()` | Use `IHandler<TReq, TRes>` resolved directly from DI |
296
+ | Create a service/manager layer | Handler calls Repository + UnitOfWork directly |
297
+ | Use `Guid.NewGuid()` | Use `Guid.CreateVersion7()` for time-sortable IDs |
298
+ | Make handler classes non-sealed | Always `sealed class` |
299
+ | Use mutable DTOs (class with setters) | Always `sealed record` with positional parameters |
300
+ | Omit `CancellationToken` from async methods | Pass `CancellationToken` through every async call |
301
+ | Put business logic in endpoints | Endpoints only map HTTP and call `Match()` |
302
+ | Share handlers across features | Each feature has its own handler, even if similar |
303
+ | Use constructor + field for DI | Use primary constructors: `class Handler(IDep dep)` |
304
+ | Group by technical concern (Controllers/, Services/) | Group by feature: `Features/BookFeature/CreateBook/` |
305
+ | Force a slice-specific query through `IRepository<T>` | Inject `DbContext` and write LINQ in the slice |
306
+ | Use raw SQL (`FromSqlRaw` / `ExecuteQuery(string)`) by default | Use LINQ; raw SQL only with a `decisions.md` justification |
307
+
308
+ ---
309
+
310
+ *MORPH-SPEC by Polymorphism Tech*